From 2b395c5a114e19cbcaa8ff508bc77ff4848fbf8e Mon Sep 17 00:00:00 2001 From: jamon Date: Mon, 9 Nov 2026 14:45:20 +0800 Subject: [PATCH 01/44] =?UTF-8?q?fix(provider):=20=E6=B5=81=E5=BC=8F?= =?UTF-8?q?=E5=93=8D=E5=BA=94=E4=B8=BA=E7=A9=BA=E6=97=B6=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E6=89=94=E6=8E=89=E5=B7=A5=E5=85=B7=E8=B0=83=E7=94=A8=EF=BC=8C?= =?UTF-8?q?=E4=B9=9F=E4=B8=8D=E5=86=8D=E5=8E=BB=E6=8E=89=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E9=87=8D=E9=97=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 模型服务的流式响应没有可识别的 delta 时,非流式兜底只取 content:模型只返回工具调用 (content 为 null)就被当成空回答,随后把工具声明去掉再问一次,模型只能把调用写成 DSML 文本,或回答“本轮没有可用工具”。 - openai_compatible / openai_base 的 chat() 带回 tool_calls、reasoning、reasoning_source、 reasoning_details(ChatResponse 增加后两个可选字段) - 空流兜底拿到工具调用时按 reasoning → 文本 → 带 tool_calls 的终止块回放;空参数只在 正常结束时当成无参调用,finish_reason 为 length / max_tokens 时保持为空,由累加器按截断拒绝 - 去掉工具重问只留给 MiniMax(原有兜底);其他模型抛可重试的 empty streaming response, 会话带着工具重试;openai_compatible.chat() 遇到空 choices 抛 empty choices(原为 IndexError) --- flocks/provider/provider.py | 4 + flocks/provider/sdk/openai_base.py | 122 ++++++-- flocks/provider/sdk/openai_compatible.py | 29 +- .../test_empty_stream_tool_fallback.py | 279 ++++++++++++++++++ 4 files changed, 410 insertions(+), 24 deletions(-) create mode 100644 tests/provider/test_empty_stream_tool_fallback.py diff --git a/flocks/provider/provider.py b/flocks/provider/provider.py index 1e8cfa078..491b9b73a 100644 --- a/flocks/provider/provider.py +++ b/flocks/provider/provider.py @@ -201,6 +201,10 @@ class ChatResponse(BaseModel): usage: Dict[str, Any] tool_calls: Optional[List[Dict[str, Any]]] = None reasoning: Optional[str] = None + # Where the reasoning came from and its structured form, so a reply replayed + # into a stream keeps what the next tool round must send back. + reasoning_source: Optional[str] = None + reasoning_details: Optional[List[Dict[str, Any]]] = None class ToolCallInfo(BaseModel): diff --git a/flocks/provider/sdk/openai_base.py b/flocks/provider/sdk/openai_base.py index 336fedd8f..288374bc6 100644 --- a/flocks/provider/sdk/openai_base.py +++ b/flocks/provider/sdk/openai_base.py @@ -855,6 +855,87 @@ def extract_reasoning_details(delta) -> Optional[List[Dict[str, Any]]]: return None +def message_tool_call_chunks(message: Any) -> Optional[List[Dict[str, Any]]]: + """A non-streaming message's tool calls, shaped like streamed tool-call deltas.""" + calls: List[Dict[str, Any]] = [] + for call in getattr(message, "tool_calls", None) or []: + function = getattr(call, "function", None) + name = getattr(function, "name", None) + if not isinstance(name, str) or not name: + continue + arguments = getattr(function, "arguments", None) + call_id = getattr(call, "id", None) + calls.append({ + "index": len(calls), + # The tool-call accumulator mints an id when the provider gave none. + "id": call_id if isinstance(call_id, str) and call_id else None, + "type": "function", + # Kept as sent: an empty or partial string may be a cut-off call. + "function": {"name": name, "arguments": arguments if isinstance(arguments, str) else ""}, + }) + return calls or None + + +def message_reasoning( + message: Any, +) -> tuple[Optional[str], Optional[str], Optional[List[Dict[str, Any]]]]: + """Reasoning text, the field it came from, and structured reasoning details.""" + reasoning, source = extract_reasoning_content_with_source(message) + if not isinstance(reasoning, str) or not reasoning: + reasoning, source = None, None + details = [item for item in extract_reasoning_details(message) or [] if isinstance(item, dict)] + return reasoning, source if isinstance(source, str) else None, details or None + + +def chat_fallback_tool_call_chunks( + response: ChatResponse, + *, + provider_id: str, + model_id: str, +) -> List[StreamChunk]: + """Replay a non-streaming answer that made tool calls as stream chunks. + + The empty-stream fallback kept only ``content``: an answer made of tool + calls alone (content null) counted as empty, and the request was then sent + again without its tools, so the model reported it had none. + """ + chunks: List[StreamChunk] = [] + # As the streaming path does: details alone (e.g. encrypted reasoning) still + # make a reasoning chunk, since the next tool round has to send them back. + if response.reasoning is not None or response.reasoning_details: + chunks.append(StreamChunk( + event_type="reasoning", + reasoning=response.reasoning or "", + finish_reason=None, + metadata=build_reasoning_metadata( + provider_id=provider_id, + model_id=model_id, + reasoning_content=response.reasoning, + reasoning_source=response.reasoning_source, + reasoning_details=response.reasoning_details, + ), + )) + if response.content: + chunks.append(StreamChunk(delta=response.content, finish_reason=None)) + finish_reason = response.finish_reason or "tool_calls" + truncated = finish_reason in ("length", "max_tokens") + tool_calls = [] + for call in response.tool_calls or []: + function = dict(call.get("function") or {}) + if not truncated and not function.get("arguments"): + # A finished answer with no arguments is a call without parameters. + # A cut-off one stays empty so the accumulator refuses to run it. + function["arguments"] = "{}" + tool_calls.append({**call, "function": function}) + chunks.append(StreamChunk( + delta="", + finish_reason=finish_reason, + tool_calls=tool_calls, + usage=response.usage or None, + )) + return chunks + + def build_reasoning_metadata( *, provider_id: str, @@ -1115,12 +1196,17 @@ async def chat( f"{self.name} API returned choice with null message. " f"model={model_id}, detail={err_detail}" ) + reasoning, reasoning_source, reasoning_details = message_reasoning(msg) return ChatResponse( id=response.id, model=response.model, content=msg.content or "", finish_reason=choice.finish_reason or "stop", usage=normalize_usage(response.usage, response_id=response.id) or {}, + tool_calls=message_tool_call_chunks(msg), + reasoning=reasoning, + reasoning_source=reasoning_source, + reasoning_details=reasoning_details, ) async def chat_stream( @@ -1406,6 +1492,16 @@ async def chat_stream( fallback_error: Optional[Exception] = None try: fallback = await self.chat(model_id, messages, **kwargs) + if fallback.tool_calls: + log.warn("openai_base.stream.empty_response_recovered_tool_calls", { + "model": model_id, + "tool_calls": len(fallback.tool_calls), + }) + for chunk in chat_fallback_tool_call_chunks( + fallback, provider_id=self.id, model_id=model_id, + ): + yield chunk + return fallback_content = fallback.content or "" if fallback_content: yield StreamChunk( @@ -1417,30 +1513,12 @@ async def chat_stream( except Exception as exc: fallback_error = exc - if kwargs.get("tools"): - log.warn("openai_base.stream.retry_without_tools", { - "model": model_id, - "reason": str(fallback_error) if fallback_error else "empty_fallback_content", - }) - no_tool_kwargs = dict(kwargs) - no_tool_kwargs.pop("tools", None) - try: - fallback = await self.chat(model_id, messages, **no_tool_kwargs) - fallback_content = fallback.content or "" - if fallback_content: - yield StreamChunk( - delta=fallback_content, - finish_reason=fallback.finish_reason or "stop", - usage=fallback.usage or None, - ) - return - except Exception as exc: - if fallback_error is None: - fallback_error = exc - + # Not retried without the tools: a model asked to act with none + # writes its calls as text or says it has no tools. The empty + # response error is retryable, so the turn is retried with them. if fallback_error: raise fallback_error raise ValueError( f"{self.name} API returned an empty streaming response and empty fallback response. " - f"model={model_id}" + f"model={model_id}, tools_declared={bool(kwargs.get('tools'))}" ) diff --git a/flocks/provider/sdk/openai_compatible.py b/flocks/provider/sdk/openai_compatible.py index e77876ee5..28a6d77ca 100644 --- a/flocks/provider/sdk/openai_compatible.py +++ b/flocks/provider/sdk/openai_compatible.py @@ -26,6 +26,7 @@ ThinkTagExtractor, apply_openai_token_limit, build_reasoning_metadata, + chat_fallback_tool_call_chunks, create_openai_http_client, create_chat_completion_with_fallbacks, _coerce_bool, @@ -35,6 +36,8 @@ extract_reasoning_details, format_openai_content, format_openai_messages, + message_reasoning, + message_tool_call_chunks, resolve_openai_token_limit, resolve_verify_ssl, ) @@ -230,18 +233,26 @@ async def chat( ) # Format response + if not response.choices: + # Worded like openai_base so the session retries it as transient. + raise ValueError(f"OpenAI-compatible API returned empty choices. model={model_id}") choice = response.choices[0] msg = getattr(choice, "message", None) if msg is None: raise ValueError( f"OpenAI-compatible API returned choice with null message. model={model_id}" ) + reasoning, reasoning_source, reasoning_details = message_reasoning(msg) return ChatResponse( id=response.id, model=response.model, content=msg.content or "", finish_reason=choice.finish_reason, usage=_normalize_stream_usage(response.usage, response_id=response.id) or {}, + tool_calls=message_tool_call_chunks(msg), + reasoning=reasoning, + reasoning_source=reasoning_source, + reasoning_details=reasoning_details, ) async def chat_stream( @@ -507,6 +518,16 @@ async def chat_stream( has_tools=bool(tools), ) fallback = await self.chat(model_id, messages, **kwargs) + if fallback.tool_calls: + self.log.warn("openai_compatible.stream.empty_response_recovered_tool_calls", { + "model": model_id, + "tool_calls": len(fallback.tool_calls), + }) + for chunk in chat_fallback_tool_call_chunks( + fallback, provider_id=self.id, model_id=model_id, + ): + yield chunk + return fallback_content = fallback.content or "" self.log.debug("openai_compatible.minimax_empty_response_fallback_result", { "model": model_id, @@ -553,7 +574,11 @@ async def chat_stream( "error": str(exc), }) - if tools: + # Only MiniMax keeps its tool-less last resort. Other models asked to + # act with no tools write their calls as text or say they have none; + # the empty-response error below is retryable, so the turn is + # retried with its tools instead. + if tools and minimax_empty_response_target: self.log.warn("openai_compatible.stream.retry_without_tools", { "model": model_id, "reason": str(fallback_error) if fallback_error else "empty_fallback_content", @@ -630,5 +655,5 @@ async def chat_stream( ) raise ValueError( f"OpenAI-compatible API returned an empty streaming response and empty fallback response. " - f"model={model_id}" + f"model={model_id}, tools_declared={bool(tools)}" ) diff --git a/tests/provider/test_empty_stream_tool_fallback.py b/tests/provider/test_empty_stream_tool_fallback.py new file mode 100644 index 000000000..51988faff --- /dev/null +++ b/tests/provider/test_empty_stream_tool_fallback.py @@ -0,0 +1,279 @@ +"""An empty streamed answer keeps its tools on the non-streaming fallback. + +The fallback used to keep only ``content``: an answer made of tool calls alone +(content null) counted as empty, and the request was then repeated without its +tools, so an agent such as the code audit's threat modeler was told it had none. +""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from flocks.provider.provider import ChatMessage, ChatResponse +from flocks.provider.sdk.openai_base import OpenAIBaseProvider, chat_fallback_tool_call_chunks +from flocks.provider.sdk.openai_compatible import OpenAICompatibleProvider +from flocks.session.lifecycle.retry import SessionRetry +from flocks.session.streaming.tool_accumulator import ( + StreamToolArgumentsTruncatedError, + ToolCallAccumulator, +) + + +TOOLS = [{"type": "function", "function": {"name": "audit_repository_summary", "parameters": {"type": "object"}}}] +TOOL_CALLS = [{ + "index": 0, + "id": "call_summary", + "type": "function", + "function": {"name": "audit_repository_summary", "arguments": "{}"}, +}] + + +class _BaseProvider(OpenAIBaseProvider): + DEFAULT_BASE_URL = "https://api.custom.com/v1" + ENV_API_KEY = ["CUSTOM_API_KEY"] + ENV_BASE_URL = "CUSTOM_BASE_URL" + CATALOG_ID = "" + + def __init__(self): + super().__init__(provider_id="custom-provider", name="Custom Provider") + + +def _with_client(provider): + create = AsyncMock() + provider._client = MagicMock() + provider._client.chat.completions.create = create + return provider, create + + +async def _empty_stream(): + if False: + yield None + + +def _fallback(*, content="", tool_calls=None, reasoning=None, finish_reason=None, **extra) -> ChatResponse: + return ChatResponse( + id="resp_fallback", + model="deepseek-v4-flash", + content=content, + finish_reason=finish_reason or ("tool_calls" if tool_calls else "stop"), + usage={"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, + tool_calls=tool_calls, + reasoning=reasoning, + **extra, + ) + + +PROVIDERS = [ + pytest.param(OpenAICompatibleProvider, id="openai_compatible"), + pytest.param(_BaseProvider, id="openai_base"), +] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("provider_class", PROVIDERS) +async def test_tool_calls_of_the_chat_fallback_reach_the_stream(provider_class): + provider, create = _with_client(provider_class()) + create.return_value = _empty_stream() + provider.chat = AsyncMock(return_value=_fallback(tool_calls=TOOL_CALLS, reasoning="先看仓库概况")) + + chunks = [ + chunk async for chunk in provider.chat_stream( + "deepseek-v4-flash", + [ChatMessage(role="user", content="build the threat model")], + tools=TOOLS, + ) + ] + + assert [chunk.reasoning for chunk in chunks if chunk.event_type == "reasoning"] == ["先看仓库概况"] + terminal = chunks[-1] + assert terminal.tool_calls == TOOL_CALLS + assert terminal.finish_reason == "tool_calls" + provider.chat.assert_awaited_once() + assert provider.chat.await_args.kwargs["tools"] == TOOLS + + +@pytest.mark.asyncio +@pytest.mark.parametrize("provider_class", PROVIDERS) +async def test_a_blank_answer_is_not_retried_without_the_tools(provider_class): + provider, create = _with_client(provider_class()) + create.return_value = _empty_stream() + provider.chat = AsyncMock(return_value=_fallback(content="")) + + # "empty streaming response" is what the session retry treats as transient. + with pytest.raises(ValueError, match="empty streaming response.*tools_declared=True"): + _ = [ + chunk async for chunk in provider.chat_stream( + "deepseek-v4-flash", + [ChatMessage(role="user", content="build the threat model")], + tools=TOOLS, + ) + ] + + provider.chat.assert_awaited_once() + assert provider.chat.await_args.kwargs["tools"] == TOOLS + + +@pytest.mark.asyncio +@pytest.mark.parametrize("provider_class", PROVIDERS) +async def test_chat_returns_the_tool_calls_and_reasoning_of_its_message(provider_class): + provider, create = _with_client(provider_class()) + message = SimpleNamespace( + content=None, + reasoning_content="先看仓库概况", + tool_calls=[SimpleNamespace( + id="call_summary", + function=SimpleNamespace(name="audit_repository_summary", arguments=""), + )], + ) + create.return_value = SimpleNamespace( + id="resp_1", + model="deepseek-v4-flash", + usage=SimpleNamespace(prompt_tokens=1, completion_tokens=1, total_tokens=2), + choices=[SimpleNamespace(finish_reason="tool_calls", message=message)], + ) + + response = await provider.chat( + "deepseek-v4-flash", + [ChatMessage(role="user", content="build the threat model")], + tools=TOOLS, + ) + + assert response.content == "" + assert response.reasoning == "先看仓库概况" + assert response.reasoning_source == "reasoning_content" + # Kept as sent: only the replay decides whether "" means "no parameters". + assert response.tool_calls == [{ + "index": 0, + "id": "call_summary", + "type": "function", + "function": {"name": "audit_repository_summary", "arguments": ""}, + }] + + +class _Events: + session_id = "ses_fallback" + + def __init__(self) -> None: + self.events = [] + + async def process_event(self, event) -> None: + self.events.append(event) + + +async def _accumulate(chunks): + """Feed replayed chunks to the real accumulator, as the runner does.""" + processor = _Events() + accumulator = ToolCallAccumulator(processor) + finish_reason = None + for chunk in chunks: + for call in chunk.tool_calls or []: + await accumulator.feed_chunk(call) + finish_reason = chunk.finish_reason or finish_reason + try: + await accumulator.flush_remaining(finish_reason, output_limit=100, raised_output_limit=200) + except StreamToolArgumentsTruncatedError: + # The runner turns this into a tool error the model can react to. + processor.events.append(SimpleNamespace(truncated=True)) + return [type(event).__name__ for event in processor.events], processor.events + + +@pytest.mark.asyncio +@pytest.mark.parametrize("finish_reason", ["length", "max_tokens"]) +async def test_a_cut_off_fallback_call_is_refused_not_run(finish_reason): + chunks = chat_fallback_tool_call_chunks( + _fallback(tool_calls=[{**TOOL_CALLS[0], "function": {"name": "audit_repository_summary", "arguments": ""}}], + finish_reason=finish_reason), + provider_id="custom-h20", + model_id="deepseek-v4-flash", + ) + + kinds, events = await _accumulate(chunks) + + assert "ToolCallEvent" not in kinds + assert "ToolInputErrorEvent" in kinds + assert getattr(events[-1], "truncated", False) + + +@pytest.mark.asyncio +async def test_a_finished_fallback_call_without_arguments_runs_with_none(): + chunks = chat_fallback_tool_call_chunks( + _fallback(tool_calls=[{**TOOL_CALLS[0], "function": {"name": "audit_repository_summary", "arguments": ""}}]), + provider_id="custom-h20", + model_id="deepseek-v4-flash", + ) + + kinds, events = await _accumulate(chunks) + + calls = [event for event in events if type(event).__name__ == "ToolCallEvent"] + assert [(call.tool_name, call.input) for call in calls] == [("audit_repository_summary", {})] + + +def test_reasoning_details_alone_still_make_a_reasoning_chunk(): + details = [{"type": "reasoning.encrypted", "data": "opaque"}] + + chunks = chat_fallback_tool_call_chunks( + _fallback(tool_calls=TOOL_CALLS, reasoning_details=details), + provider_id="openrouter", + model_id="some-model", + ) + + reasoning = [chunk for chunk in chunks if chunk.event_type == "reasoning"] + assert len(reasoning) == 1 + assert reasoning[0].metadata["reasoningDetails"] == details + + +@pytest.mark.asyncio +async def test_empty_choices_on_the_fallback_are_retried_with_the_tools(): + provider, create = _with_client(OpenAICompatibleProvider()) + create.side_effect = [ + _empty_stream(), + SimpleNamespace(id="resp_empty", model="deepseek-v4-flash", usage=None, choices=[]), + ] + + with pytest.raises(ValueError, match="empty choices") as raised: + _ = [ + chunk async for chunk in provider.chat_stream( + "deepseek-v4-flash", + [ChatMessage(role="user", content="build the threat model")], + tools=TOOLS, + ) + ] + + message = str(raised.value) + assert SessionRetry.retryable({"name": "UnknownError", "message": message, "data": {"message": message}}) + assert create.await_count == 2 + assert all(call.kwargs.get("tools") == TOOLS for call in create.await_args_list) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("provider_class", PROVIDERS) +async def test_a_cut_off_call_from_the_endpoint_is_not_run_through_the_fallback(provider_class): + provider, create = _with_client(provider_class()) + message = SimpleNamespace( + content=None, + tool_calls=[SimpleNamespace( + id="call_summary", + function=SimpleNamespace(name="audit_repository_summary", arguments=""), + )], + ) + create.side_effect = [ + _empty_stream(), + SimpleNamespace( + id="resp_cut", model="deepseek-v4-flash", + usage=SimpleNamespace(prompt_tokens=1, completion_tokens=1, total_tokens=2), + choices=[SimpleNamespace(finish_reason="length", message=message)], + ), + ] + + chunks = [ + chunk async for chunk in provider.chat_stream( + "deepseek-v4-flash", + [ChatMessage(role="user", content="build the threat model")], + tools=TOOLS, + ) + ] + kinds, _events = await _accumulate(chunks) + + assert "ToolCallEvent" not in kinds + assert "ToolInputErrorEvent" in kinds From d8c1565eb58bf58b951be5d60913fb9a53c411d7 Mon Sep 17 00:00:00 2001 From: stephamie7 <1223696150@qq.com> Date: Mon, 9 Nov 2026 18:05:58 +0800 Subject: [PATCH 02/44] fix(session): keep new sidebar sessions in activity order --- .../components/layout/SessionHistoryPanel.tsx | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/webui/src/components/layout/SessionHistoryPanel.tsx b/webui/src/components/layout/SessionHistoryPanel.tsx index a043091d9..b14e703b4 100644 --- a/webui/src/components/layout/SessionHistoryPanel.tsx +++ b/webui/src/components/layout/SessionHistoryPanel.tsx @@ -230,8 +230,8 @@ export default function SessionHistoryPanel({ collapsed, onExpandSidebar, onNavi }); const compactCount = HISTORY_PAGE_SIZE; - // The open session can sort past the loaded pages; read it on its own so it stays listed - // (and its folder is known) without loading every older page. + // The open session may be older than the loaded pages, or newly created while + // their refresh is pending. Read it separately so either case stays reachable. const [olderOpenSession, setOlderOpenSession] = useState(null); // Bumped by refreshes so a renamed or moved open session is read again. const [olderOpenSessionVersion, setOlderOpenSessionVersion] = useState(0); @@ -255,10 +255,16 @@ export default function SessionHistoryPanel({ collapsed, onExpandSidebar, onNavi cancelled = true; }; }, [olderOpenSessionVersion, openSessionInPage, selectedSessionId]); - const listedSessions = useMemo( - () => (olderOpenSession && !sessions.some((session) => session.id === olderOpenSession.id) ? [...sessions, olderOpenSession] : sessions), - [olderOpenSession, sessions], - ); + const listedSessions = useMemo(() => { + if (!olderOpenSession || olderOpenSession.id !== selectedSessionId + || sessions.some((session) => session.id === olderOpenSession.id)) return sessions; + // A missing row is not necessarily old. Match the API's newest-activity-first + // order before grouping, so a new session does not jump from the bottom to + // the top when the pending list response arrives. Copy before sorting. + return [...sessions, olderOpenSession].sort( + (a, b) => (b.time?.updated ?? 0) - (a.time?.updated ?? 0), + ); + }, [olderOpenSession, selectedSessionId, sessions]); // Handlers that await a confirmation read the list as it is afterwards, not as it was when they started. const listedSessionsRef = useRef(listedSessions); listedSessionsRef.current = listedSessions; From 7121b5a6e23e0f4566b5aab0635e2f15b89245cf Mon Sep 17 00:00:00 2001 From: jamon Date: Tue, 10 Nov 2026 20:10:05 +0800 Subject: [PATCH 03/44] fix(wecom): report why the channel cannot connect When the server refuses the bot's credentials, the WeCom SDK only emits an error event and closes the socket itself; with websockets >= 14 that clean close ends its receive loop, so it neither reconnects nor reports a disconnect. The gateway had already marked the channel connected 0.5s after start(), so a wrong secret showed the channel as running with no error. A connection replaced by the same bot elsewhere (disconnected_event) stopped the SDK the same way, and network failures only surfaced as "reconnect timed out" after 60s. - Declare self_managed_connection: connected only once authenticated. - Record each SDK error in the channel status. Refused credentials and a replaced connection end start(), so the gateway shows the reason and retries with backoff. - The reconnect watchdog message names the last error. - Events from a client that has since been replaced are ignored. - The status only gives the cause, scheme://host:port, the error type and numeric codes (WeCom errcode, errno, HTTP status). The raw error can quote a credential-bearing address and the status is readable by every signed-in user, so it is written to the server log (wecom.ws.error) only. --- flocks/channel/builtin/wecom/channel.py | 189 +++++++++++++-- tests/channel/test_wecom.py | 297 ++++++++++++++++++++++++ 2 files changed, 468 insertions(+), 18 deletions(-) diff --git a/flocks/channel/builtin/wecom/channel.py b/flocks/channel/builtin/wecom/channel.py index 486950190..9daba4167 100644 --- a/flocks/channel/builtin/wecom/channel.py +++ b/flocks/channel/builtin/wecom/channel.py @@ -3,7 +3,10 @@ Uses the ``wecom-aibot-sdk`` package to maintain a WebSocket long-connection to ``wss://openws.work.weixin.qq.com``. The SDK handles authentication, -heartbeat keep-alive, and exponential-backoff reconnection internally. +heartbeat keep-alive, and exponential-backoff reconnection internally; what it +does not recover from (refused credentials, the server dropping the connection +for a newer one) ends start() with a readable reason, which the gateway shows +in the channel status and retries with backoff. Reference implementation: https://github.com/WecomTeam/wecom-openclaw-plugin @@ -16,6 +19,7 @@ import re from collections import OrderedDict from typing import Any, Awaitable, Callable, Optional +from urllib.parse import urlsplit from flocks.channel.base import ( ChannelCapabilities, @@ -33,6 +37,92 @@ _FRAME_CACHE_MAX = 500 _DEFAULT_RECONNECT_TIMEOUT_SECONDS = 60.0 _LEADING_MENTION_RE = re.compile(r"^\s*(?:@\S+(?:\s+|$))+") +# Shown in error messages when no websocketUrl is configured; the SDK's own default. +_FALLBACK_WS_URL = "wss://openws.work.weixin.qq.com" +# The SDK reports a refused subscribe frame as a plain Exception starting with +# this text (wecom_aibot_sdk.ws ``_handle_frame``), and raises +# WSAuthFailureError once it gives up retrying. +_AUTH_FAILURE_PREFIX = "Authentication failed" +# Reason the SDK passes to "disconnected" when the server drops this connection +# because the same bot opened another one (its ``disconnected_event``). +_REPLACED_BY_NEW_CONNECTION_PREFIX = "New connection established" + + +def _is_auth_failure(error: BaseException) -> bool: + return type(error).__name__ == "WSAuthFailureError" or str(error).startswith(_AUTH_FAILURE_PREFIX) + + +def _shown_ws_url(url: str) -> str: + """The WebSocket address as status messages show it: scheme, host and port only. + + A custom websocketUrl (or the {env:…}/{secret:…} it came from) may carry a + token in its user info, path or query, and the channel status is readable + by every signed-in user. + """ + try: + parts = urlsplit(url) + host = parts.hostname or "" + port = parts.port + except ValueError: + return "自定义地址" + if not parts.scheme or not host: + return "自定义地址" + if ":" in host: + host = f"[{host}]" + return f"{parts.scheme}://{host}" + (f":{port}" if port else "") + + +# The code the SDK appends to a refused subscribe ("… (code: 40058)"). +_AUTH_ERRCODE_RE = re.compile(r"\(code: (-?\d+)\)\s*$") +_SEE_SERVER_LOG = "详细报错见服务端日志 wecom.ws.error。" + + +def _error_facts(error: BaseException) -> str: + """What the status may say about an SDK error: its type and numeric codes, never its text. + + The text can quote an address (a redirect target, an invalid URI) with the + credentials it carries, or whatever a custom server sent back, and the + channel status is readable by every signed-in user. The full error is + logged on the server (``wecom.ws.error``) only. + """ + facts = [f"错误类型 {type(error).__name__}"] + errno = getattr(error, "errno", None) + if isinstance(errno, int): + facts.append(f"errno {errno}") + # websockets' InvalidStatus carries the response; older InvalidStatusCode the code itself. + status = getattr(getattr(error, "response", None), "status_code", None) + if status is None: + status = getattr(error, "status_code", None) + if isinstance(status, int): + facts.append(f"HTTP {status}") + return ",".join(facts) + + +def _describe_sdk_error(error: BaseException, ws_url: str) -> str: + """What the channel status shows for an SDK ``error`` event: the cause, then type and codes only.""" + if _is_auth_failure(error): + match = _AUTH_ERRCODE_RE.search(str(error)) + facts = f"企业微信错误码 {match.group(1)}" if match else _error_facts(error) + return ( + "企业微信机器人鉴权失败:请在企业微信管理后台核对智能机器人的 Bot ID 和 Secret," + "Secret 重置过的要在这里重新填写并保存。" + f"{facts},{_SEE_SERVER_LOG}" + ) + return ( + f"连接企业微信长连接服务({_shown_ws_url(ws_url)})出错:请确认服务器能访问这个地址," + "需要走代理的检查代理设置。" + f"{_error_facts(error)},{_SEE_SERVER_LOG}" + ) + + +def _describe_replaced_connection(reason: str) -> Optional[str]: + """The status message when the server dropped this connection for a newer one, else None.""" + if not reason.startswith(_REPLACED_BY_NEW_CONNECTION_PREFIX): + return None + return ( + "企业微信服务端断开了这个连接:同一个机器人在别处建立了新的长连接(一个 Bot ID 同时只能保持一个连接)。" + "请停掉其他正在使用这个机器人的服务(比如升级前的旧版本),再点「重启连接」。" + ) class _WeComSdkLogger: @@ -85,6 +175,13 @@ def __init__(self) -> None: self._reconnect_timeout_seconds = _DEFAULT_RECONNECT_TIMEOUT_SECONDS self._reconnect_timeout_event = asyncio.Event() self._reconnect_watchdog_task: asyncio.Task[None] | None = None + self._ws_url = _FALLBACK_WS_URL + # Set when the SDK will not recover on its own (refused credentials, a + # newer connection took over): start() fails with this message so the + # gateway shows it and retries with backoff. + self._failure_event = asyncio.Event() + self._failure_message = "" + self._last_error_message: Optional[str] = None def meta(self) -> ChannelMeta: return ChannelMeta( @@ -93,10 +190,13 @@ def meta(self) -> ChannelMeta: ) def capabilities(self) -> ChannelCapabilities: + # Connected only once WeCom accepts the bot's credentials + # (_handle_authenticated), not as soon as start() is running. return ChannelCapabilities( chat_types=[ChatType.DIRECT, ChatType.GROUP], media=True, threads=False, reactions=False, edit=False, rich_text=True, + self_managed_connection=True, ) def validate_config(self, config: dict) -> Optional[str]: @@ -130,6 +230,9 @@ async def start(self, config, on_message, abort_event=None): if error: raise ValueError(error) self._reconnect_timeout_event = asyncio.Event() + self._failure_event = asyncio.Event() + self._failure_message = "" + self._last_error_message = None self._cancel_reconnect_watchdog() try: @@ -141,7 +244,8 @@ async def start(self, config, on_message, abort_event=None): ) ws_url = config.get("websocketUrl", "") - self._ws_client = WSClient( + self._ws_url = ws_url or _FALLBACK_WS_URL + client = WSClient( bot_id=config["botId"], secret=config["secret"], **({"ws_url": ws_url} if ws_url else {}), @@ -151,22 +255,25 @@ async def start(self, config, on_message, abort_event=None): plug_version="1.0.0", # 企微服务端用于下发 MCP Server URL 时的版本校验 logger=_WeComSdkLogger(), ) + self._ws_client = client - self._ws_client.on("authenticated", self._handle_authenticated) - self._ws_client.on("disconnected", self._handle_disconnected) - self._ws_client.on("reconnecting", self._handle_reconnecting) - self._ws_client.on("error", self._handle_error) + # Each handler knows which client raised the event: one that has been + # replaced (a restart) must not change the status of the next one. + client.on("authenticated", lambda: self._handle_authenticated(client=client)) + client.on("disconnected", lambda reason="": self._handle_disconnected(reason, client=client)) + client.on("reconnecting", lambda attempt=0: self._handle_reconnecting(attempt, client=client)) + client.on("error", lambda error: self._handle_error(error, client=client)) handler = self._make_message_handler(on_message) # 监听通用 message 事件(SDK 对所有消息类型都会触发此事件) # 同时保留各类型事件作为备用,handler 内部有去重保护 - self._ws_client.on("message", handler) + client.on("message", handler) for event in ("message.text", "message.image", "message.mixed", "message.voice", "message.file"): - self._ws_client.on(event, handler) + client.on(event, handler) log.info("wecom.ws.connecting", {"bot_id": config["botId"]}) - await self._ws_client.connect() + await client.connect() try: await self._wait_until_stopped(abort_event) @@ -329,38 +436,84 @@ async def _wait_until_stopped( abort_event.wait() if abort_event else asyncio.Event().wait() ) reconnect_waiter = asyncio.create_task(self._reconnect_timeout_event.wait()) + failure_waiter = asyncio.create_task(self._failure_event.wait()) done, pending = await asyncio.wait( - {abort_waiter, reconnect_waiter}, + {abort_waiter, reconnect_waiter, failure_waiter}, return_when=asyncio.FIRST_COMPLETED, ) for task in pending: task.cancel() await asyncio.gather(*pending, return_exceptions=True) + if failure_waiter in done and self._failure_event.is_set(): + raise RuntimeError(self._failure_message) if reconnect_waiter in done and self._reconnect_timeout_event.is_set(): - raise RuntimeError( - "WeCom reconnect timed out after " - f"{self._reconnect_timeout_seconds:.1f}s" - ) + raise RuntimeError(self._reconnect_timeout_message()) + + def _reconnect_timeout_message(self) -> str: + head = f"WeCom reconnect timed out after {self._reconnect_timeout_seconds:.1f}s" + if self._last_error_message: + return f"{head}。最近一次错误:{self._last_error_message}" + return ( + f"{head}:断开后没能重新连上企业微信长连接服务({_shown_ws_url(self._ws_url)})," + "请确认服务器能访问这个地址,需要走代理的检查代理设置。" + ) - def _handle_authenticated(self) -> None: + def _is_stale(self, client: Any) -> bool: + """True for an event raised by a client this channel no longer runs.""" + return client is not None and client is not self._ws_client + + def _fail(self, message: str) -> None: + """End this connection attempt: start() raises *message*, which the status shows.""" + self.mark_disconnected(message) + self._failure_message = message + self._failure_event.set() + + def _handle_authenticated(self, client: Any = None) -> None: + if self._is_stale(client): + return self.mark_connected() + self._last_error_message = None self._reconnect_timeout_event.clear() self._cancel_reconnect_watchdog() log.info("wecom.ws.authenticated") - def _handle_disconnected(self, reason: str) -> None: + def _handle_disconnected(self, reason: str, client: Any = None) -> None: + if self._is_stale(client): + return + reason = str(reason) + replaced = None if self._intentional_disconnect else _describe_replaced_connection(reason) + if replaced: + # The SDK stops reconnecting after this: the server would drop a new + # connection again while the other one is up. + log.warning("wecom.ws.replaced", {"reason": reason}) + self._fail(replaced) + return self.mark_disconnected() log.warning("wecom.ws.disconnected", {"reason": reason}) self._start_reconnect_watchdog(reason=f"disconnected:{reason}") - def _handle_reconnecting(self, attempt: int) -> None: + def _handle_reconnecting(self, attempt: int, client: Any = None) -> None: + if self._is_stale(client): + return self.mark_disconnected() log.info("wecom.ws.reconnecting", {"attempt": attempt}) self._start_reconnect_watchdog(reason=f"reconnecting:{attempt}") - def _handle_error(self, error: Exception) -> None: + def _handle_error(self, error: Exception, client: Any = None) -> None: log.error("wecom.ws.error", {"error": str(error)}) + if self._is_stale(client) or self._intentional_disconnect: + return + message = _describe_sdk_error(error, self._ws_url) + self._last_error_message = message + if _is_auth_failure(error): + # After a refused subscribe frame the SDK closes the socket itself, + # and as a clean close ends its receive loop it never tries again. + self._fail(message) + return + # Connection-level errors: the SDK keeps reconnecting; the status says why + # until it is back (or the reconnect watchdog gives up). + self.mark_disconnected(message) def _start_reconnect_watchdog(self, reason: str) -> None: if self._intentional_disconnect or self._ws_client is None: diff --git a/tests/channel/test_wecom.py b/tests/channel/test_wecom.py index 62a20059f..630c494d2 100644 --- a/tests/channel/test_wecom.py +++ b/tests/channel/test_wecom.py @@ -516,6 +516,303 @@ async def _disconnect(self): assert ch._ws_client is None +# ------------------------------------------------------------------ +# connection status: what the channel page shows when WeCom fails +# ------------------------------------------------------------------ + +def _scripted_ws_client(script): + """A WSClient stand-in whose connect() replays SDK events: [(event, *args), ...].""" + + class FakeWSClient: + last_instance = None + + def __init__(self, *args, **kwargs): + self.handlers = {} + self.disconnect = AsyncMock() + FakeWSClient.last_instance = self + + def on(self, event, handler): + self.handlers[event] = handler + + async def connect(self): + for event, *args in script: + self.handlers[event](*args) + + return FakeWSClient + + +class TestWeComConnectionStatus: + AUTH_REFUSED = Exception("Authentication failed: invalid secret (code: 40058)") + REPLACED = "New connection established, server disconnected this connection" + + def test_connection_is_self_managed(self): + # Connected only once WeCom accepts the credentials, not when start() runs. + assert WeComChannel().capabilities().self_managed_connection is True + + async def test_refused_credentials_end_start_with_the_reason(self): + FakeWSClient = _scripted_ws_client([("error", self.AUTH_REFUSED)]) + ch = WeComChannel() + config = {"botId": "bot-1", "secret": "wrong-secret"} + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + with pytest.raises(RuntimeError, match="鉴权失败") as raised: + await asyncio.wait_for(ch.start(config, AsyncMock(), asyncio.Event()), timeout=5) + + assert "Bot ID 和 Secret" in str(raised.value) + assert "企业微信错误码 40058" in str(raised.value) + # What the server said stays in the server log, not in the status. + assert "invalid secret" not in str(raised.value) + assert ch.status.connected is False + assert ch.status.last_error == str(raised.value) + assert ch.status.error_count == 1 + FakeWSClient.last_instance.disconnect.assert_awaited_once() + + async def test_connection_replaced_elsewhere_ends_start_with_the_reason(self): + FakeWSClient = _scripted_ws_client([("authenticated",), ("disconnected", self.REPLACED)]) + ch = WeComChannel() + config = {"botId": "bot-1", "secret": "secret-1"} + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + with pytest.raises(RuntimeError, match="别处建立了新的长连接") as raised: + await asyncio.wait_for(ch.start(config, AsyncMock(), asyncio.Event()), timeout=5) + + assert "停掉其他正在使用这个机器人的服务" in str(raised.value) + assert ch.status.connected is False + assert ch.status.last_error == str(raised.value) + + async def test_reconnect_timeout_names_the_last_error(self): + FakeWSClient = _scripted_ws_client([ + ("error", ConnectionRefusedError(61, "Connect call failed ('127.0.0.1', 9)")), + ("reconnecting", 1), + ]) + ch = WeComChannel() + config = { + "botId": "bot-1", + "secret": "secret-1", + "websocketUrl": "ws://127.0.0.1:9", + "reconnectTimeoutSeconds": 0.01, + } + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + with pytest.raises(RuntimeError, match="reconnect timed out") as raised: + await asyncio.wait_for(ch.start(config, AsyncMock(), asyncio.Event()), timeout=5) + + message = str(raised.value) + assert "最近一次错误" in message + assert "ws://127.0.0.1:9" in message + assert "错误类型 ConnectionRefusedError,errno 61" in message + assert "Connect call failed" not in message + assert "ConnectionRefusedError" in (ch.status.last_error or "") + + TOKEN_URL = "wss://bot:pa55word@gw.example.com:8443/ws/path-token-abc?token=SECRET123#frag" # secret-guard: allow (synthetic test credential) + URL_SECRETS = ("SECRET123", "path-token-abc", "pa55word", "#frag") + + async def test_status_keeps_credentials_in_the_address_out(self): + # The channel status is readable by every signed-in user; a custom + # address may carry a token. Only scheme, host and port are shown. + FakeWSClient = _scripted_ws_client([ + ("error", ValueError(f"{self.TOKEN_URL} isn't a valid URI")), + ("error", OSError("connect to gw.example.com:8443/ws/path-token-abc?token=SECRET123 failed")), + ("reconnecting", 1), + ]) + ch = WeComChannel() + config = { + "botId": "bot-1", + "secret": "secret-1", + "websocketUrl": self.TOKEN_URL, + "reconnectTimeoutSeconds": 0.01, + } + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + with pytest.raises(RuntimeError, match="reconnect timed out") as raised: + await asyncio.wait_for(ch.start(config, AsyncMock(), asyncio.Event()), timeout=5) + + for shown in (str(raised.value), ch.status.last_error or ""): + assert "wss://gw.example.com:8443" in shown + for secret in self.URL_SECRETS: + assert secret not in shown + + async def test_reconnect_timeout_without_error_shows_only_the_host(self): + FakeWSClient = _scripted_ws_client([("disconnected", "socket closed")]) + ch = WeComChannel() + config = { + "botId": "bot-1", + "secret": "secret-1", + "websocketUrl": self.TOKEN_URL, + "reconnectTimeoutSeconds": 0.01, + } + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + with pytest.raises(RuntimeError, match="reconnect timed out") as raised: + await asyncio.wait_for(ch.start(config, AsyncMock(), asyncio.Event()), timeout=5) + + assert "wss://gw.example.com:8443" in str(raised.value) + for secret in self.URL_SECRETS: + assert secret not in str(raised.value) + + @pytest.mark.parametrize( + ("configured", "raw_error", "secrets"), + [ + # websockets' redirect check names the target, which keeps only some of the parameters. + ( + "wss://gw.example/ws/path-token?token=SECRET123®ion=cn", # secret-guard: allow (synthetic test credential) + "cannot follow redirect to ws://gw.example/ws/path-token?token=SECRET123", + ("SECRET123", "path-token"), + ), + # A parameter value on its own, outside any address. + ( + "wss://gw.example/ws?token=SECRET123®ion=cn", # secret-guard: allow (synthetic test credential) + "server refused credential SECRET123", + ("SECRET123",), + ), + # Percent-encoded in the configured address, decoded (or encoded) in the error. + ( + "wss://gw.example/ws?token=a%2Fb%2Bc12345", # secret-guard: allow (synthetic test credential) + "rejected a/b+c12345 (sent as a%2Fb%2Bc12345)", + ("a/b+c12345", "a%2Fb%2Bc12345"), + ), + # User info, in an address the error rewrote with an explicit port. + ( + "wss://bot:pa55word@gw.example/ws", # secret-guard: allow (synthetic test credential) + "InvalidURI: wss://bot:pa55word@gw.example:443/ws is not valid", # secret-guard: allow (synthetic) + ("pa55word", "bot:pa55word"), + ), + # A quote inside the credential: an address pattern would stop there and miss the rest. + ( + "wss://bot:ab'LONGSECRET123456@gw.example/ws", # secret-guard: allow (synthetic test credential) + "cannot follow redirect to ws://bot:ab'LONGSECRET123456@gw.example/ws", # secret-guard: allow (synthetic) + ("LONGSECRET123456",), + ), + ( + "wss://gw.example/ws?token=ab%27LONGSECRET123456", # secret-guard: allow (synthetic test credential) + "cannot follow redirect to ws://gw.example/ws?token=ab'LONGSECRET123456", # secret-guard: allow (synthetic) + ("LONGSECRET123456",), + ), + ], + ) + def test_error_text_loses_credentials_of_the_address(self, configured, raw_error, secrets): + from flocks.channel.builtin.wecom.channel import _describe_sdk_error + + shown = _describe_sdk_error(RuntimeError(raw_error), configured) + + assert "wss://gw.example" in shown + for secret in secrets: + assert secret not in shown + + def test_status_gives_type_and_codes_never_the_error_text(self): + from flocks.channel.builtin.wecom.channel import _describe_sdk_error + + class InvalidStatus(Exception): + # Shaped like websockets.exceptions.InvalidStatus: the code sits on the response. + def __init__(self): + super().__init__("server rejected WebSocket connection: HTTP 403 body=whatever-the-proxy-said") + self.response = types.SimpleNamespace(status_code=403) + + shown = _describe_sdk_error(InvalidStatus(), "wss://gw.example/ws") + assert "错误类型 InvalidStatus,HTTP 403" in shown + assert "whatever-the-proxy-said" not in shown + + refused = _describe_sdk_error( + Exception("Authentication failed: echoed wss://gw.example/ws?token=ECHOED (code: 40058)"), + "wss://gw.example/ws", + ) + assert "企业微信错误码 40058" in refused + assert "ECHOED" not in refused + assert "wecom.ws.error" in refused # where the full error is + + @pytest.mark.parametrize( + ("url", "shown"), + [ + ("wss://openws.work.weixin.qq.com", "wss://openws.work.weixin.qq.com"), + ("ws://[::1]:9/path?k=v", "ws://[::1]:9"), + ("wss://user:pw@host.example/x", "wss://host.example"), + ("wss://host.example:99999/x", "自定义地址"), + ("openws.work.weixin.qq.com/ws", "自定义地址"), + ], + ) + def test_shown_address_is_scheme_host_and_port(self, url, shown): + from flocks.channel.builtin.wecom.channel import _shown_ws_url + + assert _shown_ws_url(url) == shown + + async def test_transient_connection_error_shows_until_authenticated(self): + ch = WeComChannel() + client = object() + ch._ws_client = client + + ch._handle_error(OSError("network is unreachable"), client=client) + assert ch.status.connected is False + assert "错误类型 OSError" in (ch.status.last_error or "") + assert "network is unreachable" not in (ch.status.last_error or "") + assert not ch._failure_event.is_set() + + ch._handle_authenticated(client=client) + assert ch.status.connected is True + assert ch.status.last_error is None + + async def test_events_from_a_replaced_client_are_ignored(self): + ch = WeComChannel() + old_client, new_client = object(), object() + ch._ws_client = new_client + + ch._handle_error(self.AUTH_REFUSED, client=old_client) + ch._handle_disconnected(self.REPLACED, client=old_client) + ch._handle_authenticated(client=old_client) + + assert not ch._failure_event.is_set() + assert ch.status.connected is False + assert ch.status.last_error is None + + async def test_gateway_marks_connected_only_after_authentication(self): + from flocks.channel.gateway.manager import GatewayManager + + FakeWSClient = _scripted_ws_client([]) # connected socket, no answer to the subscribe yet + ch = WeComChannel() + abort_event = asyncio.Event() + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + task = asyncio.create_task(GatewayManager()._run_with_reconnect( + channel_id="wecom", + plugin=ch, + config={"botId": "bot-1", "secret": "secret-1"}, + on_message=AsyncMock(), + abort_event=abort_event, + )) + # The gateway pre-marks channels that are not self-managed after 0.5 s. + await asyncio.sleep(0.7) + assert ch.status.connected is False + + FakeWSClient.last_instance.handlers["authenticated"]() + assert ch.status.connected is True + + abort_event.set() + await asyncio.wait_for(task, timeout=5) + + async def test_gateway_shows_refused_credentials_while_waiting_to_retry(self): + from flocks.channel.gateway.manager import GatewayManager + + FakeWSClient = _scripted_ws_client([("error", self.AUTH_REFUSED)]) + ch = WeComChannel() + abort_event = asyncio.Event() + + with patch("wecom_aibot_sdk.WSClient", FakeWSClient): + task = asyncio.create_task(GatewayManager()._run_with_reconnect( + channel_id="wecom", + plugin=ch, + config={"botId": "bot-1", "secret": "wrong-secret"}, + on_message=AsyncMock(), + abort_event=abort_event, + )) + await asyncio.sleep(0.2) # first attempt failed; the gateway waits before retrying + + assert ch.status.connected is False + assert "鉴权失败" in (ch.status.last_error or "") + assert ch.status.error_count == 1 + + abort_event.set() + await asyncio.wait_for(task, timeout=5) + + # ------------------------------------------------------------------ # normalize_target # ------------------------------------------------------------------ From 03a83a467b253c55a20bcd07314d2cf3dad9f19c Mon Sep 17 00:00:00 2001 From: jamon Date: Tue, 10 Nov 2026 20:10:05 +0800 Subject: [PATCH 04/44] fix(webui): show stored channel credentials as saved Admins read channel credentials as their {secret:...}, {env:...} or {file:...} reference, and the channel page put that text into the secret field as its value. Users took the secret for lost, and typing a new one after the reference saved "{secret:...}new": the stored value plus the new one, which then fails authentication. - A whole-value reference renders as an empty field marked as saved; typing replaces it. - An emptied field reports undefined for every caller, so the save leaves the stored credential alone. Nested Feishu accounts used to send an empty string here, which overwrote the stored reference. - The email password and access token fields no longer share one input instance across auth modes. - The header badge says "connection error" while the gateway waits to retry, matching the status panel and the channel list. --- webui/src/locales/en-US/channel.json | 7 + webui/src/locales/zh-CN/channel.json | 7 + webui/src/pages/Channel/index.test.tsx | 252 +++++++++++++++++++++++++ webui/src/pages/Channel/index.tsx | 60 +++++- 4 files changed, 322 insertions(+), 4 deletions(-) diff --git a/webui/src/locales/en-US/channel.json b/webui/src/locales/en-US/channel.json index ccbed875c..f49707773 100644 --- a/webui/src/locales/en-US/channel.json +++ b/webui/src/locales/en-US/channel.json @@ -78,6 +78,13 @@ "restartHint": "Manually stop and re-establish the long connection", "restartSuccess": "{{channel}} restarted", "restartFailed": "Restart failed", + "secretInput": { + "saved": "Saved", + "savedPlaceholder": "Saved. Type a new value to replace it", + "envPlaceholder": "From environment variable {{name}}. Type a new value to replace it", + "filePlaceholder": "From file {{name}}. Type a new value to replace it", + "savedTitle": "Stored on the server and not shown here. Type a new value and save to replace it; leave it empty to keep it." + }, "security": { "defaultAgent": "Default Agent", "defaultAgentHint": "Must be one of visible agents; falls back to system default when unset", diff --git a/webui/src/locales/zh-CN/channel.json b/webui/src/locales/zh-CN/channel.json index 29b3e228c..746f4819b 100644 --- a/webui/src/locales/zh-CN/channel.json +++ b/webui/src/locales/zh-CN/channel.json @@ -78,6 +78,13 @@ "restartHint": "手动停止并重新建立长连接", "restartSuccess": "{{channel}} 已重启", "restartFailed": "重启失败", + "secretInput": { + "saved": "已保存", + "savedPlaceholder": "已保存,输入新值可替换", + "envPlaceholder": "取自环境变量 {{name}},输入新值可替换", + "filePlaceholder": "取自文件 {{name}},输入新值可替换", + "savedTitle": "已保存在服务器上,页面不显示原值。输入新值后保存即可替换;留空保存则保持不变。" + }, "security": { "defaultAgent": "默认 Agent", "defaultAgentHint": "必须为可见 Agent 之一;未设置时按系统默认", diff --git a/webui/src/pages/Channel/index.test.tsx b/webui/src/pages/Channel/index.test.tsx index b51531ef4..c620e7b86 100644 --- a/webui/src/pages/Channel/index.test.tsx +++ b/webui/src/pages/Channel/index.test.tsx @@ -100,6 +100,258 @@ describe('ChannelPage WeCom configuration', () => { }); }); +describe('ChannelPage saved secret reference', () => { + const reference = '{secret:channel_wecom_secret}'; + + beforeEach(() => { + vi.clearAllMocks(); + useAgents.mockReturnValue({ agents: [] }); + client.patch.mockResolvedValue({ data: {} }); + client.post.mockResolvedValue({ data: {} }); + client.get.mockImplementation((url: string) => { + if (url === '/api/channel/list') { + return Promise.resolve({ + data: [{ + id: 'wecom', + label: 'WeCom', + aliases: [], + capabilities: { + chat_types: ['direct', 'group'], + media: true, + threads: false, + reactions: false, + edit: false, + rich_text: false, + }, + running: false, + }], + }); + } + if (url === '/api/config') { + // What GET /api/config returns admins: where the secret is stored, not the secret. + return Promise.resolve({ + data: { channels: { wecom: { enabled: true, botId: 'bot-id', secret: reference } } }, + }); + } + if (url === '/api/channel/status') { + return Promise.resolve({ data: {} }); + } + return Promise.reject(new Error(`Unexpected GET ${url}`)); + }); + }); + + async function saveAndGetWeComPayload(user: ReturnType) { + await user.click(screen.getByRole('button', { name: 'save' })); + await waitFor(() => { + expect(client.patch).toHaveBeenCalledWith('/api/config/', expect.any(Object)); + }); + return client.patch.mock.calls[0][1].channels.wecom; + } + + it('shows the stored secret as saved instead of its reference text', async () => { + render(); + + const secretInput = await screen.findByPlaceholderText('secretInput.savedPlaceholder'); + expect(secretInput).toHaveValue(''); + expect(screen.getByText('secretInput.saved')).toBeInTheDocument(); + expect(screen.queryByDisplayValue(reference)).not.toBeInTheDocument(); + }); + + it('keeps the stored secret when the field is left alone', async () => { + const user = userEvent.setup(); + render(); + await screen.findByPlaceholderText('secretInput.savedPlaceholder'); + + expect((await saveAndGetWeComPayload(user)).secret).toBe(reference); + }); + + it('saves a newly typed secret', async () => { + const user = userEvent.setup(); + render(); + + await user.type(await screen.findByPlaceholderText('secretInput.savedPlaceholder'), 'new-secret'); + expect(screen.getByDisplayValue('new-secret')).toBeInTheDocument(); + + expect((await saveAndGetWeComPayload(user)).secret).toBe('new-secret'); + }); + + it('header says the connection failed while the gateway waits to retry', async () => { + client.get.mockImplementation((url: string) => { + if (url === '/api/channel/list') { + return Promise.resolve({ + data: [{ + id: 'wecom', + label: 'WeCom', + aliases: [], + capabilities: { chat_types: ['direct'], media: false, threads: false, reactions: false, edit: false, rich_text: false }, + running: true, + }], + }); + } + if (url === '/api/config') { + return Promise.resolve({ + data: { channels: { wecom: { enabled: true, botId: 'bot-id', secret: reference } } }, + }); + } + if (url === '/api/channel/status') { + return Promise.resolve({ + data: { wecom: { connected: false, last_error: 'auth refused', error_count: 1, reconnect_count: 2 } }, + }); + } + return Promise.reject(new Error(`Unexpected GET ${url}`)); + }); + render(); + + expect(await screen.findByText('auth refused')).toBeInTheDocument(); + expect(screen.queryByText('header.connecting')).not.toBeInTheDocument(); + }); + + it('leaves the stored secret alone when a typed one is cleared again', async () => { + const user = userEvent.setup(); + render(); + + await user.type(await screen.findByPlaceholderText('secretInput.savedPlaceholder'), 'x'); + await user.clear(screen.getByDisplayValue('x')); + + // Left out of the save, so the server keeps what it stores. + const payload = await saveAndGetWeComPayload(user); + expect(Object.prototype.hasOwnProperty.call(payload, 'secret')).toBe(false); + }); +}); + +describe('ChannelPage feishu account credentials', () => { + beforeEach(() => { + vi.clearAllMocks(); + useAgents.mockReturnValue({ agents: [] }); + client.patch.mockResolvedValue({ data: {} }); + client.post.mockResolvedValue({ data: {} }); + client.get.mockImplementation((url: string) => { + if (url === '/api/channel/list') { + return Promise.resolve({ + data: [{ + id: 'feishu', + label: 'Feishu', + aliases: [], + capabilities: { chat_types: ['direct', 'group'], media: true, threads: true, reactions: true, edit: true, rich_text: true }, + running: false, + }], + }); + } + if (url === '/api/config') { + return Promise.resolve({ + data: { + channels: { + feishu: { + enabled: false, + accounts: { a: { enabled: true, appId: 'cli_a', appSecret: '{secret:feishu_account_a_secret}' } }, + }, + }, + }, + }); + } + if (url === '/api/channel/status') { + return Promise.resolve({ data: {} }); + } + return Promise.reject(new Error(`Unexpected GET ${url}`)); + }); + }); + + it('keeps a nested account secret when its field is typed in and cleared again', async () => { + const user = userEvent.setup(); + render(); + + await user.click(await screen.findByText('feishu.multiAccount')); + await user.type(await screen.findByPlaceholderText('secretInput.savedPlaceholder'), 'x'); + await user.clear(screen.getByDisplayValue('x')); + await user.click(screen.getByRole('button', { name: 'save' })); + await waitFor(() => { + expect(client.patch).toHaveBeenCalledWith('/api/config/', expect.any(Object)); + }); + + // As sent on the wire: an empty string here would overwrite the stored reference. + const sent = JSON.parse(JSON.stringify(client.patch.mock.calls[0][1])); + const account = sent.channels.feishu.accounts.a; + expect(account.appId).toBe('cli_a'); + expect(Object.prototype.hasOwnProperty.call(account, 'appSecret')).toBe(false); + }); +}); + +describe('ChannelPage email credentials across auth modes', () => { + function mockEmail(email: Record) { + client.get.mockImplementation((url: string) => { + if (url === '/api/channel/list') { + return Promise.resolve({ + data: [{ + id: 'email', + label: 'Email', + aliases: [], + capabilities: { chat_types: ['direct'], media: true, threads: false, reactions: false, edit: false, rich_text: false }, + running: false, + }], + }); + } + if (url === '/api/config') { + return Promise.resolve({ data: { channels: { email } } }); + } + if (url === '/api/channel/status') { + return Promise.resolve({ data: {} }); + } + return Promise.reject(new Error(`Unexpected GET ${url}`)); + }); + } + + beforeEach(() => { + vi.clearAllMocks(); + useAgents.mockReturnValue({ agents: [] }); + client.patch.mockResolvedValue({ data: {} }); + client.post.mockResolvedValue({ data: {} }); + }); + + async function switchTypeClearAndSave( + user: ReturnType, + mode: string, + placeholder: string, + ) { + // The auth mode emit(e.target.value)} + placeholder={hint} + autoComplete="new-password" + className="w-full px-3 py-1.5 pr-20 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500" + /> + + + + {t('secretInput.saved')} + + + + ); + } + return (
onChange(e.target.value)} + onChange={(e) => emit(e.target.value)} placeholder={placeholder} + autoComplete="new-password" className="w-full px-3 py-1.5 pr-9 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500" /> + + + ) : ( + + )} +
+ + )} + {!isBusy && error && ( })); vi.mock('@/components/common/PageHeader', () => ({ default: ({ title, actions }: any) =>

{title}

{actions}
})); vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (k: string) => k, i18n: { language: 'zh-CN' } }) })); @@ -34,4 +37,15 @@ describe('AdminUsersPage', () => { await waitFor(() => expect(logout).toHaveBeenCalledTimes(1)); expect(screen.queryByText('OTP-1234-5678')).not.toBeInTheDocument(); }); + + it('says why the password reset was refused instead of the bare status code', async () => { + logout.mockClear(); + vi.mocked(authApi.resetPassword).mockRejectedValueOnce(backendError(429, '重置过于频繁,请 10 分钟后再试')); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'admin.resetAction' })); + + await waitFor(() => expect(toast.error).toHaveBeenCalledWith('admin.resetFailedToast', '重置过于频繁,请 10 分钟后再试')); + expect(logout).not.toHaveBeenCalled(); + }); }); diff --git a/webui/src/pages/AdminUsers/index.tsx b/webui/src/pages/AdminUsers/index.tsx index 2a9443727..ff703898d 100644 --- a/webui/src/pages/AdminUsers/index.tsx +++ b/webui/src/pages/AdminUsers/index.tsx @@ -5,6 +5,7 @@ import CopyButton from '@/components/common/CopyButton'; import { useAuth } from '@/contexts/AuthContext'; import { useToast } from '@/components/common/Toast'; import { useConfirm } from '@/components/common/ConfirmDialog'; +import { extractErrorMessage } from '@/utils/error'; function formatDateTime(value: string | null | undefined, locale: string) { if (!value) return '-'; @@ -66,7 +67,7 @@ export default function AdminUsersPage() { } catch (err: any) { toast.error( t('admin.resetFailedToast'), - err?.response?.data?.detail || err?.message || t('admin.resetFailedToast'), + extractErrorMessage(err, t('admin.resetFailedToast')), ); } }; diff --git a/webui/src/pages/Settings/ArchivedDataPanel.test.tsx b/webui/src/pages/Settings/ArchivedDataPanel.test.tsx index cd5756afe..bde124e5c 100644 --- a/webui/src/pages/Settings/ArchivedDataPanel.test.tsx +++ b/webui/src/pages/Settings/ArchivedDataPanel.test.tsx @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { act, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import ArchivedDataPanel from './ArchivedDataPanel'; +import { backendError } from '@/test/helpers'; const { sessionApi, toast } = vi.hoisted(() => ({ sessionApi: { @@ -53,6 +54,14 @@ describe('ArchivedDataPanel', () => { sessionApi.delete.mockResolvedValue(true); }); + it('says why the archived sessions could not be loaded instead of the bare status code', async () => { + sessionApi.list.mockRejectedValue(backendError(403, '只有管理员可以查看归档数据')); + render(); + + expect(await screen.findByText('只有管理员可以查看归档数据')).toBeInTheDocument(); + expect(screen.queryByText(/status code 403/)).not.toBeInTheDocument(); + }); + it('loads archived sessions and restores one', async () => { const user = userEvent.setup(); render(); diff --git a/webui/src/pages/Settings/ArchivedDataPanel.tsx b/webui/src/pages/Settings/ArchivedDataPanel.tsx index da4c696c6..3c5853c66 100644 --- a/webui/src/pages/Settings/ArchivedDataPanel.tsx +++ b/webui/src/pages/Settings/ArchivedDataPanel.tsx @@ -5,6 +5,7 @@ import { sessionApi } from '@/api/session'; import { useToast } from '@/components/common/Toast'; import PageHeader from '@/components/common/PageHeader'; import type { Session } from '@/types'; +import { extractErrorMessage } from '@/utils/error'; const PAGE_SIZE = 50; const SYSTEM_SESSION_OWNER_USER_ID = 'api-token-service'; @@ -82,7 +83,7 @@ export default function ArchivedDataPanel() { if (!append) setSelectedIds(new Set()); } catch (err: any) { if (requestSeq !== requestSeqRef.current) return; - setError(err?.response?.data?.detail || err?.message || t('archivedData.loadFailed')); + setError(extractErrorMessage(err, t('archivedData.loadFailed'))); } finally { if (requestSeq === requestSeqRef.current) { setLoading(false); diff --git a/webui/src/pages/Settings/DataRetentionSection.tsx b/webui/src/pages/Settings/DataRetentionSection.tsx index 1d74e7a5e..ad0cd68a1 100644 --- a/webui/src/pages/Settings/DataRetentionSection.tsx +++ b/webui/src/pages/Settings/DataRetentionSection.tsx @@ -11,6 +11,7 @@ import { type DataRetentionState, } from '@/api/dataRetention'; import { formatBytes } from '@/api/workspace'; +import { extractErrorMessage } from '@/utils/error'; /** Choices offered for every kind of data; 0 keeps it forever. */ const RETENTION_PRESETS = [7, 14, 30, 90, 180, 365, 0]; @@ -85,7 +86,7 @@ export default function DataRetentionSection() { } return next; } catch (err: any) { - if (mountedRef.current) showToastError(loadFailedMessage, err?.response?.data?.detail || err?.message); + if (mountedRef.current) showToastError(loadFailedMessage, extractErrorMessage(err, '')); return null; } }, [loadFailedMessage, showToastError]); @@ -113,7 +114,7 @@ export default function DataRetentionSection() { setDraft(policyOf(next)); }) .catch((err: any) => { - if (!cancelled) showToastError(loadFailedMessage, err?.response?.data?.detail || err?.message); + if (!cancelled) showToastError(loadFailedMessage, extractErrorMessage(err, '')); }) .finally(() => { if (!cancelled) setLoading(false); @@ -204,7 +205,7 @@ export default function DataRetentionSection() { setSavedAt(requestedAt); showToastSuccess(t(willDelete ? 'dataRetentionSavedCleaning' : 'dataRetentionSaved')); } catch (err: any) { - showToastError(t('dataRetentionSaveFailed'), err?.response?.data?.detail || err?.message); + showToastError(t('dataRetentionSaveFailed'), extractErrorMessage(err, '')); } finally { if (mountedRef.current) setSaving(false); } diff --git a/webui/src/pages/Settings/index.test.tsx b/webui/src/pages/Settings/index.test.tsx index 80c9f9d48..d1d1748c0 100644 --- a/webui/src/pages/Settings/index.test.tsx +++ b/webui/src/pages/Settings/index.test.tsx @@ -5,6 +5,7 @@ import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; import SettingsPage from './index'; import { ThemeContext, type Theme, type ThemeMode } from '@/contexts/ThemeContext'; import { ToastProvider } from '@/components/common/Toast'; +import { backendError } from '@/test/helpers'; const { changeLanguage, dataRetentionApi, setTheme, toolFailureConfigApi, useAuth } = vi.hoisted(() => ({ changeLanguage: vi.fn(), @@ -183,6 +184,28 @@ describe('SettingsPage', () => { }); }); + it('says why the tool failure setting could not be loaded or saved instead of the bare status code', async () => { + const user = userEvent.setup(); + toolFailureConfigApi.get.mockRejectedValue(backendError(503, '配置服务暂时不可用')); + toolFailureConfigApi.update.mockRejectedValue(backendError(403, '只有管理员可以修改这个设置')); + + renderSettings('/settings/preferences'); + + expect(await screen.findByText('配置服务暂时不可用')).toBeInTheDocument(); + await user.click(await screen.findByRole('switch', { name: 'toolFailureAutoDisable' })); + expect(await screen.findByText('只有管理员可以修改这个设置')).toBeInTheDocument(); + expect(screen.queryByText(/status code/)).not.toBeInTheDocument(); + }); + + it('says why the data retention policy could not be loaded instead of the bare status code', async () => { + dataRetentionApi.get.mockRejectedValue(backendError(503, '数据库当前只读,读不到保留策略')); + + renderSettings('/settings/preferences'); + + expect(await screen.findByText('数据库当前只读,读不到保留策略')).toBeInTheDocument(); + expect(screen.queryByText(/status code 503/)).not.toBeInTheDocument(); + }); + it('previews the cleanup and saves the data retention policy only after the admin confirms', async () => { const user = userEvent.setup(); const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true); diff --git a/webui/src/pages/Settings/index.tsx b/webui/src/pages/Settings/index.tsx index 8bbd2e335..46dc69a30 100644 --- a/webui/src/pages/Settings/index.tsx +++ b/webui/src/pages/Settings/index.tsx @@ -30,6 +30,7 @@ import { type SettingsSectionId, } from '@/utils/settingsSections'; import { preloadI18nNamespaces } from '@/i18nResources'; +import { extractErrorMessage } from '@/utils/error'; import DataRetentionSection from './DataRetentionSection'; type LazySettingsModule = { default: ComponentType }; @@ -183,7 +184,7 @@ function PreferencesPanel() { if (!cancelled) { showToastError( toolFailureSettingLoadFailedMessage, - err?.response?.data?.detail || err?.message, + extractErrorMessage(err, ''), ); } }) @@ -204,7 +205,7 @@ function PreferencesPanel() { await updateProductName(normalizedDisplayName || null); showToastSuccess(t('displayNameSaved')); } catch (err: any) { - showToastError(t('displayNameSaveFailed'), err?.response?.data?.detail || err?.message); + showToastError(t('displayNameSaveFailed'), extractErrorMessage(err, '')); } finally { setSavingDisplayName(false); } @@ -216,7 +217,7 @@ function PreferencesPanel() { await updateProductName(null); showToastSuccess(t('displayNameSaved')); } catch (err: any) { - showToastError(t('displayNameSaveFailed'), err?.response?.data?.detail || err?.message); + showToastError(t('displayNameSaveFailed'), extractErrorMessage(err, '')); } finally { setSavingDisplayName(false); } @@ -232,7 +233,7 @@ function PreferencesPanel() { await uploadProductFavicon(file); showToastSuccess(t('faviconSaved')); } catch (err: any) { - showToastError(t('faviconSaveFailed'), err?.response?.data?.detail || err?.message); + showToastError(t('faviconSaveFailed'), extractErrorMessage(err, '')); } finally { setSavingFavicon(false); } @@ -244,7 +245,7 @@ function PreferencesPanel() { await resetProductFavicon(); showToastSuccess(t('faviconSaved')); } catch (err: any) { - showToastError(t('faviconSaveFailed'), err?.response?.data?.detail || err?.message); + showToastError(t('faviconSaveFailed'), extractErrorMessage(err, '')); } finally { setSavingFavicon(false); } @@ -260,7 +261,7 @@ function PreferencesPanel() { } catch (err: any) { showToastError( t('toolFailureSettingSaveFailed'), - err?.response?.data?.detail || err?.message, + extractErrorMessage(err, ''), ); } finally { setSavingToolFailure(false); diff --git a/webui/src/pages/SystemLog/index.test.tsx b/webui/src/pages/SystemLog/index.test.tsx index a140c5b90..382e1d41d 100644 --- a/webui/src/pages/SystemLog/index.test.tsx +++ b/webui/src/pages/SystemLog/index.test.tsx @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { render, screen } from '@testing-library/react'; import SystemLogPage from './index'; +import { backendError } from '@/test/helpers'; const { logsAPI } = vi.hoisted(() => ({ logsAPI: { @@ -33,4 +34,11 @@ describe('SystemLogPage toolbar', () => { expect(screen.getByRole('combobox')).toHaveValue('2026-09-15/flocks.log'); expect(logsAPI.readLatest).toHaveBeenCalled(); }); + + it('says why the log could not be read instead of the bare status code', async () => { + logsAPI.readLatest.mockRejectedValue(backendError(403, '只有管理员可以查看系统日志')); + render(); + expect(await screen.findByText('只有管理员可以查看系统日志')).toBeInTheDocument(); + expect(screen.queryByText(/status code 403/)).not.toBeInTheDocument(); + }); }); diff --git a/webui/src/pages/SystemLog/index.tsx b/webui/src/pages/SystemLog/index.tsx index 9f574c466..6a784ccd2 100644 --- a/webui/src/pages/SystemLog/index.tsx +++ b/webui/src/pages/SystemLog/index.tsx @@ -3,6 +3,7 @@ import { RefreshCw, ChevronDown, ScrollText } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import PageHeader from '@/components/common/PageHeader'; import { logsAPI, type LogFileInfo, type LogContentResponse } from '@/api/logs'; +import { extractErrorMessage } from '@/utils/error'; export default function SystemLogPage() { const { t } = useTranslation('tool'); @@ -34,7 +35,7 @@ export default function SystemLogPage() { setLogContent(res.data); setSelectedFile(res.data?.filename || null); } catch (err: any) { - setError(err.response?.data?.detail || err.message || 'Failed to load logs'); + setError(extractErrorMessage(err, 'Failed to load logs')); setLogContent(null); } finally { setLoading(false); From 95069bab648fc43db34e9907ee444ee5a55b48b6 Mon Sep 17 00:00:00 2001 From: jamon Date: Thu, 12 Nov 2026 19:07:19 +0800 Subject: [PATCH 20/44] =?UTF-8?q?fix(webui):=20=E5=B7=A5=E5=85=B7=E5=92=8C?= =?UTF-8?q?=20MCP=20=E9=A1=B5=E7=9A=84=E5=A4=B1=E8=B4=A5=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=E6=98=BE=E7=A4=BA=E5=90=8E=E7=AB=AF=E5=8E=9F=E5=9B=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit API 服务和 MCP 服务的安装、连接、启停、删除、保存、测试连接, ThreatBook 两个配置面板的读取 / 保存 / 测试,以及新建 MCP 的测试连接, 失败时原来只弹 "Request failed with status code 4xx"。改用 extractErrorMessage,标题不变,没有任何信息时退回"未知错误"。 Tool/index.tsx 里 LegacyMCPTabContent / LegacyAPITabContent 的 11 处、 pages/MCP/index.tsx 和 AddMCPDialog.tsx 各 1 处目前没有引用或路由, 一并按同样写法改了,界面上没有入口可验证。 --- webui/src/pages/MCP/index.tsx | 3 +- webui/src/pages/Tool/ToolSheets.tsx | 2 +- .../Tool/components/APITabContent.test.tsx | 29 ++++++- .../pages/Tool/components/APITabContent.tsx | 14 ++-- .../pages/Tool/components/AddMCPDialog.tsx | 3 +- .../Tool/components/MCPTabContent.test.tsx | 36 ++++++++ .../pages/Tool/components/MCPTabContent.tsx | 10 +-- .../components/ServiceDetailPanel.test.tsx | 82 +++++++++++++++++++ .../Tool/components/ServiceDetailPanel.tsx | 7 +- .../components/ServiceDetailPanelApi.test.tsx | 22 +++++ .../components/ThreatBookAPIConfigPanel.tsx | 19 +++-- .../components/ThreatBookMCPConfigPanel.tsx | 19 +++-- webui/src/pages/Tool/index.tsx | 22 ++--- 13 files changed, 220 insertions(+), 48 deletions(-) diff --git a/webui/src/pages/MCP/index.tsx b/webui/src/pages/MCP/index.tsx index e5ca185da..17d0b492b 100644 --- a/webui/src/pages/MCP/index.tsx +++ b/webui/src/pages/MCP/index.tsx @@ -10,6 +10,7 @@ import EmptyState from '@/components/common/EmptyState'; import { mcpAPI, MCPServer } from '@/api/mcp'; import type { MCPCatalogEntry, MCPCatalogCategory } from '@/types'; import { getCatalogDescription } from '@/utils/mcpCatalog'; +import { extractErrorMessage } from '@/utils/error'; type TabType = 'servers' | 'catalog'; @@ -284,7 +285,7 @@ function CatalogTab() { alert(installMessage); } } catch (err: any) { - alert(`${t('catalog.installFailed')}: ${err.response?.data?.detail || err.message}`); + alert(`${t('catalog.installFailed')}: ${extractErrorMessage(err, '')}`); } finally { setInstalling(null); } diff --git a/webui/src/pages/Tool/ToolSheets.tsx b/webui/src/pages/Tool/ToolSheets.tsx index 7c49feff0..0589c1e63 100644 --- a/webui/src/pages/Tool/ToolSheets.tsx +++ b/webui/src/pages/Tool/ToolSheets.tsx @@ -620,7 +620,7 @@ export function MCPSheet({ onClose, onSaved, onRefresh }: MCPSheetProps) { setConnStatus('failed'); setTestResult({ success: false, - message: err.response?.data?.detail ?? err.message ?? t('detail.testFailed'), + message: extractErrorMessage(err, t('detail.testFailed')), }); } }; diff --git a/webui/src/pages/Tool/components/APITabContent.test.tsx b/webui/src/pages/Tool/components/APITabContent.test.tsx index be0dab94a..b20e9d983 100644 --- a/webui/src/pages/Tool/components/APITabContent.test.tsx +++ b/webui/src/pages/Tool/components/APITabContent.test.tsx @@ -3,6 +3,7 @@ import userEvent from '@testing-library/user-event'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import APITabContent from './APITabContent'; +import { backendError } from '@/test/helpers'; vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ user: { role: 'admin' } }) })); @@ -50,7 +51,10 @@ vi.mock('./ServiceDetailPanel', () => ({ vi.mock('react-i18next', () => ({ useTranslation: () => ({ - t: (key: string) => key, + // A failure alert carries its reason as the `error` value; show it so a test can read it. + t: (key: string, options?: Record) => ( + typeof options?.error === 'string' ? `${key}: ${options.error}` : key + ), i18n: { language: 'zh-CN' }, }), })); @@ -304,6 +308,29 @@ describe('APITabContent', () => { expect(providerAPI.updateApiService).toHaveBeenCalledExactlyOnceWith('service', { enabled: false }); }); + it('says why a service could not be switched off or removed instead of the bare status code', async () => { + const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {}); + const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true); + try { + providerAPI.listApiServices.mockResolvedValue({ data: [{ id: 'service', name: 'Native API', group: 'Ops', enabled: true, tool_count: 0 }] }); + providerAPI.updateApiService.mockRejectedValue(backendError(403, '只有管理员可以停用服务')); + providerAPI.deleteApiService.mockRejectedValue(backendError(409, '服务仍被工作流引用,不能删除')); + render(); + await screen.findByText('Native API'); + + fireEvent.click(screen.getByTitle('detail.disableServer')); + await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('只有管理员可以停用服务')); + + fireEvent.click(screen.getByTitle('button.delete')); + await waitFor(() => expect(alertSpy).toHaveBeenLastCalledWith('alert.deleteFailed: 服务仍被工作流引用,不能删除')); + expect(providerAPI.deleteApiService).toHaveBeenCalledWith('service'); + } finally { + alertSpy.mockRestore(); + confirmSpy.mockRestore(); + } + }); + it.each(['create', 'rename'])('rejects fresh native API name collisions before %s writes', async (operation) => { const service = { id: 'service__v1', name: 'Native API', group: 'Ops', enabled: true, tool_count: 0 }; providerAPI.listApiServices.mockResolvedValueOnce({ data: [service] }).mockResolvedValue({ data: [service, { ...service, id: 'other__v2', group: 'Existing' }] }); diff --git a/webui/src/pages/Tool/components/APITabContent.tsx b/webui/src/pages/Tool/components/APITabContent.tsx index a544439e1..819fc0736 100644 --- a/webui/src/pages/Tool/components/APITabContent.tsx +++ b/webui/src/pages/Tool/components/APITabContent.tsx @@ -228,7 +228,7 @@ export default function APITabContent({ onConfiguredChange(entryId); setCredModalEntry(null); } catch (err: any) { - alert(err.response?.data?.detail || err.message); + alert(extractErrorMessage(err, t('alert.unknownError'))); setInstalling(null); return; } @@ -242,7 +242,7 @@ export default function APITabContent({ alert(t('alert.mcpConfiguredDisabled', { name: entryName })); } } catch (err: any) { - alert(err.response?.data?.detail || err.message); + alert(extractErrorMessage(err, t('alert.unknownError'))); } finally { setInstalling(null); } @@ -257,7 +257,7 @@ export default function APITabContent({ shouldConnect = installRes.data?.config?.enabled !== false; onConfiguredChange(entry.id); } catch (err: any) { - alert(err.response?.data?.detail || err.message); + alert(extractErrorMessage(err, t('alert.unknownError'))); setInstalling(null); return; } @@ -271,7 +271,7 @@ export default function APITabContent({ alert(t('alert.mcpConfiguredDisabled', { name: entry.name })); } } catch (err: any) { - alert(err.response?.data?.detail || err.message); + alert(extractErrorMessage(err, t('alert.unknownError'))); } finally { setInstalling(null); } @@ -285,7 +285,7 @@ export default function APITabContent({ await onRefreshTools(); await fetchServices(); } catch (err: any) { - alert(err.response?.data?.detail || err.message); + alert(extractErrorMessage(err, t('alert.unknownError'))); } finally { setInstalling(null); } @@ -301,7 +301,7 @@ export default function APITabContent({ }); setServices((prev) => prev.map((s) => (s.id === serviceId ? res.data : s))); } catch (err: any) { - alert(err.response?.data?.detail || err.message); + alert(extractErrorMessage(err, t('alert.unknownError'))); } }; @@ -316,7 +316,7 @@ export default function APITabContent({ await onRefreshTools(); await fetchServices(); } catch (err: any) { - alert(t('alert.deleteFailed', { error: err.response?.data?.detail || err.message })); + alert(t('alert.deleteFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); } finally { setInstalling(null); } diff --git a/webui/src/pages/Tool/components/AddMCPDialog.tsx b/webui/src/pages/Tool/components/AddMCPDialog.tsx index 2251c5630..5a9c3f234 100644 --- a/webui/src/pages/Tool/components/AddMCPDialog.tsx +++ b/webui/src/pages/Tool/components/AddMCPDialog.tsx @@ -5,6 +5,7 @@ import { import { useTranslation } from 'react-i18next'; import client from '@/api/client'; import { useToast } from '@/components/common/Toast'; +import { extractErrorMessage } from '@/utils/error'; interface AddMCPDialogProps { onClose: () => void; @@ -51,7 +52,7 @@ export default function AddMCPDialog({ onClose, onSuccess, onSwitchToChat }: Add onClose(); onSuccess(); } catch (err: any) { - toast.error(t('alert.addFailed', { error: err.response?.data?.detail || err.message })); + toast.error(t('alert.addFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); } finally { setSubmitting(false); } diff --git a/webui/src/pages/Tool/components/MCPTabContent.test.tsx b/webui/src/pages/Tool/components/MCPTabContent.test.tsx index b0ea87561..6eba18586 100644 --- a/webui/src/pages/Tool/components/MCPTabContent.test.tsx +++ b/webui/src/pages/Tool/components/MCPTabContent.test.tsx @@ -3,6 +3,7 @@ import { fireEvent, render, screen, waitFor, within } from '@testing-library/rea import userEvent from '@testing-library/user-event'; import MCPTabContent from './MCPTabContent'; +import { backendError } from '@/test/helpers'; vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ user: { role: 'admin' } }) })); @@ -58,6 +59,8 @@ vi.mock('react-i18next', () => ({ if (key === 'credentials.enterField') { return `请输入 ${String(options?.field || '')}`; } + // A failure alert carries its reason as the `error` value; show it so a test can read it. + if (typeof options?.error === 'string') return `${key}: ${options.error}`; const translations: Record = { 'catalog.all': '全部', 'mcp.refreshStatus': '刷新状态', @@ -259,6 +262,39 @@ describe('MCPTabContent', () => { expect(mcpAPI.update).not.toHaveBeenCalled(); }); + it('says why a server could not be enabled instead of the bare status code', async () => { + mcpAPI.list.mockResolvedValue({ data: { native: { status: 'disabled', group: 'Ops', tools: [], resources: [] } } }); + mcpAPI.update.mockRejectedValue(backendError(403, '只有管理员可以启用 MCP 服务')); + render(); + await screen.findByText('native'); + + fireEvent.click(screen.getByRole('button', { name: 'detail.enableServer' })); + + await waitFor(() => expect(window.alert).toHaveBeenCalledWith('alert.saveFailed: 只有管理员可以启用 MCP 服务')); + expect(mcpAPI.update).toHaveBeenCalledWith('native', { enabled: true }); + }); + + it('says why a catalog entry could not be installed instead of the bare status code', async () => { + mcpAPI.catalogInstall.mockRejectedValue(backendError(400, 'MCP 服务地址不在允许的范围内')); + const onConfiguredChange = vi.fn(); + render(); + + fireEvent.click(await screen.findByRole('button', { name: '安装' })); + + await waitFor(() => expect(window.alert).toHaveBeenCalledWith('alert.configFailed: MCP 服务地址不在允许的范围内')); + expect(onConfiguredChange).not.toHaveBeenCalled(); + expect(mcpAPI.connect).not.toHaveBeenCalled(); + }); + it.each(['create', 'rename'])('rejects fresh native MCP name collisions before %s writes', async (operation) => { const server = { status: 'connected', group: 'Ops', tools: [], resources: [] }; mcpAPI.list.mockResolvedValueOnce({ data: { native: server } }).mockResolvedValue({ data: { native: server, new: { ...server, group: 'Existing' } } }); diff --git a/webui/src/pages/Tool/components/MCPTabContent.tsx b/webui/src/pages/Tool/components/MCPTabContent.tsx index cfad018e8..c36fca305 100644 --- a/webui/src/pages/Tool/components/MCPTabContent.tsx +++ b/webui/src/pages/Tool/components/MCPTabContent.tsx @@ -156,7 +156,7 @@ export default function MCPTabContent({ await fetchServers(); await onRefreshTools(); } catch (err: any) { - alert(t('alert.removeFailed', { error: err.response?.data?.detail ?? err.message })); + alert(t('alert.removeFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); } }; @@ -304,7 +304,7 @@ export default function MCPTabContent({ shouldConnect = installRes.data?.config?.enabled !== false; onConfiguredChange(entry.id); } catch (err: any) { - alert(t('alert.configFailed', { error: err.response?.data?.detail || err.message })); + alert(t('alert.configFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); setInstalling(null); return false; } @@ -319,7 +319,7 @@ export default function MCPTabContent({ alert(t('alert.mcpConfiguredDisabled', { name: entry.name })); } } catch (err: any) { - alert(t('alert.connectFailed', { error: err.response?.data?.detail || err.message })); + alert(t('alert.connectFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); } finally { setInstalling(null); } @@ -370,7 +370,7 @@ export default function MCPTabContent({ await fetchServers(); await onRefreshTools(); } catch (err: any) { - alert(t('alert.saveFailed', { error: err.response?.data?.detail || err.message })); + alert(t('alert.saveFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); } finally { setInstalling(null); } @@ -824,7 +824,7 @@ function MCPToolDetailPanel({ tool, onClose }: { tool: Tool; onClose: () => void const res = await toolAPI.test(tool.name, params); setTestResult({ success: true, data: res.data }); } catch (err: any) { - setTestResult({ success: false, error: err.response?.data?.detail ?? err.message }); + setTestResult({ success: false, error: extractErrorMessage(err, t('alert.unknownError')) }); } finally { setTesting(false); } diff --git a/webui/src/pages/Tool/components/ServiceDetailPanel.test.tsx b/webui/src/pages/Tool/components/ServiceDetailPanel.test.tsx index 9913e8c64..f03f8d3d8 100644 --- a/webui/src/pages/Tool/components/ServiceDetailPanel.test.tsx +++ b/webui/src/pages/Tool/components/ServiceDetailPanel.test.tsx @@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MCPServerDetailPanel } from './ServiceDetailPanel'; +import { backendError } from '@/test/helpers'; const { currentLanguage, mcpAPI } = vi.hoisted(() => ({ currentLanguage: { value: 'zh-CN' }, @@ -146,6 +147,8 @@ vi.mock('react-i18next', () => ({ 'detail.threatbookMcp.migrateToChina': isChinese ? '改为中国区配置' : 'Switch to China', 'alert.connectionOk': '连接成功', }; + // A failure alert carries its reason as the `error` value; show it so a test can read it. + if (typeof options?.error === 'string') return `${key}: ${options.error}`; return (translations[key] ?? key).replace('{{region}}', String(options?.region ?? '')); }, i18n: { @@ -287,6 +290,85 @@ describe('MCPServerDetailPanel', () => { expect(mcpAPI.testExisting).not.toHaveBeenCalled(); }); + function renderDemoPanel() { + render( + , + ); + } + + it('says why the connection test was refused instead of the bare status code', async () => { + const user = userEvent.setup(); + mcpAPI.testExisting.mockRejectedValue(backendError(400, 'MCP 服务地址不在允许的范围内')); + renderDemoPanel(); + + await screen.findByLabelText('service-url'); + await user.click(screen.getByRole('button', { name: 'trigger-test' })); + + expect(await screen.findByText('MCP 服务地址不在允许的范围内')).toBeInTheDocument(); + expect(screen.queryByText(/status code 400/)).not.toBeInTheDocument(); + }); + + it('says why the configuration could not be saved instead of the bare status code', async () => { + const user = userEvent.setup(); + const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {}); + try { + mcpAPI.update.mockRejectedValue(backendError(403, '只有管理员可以修改 MCP 配置')); + renderDemoPanel(); + + const urlInput = await screen.findByLabelText('service-url'); + await user.clear(urlInput); + await user.type(urlInput, 'https://saved.example.com/mcp'); + await user.click(screen.getByRole('button', { name: '保存' })); + + await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('alert.saveFailed: 只有管理员可以修改 MCP 配置')); + } finally { + alertSpy.mockRestore(); + } + }); + + it('says why the saved ThreatBook MCP key could not be shown', async () => { + const user = userEvent.setup(); + mcpAPI.get.mockResolvedValue({ + ...detailResponse, + data: { + ...detailResponse.data, + name: 'threatbook_mcp', + config: { type: 'sse', url: 'https://mcp.threatbook.cn/mcp?apikey={secret:threatbook_mcp_key}' }, + }, + }); + mcpAPI.getCredentials.mockResolvedValue({ + data: { has_credential: true, secret_id: 'threatbook_mcp_key', api_key_masked: '************' }, // secret-guard: allow (the name of a secret, not its value) + }); + mcpAPI.revealCredentials.mockRejectedValue(backendError(403, '只有管理员可以查看密钥')); + + render( + , + ); + + await user.click(await screen.findByRole('button', { name: '编辑配置' })); + await user.click(screen.getByTitle('显示')); + + expect(await screen.findByText('只有管理员可以查看密钥')).toBeInTheDocument(); + expect(screen.getByLabelText('API Key *')).toHaveValue('************'); + }); + it('shows the China free key link for ThreatBook MCP in Chinese', async () => { render( ({ providerAPI: { @@ -665,4 +666,25 @@ describe('APIServiceDetailPanel', () => { expect(providerAPI.testCredentials).not.toHaveBeenCalled(); }); }); + + it('says why the ThreatBook API key could not be saved instead of the bare status code', async () => { + const user = userEvent.setup(); + providerAPI.getServiceCredentials.mockResolvedValueOnce({ data: { has_credential: false } }); + providerAPI.configureServiceCredentials.mockRejectedValueOnce(backendError(400, 'API Key 格式不正确')); + + render( + , + ); + + await user.type(await screen.findByPlaceholderText('粘贴国际区 ThreatBook API Key'), 'bad-key'); + await user.click(screen.getByRole('button', { name: '保存并验证' })); + + expect(await screen.findByText('API Key 格式不正确')).toBeInTheDocument(); + expect(screen.queryByText(/status code 400/)).not.toBeInTheDocument(); + }); }); diff --git a/webui/src/pages/Tool/components/ThreatBookAPIConfigPanel.tsx b/webui/src/pages/Tool/components/ThreatBookAPIConfigPanel.tsx index f2531d0bd..f4e6728f0 100644 --- a/webui/src/pages/Tool/components/ThreatBookAPIConfigPanel.tsx +++ b/webui/src/pages/Tool/components/ThreatBookAPIConfigPanel.tsx @@ -16,6 +16,7 @@ import { type ThreatBookRegion, } from "@/constants/threatbook"; import type { ProviderCredentials } from "@/types"; +import { extractErrorMessage } from "@/utils/error"; interface Props { serviceName: string; @@ -101,10 +102,10 @@ export default function ThreatBookAPIConfigPanel({ } catch (error: any) { setResult({ success: false, - message: - error.response?.data?.detail || - error.message || + message: extractErrorMessage( + error, t("detail.threatbookApi.revealFailed"), + ), }); return; } finally { @@ -165,10 +166,10 @@ export default function ThreatBookAPIConfigPanel({ } catch (error: any) { setResult({ success: false, - message: - error.response?.data?.detail || - error.message || + message: extractErrorMessage( + error, t("detail.threatbookApi.saveFailed"), + ), }); onTestResult?.(serviceName, { status: "error" }); } finally { @@ -184,10 +185,10 @@ export default function ThreatBookAPIConfigPanel({ } catch (error: any) { setResult({ success: false, - message: - error.response?.data?.detail || - error.message || + message: extractErrorMessage( + error, t("detail.threatbookApi.testFailed"), + ), }); onTestResult?.(serviceName, { status: "error" }); } finally { diff --git a/webui/src/pages/Tool/components/ThreatBookMCPConfigPanel.tsx b/webui/src/pages/Tool/components/ThreatBookMCPConfigPanel.tsx index e50ea58d3..70baf78ca 100644 --- a/webui/src/pages/Tool/components/ThreatBookMCPConfigPanel.tsx +++ b/webui/src/pages/Tool/components/ThreatBookMCPConfigPanel.tsx @@ -16,6 +16,7 @@ import { THREATBOOK_REGION_CONFIG, } from "@/constants/threatbook"; import type { MCPCredentials, MCPServer } from "@/types"; +import { extractErrorMessage } from "@/utils/error"; interface Props { serverName: string; @@ -115,10 +116,10 @@ export default function ThreatBookMCPConfigPanel({ } catch (error: any) { setResult({ success: false, - message: - error.response?.data?.detail || - error.message || + message: extractErrorMessage( + error, t("detail.threatbookMcp.revealFailed"), + ), }); return; } finally { @@ -159,10 +160,10 @@ export default function ThreatBookMCPConfigPanel({ } catch (error: any) { setResult({ success: false, - message: - error.response?.data?.detail || - error.message || + message: extractErrorMessage( + error, t("detail.threatbookMcp.saveFailed"), + ), }); } finally { setSaving(false); @@ -182,10 +183,10 @@ export default function ThreatBookMCPConfigPanel({ } catch (error: any) { setResult({ success: false, - message: - error.response?.data?.detail || - error.message || + message: extractErrorMessage( + error, t("detail.threatbookMcp.testFailed"), + ), }); } finally { setTesting(false); diff --git a/webui/src/pages/Tool/index.tsx b/webui/src/pages/Tool/index.tsx index 71d6c8ea9..8d879ea69 100644 --- a/webui/src/pages/Tool/index.tsx +++ b/webui/src/pages/Tool/index.tsx @@ -1138,7 +1138,7 @@ function LegacyMCPTabContent({ await fetchServers(); onRefreshTools(); } catch (err: any) { - alert(t('alert.removeFailed', { error: err.response?.data?.detail ?? err.message })); + alert(t('alert.removeFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); } }; @@ -1246,7 +1246,7 @@ function LegacyMCPTabContent({ onConfiguredChange(entryId); setCredModalEntry(null); } catch (err: any) { - alert(t('alert.configFailed', { error: err.response?.data?.detail || err.message })); + alert(t('alert.configFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); setInstalling(null); return; } @@ -1260,7 +1260,7 @@ function LegacyMCPTabContent({ alert(t('alert.mcpConfiguredDisabled', { name: entryName })); } } catch (err: any) { - alert(t('alert.connectFailed', { error: err.response?.data?.detail || err.message })); + alert(t('alert.connectFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); } finally { setInstalling(null); } @@ -1276,7 +1276,7 @@ function LegacyMCPTabContent({ shouldConnect = installRes.data?.config?.enabled !== false; onConfiguredChange(entry.id); } catch (err: any) { - alert(t('alert.configFailed', { error: err.response?.data?.detail || err.message })); + alert(t('alert.configFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); setInstalling(null); return; } @@ -1290,7 +1290,7 @@ function LegacyMCPTabContent({ alert(t('alert.mcpConfiguredDisabled', { name: entry.name })); } } catch (err: any) { - alert(t('alert.connectFailed', { error: err.response?.data?.detail || err.message })); + alert(t('alert.connectFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); } finally { setInstalling(null); } @@ -1640,7 +1640,7 @@ function MCPServerDetailPanel({ } catch (err: any) { setTestResult({ success: false, - message: err.response?.data?.detail ?? err.message ?? t('detail.testFailed'), + message: extractErrorMessage(err, t('detail.testFailed')), }); } finally { setTestingConnection(false); @@ -1846,7 +1846,7 @@ function MCPToolDetailPanel({ tool, onClose }: { tool: Tool; onClose: () => void const res = await toolAPI.test(tool.name, params); setTestResult({ success: res.data.success, data: res.data.output, error: res.data.error }); } catch (err: any) { - setTestResult({ success: false, error: err.response?.data?.detail ?? err.message }); + setTestResult({ success: false, error: extractErrorMessage(err, t('alert.unknownError')) }); } finally { setTesting(false); } @@ -2370,7 +2370,7 @@ function LegacyAPITabContent({ onConfiguredChange(entryId); setCredModalEntry(null); } catch (err: any) { - alert(t('alert.configFailed', { error: err.response?.data?.detail || err.message })); + alert(t('alert.configFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); setInstalling(null); return; } @@ -2384,7 +2384,7 @@ function LegacyAPITabContent({ alert(t('alert.mcpConfiguredDisabled', { name: entryName })); } } catch (err: any) { - alert(t('alert.connectFailed', { error: err.response?.data?.detail || err.message })); + alert(t('alert.connectFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); } finally { setInstalling(null); } @@ -2400,7 +2400,7 @@ function LegacyAPITabContent({ shouldConnect = installRes.data?.config?.enabled !== false; onConfiguredChange(entry.id); } catch (err: any) { - alert(t('alert.configFailed', { error: err.response?.data?.detail || err.message })); + alert(t('alert.configFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); setInstalling(null); return; } @@ -2414,7 +2414,7 @@ function LegacyAPITabContent({ alert(t('alert.mcpConfiguredDisabled', { name: entry.name })); } } catch (err: any) { - alert(t('alert.connectFailed', { error: err.response?.data?.detail || err.message })); + alert(t('alert.connectFailed', { error: extractErrorMessage(err, t('alert.unknownError')) })); } finally { setInstalling(null); } From 463c14f4840825b6b4fe0c8f16aaa6ec02d4aa62 Mon Sep 17 00:00:00 2001 From: jamon Date: Thu, 12 Nov 2026 19:07:19 +0800 Subject: [PATCH 21/44] =?UTF-8?q?fix(webui):=20=E6=A8=A1=E5=9E=8B=E3=80=81?= =?UTF-8?q?=E9=80=9A=E9=81=93=E3=80=81Agent=20=E5=92=8C=E8=AE=BE=E5=A4=87?= =?UTF-8?q?=E6=8E=A5=E5=85=A5=E9=A1=B5=E7=9A=84=E5=A4=B1=E8=B4=A5=E6=8F=90?= =?UTF-8?q?=E7=A4=BA=E6=98=BE=E7=A4=BA=E5=90=8E=E7=AB=AF=E5=8E=9F=E5=9B=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Model:手动添加模型被拒绝时提示后端原因;添加后的连通性检查在后端 没给原因时仍显示 "Request failed" - Channel:Telegram 配对、WhatsApp 配对、微信扫码登录 - Agent:委派开关和编辑保存(AgentFormDialogs.tsx 目前没有引用,一并改了) - DeviceIntegration:errDetail 原来只认 detail,机房分组和设备模板 安装 / 更新失败时永远只显示兜底文案;现在能读到后端原因,没有原因时 仍是原来的文案 --- webui/src/pages/Agent/AgentFormDialogs.tsx | 3 +- webui/src/pages/Agent/AgentSheet.test.tsx | 23 ++++++++- webui/src/pages/Agent/AgentSheet.tsx | 3 +- webui/src/pages/Agent/index.test.tsx | 22 ++++++++- webui/src/pages/Agent/index.tsx | 3 +- webui/src/pages/Channel/index.test.tsx | 49 +++++++++++++++++++ webui/src/pages/Channel/index.tsx | 6 +-- .../pages/DeviceIntegration/index.test.tsx | 34 +++++++++++++ webui/src/pages/DeviceIntegration/index.tsx | 5 +- webui/src/pages/Model/index.test.tsx | 33 ++++++++++++- webui/src/pages/Model/index.tsx | 11 ++--- 11 files changed, 173 insertions(+), 19 deletions(-) diff --git a/webui/src/pages/Agent/AgentFormDialogs.tsx b/webui/src/pages/Agent/AgentFormDialogs.tsx index ccfdd8ccc..0abb6926c 100644 --- a/webui/src/pages/Agent/AgentFormDialogs.tsx +++ b/webui/src/pages/Agent/AgentFormDialogs.tsx @@ -1,6 +1,7 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; import { agentAPI, Agent } from '@/api/agent'; +import { extractErrorMessage } from '@/utils/error'; // ============================================================================ // Create Agent Dialog @@ -107,7 +108,7 @@ export function EditAgentDialog({ // onClose is called by the parent via onUpdated → setEditingAgent(null); // calling it here again would set state on an already-unmounted component. } catch (err: any) { - alert(t('agent:error.updateFailed', { detail: err.response?.data?.detail ?? err.message })); + alert(t('agent:error.updateFailed', { detail: extractErrorMessage(err, '') })); } finally { setLoading(false); } diff --git a/webui/src/pages/Agent/AgentSheet.test.tsx b/webui/src/pages/Agent/AgentSheet.test.tsx index 8c53b7e91..ef2531064 100644 --- a/webui/src/pages/Agent/AgentSheet.test.tsx +++ b/webui/src/pages/Agent/AgentSheet.test.tsx @@ -1,8 +1,9 @@ -import { render } from '@testing-library/react'; +import { act, render } from '@testing-library/react'; import { describe, expect, it, vi, beforeEach } from 'vitest'; import AgentSheet from './AgentSheet'; -import type { Agent } from '@/api/agent'; +import { agentAPI, type Agent } from '@/api/agent'; +import { backendError } from '@/test/helpers'; const { capturedEntitySheetProps, @@ -134,6 +135,8 @@ vi.mock('react-i18next', () => ({ 'common:entity.defaultTestPrompt': '你好,请介绍一下你自己以及你的主要功能。', 'sheet.done': '完成', }; + // A failure alert carries its reason as the `detail` value; show it so a test can read it. + if (typeof params?.detail === 'string') return `${key}: ${params.detail}`; const fallback = params?.defaultValue; return translations[key] ?? (typeof fallback === 'string' ? fallback : key); }, @@ -284,4 +287,20 @@ describe('AgentSheet', () => { expect(props.rexSystemContext).toContain('不要建议提取或覆盖这些字段'); expect(props.rexWelcomeMessage).toContain('当前只支持保存模型和温度'); }); + + it('says why an agent could not be saved instead of the bare status code', async () => { + const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {}); + try { + vi.mocked(agentAPI.update).mockRejectedValueOnce(backendError(403, '该 Agent 的提示词受保护,不能修改')); + const onSaved = vi.fn(); + render(); + + await act(async () => { await capturedEntitySheetProps.at(-1).onSubmit(); }); + + expect(alertSpy).toHaveBeenCalledWith('error.updateFailed: 该 Agent 的提示词受保护,不能修改'); + expect(onSaved).not.toHaveBeenCalled(); + } finally { + alertSpy.mockRestore(); + } + }); }); diff --git a/webui/src/pages/Agent/AgentSheet.tsx b/webui/src/pages/Agent/AgentSheet.tsx index 14ce447a6..fb9f7e6ec 100644 --- a/webui/src/pages/Agent/AgentSheet.tsx +++ b/webui/src/pages/Agent/AgentSheet.tsx @@ -22,6 +22,7 @@ import { providerAPI, defaultModelAPI, modelV2API } from '@/api/provider'; import { toolAPI, Tool } from '@/api/tool'; import { skillAPI, Skill } from '@/api/skill'; import type { ModelDefinitionV2 } from '@/types'; +import { extractErrorMessage } from '@/utils/error'; interface AvailableModel { providerID: string; @@ -208,7 +209,7 @@ export default function AgentSheet({ agent, onClose, onSaved }: AgentSheetProps) onSaved(); onClose(); } catch (err: any) { - alert(t('error.updateFailed', { detail: err.response?.data?.detail ?? err.message })); + alert(t('error.updateFailed', { detail: extractErrorMessage(err, '') })); } finally { setLoading(false); } diff --git a/webui/src/pages/Agent/index.test.tsx b/webui/src/pages/Agent/index.test.tsx index 23b33cb3a..b294642bd 100644 --- a/webui/src/pages/Agent/index.test.tsx +++ b/webui/src/pages/Agent/index.test.tsx @@ -4,6 +4,7 @@ import { act, fireEvent, render, screen, waitFor, within } from '@testing-librar import userEvent from '@testing-library/user-event'; import { __resetAgentsResourceForTesting } from '@/hooks/useAgents'; import AgentPage from './index'; +import { backendError } from '@/test/helpers'; const { listMock, refreshMock, deleteMock, setDelegatableMock } = vi.hoisted(() => ({ listMock: vi.fn(), @@ -14,7 +15,8 @@ const { listMock, refreshMock, deleteMock, setDelegatableMock } = vi.hoisted(() vi.mock('react-i18next', () => ({ useTranslation: () => ({ - t: (key: string) => ({ + // A failure alert carries its reason as the `detail` value; show it so a test can read it. + t: (key: string, options?: Record) => (typeof options?.detail === 'string' ? `${key}: ${options.detail}` : undefined) ?? ({ pageTitle: 'AI Agents', pageDescription: '管理和配置 AI Agent', totalCount: '共 2 个 Agent', @@ -166,6 +168,24 @@ describe('AgentPage protected prompts', () => { }); }); +describe('AgentPage delegation switch', () => { + it('says why delegation could not be changed instead of the bare status code', async () => { + const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {}); + try { + listMock.mockResolvedValue({ data: [makeAgent({ name: 'open-sub', mode: 'subagent', delegatable: false })] }); + setDelegatableMock.mockRejectedValue(backendError(403, '只有管理员可以修改委派设置')); + render(); + + fireEvent.click(within(await screen.findByTestId('agent-card-open-sub')).getByRole('switch')); + + await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('error.updateFailed: 只有管理员可以修改委派设置')); + expect(setDelegatableMock).toHaveBeenCalledWith('open-sub', true); + } finally { + alertSpy.mockRestore(); + } + }); +}); + describe('AgentPage cards', () => { it('使用与工作流卡片一致的纯色扁平样式', async () => { listMock.mockResolvedValue({ diff --git a/webui/src/pages/Agent/index.tsx b/webui/src/pages/Agent/index.tsx index b941c8d28..46932d4cf 100644 --- a/webui/src/pages/Agent/index.tsx +++ b/webui/src/pages/Agent/index.tsx @@ -18,6 +18,7 @@ import GroupNav, { useGroupDrag, type GroupDrag } from '@/components/plugin-grou import { deriveGroupNav, matchesGroup, saveGroupItems, type GroupSelection } from '@/components/plugin-groups/groupView'; import PluginViewToggle from '@/components/plugin-groups/PluginViewToggle'; import { usePluginViewMode, type PluginViewMode } from '@/hooks/usePluginViewMode'; +import { extractErrorMessage } from '@/utils/error'; // ============================================================================ // Main Page Component @@ -104,7 +105,7 @@ export default function AgentPage() { } await refetch(false); } catch (err: any) { - alert(t('error.updateFailed', { detail: err.response?.data?.detail ?? err.message })); + alert(t('error.updateFailed', { detail: extractErrorMessage(err, '') })); } finally { setTogglingAgents((prev) => ({ ...prev, [agent.name]: false })); } diff --git a/webui/src/pages/Channel/index.test.tsx b/webui/src/pages/Channel/index.test.tsx index c620e7b86..b46754330 100644 --- a/webui/src/pages/Channel/index.test.tsx +++ b/webui/src/pages/Channel/index.test.tsx @@ -3,6 +3,7 @@ import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import ChannelPage from './index'; +import { backendError } from '@/test/helpers'; const { client, toast, useAgents } = vi.hoisted(() => ({ client: { @@ -424,6 +425,54 @@ describe('ChannelPage error surfacing', () => { }); }); +describe('ChannelPage pairing failures', () => { + const capabilities = { chat_types: ['direct'], media: true, threads: false, reactions: false, edit: false, rich_text: false }; + + function serveChannel(id: string, saved: Record) { + client.get.mockImplementation((url: string) => { + if (url === '/api/channel/list') { + return Promise.resolve({ data: [{ id, label: id, aliases: [], capabilities, running: false }] }); + } + if (url === '/api/config') return Promise.resolve({ data: { channels: { [id]: saved } } }); + if (url === '/api/channel/status') return Promise.resolve({ data: {} }); + return Promise.reject(new Error(`Unexpected GET ${url}`)); + }); + } + + beforeEach(() => { + vi.clearAllMocks(); + useAgents.mockReturnValue({ agents: [] }); + client.patch.mockResolvedValue({ data: {} }); + }); + + it('says why a Telegram pairing code was refused', async () => { + serveChannel('telegram', { enabled: true, botToken: 'token', allowFrom: ['1001'] }); + client.post.mockRejectedValue(backendError(400, '配对码无效或已过期')); + const user = userEvent.setup(); + render(); + + await user.type(await screen.findByPlaceholderText('telegram.pairingCodePlaceholder'), 'abc123'); + await user.click(screen.getByRole('button', { name: 'telegram.pairingButton' })); + + await waitFor(() => { + expect(toast.error).toHaveBeenCalledWith('telegram.pairingError', '配对码无效或已过期'); + }); + expect(client.post).toHaveBeenCalledWith('/api/channel/telegram/pair', { code: 'ABC123' }); + }); + + it('says why the Weixin QR login could not start', async () => { + serveChannel('weixin', { enabled: true }); + client.post.mockRejectedValue(backendError(502, '无法连接微信 iLink 服务')); + const user = userEvent.setup(); + render(); + + await user.click(await screen.findByRole('button', { name: /weixin.qrLoginButton/ })); + + expect(await screen.findByText('无法连接微信 iLink 服务')).toBeInTheDocument(); + expect(screen.queryByText(/status code 502/)).not.toBeInTheDocument(); + }); +}); + describe('ChannelPage feishu transport badge', () => { const list = [{ id: 'feishu', label: 'Feishu', aliases: [], diff --git a/webui/src/pages/Channel/index.tsx b/webui/src/pages/Channel/index.tsx index e5cac6907..86001d967 100644 --- a/webui/src/pages/Channel/index.tsx +++ b/webui/src/pages/Channel/index.tsx @@ -1818,7 +1818,7 @@ function TelegramPanel({ config, agentOptions, onChange, onRefresh }: TelegramPa setPairingState('done'); setTimeout(() => setPairingState('idle'), 3000); } catch (err: any) { - const detail = err?.response?.data?.detail ?? err?.message ?? ''; + const detail = extractErrorMessage(err, ''); toast.error(t('telegram.pairingError'), detail); setPairingState('idle'); } @@ -2575,7 +2575,7 @@ function WhatsAppPanel({ config, onChange, onPairSuccess }: WhatsAppPanelProps) } }, 1500); } catch (err: any) { - const detail = err?.response?.data?.detail ?? err?.message ?? ''; + const detail = extractErrorMessage(err, ''); setQrError(detail); setQrPhase('error'); } @@ -2937,7 +2937,7 @@ function WeixinPanel({ config, agentOptions, onChange, onQrLoginSuccess }: Weixi } }, 2000); } catch (err: any) { - const detail = err?.response?.data?.detail ?? err?.message ?? ''; + const detail = extractErrorMessage(err, ''); setQrError(detail); setQrPhase('error'); } diff --git a/webui/src/pages/DeviceIntegration/index.test.tsx b/webui/src/pages/DeviceIntegration/index.test.tsx index 6c0438440..426e51b4a 100644 --- a/webui/src/pages/DeviceIntegration/index.test.tsx +++ b/webui/src/pages/DeviceIntegration/index.test.tsx @@ -5,6 +5,7 @@ import userEvent from '@testing-library/user-event'; import { PaneActiveContext } from '@/components/layout/PaneActiveContext'; import DeviceIntegrationPage from './index'; +import { backendError } from '@/test/helpers'; const mocks = vi.hoisted(() => ({ toastSuccess: vi.fn(), @@ -1019,6 +1020,39 @@ describe('DeviceIntegrationPage', () => { expect(mocks.createAndSend.mock.calls[0][0].text).toContain('storage_key=onesig_v2_5_3_D20250710_api_v2_5_3_D20250710'); }); + it.each([ + ['the reason the service gave', backendError(403, '「onesig」需要单独授权后才能安装'), '「onesig」需要单独授权后才能安装'], + // No reason in the answer: its own wording, never the transport's "Network Error". + ['its own wording when the service gave none', new Error('Network Error'), '设备模板「onesig」安装失败'], + // The catch-all fault only says that it failed; the page's own wording says what did. + ['its own wording when the service only says it failed', Object.assign(new Error('Request failed with status code 500'), { + response: { status: 500, data: { error: 'InternalServerError', message: 'Internal server error' } }, + }), '设备模板「onesig」安装失败'], + ])('reports a failed template install with %s', async (_name, error, expected) => { + const user = userEvent.setup(); + mocks.listTemplates.mockResolvedValue({ + data: [buildTemplate({ + plugin_id: 'onesig_v2_5_3_D20250710', + storage_key: 'onesig_v2_5_3_D20250710_api_v2_5_3_D20250710', + service_id: 'onesig_v2_5_3_D20250710_api', + name: 'onesig', + version: '2.5.3 D20250710', + installed: false, + state: 'available', + })], + }); + mocks.hubInstall.mockRejectedValue(error); + + render(); + + await openSupportedDeviceList(user); + await user.click(screen.getByText('微步')); + await user.click(screen.getByText('onesig')); + + await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith(expected)); + expect(mocks.createAndSend).not.toHaveBeenCalled(); + }); + it('sends api guidance directly to Rex without opening a custom form', async () => { const user = userEvent.setup(); render(); diff --git a/webui/src/pages/DeviceIntegration/index.tsx b/webui/src/pages/DeviceIntegration/index.tsx index 24e4a7465..1af6549ff 100644 --- a/webui/src/pages/DeviceIntegration/index.tsx +++ b/webui/src/pages/DeviceIntegration/index.tsx @@ -26,6 +26,7 @@ import PluginGroupButton from '@/components/plugin-groups/PluginGroupButton'; import { deriveGroupNav, matchesGroup, saveGroupItems, type GroupSelection } from '@/components/plugin-groups/groupView'; import { usePluginViewMode, type PluginViewMode } from '@/hooks/usePluginViewMode'; import PluginViewToggle from '@/components/plugin-groups/PluginViewToggle'; +import { extractServerMessage } from '@/utils/error'; // ============================================================================ // Constants @@ -47,9 +48,7 @@ function SessionChatFallback() { /** Pull the backend's human-readable error detail (e.g. "机房名称已存在") * out of an axios error, falling back to a generic message. */ function errDetail(err: unknown, fallback: string): string { - return ( - (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail || fallback - ); + return extractServerMessage(err) || fallback; } // ============================================================================ diff --git a/webui/src/pages/Model/index.test.tsx b/webui/src/pages/Model/index.test.tsx index be5fd98ae..dfb162276 100644 --- a/webui/src/pages/Model/index.test.tsx +++ b/webui/src/pages/Model/index.test.tsx @@ -4,7 +4,7 @@ import userEvent from '@testing-library/user-event'; import { vi } from 'vitest'; import ModelPage from './index'; -import { renderWithRouter } from '@/test/helpers'; +import { backendError, renderWithRouter } from '@/test/helpers'; const mocks = vi.hoisted(() => ({ toast: { @@ -740,6 +740,37 @@ describe('ModelPage configure provider dialog', () => { expect(sheet.getByText('form.modelId')).toBeVisible(); expect(mocks.setCredentials).not.toHaveBeenCalled(); }); + + async function submitHandTypedModel(user: ReturnType) { + renderWithRouter(); + const sheet = await openAddModelDialog(user); + await user.click(sheet.getByRole('tab', { name: 'discovery.manual' })); + await user.type(sheet.getByPlaceholderText('model-id'), 'dup-model'); + await user.type(sheet.getByPlaceholderText('model-name'), 'Dup Model'); + await user.click(sheet.getByRole('button', { name: 'form.addModelBtn' })); + return sheet; + } + + it('says why a hand-typed model was refused instead of the bare status code', async () => { + mocks.createDefinition.mockRejectedValue(backendError(409, '模型 dup-model 已存在')); + const user = userEvent.setup(); await submitHandTypedModel(user); + await waitFor(() => expect(mocks.toast.error).toHaveBeenCalledWith('operationFailed', '模型 dup-model 已存在')); + }); + + it('says why the check of a hand-typed model failed, and keeps its own wording when the service gives no reason', async () => { + mocks.createDefinition.mockResolvedValue({ data: { id: 'dup-model' } }); + mocks.testCredentials.mockRejectedValue(backendError(502, '上游模型服务拒绝了这个模型')); + const user = userEvent.setup(); const sheet = await submitHandTypedModel(user); + expect(await sheet.findByText('上游模型服务拒绝了这个模型')).toBeInTheDocument(); + }); + + it('does not show the transport error for a failed check the service gave no reason for', async () => { + mocks.createDefinition.mockResolvedValue({ data: { id: 'dup-model' } }); + mocks.testCredentials.mockRejectedValue(new Error('Network Error')); + const user = userEvent.setup(); const sheet = await submitHandTypedModel(user); + expect(await sheet.findByText('Request failed')).toBeInTheDocument(); + expect(sheet.queryByText('Network Error')).not.toBeInTheDocument(); + }); }); describe('ModelPage member access', () => { diff --git a/webui/src/pages/Model/index.tsx b/webui/src/pages/Model/index.tsx index 5938cb6d6..12d9ef41a 100644 --- a/webui/src/pages/Model/index.tsx +++ b/webui/src/pages/Model/index.tsx @@ -29,7 +29,7 @@ import ProviderCatalogPicker from './ProviderCatalogPicker'; import ModelDiscovery, { ModelImportSummary, toModelImport } from './ModelDiscovery'; import TokenUsageCard from './TokenUsageCard'; import { formatPricePerMillion, formatPricingPerMillion, formatPricingTierRange, isPricingFree } from '@/utils/modelPricing'; -import { extractErrorMessage } from '@/utils/error'; +import { extractErrorMessage, extractServerMessage } from '@/utils/error'; import { convertCurrencyAmount, getConvertedTotalCost, @@ -1543,12 +1543,12 @@ function AddProviderDialog({ connectedIds, onClose, onAdded }: { latency: res.data.latency_ms, }); } catch (err: any) { - setModelTestResult({ success: false, message: err.response?.data?.detail || 'Request failed' }); + setModelTestResult({ success: false, message: extractServerMessage(err) || 'Request failed' }); } finally { setModelTesting(false); } } catch (err: any) { - toast.error(t('operationFailed'), err.response?.data?.detail || err.message); + toast.error(t('operationFailed'), extractErrorMessage(err, '')); } finally { setAddingModel(false); } @@ -2149,13 +2149,12 @@ function AddModelDialog({ provider, models, loadingModels, onClose, onCreated, i latency: res.data.latency_ms, }); } catch (err: any) { - setTestResult({ success: false, message: err.response?.data?.detail || 'Request failed' }); + setTestResult({ success: false, message: extractServerMessage(err) || 'Request failed' }); } finally { setTesting(false); } } catch (err: any) { - const detail = err.response?.data?.detail || err.message; - toast.error(t('operationFailed'), detail); + toast.error(t('operationFailed'), extractErrorMessage(err, '')); } finally { setLoading(false); } From fb352c28fbf095c58cd619bb74335b29b5a51d70 Mon Sep 17 00:00:00 2001 From: jamon Date: Thu, 12 Nov 2026 19:07:19 +0800 Subject: [PATCH 22/44] =?UTF-8?q?fix(webui):=20=E5=B7=A5=E4=BD=9C=E6=B5=81?= =?UTF-8?q?=E8=8A=82=E7=82=B9=E4=BF=9D=E5=AD=98=E5=92=8C=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E8=BF=90=E8=A1=8C=E7=9A=84=E5=A4=B1=E8=B4=A5=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=E6=98=BE=E7=A4=BA=E5=90=8E=E7=AB=AF=E5=8E=9F=E5=9B=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NodeInfoPanel 的单节点执行、保存节点,RunTab 的测试运行,失败时原来 只显示 axios 的状态码那句话。改用 extractErrorMessage。保存节点可能 碰到部署统一管理的工作流,那个 403 是后端唯一真的回 detail 的地方, 两种形状各有一条用例。 RunTab 的用例断言的是回调里的 errorMessage:运行被拒绝后历史列表会 重新加载并把这条没有 id 的执行记录换掉,原因在页面上留不住。这是原有 问题,这里没有动。 --- .../WorkflowDetail/NodeInfoPanel.test.tsx | 43 +++++++++++++++++++ .../pages/WorkflowDetail/NodeInfoPanel.tsx | 5 ++- .../pages/WorkflowDetail/tabs/RunTab.test.tsx | 19 ++++++++ .../src/pages/WorkflowDetail/tabs/RunTab.tsx | 2 +- 4 files changed, 66 insertions(+), 3 deletions(-) diff --git a/webui/src/pages/WorkflowDetail/NodeInfoPanel.test.tsx b/webui/src/pages/WorkflowDetail/NodeInfoPanel.test.tsx index ee9b36df4..7eed8d0a2 100644 --- a/webui/src/pages/WorkflowDetail/NodeInfoPanel.test.tsx +++ b/webui/src/pages/WorkflowDetail/NodeInfoPanel.test.tsx @@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { render, screen, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import NodeInfoPanel from './NodeInfoPanel'; +import { backendError } from '@/test/helpers'; const { workflowAPI } = vi.hoisted(() => ({ workflowAPI: { @@ -318,6 +319,48 @@ describe('NodeInfoPanel', () => { expect(screen.getByText(/done/)).toBeInTheDocument(); }); + function renderNode() { + render( + {}} + onSaved={() => {}} + /> + ); + } + + it('says why a single node run was refused instead of the bare status code', async () => { + const user = userEvent.setup(); + workflowAPI.runNode.mockRejectedValue(backendError(409, '工作流正在运行,不能单独执行节点')); + renderNode(); + + await user.click(screen.getByRole('button', { name: '执行节点' })); + + expect(await screen.findByText('工作流正在运行,不能单独执行节点')).toBeInTheDocument(); + expect(screen.queryByText(/status code 409/)).not.toBeInTheDocument(); + }); + + it.each([ + ['the route refuses the save', backendError(403, '只有管理员可以修改工作流')], + // The one answer of the service that does carry `detail`: a write to a workflow the + // deployment manages (managed_workflow_read_only_handler in flocks/server/app.py). + ['the workflow is managed by the deployment', Object.assign(new Error('Request failed with status code 403'), { + response: { status: 403, data: { detail: '该工作流由部署统一管理,不能修改' } }, + })], + ])('says why a node could not be saved when %s', async (_name, error) => { + const user = userEvent.setup(); + workflowAPI.update.mockRejectedValue(error); + renderNode(); + + await user.click(screen.getByRole('button', { name: '保存节点' })); + + const reason = (error as unknown as { response: { data: { detail?: string; message?: string } } }).response.data; + expect(await screen.findByText(reason.detail ?? reason.message ?? '')).toBeInTheDocument(); + expect(screen.queryByText(/status code 403/)).not.toBeInTheDocument(); + }); + it('opens the expanded code editor and keeps code in sync', async () => { const user = userEvent.setup(); diff --git a/webui/src/pages/WorkflowDetail/NodeInfoPanel.tsx b/webui/src/pages/WorkflowDetail/NodeInfoPanel.tsx index 8a3e6ff64..8f40d8632 100644 --- a/webui/src/pages/WorkflowDetail/NodeInfoPanel.tsx +++ b/webui/src/pages/WorkflowDetail/NodeInfoPanel.tsx @@ -16,6 +16,7 @@ import { } from '@/api/workflow'; import CopyButton from '@/components/common/CopyButton'; import { getWorkflowDisplayName } from '@/utils/workflowDisplay'; +import { extractErrorMessage } from '@/utils/error'; // ───────────────────────────────────────────── // Constants @@ -452,7 +453,7 @@ function NodeRunSection({ node_id: node.id, outputs: {}, stdout: '', - error: error?.response?.data?.detail || error?.message || t('detail.nodeInfo.runNodeFailed'), + error: extractErrorMessage(error, t('detail.nodeInfo.runNodeFailed')), success: false, }); } finally { @@ -638,7 +639,7 @@ export default function NodeInfoPanel({ node, workflow, latestExecution, width = setSavedOk(true); onSaved(res.data); setTimeout(() => setSavedOk(false), 2500); } catch (e: any) { - setSaveErr(e?.response?.data?.detail || e?.message || t('detail.nodeInfo.saveFailed')); + setSaveErr(extractErrorMessage(e, t('detail.nodeInfo.saveFailed'))); } finally { setSaving(false); } diff --git a/webui/src/pages/WorkflowDetail/tabs/RunTab.test.tsx b/webui/src/pages/WorkflowDetail/tabs/RunTab.test.tsx index dff4bafff..492469b37 100644 --- a/webui/src/pages/WorkflowDetail/tabs/RunTab.test.tsx +++ b/webui/src/pages/WorkflowDetail/tabs/RunTab.test.tsx @@ -4,6 +4,7 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import RunTab from './RunTab'; import type { WorkflowExecution } from '@/api/workflow'; +import { backendError } from '@/test/helpers'; const { workflowAPI } = vi.hoisted(() => ({ workflowAPI: { @@ -248,6 +249,24 @@ describe('RunTab', () => { }); }); + it('says why a test run was refused instead of the bare status code', async () => { + const user = userEvent.setup(); + const onLatestExecutionChange = vi.fn(); + workflowAPI.run.mockRejectedValue(backendError(409, 'Only one syslog trigger is supported per workflow')); + + render(); + + fireEvent.change(screen.getAllByRole('textbox')[0], { target: { value: '{"topic":"saved"}' } }); + await user.click(screen.getByRole('button', { name: '测试运行' })); + + // Asserted on what the tab reports rather than on the page: the history list reloads right + // after and replaces an execution that has no id, so the line does not stay on screen. + await waitFor(() => expect(onLatestExecutionChange).toHaveBeenCalledWith(expect.objectContaining({ + status: 'error', + errorMessage: 'Only one syslog trigger is supported per workflow', + }))); + }); + it('shows a copy button when output results are available', async () => { render( Date: Thu, 12 Nov 2026 19:07:19 +0800 Subject: [PATCH 23/44] =?UTF-8?q?fix(hub):=20=E5=A5=97=E4=BB=B6=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E7=9A=84=E7=A1=AE=E8=AE=A4=E8=BF=87=E6=9C=9F=E6=97=B6?= =?UTF-8?q?=E5=86=8D=E5=BC=B9=E4=B8=80=E6=AC=A1=E7=A1=AE=E8=AE=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新确认之后文件又有变化时,后端回 409 并带上新的更新计划: HTTPException(detail={"code": "hub_update_confirmation_required", "plan": ...})。 经过 http_exception_handler 之后计划在 data.message 里, useProtectedHubUpdate 读的是 data.detail,永远拿不到,于是不再弹确认, 只提示 "Request failed with status code 409",更新走不下去。原来的用例 mock 的是后端不会发的 {detail: {...}} 形状,所以一直是绿的。 - useProtectedHubUpdate 改读 data.message,兼容 data.detail - installStream 在流开始前被拒绝时原来只认 detail,显示成 "HTTP 403", 改用 extractServerMessage --- webui/src/api/hub.test.ts | 16 ++++++++++++++++ webui/src/api/hub.ts | 5 +++-- .../hub/useProtectedHubUpdate.test.tsx | 16 ++++++++++++---- .../src/components/hub/useProtectedHubUpdate.tsx | 7 +++++-- 4 files changed, 36 insertions(+), 8 deletions(-) diff --git a/webui/src/api/hub.test.ts b/webui/src/api/hub.test.ts index 57a1e5e11..67e9e39b1 100644 --- a/webui/src/api/hub.test.ts +++ b/webui/src/api/hub.test.ts @@ -54,6 +54,22 @@ describe('hubAPI.installStream', () => { .rejects.toThrow('该套件需要授权后才能安装'); }); + it.each([ + // The service's exception handler puts the route's `detail` under `message`; there is no `detail`. + ['a refusal', 403, '该套件需要授权后才能安装', '该套件需要授权后才能安装'], + ['a structured refusal', 409, { code: 'hub_guided_install', message: '该插件通过 Rex 会话安装' }, '该插件通过 Rex 会话安装'], + ])('says why the service rejected an install before streaming: %s', async (_name, status, message, expected) => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ + ok: false, + status, + json: async () => ({ error: 'HTTPException', message }), + })); + + const { hubAPI } = await import('./hub'); + + await expect(hubAPI.installStream('component', 'pro-scene', vi.fn())).rejects.toThrow(expected); + }); + it('falls back to the HTTP status for a non-JSON error response', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, diff --git a/webui/src/api/hub.ts b/webui/src/api/hub.ts index 43dacefaf..5db0b669e 100644 --- a/webui/src/api/hub.ts +++ b/webui/src/api/hub.ts @@ -1,4 +1,5 @@ import client, { getApiBase } from './client'; +import { extractServerMessage } from '@/utils/error'; export type HubPluginType = 'skill' | 'agent' | 'tool' | 'device' | 'workflow' | 'webui' | 'component'; export type HubPluginState = @@ -233,8 +234,8 @@ export const hubAPI = { }) .then(async (res) => { if (!res.ok || !res.body) { - const payload = await res.json().catch(() => null) as { detail?: unknown } | null; - reject(new Error(typeof payload?.detail === 'string' ? payload.detail : `HTTP ${res.status}`)); + const payload: unknown = await res.json().catch(() => null); + reject(new Error(extractServerMessage({ response: { data: payload } }) ?? `HTTP ${res.status}`)); return; } diff --git a/webui/src/components/hub/useProtectedHubUpdate.test.tsx b/webui/src/components/hub/useProtectedHubUpdate.test.tsx index 538a99e6b..c646ed854 100644 --- a/webui/src/components/hub/useProtectedHubUpdate.test.tsx +++ b/webui/src/components/hub/useProtectedHubUpdate.test.tsx @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { act, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { useProtectedHubUpdate } from './useProtectedHubUpdate'; +import { backendError } from '@/test/helpers'; const { hubAPI, done, error } = vi.hoisted(() => ({ hubAPI: { previewUpdate: vi.fn(), update: vi.fn() }, done: vi.fn(), error: vi.fn(), @@ -90,10 +91,17 @@ describe('protected Hub updates', () => { expect(screen.getByRole('status')).toHaveTextContent('/data/hub/backups/snapshot'); }); - it('requests confirmation again when files change after preview', async () => { - hubAPI.update.mockRejectedValueOnce({ response: { status: 409, data: { detail: { - code: 'hub_update_confirmation_required', plan: { ...changedPlan, token: 'second' }, - } } } }); + it.each([ + // What the service sends: its exception handler puts the route's `detail` under `message` + // (hub_update_plugin in flocks/server/routes/hub.py raises it as an HTTPException). + ['the exception handler sends it', backendError(409, { + code: 'hub_update_confirmation_required', plan: { ...changedPlan, token: 'second' }, // secret-guard: allow (the test's own plan token) + })], + ['it arrives under detail', { response: { status: 409, data: { detail: { + code: 'hub_update_confirmation_required', plan: { ...changedPlan, token: 'second' }, // secret-guard: allow (the test's own plan token) + } } } }], + ])('requests confirmation again when files change after preview, as %s', async (_name, conflict) => { + hubAPI.update.mockRejectedValueOnce(conflict); render(); await userEvent.click(screen.getByRole('button', { name: '更新' })); await userEvent.click(await screen.findByRole('button', { name: '备份并覆盖更新' })); diff --git a/webui/src/components/hub/useProtectedHubUpdate.tsx b/webui/src/components/hub/useProtectedHubUpdate.tsx index 85d8b0935..652427422 100644 --- a/webui/src/components/hub/useProtectedHubUpdate.tsx +++ b/webui/src/components/hub/useProtectedHubUpdate.tsx @@ -61,8 +61,11 @@ export function useProtectedHubUpdate() { if (response?.data?.backupPath && mounted.current) setBackupPath(response.data.backupPath); return true; } catch (error) { - const conflict = error as { response?: { status?: number; data?: { detail?: { code?: string; plan?: HubUpdatePlan } } } }; - const detail = conflict.response?.data?.detail; + // The service's exception handler sends the route's `detail` under `message` + // ({ error, message }); plain FastAPI would send it under `detail`. + type Refusal = { code?: string; plan?: HubUpdatePlan }; + const conflict = error as { response?: { status?: number; data?: { message?: Refusal; detail?: Refusal } } }; + const detail = conflict.response?.data?.message ?? conflict.response?.data?.detail; if (conflict.response?.status === 409 && detail?.code === 'hub_update_confirmation_required' && detail.plan) { current = detail.plan; continue; From 09ef0348e4d2b49c8a9558642b5d5f48ec1ab338 Mon Sep 17 00:00:00 2001 From: jamon Date: Thu, 12 Nov 2026 19:57:18 +0800 Subject: [PATCH 24/44] =?UTF-8?q?fix(webui):=20=E5=B7=A5=E4=BD=9C=E6=B5=81?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E8=BF=90=E8=A1=8C=E8=A2=AB=E6=8B=92=E7=BB=9D?= =?UTF-8?q?=E5=90=8E=E5=A4=B1=E8=B4=A5=E5=8E=9F=E5=9B=A0=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E4=B8=80=E9=97=AA=E8=80=8C=E8=BF=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 点「测试运行」时这次运行没能发起(后端回 404 / 409 / 403,或者连不上 后端),失败原因在页面上出现几毫秒就没了,看起来像点了没反应。 handleRun 放进测试区的是一条没有 id 的本地失败记录,历史列表随即重新 加载,把它换成历史里最新的一条或者清空;之后每 10 秒的自动刷新、历史 请求失败的分支、带 execId 打开页面的分支也都会换掉它。 历史回写改成函数式更新:父组件手里当前是这条本地失败记录时保持不动, 下一次运行再替换它。判断放在应用更新的时候做,而不是看 HistorySection 上次渲染拿到的 id,这样早先发出的历史请求晚回来、或者正好落在失败记录 已上报但页面还没重渲染之间,也不会盖掉它。为此 onLatestExecutionChange 的类型放宽成能接收 updater(RunTab、OverviewTab、RightPanel;index.tsx 传的本来就是 setLatestExecution)。 RunTab.test.tsx 补 7 条用例:历史为空、历史非空、历史请求也失败、历史 响应晚到、历史响应紧跟在拒绝之后、带 execId 打开,以及随后成功运行会 替换失败原因。 --- webui/src/pages/WorkflowDetail/RightPanel.tsx | 3 +- .../pages/WorkflowDetail/tabs/OverviewTab.tsx | 4 +- .../pages/WorkflowDetail/tabs/RunTab.test.tsx | 167 +++++++++++++++++- .../src/pages/WorkflowDetail/tabs/RunTab.tsx | 42 +++-- 4 files changed, 201 insertions(+), 15 deletions(-) diff --git a/webui/src/pages/WorkflowDetail/RightPanel.tsx b/webui/src/pages/WorkflowDetail/RightPanel.tsx index 0a8e0eaa9..d2c3ed9e1 100644 --- a/webui/src/pages/WorkflowDetail/RightPanel.tsx +++ b/webui/src/pages/WorkflowDetail/RightPanel.tsx @@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next'; import { Workflow, WorkflowExecution, WorkflowNode } from '@/api/workflow'; import { useConfirm } from '@/components/common/ConfirmDialog'; import OverviewTab from './tabs/OverviewTab'; +import type { LatestExecutionChange } from './tabs/RunTab'; import ChatTab, { type WorkflowChatLaunchRequest } from './tabs/ChatTab'; import IntegrationTab from './tabs/IntegrationTab'; import { getWorkflowDisplayName } from '@/utils/workflowDisplay'; @@ -74,7 +75,7 @@ interface RightPanelProps { chatLaunchRequest?: WorkflowChatLaunchRequest | null; onChatLaunchRequestHandled?: (id: number) => void; onActiveTabChange?: (tab: RightPanelTabId) => void; - onLatestExecutionChange?: (execution: WorkflowExecution | null) => void; + onLatestExecutionChange?: LatestExecutionChange; onExecutionSettled?: () => void; onWorkflowUpdated?: (updated: Workflow) => void; onFirstMessageSent?: () => void; diff --git a/webui/src/pages/WorkflowDetail/tabs/OverviewTab.tsx b/webui/src/pages/WorkflowDetail/tabs/OverviewTab.tsx index fd3b6d6e9..0c8d22792 100644 --- a/webui/src/pages/WorkflowDetail/tabs/OverviewTab.tsx +++ b/webui/src/pages/WorkflowDetail/tabs/OverviewTab.tsx @@ -2,12 +2,12 @@ import { useState, type ReactNode } from 'react'; import { useTranslation } from 'react-i18next'; import { Workflow, WorkflowExecution } from '@/api/workflow'; import { Calendar, User, Tag, Activity, Clock, CheckCircle, XCircle, Layers, ChevronDown, ChevronRight, FileText } from 'lucide-react'; -import RunTab from './RunTab'; +import RunTab, { type LatestExecutionChange } from './RunTab'; interface OverviewTabProps { workflow: Workflow; latestExecution?: WorkflowExecution | null; - onLatestExecutionChange?: (execution: WorkflowExecution | null) => void; + onLatestExecutionChange?: LatestExecutionChange; onExecutionSettled?: () => void; focusExecutionId?: string; } diff --git a/webui/src/pages/WorkflowDetail/tabs/RunTab.test.tsx b/webui/src/pages/WorkflowDetail/tabs/RunTab.test.tsx index dff4bafff..3a65304c8 100644 --- a/webui/src/pages/WorkflowDetail/tabs/RunTab.test.tsx +++ b/webui/src/pages/WorkflowDetail/tabs/RunTab.test.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import RunTab from './RunTab'; import type { WorkflowExecution } from '@/api/workflow'; @@ -395,4 +395,169 @@ describe('RunTab', () => { expect(screen.getByText('concurrent_triage')).toBeInTheDocument(); }); + describe('a test run the server refused', () => { + const reason = 'Workflow not found: wf-1'; + const earlierRun: WorkflowExecution = { + id: 'exec-earlier', + workflowId: 'wf-1', + inputParams: {}, + outputResults: { marker: 'earlier-run' }, + status: 'success', + startedAt: new Date('2026-01-01T00:00:00Z').getTime(), + duration: 1, + executionLog: [], + }; + + /** + * Refuse the next test run and, from the moment it is sent, hold back the history responses: + * the history reloads right after a refusal, and that reload is what used to wipe the reason. + * The returned function answers the held requests and waits for the page to take the answer in. + */ + function refuseNextRun() { + let answer!: (history: WorkflowExecution[] | Error) => void; + const held = new Promise<{ data: WorkflowExecution[] }>((resolve, reject) => { + answer = (history) => (history instanceof Error ? reject(history) : resolve({ data: history })); + }); + held.catch(() => undefined); + workflowAPI.run.mockImplementationOnce(() => { + workflowAPI.getHistory.mockReturnValue(held); + return Promise.reject(new Error(reason)); + }); + return async (history: WorkflowExecution[] | Error) => { + await waitFor(() => { + expect(workflowAPI.getHistory.mock.results.some((result) => result.value === held)).toBe(true); + }); + await act(async () => { + answer(history); + }); + }; + } + + it('keeps the reason on screen after the history reloads empty', async () => { + const user = userEvent.setup(); + const answerHistory = refuseNextRun(); + + render(); + await screen.findByText('暂无执行记录'); + await user.click(screen.getByRole('button', { name: '测试运行' })); + + expect(await screen.findByText(reason)).toBeInTheDocument(); + await answerHistory([]); + expect(screen.getByText(reason)).toBeInTheDocument(); + }); + + it('keeps the reason on screen instead of going back to an earlier run from the history', async () => { + const user = userEvent.setup(); + workflowAPI.getHistory.mockResolvedValue({ data: [earlierRun] }); + const answerHistory = refuseNextRun(); + + render(); + expect(await screen.findByText(/"marker": "earlier-run"/)).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: '测试运行' })); + + expect(await screen.findByText(reason)).toBeInTheDocument(); + await answerHistory([earlierRun]); + expect(screen.getByText(reason)).toBeInTheDocument(); + expect(screen.queryByText(/"marker": "earlier-run"/)).not.toBeInTheDocument(); + }); + + it('keeps the reason on screen when the history cannot be loaded either', async () => { + const user = userEvent.setup(); + workflowAPI.getHistory.mockResolvedValue({ data: [earlierRun] }); + const answerHistory = refuseNextRun(); + + render(); + expect(await screen.findByText(/"marker": "earlier-run"/)).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: '测试运行' })); + + expect(await screen.findByText(reason)).toBeInTheDocument(); + await answerHistory(new Error('Network Error')); + expect(screen.getByText(reason)).toBeInTheDocument(); + }); + + it('keeps the reason on screen when a history response asked for before the refusal arrives after it', async () => { + const user = userEvent.setup(); + let answerEarlyRequest!: (response: { data: WorkflowExecution[] }) => void; + workflowAPI.getHistory.mockReturnValueOnce(new Promise((resolve) => { + answerEarlyRequest = resolve; + })); + workflowAPI.run.mockRejectedValue(new Error(reason)); + + render(); + await user.click(screen.getByRole('button', { name: '测试运行' })); + + expect(await screen.findByText(reason)).toBeInTheDocument(); + await act(async () => { + answerEarlyRequest({ data: [earlierRun] }); + }); + expect(screen.getByText(reason)).toBeInTheDocument(); + expect(screen.queryByText(/"marker": "earlier-run"/)).not.toBeInTheDocument(); + }); + + it('keeps the reason when the history answers right behind the refusal, before the page has redrawn', async () => { + const user = userEvent.setup(); + let answerEarlyRequest!: (response: { data: WorkflowExecution[] }) => void; + workflowAPI.getHistory.mockReturnValueOnce(new Promise((resolve) => { + answerEarlyRequest = resolve; + })); + workflowAPI.run.mockImplementation(() => { + const refusal = Promise.reject(new Error(reason)); + // Attached ahead of the tab's own handler: the history request from before the refusal is + // answered in the same turn, once the tab has reported the refusal and before it redraws. + refusal.catch(() => queueMicrotask(() => answerEarlyRequest({ data: [earlierRun] }))); + return refusal; + }); + + render(); + await user.click(screen.getByRole('button', { name: '测试运行' })); + + expect(await screen.findByText(reason)).toBeInTheDocument(); + expect(screen.queryByText(/"marker": "earlier-run"/)).not.toBeInTheDocument(); + }); + + it('keeps the reason on screen when the page was opened on one execution', async () => { + const user = userEvent.setup(); + workflowAPI.getHistory.mockResolvedValue({ data: [earlierRun] }); + const answerHistory = refuseNextRun(); + + render(); + expect((await screen.findAllByText(/"marker": "earlier-run"/)).length).toBeGreaterThan(0); + await user.click(screen.getByRole('button', { name: '测试运行' })); + + expect(await screen.findByText(reason)).toBeInTheDocument(); + await answerHistory([earlierRun]); + expect(screen.getByText(reason)).toBeInTheDocument(); + }); + + it('gives way to the next run once the server accepts one', async () => { + const user = userEvent.setup(); + const answerHistory = refuseNextRun(); + + render(); + await screen.findByText('暂无执行记录'); + await user.click(screen.getByRole('button', { name: '测试运行' })); + + expect(await screen.findByText(reason)).toBeInTheDocument(); + await answerHistory([]); + expect(screen.getByText(reason)).toBeInTheDocument(); + + const nextRun: WorkflowExecution = { + id: 'exec-next', + workflowId: 'wf-1', + inputParams: {}, + status: 'running', + startedAt: Date.now(), + executionLog: [], + }; + workflowAPI.run.mockResolvedValue({ data: nextRun }); + workflowAPI.getHistory.mockResolvedValue({ + data: [{ ...nextRun, status: 'success', outputResults: { marker: 'next-run' }, duration: 2 }], + }); + await user.click(screen.getByRole('button', { name: '测试运行' })); + + expect(await screen.findByText(/"marker": "next-run"/)).toBeInTheDocument(); + expect(screen.queryByText(reason)).not.toBeInTheDocument(); + }); + }); + }); diff --git a/webui/src/pages/WorkflowDetail/tabs/RunTab.tsx b/webui/src/pages/WorkflowDetail/tabs/RunTab.tsx index d9901fb7b..824fa1700 100644 --- a/webui/src/pages/WorkflowDetail/tabs/RunTab.tsx +++ b/webui/src/pages/WorkflowDetail/tabs/RunTab.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect, useCallback, useRef } from 'react'; +import { useState, useEffect, useCallback, useRef, type Dispatch, type SetStateAction } from 'react'; import { Loader2, ChevronDown, ChevronRight, StopCircle, Clock, CheckCircle, XCircle, AlertCircle, FlaskConical, @@ -14,10 +14,16 @@ import CopyButton from '@/components/common/CopyButton'; import WorkflowStatusBadge from '@/components/common/WorkflowStatusBadge'; import { extractErrorMessage } from '@/utils/error'; +/** + * How the tab hands the latest execution to whoever holds it. Like a state setter it also takes + * an updater, which is given the execution held at the moment the update is applied. + */ +export type LatestExecutionChange = Dispatch>; + interface RunTabProps { workflow: Workflow; latestExecution: WorkflowExecution | null; - onLatestExecutionChange?: (execution: WorkflowExecution | null) => void; + onLatestExecutionChange?: LatestExecutionChange; onExecutionSettled?: () => void; sections?: RunTabSection[]; embedded?: boolean; @@ -36,6 +42,11 @@ function getExecutionDisplayStatus(execution?: WorkflowExecution | null): string return execution.status; } +/** An execution the test section made up to say why a run never started: it has no id. */ +function isLocalRunFailure(execution: WorkflowExecution | null): boolean { + return !!execution && !execution.id; +} + function getExecutionDisplayMessage( execution: WorkflowExecution | null | undefined, t: (key: string) => string, @@ -951,7 +962,7 @@ function HistorySection({ workflowId: string; latestExecutionId?: string; focusExecutionId?: string; - onLatestExecutionChange?: (execution: WorkflowExecution | null) => void; + onLatestExecutionChange?: LatestExecutionChange; embedded?: boolean; hideSectionHeader?: boolean; }) { @@ -963,6 +974,15 @@ function HistorySection({ const [focusedExecutionError, setFocusedExecutionError] = useState(''); const executionNotFoundText = t('detail.run.executionNotFound'); + // A test run that could not be started leaves an execution with no id in the test section, to + // say why (TestSection.handleRun). It is not in the history, so a history refresh must not swap + // it for an older run or clear it; the next run replaces it. Whether to keep it is decided + // against the execution held when the update is applied: the history answers later, and what + // this section last rendered with may be out of date by then. + const syncLatestExecution = useCallback((execution: WorkflowExecution | null) => { + onLatestExecutionChange?.((current) => (isLocalRunFailure(current) ? current : execution)); + }, [onLatestExecutionChange]); + const loadFocusedExecution = useCallback(async (executionId: string): Promise => { try { const res = await workflowAPI.getExecution(workflowId, executionId); @@ -993,7 +1013,7 @@ function HistorySection({ if (focusExecutionId) { const focusedExecution = nextHistory.find((item: WorkflowExecution) => item.id === focusExecutionId) ?? null; if (focusedExecution) { - onLatestExecutionChange?.(focusedExecution); + syncLatestExecution(focusedExecution); setSelectedExec(focusedExecution); setExpanded(true); } @@ -1002,12 +1022,12 @@ function HistorySection({ ? nextHistory.find((item: WorkflowExecution) => item.id === latestExecutionId) : nextHistory[0]; if (matchingExecution) { - onLatestExecutionChange?.(matchingExecution); + syncLatestExecution(matchingExecution); } else if (!latestExecutionId) { - onLatestExecutionChange?.(nextHistory[0]); + syncLatestExecution(nextHistory[0]); } } else if (!latestExecutionId) { - onLatestExecutionChange?.(null); + syncLatestExecution(null); } setSelectedExec(prev => { if (!prev) return null; @@ -1038,16 +1058,16 @@ function HistorySection({ if (focusExecutionId) { const focusedExecution = nextHistory.find((item) => item.id === focusExecutionId) ?? null; setSelectedExec(focusedExecution); - if (focusedExecution) onLatestExecutionChange?.(focusedExecution); + if (focusedExecution) syncLatestExecution(focusedExecution); } else if (nextHistory.length > 0) { - onLatestExecutionChange?.(nextHistory[0]); + syncLatestExecution(nextHistory[0]); } else { - onLatestExecutionChange?.(null); + syncLatestExecution(null); } } finally { setLoading(false); } - }, [executionNotFoundText, focusExecutionId, latestExecutionId, loadFocusedExecution, onLatestExecutionChange, workflowId]); + }, [executionNotFoundText, focusExecutionId, latestExecutionId, loadFocusedExecution, syncLatestExecution, workflowId]); const hasRunning = history.some(e => e.status === 'running'); From 86b36c0a6fcaea55dc784245addde2ed37c1ee0e Mon Sep 17 00:00:00 2001 From: jamon Date: Thu, 12 Nov 2026 22:20:44 +0800 Subject: [PATCH 25/44] =?UTF-8?q?fix(copy):=20=E6=8C=89=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=E6=96=87=E6=A1=88=E6=A3=80=E6=9F=A5=E8=A1=A8=20v0.21=20?= =?UTF-8?q?=E8=B0=83=E6=95=B4=E7=95=8C=E9=9D=A2=E6=8F=90=E7=A4=BA=EF=BC=8C?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=8D=B8=E8=BD=BD=E8=AF=AF=E5=88=A4=E5=92=8C?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E5=9C=B0=E5=9D=80=20500?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 登录、新建文件夹/目录、Cron、MCP 表单、分组名称的空值和格式问题改为字段下提示 - 分组文案按对象类型(智能体/技能/工作流/工具/设备);批量保存失败改为计数加逐条原因,服务端原话放进技术详情 - 模型页统一叫「API 代理 URL」,检查和获取模型失败不再显示 Internal server error;普通成员看模型详情为只读 - Flocks Pro 页、升级弹窗、升级说明按核实结果改写:首次启动把数据复制进自带 PostgreSQL,原数据文件只读、不再更新 - 更新内容弹窗把 feat(x):这类前缀换成模块名,代码块里的示例原样保留 - hub:服务从主目录启动时项目插件根就是用户插件根,不再把全局安装判成项目内置(卸载报 Built-in project Hub plugins cannot be removed);这种布局下 project 记录按用户安装校验,先校验全部目标再删除 - provider:主机名无法按 IDNA 编码(a..b、超长标签)归为 invalid_base_url,不再 500 --- flocks/cli/commands/enterprise.py | 2 +- flocks/hub/installer.py | 25 ++- flocks/provider/model_discovery.py | 4 + flocks/updater/enterprise.py | 2 +- tests/hub/test_uninstall_flocks_root_g3b.py | 103 +++++++++++++ tests/provider/test_model_discovery.py | 21 +++ .../components/common/EntitySheet.test.tsx | 21 +++ webui/src/components/common/EntitySheet.tsx | 35 +++-- .../layout/ProjectFolderDialog.test.tsx | 41 ++++- .../components/layout/ProjectFolderDialog.tsx | 36 +++-- .../plugin-groups/GroupNav.test.tsx | 54 ++++++- .../src/components/plugin-groups/GroupNav.tsx | 49 ++++-- .../plugin-groups/groupView.test.ts | 30 +++- .../src/components/plugin-groups/groupView.ts | 52 +++++-- webui/src/locales/en-US/agent.json | 6 +- webui/src/locales/en-US/auth.json | 4 +- webui/src/locales/en-US/channel.json | 2 +- webui/src/locales/en-US/common.json | 2 + webui/src/locales/en-US/flockspro.json | 20 +-- webui/src/locales/en-US/model.json | 16 +- webui/src/locales/en-US/nav.json | 7 +- webui/src/locales/en-US/pluginGroups.json | 50 ++++-- webui/src/locales/en-US/task.json | 1 + webui/src/locales/en-US/tool.json | 16 +- webui/src/locales/en-US/update.json | 4 +- webui/src/locales/en-US/workflow.json | 4 +- webui/src/locales/en-US/workspace.json | 3 + webui/src/locales/zh-CN/agent.json | 6 +- webui/src/locales/zh-CN/auth.json | 10 +- webui/src/locales/zh-CN/channel.json | 2 +- webui/src/locales/zh-CN/common.json | 2 + webui/src/locales/zh-CN/flockspro.json | 24 +-- webui/src/locales/zh-CN/model.json | 18 ++- webui/src/locales/zh-CN/nav.json | 7 +- webui/src/locales/zh-CN/pluginGroups.json | 50 ++++-- webui/src/locales/zh-CN/task.json | 1 + webui/src/locales/zh-CN/tool.json | 18 ++- webui/src/locales/zh-CN/update.json | 6 +- webui/src/locales/zh-CN/workflow.json | 4 +- webui/src/locales/zh-CN/workspace.json | 3 + webui/src/pages/Agent/AgentSheet.test.tsx | 16 +- webui/src/pages/Agent/AgentSheet.tsx | 15 +- webui/src/pages/Agent/index.tsx | 12 +- webui/src/pages/DeviceIntegration/index.tsx | 8 +- webui/src/pages/Login/index.test.tsx | 57 +++++++ webui/src/pages/Login/index.tsx | 25 ++- webui/src/pages/Model/ModelDiscovery.test.tsx | 23 +++ webui/src/pages/Model/ModelDiscovery.tsx | 5 +- webui/src/pages/Model/ProviderKeyCheck.tsx | 5 +- webui/src/pages/Model/index.test.tsx | 15 +- webui/src/pages/Model/index.tsx | 1 + webui/src/pages/SceneSuites/index.test.tsx | 2 +- webui/src/pages/SceneSuites/index.tsx | 7 +- webui/src/pages/Skill/index.test.tsx | 3 +- webui/src/pages/Skill/index.tsx | 12 +- webui/src/pages/Task/TaskSheet.test.tsx | 33 ++++ webui/src/pages/Task/TaskSheet.tsx | 32 +++- webui/src/pages/Tool/ToolGroups.test.tsx | 7 +- webui/src/pages/Tool/ToolSheets.test.ts | 35 ++++- webui/src/pages/Tool/ToolSheets.tsx | 143 +++++++++++++----- .../pages/Tool/components/APITabContent.tsx | 14 +- .../pages/Tool/components/MCPTabContent.tsx | 14 +- .../components/ServiceDetailPanel.test.tsx | 6 + .../Tool/components/ServiceDetailPanel.tsx | 47 +++--- webui/src/pages/Tool/index.tsx | 35 ++--- webui/src/pages/Workflow/index.tsx | 12 +- webui/src/pages/Workspace/index.test.tsx | 44 ++++++ webui/src/pages/Workspace/index.tsx | 28 +++- webui/src/utils/releaseNotes.test.ts | 48 +++++- webui/src/utils/releaseNotes.ts | 71 ++++++++- 70 files changed, 1214 insertions(+), 322 deletions(-) create mode 100644 webui/src/pages/Login/index.test.tsx diff --git a/flocks/cli/commands/enterprise.py b/flocks/cli/commands/enterprise.py index 459d44e87..60ddadbd7 100644 --- a/flocks/cli/commands/enterprise.py +++ b/flocks/cli/commands/enterprise.py @@ -135,7 +135,7 @@ async def progress(received: int, total: int | None) -> None: path = asyncio.run(enterprise.download(offer, progress)) console.print(f"[green]✓ 已下载并校验:{path}[/green]") if not enterprise.can_run_installer_here(): - console.print("[yellow]这台机器由 systemd 管(开源离线包),要以 root 运行安装包:[/yellow]") + console.print("[yellow]当前开源版由 systemd 管理(开源离线包),请使用 root 权限运行安装包:[/yellow]") console.print(f" [bold]{enterprise.installer_command(str(path))}[/bold]") return 1 console.print(f"运行 {path.name}(开源版会停下,企业版起来后照旧用 flocks start|stop|status|update)") diff --git a/flocks/hub/installer.py b/flocks/hub/installer.py index 37f34d15c..5dc21844d 100644 --- a/flocks/hub/installer.py +++ b/flocks/hub/installer.py @@ -765,7 +765,23 @@ async def _rollback_component_ref_installs( raise RuntimeError("Dependency rollback incomplete; " + "; ".join(errors)) +def _project_root_is_user_root(plugin_type: PluginType) -> bool: + """The instance directory holds the flocks root (``~`` holding ``~/.flocks``). + + Its ``.flocks/plugins`` is then the user plugin root itself: what is installed + there was installed by the user, nothing in it shipped with a project. + """ + try: + return local.install_root(plugin_type, "project").resolve() == local.install_root(plugin_type, "global").resolve() + except OSError: + return False + + def _is_project_install_path(plugin_type: PluginType, install_path: Path) -> bool: + if _project_root_is_user_root(plugin_type): + # A server started from the home directory would otherwise refuse to + # uninstall anything ("Built-in project Hub plugins cannot be removed"). + return False try: project_root = local.install_root(plugin_type, "project").resolve() resolved_install_path = install_path.resolve() @@ -1296,6 +1312,11 @@ async def _uninstall_plugin( record = local.get_record(plugin_type, plugin_id) install_path = Path(record.installPath) if record and record.installPath else local.infer_local_install(plugin_type, plugin_id) scope = record.scope if record else "global" + if scope == "project" and _project_root_is_user_root(plugin_type): + # The project plugin root is the user plugin root: a "project" record there is + # a user install, checked and removed as one -- every target is validated + # (the access contracts included) before anything is deleted. + scope = "global" if install_path is not None: await asyncio.to_thread(_validate_uninstall_target, plugin_type, plugin_id, install_path, scope) if plugin_type == "webui" and scope != "project": @@ -1317,7 +1338,7 @@ async def _uninstall_plugin( # A missing page payload can still leave its access contracts behind. # Keep project-managed contracts protected even when their pages vanished. access_removed = False - if plugin_type == "webui" and (record is None or record.scope != "project"): + if plugin_type == "webui" and scope != "project": access_removed = await asyncio.to_thread( _remove_attached_access_contracts, plugin_type, plugin_id, "global", recovery_root=recovery_root, ) @@ -1346,7 +1367,7 @@ async def _uninstall_plugin( else: install_path.unlink() _remove_attached_access_contracts( - plugin_type, plugin_id, record.scope if record else "global", recovery_root=recovery_root, + plugin_type, plugin_id, scope, recovery_root=recovery_root, ) local.remove_installed_record(plugin_type, plugin_id) clear_catalog_caches() diff --git a/flocks/provider/model_discovery.py b/flocks/provider/model_discovery.py index dd5d946c4..8ff4f97c2 100644 --- a/flocks/provider/model_discovery.py +++ b/flocks/provider/model_discovery.py @@ -328,6 +328,10 @@ async def _validate_resolved_addresses(url: str) -> None: # The HTTP transport owns connection error reporting; a test or custom # transport may also resolve names independently of the system resolver. return + except UnicodeError: + # The resolver encodes names with IDNA: an empty label ("a..b") or one + # longer than 63 characters is not a host name, not a server failure. + raise DiscoveryError("invalid_base_url", "The provider base URL does not name a valid host.") from None for address in addresses: target = ipaddress.ip_address(address[4][0].split("%", 1)[0]) if getattr(target, "ipv4_mapped", None): diff --git a/flocks/updater/enterprise.py b/flocks/updater/enterprise.py index c49505e3d..37939559d 100644 --- a/flocks/updater/enterprise.py +++ b/flocks/updater/enterprise.py @@ -1047,7 +1047,7 @@ def start_installer(path: Path, offer: InstallerOffer, attempt: str | None = Non if _WINDOWS: return _start_windows_installer(path, offer, attempt) if run_by_systemd(): - raise EnterpriseUpgradeError(f"这台机器由 systemd 管,要以 root 执行:{installer_command(str(path))}") + raise EnterpriseUpgradeError(f"当前开源版由 systemd 管理,请使用 root 权限运行:{installer_command(str(path))}") if not install_root_ready(): raise EnterpriseUpgradeError(f"先用 root 执行一次:{prepare_command()}") prior_result = _prior_installation_result() diff --git a/tests/hub/test_uninstall_flocks_root_g3b.py b/tests/hub/test_uninstall_flocks_root_g3b.py index 1af7ec431..07eb02f3f 100644 --- a/tests/hub/test_uninstall_flocks_root_g3b.py +++ b/tests/hub/test_uninstall_flocks_root_g3b.py @@ -70,3 +70,106 @@ async def test_uninstall_still_refuses_paths_outside_user_root(isolated_root, tm with pytest.raises(ValueError, match="user-managed install location"): await installer.uninstall_plugin("skill", "foreign") assert elsewhere.exists() + + +@pytest.fixture +def home_project_root(tmp_path, monkeypatch): + """The default layout with the server started from the home directory. + + The instance directory is ``~`` and the flocks root ``~/.flocks``: the + project plugin root ``~/.flocks/plugins`` is the user plugin root itself. + """ + home = tmp_path / "home" + root = home / ".flocks" + (root / "config").mkdir(parents=True) + (root / "data").mkdir() + monkeypatch.setenv("FLOCKS_ROOT", str(root)) + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setattr(local.Instance, "get_directory", staticmethod(lambda: str(home))) + monkeypatch.setattr(local.Config, "get_data_path", staticmethod(lambda: root / "data")) + assert local.install_root("component", "project").resolve() == local.install_root("component", "global").resolve() + return root + + +async def test_uninstall_from_home_directory_instance_is_not_a_project_builtin(home_project_root, monkeypatch): + """v0.21 #6: 场景管理卸载告警运营套件报 "Built-in project Hub plugins cannot be removed".""" + path = _install_skill_under(home_project_root, "home-skill") + + async def _no_refresh(*_a, **_k): + return None + + monkeypatch.setattr(installer, "_refresh_runtime", _no_refresh) + monkeypatch.setattr(installer, "_remove_attached_access_contracts", lambda *_a, **_k: None) + + assert installer._is_project_install_path("skill", path) is False + assert await installer.uninstall_plugin("skill", "home-skill") is True + assert not path.exists() + + +async def test_project_scope_record_in_shared_root_is_still_confined(home_project_root, tmp_path, monkeypatch): + elsewhere = tmp_path / "elsewhere" / "skills" / "foreign" + elsewhere.mkdir(parents=True) + (elsewhere / "SKILL.md").write_text("---\nname: foreign\ndescription: d\n---\n", encoding="utf-8") + local.save_installed_record(InstalledPluginRecord( + id="foreign", type="skill", version="1.0.0", source="x", installedAt=1, enabled=True, + scope="project", installPath=str(elsewhere), + )) + + with pytest.raises(ValueError, match="user-managed install location"): + await installer.uninstall_plugin("skill", "foreign") + assert elsewhere.exists() + + +def test_distinct_project_root_still_protects_shipped_plugins(isolated_root, tmp_path): + shipped = tmp_path / "proj" / ".flocks" / "plugins" / "skills" / "shipped" + shipped.mkdir(parents=True) + assert installer._is_project_install_path("skill", shipped) is True + with pytest.raises(ValueError, match="Built-in project Hub plugins cannot be removed"): + installer._validate_uninstall_target("skill", "shipped", shipped, "global") + + +def _install_webui_under_shared_root(plugin_id: str, *, scope: str) -> tuple[Path, Path]: + page = local.install_dir("webui", plugin_id, "global") + (page / "pages" / "home").mkdir(parents=True) + (page / "pages" / "home" / "page.json").write_text("{}", encoding="utf-8") + access = local.install_root("webui", "global").resolve().parent / "access" / plugin_id + access.mkdir(parents=True) + (access / "contract.py").write_text("# access contract\n", encoding="utf-8") + local.save_installed_record(InstalledPluginRecord( + id=plugin_id, type="webui", version="1.0.0", source="bundled:plugins/webuis/" + plugin_id, + installedAt=1, enabled=True, scope=scope, installPath=str(page), + )) + return page, access + + +@pytest.mark.parametrize("scope", ["project", "global"]) +async def test_shared_root_webui_record_is_removed_with_its_access_contracts(home_project_root, monkeypatch, scope): + # Codex review 20261112-212545-2f33: a "project" record in the shared root used to pass the + # path check, delete the pages and then be refused at the access contracts. + page, access = _install_webui_under_shared_root("shared_ui", scope=scope) + + async def _no_refresh(*_a, **_k): + return None + + monkeypatch.setattr(installer, "_refresh_runtime", _no_refresh) + assert await installer.uninstall_plugin("webui", "shared_ui") is True + assert not page.exists() and not access.exists() + assert local.get_record("webui", "shared_ui") is None + + +async def test_shared_root_webui_is_untouched_when_its_access_contracts_cannot_be_removed(home_project_root, tmp_path, monkeypatch): + page, access = _install_webui_under_shared_root("linked_ui", scope="project") + # A link where the access contracts should be: refused before anything is deleted. + elsewhere = tmp_path / "elsewhere-access" + access.rename(elsewhere) + access.symlink_to(elsewhere, target_is_directory=True) + + async def _no_refresh(*_a, **_k): + return None + + monkeypatch.setattr(installer, "_refresh_runtime", _no_refresh) + with pytest.raises(ValueError, match="escapes"): + await installer.uninstall_plugin("webui", "linked_ui") + assert (page / "pages" / "home" / "page.json").is_file() + assert (elsewhere / "contract.py").is_file() + assert local.get_record("webui", "linked_ui") is not None diff --git a/tests/provider/test_model_discovery.py b/tests/provider/test_model_discovery.py index 0df5842c1..0defc62cf 100644 --- a/tests/provider/test_model_discovery.py +++ b/tests/provider/test_model_discovery.py @@ -604,6 +604,27 @@ async def test_non_http_url_is_rejected_without_network(discovery_runtime, upstr assert not upstream.requests +@pytest.mark.asyncio +@pytest.mark.parametrize("base_url", ["http://a..b/v1", "http://" + "x" * 64 + ".example.com/v1"]) +async def test_host_name_the_resolver_cannot_encode_is_an_invalid_url(base_url, discovery_runtime, monkeypatch): + # v0.21 #27: these used to escape the resolver check as UnicodeError and + # answer 500 "Internal server error". The real resolver check runs here + # (the upstream fixture stubs it); the transport only records requests. + requests = [] + real_client = httpx.AsyncClient + + def factory(*args, **kwargs): + kwargs["transport"] = httpx.MockTransport(lambda request: requests.append(request) or httpx.Response(200, json={"data": []})) + return real_client(*args, **kwargs) + + monkeypatch.setattr(discovery_runtime.module.httpx, "AsyncClient", factory) + result = await discovery_runtime.module.discover_models("openai-compatible", api_key="sk-test", base_url=base_url) # secret-guard: allow 误报:测试用假 key + + assert result["status"] == "error" + assert result["code"] == "invalid_base_url" + assert not requests + + @pytest.mark.asyncio async def test_missing_url_and_key_are_distinguished(discovery_runtime, upstream): missing_url = await discovery_runtime.module.discover_models("openai-compatible") diff --git a/webui/src/components/common/EntitySheet.test.tsx b/webui/src/components/common/EntitySheet.test.tsx index a8a85b394..421e95153 100644 --- a/webui/src/components/common/EntitySheet.test.tsx +++ b/webui/src/components/common/EntitySheet.test.tsx @@ -54,6 +54,7 @@ const entityTranslations: Record = { 'entity.createTitle': '创建 {{entityType}}', 'entity.editTitle': '编辑 {{entityType}}', 'entity.editTitleWithName': '编辑 {{entityType}}:{{entityName}}', + 'entity.viewTitleWithName': '{{entityType}}详情:{{entityName}}', 'entity.defaultCreate': '创建', 'entity.defaultSave': '保存', 'entity.tabDetails': '详情', @@ -448,6 +449,26 @@ describe('EntitySheet', () => { }); }); + describe('Read-only view', () => { + it('titles the sheet as details and offers no save or cancel, only the close button', async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + const onSubmit = vi.fn(); + render( + +
Form content
+
, + ); + + expect(screen.getByText('模型详情:DeepSeek-V4.1-Flash-1017')).toBeInTheDocument(); + expect(screen.queryByText('保存')).not.toBeInTheDocument(); + expect(screen.queryByText('取消')).not.toBeInTheDocument(); + await user.click(document.querySelectorAll('button')[0]); + expect(onClose).toHaveBeenCalled(); + expect(onSubmit).not.toHaveBeenCalled(); + }); + }); + describe('Footer actions', () => { it('should show "创建" button in create mode', () => { render( diff --git a/webui/src/components/common/EntitySheet.tsx b/webui/src/components/common/EntitySheet.tsx index ca541df12..3040a92f9 100644 --- a/webui/src/components/common/EntitySheet.tsx +++ b/webui/src/components/common/EntitySheet.tsx @@ -176,6 +176,8 @@ export interface EntitySheetProps { rexComposerTextareaMaxHeight?: number; /** Optional element rendered on the left side of the form-tab footer (e.g. delete button) */ footerLeft?: React.ReactNode; + /** Edit mode the viewer may only look at: "{{entityType}}详情" title, no save/cancel (the header still closes). */ + readOnly?: boolean; } // ─── Main Component ─────────────────────────────────────────────────────────── @@ -224,6 +226,7 @@ export default function EntitySheet({ rexComposerTextareaMinHeight, rexComposerTextareaMaxHeight, footerLeft, + readOnly = false, }: EntitySheetProps) { const { t } = useTranslation('common'); const supportsVision = useDefaultModelVision(); @@ -234,9 +237,13 @@ export default function EntitySheet({ const title = mode === 'create' ? t('entity.createTitle', { entityType }) - : entityName - ? t('entity.editTitleWithName', { entityType, entityName }) - : t('entity.editTitle', { entityType }); + : readOnly + ? entityName + ? t('entity.viewTitleWithName', { entityType, entityName }) + : t('entity.viewTitle', { entityType }) + : entityName + ? t('entity.editTitleWithName', { entityType, entityName }) + : t('entity.editTitle', { entityType }); const defaultSubmitLabel = mode === 'create' ? t('entity.defaultCreate') : t('entity.defaultSave'); const effectiveDefaultTestPrompt = defaultTestPrompt ?? t('entity.defaultTestPrompt', { defaultValue: 'Hello, please introduce yourself.' }); @@ -767,8 +774,8 @@ export default function EntitySheet({ )} - {/* ── Footer ── */} - {(!showTabs || activeTab === 'form') && ( + {/* ── Footer ── (a read-only sheet with nothing on the left has none) */} + {(!showTabs || activeTab === 'form') && !(readOnly && !footerLeft && !(onRunTest && !hideTest)) && (
{/* Left: custom footer element and/or test button */} @@ -785,14 +792,16 @@ export default function EntitySheet({ )}
- + {!readOnly && ( + + )}
)} diff --git a/webui/src/components/layout/ProjectFolderDialog.test.tsx b/webui/src/components/layout/ProjectFolderDialog.test.tsx index 78ed4f015..1b980c017 100644 --- a/webui/src/components/layout/ProjectFolderDialog.test.tsx +++ b/webui/src/components/layout/ProjectFolderDialog.test.tsx @@ -129,6 +129,45 @@ describe('ProjectFolderDialog', () => { expect(screen.queryByRole('button', { name: 'history.parentFolder' })).not.toBeInTheDocument(); }); + it('answers a missing name under the name field, without a failed-save toast', async () => { + serveFolders({ '': homeListing() }); + await renderDialog(); + + fireEvent.click(screen.getByRole('button', { name: 'history.createFolder' })); + + expect(await screen.findByText('history.folderNameEmpty')).toBeInTheDocument(); + expect(nameInput()).toHaveAttribute('aria-invalid', 'true'); + expect(toastMock.error).not.toHaveBeenCalled(); + expect(apiPost).not.toHaveBeenCalled(); + fireEvent.change(nameInput(), { target: { value: 'AAA' } }); + expect(screen.queryByText('history.folderNameEmpty')).not.toBeInTheDocument(); + }); + + it('drops the missing-directory answer once the directory fills in from the name', async () => { + serveFolders({ '': homeListing() }); + await renderDialog(); + fireEvent.click(screen.getByRole('button', { name: 'history.createFolder' })); + expect(await screen.findByText('history.folderPathEmpty')).toBeInTheDocument(); + + // Only the name is typed: the directory follows it under the default root. + await typeName('AAA', `${HOME}/AAA`); + expect(screen.queryByText('history.folderNameEmpty')).not.toBeInTheDocument(); + expect(screen.queryByText('history.folderPathEmpty')).not.toBeInTheDocument(); + expect(apiPost).not.toHaveBeenCalled(); + }); + + it('drops the missing-name answer once a picked directory names the folder', async () => { + serveFolders({ '': homeListing() }); + await renderDialog(); + fireEvent.click(screen.getByRole('button', { name: 'history.createFolder' })); + expect(await screen.findByText('history.folderNameEmpty')).toBeInTheDocument(); + + browse(); + await waitFor(() => expect(nameInput()).not.toHaveValue('')); + expect(screen.queryByText('history.folderNameEmpty')).not.toBeInTheDocument(); + expect(screen.queryByText('history.folderPathEmpty')).not.toBeInTheDocument(); + }); + it('says why the folder could not be saved', async () => { serveFolders({ '': homeListing() }); apiPost.mockRejectedValue(httpError(400, 'Project directory is outside the allowed roots')); @@ -138,7 +177,7 @@ describe('ProjectFolderDialog', () => { fireEvent.click(screen.getByRole('button', { name: 'history.createFolder' })); await waitFor(() => expect(toastMock.error).toHaveBeenCalledWith( - 'history.folderSaveFailed', + 'history.folderCreateFailed', 'Project directory is outside the allowed roots', )); expect(apiPost).toHaveBeenCalledWith('/api/project', { name: 'AAA', worktree: `${HOME}/AAA` }); diff --git a/webui/src/components/layout/ProjectFolderDialog.tsx b/webui/src/components/layout/ProjectFolderDialog.tsx index 410885170..7d8f71980 100644 --- a/webui/src/components/layout/ProjectFolderDialog.tsx +++ b/webui/src/components/layout/ProjectFolderDialog.tsx @@ -63,6 +63,9 @@ export default function ProjectFolderDialog({ mode, project, onClose, onSaved }: const [browser, setBrowser] = useState(null); const [browserLoading, setBrowserLoading] = useState(false); const [submitting, setSubmitting] = useState(false); + // A missing name or directory is answered under its field, not as a failed save. + const [nameError, setNameError] = useState(''); + const [pathError, setPathError] = useState(''); const requestIdRef = useRef(0); const loadBrowser = useCallback(async (path?: string) => { @@ -78,6 +81,7 @@ export default function ProjectFolderDialog({ mode, project, onClose, onSaved }: if (next.missing) return; setWorktree(next.path); setWorktreeEdited(true); + setPathError(''); if (!nameEdited) setName(pathBasename(next.path)); } catch (err: unknown) { if (requestId === requestIdRef.current) toast.error(t('history.folderBrowseFailed'), extractErrorMessage(err, '')); @@ -107,6 +111,11 @@ export default function ProjectFolderDialog({ mode, project, onClose, onSaved }: setWorktree(folderName ? joinFolderPath(defaultRoot, folderName) : ''); }, [defaultRoot, mode, name, worktreeEdited]); + // A field filled in for the user (the directory follows the name, a picked + // directory names the folder) no longer lacks a value. + useEffect(() => { if (name.trim()) setNameError(''); }, [name]); + useEffect(() => { if (worktree.trim()) setPathError(''); }, [worktree]); + useEffect(() => { const onKeyDown = (event: KeyboardEvent) => { if (event.key === 'Escape' && !submitting) onClose(); @@ -119,14 +128,11 @@ export default function ProjectFolderDialog({ mode, project, onClose, onSaved }: if (submitting) return; const nextName = name.trim(); const nextWorktree = worktree.trim(); - if (!nextName) { - toast.error(t('history.folderSaveFailed'), t('history.folderNameEmpty')); - return; - } - if (mode === 'create' && !nextWorktree) { - toast.error(t('history.folderSaveFailed'), t('history.folderPathEmpty')); - return; - } + const missingName = nextName ? '' : t('history.folderNameEmpty'); + const missingPath = mode === 'create' && !nextWorktree ? t('history.folderPathEmpty') : ''; + setNameError(missingName); + setPathError(missingPath); + if (missingName || missingPath) return; setSubmitting(true); try { const response = mode === 'create' @@ -134,7 +140,7 @@ export default function ProjectFolderDialog({ mode, project, onClose, onSaved }: : await apiClient.patch(`/api/project/${project?.id}`, { name: nextName }); onSaved(response.data as ProjectFolderSummary); } catch (err: unknown) { - toast.error(t('history.folderSaveFailed'), extractErrorMessage(err, '')); + toast.error(t(mode === 'create' ? 'history.folderCreateFailed' : 'history.folderRenameFailed'), extractErrorMessage(err, '')); } finally { setSubmitting(false); } @@ -165,9 +171,12 @@ export default function ProjectFolderDialog({ mode, project, onClose, onSaved }: maxLength={80} disabled={submitting} placeholder={t('history.folderNamePlaceholder')} - onChange={(event) => { setName(event.target.value); setNameEdited(true); }} + onChange={(event) => { setName(event.target.value); setNameEdited(true); setNameError(''); }} + aria-invalid={nameError ? true : undefined} + aria-describedby={nameError ? 'project-folder-name-error' : undefined} className={inputClass} /> + {nameError &&

{nameError}

} {mode === 'create' && (
@@ -183,8 +192,11 @@ export default function ProjectFolderDialog({ mode, project, onClose, onSaved }: setBrowserLoading(false); setWorktree(event.target.value); setWorktreeEdited(true); + setPathError(''); if (!nameEdited) setName(pathBasename(event.target.value)); }} + aria-invalid={pathError ? true : undefined} + aria-describedby={pathError ? 'project-folder-path-error' : undefined} className={`${inputClass} min-w-0 flex-1 font-mono text-xs`} />
-

{t('history.folderPathHint')}

+ {pathError + ?

{pathError}

+ :

{t('history.folderPathHint')}

} {browser && (
diff --git a/webui/src/components/plugin-groups/GroupNav.test.tsx b/webui/src/components/plugin-groups/GroupNav.test.tsx index 1b2d7e4b8..5090c959f 100644 --- a/webui/src/components/plugin-groups/GroupNav.test.tsx +++ b/webui/src/components/plugin-groups/GroupNav.test.tsx @@ -6,7 +6,7 @@ import { I18nextProvider, initReactI18next } from 'react-i18next'; import GroupNav, { useGroupDrag } from './GroupNav'; import PluginGroupButton from './PluginGroupButton'; import { ToastProvider, useToast } from '@/components/common/Toast'; -import { deriveGroupNav, type GroupNavItem, type GroupSelection } from './groupView'; +import { deriveGroupNav, GroupSaveError, type GroupNavItem, type GroupSelection } from './groupView'; import messages from '@/locales/en-US/pluginGroups.json'; import zhMessages from '@/locales/zh-CN/pluginGroups.json'; @@ -102,10 +102,10 @@ describe('pure native GroupNav', () => { }); it('only shows a short drag hint, without permanent readonly or implementation explanations', async () => { - await mount([{ key: 'builtin', name: 'Built-in', group: 'Fixed', readOnlyReason: messages.readOnly.system }]); + await mount([{ key: 'custom', name: 'Custom' }, { key: 'builtin', name: 'Built-in', group: 'Fixed', readOnlyReason: 'The group of a built-in plugin cannot be changed.' }]); const sidebar = screen.getByRole('complementary'); - expect(within(sidebar).getByText(messages.countsDescription)).toBeInTheDocument(); - expect(sidebar).not.toHaveTextContent(messages.readOnly.system); + expect(within(sidebar).getByText('Drag plugins onto a group.')).toBeInTheDocument(); + expect(sidebar).not.toHaveTextContent('The group of a built-in plugin cannot be changed.'); expect(sidebar).not.toHaveTextContent(/derived|administrators|personal|native group/i); expect(notify).not.toHaveBeenCalled(); }); @@ -151,6 +151,50 @@ describe('pure native GroupNav', () => { expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); }); + it('names what the page groups and only shows the drag hint once something can be grouped', async () => { + const i18n = createInstance(); + await i18n.use(initReactI18next).init({ lng: 'zh-CN', resources: { 'zh-CN': { pluginGroups: zhMessages } }, interpolation: { escapeValue: false } }); + const props = { preferenceKey: 'kinds', selection: null, onSelect: vi.fn(), onMove: move, onRename: rename, onDelete: remove, total: 1, ungroupedCount: 1, groups: [] }; + const { rerender } = render(); + expect(screen.getByText('拖动智能体到分组。')).toBeInTheDocument(); + rerender(); + expect(screen.getByText('暂无可分组设备。')).toBeInTheDocument(); + expect(screen.queryByText(/拖动/)).not.toBeInTheDocument(); + rerender(); + expect(screen.getByText('暂无可分组 MCP 服务。')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: '新建分组' })).toBeDisabled(); + }); + + it('says which rule an invalid group name breaks', async () => { + await mount([{ key: 'a', name: 'Alpha' }]); + fireEvent.click(screen.getByRole('button', { name: 'New group' })); + const input = screen.getByRole('textbox', { name: 'Group name' }); + expect(screen.getByText(messages.dialog.nameHint)).toBeInTheDocument(); + fireEvent.change(input, { target: { value: ' ' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect(screen.getByRole('alert')).toHaveTextContent(messages.validation.required); + fireEvent.change(input, { target: { value: 'x'.repeat(33) } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect(screen.getByRole('alert')).toHaveTextContent(messages.validation.tooLong); + fireEvent.change(input, { target: { value: 'a\u0007b' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect(screen.getByRole('alert')).toHaveTextContent(messages.validation.controlChars); + expect(move).not.toHaveBeenCalled(); + }); + + it('keeps the server wording of a reworded failure under technical details', async () => { + move.mockRejectedValueOnce(new GroupSaveError('Saved 0; failed 1.\n\nAlpha (a): It changed after it was checked. Refresh and try again.', 'Alpha (a): /srv/x changed after it was checked')); + await mount([{ key: 'a', name: 'Alpha', group: 'Ops' }, { key: 'b', name: 'Beta', group: 'Ops' }]); + fireEvent.keyDown(screen.getByTestId('a'), { key: 'm', altKey: true }); + fireEvent.change(screen.getByRole('combobox', { name: 'Destination group' }), { target: { value: '' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + const alert = await screen.findByRole('alert'); + expect(alert).toHaveTextContent('It changed after it was checked. Refresh and try again.'); + const details = within(alert).getByText('Technical details'); + expect(details.closest('details')).not.toHaveAttribute('open'); + expect(within(alert).getByText('Alpha (a): /srv/x changed after it was checked')).toBeInTheDocument(); + }); + it('only clears a missing selection for an authoritative unfiltered inventory', async () => { const i18n = createInstance(); await i18n.use(initReactI18next).init({ lng: 'en-US', resources: { 'en-US': { pluginGroups: messages } } }); @@ -172,7 +216,7 @@ describe('pure native GroupNav', () => { fireEvent.click(screen.getByRole('button', { name: 'New group' })); fireEvent.change(screen.getByRole('textbox', { name: 'Group name' }), { target: { value: ' Ops ' } }); fireEvent.click(screen.getByRole('button', { name: 'Save' })); - expect(screen.getByRole('alert')).toHaveTextContent(messages.validation.firstPlugin); + expect(screen.getByRole('alert')).toHaveTextContent('Choose an editable plugin.'); expect(move).not.toHaveBeenCalled(); expect(localStorage.length).toBe(0); const select = screen.getByRole('combobox', { name: 'First editable plugin' }); diff --git a/webui/src/components/plugin-groups/GroupNav.tsx b/webui/src/components/plugin-groups/GroupNav.tsx index 86bde24e9..eab91ba10 100644 --- a/webui/src/components/plugin-groups/GroupNav.tsx +++ b/webui/src/components/plugin-groups/GroupNav.tsx @@ -2,7 +2,7 @@ import { useEffect, useId, useRef, useState, type HTMLAttributes, type ReactNode import { GripVertical, Pencil, Plus, Trash2, X } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { useOptionalToast } from '@/components/common/Toast'; -import { GroupActionCancelled, groupItemLabel, groupLabel, groupName, orderGroupNames, type GroupNavEntry, type GroupNavItem, type GroupSelection } from './groupView'; +import { GroupActionCancelled, GroupSaveError, groupItemLabel, groupLabel, groupName, groupNoun, orderGroupNames, type GroupItemKind, type GroupNavEntry, type GroupNavItem, type GroupSelection } from './groupView'; const RESOURCE_MIME = 'application/x-flocks-visible-plugin'; const ORDER_MIME = 'application/x-flocks-group-order'; @@ -104,6 +104,8 @@ export interface GroupNavProps { clearMovingItem?: () => void; /** Accept only a gesture started by this page's currently mounted resource. */ consumeResourceDrag?: (token: string) => GroupNavItem | undefined; + /** What this page groups, so messages say "智能体" or "工作流" instead of "插件". */ + itemKind?: GroupItemKind; className?: string; } @@ -155,9 +157,10 @@ function GroupDialog({ titleId, onClose, busy, children }: { /** Prop-driven native-group navigation. Only dialogs, feedback and personal order live here. */ export default function GroupNav({ preferenceKey, groups, total, ungroupedCount, inventoryComplete = false, items, selection, onSelect, - onMove, onCreate, onRename, onDelete, movingItem, clearMovingItem, consumeResourceDrag, className = '', + onMove, onCreate, onRename, onDelete, movingItem, clearMovingItem, consumeResourceDrag, itemKind = 'plugin', className = '', }: GroupNavProps) { const { t } = useTranslation('pluginGroups'); + const nouns = groupNoun(t, itemKind); const toast = useOptionalToast(); const dialogTitleId = useId(); const [dialog, setDialog] = useState(null); @@ -169,6 +172,8 @@ export default function GroupNav({ const orderSequence = useRef(0); // Success/cancel feedback is a top-right toast; failures stay in place until the next action. const [error, setError] = useState(''); + // The server's own words behind a reworded failure, folded away under "技术详情". + const [errorDetails, setErrorDetails] = useState(''); const names = groups.filter((entry) => entry.count > 0 && entry.name).map((entry) => entry.name); const storageKey = `flocks:plugin-group-order:${preferenceKey}`; const [personalOrder, setPersonalOrder] = useState(() => ({ key: storageKey, value: readOrder(storageKey) })); @@ -202,6 +207,7 @@ export default function GroupNav({ busyRef.current = true; setBusy(true); setError(''); + setErrorDetails(''); try { await action(); if (close) { setDialog(null); clearMovingItem?.(); } @@ -211,14 +217,17 @@ export default function GroupNav({ // The user just declined the confirmation; nothing else to report. setDialog(null); clearMovingItem?.(); - } else setError(err instanceof Error ? err.message : String(err)); + } else { + setError(err instanceof Error ? err.message : String(err)); + setErrorDetails(err instanceof GroupSaveError ? err.details : ''); + } } finally { busyRef.current = false; setBusy(false); } }; - const openCreate = (key = '') => { setName(''); setError(''); setDialog({ kind: 'create', key }); }; + const openCreate = (key = '') => { setName(''); setError(''); setErrorDetails(''); setDialog({ kind: 'create', key }); }; const dropProps = (target?: string, orderTarget?: string): HTMLAttributes => ({ onDragOver: (event) => { if (event.dataTransfer.types.includes(RESOURCE_MIME) || (orderTarget && event.dataTransfer.types.includes(ORDER_MIME))) event.preventDefault(); @@ -244,16 +253,26 @@ export default function GroupNav({ const submit = () => { if (!dialog) return; const next = name.trim(); - if (!next || [...next].length > 32 || /[\u0000-\u001f\u007f]/.test(next)) { setError(t('validation.length')); return; } + setErrorDetails(''); + if (!next) { setError(t('validation.required')); return; } + if ([...next].length > 32) { setError(t('validation.tooLong')); return; } + if (/[\u0000-\u001f\u007f]/.test(next)) { setError(t('validation.controlChars')); return; } if (names.includes(next)) { setError(t('validation.duplicate')); return; } if (dialog.kind === 'rename') { void run(() => onRename(dialog.name, next)); return; } const first = editableItems.find((item) => item.key === dialog.key); - if (!first) { setError(t('validation.firstPlugin')); return; } + if (!first) { setError(t('validation.firstPlugin', nouns)); return; } void run(() => (onCreate ?? onMove)(first.key, next)); }; const modalOpen = !!dialog || !!movingItem; - const closeModal = () => { if (!busy) { setDialog(null); clearMovingItem?.(); setError(''); } }; + const closeModal = () => { if (!busy) { setDialog(null); clearMovingItem?.(); setError(''); setErrorDetails(''); } }; + const errorBlock = (className: string) => error &&
+

{error}

+ {errorDetails &&
+ {t('errors.details')} +
{errorDetails}
+
} +
; const navigationButton = (value: GroupSelection, label: string, count: number) => (
-

{t('countsDescription')}

+ {/* The drag hint only once something can be dragged; until then say there is nothing to group. */} +

{editableItems.length ? t('countsDescription', nouns) : t('readOnly.noEditable', nouns)}

- {error && !modalOpen &&

{error}

} + {!modalOpen && errorBlock('mt-3 px-2')} {modalOpen &&

{dialog ? t(`dialog.${dialog.kind}Title`) : t('dialog.moveTitle', { name: movingItem?.name })}

@@ -314,10 +334,11 @@ export default function GroupNav({ setName(event.target.value)} disabled={busy} className="mt-1 w-full rounded border border-gray-300 px-3 py-2 text-sm" /> - {dialog.kind === 'create' && } - {error &&

{error}

} + {errorBlock('mt-3')}
{!dialog && movingItem && } diff --git a/webui/src/components/plugin-groups/groupView.test.ts b/webui/src/components/plugin-groups/groupView.test.ts index 5f58c46c9..0e6c81bae 100644 --- a/webui/src/components/plugin-groups/groupView.test.ts +++ b/webui/src/components/plugin-groups/groupView.test.ts @@ -3,11 +3,12 @@ import { createInstance } from 'i18next'; import enGroups from '@/locales/en-US/pluginGroups.json'; const i18n = createInstance(); const t = i18n.t.bind(i18n); -import { deriveGroupNav, GroupActionCancelled, groupLabel, matchesGroup, orderGroupNames, saveGroupItems } from './groupView'; +import { assertGroupItemsEditable, deriveGroupNav, GroupActionCancelled, groupLabel, GroupSaveError, matchesGroup, orderGroupNames, saveGroupItems } from './groupView'; beforeEach(async () => { vi.restoreAllMocks(); - await i18n.init({ lng: 'en-US', resources: { 'en-US': { pluginGroups: enGroups } } }); + // Same as the application (src/i18n.ts): React escapes, i18next must not. + await i18n.init({ lng: 'en-US', resources: { 'en-US': { pluginGroups: enGroups } }, interpolation: { escapeValue: false } }); }); describe('native group view helpers', () => { @@ -71,9 +72,9 @@ describe('native group view helpers', () => { const result = saveGroupItems([ { key: 'a', name: 'Alpha' }, { key: 'b', name: 'Beta' }, { key: 'c', name: 'Gamma' }, ], null, save, reload, t, true); - await expect(result).rejects.toThrow('Failed plugins:\nBeta (b): disk full'); - await expect(result).rejects.toThrow('Saved plugins: Alpha (a), Gamma (c)'); - await expect(result).rejects.toThrow('Saved 2; failed 1'); + // Counts first, then one line per failure; the succeeded ones are only counted. + await expect(result).rejects.toThrow('Saved 2; failed 1.\n\nBeta (b): disk full'); + await expect(result).rejects.not.toThrow('Alpha (a)'); expect(confirm.mock.lastCall?.[0]).toContain('3 plugins'); expect(confirm.mock.lastCall?.[0]).not.toContain('atomic'); expect(confirm.mock.lastCall?.[0]).toContain('Alpha (a), Beta (b), Gamma (c)'); @@ -89,6 +90,25 @@ describe('native group view helpers', () => { expect(save).toHaveBeenCalledExactlyOnceWith('a', 'Ops'); }); + it('rewords a file that changed after it was checked and keeps the server text as details', async () => { + const raw = 'Failed to update workflow: /home/u/.flocks/plugins/workflows/hq changed after it was checked; check it again and retry.'; + const save = vi.fn().mockRejectedValue(new Error(raw)); + const error = await saveGroupItems([{ key: 'hq', name: 'SOC' }], 'Ops', save, vi.fn(), t, false, 'workflow').catch((e: unknown) => e); + expect(error).toBeInstanceOf(GroupSaveError); + expect((error as GroupSaveError).message).toBe('Saved 0; failed 1.\n\nSOC (hq): It changed after it was checked. Refresh and try again.'); + expect((error as GroupSaveError).message).not.toContain('/home/u'); + expect((error as GroupSaveError).details).toBe(`SOC (hq): ${raw}`); + }); + + it('names what the page groups instead of plugins', async () => { + expect(() => assertGroupItemsEditable([{ key: 'rex', name: 'Rex', readOnlyReason: 'built-in' }], t, 'agent')) + .toThrow('Groups cannot be changed for these agents: Rex (rex)'); + await expect(saveGroupItems([], 'Ops', vi.fn(), vi.fn(), t, false, 'device')).rejects.toThrow('This device or group is unavailable.'); + const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false); + await expect(saveGroupItems([{ key: 'a', name: 'A' }], null, vi.fn(), vi.fn(), t, true, 'skill')).rejects.toBeInstanceOf(GroupActionCancelled); + expect(confirm.mock.lastCall?.[0]).toContain('Move these 1 skills'); + }); + it('does not write or report saved when the actual-scope confirmation is cancelled', async () => { vi.spyOn(window, 'confirm').mockReturnValue(false); const save = vi.fn(); diff --git a/webui/src/components/plugin-groups/groupView.ts b/webui/src/components/plugin-groups/groupView.ts index 943ba0254..d405bd897 100644 --- a/webui/src/components/plugin-groups/groupView.ts +++ b/webui/src/components/plugin-groups/groupView.ts @@ -18,6 +18,13 @@ export interface GroupNavEntry { /** null is All; the empty string is Ungrouped. Neither is a group name. */ export type GroupSelection = string | null; +/** What a page groups; messages name it ("拖动智能体到分组") instead of the generic "plugin". */ +export type GroupItemKind = 'plugin' | 'agent' | 'skill' | 'workflow' | 'tool' | 'mcp' | 'api' | 'device'; +/** `{{noun}}` / `{{nouns}}` for pluginGroups messages that name the grouped items. */ +export const groupNoun = (t: TFunction, kind: GroupItemKind = 'plugin') => ({ + noun: t(`pluginGroups:noun.${kind}`), + nouns: t(`pluginGroups:nouns.${kind}`), +}); export const groupItemLabel = (item: GroupNavItem): string => item.name === item.key ? item.name : `${item.name} (${item.key})`; export const groupName = (value?: string | null): string => value?.trim() ?? ''; @@ -61,10 +68,26 @@ export function orderGroupNames(names: string[], saved: unknown): string[] { */ export class GroupActionCancelled extends Error {} -export function assertGroupItemsEditable(items: readonly GroupNavItem[], t: TFunction): void { +/** A batch that did not fully succeed: `message` is for people, `details` keeps the server's own words. */ +export class GroupSaveError extends Error { + constructor(message: string, readonly details = '') { + super(message); + this.name = 'GroupSaveError'; + } +} + +/** Server failures said in the user's words; anything else is shown as the server said it. */ +function groupFailureReason(raw: string, t: TFunction, kind: GroupItemKind): string { + // flocks.tool.nofollow: the file (or a link on its way) is no longer the one checked before writing. + if (/changed after it was checked/i.test(raw)) return t('pluginGroups:errors.changedAfterCheck'); + return raw || t('pluginGroups:errors.write', groupNoun(t, kind)); +} + +export function assertGroupItemsEditable(items: readonly GroupNavItem[], t: TFunction, kind: GroupItemKind = 'plugin'): void { const readOnly = items.filter((item) => item.readOnlyReason); if (readOnly.length) { throw new Error(t('pluginGroups:errors.readOnlyMembers', { + ...groupNoun(t, kind), items: readOnly.map(groupItemLabel).join(', '), })); } @@ -77,14 +100,17 @@ export async function saveGroupItems( reload: () => Promise, t: TFunction, confirmScope = false, + kind: GroupItemKind = 'plugin', ): Promise { - if (!items.length) throw new Error(t('pluginGroups:errors.missing')); - assertGroupItemsEditable(items, t); + const nouns = groupNoun(t, kind); + if (!items.length) throw new Error(t('pluginGroups:errors.missing', nouns)); + assertGroupItemsEditable(items, t, kind); if (confirmScope) { const target = group === null ? t('pluginGroups:ungrouped') : groupLabel(group, t); const confirmed = await requestConfirm({ title: t('pluginGroups:confirmScopeTitle', { group: target }), description: t('pluginGroups:confirmScope', { + ...nouns, count: items.length, group: target, items: items.map(groupItemLabel).join(', '), @@ -95,13 +121,18 @@ export async function saveGroupItems( } const failures: string[] = []; - const succeeded: string[] = []; + // The server's own words (with paths) for the technical details, only where they were reworded. + const details: string[] = []; + let succeeded = 0; for (const item of items) { try { await save(item.key, group); - succeeded.push(groupItemLabel(item)); + succeeded += 1; } catch (error) { - failures.push(`${groupItemLabel(item)}: ${extractErrorMessage(error, t('pluginGroups:errors.write'))}`); + const raw = extractErrorMessage(error, ''); + const reason = groupFailureReason(raw, t, kind); + failures.push(t('pluginGroups:errors.failedItem', { item: groupItemLabel(item), reason })); + if (raw && raw !== reason) details.push(`${groupItemLabel(item)}: ${raw}`); } } let refreshError = ''; @@ -109,11 +140,8 @@ export async function saveGroupItems( refreshError = `${t('pluginGroups:errors.refresh')} ${extractErrorMessage(error, '')}`; } if (failures.length || refreshError) { - throw new Error([ - t('pluginGroups:errors.partial', { succeeded: succeeded.length, failed: failures.length }), - succeeded.length ? `${t('pluginGroups:errors.succeededItems')} ${succeeded.join(', ')}` : '', - ...(failures.length ? [t('pluginGroups:errors.failedItems'), ...failures] : []), - refreshError, - ].filter(Boolean).join('\n')); + const summary = t('pluginGroups:errors.partial', { succeeded, failed: failures.length }); + const body = [...failures, refreshError].filter(Boolean).join('\n'); + throw new GroupSaveError(body ? `${summary}\n\n${body}` : summary, details.join('\n')); } } diff --git a/webui/src/locales/en-US/agent.json b/webui/src/locales/en-US/agent.json index 37106261b..17a3713f2 100644 --- a/webui/src/locales/en-US/agent.json +++ b/webui/src/locales/en-US/agent.json @@ -68,7 +68,8 @@ "loadingSkills": "Loading skills...", "primaryModeLabel": "Primary (Primary Agent)", "subagentModeLabel": "Subagent (Sub-Agent)", - "nativeReadOnlyMessage": "Built-in agents only support editing the model, temperature, and sub-agent enabled state; other settings are maintained by the system", + "nativeReadOnlyMessage": "The {{name}} primary agent supports changing only its model and temperature.", + "nativeSubagentReadOnlyMessage": "The built-in subagent {{name}} supports changing only its model and temperature.", "rexAssistWrite": "Rex Assist Writing", "color": "Color", "colorOptional": "(Optional)" @@ -132,7 +133,8 @@ "emptyStateTitle": "No editing conversation yet", "guidePanelTitle": "Rex Assisted Editing", "guidePanelDesc": "Choose an editing entry. Rex will use the current Agent configuration to guide prompt, responsibility, permission, and parameter changes.", - "nativeGuidePanelDesc": "This is a built-in Agent. Only model and temperature can be saved, so Rex will guide model choice, temperature strategy, and validation.", + "nativeGuidePanelDesc": "The {{name}} primary agent supports changing only its model and temperature; Rex guides the change through model choice, temperature and how to verify it.", + "nativeSubagentGuidePanelDesc": "The built-in subagent {{name}} supports changing only its model and temperature; Rex guides the change through model choice, temperature and how to verify it.", "guideSectionTitle": "Editing Guides", "caseSectionTitle": "Editing Cases", "guideActions": [ diff --git a/webui/src/locales/en-US/auth.json b/webui/src/locales/en-US/auth.json index 0af8e9474..bc0a1e054 100644 --- a/webui/src/locales/en-US/auth.json +++ b/webui/src/locales/en-US/auth.json @@ -25,6 +25,8 @@ "title": "Sign in to {{productName}}", "description": "Sign in to this {{productName}} instance with your local account", "failed": "Sign in failed", + "usernameRequired": "Enter a username.", + "passwordRequired": "Enter a password.", "recoverUsername": "Forgot your username? Sign in to the machine running {{productName}} and run", "recoverPassword": "Recover password: after confirming the username, run" }, @@ -53,7 +55,7 @@ "pageDescription": "Manage local account and password.", "sectionTitle": "Account", "listTitle": "Local accounts", - "sectionDescription": "Manage the current administrator account and password.", + "sectionDescription": "Manage the current account and password.", "columnUsername": "Username", "columnRole": "Role", "columnLastLogin": "Last sign-in", diff --git a/webui/src/locales/en-US/channel.json b/webui/src/locales/en-US/channel.json index f49707773..f0a9e77c1 100644 --- a/webui/src/locales/en-US/channel.json +++ b/webui/src/locales/en-US/channel.json @@ -96,7 +96,7 @@ "visibleAgentsSelectedCount": "{{first}}, {{second}}, and {{count}} selected", "visibleAgentsNoOptions": "No agents available", "permissionMode": "Permission Mode", - "permissionModeHint": "Default permission mode for this channel session; it can also be changed from the Session page.", + "permissionModeHint": "Default permission mode for this channel’s sessions; each session can also be adjusted on its own.", "permissionModeReadonly": "readonly", "permissionModeRequireConfirm": "require-confirm", "permissionModeAutoConfirmAll": "auto-allow-all" diff --git a/webui/src/locales/en-US/common.json b/webui/src/locales/en-US/common.json index 7b60d9a4f..9fde432a0 100644 --- a/webui/src/locales/en-US/common.json +++ b/webui/src/locales/en-US/common.json @@ -114,6 +114,8 @@ "createTitle": "Create {{entityType}}", "editTitle": "Edit {{entityType}}", "editTitleWithName": "Edit {{entityType}}: {{entityName}}", + "viewTitle": "{{entityType}} details", + "viewTitleWithName": "{{entityType}} details: {{entityName}}", "defaultCreate": "Create", "defaultSave": "Save", "tabDetails": "Details", diff --git a/webui/src/locales/en-US/flockspro.json b/webui/src/locales/en-US/flockspro.json index 4616b8c0f..4db66b1ff 100644 --- a/webui/src/locales/en-US/flockspro.json +++ b/webui/src/locales/en-US/flockspro.json @@ -1,5 +1,5 @@ { - "description": "Complete console account login, upgrade application, and upgrade execution locally.", + "description": "Sign in with a cloud account to apply for an enterprise licence, then upgrade to the enterprise edition.", "loading": "Loading...", "consoleLogin": { "title": "Console Account Login", @@ -14,13 +14,13 @@ "previousTitle": "Flocks Pro {{version}}", "previousDescription": "This machine has the previous enterprise edition (the Python one), not yet moved to the new enterprise edition.", "licensedTitle": "Flocks Pro", - "licensedDescription": "This machine has an enterprise licence, not yet moved to the new enterprise edition.", + "licensedDescription": "Enterprise licence obtained; not upgraded yet.", "openTitle": "Upgrade to Flocks Pro", "openDescription": "Review the current license information, submit applications, and track approval status.", "previousNote": "The enterprise edition is a separate installer now, and the previous one gets no more releases. The open part keeps upgrading with flocks update; the previous edition's audit logs, security configuration, user management and prompt redaction pages come back with the new enterprise edition.", - "licensedNote": "The licence is kept on this machine; the new enterprise edition takes it over when you upgrade.", + "licensedNote": "The licence is saved on this machine and will be used after upgrading to the enterprise edition.", "lapsedNote": "The licence on this machine is no longer valid. Once it is renewed or a new one is issued, the new enterprise edition goes by that one.", - "openNote": "The enterprise edition is a separate installer: it takes this install's data over (moved into its own PostgreSQL on its first start) and is used the same way." + "openNote": "The enterprise edition is a separate installer: its first start copies the open edition’s data into its bundled PostgreSQL, and everything is used as before." }, "licenceStatus": { "commercial": "Commercial", @@ -121,11 +121,11 @@ }, "upgrade": { "title": "Enterprise updates", - "currentPrevious": "This is the previous enterprise edition {{version}}. Check what new enterprise edition Console has for this machine's platform; upgrading downloads and checks it and hands it to its installer, and the service restarts by itself.", - "currentOpen": "This is the open edition. Check what new enterprise edition Console has for this machine's platform; upgrading downloads and checks it and hands it to its installer, and the service restarts by itself.", - "whatChanges": "After the upgrade the program is in {{root}}, the data stays where it is (moved into the bundled PostgreSQL on the first start; the original is kept) and the machine's licence is carried over; flocks start|stop|restart|status|logs|update work as before.", - "whatChangesWindows": "After the upgrade the program is in {{root}} and runs as the FlocksPro Core service, started with the machine; the open edition's data is copied for it (the original stays) and the machine's licence is carried over. Windows asks for an administrator while it installs.", - "systemd": "systemd runs this machine (the open edition's offline package): the installer runs as root. The page can download it; then run the command it gives.", + "currentPrevious": "This is the previous enterprise edition {{version}}. The service restarts automatically during the upgrade.", + "currentOpen": "The service restarts automatically during the upgrade.", + "whatChanges": "After the upgrade the program is in {{root}} and the data directory stays the same; the first start copies the existing data into the bundled PostgreSQL, and the original data files are kept but no longer updated; the machine’s licence is carried over. flocks start|stop|restart|status|logs|update keep managing the service.", + "whatChangesWindows": "After the upgrade the program is in {{root}} and the enterprise edition starts at boot as the \"FlocksPro Core\" service; the open edition’s data is copied for the enterprise edition, and the original directory is kept but no longer updated; the machine’s licence is carried over. Windows asks for administrator confirmation during the installation.", + "systemd": "This open edition is managed by systemd. Download the installer and run the command shown here with root privileges.", "prepare": "{{account}} cannot write {{root}} yet: run this once as root, then come back.", "recheck": "Done, check again", "check": "Check for a new version", @@ -136,7 +136,7 @@ }, "progress": { "downloading": "Downloading the new enterprise edition {{version}}", - "installing": "The installer runs ({{version}}): the open edition stops first, and the enterprise edition's first start moves the data, which can take a few minutes. This page reloads once it is done.", + "installing": "Upgrading to {{version}}. The open edition stops, and the enterprise edition’s first start migrates the data, which can take a few minutes; the page refreshes automatically when the installation finishes.", "restarting": "The open edition has stopped and the enterprise edition is starting for the first time (moving the data). The page reloads if it listens on this address; otherwise open the address the installer printed.", "finished": "The new enterprise edition {{version}} is installed; reload the page.", "failed": "The install did not finish and the open edition keeps running; the installer output below says why.", diff --git a/webui/src/locales/en-US/model.json b/webui/src/locales/en-US/model.json index 3fdec1a30..326aa1882 100644 --- a/webui/src/locales/en-US/model.json +++ b/webui/src/locales/en-US/model.json @@ -166,7 +166,7 @@ "providerType": "Provider Type", "baseUrl": "Base URL", "baseUrlOptional": "(optional, leave empty for default)", - "baseUrlRequired": "Please enter Base URL", + "baseUrlRequired": "Enter the API proxy URL.", "threatbookIoNodeNotice": "The international node (threatbook.io) is not yet available. The China node (threatbook.cn) is used for now.", "apiKey": "API Key", "ollamaNoKey": "(Ollama usually doesn't need this)", @@ -277,6 +277,7 @@ "importing": "Adding…", "empty": "The service returned no models. Fetch again or add a model manually.", "failed": "Could not fetch models. Review the message above, then retry or add a model manually.", + "requestFailed": "Could not fetch the model list. Check the API proxy URL and the network, then try again; if it still fails, contact your administrator.", "importSummary": "Added {{added}}, already present {{skipped}}, failed {{failed}}.", "retryFailed": "Retry failed models", "importPartial": "Credentials saved. Some models could not be added; review the results and retry.", @@ -296,9 +297,9 @@ "models_discovered": "Select the models you want to add.", "catalog_fallback": "This service does not expose a model list. Showing built-in recommendations.", "discovery_unsupported": "Model discovery is not available for this service. Add models manually.", - "missing_base_url": "Enter the Base URL first.", + "missing_base_url": "Enter the API proxy URL.", "missing_credentials": "Enter the required credentials first.", - "invalid_base_url": "Check that the Base URL is a valid, complete URL.", + "invalid_base_url": "The API proxy URL is not valid. Enter the full address.", "authentication_failed": "Authentication failed. Check your API key.", "permission_denied": "Your credentials do not have permission to list models.", "rate_limited": "Too many requests. Try again later.", @@ -416,10 +417,11 @@ "inventorySaveFailedAfterCredentials": "Connection information was saved, but the model list was not saved: {{error}}. Check and retry.", "saving": "Saving…", "checkKey": "Check connection", - "checkKeyHint": "Check whether the API key is valid.", - "checkModelListHint": "Verify the API key by fetching the live model list.", + "checkKeyHint": "Check whether the connection settings work.", + "checkModelListHint": "Check whether the connection settings work by fetching the model list.", "check": "Check", "checkingKey": "Checking…", + "checkFailed": "The connection check failed. Check the API proxy URL and the network, then try again; if it still fails, contact your administrator.", "keyUnverified": "This service cannot independently verify the key.", "supports_tools": "Tools", "supports_vision": "Vision", @@ -429,9 +431,9 @@ "models_discovered": "Select the models you want to add.", "catalog_fallback": "This service cannot independently verify the key.", "discovery_unsupported": "This service cannot independently verify the key.", - "missing_base_url": "Enter the Base URL first.", + "missing_base_url": "Enter the API proxy URL.", "missing_credentials": "Enter the required credentials first.", - "invalid_base_url": "Check that the Base URL is a valid, complete URL.", + "invalid_base_url": "The API proxy URL is not valid. Enter the full address.", "authentication_failed": "Authentication failed. Check your API key.", "permission_denied": "Insufficient permissions to verify the key.", "rate_limited": "Too many requests. Try again later.", diff --git a/webui/src/locales/en-US/nav.json b/webui/src/locales/en-US/nav.json index adf1149ff..ddbc10f6d 100644 --- a/webui/src/locales/en-US/nav.json +++ b/webui/src/locales/en-US/nav.json @@ -197,16 +197,17 @@ "renameFolder": "Rename folder", "folderName": "Folder name", "folderNamePlaceholder": "e.g. Project files", - "folderNameEmpty": "Enter a folder name", + "folderNameEmpty": "Enter a folder name.", "folderPath": "Directory", "folderPathPlaceholder": "Choose or type a directory", "folderPathHint": "Sessions run in this directory; it is created if missing.", - "folderPathEmpty": "Enter a directory", + "folderPathEmpty": "Choose or enter a directory.", "chooseFolder": "Browse", "parentFolder": "Parent folder", "noSubfolders": "No subfolders", "folderBrowseFailed": "Failed to read directory", - "folderSaveFailed": "Save failed", + "folderCreateFailed": "Could not create the folder. Try again.", + "folderRenameFailed": "Could not rename the folder. Try again.", "createFolder": "Create folder", "saveName": "Save name", "cancel": "Cancel", diff --git a/webui/src/locales/en-US/pluginGroups.json b/webui/src/locales/en-US/pluginGroups.json index 1ce4837b8..3ea557fff 100644 --- a/webui/src/locales/en-US/pluginGroups.json +++ b/webui/src/locales/en-US/pluginGroups.json @@ -1,7 +1,27 @@ { "title": "Groups", "navigation": "Filter by group", - "countsDescription": "Drag a plugin onto a group to move it.", + "countsDescription": "Drag {{nouns}} onto a group.", + "noun": { + "plugin": "plugin", + "agent": "agent", + "skill": "skill", + "workflow": "workflow", + "tool": "tool", + "mcp": "MCP service", + "api": "API service", + "device": "device" + }, + "nouns": { + "plugin": "plugins", + "agent": "agents", + "skill": "skills", + "workflow": "workflows", + "tool": "tools", + "mcp": "MCP services", + "api": "API services", + "device": "devices" + }, "defaultNames": { "平台集成": "Platform Integrations", "安全研判": "Security Analysis", @@ -37,7 +57,7 @@ "saved": "Group changes saved.", "cancel": "Cancel", "close": "Close", - "confirmScope": "Move these {{count}} plugins to “{{group}}”?\n{{items}}\nNo plugins will be deleted.", + "confirmScope": "Move these {{count}} {{nouns}} to “{{group}}”?\n{{items}}\nNo {{nouns}} will be deleted.", "confirmScopeTitle": "Move to “{{group}}”", "confirmScopeAction": "Move", "dialog": { @@ -45,30 +65,34 @@ "renameTitle": "Rename group", "moveTitle": "Edit group for {{name}}", "name": "Group name", - "firstPlugin": "First editable plugin", - "choosePlugin": "Choose a plugin", + "nameHint": "1–32 characters, not counting leading/trailing spaces; no control characters.", + "firstPlugin": "First editable {{noun}}", + "choosePlugin": "Select {{noun}}", "destination": "Destination group" }, "validation": { - "length": "Use 1–32 characters, excluding leading/trailing spaces and control characters.", "duplicate": "A group with this name already exists. Choose another name.", - "firstPlugin": "Choose an editable plugin." + "required": "Enter a group name.", + "tooLong": "Group names can be at most 32 characters.", + "controlChars": "Group names cannot contain control characters.", + "firstPlugin": "Choose an editable {{noun}}." }, "readOnly": { - "system": "The group of a built-in plugin cannot be changed.", + "system": "The group of a built-in {{noun}} cannot be changed.", "builtinSkill": "The group of a built-in skill cannot be changed.", "externalSkill": "Skills from external directories (such as ~/.claude/skills) cannot be regrouped here.", "admin": "You do not have permission to change groups.", "catalog": "Install or configure this service first.", - "noEditable": "No plugins are available for grouping." + "noEditable": "No {{nouns}} can be grouped yet." }, "errors": { - "missing": "This plugin or group is unavailable. Refresh and try again.", - "readOnlyMembers": "Groups cannot be changed for these plugins: {{items}}", - "write": "Could not save this plugin’s group.", + "missing": "This {{noun}} or group is unavailable. Refresh and try again.", + "readOnlyMembers": "Groups cannot be changed for these {{nouns}}: {{items}}", + "write": "Could not save this {{noun}}’s group.", "partial": "Saved {{succeeded}}; failed {{failed}}.", - "succeededItems": "Saved plugins:", - "failedItems": "Failed plugins:", + "failedItem": "{{item}}: {{reason}}", + "changedAfterCheck": "It changed after it was checked. Refresh and try again.", + "details": "Technical details", "refresh": "Could not refresh the list. Refresh and try again." }, "drag": { diff --git a/webui/src/locales/en-US/task.json b/webui/src/locales/en-US/task.json index 33cc78a80..d67307e26 100644 --- a/webui/src/locales/en-US/task.json +++ b/webui/src/locales/en-US/task.json @@ -187,6 +187,7 @@ "recurring": "Recurring", "selectFrequency": "Select frequency", "customOption": "Custom...", + "cronInvalid": "Invalid cron expression. Use five fields (minute hour day month weekday), e.g. 0 6 * * * runs daily at 06:00 in the selected timezone. Six-field cron and shortcuts such as @daily are not supported.", "customCronLabel": "Custom Cron Expression", "timezoneLabel": "Timezone", "timezoneShanghai": "Asia/Shanghai (Beijing Time UTC+8)", diff --git a/webui/src/locales/en-US/tool.json b/webui/src/locales/en-US/tool.json index 3b3634734..0e5441e3b 100644 --- a/webui/src/locales/en-US/tool.json +++ b/webui/src/locales/en-US/tool.json @@ -143,7 +143,7 @@ "api": { "emptyStateTitle": "No setup conversation yet", "guidePanelTitle": "Rex Assisted Setup", - "guidePanelDesc": "Choose a guide or case. Rex will load the tool-builder skill, confirm API docs, auth, and output shape, then generate a YAML tool.", + "guidePanelDesc": "Choose a guide or case. Rex will confirm the API docs, authentication and output format, then generate the tool.", "guideSectionTitle": "Setup Guides", "caseSectionTitle": "Setup Cases", "guideActions": [ @@ -184,7 +184,7 @@ "local": { "emptyStateTitle": "No creation conversation yet", "guidePanelTitle": "Rex Assisted Creation", - "guidePanelDesc": "Choose a guide or case. Rex will load the tool-builder skill, confirm inputs, outputs, implementation, and smoke tests, then generate a local Python tool.", + "guidePanelDesc": "Choose a guide or case. Rex will confirm the inputs and outputs, implementation and smoke tests, then generate a local Python tool.", "guideSectionTitle": "Creation Guides", "caseSectionTitle": "Creation Cases", "guideActions": [ @@ -269,7 +269,14 @@ "startCommandRequired": "Please enter start command", "serviceUrlRequired": "Please enter service URL", "chatPrompt": "Help me connect an MCP service named \"{{name}}\"", - "chatSubtitle": "Let Rex help you connect MCP services via chat" + "chatSubtitle": "Let Rex help you connect MCP services via chat", + "errors": { + "nameRequired": "Enter a service name.", + "commandRequired": "Enter a start command.", + "urlRequired": "Enter the service URL.", + "urlScheme": "The service URL must start with http:// or https://.", + "invalidHeaders": "Enter a valid JSON object." + } }, "addAPI": { @@ -641,7 +648,7 @@ "addFailed": "Add failed: {{error}}", "mcpNameRequired": "Please enter MCP service name", "apiKeyRequired": "Please enter API Key", - "invalidHeaders": "Extra headers must be a valid JSON object", + "invalidHeaders": "Enter a valid JSON object.", "credSaved": "Credentials saved", "saveFailed": "Save failed: {{error}}", "testFailed": "Test failed: {{error}}", @@ -701,6 +708,7 @@ "mcpHintDesc": "Switch to the \"Workbench\" tab, tell Rex what MCP service you want to connect, and it will automatically complete the configuration.", "connSuccess": "Connected", "connFailed": "Connection Failed", + "mcpConnectFailed": "Could not connect to the MCP service. Check the service URL, the service status and the network, then try again; if it still fails, contact your administrator.", "addFailedTitle": "Add Failed" }, diff --git a/webui/src/locales/en-US/update.json b/webui/src/locales/en-US/update.json index 7e4a7e15a..c7ef956b2 100644 --- a/webui/src/locales/en-US/update.json +++ b/webui/src/locales/en-US/update.json @@ -83,8 +83,8 @@ "restarting": "Starting the service again; this page will say when it is done.", "restarted": "The service was restarted and data was not touched. The components this upgrade installed cannot be undone and may already be the new ones: check ~/.flocks/run/upgrade-result.json on the server, resolve the cause, then upgrade again." }, - "enterpriseDesc": "This machine has an enterprise licence, so this upgrades it to the new enterprise edition: the program goes to {{root}}, its data and licence stay, and the web address stays the same. The open edition stops first, and the first start migrates data, which can take minutes.", - "enterpriseInstalling": "The open edition stops first, and the first start of the enterprise edition migrates data, which can take minutes. This page refreshes by itself when it is done.", + "enterpriseDesc": "The program will be installed in {{root}}. Existing data and the licence are carried over, and the web address stays the same. The open edition stops during the upgrade; the first start migrates data, which can take a few minutes.", + "enterpriseInstalling": "The open edition stops, and the enterprise edition’s first start migrates the data, which can take a few minutes; the page refreshes automatically when the installation finishes.", "enterpriseStageLabels": { "fetching": "Download the new enterprise installer", "restarting": "Install the new enterprise edition" diff --git a/webui/src/locales/en-US/workflow.json b/webui/src/locales/en-US/workflow.json index 096e8790f..92cc711d7 100644 --- a/webui/src/locales/en-US/workflow.json +++ b/webui/src/locales/en-US/workflow.json @@ -299,7 +299,7 @@ "publishing": "Publishing, please wait...", "publishAsApi": "Publish as API Service", "guidePanelTitle": "Rex Assisted Publishing", - "guidePanelDesc": "Choose a publishing method. Rex will read guide.md and the config store first, then help you confirm, apply, or start it.", + "guidePanelDesc": "Choose a publishing method. Rex will guide you through the configuration and confirm whether to apply or start it.", "cardGuideTitle": "Flocks Assisted Config", "cardGuideAction": "Assist config", "cardGuideApiFocus": "API publish config", @@ -507,7 +507,7 @@ "contextMessage": "The user wants to create a Flocks workflow, please use the workflow-builder skill to complete it.", "emptyStateTitle": "No execution records yet", "guidePanelTitle": "Rex Assisted Creation", - "guidePanelDesc": "Choose a guide or creation case. Rex will follow the workflow-builder skill to confirm scenario, inputs, outputs, node flow, and sample data before writing files.", + "guidePanelDesc": "Choose a guide or creation case. Rex will confirm the scenario, inputs and outputs, node flow and sample data, then generate the workflow.", "generateEditDocPrompt": "This new task was triggered by the user clicking \"Generate Spec\". The button means: first use the workflow-builder skill to generate workflow.md, then let \"Generate Workflow\" create workflow.json from the confirmed workflow.md.\n\nPlease proceed as follows:\n1. Load and follow the workflow-builder skill first.\n2. You must use the question tool to ask whether I want a Chinese or English workflow spec; ask only one question at a time and allow custom input.\n3. If the left editor already has content, treat it as a draft. If it is empty, use the question tool to collect the business scenario, inputs, outputs, trigger mode, node flow, samples, and acceptance criteria needed to create the workflow.\n4. Use the workflow_zh.md / workflow_en.md template structure from the workflow-builder skill, but generate only one workflow.md file.\n5. Make workflow.md easy for humans to edit: explain purpose, scenarios, inputs, outputs, node flow, editable points, samples, and acceptance checks.\n6. Before writing workflow.md, show a diff and wait for my confirmation; after confirmation, write workflow.md under the new workflow directory.\n7. When finished, remind me that I can click \"Generate Workflow\" to generate workflow.json from workflow.md.\n\nCurrent left editor content:\n~~~markdown\n{{editDocContent}}\n~~~", "generateWorkflowPrompt": "The user clicked the \"Generate Workflow\" button. This button means: generate the formal Flocks workflow from the current workflow.md in the left editor, with workflow.json as the core machine-executable artifact.\n\nPlease follow the workflow-builder skill:\n1. Load and follow the workflow-builder skill first.\n2. Treat the workflow.md content below as the primary source of intent; do not interpret this as a request to rewrite workflow.md.\n3. If no workflow directory exists yet, first confirm/generate a suitable workflow ID and directory from workflow.md, then write workflow.md and workflow.json. If a directory already exists, read the existing workflow.json and update the machine definition from workflow.md.\n4. The generated workflow.json must be valid JSON, and nodes plus edges must form a complete flow diagram.\n5. Before writing workflow.json, show a diff and wait for my confirmation.\n6. When finished, explain what changed in workflow.json and how I should test it.\n\nCurrent editor content of workflow.md:\n~~~markdown\n{{editDocContent}}\n~~~", "guideSectionTitle": "Creation Guides", diff --git a/webui/src/locales/en-US/workspace.json b/webui/src/locales/en-US/workspace.json index 924482082..903e3d14e 100644 --- a/webui/src/locales/en-US/workspace.json +++ b/webui/src/locales/en-US/workspace.json @@ -11,6 +11,9 @@ "newDir": "New folder", "upload": "Upload file", "dirNamePlaceholder": "Folder name", + "dirNameRequired": "Enter a directory name.", + "dirNameExists": "A directory with this name already exists here. Choose another name.", + "dirNameTakenByFile": "A file with this name already exists here. Choose another name.", "create": "Create", "dropHere": "Drop files here to upload", "emptyDir": "Empty folder — drop files or click upload", diff --git a/webui/src/locales/zh-CN/agent.json b/webui/src/locales/zh-CN/agent.json index 313ad5e1c..75b16e52f 100644 --- a/webui/src/locales/zh-CN/agent.json +++ b/webui/src/locales/zh-CN/agent.json @@ -68,7 +68,8 @@ "loadingSkills": "加载 Skill 列表...", "primaryModeLabel": "Primary(主 Agent)", "subagentModeLabel": "Subagent(子 Agent)", - "nativeReadOnlyMessage": "内置 Agent 仅支持修改模型、温度,以及子 Agent 的启用状态,其他配置由系统维护", + "nativeReadOnlyMessage": "{{name}} 主 Agent 仅支持修改模型和温度。", + "nativeSubagentReadOnlyMessage": "内置子 Agent {{name}} 仅支持修改模型和温度。", "rexAssistWrite": "Rex 协助编写", "color": "颜色", "colorOptional": "(可选)" @@ -132,7 +133,8 @@ "emptyStateTitle": "暂无编辑对话", "guidePanelTitle": "Rex 辅助修改", "guidePanelDesc": "选择一个编辑入口,Rex 会基于当前 Agent 配置,引导你调整 Prompt、职责边界、工具权限和参数。", - "nativeGuidePanelDesc": "这是内置 Agent,只支持保存模型和温度;Rex 会围绕模型选择、温度策略和验证方式引导修改。", + "nativeGuidePanelDesc": "{{name}} 主 Agent 仅支持修改模型和温度;Rex 会围绕模型选择、温度策略和验证方式引导修改。", + "nativeSubagentGuidePanelDesc": "内置子 Agent {{name}} 仅支持修改模型和温度;Rex 会围绕模型选择、温度策略和验证方式引导修改。", "guideSectionTitle": "编辑引导", "caseSectionTitle": "编辑案例", "guideActions": [ diff --git a/webui/src/locales/zh-CN/auth.json b/webui/src/locales/zh-CN/auth.json index e0f5e7391..e6eaa3c21 100644 --- a/webui/src/locales/zh-CN/auth.json +++ b/webui/src/locales/zh-CN/auth.json @@ -25,8 +25,10 @@ "title": "{{productName}} 登录", "description": "使用本地账号登录当前 {{productName}} 实例", "failed": "登录失败", - "recoverUsername": "忘记账号名:请登录 {{productName}} 所在机器后执行", - "recoverPassword": "找回密码:确认账号名后执行" + "usernameRequired": "请输入用户名。", + "passwordRequired": "请输入密码。", + "recoverUsername": "忘记用户名:请登录 {{productName}} 所在机器后执行", + "recoverPassword": "找回密码:确认用户名后执行" }, "setup": { "title": "初始化管理员账号", @@ -53,7 +55,7 @@ "pageDescription": "管理本地账号与密码。", "sectionTitle": "账号管理", "listTitle": "本地账号", - "sectionDescription": "管理当前管理员账号与密码。", + "sectionDescription": "管理当前账号与密码。", "columnUsername": "用户名", "columnRole": "角色", "columnLastLogin": "最近登录", @@ -69,7 +71,7 @@ "resetFailedToast": "重置失败", "resetDialogTitle": "一次性密码已生成", "resetDialogDescription": "当前账号已被重置,请先复制一次性密码,关闭后将返回登录页。", - "resetDialogUsernameLabel": "账号名", + "resetDialogUsernameLabel": "用户名", "resetDialogPasswordLabel": "一次性密码", "resetDialogWarning": "请先复制保存,关闭弹窗后将无法再次直接看到这串密码。", "resetDialogClose": "关闭", diff --git a/webui/src/locales/zh-CN/channel.json b/webui/src/locales/zh-CN/channel.json index 746f4819b..53041fd61 100644 --- a/webui/src/locales/zh-CN/channel.json +++ b/webui/src/locales/zh-CN/channel.json @@ -96,7 +96,7 @@ "visibleAgentsSelectedCount": "{{first}}、{{second}} 等 {{count}} 个", "visibleAgentsNoOptions": "暂无可选 Agent", "permissionMode": "权限模式", - "permissionModeHint": "该 channel session 的默认权限模式;Session 页面也可以单独调整。", + "permissionModeHint": "设置通道会话的默认权限模式,也可在会话中单独调整。", "permissionModeReadonly": "readonly", "permissionModeRequireConfirm": "require-confirm", "permissionModeAutoConfirmAll": "auto-allow-all" diff --git a/webui/src/locales/zh-CN/common.json b/webui/src/locales/zh-CN/common.json index 4c2e37222..039fc028b 100644 --- a/webui/src/locales/zh-CN/common.json +++ b/webui/src/locales/zh-CN/common.json @@ -114,6 +114,8 @@ "createTitle": "创建 {{entityType}}", "editTitle": "编辑 {{entityType}}", "editTitleWithName": "编辑 {{entityType}}:{{entityName}}", + "viewTitle": "{{entityType}}详情", + "viewTitleWithName": "{{entityType}}详情:{{entityName}}", "defaultCreate": "创建", "defaultSave": "保存", "tabDetails": "详情", diff --git a/webui/src/locales/zh-CN/flockspro.json b/webui/src/locales/zh-CN/flockspro.json index 11c65d410..d90186519 100644 --- a/webui/src/locales/zh-CN/flockspro.json +++ b/webui/src/locales/zh-CN/flockspro.json @@ -1,5 +1,5 @@ { - "description": "在本地完成云账号登录、升级申请与升级执行。", + "description": "登录云账号申请企业版授权,并升级至企业版。", "loading": "加载中...", "consoleLogin": { "title": "云账号登录", @@ -12,15 +12,15 @@ }, "machine": { "previousTitle": "Flocks Pro {{version}}", - "previousDescription": "这台机器装着老企业版(Python 版),还没有升级到新企业版。", + "previousDescription": "已安装旧版企业版(Python 版),尚未升级至新企业版。", "licensedTitle": "Flocks Pro", - "licensedDescription": "这台机器有企业版授权,还没有升级到新企业版。", + "licensedDescription": "已获得企业版授权,尚未升级。", "openTitle": "升级为 Flocks Pro", "openDescription": "查看当前授权信息、提交申请并跟踪审批进度。", "previousNote": "企业版换成了单独的安装包,老企业版不再更新。开源部分照常用 flocks update 升级;老企业版的审计日志、安全配置、用户管理、Prompt 脱敏这些页面,升级到新企业版后回来。", - "licensedNote": "授权已经保存在这台机器上,升级到新企业版时会沿用它。", - "lapsedNote": "这台机器上的授权已失效;续期或重新申请之后,升级到新企业版时沿用新的授权。", - "openNote": "企业版是单独的安装包:装好后开源版的数据会迁过去(第一次启动迁进自带的 PostgreSQL),用法照旧。" + "licensedNote": "授权已保存在当前机器,升级至企业版时将沿用该授权。", + "lapsedNote": "当前机器上的授权已失效;续期或重新申请后,升级至企业版时将沿用新的授权。", + "openNote": "企业版是独立的安装包:安装后首次启动会把开源版的数据复制到企业版自带的 PostgreSQL,使用方式不变。" }, "licenceStatus": { "commercial": "商用授权", @@ -121,11 +121,11 @@ }, "upgrade": { "title": "企业版更新", - "currentPrevious": "当前是老企业版 {{version}}。检查 Console 给这台机器所在平台的新企业版,升级时下载、校验后交给安装包运行,服务会自动重启。", - "currentOpen": "当前是开源版。检查 Console 给这台机器所在平台的新企业版,升级时下载、校验后交给安装包运行,服务会自动重启。", - "whatChanges": "升级后:程序在 {{root}},数据还在原来的目录(第一次启动迁进自带的 PostgreSQL,原来的数据留着),授权沿用这台机器上的;之后照旧用 flocks start|stop|restart|status|logs|update。", - "whatChangesWindows": "升级后:程序在 {{root}},企业版作为「FlocksPro Core」服务随开机启动;开源版的数据复制一份给企业版(原来的目录留着),授权沿用这台机器上的。安装时 Windows 会弹出管理员确认框。", - "systemd": "这台机器由 systemd 管(开源版离线包):升级要以 root 运行安装包,这里可以把安装包下载好,再按给出的命令执行。", + "currentPrevious": "当前为旧版企业版 {{version}}。升级期间,服务将自动重启。", + "currentOpen": "升级期间,服务将自动重启。", + "whatChanges": "升级后:程序位于 {{root}},数据目录不变;首次启动会把现有数据复制到企业版自带的 PostgreSQL,原数据文件保留且不再更新;授权沿用当前机器上的授权。之后仍可使用 flocks start|stop|restart|status|logs|update 管理服务。", + "whatChangesWindows": "升级后:程序位于 {{root}},企业版作为「FlocksPro Core」服务随开机启动;开源版的数据会复制一份给企业版,原目录保留且不再更新;授权沿用当前机器上的授权。安装时 Windows 会弹出管理员确认框。", + "systemd": "当前开源版由 systemd 管理。请下载安装包,并使用 root 权限按页面提供的命令运行。", "prepare": "{{account}} 还不能写 {{root}}:先用 root 执行一次(只要这一次),再回来升级。", "recheck": "已执行,重新检查", "check": "检查新版本", @@ -136,7 +136,7 @@ }, "progress": { "downloading": "正在下载新企业版 {{version}}", - "installing": "安装包在运行({{version}}):开源版会先停下,企业版第一次启动要迁移数据,可能要几分钟。装好后这个页面会自动刷新。", + "installing": "正在升级至 {{version}}。开源版将停止,企业版首次启动需迁移数据,可能需要几分钟,安装完成后页面自动刷新。", "restarting": "开源版已经停下,企业版正在第一次启动(迁移数据)。它监听在这个地址时,页面会自动刷新;地址不同的话,装好后打开安装输出里的地址。", "finished": "新企业版 {{version}} 装好了,刷新页面即可。", "failed": "安装没有完成,开源版照常运行;原因看下面的安装输出。", diff --git a/webui/src/locales/zh-CN/model.json b/webui/src/locales/zh-CN/model.json index 6b4517686..d311393ff 100644 --- a/webui/src/locales/zh-CN/model.json +++ b/webui/src/locales/zh-CN/model.json @@ -121,7 +121,7 @@ "testing": "测试中", "success": "成功", "failed": "失败", - "configAdminOnly": "模型配置仅管理员可修改", + "configAdminOnly": "模型配置仅管理员可修改。", "noModelsMember": "请联系管理员添加模型" }, "status": { @@ -166,7 +166,7 @@ "providerType": "Provider 类型", "baseUrl": "Base URL", "baseUrlOptional": "(可选,留空用默认)", - "baseUrlRequired": "请填写 Base URL", + "baseUrlRequired": "请输入 API 代理 URL。", "threatbookIoNodeNotice": "国际节点(threatbook.io)尚未上线,暂使用国内节点(threatbook.cn)。", "apiKey": "API Key", "ollamaNoKey": "(Ollama 通常不需要)", @@ -277,6 +277,7 @@ "importing": "正在新增…", "empty": "服务未返回模型,可重新获取或手动添加。", "failed": "未能获取模型,请检查上方提示后重试,也可手动添加。", + "requestFailed": "获取模型列表失败,请检查 API 代理 URL 和网络后重试;仍失败请联系管理员。", "importSummary": "新增 {{added}} 个,已存在 {{skipped}} 个,失败 {{failed}} 个。", "retryFailed": "重试失败项", "importPartial": "凭据已保存,部分模型新增失败,请查看结果并重试。", @@ -296,9 +297,9 @@ "models_discovered": "已获取模型列表,请选择要新增的模型。", "catalog_fallback": "该服务不提供模型列表接口,展示内置推荐目录。", "discovery_unsupported": "该服务暂不支持获取模型列表,可手动添加。", - "missing_base_url": "请先填写 Base URL。", + "missing_base_url": "请输入 API 代理 URL。", "missing_credentials": "请先填写所需凭据。", - "invalid_base_url": "Base URL 格式有误,请检查完整地址。", + "invalid_base_url": "API 代理 URL 格式不正确,请输入完整地址。", "authentication_failed": "凭据校验失败,请检查 API Key。", "permission_denied": "当前凭据无权获取模型列表,请检查账号权限。", "rate_limited": "服务请求过于频繁,请稍后重试。", @@ -416,10 +417,11 @@ "inventorySaveFailedAfterCredentials": "连接信息已保存,模型列表保存失败:{{error}}。请检查后重试。", "saving": "正在保存…", "checkKey": "检查连接", - "checkKeyHint": "检查 API Key 是否有效。", - "checkModelListHint": "通过获取服务端模型列表验证 API Key。", + "checkKeyHint": "检查连接配置是否可用。", + "checkModelListHint": "通过获取模型列表检查连接配置是否可用。", "check": "检查", "checkingKey": "检查中…", + "checkFailed": "连接检查失败,请检查 API 代理 URL 和网络后重试;仍失败请联系管理员。", "keyUnverified": "该服务暂无法独立验证 Key。", "supports_tools": "工具调用", "supports_vision": "视觉", @@ -429,9 +431,9 @@ "models_discovered": "已获取模型列表,请选择要新增的模型。", "catalog_fallback": "该服务暂无法独立验证 Key。", "discovery_unsupported": "该服务暂无法独立验证 Key。", - "missing_base_url": "请先填写 Base URL。", + "missing_base_url": "请输入 API 代理 URL。", "missing_credentials": "请先填写所需凭据。", - "invalid_base_url": "Base URL 格式有误,请检查完整地址。", + "invalid_base_url": "API 代理 URL 格式不正确,请输入完整地址。", "authentication_failed": "凭据校验失败,请检查 API Key。", "permission_denied": "凭据权限不足,无法验证 Key。", "rate_limited": "服务请求过于频繁,请稍后重试。", diff --git a/webui/src/locales/zh-CN/nav.json b/webui/src/locales/zh-CN/nav.json index 22491b10c..567223efc 100644 --- a/webui/src/locales/zh-CN/nav.json +++ b/webui/src/locales/zh-CN/nav.json @@ -194,16 +194,17 @@ "renameFolder": "重命名文件夹", "folderName": "文件夹名称", "folderNamePlaceholder": "例如:项目资料", - "folderNameEmpty": "请填写文件夹名称", + "folderNameEmpty": "请输入文件夹名称。", "folderPath": "目录", "folderPathPlaceholder": "选择或输入目录", "folderPathHint": "会话在该目录下运行,目录不存在时会自动创建。", - "folderPathEmpty": "请填写目录", + "folderPathEmpty": "请选择或输入目录。", "chooseFolder": "浏览", "parentFolder": "上级目录", "noSubfolders": "没有子目录", "folderBrowseFailed": "读取目录失败", - "folderSaveFailed": "保存失败", + "folderCreateFailed": "文件夹创建失败,请重试。", + "folderRenameFailed": "文件夹重命名失败,请重试。", "createFolder": "创建文件夹", "saveName": "保存名称", "cancel": "取消", diff --git a/webui/src/locales/zh-CN/pluginGroups.json b/webui/src/locales/zh-CN/pluginGroups.json index ad0ecbbe8..2f097219e 100644 --- a/webui/src/locales/zh-CN/pluginGroups.json +++ b/webui/src/locales/zh-CN/pluginGroups.json @@ -1,7 +1,27 @@ { "title": "分组", "navigation": "按分组筛选", - "countsDescription": "拖动插件到分组即可归组。", + "countsDescription": "拖动{{nouns}}到分组。", + "noun": { + "plugin": "插件", + "agent": "智能体", + "skill": "技能", + "workflow": "工作流", + "tool": "工具", + "mcp": " MCP 服务", + "api": " API 服务", + "device": "设备" + }, + "nouns": { + "plugin": "插件", + "agent": "智能体", + "skill": "技能", + "workflow": "工作流", + "tool": "工具", + "mcp": " MCP 服务", + "api": " API 服务", + "device": "设备" + }, "defaultNames": { "平台集成": "平台集成", "安全研判": "安全研判", @@ -37,7 +57,7 @@ "saved": "分组更改已保存。", "cancel": "取消", "close": "关闭", - "confirmScope": "将以下 {{count}} 个插件移到“{{group}}”?\n{{items}}\n不会删除插件。", + "confirmScope": "将以下 {{count}} 个{{noun}}移到“{{group}}”?\n{{items}}\n不会删除{{noun}}。", "confirmScopeTitle": "移动到“{{group}}”", "confirmScopeAction": "确认移动", "dialog": { @@ -45,30 +65,34 @@ "renameTitle": "重命名分组", "moveTitle": "设置 {{name}} 的分组", "name": "分组名称", - "firstPlugin": "首个可编辑插件", - "choosePlugin": "选择一个插件", + "nameHint": "名称需为 1–32 个字符,不计首尾空格,不能包含控制字符。", + "firstPlugin": "选择第一个可编辑的{{noun}}", + "choosePlugin": "请选择{{noun}}", "destination": "目标分组" }, "validation": { - "length": "名称需为 1–32 个字符,不计首尾空格,不能包含控制字符。", "duplicate": "已有同名分组,请使用其他名称。", - "firstPlugin": "请选择一个可编辑插件。" + "required": "请输入分组名称。", + "tooLong": "分组名称不能超过 32 个字符。", + "controlChars": "分组名称不能包含控制字符。", + "firstPlugin": "请选择可编辑的{{noun}}。" }, "readOnly": { - "system": "内置插件的分组不能修改。", + "system": "内置{{noun}}的分组不能修改。", "builtinSkill": "内置技能的分组不能修改。", "externalSkill": "外部目录(如 ~/.claude/skills)里的技能不能在这里改分组。", "admin": "你没有修改分组的权限。", "catalog": "请先安装或配置此服务。", - "noEditable": "暂无可修改分组的插件。" + "noEditable": "暂无可分组{{nouns}}。" }, "errors": { - "missing": "插件或分组不可用,请刷新后重试。", - "readOnlyMembers": "以下插件的分组不能修改:{{items}}", - "write": "无法保存此插件的分组。", + "missing": "所选{{noun}}或分组不可用,请刷新后重试。", + "readOnlyMembers": "以下{{noun}}的分组不能修改:{{items}}", + "write": "无法保存此{{noun}}的分组。", "partial": "已保存 {{succeeded}} 个,失败 {{failed}} 个。", - "succeededItems": "已保存插件:", - "failedItems": "失败插件:", + "failedItem": "{{item}}:{{reason}}", + "changedAfterCheck": "检查后发生变化,请刷新后重试。", + "details": "技术详情", "refresh": "列表刷新失败,请刷新后重试。" }, "drag": { diff --git a/webui/src/locales/zh-CN/task.json b/webui/src/locales/zh-CN/task.json index b49dd2f2f..aede0118e 100644 --- a/webui/src/locales/zh-CN/task.json +++ b/webui/src/locales/zh-CN/task.json @@ -187,6 +187,7 @@ "recurring": "循环执行", "selectFrequency": "请选择频率", "customOption": "自定义…", + "cronInvalid": "Cron 表达式格式错误,请使用五字段格式(分、时、日、月、星期)。示例:0 6 * * *(按所选时区每天 06:00 执行)。不支持六字段格式和 @daily。", "customCronLabel": "自定义 Cron 表达式", "timezoneLabel": "时区", "cronDescLabel": "周期描述", diff --git a/webui/src/locales/zh-CN/tool.json b/webui/src/locales/zh-CN/tool.json index 1c82446fc..5b05f7a8a 100644 --- a/webui/src/locales/zh-CN/tool.json +++ b/webui/src/locales/zh-CN/tool.json @@ -102,7 +102,7 @@ "mcp": { "emptyStateTitle": "暂无接入对话", "guidePanelTitle": "Rex 辅助接入", - "guidePanelDesc": "选择一个引导或案例,Rex 会先确认服务类型、连接方式、凭证和启动命令,再帮你生成可测试的 MCP 配置。", + "guidePanelDesc": "请选择引导或案例,Rex 将确认服务类型、连接方式、凭证和启动命令,并生成可测试的 MCP 配置。", "guideSectionTitle": "接入引导", "caseSectionTitle": "接入案例", "guideActions": [ @@ -143,7 +143,7 @@ "api": { "emptyStateTitle": "暂无接入对话", "guidePanelTitle": "Rex 辅助接入", - "guidePanelDesc": "选择一个引导或案例,Rex 会加载 tool-builder skill,确认 API 文档、认证和输出格式后生成 YAML 工具。", + "guidePanelDesc": "请选择引导或案例,Rex 将确认 API 文档、认证方式和输出格式,并生成工具。", "guideSectionTitle": "接入引导", "caseSectionTitle": "接入案例", "guideActions": [ @@ -184,7 +184,7 @@ "local": { "emptyStateTitle": "暂无创建对话", "guidePanelTitle": "Rex 辅助创建", - "guidePanelDesc": "选择一个引导或案例,Rex 会加载 tool-builder skill,确认工具输入输出、实现方式和冒烟测试后生成本地 Python 工具。", + "guidePanelDesc": "请选择引导或案例,Rex 将确认工具的输入输出、实现方式和冒烟测试,并生成本地 Python 工具。", "guideSectionTitle": "创建引导", "caseSectionTitle": "创建案例", "guideActions": [ @@ -269,7 +269,14 @@ "startCommandRequired": "请输入启动命令", "serviceUrlRequired": "请输入服务地址", "chatPrompt": "请帮我接入名为 \"{{name}}\" 的 MCP 服务", - "chatSubtitle": "通过对话让 Rex 帮你接入 MCP 服务" + "chatSubtitle": "通过对话让 Rex 帮你接入 MCP 服务", + "errors": { + "nameRequired": "请输入服务名称。", + "commandRequired": "请输入启动命令。", + "urlRequired": "请输入服务地址。", + "urlScheme": "服务地址格式不正确,请以 http:// 或 https:// 开头。", + "invalidHeaders": "请输入有效的 JSON 对象。" + } }, "addAPI": { @@ -641,7 +648,7 @@ "addFailed": "添加失败: {{error}}", "mcpNameRequired": "请输入 MCP 服务名称", "apiKeyRequired": "请输入 API Key", - "invalidHeaders": "额外请求头必须是合法的 JSON 对象", + "invalidHeaders": "请输入有效的 JSON 对象。", "credSaved": "凭证已保存", "saveFailed": "保存失败: {{error}}", "testFailed": "测试失败: {{error}}", @@ -701,6 +708,7 @@ "mcpHintDesc": "不确定怎么填?切换到「工作台」标签页,告诉 Rex 你想接入什么 MCP 服务,它会帮你自动完成配置。", "connSuccess": "连接成功", "connFailed": "连接失败", + "mcpConnectFailed": "MCP 服务连接失败,请检查服务地址、服务状态和网络后重试;仍失败请联系管理员。", "addFailedTitle": "添加失败" }, diff --git a/webui/src/locales/zh-CN/update.json b/webui/src/locales/zh-CN/update.json index e58252ce8..e3005e490 100644 --- a/webui/src/locales/zh-CN/update.json +++ b/webui/src/locales/zh-CN/update.json @@ -10,7 +10,7 @@ "details": "详情", "newVersionTitle": "发现新版本", "newVersionDesc": "本次更新包含新的产品能力、体验优化和问题修复,建议升级后查看重点变化。", - "confirmUpgrade": "确认升级到 {{version}}?", + "confirmUpgrade": "确认升级至 {{version}}?", "confirmUpgradeDesc": "升级过程中服务会短暂重启,页面将在完成后自动刷新。", "confirmAction": "确认升级", "laterAction": "稍后再说", @@ -83,8 +83,8 @@ "restarting": "正在把服务起回来,好了这里会告诉你。", "restarted": "服务已重新启动,数据没有动。这次升级装的组件没有办法还原,可能已经是新的:到服务器上查看 ~/.flocks/run/upgrade-result.json,把原因处理掉之后重新升级。" }, - "enterpriseDesc": "这台机器有企业版授权,这次升级到新企业版:程序装到 {{root}},数据和授权沿用,网页地址不变。开源版会先停下,第一次启动要迁移数据,可能要几分钟。", - "enterpriseInstalling": "开源版会先停下,企业版第一次启动要迁移数据,可能要几分钟。装好后这个页面会自动刷新。", + "enterpriseDesc": "程序安装至 {{root}}。原有数据和授权沿用,访问地址不变。升级期间开源版服务将停止;首次启动需迁移数据,可能需要几分钟。", + "enterpriseInstalling": "开源版将停止,企业版首次启动需迁移数据,可能需要几分钟,安装完成后页面自动刷新。", "enterpriseStageLabels": { "fetching": "下载新企业版安装包", "restarting": "安装新企业版" diff --git a/webui/src/locales/zh-CN/workflow.json b/webui/src/locales/zh-CN/workflow.json index cea3b4b05..a4a6a89fe 100644 --- a/webui/src/locales/zh-CN/workflow.json +++ b/webui/src/locales/zh-CN/workflow.json @@ -299,7 +299,7 @@ "publishing": "发布中,请稍候...", "publishAsApi": "发布为 API 服务", "guidePanelTitle": "Rex 辅助发布", - "guidePanelDesc": "选择一种发布方式,Rex 会先读取 guide.md 和配置库,再引导你确认、应用或启动。", + "guidePanelDesc": "请选择发布方式,Rex 将引导你完成配置,并确认是否应用或启动。", "cardGuideTitle": "Flocks辅助配置", "cardGuideAction": "辅助配置", "cardGuideApiFocus": "API 发布配置", @@ -507,7 +507,7 @@ "contextMessage": "用户希望创建一个 Flocks 工作流,请使用 workflow-builder skill 来完成。", "emptyStateTitle": "暂无执行记录", "guidePanelTitle": "Rex 辅助创建", - "guidePanelDesc": "选择一个引导或创建案例,Rex 会按 workflow-builder skill 先确认场景、输入输出、节点流程和样例,再生成文件。", + "guidePanelDesc": "请选择引导或创建案例,Rex 将确认场景、输入输出、节点流程和样例,并生成工作流。", "generateEditDocPrompt": "这是用户点击「生成说明」触发的新任务。按钮含义是:先按 workflow-builder skill 生成 workflow.md 说明文件,确认后再由「生成工作流」基于 workflow.md 生成 workflow.json。\n\n请按下面流程推进:\n1. 先加载并遵守 workflow-builder skill。\n2. 必须使用 question 工具询问我需要中文流程说明文档还是英文流程说明文档;一次只问一个问题,必须允许自定义输入。\n3. 如果左侧编辑器已有内容,把它作为已有草稿参考;如果为空,就先通过 question 工具收集创建工作流所需的业务场景、输入、输出、触发方式、节点流程、样例和验收标准。\n4. 参考 workflow-builder skill 中的 workflow_zh.md / workflow_en.md 模板结构,只生成一份 workflow.md。\n5. workflow.md 要面向人编辑:说明功能、适用场景、输入输出、节点流程、可修改点、样例和验收方式。\n6. 写入 workflow.md 前先展示 diff 并等待我确认;确认后再写入新工作流目录下的 workflow.md。\n7. 完成后提醒我可以点击「生成工作流」基于 workflow.md 生成 workflow.json。\n\n当前左侧编辑器内容:\n~~~markdown\n{{editDocContent}}\n~~~", "generateWorkflowPrompt": "用户点击了「生成工作流」按钮。这个按钮的意思是:基于当前左侧编辑器里的 workflow.md 内容生成正式 Flocks 工作流,其中核心产物是 workflow.json。\n\n请按 workflow-builder skill 推进:\n1. 先读取并遵守 workflow-builder skill。\n2. 以下方 workflow.md 内容作为主要意图来源,不要把任务理解成重写 workflow.md。\n3. 若还没有工作流目录,请先根据 workflow.md 确认/生成合适的工作流 ID 和目录,再写入 workflow.md 与 workflow.json;若已有目录,则读取现有 workflow.json 并基于 workflow.md 更新机器定义。\n4. 生成的 workflow.json 必须是合法 JSON,节点和边必须组成完整流程图。\n5. 写 workflow.json 前必须展示 diff 并等待我确认。\n6. 完成后说明 workflow.json 改了什么,以及应该如何测试。\n\n当前编辑器中的 workflow.md 内容:\n~~~markdown\n{{editDocContent}}\n~~~", "guideSectionTitle": "创建引导", diff --git a/webui/src/locales/zh-CN/workspace.json b/webui/src/locales/zh-CN/workspace.json index 201f5599a..0bd64fd36 100644 --- a/webui/src/locales/zh-CN/workspace.json +++ b/webui/src/locales/zh-CN/workspace.json @@ -11,6 +11,9 @@ "newDir": "新建目录", "upload": "上传文件", "dirNamePlaceholder": "目录名称", + "dirNameRequired": "请输入目录名称。", + "dirNameExists": "当前目录下已存在同名目录,请修改名称。", + "dirNameTakenByFile": "当前目录下已存在同名文件,请修改名称。", "create": "创建", "dropHere": "拖放文件到此处上传", "emptyDir": "空目录 — 拖放文件或点击上传", diff --git a/webui/src/pages/Agent/AgentSheet.test.tsx b/webui/src/pages/Agent/AgentSheet.test.tsx index 8c53b7e91..159b583e6 100644 --- a/webui/src/pages/Agent/AgentSheet.test.tsx +++ b/webui/src/pages/Agent/AgentSheet.test.tsx @@ -111,6 +111,7 @@ vi.mock('react-i18next', () => ({ 'edit.guidePanelTitle': 'Rex 辅助修改', 'edit.guidePanelDesc': '编辑描述', 'edit.nativeGuidePanelDesc': '内置编辑描述', + 'edit.nativeSubagentGuidePanelDesc': '内置子 Agent 编辑描述', 'edit.nativeGuideActions': [ { label: '检查模型策略', @@ -231,6 +232,18 @@ describe('AgentSheet', () => { expect(props.rexSystemContext).toContain('Skills:agent-builder'); }); + it('names the primary agent when it is the built-in one being edited', () => { + render( + , + ); + + expect(capturedEntitySheetProps.at(-1).rexGuidePanelDesc).toBe('内置编辑描述'); + }); + it('uses a model and temperature guide when editing a native agent', () => { render( { const props = capturedEntitySheetProps.at(-1); expect(props.mode).toBe('edit'); expect(props.initialTab).toBe('rex'); - expect(props.rexGuidePanelDesc).toBe('内置编辑描述'); + // A built-in subagent and the primary agent say the same scope in their own words. + expect(props.rexGuidePanelDesc).toBe('内置子 Agent 编辑描述'); expect(props.rexGuideGroups).toEqual([ { title: '编辑引导', diff --git a/webui/src/pages/Agent/AgentSheet.tsx b/webui/src/pages/Agent/AgentSheet.tsx index 14ce447a6..32f5cbb5d 100644 --- a/webui/src/pages/Agent/AgentSheet.tsx +++ b/webui/src/pages/Agent/AgentSheet.tsx @@ -22,6 +22,7 @@ import { providerAPI, defaultModelAPI, modelV2API } from '@/api/provider'; import { toolAPI, Tool } from '@/api/tool'; import { skillAPI, Skill } from '@/api/skill'; import type { ModelDefinitionV2 } from '@/types'; +import { getAgentDisplayName } from '@/utils/agentDisplay'; interface AvailableModel { providerID: string; @@ -57,7 +58,7 @@ interface AgentSheetProps { } export default function AgentSheet({ agent, onClose, onSaved }: AgentSheetProps) { - const { t } = useTranslation(['agent', 'common']); + const { t, i18n } = useTranslation(['agent', 'common']); const isEdit = !!agent; const isNative = !!agent?.native; @@ -335,7 +336,10 @@ export default function AgentSheet({ agent, onClose, onSaved }: AgentSheetProps) rexGuideGroups={guideGroups} rexGuidePanelTitle={isEdit ? t('edit.guidePanelTitle') : t('create.guidePanelTitle')} rexGuidePanelDesc={isEdit - ? t(isNative ? 'edit.nativeGuidePanelDesc' : 'edit.guidePanelDesc', { name: agent?.name ?? formData.name }) + ? t( + isNative ? (agent?.mode === 'primary' ? 'edit.nativeGuidePanelDesc' : 'edit.nativeSubagentGuidePanelDesc') : 'edit.guidePanelDesc', + { name: isNative ? getAgentDisplayName(agent, i18n?.language) : agent?.name ?? formData.name }, + ) : t('create.guidePanelDesc')} rexGuideEmptyTitle={isEdit ? t('edit.emptyStateTitle') : t('create.emptyStateTitle')} rexGuideIcon={} @@ -397,7 +401,7 @@ function AgentFormContent({ skillsLoading = false, isPrimary, }: AgentFormContentProps) { - const { t } = useTranslation('agent'); + const { t, i18n } = useTranslation('agent'); const { openRex } = useEntitySheet(); const update = (fields: Partial) => onChange({ ...formData, ...fields }); @@ -442,7 +446,10 @@ function AgentFormContent({ {nativeReadOnly && (
- {t('form.nativeReadOnlyMessage')} + {/* One sentence for the sheet and the Rex panel: only model and temperature are saved. */} + {t(formData.mode === 'primary' ? 'form.nativeReadOnlyMessage' : 'form.nativeSubagentReadOnlyMessage', { + name: getAgentDisplayName(formData, i18n?.language), + })}
)} diff --git a/webui/src/pages/Agent/index.tsx b/webui/src/pages/Agent/index.tsx index b941c8d28..97c3fa76a 100644 --- a/webui/src/pages/Agent/index.tsx +++ b/webui/src/pages/Agent/index.tsx @@ -15,7 +15,7 @@ import { agentAPI, Agent } from '@/api/agent'; import { getAgentDisplayDescription, getAgentDisplayName } from '@/utils/agentDisplay'; import AgentSheet from './AgentSheet'; import GroupNav, { useGroupDrag, type GroupDrag } from '@/components/plugin-groups/GroupNav'; -import { deriveGroupNav, matchesGroup, saveGroupItems, type GroupSelection } from '@/components/plugin-groups/groupView'; +import { deriveGroupNav, matchesGroup, saveGroupItems, type GroupSelection, groupNoun } from '@/components/plugin-groups/groupView'; import PluginViewToggle from '@/components/plugin-groups/PluginViewToggle'; import { usePluginViewMode, type PluginViewMode } from '@/hooks/usePluginViewMode'; @@ -36,7 +36,7 @@ export default function AgentPage() { const [groupSelection, setGroupSelection] = useState(null); const asGroupItem = (agent: Agent) => ({ key: agent.name, name: getAgentDisplayName(agent, i18n.language), group: agent.group, - readOnlyReason: agent.group_readonly ? t('pluginGroups:readOnly.system') : undefined, + readOnlyReason: agent.group_readonly ? t('pluginGroups:readOnly.system', groupNoun(t, 'agent')) : undefined, }); const visibleAgents = (inventory: Agent[]) => inventory.filter((agent) => agent.mode === 'primary' || !(agent.tags ?? []).includes('system')); const groupItems = visibleAgents(agents).map(asGroupItem); @@ -47,17 +47,17 @@ export default function AgentPage() { const loadGroupItems = async () => visibleAgents((await agentAPI.list()).data).map(asGroupItem); const moveGroup = async (key: string, group: string | null) => { const inventory = await loadGroupItems(); - await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroups, t); + await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroups, t, false, 'agent'); }; const createGroup = async (key: string, group: string) => { const inventory = await loadGroupItems(); if (inventory.some((item) => matchesGroup(item.group, group))) throw new Error(t('pluginGroups:validation.duplicate')); - await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroups, t); + await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroups, t, false, 'agent'); }; const changeGroup = async (from: string, to: string | null) => { const inventory = await loadGroupItems(); if (to !== null && inventory.some((item) => matchesGroup(item.group, to))) throw new Error(t('pluginGroups:validation.duplicate')); - await saveGroupItems(inventory.filter((item) => matchesGroup(item.group, from)), to, saveGroup, reloadGroups, t, true); + await saveGroupItems(inventory.filter((item) => matchesGroup(item.group, from)), to, saveGroup, reloadGroups, t, true, 'agent'); }; const selectAgent = (agent: Agent) => setEditingAgent(agent); @@ -176,7 +176,7 @@ export default function AgentPage() { scrollbar is absent, preventing the layout shift that occurs when filters toggle between many results (scrollbar visible) and few results (no bar). */}
- changeGroup(name, null)} {...groupDrag} /> + changeGroup(name, null)} {...groupDrag} />
{agents.length === 0 ? ( (await deviceAPI.list()).data.map(asBusinessItem); const moveBusinessGroup = async (key: string, group: string | null) => { const inventory = await loadBusinessItems(); - await saveGroupItems(inventory.filter((item) => item.key === key), group, saveBusinessGroup, reloadBusinessDevices, t); + await saveGroupItems(inventory.filter((item) => item.key === key), group, saveBusinessGroup, reloadBusinessDevices, t, false, 'device'); }; const createBusinessGroup = async (key: string, group: string) => { const inventory = await loadBusinessItems(); if (inventory.some((item) => matchesGroup(item.group, group))) throw new Error(t('pluginGroups:validation.duplicate')); - await saveGroupItems(inventory.filter((item) => item.key === key), group, saveBusinessGroup, reloadBusinessDevices, t); + await saveGroupItems(inventory.filter((item) => item.key === key), group, saveBusinessGroup, reloadBusinessDevices, t, false, 'device'); }; const changeBusinessGroup = async (from: string, to: string | null) => { const inventory = await loadBusinessItems(); if (to !== null && inventory.some((item) => matchesGroup(item.group, to))) throw new Error(t('pluginGroups:validation.duplicate')); - await saveGroupItems(inventory.filter((item) => matchesGroup(item.group, from)), to, saveBusinessGroup, reloadBusinessDevices, t, true); + await saveGroupItems(inventory.filter((item) => matchesGroup(item.group, from)), to, saveBusinessGroup, reloadBusinessDevices, t, true, 'device'); }; const businessNav: GroupNavProps = { - preferenceKey: 'device', inventoryComplete: !loading && !refreshing, ...deriveGroupNav(businessItems), items: businessItems, + preferenceKey: 'device', itemKind: 'device', inventoryComplete: !loading && !refreshing, ...deriveGroupNav(businessItems), items: businessItems, selection: businessGroup, onSelect: setBusinessGroup, onMove: moveBusinessGroup, onCreate: createBusinessGroup, onRename: changeBusinessGroup, onDelete: (name) => changeBusinessGroup(name, null), ...businessDrag, }; diff --git a/webui/src/pages/Login/index.test.tsx b/webui/src/pages/Login/index.test.tsx new file mode 100644 index 000000000..ec6564ad3 --- /dev/null +++ b/webui/src/pages/Login/index.test.tsx @@ -0,0 +1,57 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import LoginPage from './index'; + +const { login } = vi.hoisted(() => ({ login: vi.fn() })); + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})); +vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ login }) })); +vi.mock('@/contexts/ProductNameContext', () => ({ useProductName: () => ({ productName: 'Flocks' }) })); +vi.mock('@/components/layout/AuthLayout', () => ({ default: ({ children }: { children: React.ReactNode }) => <>{children} })); + +const username = () => screen.getByPlaceholderText('fields.usernamePlaceholder'); +const password = () => screen.getByPlaceholderText('fields.passwordPlaceholder'); +const submit = () => fireEvent.click(screen.getByRole('button', { name: 'actions.login' })); + +describe('LoginPage (v0.21 #1)', () => { + beforeEach(() => { + login.mockReset(); + }); + + it('asks for each empty field under it instead of trying to log in', () => { + render(); + submit(); + + expect(screen.getByText('login.usernameRequired')).toBeInTheDocument(); + expect(screen.getByText('login.passwordRequired')).toBeInTheDocument(); + expect(username()).toHaveAttribute('aria-invalid', 'true'); + expect(login).not.toHaveBeenCalled(); + }); + + it('treats a username of spaces as empty and clears a message once the field is filled', () => { + render(); + fireEvent.change(username(), { target: { value: ' ' } }); + fireEvent.change(password(), { target: { value: 'secret' } }); + submit(); + + expect(screen.getByText('login.usernameRequired')).toBeInTheDocument(); + expect(screen.queryByText('login.passwordRequired')).not.toBeInTheDocument(); + fireEvent.change(username(), { target: { value: 'admin' } }); + expect(screen.queryByText('login.usernameRequired')).not.toBeInTheDocument(); + expect(login).not.toHaveBeenCalled(); + }); + + it('shows the server answer for filled-in credentials', async () => { + login.mockRejectedValue({ response: { data: { message: '用户名或密码错误' } } }); + render(); + fireEvent.change(username(), { target: { value: 'admin' } }); + fireEvent.change(password(), { target: { value: 'wrong' } }); + submit(); + + await waitFor(() => expect(login).toHaveBeenCalledWith('admin', 'wrong')); + expect(await screen.findByText('用户名或密码错误')).toBeInTheDocument(); + }); +}); diff --git a/webui/src/pages/Login/index.tsx b/webui/src/pages/Login/index.tsx index 7a0a4966a..c5d7ab945 100644 --- a/webui/src/pages/Login/index.tsx +++ b/webui/src/pages/Login/index.tsx @@ -13,11 +13,19 @@ export default function LoginPage() { const [password, setPassword] = useState(''); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); + // Empty fields are answered under each field; the server only judges filled-in credentials. + const [fieldErrors, setFieldErrors] = useState<{ username?: string; password?: string }>({}); const onSubmit = async (e: React.FormEvent) => { e.preventDefault(); - setSubmitting(true); + const missing = { + username: username.trim() ? undefined : t('login.usernameRequired'), + password: password ? undefined : t('login.passwordRequired'), + }; + setFieldErrors(missing); setError(null); + if (missing.username || missing.password) return; + setSubmitting(true); try { await login(username, password); } catch (err: any) { @@ -36,6 +44,7 @@ export default function LoginPage() {
@@ -46,22 +55,32 @@ export default function LoginPage() { setUsername(e.target.value)} + onChange={(e) => { setUsername(e.target.value); setFieldErrors((prev) => ({ ...prev, username: undefined })); }} className="w-full border border-gray-300 rounded-lg px-3 py-2 outline-none focus:border-blue-500 dark:border-[#4a5563] dark:bg-[#252c35] dark:text-[#d7dee8] dark:placeholder:text-[#9aa7b4] dark:focus:border-[#539bf5]" placeholder={t('fields.usernamePlaceholder')} autoComplete="username" required + aria-invalid={fieldErrors.username ? true : undefined} + aria-describedby={fieldErrors.username ? 'login-username-error' : undefined} /> + {fieldErrors.username && ( +

{fieldErrors.username}

+ )}
setPassword(e.target.value)} + onChange={(e) => { setPassword(e.target.value); setFieldErrors((prev) => ({ ...prev, password: undefined })); }} placeholder={t('fields.passwordPlaceholder')} autoComplete="current-password" required + aria-invalid={fieldErrors.password ? true : undefined} + aria-describedby={fieldErrors.password ? 'login-password-error' : undefined} /> + {fieldErrors.password && ( +

{fieldErrors.password}

+ )}
{error && (
diff --git a/webui/src/pages/Model/ModelDiscovery.test.tsx b/webui/src/pages/Model/ModelDiscovery.test.tsx index 9c81cb40e..c3f746f26 100644 --- a/webui/src/pages/Model/ModelDiscovery.test.tsx +++ b/webui/src/pages/Model/ModelDiscovery.test.tsx @@ -219,3 +219,26 @@ it.each(['threatbook-cn-llm', 'threatbook-io-llm'])('shows the dedicated model-l expect(api.discoverModels).not.toHaveBeenCalled(); expect(api.saveModelInventory).not.toHaveBeenCalled(); }); + +// v0.21 #27: "Internal server error" said what failed, in the user's words; a refusal keeps its own words. +it('says the connection check failed when the server fails, and keeps a refusal as the service said it', async () => { + const user = userEvent.setup(); + api.checkKey.mockRejectedValueOnce({ response: { status: 500, data: { error: 'InternalServerError', message: 'Internal server error' } } }); + render(); + await user.click(screen.getByRole('button', { name: 'compact.check' })); + expect(await screen.findByRole('alert')).toHaveTextContent('compact.checkFailed'); + expect(screen.getByRole('alert')).not.toHaveTextContent('Internal server error'); + + api.checkKey.mockRejectedValueOnce({ response: { status: 403, data: { detail: 'Administrator access required' } } }); + await user.click(screen.getByRole('button', { name: 'compact.check' })); + await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('Administrator access required')); +}); + +it('says fetching the model list failed when the server fails', async () => { + const user = userEvent.setup(); + api.discoverModels.mockRejectedValueOnce({ response: { status: 500, data: { error: 'InternalServerError', message: 'Internal server error' } } }); + render(); + await user.click(fetchButton()); + expect(await screen.findByText('discovery.requestFailed')).toBeInTheDocument(); + expect(screen.queryByText('Internal server error')).not.toBeInTheDocument(); +}); diff --git a/webui/src/pages/Model/ModelDiscovery.tsx b/webui/src/pages/Model/ModelDiscovery.tsx index 2196b2dbf..cad02382e 100644 --- a/webui/src/pages/Model/ModelDiscovery.tsx +++ b/webui/src/pages/Model/ModelDiscovery.tsx @@ -2,7 +2,7 @@ import { useEffect, useId, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Loader2, Pencil, Plus, RefreshCw, Search, Trash2 } from 'lucide-react'; import { providerAPI } from '@/api/provider'; -import { extractErrorMessage } from '@/utils/error'; +import { extractErrorMessage, isServiceRefusal } from '@/utils/error'; import type { DiscoveredModel, InventoryModelInput, @@ -419,7 +419,8 @@ export default function ModelDiscovery({ setDirty(true); if (response.data.source === 'catalog') setNotice(t('compact.catalogNotice')); } catch (reason) { - if (version === request.current) setError(extractErrorMessage(reason)); + // A refusal says what to fix; a server failure ("Internal server error") or a lost request does not. + if (version === request.current) setError(isServiceRefusal(reason) ? extractErrorMessage(reason) : t('discovery.requestFailed')); } finally { if (version === request.current) setLoading(false); } diff --git a/webui/src/pages/Model/ProviderKeyCheck.tsx b/webui/src/pages/Model/ProviderKeyCheck.tsx index 8a95162ac..7204e7cab 100644 --- a/webui/src/pages/Model/ProviderKeyCheck.tsx +++ b/webui/src/pages/Model/ProviderKeyCheck.tsx @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Loader2 } from 'lucide-react'; import { providerAPI } from '@/api/provider'; -import { extractErrorMessage } from '@/utils/error'; +import { extractErrorMessage, isServiceRefusal } from '@/utils/error'; export default function ProviderKeyCheck({ providerId, @@ -40,7 +40,8 @@ export default function ProviderKeyCheck({ }); } catch (error) { if (current === version.current) - setResult({ status: 'invalid', message: extractErrorMessage(error) }); + // A refusal says what to fix; a server failure ("Internal server error") or a lost request does not. + setResult({ status: 'invalid', message: isServiceRefusal(error) ? extractErrorMessage(error) : t('compact.checkFailed') }); } finally { if (current === version.current) setChecking(false); } diff --git a/webui/src/pages/Model/index.test.tsx b/webui/src/pages/Model/index.test.tsx index be5fd98ae..d91afcf48 100644 --- a/webui/src/pages/Model/index.test.tsx +++ b/webui/src/pages/Model/index.test.tsx @@ -143,6 +143,7 @@ vi.mock('@/components/common/EntitySheet', () => ({ submitLabel, onSubmit, onClose, + readOnly, }: { open?: boolean; children?: React.ReactNode; @@ -150,13 +151,14 @@ vi.mock('@/components/common/EntitySheet', () => ({ submitLabel?: React.ReactNode; onSubmit?: () => void; onClose?: () => void; + readOnly?: boolean; }) => open ? ( -
+
{children}
- + }
) : null, })); @@ -845,9 +847,10 @@ describe('ModelPage member access', () => { const sheet = await screen.findByTestId('entity-sheet'); expect(within(sheet).getByText('detail.configAdminOnly')).toBeInTheDocument(); expect(within(sheet).getByRole('group')).toBeDisabled(); - const save = within(sheet).getByRole('button', { name: 'Save' }); - expect(save).toBeDisabled(); - await user.click(save); + // A details view: no save or cancel, the sheet still closes. + expect(sheet).toHaveAttribute('data-read-only', 'true'); + expect(within(sheet).queryByRole('button', { name: 'Save' })).not.toBeInTheDocument(); + expect(within(sheet).getByRole('button', { name: 'Close sheet' })).toBeInTheDocument(); expect(mocks.createDefinition).not.toHaveBeenCalled(); expect(mocks.updateModelSettings).not.toHaveBeenCalled(); }); diff --git a/webui/src/pages/Model/index.tsx b/webui/src/pages/Model/index.tsx index 5938cb6d6..7319ee25a 100644 --- a/webui/src/pages/Model/index.tsx +++ b/webui/src/pages/Model/index.tsx @@ -2532,6 +2532,7 @@ function ModelDetailSheet({ onSubmit={handleSave} hideRex hideTest + readOnly={readOnly} > {settingsLoadError && (
diff --git a/webui/src/pages/SceneSuites/index.test.tsx b/webui/src/pages/SceneSuites/index.test.tsx index 46bf9cc52..f232d4a76 100644 --- a/webui/src/pages/SceneSuites/index.test.tsx +++ b/webui/src/pages/SceneSuites/index.test.tsx @@ -484,7 +484,7 @@ describe('SceneSuitesPage', () => { await user.click(await screen.findByRole('button', { name: '卸载' })); await waitFor(() => expect(toast.error).toHaveBeenCalledWith( - '操作失败: 告警运营套件', '场景正在运行,请稍后重试', + '告警运营套件卸载失败,请重试;如仍失败,请联系管理员。', '场景正在运行,请稍后重试', )); }); diff --git a/webui/src/pages/SceneSuites/index.tsx b/webui/src/pages/SceneSuites/index.tsx index 68c968f34..729dd9366 100644 --- a/webui/src/pages/SceneSuites/index.tsx +++ b/webui/src/pages/SceneSuites/index.tsx @@ -44,6 +44,7 @@ const TEXT = { empty: '还没有可用的场景套件', loadFailed: '加载场景套件失败', actionFailed: '操作失败', + uninstallFailed: '{name}卸载失败,请重试;如仍失败,请联系管理员。', installed_ok: '安装完成,场景已启用', installedEnableFailed: '安装已完成,但启用失败。请点击“启用”重试。', updatedEnableFailed: '更新已完成,但启用失败。请点击“启用”重试。', @@ -82,6 +83,7 @@ const TEXT = { empty: 'No scene suite is available yet', loadFailed: 'Failed to load scene suites', actionFailed: 'Action failed', + uninstallFailed: 'Could not uninstall {name}. Try again; if it still fails, contact your administrator.', installed_ok: 'Installed and enabled', installedEnableFailed: 'Installed, but enabling failed. Click Enable to retry.', updatedEnableFailed: 'Updated, but enabling failed. Click Enable to retry.', @@ -242,7 +244,10 @@ export default function SceneSuitesPage() { setInstallProgress((current) => failSuiteInstallProgress(current, progressEntry(suite), detail || text.actionFailed)); } toast.error( - installed ? text.installedEnableFailed : updated ? text.updatedEnableFailed : `${text.actionFailed}: ${suiteName(suite, zh)}`, + installed ? text.installedEnableFailed + : updated ? text.updatedEnableFailed + : action === 'uninstall' ? text.uninstallFailed.replace('{name}', suiteName(suite, zh)) + : `${text.actionFailed}: ${suiteName(suite, zh)}`, detail, ); } finally { diff --git a/webui/src/pages/Skill/index.test.tsx b/webui/src/pages/Skill/index.test.tsx index fd04db7ed..b2d1c28f7 100644 --- a/webui/src/pages/Skill/index.test.tsx +++ b/webui/src/pages/Skill/index.test.tsx @@ -287,7 +287,8 @@ describe('SkillPage', () => { await screen.findByText('first'); fireEvent.click(screen.getByRole('button', { name: 'deleteNamed' })); expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); - await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('failed: write denied')); + await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('pluginGroups:errors.partial')); + expect(tMock).toHaveBeenCalledWith('pluginGroups:errors.failedItem', { item: 'failed', reason: 'write denied' }); expect(listMock).toHaveBeenCalledOnce(); expect(updateGroupMock).toHaveBeenCalledTimes(2); expect(screen.getByRole('button', { name: 'Ops 1' })).toBeInTheDocument(); diff --git a/webui/src/pages/Skill/index.tsx b/webui/src/pages/Skill/index.tsx index b151466c2..0cd5684dd 100644 --- a/webui/src/pages/Skill/index.tsx +++ b/webui/src/pages/Skill/index.tsx @@ -23,7 +23,7 @@ import { isSkillDefinitionReadOnly, skillAPI, Skill } from '@/api/skill'; import SkillSheet from './SkillSheet'; import SkillInstallDialog from './SkillInstallDialog'; import GroupNav, { useGroupDrag, type GroupDrag } from '@/components/plugin-groups/GroupNav'; -import { deriveGroupNav, matchesGroup, saveGroupItems, type GroupSelection } from '@/components/plugin-groups/groupView'; +import { deriveGroupNav, matchesGroup, saveGroupItems, type GroupSelection, groupNoun } from '@/components/plugin-groups/groupView'; import { usePluginViewMode } from '@/hooks/usePluginViewMode'; import PluginViewToggle from '@/components/plugin-groups/PluginViewToggle'; import PluginGroupButton from '@/components/plugin-groups/PluginGroupButton'; @@ -118,7 +118,7 @@ export default function SkillPage() { key: skill.name, name: skill.name, group: skill.group, // Skills found in ~/.claude/skills are not built in, but only user skills are written to. readOnlyReason: skill.group_readonly - ? t(skill.source === 'claude' ? 'pluginGroups:readOnly.externalSkill' : 'pluginGroups:readOnly.system') + ? t(skill.source === 'claude' ? 'pluginGroups:readOnly.externalSkill' : 'pluginGroups:readOnly.system', groupNoun(t, 'skill')) : isSkillDefinitionReadOnly(skill) ? t('pluginGroups:readOnly.builtinSkill') : undefined, }); const groupItems = visibleSkills.map(asGroupItem); @@ -133,17 +133,17 @@ export default function SkillPage() { }; const moveGroup = async (key: string, group: string | null) => { const inventory = await loadGroupItems(); - await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, refreshGroupingInventory, t); + await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, refreshGroupingInventory, t, false, 'skill'); }; const createGroup = async (key: string, group: string) => { const inventory = await loadGroupItems(); if (inventory.some((item) => matchesGroup(item.group, group))) throw new Error(t('pluginGroups:validation.duplicate')); - await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, refreshGroupingInventory, t); + await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, refreshGroupingInventory, t, false, 'skill'); }; const changeGroup = async (from: string, to: string | null) => { const inventory = await loadGroupItems(); if (to !== null && inventory.some((item) => matchesGroup(item.group, to))) throw new Error(t('pluginGroups:validation.duplicate')); - await saveGroupItems(inventory.filter((item) => matchesGroup(item.group, from)), to, saveGroup, refreshGroupingInventory, t, true); + await saveGroupItems(inventory.filter((item) => matchesGroup(item.group, from)), to, saveGroup, refreshGroupingInventory, t, true, 'skill'); }; const enabledCount = useMemo( @@ -418,7 +418,7 @@ export default function SkillPage() {
- changeGroup(name, null)} {...groupDrag} /> + changeGroup(name, null)} {...groupDrag} />
{visibleSkills.length === 0 ? ( diff --git a/webui/src/pages/Task/TaskSheet.test.tsx b/webui/src/pages/Task/TaskSheet.test.tsx index 268290f14..fce6376c1 100644 --- a/webui/src/pages/Task/TaskSheet.test.tsx +++ b/webui/src/pages/Task/TaskSheet.test.tsx @@ -378,6 +378,39 @@ describe('TaskSheet', () => { expect(onClose).toHaveBeenCalledTimes(1); }); + it('cron 不是五字段时在表达式下方提示,不提交、不弹失败', async () => { + const user = userEvent.setup(); + render(); + + await user.type(screen.getByPlaceholderText('输入任务标题'), '六字段'); + await user.type(screen.getByPlaceholderText('0 9 * * 1-5'), '0 0 6 * * *'); + await user.click(screen.getByRole('button', { name: '提交' })); + + expect(await screen.findByRole('alert')).toHaveTextContent('form.cronInvalid'); + expect(mocks.createScheduler).not.toHaveBeenCalled(); + expect(mocks.toastError).not.toHaveBeenCalled(); + expect(screen.getByPlaceholderText('0 9 * * 1-5')).toHaveValue('0 0 6 * * *'); + + await user.type(screen.getByPlaceholderText('0 9 * * 1-5'), '{backspace}{backspace}'); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + }); + + it('服务端判 cron 无效时同样提示在表达式下方并保留输入', async () => { + const user = userEvent.setup(); + mocks.createScheduler.mockRejectedValueOnce({ + response: { status: 400, data: { error: 'HTTPException', message: "Invalid cron expression: '99 * * * *' is not a valid 5-field cron." } }, + }); + render(); + + await user.type(screen.getByPlaceholderText('输入任务标题'), '无效分钟'); + await user.type(screen.getByPlaceholderText('0 9 * * 1-5'), '99 * * * *'); + await user.click(screen.getByRole('button', { name: '提交' })); + + expect(await screen.findByRole('alert')).toHaveTextContent('form.cronInvalid'); + expect(mocks.toastError).not.toHaveBeenCalled(); + expect(screen.getByPlaceholderText('0 9 * * 1-5')).toHaveValue('99 * * * *'); + }); + it('创建 workflow 定时任务时提交 JSON 参数到 context', async () => { const user = userEvent.setup(); diff --git a/webui/src/pages/Task/TaskSheet.tsx b/webui/src/pages/Task/TaskSheet.tsx index b34fc1e9a..2f0bcb326 100644 --- a/webui/src/pages/Task/TaskSheet.tsx +++ b/webui/src/pages/Task/TaskSheet.tsx @@ -106,6 +106,8 @@ export default function TaskSheet({ task, defaultScheduleKind = 'recurring', onC }); const [loading, setLoading] = useState(false); + // A rejected cron expression is answered next to the expression, keeping what was typed. + const [cronError, setCronError] = useState(''); const [agents, setAgents] = useState([]); const [workflows, setWorkflows] = useState([]); const guideGroups = useMemo(() => { @@ -147,9 +149,16 @@ export default function TaskSheet({ task, defaultScheduleKind = 'recurring', onC const canSubmit = formData.title.trim() && (isImmediate || (isOnce ? formData.runAt : effectiveCron.trim())); + const cronShown = !isOnce && !isRunOnce && isRecurring; + + useEffect(() => { setCronError(''); }, [formData.cron, formData.scheduleKind]); const handleSubmit = async () => { if (!canSubmit) return; + if (cronShown && !isFiveFieldCron(effectiveCron)) { + setCronError(t('form.cronInvalid')); + return; + } setLoading(true); try { let workflowContext: Record | undefined; @@ -214,7 +223,13 @@ export default function TaskSheet({ task, defaultScheduleKind = 'recurring', onC onSaved(); onClose(); } catch (err: unknown) { - toast.error(t(isEdit ? 'taskSheet.saveFailed' : 'taskSheet.createFailed'), extractErrorMessage(err)); + const message = extractErrorMessage(err); + // flocks.task.models.validate_cron_expression: English for API and agent callers. + if (cronShown && /invalid cron expression/i.test(message)) { + setCronError(t('form.cronInvalid')); + return; + } + toast.error(t(isEdit ? 'taskSheet.saveFailed' : 'taskSheet.createFailed'), message); } finally { setLoading(false); } @@ -316,6 +331,7 @@ ${fields} isEdit={isEdit} isRunOnce={isRunOnce} effectiveCron={effectiveCron} + cronError={cronError} agents={agents} workflows={workflows} /> @@ -332,6 +348,7 @@ interface TaskFormContentProps { isEdit: boolean; isRunOnce: boolean; effectiveCron: string; + cronError?: string; agents: Agent[]; workflows: WorkflowSummary[]; } @@ -343,6 +360,7 @@ function TaskFormContent({ isEdit, isRunOnce, effectiveCron, + cronError, agents, workflows, }: TaskFormContentProps) { @@ -498,12 +516,16 @@ function TaskFormContent({ type="text" value={formData.cron} onChange={(e) => update({ cron: e.target.value })} + aria-invalid={cronError ? true : undefined} + aria-describedby={cronError ? 'task-cron-error' : undefined} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 outline-none font-mono text-sm" placeholder="0 9 * * 1-5" /> )} - {effectiveCron && ( + {cronError ? ( + + ) : effectiveCron && (

{describeCron(effectiveCron)}

)} @@ -747,6 +769,12 @@ function buildRexWelcome(isEdit: boolean, taskTitle?: string): string { // ─── Helpers ────────────────────────────────────────────────────────────────── +/** The scheduler takes plain five-field cron only (flocks.task.models.validate_cron_expression). */ +function isFiveFieldCron(cron: string): boolean { + const value = cron.trim(); + return !value.startsWith('@') && value.split(/\s+/).length === 5; +} + function parseJsonFromText(text: string): Record | null { const fenced = text.match(/```(?:json)?\s*\n([\s\S]+?)\n```/); if (fenced) { diff --git a/webui/src/pages/Tool/ToolGroups.test.tsx b/webui/src/pages/Tool/ToolGroups.test.tsx index 7df97880c..f9f05e876 100644 --- a/webui/src/pages/Tool/ToolGroups.test.tsx +++ b/webui/src/pages/Tool/ToolGroups.test.tsx @@ -488,7 +488,7 @@ describe('Tools native group attributes and original view preservation', () => { expect(dataTransfer.setData).not.toHaveBeenCalled(); fireEvent.click(within(nativeRow('tool_00')).getByRole('button', { name: zhGroups.editGroup })); expect(mocks.toastWarning).toHaveBeenCalledTimes(2); - expect(mocks.toastWarning).toHaveBeenLastCalledWith(zhGroups.readOnly.system); + expect(mocks.toastWarning).toHaveBeenLastCalledWith('内置工具的分组不能修改。'); expect(mocks.get).not.toHaveBeenCalled(); expect(mocks.patch).not.toHaveBeenCalled(); expect(screen.getByRole('button', { name: '重命名分组 Alpha' })).toBeDisabled(); @@ -514,7 +514,7 @@ describe('Tools native group attributes and original view preservation', () => { fireEvent.change(screen.getByRole('combobox'), { target: { value: 'tool_00' } }); } fireEvent.click(screen.getByRole('button', { name: '保存' })); - await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(zhGroups.errors.readOnlyMembers.replace('{{items}}', 'tool_00'))); + await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('以下工具的分组不能修改:tool_00')); expect(mocks.patch).not.toHaveBeenCalled(); }); @@ -603,7 +603,8 @@ describe('Tools native group attributes and original view preservation', () => { await mount(); fireEvent.click(screen.getByRole('button', { name: '删除分组 Alpha' })); expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); - await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('tool_02: read-only filesystem')); + await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('已保存 29 个,失败 1 个。')); + expect(screen.getByRole('alert')).toHaveTextContent('tool_02:read-only filesystem'); expect(mocks.patch).toHaveBeenCalledTimes(30); expect(screen.getByRole('button', { name: 'Alpha 1' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '未分组 30' })).toBeInTheDocument(); diff --git a/webui/src/pages/Tool/ToolSheets.test.ts b/webui/src/pages/Tool/ToolSheets.test.ts index 4f861f7a2..e37a52409 100644 --- a/webui/src/pages/Tool/ToolSheets.test.ts +++ b/webui/src/pages/Tool/ToolSheets.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { buildMCPConfigFromForm, buildMCPFormDataFromConfig, getMCPFormError } from './ToolSheets'; +import { buildMCPConfigFromForm, buildMCPFormDataFromConfig, clearMCPFieldErrors, getMCPFieldErrors, getMCPFormError, mcpTestFailure, mcpTestOutcome } from './ToolSheets'; describe('ToolSheets MCP helpers', () => { it('builds remote MCP config with transport and bearer auth', () => { @@ -73,3 +73,36 @@ describe('ToolSheets MCP helpers', () => { })).toBe('invalidHeaders'); }); }); + +describe('MCP form answers (v0.21 #21–#24)', () => { + const base = { + name: '', connType: 'sse' as const, command: '', args: '', url: '', transport: 'auto' as const, + authType: 'none' as const, authValue: '', authHeaderName: 'X-API-Key', authQueryName: 'apikey', headersText: '', + }; + const t = (key: string) => key; + + it('names each missing or malformed field instead of doing nothing', () => { + expect(getMCPFieldErrors(base)).toEqual({ name: 'nameRequired', url: 'urlRequired' }); + expect(getMCPFieldErrors({ ...base, name: 'demo', url: 'example.com/mcp' })).toEqual({ url: 'urlScheme' }); + expect(getMCPFieldErrors({ ...base, name: 'demo', url: 'HTTPS://example.com/mcp', headersText: '{bad' })).toEqual({ headersText: 'invalidHeaders' }); + expect(getMCPFieldErrors({ ...base, name: 'demo', connType: 'stdio' })).toEqual({ command: 'commandRequired' }); + expect(getMCPFieldErrors({ ...base, name: 'demo', url: 'http://127.0.0.1:8080/sse' })).toEqual({}); + }); + + it('drops only the errors of the fields that changed', () => { + const errors = { name: 'nameRequired', url: 'urlScheme', headersText: 'invalidHeaders' } as const; + expect(clearMCPFieldErrors(errors, { url: 'https://x' })).toEqual({ name: 'nameRequired', headersText: 'invalidHeaders' }); + expect(clearMCPFieldErrors(errors, { connType: 'stdio' })).toEqual({ name: 'nameRequired' }); + }); + + it('says a failed connection in words and keeps the server diagnosis apart', () => { + expect(mcpTestOutcome({ success: false, message: 'Connection failed: copy-check__test__: [Errno 16] Device or resource busy' }, t)) + .toEqual({ success: false, message: 'sheet.mcpConnectFailed', detail: 'Connection failed: copy-check__test__: [Errno 16] Device or resource busy', latency: undefined, tools_count: undefined }); + expect(mcpTestOutcome({ success: true, message: 'ok', tools_count: 3 }, t)).toMatchObject({ success: true, message: 'ok', tools_count: 3 }); + expect(mcpTestFailure({ response: { status: 500, data: { error: 'InternalServerError', message: 'Internal server error' } } }, t)) + .toEqual({ success: false, message: 'sheet.mcpConnectFailed', detail: 'Internal server error' }); + // A request the service refused never reached the MCP server. + expect(mcpTestFailure({ response: { status: 400, data: { detail: 'MCP server url must use http:// or https://' } } }, t)) + .toEqual({ success: false, message: 'MCP server url must use http:// or https://', refused: true }); + }); +}); diff --git a/webui/src/pages/Tool/ToolSheets.tsx b/webui/src/pages/Tool/ToolSheets.tsx index 7c49feff0..7b742f0f6 100644 --- a/webui/src/pages/Tool/ToolSheets.tsx +++ b/webui/src/pages/Tool/ToolSheets.tsx @@ -14,7 +14,7 @@ import { buildGuidedCreateGroups } from '@/components/common/GuidedCreatePanel'; import { useRexComposerControls } from '@/components/common/useRexComposerControls'; import client from '@/api/client'; import { mcpAPI } from '@/api/mcp'; -import { extractErrorMessage } from '@/utils/error'; +import { extractErrorMessage, isServiceRefusal } from '@/utils/error'; // ─── MCPSheet ───────────────────────────────────────────────────────────────── @@ -83,6 +83,67 @@ export function getMCPFormError(formData: MCPFormData): 'invalidHeaders' | null } } +export type MCPFieldErrorCode = 'nameRequired' | 'commandRequired' | 'urlRequired' | 'urlScheme' | 'invalidHeaders'; +export type MCPFieldErrors = Partial>; + +/** + * What the form can tell before asking the server, answered under each field. + * The server checks the address the same way (flocks.server.routes.mcp). + */ +export function getMCPFieldErrors(formData: MCPFormData): MCPFieldErrors { + const errors: MCPFieldErrors = {}; + if (!formData.name.trim()) errors.name = 'nameRequired'; + if (formData.connType === 'stdio') { + if (!formData.command.trim()) errors.command = 'commandRequired'; + return errors; + } + const url = formData.url.trim(); + if (!url) errors.url = 'urlRequired'; + else if (!/^https?:\/\//i.test(url)) errors.url = 'urlScheme'; + if (getMCPFormError(formData) === 'invalidHeaders') errors.headersText = 'invalidHeaders'; + return errors; +} + +/** Drop the errors of the fields a change touched (switching the type re-asks for its own fields). */ +export function clearMCPFieldErrors(errors: MCPFieldErrors, fields: Partial): MCPFieldErrors { + const next = { ...errors }; + for (const key of Object.keys(fields)) delete next[key as keyof MCPFieldErrors]; + if ('connType' in fields) { delete next.command; delete next.url; delete next.headersText; } + return next; +} + +export interface MCPTestResult { + success: boolean; + message: string; + /** The server's own diagnosis of a failed connection, kept under the readable message. */ + detail?: string; + /** The server refused the request (4xx) before trying to connect. */ + refused?: boolean; + latency?: number; + tools_count?: number; +} + +/** A failed connection said in the user's words; a refused request (4xx) is shown as the server said it. */ +export function mcpTestFailure(err: unknown, t: (key: string) => string): MCPTestResult { + const raw = extractErrorMessage(err, ''); + if (isServiceRefusal(err) && raw) return { success: false, message: raw, refused: true }; + return { success: false, message: t('sheet.mcpConnectFailed'), detail: raw || undefined }; +} + +export function mcpTestOutcome( + data: { success?: boolean; message?: string; latency_ms?: number; tools_count?: number }, + t: (key: string) => string, +): MCPTestResult { + const success = data.success ?? false; + return { + success, + message: success ? (data.message ?? t('sheet.connSuccess')) : t('sheet.mcpConnectFailed'), + detail: success ? undefined : data.message || undefined, + latency: data.latency_ms, + tools_count: data.tools_count, + }; +} + export function buildMCPConfigFromForm(formData: MCPFormData): Record { const config: Record = { type: formData.connType }; if (formData.connType === 'stdio') { @@ -250,9 +311,11 @@ interface MCPFormFieldsProps { onChange?: (fields: Partial) => void; disabledFields?: Partial>; connStatus: ConnStatus; - testResult: { success: boolean; message: string; tools_count?: number } | null; + testResult: MCPTestResult | null; onTestConnection: () => void; isTesting: boolean; + /** Messages for the fields the user still has to fix (see getMCPFieldErrors). */ + fieldErrors?: MCPFieldErrors; } export function MCPFormFields({ @@ -263,9 +326,13 @@ export function MCPFormFields({ testResult, onTestConnection, isTesting, + fieldErrors, }: MCPFormFieldsProps) { const { t } = useTranslation('tool'); const readOnly = !onChange; + const fieldError = (field: keyof MCPFieldErrors) => fieldErrors?.[field] + ?

{t(`addMCP.errors.${fieldErrors[field]}`)}

+ : null; const baseInputClass = 'w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-red-500'; @@ -290,8 +357,10 @@ export function MCPFormFields({ onChange={isFieldReadOnly('name') ? undefined : (e) => update({ name: e.target.value })} readOnly={isFieldReadOnly('name')} placeholder={t('addMCP.serviceNamePlaceholder')} + aria-invalid={fieldErrors?.name ? true : undefined} className={inputClassFor('name')} /> + {fieldError('name')}
{/* 连接方式 */} @@ -336,8 +405,10 @@ export function MCPFormFields({ onChange={isFieldReadOnly('command') ? undefined : (e) => update({ command: e.target.value })} readOnly={isFieldReadOnly('command')} placeholder={t('addMCP.startCommandPlaceholder')} + aria-invalid={fieldErrors?.command ? true : undefined} className={inputClassFor('command', 'font-mono')} /> + {fieldError('command')}
@@ -368,6 +439,7 @@ export function MCPFormFields({ onChange={isFieldReadOnly('url') ? undefined : (e) => update({ url: e.target.value })} readOnly={isFieldReadOnly('url')} placeholder={t('addMCP.serviceUrlPlaceholder')} + aria-invalid={fieldErrors?.url ? true : undefined} className={`${inputClassFor('url', 'font-mono')} flex-1 min-w-0`} />
+ {fieldError('url')}
@@ -490,9 +563,10 @@ export function MCPFormFields({ readOnly={isFieldReadOnly('headersText')} placeholder={t('addMCP.extraHeadersPlaceholder')} rows={4} + aria-invalid={fieldErrors?.headersText ? true : undefined} className={inputClassFor('headersText', 'font-mono')} /> - {!readOnly &&

{t('addMCP.extraHeadersHint')}

} + {fieldError('headersText') ?? (!readOnly &&

{t('addMCP.extraHeadersHint')}

)}
)} @@ -522,7 +596,10 @@ export function MCPFormFields({ ? : } - {testResult.message} +
+

{testResult.message}

+ {testResult.detail &&

{testResult.detail}

} +
)} @@ -561,22 +638,20 @@ export function MCPSheet({ onClose, onSaved, onRefresh }: MCPSheetProps) { }); const [submitting, setSubmitting] = useState(false); const [connStatus, setConnStatus] = useState('idle'); - const [testResult, setTestResult] = useState<{ - success: boolean; - message: string; - tools_count?: number; - } | null>(null); + const [testResult, setTestResult] = useState(null); + const [fieldErrors, setFieldErrors] = useState({}); const canSubmit = !!(formData.name.trim() && (formData.connType === 'stdio' ? formData.command.trim() : formData.url.trim())); - const formError = getMCPFormError(formData); + const validate = () => { + const errors = getMCPFieldErrors(formData); + setFieldErrors(errors); + return Object.keys(errors).length === 0; + }; const handleSubmit = async () => { if (!canSubmit || submitting) return; - if (formError === 'invalidHeaders') { - alert(t('alert.invalidHeaders')); - return; - } + if (!validate()) return; try { setSubmitting(true); await client.post('/api/mcp', { name: formData.name, config: buildMCPConfigFromForm(formData) }); @@ -590,38 +665,29 @@ export function MCPSheet({ onClose, onSaved, onRefresh }: MCPSheetProps) { const update = (fields: Partial) => { setFormData(prev => ({ ...prev, ...fields })); - // 表单变化时重置测试状态 - if (connStatus !== 'idle') { - setConnStatus('idle'); - setTestResult(null); - } + setFieldErrors(prev => clearMCPFieldErrors(prev, fields)); + // 表单变化时重置测试状态(被拒绝的请求状态是 idle,结果同样要清掉) + setTestResult(null); + if (connStatus !== 'idle') setConnStatus('idle'); }; /** 仅测试连接,不保存到配置 */ const handleTestConnection = async () => { - if (!canSubmit || connStatus === 'testing') return; - if (formError === 'invalidHeaders') { - alert(t('alert.invalidHeaders')); - return; - } + if (connStatus === 'testing') return; + // Missing or malformed fields are answered under the field: no connection was tried. + if (!validate()) return; setTestResult(null); setConnStatus('testing'); try { const res = await mcpAPI.test(formData.name, buildMCPConfigFromForm(formData)); - const data = res.data; - const success = data.success ?? false; - setConnStatus(success ? 'tested' : 'failed'); - setTestResult({ - success, - message: data.message ?? (success ? t('sheet.connSuccess') : t('sheet.connFailed')), - tools_count: data.tools_count, - }); - } catch (err: any) { - setConnStatus('failed'); - setTestResult({ - success: false, - message: err.response?.data?.detail ?? err.message ?? t('detail.testFailed'), - }); + const outcome = mcpTestOutcome(res.data, t); + setConnStatus(outcome.success ? 'tested' : 'failed'); + setTestResult(outcome); + } catch (err: unknown) { + const outcome = mcpTestFailure(err, t); + // A refused request never reached the service: no "connection failed" badge. + setConnStatus(outcome.refused ? 'idle' : 'failed'); + setTestResult(outcome); } }; @@ -655,6 +721,7 @@ export function MCPSheet({ onClose, onSaved, onRefresh }: MCPSheetProps) { testResult={testResult} onTestConnection={handleTestConnection} isTesting={isTesting} + fieldErrors={fieldErrors} /> {/* 测试后展示工具数/资源数(与详情页样式一致) */} {testResult?.tools_count != null && ( diff --git a/webui/src/pages/Tool/components/APITabContent.tsx b/webui/src/pages/Tool/components/APITabContent.tsx index a544439e1..8a7d90c8a 100644 --- a/webui/src/pages/Tool/components/APITabContent.tsx +++ b/webui/src/pages/Tool/components/APITabContent.tsx @@ -15,7 +15,7 @@ import { getCatalogDescription } from '@/utils/mcpCatalog'; import { APIServiceDetailPanel } from './ServiceDetailPanel'; import { SERVICE_TAB_GRID_COLS } from './gridLayout'; import GroupNav, { useGroupDrag } from '@/components/plugin-groups/GroupNav'; -import { deriveGroupNav, matchesGroup, saveGroupItems, type GroupSelection } from '@/components/plugin-groups/groupView'; +import { deriveGroupNav, matchesGroup, saveGroupItems, type GroupSelection, groupNoun } from '@/components/plugin-groups/groupView'; import { useAuth } from '@/contexts/AuthContext'; import { extractErrorMessage } from '@/utils/error'; @@ -336,12 +336,12 @@ export default function APITabContent({ // builtin, credentials and enabled state do not establish group ownership. const asServiceGroupItem = (service: APIServiceSummary) => ({ key: service.id, name: service.name, group: service.group, - readOnlyReason: service.group_readonly ? t('pluginGroups:readOnly.system') + readOnlyReason: service.group_readonly ? t('pluginGroups:readOnly.system', groupNoun(t, 'api')) : user?.role === 'admin' ? undefined : t('pluginGroups:readOnly.admin'), }); const asCatalogGroupItem = (entry: MCPCatalogEntry) => ({ key: `catalog:${entry.id}`, name: entry.name, group: entry.group, - readOnlyReason: t(entry.group_readonly ? 'pluginGroups:readOnly.system' : 'pluginGroups:readOnly.catalog'), + readOnlyReason: t(entry.group_readonly ? 'pluginGroups:readOnly.system' : 'pluginGroups:readOnly.catalog', groupNoun(t, 'api')), }); const groupInventory = (nativeServices: APIServiceSummary[]) => [ ...nativeServices.map(asServiceGroupItem), @@ -361,18 +361,18 @@ export default function APITabContent({ }; const moveGroup = async (key: string, group: string | null) => { const inventory = await loadGroupItems(); - await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroupData, t); + await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroupData, t, false, 'api'); }; const createGroup = async (key: string, group: string) => { const inventory = await loadGroupItems(); if (inventory.some((item) => matchesGroup(item.group, group))) throw new Error(t('pluginGroups:validation.duplicate')); - await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroupData, t); + await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroupData, t, false, 'api'); }; const changeGroup = async (from: string, to: string | null) => { const inventory = await loadGroupItems(); if (to !== null && inventory.some((item) => matchesGroup(item.group, to))) throw new Error(t('pluginGroups:validation.duplicate')); const members = inventory.filter((item) => matchesGroup(item.group, from)); - await saveGroupItems(members, to, saveGroup, reloadGroupData, t, true); + await saveGroupItems(members, to, saveGroup, reloadGroupData, t, true, 'api'); }; const query = searchQuery.trim().toLowerCase(); const matchesQuery = (...values: (string | undefined)[]) => !query || values.some((value) => value?.toLowerCase().includes(query)); @@ -384,7 +384,7 @@ export default function APITabContent({ return (
- changeGroup(name, null)} {...groupDrag} /> + changeGroup(name, null)} {...groupDrag} />
{servicesError !== null &&
{extractErrorMessage(servicesError, t('alert.refreshFailedTitle'))} diff --git a/webui/src/pages/Tool/components/MCPTabContent.tsx b/webui/src/pages/Tool/components/MCPTabContent.tsx index cfad018e8..d11450147 100644 --- a/webui/src/pages/Tool/components/MCPTabContent.tsx +++ b/webui/src/pages/Tool/components/MCPTabContent.tsx @@ -16,7 +16,7 @@ import { getCatalogDescription, getMetadataDescription } from '@/utils/mcpCatalo import { MCPServerDetailPanel } from './ServiceDetailPanel'; import { SERVICE_TAB_GRID_COLS } from './gridLayout'; import GroupNav, { useGroupDrag } from '@/components/plugin-groups/GroupNav'; -import { deriveGroupNav, matchesGroup, saveGroupItems, type GroupSelection } from '@/components/plugin-groups/groupView'; +import { deriveGroupNav, matchesGroup, saveGroupItems, type GroupSelection, groupNoun } from '@/components/plugin-groups/groupView'; import { useAuth } from '@/contexts/AuthContext'; import { extractErrorMessage } from '@/utils/error'; @@ -449,12 +449,12 @@ export default function MCPTabContent({ // A configured service wins over its catalog default, including an explicit clear. const asServerGroupItem = (server: MCPServer) => ({ key: server.name, name: catalogEntryById.get(server.name)?.name || server.name, group: server.group, - readOnlyReason: server.group_readonly ? t('pluginGroups:readOnly.system') + readOnlyReason: server.group_readonly ? t('pluginGroups:readOnly.system', groupNoun(t, 'mcp')) : user?.role === 'admin' ? undefined : t('pluginGroups:readOnly.admin'), }); const asCatalogGroupItem = (entry: MCPCatalogEntry) => ({ key: entry.id, name: entry.name, group: entry.group, - readOnlyReason: t(entry.group_readonly ? 'pluginGroups:readOnly.system' : 'pluginGroups:readOnly.catalog'), + readOnlyReason: t(entry.group_readonly ? 'pluginGroups:readOnly.system' : 'pluginGroups:readOnly.catalog', groupNoun(t, 'mcp')), }); const groupInventory = (nativeServers: MCPServer[]) => [ ...nativeServers.map(asServerGroupItem), @@ -468,18 +468,18 @@ export default function MCPTabContent({ const loadGroupItems = async () => groupInventory(serverRows((await mcpAPI.list()).data)); const moveGroup = async (key: string, group: string | null) => { const inventory = await loadGroupItems(); - await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroupData, t); + await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroupData, t, false, 'mcp'); }; const createGroup = async (key: string, group: string) => { const inventory = await loadGroupItems(); if (inventory.some((item) => matchesGroup(item.group, group))) throw new Error(t('pluginGroups:validation.duplicate')); - await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroupData, t); + await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroupData, t, false, 'mcp'); }; const changeGroup = async (from: string, to: string | null) => { const inventory = await loadGroupItems(); if (to !== null && inventory.some((item) => matchesGroup(item.group, to))) throw new Error(t('pluginGroups:validation.duplicate')); const members = inventory.filter((item) => matchesGroup(item.group, from)); - await saveGroupItems(members, to, saveGroup, reloadGroupData, t, true); + await saveGroupItems(members, to, saveGroup, reloadGroupData, t, true, 'mcp'); }; const visibleCards = unifiedCards.filter(({ runtimeServer, entry }) => ( matchesGroup(runtimeServer ? runtimeServer.group : entry?.group, groupSelection) @@ -487,7 +487,7 @@ export default function MCPTabContent({ return (
- changeGroup(name, null)} {...groupDrag} /> + changeGroup(name, null)} {...groupDrag} />
{serversError !== null &&
{extractErrorMessage(serversError, t('alert.refreshFailedTitle'))} diff --git a/webui/src/pages/Tool/components/ServiceDetailPanel.test.tsx b/webui/src/pages/Tool/components/ServiceDetailPanel.test.tsx index 9913e8c64..fe8631340 100644 --- a/webui/src/pages/Tool/components/ServiceDetailPanel.test.tsx +++ b/webui/src/pages/Tool/components/ServiceDetailPanel.test.tsx @@ -56,6 +56,12 @@ vi.mock('../ToolSheets', () => ({ } ), getMCPFormError: () => null, + getMCPFieldErrors: () => ({}), + clearMCPFieldErrors: (errors: Record) => errors, + mcpTestOutcome: (data: { success?: boolean; message?: string; tools_count?: number }) => ({ + success: data.success ?? false, message: data.message ?? '', tools_count: data.tools_count, + }), + mcpTestFailure: (err: { message?: string }) => ({ success: false, message: err?.message ?? '' }), buildMCPFormDataFromConfig: ( name: string, config?: { type?: 'stdio' | 'sse' | 'local' | 'remote'; url?: string } | null, diff --git a/webui/src/pages/Tool/components/ServiceDetailPanel.tsx b/webui/src/pages/Tool/components/ServiceDetailPanel.tsx index 05a7e7f2b..4b970bc3f 100644 --- a/webui/src/pages/Tool/components/ServiceDetailPanel.tsx +++ b/webui/src/pages/Tool/components/ServiceDetailPanel.tsx @@ -12,7 +12,7 @@ import { toolAPI } from '@/api/tool'; import LoadingSpinner from '@/components/common/LoadingSpinner'; import { getCatalogDescription, getMetadataDescription } from '@/utils/mcpCatalog'; import { EnabledBadge } from './badges'; -import { buildMCPConfigFromForm, buildMCPFormDataFromConfig, getMCPFormError, MCPFormFields } from '../ToolSheets'; +import { buildMCPConfigFromForm, buildMCPFormDataFromConfig, clearMCPFieldErrors, getMCPFieldErrors, MCPFormFields, mcpTestFailure, mcpTestOutcome, type MCPFieldErrors, type MCPTestResult } from '../ToolSheets'; import type { MCPFormData, ConnStatus as MCPConnStatus } from '../ToolSheets'; import type { APIServiceCredentialField, APIServiceMetadata, ProviderCredentials } from '@/types'; import ThreatBookMCPConfigPanel from './ThreatBookMCPConfigPanel'; @@ -89,7 +89,8 @@ export function MCPServerDetailPanel({ const [initialFormData, setInitialFormData] = useState(null); const [detailLoading, setDetailLoading] = useState(true); const [testingConnection, setTestingConnection] = useState(false); - const [testResult, setTestResult] = useState<{ success: boolean; message: string; latency?: number; tools_count?: number } | null>(null); + const [testResult, setTestResult] = useState(null); + const [fieldErrors, setFieldErrors] = useState({}); const [refreshing, setRefreshing] = useState(false); const [savingConfig, setSavingConfig] = useState(false); const isThreatBookServer = isThreatBookMCPServer(server.name); @@ -132,32 +133,30 @@ export function MCPServerDetailPanel({ const handleFormChange = (fields: Partial) => { setFormData((prev) => (prev ? { ...prev, ...fields } : prev)); + setFieldErrors((prev) => clearMCPFieldErrors(prev, fields)); setTestResult(null); }; + const validate = (data: MCPFormData) => { + const errors = getMCPFieldErrors(data); + setFieldErrors(errors); + return Object.keys(errors).length === 0; + }; + const handleTestConnection = async () => { if (!formData) return; - if (getMCPFormError(formData) === 'invalidHeaders') { - alert(t('alert.invalidHeaders')); - return; - } + if (!validate(formData)) return; setTestingConnection(true); setTestResult(null); const currentConfig = buildMCPConfigFromForm(formData); try { const res = await mcpAPI.testExisting(server.name, currentConfig); - const data = res.data; - setTestResult({ - success: data.success ?? false, - message: data.message ?? (data.success ? t('alert.connectionOk') : t('detail.testFailed')), - latency: data.latency_ms, - tools_count: data.tools_count, - }); - } catch (err: any) { - setTestResult({ - success: false, - message: err.response?.data?.detail ?? err.message ?? t('detail.testFailed'), - }); + setTestResult(mcpTestOutcome({ + ...res.data, + message: res.data.message ?? (res.data.success ? t('alert.connectionOk') : undefined), + }, t)); + } catch (err: unknown) { + setTestResult(mcpTestFailure(err, t)); } finally { setSavingConfig(false); setTestingConnection(false); @@ -166,10 +165,7 @@ export function MCPServerDetailPanel({ const handleSaveConfig = async () => { if (!formData || !isDirty) return; - if (getMCPFormError(formData) === 'invalidHeaders') { - alert(t('alert.invalidHeaders')); - return; - } + if (!validate(formData)) return; try { setSavingConfig(true); setTestResult(null); @@ -186,6 +182,7 @@ export function MCPServerDetailPanel({ const handleResetConfig = () => { if (!initialFormData) return; setFormData(initialFormData); + setFieldErrors({}); setTestResult(null); }; @@ -255,16 +252,18 @@ export function MCPServerDetailPanel({ ? 'saving' : testingConnection ? 'testing' - : testResult?.success === false + // A request the service refused never tried the connection. + : testResult?.success === false && !testResult.refused ? 'failed' : server.status === 'connected' ? 'connected' : testResult?.success === true ? 'tested' : 'idle'} - testResult={testResult ? { success: testResult.success, message: testResult.message, tools_count: testResult.tools_count } : null} + testResult={testResult} onTestConnection={handleTestConnection} isTesting={testingConnection} + fieldErrors={fieldErrors} /> )} diff --git a/webui/src/pages/Tool/index.tsx b/webui/src/pages/Tool/index.tsx index 71d6c8ea9..809b57b75 100644 --- a/webui/src/pages/Tool/index.tsx +++ b/webui/src/pages/Tool/index.tsx @@ -49,7 +49,7 @@ import { useToast } from '@/components/common/Toast'; import { useToolPage } from '@/hooks/useTools'; import GroupNav, { useGroupDrag, type GroupDrag } from '@/components/plugin-groups/GroupNav'; import PluginGroupButton from '@/components/plugin-groups/PluginGroupButton'; -import { assertGroupItemsEditable, saveGroupItems, type GroupSelection } from '@/components/plugin-groups/groupView'; +import { assertGroupItemsEditable, saveGroupItems, type GroupSelection, groupNoun } from '@/components/plugin-groups/groupView'; import { useAuth } from '@/contexts/AuthContext'; import { usePluginViewMode } from '@/hooks/usePluginViewMode'; import PluginViewToggle from '@/components/plugin-groups/PluginViewToggle'; @@ -60,7 +60,7 @@ import { mcpAPI, MCPServer } from '@/api/mcp'; import { providerAPI } from '@/api/provider'; import client from '@/api/client'; import type { MCPServerDetail, MCPCredentials, MCPCredentialInput, MCPCatalogEntry, MCPCatalogCategory } from '@/types'; -import { MCPSheet, APISheet, GenerateToolSheet, MCPFormFields, buildMCPFormDataFromConfig } from './ToolSheets'; +import { MCPSheet, APISheet, GenerateToolSheet, MCPFormFields, buildMCPFormDataFromConfig, mcpTestFailure, mcpTestOutcome, type MCPTestResult } from './ToolSheets'; import type { MCPFormData, ConnStatus as MCPConnStatus } from './ToolSheets'; import MCPTabContent from './components/MCPTabContent'; import APITabContent from './components/APITabContent'; @@ -350,7 +350,7 @@ export default function ToolPage() { const readOnlyReason = user?.role === 'admin' ? undefined : t('pluginGroups:readOnly.admin'); const asGroupItem = (tool: Tool) => ({ key: tool.name, name: tool.name, group: tool.group, - readOnlyReason: tool.group_readonly ? t('pluginGroups:readOnly.system') : readOnlyReason, + readOnlyReason: tool.group_readonly ? t('pluginGroups:readOnly.system', groupNoun(t, 'tool')) : readOnlyReason, }); const toolGroupItems = tools.map(asGroupItem); const toolGroupDrag = useGroupDrag(toolGroupItems, toast.warning); @@ -378,7 +378,7 @@ export default function ToolPage() { }; const moveToolGroup = async (key: string, group: string | null) => { const { data } = await toolAPI.get(key); - await saveGroupItems([asGroupItem(data)], group, saveToolGroup, reloadToolGroups, t); + await saveGroupItems([asGroupItem(data)], group, saveToolGroup, reloadToolGroups, t, false, 'tool'); }; const ensureNewToolGroup = async (name: string) => { // Query-independent native facets include names hidden by search, columns or tabs. @@ -396,12 +396,12 @@ export default function ToolPage() { // Audit the entire native group, including members hidden by query, columns, // tabs or pagination. Counts and the loaded 25 rows cannot prove writability. const wholeGroup = await listAllToolPages({ group: from, sortBy: toolPageParams.sortBy, sortDir: toolPageParams.sortDir }, { requireComplete: true }); - assertGroupItemsEditable(wholeGroup.map(asGroupItem), t); + assertGroupItemsEditable(wholeGroup.map(asGroupItem), t, 'tool'); // Keep the existing write scope explicit in the single native confirmation. const members = hasToolInventoryFilters ? await listAllToolPages({ ...toolPageParams, group: from }, { requireComplete: true }) : wholeGroup; - await saveGroupItems(members.map(asGroupItem), to, saveToolGroup, reloadToolGroups, t, true); + await saveGroupItems(members.map(asGroupItem), to, saveToolGroup, reloadToolGroups, t, true, 'tool'); }; const selectToolGroup = useCallback((name: GroupSelection) => { setToolGroup(name); @@ -409,7 +409,7 @@ export default function ToolPage() { }, []); // A failed first request has no facets, not an authoritative empty inventory. // Do not let it clear the selected group and silently fall back to All. - const toolGroupNav = toolFacets.group ? changeToolGroup(name, null)} {...toolGroupDrag} /> : null; @@ -1601,7 +1601,7 @@ function MCPServerDetailPanel({ const [serverDetail, setServerDetail] = useState(null); const [detailLoading, setDetailLoading] = useState(true); const [testingConnection, setTestingConnection] = useState(false); - const [testResult, setTestResult] = useState<{ success: boolean; message: string; latency?: number; tools_count?: number } | null>(null); + const [testResult, setTestResult] = useState(null); const [refreshing, setRefreshing] = useState(false); useEffect(() => { @@ -1626,22 +1626,14 @@ function MCPServerDetailPanel({ try { const res = await mcpAPI.testCredentials(server.name); const data = res.data; - setTestResult({ - success: data.success ?? false, - message: data.message ?? (data.success ? t('alert.connectionOk') : t('detail.testFailed')), - latency: data.latency_ms, - tools_count: data.tools_count, - }); + setTestResult(mcpTestOutcome({ ...data, message: data.message ?? (data.success ? t('alert.connectionOk') : undefined) }, t)); if (data.success) { const detailRes = await mcpAPI.get(server.name); setServerDetail(detailRes.data); await onRefresh(); } - } catch (err: any) { - setTestResult({ - success: false, - message: err.response?.data?.detail ?? err.message ?? t('detail.testFailed'), - }); + } catch (err: unknown) { + setTestResult(mcpTestFailure(err, t)); } finally { setTestingConnection(false); } @@ -1694,7 +1686,8 @@ function MCPServerDetailPanel({ ? 'testing' : testResult?.success === true ? 'connected' - : testResult?.success === false + // A request the service refused never tried the connection. + : testResult?.success === false && !testResult.refused ? 'failed' : server.status === 'connected' ? 'connected' @@ -1703,7 +1696,7 @@ function MCPServerDetailPanel({ diff --git a/webui/src/pages/Workflow/index.tsx b/webui/src/pages/Workflow/index.tsx index 6feb32a39..c41967df6 100644 --- a/webui/src/pages/Workflow/index.tsx +++ b/webui/src/pages/Workflow/index.tsx @@ -25,7 +25,7 @@ import { } from '@/api/workflow'; import { getWorkflowDisplayName } from '@/utils/workflowDisplay'; import GroupNav, { useGroupDrag, type GroupDrag } from '@/components/plugin-groups/GroupNav'; -import { deriveGroupNav, matchesGroup, saveGroupItems, type GroupSelection } from '@/components/plugin-groups/groupView'; +import { deriveGroupNav, matchesGroup, saveGroupItems, type GroupSelection, groupNoun } from '@/components/plugin-groups/groupView'; import PluginViewToggle from '@/components/plugin-groups/PluginViewToggle'; import { usePluginViewMode, type PluginViewMode } from '@/hooks/usePluginViewMode'; import { workflowAPI } from '@/api/workflow'; @@ -97,7 +97,7 @@ export default function WorkflowPage() { const [groupSelection, setGroupSelection] = useState(null); const asGroupItem = (workflow: WorkflowSummary) => ({ key: workflow.id, name: getWorkflowDisplayName(workflow, i18n?.language), group: workflow.group, - readOnlyReason: workflow.group_readonly ? t('pluginGroups:readOnly.system') : undefined, + readOnlyReason: workflow.group_readonly ? t('pluginGroups:readOnly.system', groupNoun(t, 'workflow')) : undefined, }); const groupItems = workflows.map(asGroupItem); const { warning } = useToast(); @@ -107,17 +107,17 @@ export default function WorkflowPage() { const loadGroupItems = async () => (await workflowAPI.listSummaries()).data.map(asGroupItem); const moveGroup = async (key: string, group: string | null) => { const inventory = await loadGroupItems(); - await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroups, t); + await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroups, t, false, 'workflow'); }; const createGroup = async (key: string, group: string) => { const inventory = await loadGroupItems(); if (inventory.some((item) => matchesGroup(item.group, group))) throw new Error(t('pluginGroups:validation.duplicate')); - await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroups, t); + await saveGroupItems(inventory.filter((item) => item.key === key), group, saveGroup, reloadGroups, t, false, 'workflow'); }; const changeGroup = async (from: string, to: string | null) => { const inventory = await loadGroupItems(); if (to !== null && inventory.some((item) => matchesGroup(item.group, to))) throw new Error(t('pluginGroups:validation.duplicate')); - await saveGroupItems(inventory.filter((item) => matchesGroup(item.group, from)), to, saveGroup, reloadGroups, t, true); + await saveGroupItems(inventory.filter((item) => matchesGroup(item.group, from)), to, saveGroup, reloadGroups, t, true, 'workflow'); }; const openFreshCreate = () => { @@ -224,7 +224,7 @@ export default function WorkflowPage() { className="flex-1 min-h-0 overflow-y-auto px-4 py-4 flex flex-col gap-4 md:flex-row max-md:px-0" style={{ scrollbarGutter: 'stable' }} > - changeGroup(name, null)} {...groupDrag} /> + changeGroup(name, null)} {...groupDrag} />
{workflows.length === 0 ? ( { expect(screen.getByText('8 B')).toBeInTheDocument(); }); + it('新建目录名称为空时在输入框下方提示,不请求服务端', async () => { + mocks.list.mockResolvedValue({ data: [] }); + const user = userEvent.setup(); + renderWithRouter(); + + await user.click(await screen.findByTitle('New directory')); + await user.type(screen.getByPlaceholderText('Folder name'), ' '); + await user.click(screen.getByRole('button', { name: 'Create' })); + + expect(screen.getByRole('alert')).toHaveTextContent('files.dirNameRequired'); + expect(mocks.createDir).not.toHaveBeenCalled(); + await user.type(screen.getByPlaceholderText('Folder name'), 'reports'); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + }); + + it('同名目录已存在时保留输入并提示改名', async () => { + mocks.list.mockResolvedValue({ data: [] }); + mocks.createDir.mockResolvedValue({ data: { path: 'reports', created: false } }); + const user = userEvent.setup(); + renderWithRouter(); + + await user.click(await screen.findByTitle('New directory')); + await user.type(screen.getByPlaceholderText('Folder name'), 'reports'); + await user.click(screen.getByRole('button', { name: 'Create' })); + + expect(await screen.findByRole('alert')).toHaveTextContent('files.dirNameExists'); + expect(screen.getByPlaceholderText('Folder name')).toHaveValue('reports'); + expect(mocks.toastError).not.toHaveBeenCalled(); + }); + + it('同名文件占用时提示改名,不弹失败 toast', async () => { + mocks.list.mockResolvedValue({ data: [] }); + mocks.createDir.mockRejectedValue({ response: { status: 409, data: { detail: 'A file already exists at: notes' } } }); + const user = userEvent.setup(); + renderWithRouter(); + + await user.click(await screen.findByTitle('New directory')); + await user.type(screen.getByPlaceholderText('Folder name'), 'notes'); + await user.click(screen.getByRole('button', { name: 'Create' })); + + expect(await screen.findByRole('alert')).toHaveTextContent('files.dirNameTakenByFile'); + expect(mocks.toastError).not.toHaveBeenCalled(); + }); + it('新建目录失败时 toast 展示服务端 message(HTTPException 错误体)', async () => { mocks.list.mockResolvedValue({ data: [] }); mocks.createDir.mockRejectedValue({ diff --git a/webui/src/pages/Workspace/index.tsx b/webui/src/pages/Workspace/index.tsx index db3644a85..917b19e98 100644 --- a/webui/src/pages/Workspace/index.tsx +++ b/webui/src/pages/Workspace/index.tsx @@ -203,7 +203,8 @@ function FilesTab() { // Upload / new-dir state const [uploading, setUploading] = useState(false); - const [newDir, setNewDir] = useState<{ show: boolean; name: string }>({ show: false, name: '' }); + // `error` stays under the name field; the input stays open so the name can be fixed. + const [newDir, setNewDir] = useState<{ show: boolean; name: string; error?: string }>({ show: false, name: '' }); const [dragOver, setDragOver] = useState(false); const [previewModalOpen, setPreviewModalOpen] = useState(false); @@ -345,13 +346,25 @@ function FilesTab() { const handleCreateDir = useCallback(async () => { const name = newDir.name.trim(); - if (!name) return; + if (!name) { + setNewDir((d) => ({ ...d, error: t('files.dirNameRequired') })); + return; + } const path = currentPath ? `${currentPath}/${name}` : name; try { - await workspaceAPI.createDir(path); + const res = await workspaceAPI.createDir(path); + // The endpoint is idempotent: an existing directory comes back as created: false. + if (res.data?.created === false) { + setNewDir((d) => ({ ...d, error: t('files.dirNameExists') })); + return; + } setNewDir({ show: false, name: '' }); loadDir(currentPath); } catch (e: any) { + if (e?.response?.status === 409) { + setNewDir((d) => ({ ...d, error: t('files.dirNameTakenByFile') })); + return; + } toastError(t('files.toast.createDirFailed'), extractErrorMessage(e)); } }, [newDir.name, currentPath, loadDir, toastError, t]); @@ -446,12 +459,15 @@ function FilesTab() {
{newDir.show && ( -
+
+
setNewDir((d) => ({ ...d, name: e.target.value }))} + onChange={(e) => setNewDir((d) => ({ ...d, name: e.target.value, error: undefined }))} + aria-invalid={newDir.error ? true : undefined} + aria-describedby={newDir.error ? 'workspace-new-dir-error' : undefined} onKeyDown={(e) => { if (e.key === 'Enter') handleCreateDir(); if (e.key === 'Escape') setNewDir({ show: false, name: '' }); @@ -464,6 +480,8 @@ function FilesTab() {
+ {newDir.error && } +
)}
{ it('falls back to full release notes when no details section is present', () => { @@ -99,3 +99,49 @@ describe('getLocalizedReleaseNotes', () => { ); }); }); + +describe('release notes written as commit subjects (v0.21 #49)', () => { + const notes = [ + "## What's Changed", + '', + '* feat(models): streamline model discovery and imports', + '* fix(enterprise): improve Flocks Pro installation and licensing flows', + '', + '
', + 'Chinese Release Notes', + '', + '* feat(models):简化模型发现与导入,支持向导草稿恢复和 Azure 部署配置', + '* fix(runtime):就地升级保留额外 Python 依赖,保护配置凭据和受管环境,修复 Windows 多实例控制问题', + '* fix(something-new):修复一个问题', + '* 已经写成读者语言的一行。', + '', + '
', + ].join('\n'); + + it('names the area instead of the commit type and module', () => { + expect(getLocalizedReleaseNotes(notes, 'zh-CN')).toBe([ + '* 模型管理:简化模型发现与导入,支持向导草稿恢复和 Azure 部署配置。', + '* 运行环境:就地升级保留额外 Python 依赖,保护配置凭据和受管环境,修复 Windows 多实例控制问题。', + '* 修复一个问题。', + '* 已经写成读者语言的一行。', + ].join('\n')); + expect(getLocalizedReleaseNotes(notes, 'en-US')).toContain('* Models: streamline model discovery and imports'); + expect(getLocalizedReleaseNotes(notes, 'en-US')).toContain('* Enterprise edition: improve Flocks Pro installation'); + }); + + it('leaves examples in fenced code blocks as written', () => { + expect(humanizeReleaseNotes(['```', '* fix: example command', '```', '* fix(models):真的一条'].join('\n'), 'zh')) + .toBe(['```', '* fix: example command', '```', '* 模型管理:真的一条。'].join('\n')); + }); + + it('keeps a longer fence open across a shorter fence inside it', () => { + const notes = ['````', '```', '* fix: example command', '```', '````', '* fix(models):真的一条'].join('\n'); + expect(humanizeReleaseNotes(notes, 'zh')) + .toBe(['````', '```', '* fix: example command', '```', '````', '* 模型管理:真的一条。'].join('\n')); + }); + + it('leaves headings and ordinary text alone', () => { + expect(humanizeReleaseNotes('## fix: not a bullet\nfeat(models): not a bullet either', 'zh')) + .toBe('## fix: not a bullet\nfeat(models): not a bullet either'); + }); +}); diff --git a/webui/src/utils/releaseNotes.ts b/webui/src/utils/releaseNotes.ts index 45796ae38..e8740dc68 100644 --- a/webui/src/utils/releaseNotes.ts +++ b/webui/src/utils/releaseNotes.ts @@ -58,14 +58,60 @@ const removeDetailsBlocks = (notes: string, sections: DetailsSection[]) => ( .trim() ); -export const getLocalizedReleaseNotes = ( - notes: string | null | undefined, - language: string | null | undefined, -): string => { - const fallback = notes?.trim() ?? ''; - if (!fallback) return ''; +/** Readers' names for the commit scopes release notes are written with. */ +const SCOPE_LABELS: Record<'zh' | 'en', Record> = { + zh: { + models: '模型管理', model: '模型管理', session: '会话', webui: '界面', ui: '界面', workflow: '工作流', + enterprise: '企业版', runtime: '运行环境', agent: '智能体', agents: '智能体', tool: '工具', tools: '工具', + mcp: 'MCP', skill: '技能', skills: '技能', channel: '通道', channels: '通道', task: '任务', tasks: '任务', + device: '设备', devices: '设备', hub: '场景套件', auth: '账号', security: '安全', updater: '升级', update: '升级', + }, + en: { + models: 'Models', model: 'Models', session: 'Sessions', webui: 'Interface', ui: 'Interface', workflow: 'Workflows', + enterprise: 'Enterprise edition', runtime: 'Runtime', agent: 'Agents', agents: 'Agents', tool: 'Tools', tools: 'Tools', + mcp: 'MCP', skill: 'Skills', skills: 'Skills', channel: 'Channels', channels: 'Channels', task: 'Tasks', tasks: 'Tasks', + device: 'Devices', devices: 'Devices', hub: 'Scene suites', auth: 'Accounts', security: 'Security', updater: 'Updates', update: 'Updates', + }, +}; - const targetLanguage = (language ?? '').toLowerCase().startsWith('zh') ? 'zh' : 'en'; +const COMMIT_PREFIX = /^(\s*[-*]\s+)(?:feat|fix|perf|refactor|chore|docs|build|ci|style|test)(?:\(([^)]+)\))?!?\s*[::]\s*(.+)$/i; + +/** + * Release notes are written as commit subjects ("feat(models):简化模型发现…"). + * Readers get the area by name instead of the commit type and code module + * ("模型管理:简化模型发现…"); lines written any other way are left alone. + */ +export const humanizeReleaseNotes = (notes: string, language: 'zh' | 'en'): string => { + // Lines inside fenced code blocks are examples, shown as written. A fence closes only + // on the same character repeated at least as many times (CommonMark), so a ``` line + // inside a ```` block stays part of the example. + let fence: { char: string; length: number } | null = null; + return notes + .split('\n') + .map((line) => { + const marker = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/); + if (marker) { + const [, run, rest] = marker; + if (!fence) { + fence = { char: run[0], length: run.length }; + return line; + } + if (run[0] === fence.char && run.length >= fence.length && !rest.trim()) { + fence = null; + return line; + } + } + const match = fence ? null : line.match(COMMIT_PREFIX); + if (!match) return line; + const [, bullet, scope, text] = match; + const label = scope ? SCOPE_LABELS[language][scope.trim().toLowerCase()] : undefined; + const body = language === 'zh' && !/[。!?.!?]$/.test(text.trim()) ? `${text.trim()}。` : text.trim(); + return `${bullet}${label ? `${label}${language === 'zh' ? ':' : ': '}` : ''}${body}`; + }) + .join('\n'); +}; + +const selectLocalizedReleaseNotes = (fallback: string, targetLanguage: 'zh' | 'en'): string => { const detailsSections = parseDetailsSections(fallback); const matchedDetails = detailsSections.find((section) => section.language === targetLanguage); if (matchedDetails?.body) return matchedDetails.body; @@ -76,3 +122,14 @@ export const getLocalizedReleaseNotes = ( return fallback; }; + +export const getLocalizedReleaseNotes = ( + notes: string | null | undefined, + language: string | null | undefined, +): string => { + const fallback = notes?.trim() ?? ''; + if (!fallback) return ''; + + const targetLanguage = (language ?? '').toLowerCase().startsWith('zh') ? 'zh' : 'en'; + return humanizeReleaseNotes(selectLocalizedReleaseNotes(fallback, targetLanguage), targetLanguage); +}; From c1c9983ba2a7ea4d26d2e9716eccdc5788872c94 Mon Sep 17 00:00:00 2001 From: jamon Date: Thu, 12 Nov 2026 22:27:45 +0800 Subject: [PATCH 26/44] fix(tool): explain why a tool gated by a disabled service cannot be enabled and link to where the service is managed (INC-F5C08C1C) --- flocks/server/routes/tool.py | 132 +++++++++- tests/server/routes/test_tool_routes.py | 4 +- tests/server/test_tool_setting_routes.py | 227 ++++++++++++++++++ webui/src/locales/en-US/tool.json | 5 + webui/src/locales/zh-CN/tool.json | 5 + .../src/pages/Tool/ToolDetailDrawer.test.tsx | 220 ++++++++++++++++- webui/src/pages/Tool/ToolServiceGate.test.tsx | 162 +++++++++++++ .../Tool/components/APITabContent.test.tsx | 26 ++ .../pages/Tool/components/APITabContent.tsx | 11 + webui/src/pages/Tool/index.tsx | 114 ++++++++- webui/src/types/index.ts | 11 + 11 files changed, 894 insertions(+), 23 deletions(-) create mode 100644 webui/src/pages/Tool/ToolServiceGate.test.tsx diff --git a/flocks/server/routes/tool.py b/flocks/server/routes/tool.py index 34ebbd271..c78616b01 100644 --- a/flocks/server/routes/tool.py +++ b/flocks/server/routes/tool.py @@ -6,7 +6,7 @@ from dataclasses import dataclass import threading import time -from typing import Annotated, List, Optional, Dict, Any, Literal, Sequence +from typing import Annotated, List, NamedTuple, Optional, Dict, Any, Literal, Sequence from fastapi import APIRouter, Depends, HTTPException, Query, status from pydantic import BaseModel, Field, field_validator from pydantic_core import PydanticCustomError @@ -54,6 +54,21 @@ class ToolInfoResponse(BaseModel): group: Optional[str] = Field(None, description="Optional plugin group") group_readonly: bool = False enabled_customized: bool = Field(False, description="True if an enabled override is recorded in flocks.json tool_settings") + service_enabled: Optional[bool] = Field( + None, + description=( + "Enabled flag of the API service that gates this tool; null when no service gates it. " + "While it is false the tool stays disabled and a request to enable it is not applied." + ), + ) + service_integration_type: Optional[str] = Field( + None, + description=( + "integration_type of that service as the API service list reports it. " + "'device' means the service is managed on the Device Integration page, " + "not in the API service list, wherever the plugin is installed." + ), + ) requires_confirmation: bool = Field(False, description="Requires confirmation") @@ -199,6 +214,8 @@ class ToolListIndexItem: requires_confirmation: bool group: Optional[str] = None group_readonly: bool = False + service_enabled: Optional[bool] = None + service_integration_type: Optional[str] = None _TOOL_SUMMARY_CACHE_TTL_SECONDS = 5.0 @@ -242,8 +259,9 @@ def _get_tool_summary_items() -> List[ToolListIndexItem]: ): return list(_tool_summary_cache_items) + services = _ServiceLookup() items = tuple( - _build_tool_index_item(t) + _build_tool_index_item(t, services=services) for t in ToolRegistry.list_tools() if t.name not in _INTERNAL_TOOL_NAMES ) @@ -295,13 +313,22 @@ def _get_tool_source(tool_info: ToolInfo) -> tuple: return "custom", None -def _build_tool_response(t: ToolInfo, *, include_parameters: bool = True) -> ToolInfoResponse: - """Build ToolInfoResponse with source info and overlay metadata.""" +def _build_tool_response( + t: ToolInfo, + *, + include_parameters: bool = True, + services: Optional["_ServiceLookup"] = None, +) -> ToolInfoResponse: + """Build ToolInfoResponse with source info and overlay metadata. + + Pass one ``services`` lookup when building many rows for one response. + """ source, source_name = _get_tool_source(t) setting = ConfigWriter.get_tool_setting(t.name) or {} customized = "enabled" in setting enabled_default = _get_default_enabled(t) parameters = [p.model_dump() for p in t.parameters] if include_parameters else [] + state = _resolve_tool_enabled_state(t, source=source, source_name=source_name, services=services) return ToolInfoResponse( name=t.name, group=normalize_tool_group(t.group if t.group_readonly else setting.get("group", t.group)), @@ -314,17 +341,20 @@ def _build_tool_response(t: ToolInfo, *, include_parameters: bool = True) -> Too vendor=t.vendor, parameters=parameters, parameters_count=len(t.parameters), - enabled=_get_effective_tool_enabled(t, source=source, source_name=source_name), + enabled=state.enabled, enabled_default=enabled_default, enabled_customized=customized, + service_enabled=state.service_enabled, + service_integration_type=state.service_integration_type, requires_confirmation=t.requires_confirmation, ) -def _build_tool_index_item(t: ToolInfo) -> ToolListIndexItem: +def _build_tool_index_item(t: ToolInfo, *, services: Optional["_ServiceLookup"] = None) -> ToolListIndexItem: """Build the lightweight index row used by the paged list endpoint.""" source, source_name = _get_tool_source(t) setting = ConfigWriter.get_tool_setting(t.name) or {} + state = _resolve_tool_enabled_state(t, source=source, source_name=source_name, services=services) return ToolListIndexItem( name=t.name, group=normalize_tool_group(t.group if t.group_readonly else setting.get("group", t.group)), @@ -336,9 +366,11 @@ def _build_tool_index_item(t: ToolInfo) -> ToolListIndexItem: source_name=source_name, vendor=t.vendor, parameters_count=len(t.parameters), - enabled=_get_effective_tool_enabled(t, source=source, source_name=source_name), + enabled=state.enabled, enabled_default=_get_default_enabled(t), enabled_customized="enabled" in setting, + service_enabled=state.service_enabled, + service_integration_type=state.service_integration_type, requires_confirmation=t.requires_confirmation, ) @@ -359,6 +391,8 @@ def _tool_index_item_to_response(item: ToolListIndexItem) -> ToolInfoResponse: enabled=item.enabled, enabled_default=item.enabled_default, enabled_customized=item.enabled_customized, + service_enabled=item.service_enabled, + service_integration_type=item.service_integration_type, requires_confirmation=item.requires_confirmation, ) @@ -792,6 +826,87 @@ def _get_effective_tool_enabled( return tool_info.enabled and _get_api_service_enabled(source_name) +class _ServiceLookup: + """API service facts for the tool rows of one response, read once each. + + ``ConfigWriter.get_api_service_raw`` re-reads and parses ``flocks.json`` + on every call and a list response builds one row per tool, so a lookup + shared by those rows asks about each service once instead of once per + tool. It must not outlive the response it was created for. + """ + + def __init__(self) -> None: + self._enabled: Dict[str, bool] = {} + self._integration_type: Dict[str, Optional[str]] = {} + + def enabled(self, service_id: str) -> bool: + if service_id not in self._enabled: + from flocks.server.routes.provider import _get_api_service_enabled + + self._enabled[service_id] = _get_api_service_enabled(service_id) + return self._enabled[service_id] + + def integration_type(self, service_id: str) -> Optional[str]: + """Return the service's ``integration_type`` as the service list reports it. + + The API service list is the reference: a service it reports as + ``device`` is left out of the API tab and managed on the device + page. The tool's own ``source`` only says which plugin directory + it was loaded from, which can differ. + """ + if service_id not in self._integration_type: + value: Any = None + try: + from flocks.server.routes.provider import _load_api_service_summary_metadata_data + + value = (_load_api_service_summary_metadata_data(service_id) or {}).get("integration_type") + except Exception as exc: + # Unreadable metadata must not take the tool list down with it. + log.debug("tool.service_integration_type.failed", {"service": service_id, "error": str(exc)}) + normalized = value.strip().lower() if isinstance(value, str) else "" + self._integration_type[service_id] = normalized or None + return self._integration_type[service_id] + + +class _ToolEnabledState(NamedTuple): + enabled: bool + service_enabled: Optional[bool] + service_integration_type: Optional[str] + + +def _resolve_tool_enabled_state( + tool_info: ToolInfo, + *, + source: Optional[str], + source_name: Optional[str], + services: Optional[_ServiceLookup] = None, +) -> _ToolEnabledState: + """Return the enabled state of a tool and the facts about what gates it. + + ``enabled`` is exactly :func:`_get_effective_tool_enabled`. + ``service_enabled`` is the flag of the API service that gates the tool, + ``None`` when no service does. Two gates exist: PATCH refuses to open a + tool whose ``provider`` service is off (:func:`_service_allows_enable`), + and the effective state of api/device tools is ANDed with the service + named by ``source_name``; for YAML api/device tools they are the same + service. ``service_integration_type`` says where that service is + managed. Clients need both to explain why such a tool is off, cannot + be switched on, and where to go instead. + """ + effective_gate = source_name if source in ("api", "device") and source_name else None + gates = [gate for gate in dict.fromkeys((tool_info.provider, effective_gate)) if gate] + if not gates: + return _ToolEnabledState(tool_info.enabled, None, None) + services = services or _ServiceLookup() + flags = {gate: services.enabled(gate) for gate in gates} + enabled = tool_info.enabled + if effective_gate: + enabled = enabled and flags[effective_gate] + # The service to send the user to: the one that is off, else the owner. + blocking = next((gate for gate in gates if not flags[gate]), gates[0]) + return _ToolEnabledState(enabled, all(flags.values()), services.integration_type(blocking)) + + def _set_global_tool_enabled(tool: Any, desired: bool) -> bool: """Persist and apply the global enabled state for a registry tool.""" with ToolRegistry._refresh_lock: @@ -866,7 +981,8 @@ async def list_tools( ) tools = ToolRegistry.list_tools(category=cat_filter) - result = [_build_tool_response(t) for t in tools if t.name not in _INTERNAL_TOOL_NAMES] + services = _ServiceLookup() + result = [_build_tool_response(t, services=services) for t in tools if t.name not in _INTERNAL_TOOL_NAMES] # Apply source filter if specified if source: diff --git a/tests/server/routes/test_tool_routes.py b/tests/server/routes/test_tool_routes.py index 7c19f633d..eef2cfc00 100644 --- a/tests/server/routes/test_tool_routes.py +++ b/tests/server/routes/test_tool_routes.py @@ -775,10 +775,10 @@ async def handler(ctx) -> ToolResult: original_build_tool_index_item = tool_routes._build_tool_index_item index_builds = 0 - def counted_build_tool_index_item(tool_info): + def counted_build_tool_index_item(tool_info, **kwargs): nonlocal index_builds index_builds += 1 - return original_build_tool_index_item(tool_info) + return original_build_tool_index_item(tool_info, **kwargs) monkeypatch.setattr(tool_routes, "_build_tool_index_item", counted_build_tool_index_item) diff --git a/tests/server/test_tool_setting_routes.py b/tests/server/test_tool_setting_routes.py index 4f4d75dc7..de2c27390 100644 --- a/tests/server/test_tool_setting_routes.py +++ b/tests/server/test_tool_setting_routes.py @@ -403,6 +403,233 @@ def test_reload_path_refreshes_enabled_default(self, tool_client): ) +class TestServiceEnabledFlag: + """``service_enabled`` tells a client why a tool is off and cannot be opened. + + Regression for INC-F5C08C1C: the status switch of a tool whose API + service is disabled did nothing visible, because the refused PATCH + answers 200 with ``enabled=false`` and nothing said why. + """ + + def test_refused_enable_reports_the_disabled_service(self, tool_client): + client, enabled_tool, _ = tool_client + _set_service(enabled=False) + name = enabled_tool.info.name + + before = client.get(f"/api/tools/{name}").json() + assert (before["enabled"], before["service_enabled"]) == (False, False) + + res = client.patch(f"/api/tools/{name}", json={"enabled": True}) + assert res.status_code == 200, res.text + body = res.json() + # The gate itself is unchanged: the tool stays off ... + assert body["enabled"] is False + # ... and the answer now carries the reason. + assert body["service_enabled"] is False + + def test_follows_the_service_flag(self, tool_client): + client, enabled_tool, _ = tool_client + name = enabled_tool.info.name + + # No api_services entry at all counts as off, exactly like the gate. + body = client.get(f"/api/tools/{name}").json() + assert (body["enabled"], body["service_enabled"]) == (False, False) + + _set_service(enabled=True) + body = client.get(f"/api/tools/{name}").json() + assert (body["enabled"], body["service_enabled"]) == (True, True) + + _set_service(enabled=False) + body = client.get(f"/api/tools/{name}").json() + assert (body["enabled"], body["service_enabled"]) == (False, False) + + def test_list_rows_carry_the_flag(self, tool_client): + client, enabled_tool, disabled_tool = tool_client + _set_service(enabled=False) + + rows = {row["name"]: row for row in client.get("/api/tools/page").json()["items"]} + assert rows[enabled_tool.info.name]["service_enabled"] is False + assert rows[enabled_tool.info.name]["enabled"] is False + listed = {row["name"]: row for row in client.get("/api/tools").json()} + assert listed[disabled_tool.info.name]["service_enabled"] is False + + # The paged list is served from a snapshot: a service change must show. + _set_service(enabled=True) + rows = {row["name"]: row for row in client.get("/api/tools/page").json()["items"]} + assert rows[enabled_tool.info.name]["service_enabled"] is True + assert rows[enabled_tool.info.name]["enabled"] is True + assert rows[disabled_tool.info.name]["service_enabled"] is True + assert rows[disabled_tool.info.name]["enabled"] is False + + def test_null_without_an_owning_service(self, tool_client): + client, _, _ = tool_client + + async def handler(ctx: ToolContext) -> ToolResult: + return ToolResult(success=True, output="ok") + + ToolRegistry.register(Tool( + info=ToolInfo( + name="plain_tool_test", + description="a tool no service gates", + category=ToolCategory.CUSTOM, + enabled=True, + ), + handler=handler, + )) + + body = client.get("/api/tools/plain_tool_test").json() + assert (body["enabled"], body["service_enabled"]) == (True, None) + assert body["service_integration_type"] is None + body = client.patch("/api/tools/plain_tool_test", json={"enabled": False}).json() + assert (body["enabled"], body["service_enabled"]) == (False, None) + body = client.patch("/api/tools/plain_tool_test", json={"enabled": True}).json() + assert (body["enabled"], body["service_enabled"]) == (True, None) + rows = {row["name"]: row for row in client.get("/api/tools/page").json()["items"]} + assert rows["plain_tool_test"]["service_enabled"] is None + + def test_provider_gate_is_reported_for_other_sources(self, tool_client): + """The gate keys on ``provider`` whatever the source; report it there too. + + A YAML plugin tool with a provider is not an api/device tool, yet the + registry forces it off while the provider's service is off and PATCH + refuses to open it. Without the flag it would be the same dead switch. + """ + client, _, _ = tool_client + tool = _stub_api_tool("yaml_plugin_tool_test", enabled=True) + tool.info.source = "plugin_yaml" + ToolRegistry.register(tool) + _set_service(enabled=False) + name = tool.info.name + + body = client.get(f"/api/tools/{name}").json() + assert body["source"] == "plugin_yaml" + assert (body["enabled"], body["service_enabled"]) == (False, False) + body = client.patch(f"/api/tools/{name}", json={"enabled": True}).json() + assert (body["enabled"], body["service_enabled"]) == (False, False) + + _set_service(enabled=True) + body = client.get(f"/api/tools/{name}").json() + assert (body["enabled"], body["service_enabled"]) == (True, True) + + + def test_reports_where_the_owning_service_is_managed(self, tool_client, tmp_path, monkeypatch): + """A device plugin installed under ``tools/api`` loads as an ``api`` tool. + + Its service is still managed on the device page: the API service list + reports ``integration_type: device`` and the API tab leaves it out. + The tool response has to carry the same answer, or a client that goes + by ``source`` sends the user to a tab that cannot show the service. + """ + from types import SimpleNamespace + + from flocks.server.routes import provider as provider_routes + from flocks.server.routes.tool import _invalidate_tool_summary_cache + + client, enabled_tool, _ = tool_client + _set_service(enabled=False) + name = enabled_tool.info.name + provider_yaml = tmp_path / "plugins" / "tools" / "api" / "legacy_device" / "_provider.yaml" + provider_yaml.parent.mkdir(parents=True) + descriptor = SimpleNamespace( + service_id=_TEST_SERVICE_ID, + version=None, + storage_key=_TEST_SERVICE_ID, + provider_yaml=provider_yaml, + ) + monkeypatch.setattr( + provider_routes, + "_find_api_service_descriptor", + lambda provider_id: descriptor if provider_id == _TEST_SERVICE_ID else None, + ) + + def declared(integration_type): + lines = [f"name: {_TEST_SERVICE_ID}"] + if integration_type is not None: + lines.append(f"integration_type: {integration_type}") + provider_yaml.write_text("\n".join(lines) + "\n", encoding="utf-8") + provider_routes._clear_api_service_summary_metadata_cache() + _invalidate_tool_summary_cache() + detail = client.get(f"/api/tools/{name}").json() + rows = {row["name"]: row for row in client.get("/api/tools/page").json()["items"]} + listed = {row["name"]: row for row in client.get("/api/tools").json()} + assert detail["source"] == "api" + assert detail["service_enabled"] is False + return ( + detail["service_integration_type"], + rows[name]["service_integration_type"], + listed[name]["service_integration_type"], + ) + + try: + assert declared("device") == ("device", "device", "device") + # The refused enable carries it too: that answer is what the drawer renders. + body = client.patch(f"/api/tools/{name}", json={"enabled": True}).json() + assert (body["enabled"], body["service_integration_type"]) == (False, "device") + assert declared('" Device "') == ("device", "device", "device") + assert declared("api") == ("api", "api", "api") + assert declared(None) == (None, None, None) + finally: + provider_routes._clear_api_service_summary_metadata_cache() + + def test_unreadable_service_metadata_does_not_break_the_tool_list(self, tool_client, monkeypatch): + from flocks.server.routes import provider as provider_routes + from flocks.server.routes.tool import _invalidate_tool_summary_cache + + client, enabled_tool, _ = tool_client + _set_service(enabled=False) + + def broken(provider_id): + raise ValueError("corrupt metadata") + + monkeypatch.setattr(provider_routes, "_load_api_service_summary_metadata_data", broken) + _invalidate_tool_summary_cache() + + page = client.get("/api/tools/page") + assert page.status_code == 200, page.text + rows = {row["name"]: row for row in page.json()["items"]} + assert rows[enabled_tool.info.name]["service_enabled"] is False + assert rows[enabled_tool.info.name]["service_integration_type"] is None + detail = client.get(f"/api/tools/{enabled_tool.info.name}") + assert detail.status_code == 200, detail.text + + def test_list_reads_each_service_once_not_once_per_tool(self, tool_client, monkeypatch): + """``get_api_service_raw`` re-reads and parses flocks.json on every call. + + One list response builds a row per tool; the service facts for those + rows must cost one lookup per service, however many tools share it. + """ + from flocks.config.config_writer import ConfigWriter + from flocks.server.routes.tool import _invalidate_tool_summary_cache + + client, _, _ = tool_client + _set_service(enabled=True) + calls: list[str] = [] + original = ConfigWriter.get_api_service_raw.__func__ + + def counting(cls, service_id): + calls.append(service_id) + return original(cls, service_id) + + monkeypatch.setattr(ConfigWriter, "get_api_service_raw", classmethod(counting)) + + def reads(path: str) -> int: + _invalidate_tool_summary_cache() + calls.clear() + assert client.get(path).status_code == 200 + return len(calls) + + paths = ("/api/tools/page", "/api/tools") + for path in paths: + reads(path) # the first lookup also fills the service metadata cache + few = {path: reads(path) for path in paths} + for idx in range(10): + ToolRegistry.register(_stub_api_tool(f"bulk_tool_test_{idx}", enabled=True)) + many = {path: reads(path) for path in paths} + + assert all(count > 0 for count in few.values()), few + assert many == few, (few, many) + + class TestUpdateTool: def test_manual_reenable_clears_repeated_failure_count(self, tool_client): client, enabled_tool, _ = tool_client diff --git a/webui/src/locales/en-US/tool.json b/webui/src/locales/en-US/tool.json index 3b3634734..9a2f2a6c8 100644 --- a/webui/src/locales/en-US/tool.json +++ b/webui/src/locales/en-US/tool.json @@ -543,6 +543,11 @@ "enabled": "Enabled", "disabled": "Disabled", "updating": "Updating…", + "serviceDisabledApi": "The API service \"{{service}}\" that owns this tool is disabled, so the tool cannot be enabled on its own. Enable the service under API Integrations first.", + "serviceDisabledDevice": "The device plugin \"{{service}}\" that owns this tool has no enabled device, so the tool cannot be enabled on its own. Add or enable a device in Device Integration first.", + "goToApiService": "Enable the service", + "goToDevices": "Go to Device Integration", + "enableNotApplied": "The tool was not enabled. Check whether the service that owns it is enabled.", "noDescription": "No description" }, diff --git a/webui/src/locales/zh-CN/tool.json b/webui/src/locales/zh-CN/tool.json index 1c82446fc..b6c8c64d8 100644 --- a/webui/src/locales/zh-CN/tool.json +++ b/webui/src/locales/zh-CN/tool.json @@ -543,6 +543,11 @@ "enabled": "已启用", "disabled": "已禁用", "updating": "更新中…", + "serviceDisabledApi": "所属 API 服务「{{service}}」未启用,这个工具不能单独启用。请先在「API 集成」里启用该服务。", + "serviceDisabledDevice": "所属设备插件「{{service}}」还没有启用的设备,这个工具不能单独启用。请先在「设备接入」添加或启用设备。", + "goToApiService": "去启用服务", + "goToDevices": "前往设备接入", + "enableNotApplied": "工具没有启用成功,请检查它所属的服务是否已启用。", "noDescription": "暂无描述" }, diff --git a/webui/src/pages/Tool/ToolDetailDrawer.test.tsx b/webui/src/pages/Tool/ToolDetailDrawer.test.tsx index 972a4faa4..81fef2945 100644 --- a/webui/src/pages/Tool/ToolDetailDrawer.test.tsx +++ b/webui/src/pages/Tool/ToolDetailDrawer.test.tsx @@ -1,6 +1,7 @@ import React from 'react'; import { describe, it, expect, vi } from 'vitest'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; import { ToolDetailDrawer } from './index'; vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ user: { role: 'admin' } }) })); @@ -11,6 +12,8 @@ vi.mock('react-i18next', () => ({ if (key === 'toolDetail.params' && typeof options?.count === 'number') { return `参数 (${options.count}个)`; } + if (key === 'toolDetail.serviceDisabledApi') return `所属 API 服务「${options?.service}」未启用`; + if (key === 'toolDetail.serviceDisabledDevice') return `所属设备插件「${options?.service}」还没有启用的设备`; const translations: Record = { 'toolDetail.tabInfo': '详情', @@ -32,6 +35,9 @@ vi.mock('react-i18next', () => ({ 'toolDetail.disabled': '禁用', 'toolDetail.customized': '已自定义', 'toolDetail.resetSetting': '恢复默认', + 'toolDetail.goToApiService': '去启用服务', + 'toolDetail.goToDevices': '前往设备接入', + 'toolDetail.enableNotApplied': '工具没有启用成功', 'alert.unknownError': '未知错误', }; @@ -226,7 +232,7 @@ describe('ToolDetailDrawer', () => { const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {}); const { container } = render(); - // dev's enable toggle is a plain button (no switch role): the h-6 w-11 pill. + // The enable toggle is the h-6 w-11 pill. const toggle = container.ownerDocument.querySelector('button.h-6.w-11') as HTMLButtonElement; expect(toggle).toBeTruthy(); fireEvent.click(toggle); @@ -234,4 +240,216 @@ describe('ToolDetailDrawer', () => { expect(screen.getByText('启用')).toBeInTheDocument(); alertSpy.mockRestore(); }); + + // INC-F5C08C1C: the backend never opens a tool whose API service is off; it + // answers 200 with enabled=false, and the switch used to do nothing visible. + describe('when the service that owns the tool is disabled', () => { + const blockedApiTool = { + name: 'af_api_app_traffic_top', + description: 'AF app traffic top', + source: 'api', + source_name: 'af_api', + category: 'custom', + enabled: false, + enabled_default: true, + enabled_customized: false, + service_enabled: false, + parameters: [], + } as any; + + async function mockedToolAPI() { + const { toolAPI } = await import('@/api/tool'); + const setEnabled = toolAPI.setEnabled as any; + setEnabled.mockReset(); + return { setEnabled }; + } + + it('says why the tool is off, locks the switch and offers the way to the service', async () => { + const { setEnabled } = await mockedToolAPI(); + const onOpenApiService = vi.fn(); + render(); + + const notice = screen.getByRole('note'); + expect(notice).toHaveTextContent('所属 API 服务「af_api」未启用'); + const toggle = screen.getByRole('switch', { name: '状态' }); + expect(toggle).toBeDisabled(); + expect(toggle).toHaveAttribute('aria-checked', 'false'); + expect(toggle).toHaveAttribute('aria-describedby', notice.id); + + fireEvent.click(toggle); + expect(setEnabled).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByRole('button', { name: '去启用服务' })); + expect(onOpenApiService).toHaveBeenCalledExactlyOnceWith('af_api'); + }); + + it('shows the reason after a refused enable when the opened row did not carry it', async () => { + const { setEnabled } = await mockedToolAPI(); + const { service_enabled: _unknown, ...staleRow } = blockedApiTool; + setEnabled.mockResolvedValue({ data: { ...blockedApiTool } }); + const onEnabledChange = vi.fn(); + const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {}); + render(); + + expect(screen.queryByRole('note')).toBeNull(); + const toggle = screen.getByRole('switch', { name: '状态' }); + expect(toggle).toBeEnabled(); + fireEvent.click(toggle); + + expect(await screen.findByRole('note')).toHaveTextContent('所属 API 服务「af_api」未启用'); + expect(setEnabled).toHaveBeenCalledExactlyOnceWith('af_api_app_traffic_top', true); + expect(screen.getByRole('switch', { name: '状态' })).toBeDisabled(); + // The parent gets the flag too, or its prop sync would hide the notice again. + expect(onEnabledChange.mock.calls[0][2].service_enabled).toBe(false); + expect(alertSpy).not.toHaveBeenCalled(); + alertSpy.mockRestore(); + }); + + it('never lets a refused enable pass silently, whatever the reason', async () => { + const { setEnabled } = await mockedToolAPI(); + const plainTool = { ...enabledTool, enabled: false }; + setEnabled.mockResolvedValue({ data: { ...plainTool } }); + const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {}); + render(); + + fireEvent.click(screen.getByRole('switch', { name: '状态' })); + await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('工具没有启用成功')); + expect(screen.queryByRole('note')).toBeNull(); + alertSpy.mockRestore(); + }); + + it('sends device tools to the device page and closes the drawer on the way', async () => { + await mockedToolAPI(); + const onClose = vi.fn(); + const onOpenApiService = vi.fn(); + render( + + + , + ); + + expect(screen.getByRole('note')).toHaveTextContent('所属设备插件「ngsoc_api_v4_15_1」还没有启用的设备'); + expect(screen.getByRole('switch', { name: '状态' })).toBeDisabled(); + expect(screen.queryByRole('button', { name: '去启用服务' })).toBeNull(); + const link = screen.getByRole('link', { name: '前往设备接入' }); + expect(link).toHaveAttribute('href', '/devices'); + fireEvent.click(link); + expect(onClose).toHaveBeenCalledTimes(1); + expect(onOpenApiService).not.toHaveBeenCalled(); + }); + + it('goes by where the service is managed, not by the directory the plugin was loaded from', async () => { + await mockedToolAPI(); + const onOpenApiService = vi.fn(); + // A device plugin installed under tools/api: an "api" tool whose + // service the API tab does not list. + const { rerender } = render( + + + , + ); + expect(screen.getByRole('note')).toHaveTextContent('所属设备插件「legacy_device」还没有启用的设备'); + expect(screen.getByRole('link', { name: '前往设备接入' })).toHaveAttribute('href', '/devices'); + expect(screen.queryByRole('button', { name: '去启用服务' })).toBeNull(); + + // The reverse: loaded from tools/device without declaring a device + // integration, so the API tab lists its service and can enable it. + rerender( + + + , + ); + expect(screen.getByRole('note')).toHaveTextContent('所属 API 服务「plain_service」未启用'); + expect(screen.queryByRole('link', { name: '前往设备接入' })).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: '去启用服务' })); + expect(onOpenApiService).toHaveBeenCalledExactlyOnceWith('plain_service'); + }); + + it('takes where the service is managed from the answer to a toggle or a reset', async () => { + const { setEnabled } = await mockedToolAPI(); + const { toolAPI } = await import('@/api/tool'); + const resetSetting = toolAPI.resetSetting as any; + resetSetting.mockReset(); + // The drawer was opened with no word about the service; the refused + // enable then says it is off and managed on the device page. + const { service_enabled: _flag, ...staleRow } = blockedApiTool; + setEnabled.mockResolvedValue({ data: { ...blockedApiTool, service_integration_type: 'device' } }); + const { unmount } = render( + + + , + ); + fireEvent.click(screen.getByRole('switch', { name: '状态' })); + expect(await screen.findByRole('note')).toHaveTextContent('所属设备插件「af_api」还没有启用的设备'); + expect(screen.getByRole('link', { name: '前往设备接入' })).toHaveAttribute('href', '/devices'); + expect(screen.queryByRole('button', { name: '去启用服务' })).toBeNull(); + unmount(); + + // Same for 恢复默认: the drawer believed the API tab lists the service. + const customized = { ...blockedApiTool, enabled_customized: true, service_integration_type: null }; + resetSetting.mockResolvedValue({ data: { ...customized, enabled_customized: false, service_integration_type: 'device' } }); + render( + + + , + ); + expect(screen.getByRole('button', { name: '去启用服务' })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: '恢复默认' })); + expect(await screen.findByRole('link', { name: '前往设备接入' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: '去启用服务' })).toBeNull(); + }); + + it('still lets an enabled tool be switched off, then locks the switch', async () => { + const { setEnabled } = await mockedToolAPI(); + // Only api/device tools have their state ANDed with the service, so + // another gated tool can still read enabled until the registry syncs. + const enabledButGated = { ...blockedApiTool, name: 'yaml_plugin_tool', source: 'plugin_yaml', enabled: true }; + setEnabled.mockResolvedValue({ data: { ...enabledButGated, enabled: false, enabled_customized: true } }); + render(); + + expect(screen.getByRole('note')).toBeInTheDocument(); + // Only api tools have a service panel on the API tab to jump to. + expect(screen.queryByRole('button', { name: '去启用服务' })).toBeNull(); + const toggle = screen.getByRole('switch', { name: '状态' }); + expect(toggle).toBeEnabled(); + fireEvent.click(toggle); + + await waitFor(() => expect(screen.getByRole('switch', { name: '状态' })).toBeDisabled()); + expect(setEnabled).toHaveBeenCalledExactlyOnceWith('yaml_plugin_tool', false); + expect(screen.getByText('已自定义')).toBeInTheDocument(); + }); + + it('leaves the switch alone when the service is enabled', async () => { + const { setEnabled } = await mockedToolAPI(); + const offTool = { ...blockedApiTool, service_enabled: true }; + setEnabled.mockResolvedValue({ data: { ...offTool, enabled: true } }); + const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {}); + render(); + + expect(screen.queryByRole('note')).toBeNull(); + const toggle = screen.getByRole('switch', { name: '状态' }); + expect(toggle).toBeEnabled(); + expect(toggle).not.toHaveAttribute('aria-describedby'); + fireEvent.click(toggle); + + await waitFor(() => expect(screen.getByRole('switch', { name: '状态' })).toHaveAttribute('aria-checked', 'true')); + expect(setEnabled).toHaveBeenCalledExactlyOnceWith('af_api_app_traffic_top', true); + expect(screen.queryByRole('note')).toBeNull(); + expect(alertSpy).not.toHaveBeenCalled(); + alertSpy.mockRestore(); + }); + }); }); diff --git a/webui/src/pages/Tool/ToolServiceGate.test.tsx b/webui/src/pages/Tool/ToolServiceGate.test.tsx new file mode 100644 index 000000000..d6768802e --- /dev/null +++ b/webui/src/pages/Tool/ToolServiceGate.test.tsx @@ -0,0 +1,162 @@ +vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ user: { role: 'admin' } }) })); +import React from 'react'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import ToolPage from './index'; + +// INC-F5C08C1C: a tool whose API service is disabled cannot be switched on from +// its own drawer. The drawer says so and takes the user to the service. + +const { getToolMock, setEnabledMock, listApiServicesMock } = vi.hoisted(() => ({ + getToolMock: vi.fn(), + setEnabledMock: vi.fn(), + listApiServicesMock: vi.fn(), +})); + +const blockedTool = { + name: 'af_api_app_traffic_top', + description: 'AF app traffic top', + source: 'api', + source_name: 'af_api', + category: 'custom', + enabled: false, + enabled_default: true, + enabled_customized: false, + service_enabled: false, + parameters: [], +}; + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: (key: string, options?: Record) => + typeof options?.defaultValue === 'string' ? options.defaultValue : key, + i18n: { language: 'zh-CN' }, + }), +})); + +vi.mock('@/components/common/Toast', async (importOriginal) => ({ + // Keep the module's other exports (GroupNav uses useOptionalToast). + ...(await importOriginal()), + useToast: () => ({ error: vi.fn(), success: vi.fn(), warning: vi.fn(), info: vi.fn() }), +})); + +vi.mock('@/hooks/useTools', () => ({ + useToolPage: () => ({ + tools: [blockedTool], + total: 1, + facets: { + category: { custom: 1 }, + source: { api: 1 }, + source_groups: { api: 1 }, + source_name: { af_api: 1 }, + enabled: { false: 1 }, + }, + loading: false, + error: null, + initialized: true, + refetch: vi.fn(), + reload: vi.fn(), + }), +})); + +vi.mock('@/api/tool', () => ({ + canDirectlyTestTool: vi.fn(() => true), + listAllToolPages: vi.fn(() => Promise.resolve([])), + toolAPI: { + get: getToolMock, + setEnabled: setEnabledMock, + listFixtures: vi.fn(() => Promise.resolve({ data: [] })), + }, +})); + +vi.mock('@/api/mcp', () => ({ + mcpAPI: { + list: vi.fn(() => Promise.resolve({ data: {} })), + catalogList: vi.fn(() => Promise.resolve({ data: [] })), + catalogCategories: vi.fn(() => Promise.resolve({ data: {} })), + catalogConfigured: vi.fn(() => Promise.resolve({ data: [] })), + }, +})); + +vi.mock('@/api/provider', () => ({ providerAPI: { listApiServices: listApiServicesMock } })); + +vi.mock('./components/ServiceDetailPanel', async (importOriginal) => ({ + ...(await importOriginal()), + APIServiceDetailPanel: ({ serviceName, enabled }: { serviceName: string; enabled?: boolean }) => ( +
service-panel:{serviceName}:{enabled ? 'on' : 'off'}
+ ), +})); + +describe('ToolPage: tool gated by a disabled API service', () => { + beforeEach(() => { + vi.clearAllMocks(); + getToolMock.mockResolvedValue({ data: blockedTool }); + listApiServicesMock.mockResolvedValue({ data: [ + { id: 'af_api', name: 'af_api', enabled: false, status: 'disabled', tool_count: 1 }, + { id: 'other_api', name: 'other_api', enabled: true, status: 'unknown', tool_count: 0 }, + ] }); + }); + + const openBlockedTool = async () => { + fireEvent.click(screen.getByRole('button', { name: blockedTool.name })); + await screen.findByRole('note'); + }; + const tab = (key: string) => screen.getByRole('button', { name: new RegExp(`^${key.replace('.', '\\.')}`) }); + + it('goes from the drawer to the service panel on the API tab', async () => { + render(); + await openBlockedTool(); + expect(screen.getByRole('switch', { name: 'toolDetail.status' })).toBeDisabled(); + + fireEvent.click(screen.getByRole('button', { name: 'toolDetail.goToApiService' })); + + // The tool drawer is gone and the service's own panel is open instead. + expect(screen.queryByRole('dialog')).toBeNull(); + expect(await screen.findByText('service-panel:af_api:off')).toBeInTheDocument(); + expect(setEnabledMock).not.toHaveBeenCalled(); + }); + + it('keeps what a refused enable said about the service when the page re-renders the drawer', async () => { + // The row and the detail know nothing about the service yet. + const { service_enabled: _flag, service_integration_type: _type, ...staleTool } = { ...blockedTool, service_integration_type: null }; + getToolMock.mockResolvedValue({ data: staleTool }); + setEnabledMock.mockResolvedValue({ data: { ...blockedTool, service_integration_type: 'device' } }); + render(); + + fireEvent.click(screen.getByRole('button', { name: blockedTool.name })); + const toggle = await screen.findByRole('switch', { name: 'toolDetail.status' }); + await waitFor(() => expect(getToolMock).toHaveBeenCalled()); + await waitFor(() => expect(screen.queryByRole('note')).toBeNull()); + fireEvent.click(toggle); + + // The page merges the answer into its copy of the tool and re-renders the + // drawer: the device wording and link must survive that prop sync. + expect(await screen.findByRole('link', { name: 'toolDetail.goToDevices' })).toHaveAttribute('href', '/devices'); + expect(screen.getByRole('note')).toHaveTextContent('toolDetail.serviceDisabledDevice'); + expect(screen.queryByRole('button', { name: 'toolDetail.goToApiService' })).toBeNull(); + expect(screen.getByRole('switch', { name: 'toolDetail.status' })).toBeDisabled(); + expect(setEnabledMock).toHaveBeenCalledExactlyOnceWith(blockedTool.name, true); + }); + + it('does not reopen the service panel when the API tab is visited again', async () => { + render(); + await openBlockedTool(); + fireEvent.click(screen.getByRole('button', { name: 'toolDetail.goToApiService' })); + await screen.findByText('service-panel:af_api:off'); + + fireEvent.click(tab('tabs.all')); + await waitFor(() => expect(screen.queryByText('service-panel:af_api:off')).toBeNull()); + fireEvent.click(tab('tabs.api')); + // The service row is back, its panel is not. + await screen.findByText('other_api', { selector: 'span' }); + expect(screen.queryByText('service-panel:af_api:off')).toBeNull(); + + // Asking again from the tool does open it again. + fireEvent.click(tab('tabs.all')); + await openBlockedTool(); + fireEvent.click(screen.getByRole('button', { name: 'toolDetail.goToApiService' })); + expect(await screen.findByText('service-panel:af_api:off')).toBeInTheDocument(); + }); +}); diff --git a/webui/src/pages/Tool/components/APITabContent.test.tsx b/webui/src/pages/Tool/components/APITabContent.test.tsx index be0dab94a..09e742e1d 100644 --- a/webui/src/pages/Tool/components/APITabContent.test.tsx +++ b/webui/src/pages/Tool/components/APITabContent.test.tsx @@ -134,6 +134,32 @@ describe('APITabContent', () => { expect(listAllToolPages).not.toHaveBeenCalled(); }); + it('opens the detail panel of the service it is asked to focus, once per request', async () => { + providerAPI.listApiServices.mockResolvedValue({ data: [ + { id: 'af_api', name: 'AF API', enabled: false, tool_count: 1 }, + { id: 'other', name: 'Other API', enabled: true, tool_count: 0 }, + ] }); + const props = { tools: [], onSelectTool: vi.fn(), onRefreshTools: vi.fn(), + catalogEntries: [], catalogCategories: {}, catalogLoading: false, configuredIds: new Set(), onConfiguredChange: vi.fn() }; + // The request arrives with the tab, before the service list has loaded. + const { rerender } = render(); + expect(screen.queryByText('detail-panel')).not.toBeInTheDocument(); + expect(await screen.findByText('detail-panel')).toBeInTheDocument(); + expect(apiDetailProps).toHaveBeenLastCalledWith(expect.objectContaining({ serviceName: 'af_api', enabled: false })); + + // Closing it is final: re-rendering with the same request does not reopen it. + fireEvent.click(screen.getByText('AF API', { selector: 'h2' }).closest('div.flex')!.querySelector('button')!); + expect(screen.queryByText('detail-panel')).not.toBeInTheDocument(); + rerender(); + expect(screen.queryByText('detail-panel')).not.toBeInTheDocument(); + // A new request for the same service opens it again. + rerender(); + expect(screen.getByText('detail-panel')).toBeInTheDocument(); + // A service that is not in the list opens nothing. + rerender(); + expect(screen.queryByText('detail-panel')).not.toBeInTheDocument(); + }); + it('keeps catalog keyword search independent of service and child-tool matches', async () => { providerAPI.listApiServices.mockResolvedValue({ data: [{ id: 'service', name: 'Native service', enabled: false, tool_count: 0 }] }); const props = { tools: [], onSelectTool: vi.fn(), onRefreshTools: vi.fn(), diff --git a/webui/src/pages/Tool/components/APITabContent.tsx b/webui/src/pages/Tool/components/APITabContent.tsx index a544439e1..a57505b68 100644 --- a/webui/src/pages/Tool/components/APITabContent.tsx +++ b/webui/src/pages/Tool/components/APITabContent.tsx @@ -41,6 +41,8 @@ interface APITabContentProps { onRefreshTools: () => Promise; onServiceCountChange?: (count: number) => void; refreshKey?: number; + /** Open this service's detail panel; a new nonce repeats the request. */ + focusService?: { id: string; nonce: number } | null; viewMode?: 'list' | 'cards'; catalogEntries: MCPCatalogEntry[]; catalogCategories: Record; @@ -58,6 +60,7 @@ export default function APITabContent({ onRefreshTools, onServiceCountChange, refreshKey, + focusService, viewMode = 'list', catalogEntries, catalogCategories, @@ -107,6 +110,14 @@ export default function APITabContent({ fetchServices(); }, [fetchServices, refreshKey]); + // The panel renders once the service is in the loaded list, so the request + // may arrive before the first fetch has finished. + const focusServiceId = focusService?.id; + const focusServiceNonce = focusService?.nonce; + useEffect(() => { + if (focusServiceId) setSelectedServiceId(focusServiceId); + }, [focusServiceId, focusServiceNonce]); + const selectedService = useMemo( () => (selectedServiceId ? services.find((service) => service.id === selectedServiceId) ?? null : null), [selectedServiceId, services], diff --git a/webui/src/pages/Tool/index.tsx b/webui/src/pages/Tool/index.tsx index 71d6c8ea9..27ed49f5d 100644 --- a/webui/src/pages/Tool/index.tsx +++ b/webui/src/pages/Tool/index.tsx @@ -1,4 +1,5 @@ import { useState, useMemo, useEffect, useCallback, useRef } from 'react'; +import { Link } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { Wrench, @@ -195,6 +196,10 @@ export default function ToolPage() { const [serviceRefreshKey, setServiceRefreshKey] = useState(0); const [showAPISheet, setShowAPISheet] = useState(false); const [showGenerateSheet, setShowGenerateSheet] = useState(false); + // One-shot request to open a service's detail panel on the API tab; the + // nonce tells two requests for the same service apart. + const [apiServiceFocus, setApiServiceFocus] = useState<{ id: string; nonce: number } | null>(null); + const apiServiceFocusSeq = useRef(0); // Sort: default by 类别 (source) MCP -> API -> 内置 const [sort, setSort] = useState({ field: 'source', dir: 'asc' }); const [filters, setFilters] = useState(EMPTY_FILTERS); @@ -478,6 +483,8 @@ export default function ToolPage() { const handleTabChange = (tab: TabKey) => { setActiveTab(tab); + // A stale request must not reopen the panel when the API tab remounts. + setApiServiceFocus(null); selectToolGroup(null); setCurrentPage(1); setSearchQuery(''); @@ -544,6 +551,16 @@ export default function ToolPage() { } }; + // A tool whose API service is off cannot be switched on from its own + // drawer: take the user to the service, where it is enabled and configured. + const openApiService = (serviceId: string) => { + setSelectedTool(null); + setTestResult(null); + handleTabChange('api'); + apiServiceFocusSeq.current += 1; + setApiServiceFocus({ id: serviceId, nonce: apiServiceFocusSeq.current }); + }; + const openDetail = (tool: Tool) => { setSelectedTool(tool); setTestParams('{}'); @@ -748,6 +765,7 @@ export default function ToolPage() { refreshKey={serviceRefreshKey} onSelectTool={openDetail} onRefreshTools={refreshToolDataAfterMutation} + focusService={apiServiceFocus} catalogEntries={apiCatalogEntries} catalogCategories={catalogCategories} catalogLoading={catalogLoading} @@ -882,10 +900,13 @@ export default function ToolPage() { ...(updated ? { enabled_customized: updated.enabled_customized, enabled_default: updated.enabled_default, + service_enabled: updated.service_enabled, + service_integration_type: updated.service_integration_type, } : {}), } : prev); void refreshToolDataAfterMutation(); }} + onOpenApiService={openApiService} /> )} @@ -3725,6 +3746,7 @@ export function ToolDetailDrawer({ onTest, onDelete, onEnabledChange, + onOpenApiService, }: { tool: Tool; testParams: string; @@ -3735,10 +3757,14 @@ export function ToolDetailDrawer({ onTest: () => void; onDelete?: (name: string) => Promise; onEnabledChange?: (name: string, enabled: boolean, updated?: Tool) => void; + /** Open the API service that owns this tool (its detail panel on the API tab). */ + onOpenApiService?: (serviceId: string) => void; }) { const { t, i18n } = useTranslation('tool'); const [section, setSection] = useState<'info' | 'test'>('info'); const [enabled, setEnabled] = useState(tool.enabled); + const [serviceEnabled, setServiceEnabled] = useState(tool.service_enabled); + const [serviceIntegrationType, setServiceIntegrationType] = useState(tool.service_integration_type); const [customized, setCustomized] = useState(!!tool.enabled_customized); const [enabledDefault, setEnabledDefault] = useState( tool.enabled_default ?? tool.enabled @@ -3757,9 +3783,36 @@ export function ToolDetailDrawer({ useEffect(() => { setEnabled(tool.enabled); + setServiceEnabled(tool.service_enabled); + setServiceIntegrationType(tool.service_integration_type); setCustomized(!!tool.enabled_customized); setEnabledDefault(tool.enabled_default ?? tool.enabled); - }, [tool.enabled, tool.enabled_customized, tool.enabled_default]); + }, [tool.enabled, tool.service_enabled, tool.service_integration_type, tool.enabled_customized, tool.enabled_default]); + + // The answer to a toggle or a reset is the newest state of the tool: take + // every field the drawer shows from it, in one place, and hand it to the + // parent so its copy cannot sync a stale one back. + const applyUpdatedTool = (updated: Tool) => { + setEnabled(updated.enabled); + setServiceEnabled(updated.service_enabled); + setServiceIntegrationType(updated.service_integration_type); + setCustomized(!!updated.enabled_customized); + setEnabledDefault(updated.enabled_default ?? updated.enabled); + onEnabledChange?.(tool.name, updated.enabled, updated); + }; + + // The backend never opens a tool whose API service is off (it answers 200 + // with enabled=false), so say why instead of offering a switch that cannot + // turn on. Switching off stays possible. + const serviceBlocked = serviceEnabled === false; + const enableLocked = serviceBlocked && !enabled; + const serviceName = tool.source_name ?? ''; + // Where the service is enabled follows its own integration_type, the same + // field the API tab filters on. `source` only says which plugin directory + // the tool was loaded from: a device plugin installed under tools/api is an + // "api" tool whose service the API tab does not list. + const serviceOnDevicePage = serviceIntegrationType === 'device'; + const serviceOnApiTab = !serviceOnDevicePage && (tool.source === 'api' || tool.source === 'device'); useEffect(() => { if (testResult?.metadata?.disabled === true) { @@ -3777,15 +3830,17 @@ export function ToolDetailDrawer({ const handleToggleEnabled = async () => { - if (toggling) return; + if (toggling || enableLocked) return; const next = !enabled; setToggling(true); try { const { data: updated } = await toolAPI.setEnabled(tool.name, next); - setEnabled(updated.enabled); - setCustomized(!!updated.enabled_customized); - setEnabledDefault(updated.enabled_default ?? updated.enabled); - onEnabledChange?.(tool.name, updated.enabled, updated); + applyUpdatedTool(updated); + // A refused enable must never look like a click that did nothing: the + // service notice below covers the known reason, this covers any other. + if (next && !updated.enabled && updated.service_enabled !== false) { + alert(t('toolDetail.enableNotApplied')); + } } catch (err: unknown) { // state was never flipped, so nothing to revert; surface the reason (e.g. 403 仅管理员可执行该操作) alert(extractErrorMessage(err, t('alert.unknownError'))); @@ -3799,10 +3854,7 @@ export function ToolDetailDrawer({ setResetting(true); try { const { data: updated } = await toolAPI.resetSetting(tool.name); - setEnabled(updated.enabled); - setCustomized(!!updated.enabled_customized); - setEnabledDefault(updated.enabled_default ?? updated.enabled); - onEnabledChange?.(tool.name, updated.enabled, updated); + applyUpdatedTool(updated); } catch (err: unknown) { alert(extractErrorMessage(err, t('alert.unknownError'))); } finally { @@ -3901,9 +3953,14 @@ export function ToolDetailDrawer({
+ {serviceBlocked && ( +
+ +
+

+ {t(serviceOnDevicePage ? 'toolDetail.serviceDisabledDevice' : 'toolDetail.serviceDisabledApi', { service: serviceName })} +

+ {serviceOnDevicePage ? ( + + {t('toolDetail.goToDevices')} + + ) : serviceOnApiTab && serviceName && onOpenApiService ? ( + + ) : null} +
+
+ )}
{tool.requires_confirmation && (
diff --git a/webui/src/types/index.ts b/webui/src/types/index.ts index c9e4b60a2..527391503 100644 --- a/webui/src/types/index.ts +++ b/webui/src/types/index.ts @@ -240,6 +240,17 @@ export interface Tool { enabled_default?: boolean; /** True when a user setting is recorded in flocks.json `tool_settings`. */ enabled_customized?: boolean; + /** + * Enabled flag of the API service that gates this tool; null or absent when + * no service does. While false the tool cannot be switched on by itself. + */ + service_enabled?: boolean | null; + /** + * integration_type of that service, as the API service list reports it. + * 'device' means it is managed on the Device Integration page and is not + * listed on the API tab, whatever `source` says. + */ + service_integration_type?: string | null; requires_confirmation: boolean; } From ff7e03c329f295943bb080201d6c402afcbb214d Mon Sep 17 00:00:00 2001 From: jamon Date: Fri, 13 Nov 2026 00:16:01 +0800 Subject: [PATCH 27/44] =?UTF-8?q?feat(licence):=20=E5=9C=A8=E7=BA=BF?= =?UTF-8?q?=E7=94=B3=E8=AF=B7=E5=B8=A6=E7=9A=84=E6=9C=BA=E5=99=A8=E6=8C=87?= =?UTF-8?q?=E7=BA=B9=E6=94=B9=E7=94=A8=E9=80=9A=E7=94=A8=E8=AE=BE=E5=A4=87?= =?UTF-8?q?=E5=8F=B7=EF=BC=88devid=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 企业版核心的申请码改用公司 libdevid 的设备号当机器指纹后,开源版在线申请 带给 Console 的 machine 也要算出同一个值,否则 Console 按它绑的授权在企业 版上会判 machine_mismatch。 - machine_identity():Linux 读得到 SMBIOS 表(root)且 UUID 不是占位值时用 devid = MD5("flocks" + 小写 UUID),否则用原来的机器 ID 摘要;macOS 用 IOPlatformUUID 的小写算 devid;Windows 仍不带(和以前一样)。 - 在线申请的 form_data 多带 machine_kind(devid / machine-id)。 - 用例 MF1–MF6,含原厂 libdevid 在虚拟机里算出的 5 组向量(2 组占位值、3 组真实 UUID)。 --- flocks/updater/enterprise_application.py | 8 +- flocks/updater/machine_fingerprint.py | 205 +++++++++++++++---- tests/updater/test_enterprise_application.py | 22 +- tests/updater/test_machine_fingerprint.py | 124 +++++++++-- 4 files changed, 286 insertions(+), 73 deletions(-) diff --git a/flocks/updater/enterprise_application.py b/flocks/updater/enterprise_application.py index 2a758456d..0a7b55a3e 100644 --- a/flocks/updater/enterprise_application.py +++ b/flocks/updater/enterprise_application.py @@ -43,7 +43,7 @@ from flocks.storage.storage import Storage from flocks.updater import enterprise from flocks.updater.enterprise import EnterpriseUpgradeError -from flocks.updater.machine_fingerprint import MachineIdUnreadable, machine_fingerprint +from flocks.updater.machine_fingerprint import MachineIdUnreadable, machine_identity from flocks.utils.log import Log log = Log.create(service="updater.enterprise_application") @@ -275,7 +275,7 @@ async def _apply(form: dict[str, Any], applied_by: str) -> dict[str, Any]: raise EnterpriseUpgradeError("已经有一份申请在审核或等着启用,处理完再申请") base, session = _console_base(), await _console_session() try: - machine = await asyncio.to_thread(machine_fingerprint) + machine, machine_kind = await asyncio.to_thread(machine_identity) except MachineIdUnreadable as exc: # Sent without it, the licence would not be bound to this machine although it could be. raise EnterpriseUpgradeError(f"读不到这台机器的标识,先处理好再申请:{exc}") from exc @@ -304,8 +304,10 @@ async def _apply(form: dict[str, Any], applied_by: str) -> dict[str, Any]: "applied_by": applied_by, # The host as the enterprise core names it: Console binds the licence it issues to it, and the # core runs on that licence on this machine only. None for a host that keeps no identifier, - # which Console shows the operator. + # which Console shows the operator. machine_kind says which fingerprint it is, for whoever + # reviews: the device id, or the machine-id digest where the device id cannot be read. "machine": machine or None, + "machine_kind": machine_kind or None, } payload = { # The machine, as Console knows it from the sign-in: Console holds one open application diff --git a/flocks/updater/machine_fingerprint.py b/flocks/updater/machine_fingerprint.py index 9dd75d489..c3a86e8c1 100644 --- a/flocks/updater/machine_fingerprint.py +++ b/flocks/updater/machine_fingerprint.py @@ -1,16 +1,24 @@ """ This machine, as the enterprise core names it. -The enterprise core (flockspro ``go/internal/activation/machine.go``) identifies the host by a digest -of the identifier the operating system keeps for it, and holds a licence Console bound to that digest -to this host. An application for a licence sends the same digest, so Console can bind the licence it -issues to the machine the application came from: a copy of the licence on another machine is then no -licence there. The raw identifier never leaves this module; Console sees only the digest. - -A host that keeps no identifier (a container without /etc/machine-id) has no digest, and Console shows -the operator that the licence cannot be bound. One whose identifier cannot be read now (a file it may -not read, ioreg failing) raises ``MachineIdUnreadable`` instead: an application then waits until it -can be read, rather than go out as one that cannot be bound by accident. +The enterprise core (flockspro ``go/internal/activation``) names the host by its device id where it can read +it: the fingerprint the company's other products license hosts by, computed as the company's libdevid computes +it on its default path -- the MD5 of the device type ``flocks`` and the host's SMBIOS system UUID as dmidecode +prints it, in lower case (on an AWS Xen host, its board asset tag or hypervisor UUID), in hex +(``flockspro go/internal/devid``). +Where it cannot read that, it names the host by a digest of the identifier the operating system keeps for it, the +way every request did before the device id. An application for a licence sends the same fingerprint, so Console +can bind the licence it issues to the machine the application came from; the core holds a licence bound to +either of a host's fingerprints to that host, so licences issued before the device id keep working there. + +Both are 32 lower-case hex digits, the shape Console takes. The raw identifiers never leave this module. + +On Linux only root may read the SMBIOS table: a process without root has no device id and names the host by +the digest, as the core run by its service account does unless root recorded the device id for it. A host +that keeps no identifier (a container without /etc/machine-id) has no fingerprint, and Console shows the +operator that the licence cannot be bound. One whose identifier cannot be read now (a file it may not read, +ioreg failing) raises ``MachineIdUnreadable`` instead: an application then waits until it can be read, rather +than go out as one that cannot be bound by accident. """ from __future__ import annotations @@ -26,42 +34,25 @@ _PLATFORM_UUID = re.compile(r'"IOPlatformUUID"\s*=\s*"([^"]+)"') #: Where Linux keeps the machine id; older distributions keep only the D-Bus copy. LINUX_MACHINE_ID_FILES = (Path("/etc/machine-id"), Path("/var/lib/dbus/machine-id")) +#: The device type Flocks hashes into its device id: each product has its own. +DEV_TYPE = "flocks" +#: What dmidecode prints for a UUID the firmware leaves all zeros or all ones: neither names a host. +_PLACEHOLDER_UUIDS = frozenset({"", "Not Settable", "Not Present"}) +#: Where Linux exposes the SMBIOS tables (root only) and an AWS Xen host its identifiers (anyone). +LINUX_SMBIOS_ENTRY_POINT = Path("/sys/firmware/dmi/tables/smbios_entry_point") +LINUX_SMBIOS_TABLE = Path("/sys/firmware/dmi/tables/DMI") +LINUX_HYPERVISOR_UUID = Path("/sys/hypervisor/uuid") +LINUX_BOARD_ASSET_TAG = Path("/sys/devices/virtual/dmi/id/board_asset_tag") + +#: What a fingerprint is (the core's activation.MachineKind*): the device id, or the machine-id digest. +KIND_DEVID = "devid" +KIND_MACHINE_ID = "machine-id" class MachineIdUnreadable(RuntimeError): """The host keeps an identifier, and it cannot be read now; ``str()`` says why.""" -def _machine_id() -> str: - if sys.platform.startswith("linux"): - for path in LINUX_MACHINE_ID_FILES: - try: - text = path.read_text(encoding="utf-8").strip() - except FileNotFoundError: - continue - except OSError as exc: - raise MachineIdUnreadable(f"读不了 {path}:{exc}") from exc - if text: - return text - return "" - if sys.platform == "darwin": - try: - # The absolute path keeps a PATH entry from standing in for it, as in the core. - result = subprocess.run( - ["/usr/sbin/ioreg", "-rd1", "-c", "IOPlatformExpertDevice"], - capture_output=True, text=True, timeout=10, check=False, - ) - except (OSError, subprocess.SubprocessError) as exc: - raise MachineIdUnreadable(f"ioreg 没有运行成功:{exc}") from exc - match = _PLATFORM_UUID.search(result.stdout or "") - if result.returncode != 0 or match is None: - # Every Mac has a platform UUID: not finding it is a failure, not a host without one. - raise MachineIdUnreadable(f"ioreg 没有给出 IOPlatformUUID(退出码 {result.returncode})") - return match.group(1) - # The enterprise edition runs on Linux and macOS only. - return "" - - def fingerprint_of(raw: str) -> str: """The digest of a machine id, as the core computes it; "" for none.""" text = raw.strip().lower() @@ -70,8 +61,134 @@ def fingerprint_of(raw: str) -> str: return hashlib.sha256(_DOMAIN + text.encode("utf-8")).hexdigest()[:32] +def device_id_of(source: str) -> str: + """The device id of what it hashes (the SMBIOS UUID, or an AWS host's identifier), as the core computes + it, in lower case: libdevid prints the same digits in upper case.""" + return hashlib.md5((DEV_TYPE + source).encode("utf-8"), usedforsecurity=False).hexdigest() + + +def format_smbios_uuid(raw: bytes, major: int, minor: int) -> str: + """A 16-byte SMBIOS UUID as dmidecode prints it and libdevid hashes it: all ones "Not Present", all zeros + "Not Settable"; from SMBIOS 2.6 the first three fields little-endian; lower-case hex in 8-4-4-4-12 groups. + "" for too few.""" + if len(raw) < 16: + return "" + data = bytearray(raw[:16]) + if data == b"\xff" * 16: + return "Not Present" + if data == b"\x00" * 16: + return "Not Settable" + if major > 2 or (major == 2 and minor >= 6): + data[0:4] = data[0:4][::-1] + data[4:6] = data[4:6][::-1] + data[6:8] = data[6:8][::-1] + text = data.hex() + return f"{text[0:8]}-{text[8:12]}-{text[12:16]}-{text[16:20]}-{text[20:32]}" + + +def smbios_system_uuid(table: bytes, major: int, minor: int) -> str: + """The UUID of the System Information structure (type 1) in a raw SMBIOS structure table, as dmidecode + prints it; "" when there is none. Firmware's table is read defensively: a structure claiming more than + is there ends the walk.""" + uuid, p = "", 0 + while p + 4 <= len(table): + kind, length = table[p], table[p + 1] + if length < 4 or p + length > len(table): + break + # The UUID came with SMBIOS 2.1, which made the structure 0x19 long. + if kind == 1 and length >= 0x19: + uuid = format_smbios_uuid(table[p + 8 : p + 24], major, minor) + if kind == 127: # end of table + break + # The formatted area is followed by the structure's strings, which end with two NULs. + nxt = p + length + while nxt + 1 < len(table) and (table[nxt] != 0 or table[nxt + 1] != 0): + nxt += 1 + p = nxt + 2 + return uuid + + +def _first_line(path: Path) -> str: + try: + return path.read_text(encoding="utf-8", errors="replace").split("\n", 1)[0].strip() + except OSError: + return "" + + +def _linux_device_id() -> str: + """This Linux host's device id, "" where it cannot be read as the host's own: without root the SMBIOS + table is closed, and a UUID the firmware leaves unset names no host.""" + hypervisor = _first_line(LINUX_HYPERVISOR_UUID) + if hypervisor[:3].lower() == "ec2": + return device_id_of(_first_line(LINUX_BOARD_ASSET_TAG) or hypervisor) + major, minor = 2, 6 + try: + entry = LINUX_SMBIOS_ENTRY_POINT.read_bytes() + except OSError: + entry = b"" + if len(entry) >= 9 and entry[:5] == b"_SM3_": + major, minor = entry[7], entry[8] + elif len(entry) >= 8 and entry[:4] == b"_SM_": + major, minor = entry[6], entry[7] + try: + table = LINUX_SMBIOS_TABLE.read_bytes() + except OSError: + return "" + uuid = smbios_system_uuid(table, major, minor) + return "" if uuid in _PLACEHOLDER_UUIDS else device_id_of(uuid) + + +def _linux_machine_id() -> str: + for path in LINUX_MACHINE_ID_FILES: + try: + text = path.read_text(encoding="utf-8").strip() + except FileNotFoundError: + continue + except OSError as exc: + raise MachineIdUnreadable(f"读不了 {path}:{exc}") from exc + if text: + return text + return "" + + +def _platform_uuid() -> str: + try: + # The absolute path keeps a PATH entry from standing in for it, as in the core. + result = subprocess.run( + ["/usr/sbin/ioreg", "-rd1", "-c", "IOPlatformExpertDevice"], + capture_output=True, text=True, timeout=10, check=False, + ) + except (OSError, subprocess.SubprocessError) as exc: + raise MachineIdUnreadable(f"ioreg 没有运行成功:{exc}") from exc + match = _PLATFORM_UUID.search(result.stdout or "") + if result.returncode != 0 or match is None: + # Every Mac has a platform UUID: not finding it is a failure, not a host without one. + raise MachineIdUnreadable(f"ioreg 没有给出 IOPlatformUUID(退出码 {result.returncode})") + return match.group(1) + + +def machine_identity() -> tuple[str, str]: + """This host's fingerprint and what it is (``KIND_DEVID`` or ``KIND_MACHINE_ID``): the device id where it + can be read, else the machine-id digest; ("", "") where the host keeps no identifier. Raises + ``MachineIdUnreadable`` when the device id cannot be read and the machine id there cannot be either. + Blocking (ioreg runs up to 10 seconds): call it off the event loop.""" + if sys.platform.startswith("linux"): + device = _linux_device_id() + if device: + return device, KIND_DEVID + digest = fingerprint_of(_linux_machine_id()) + return (digest, KIND_MACHINE_ID) if digest else ("", "") + if sys.platform == "darwin": + # A Mac keeps no SMBIOS table a process can read: its platform UUID stands in, as in the core, in + # the lower case libdevid hashes a UUID in (ioreg prints it in upper). + uuid = _platform_uuid() + if uuid.strip() not in _PLACEHOLDER_UUIDS: + return device_id_of(uuid.lower()), KIND_DEVID + return fingerprint_of(uuid), KIND_MACHINE_ID + # Windows and the rest: applications from here go out unbound, as they always have. + return "", "" + + def machine_fingerprint() -> str: - """This host's digest; "" where it keeps no identifier (a container without /etc/machine-id). - Raises ``MachineIdUnreadable`` when it keeps one that cannot be read now. Blocking (ioreg runs up - to 10 seconds): call it off the event loop.""" - return fingerprint_of(_machine_id()) + """This host's fingerprint (``machine_identity``); "" where it keeps no identifier.""" + return machine_identity()[0] diff --git a/tests/updater/test_enterprise_application.py b/tests/updater/test_enterprise_application.py index 30c1fba01..a2cae1142 100644 --- a/tests/updater/test_enterprise_application.py +++ b/tests/updater/test_enterprise_application.py @@ -134,7 +134,7 @@ def approved(request_id: str = "req_1", license_id: str = "lic_1") -> dict: async def test_ea1_an_application_goes_to_console_and_its_id_is_kept(machine: Path, monkeypatch: pytest.MonkeyPatch): seen = console(monkeypatch, lambda r: httpx.Response(200, json={"request_id": "req_1", "status": "pending"})) - monkeypatch.setattr(application, "machine_fingerprint", lambda: "0123456789abcdef0123456789abcdef") + monkeypatch.setattr(application, "machine_identity", lambda: ("0123456789abcdef0123456789abcdef", "devid")) sent = await application.apply(dict(FORM), "admin") assert sent["request_id"] == "req_1" and sent["status"] == "pending" and sent["company"] == "Acme" body = json.loads(seen[0].content) @@ -143,8 +143,9 @@ async def test_ea1_an_application_goes_to_console_and_its_id_is_kept(machine: Pa # The machine is the node: Console holds one open application per node. assert (body["node_id"], body["fingerprint"], body["install_id"], body["passport_uid"]) == ("inst-1", "fp-1", "inst-1", "pp-1") assert body["form_data"]["applied_by"] == "admin" and body["idempotency_key"] == body["form_data"]["idempotency_key"] - # Console binds the licence it issues to the host the application came from. + # Console binds the licence it issues to the host the application came from, by its device id. assert body["form_data"]["machine"] == "0123456789abcdef0123456789abcdef" + assert body["form_data"]["machine_kind"] == "devid" assert await Storage.get("console:upgrade_request_pending") is None assert body["company_name"] == "Acme" and body["contact_email"] == "li@acme.example" assert body["form_data"]["license_type"] == "poc" and body["form_data"]["applicant_phone"] == "+86 138 0000 0000" @@ -185,18 +186,19 @@ async def test_ea1b_none_while_the_hosts_identifier_cannot_be_read(machine: Path seen = console(monkeypatch, lambda r: httpx.Response(200, json={"request_id": "req_1", "status": "pending"})) from flocks.updater.machine_fingerprint import MachineIdUnreadable - def unreadable() -> str: + def unreadable() -> tuple[str, str]: raise MachineIdUnreadable("ioreg 没有给出 IOPlatformUUID(退出码 1)") - monkeypatch.setattr(application, "machine_fingerprint", unreadable) + monkeypatch.setattr(application, "machine_identity", unreadable) with pytest.raises(enterprise.EnterpriseUpgradeError, match="读不到这台机器的标识"): await application.apply(dict(FORM), "admin") assert seen == [] and await Storage.get("console:upgrade_request_pending") is None # A host that keeps none (a container without /etc/machine-id) applies, and Console shows it. - monkeypatch.setattr(application, "machine_fingerprint", lambda: "") + monkeypatch.setattr(application, "machine_identity", lambda: ("", "")) await application.apply(dict(FORM), "admin") - assert json.loads(seen[0].content)["form_data"]["machine"] is None + sent = json.loads(seen[0].content)["form_data"] + assert sent["machine"] is None and sent["machine_kind"] is None async def test_ea2_the_listing(machine: Path, monkeypatch: pytest.MonkeyPatch): @@ -454,7 +456,7 @@ def _lapsed_licence(root: Path) -> Path: async def test_ea7_a_machine_whose_licence_is_over_applies_again(machine: Path, monkeypatch: pytest.MonkeyPatch): licence = _lapsed_licence(machine) seen = console(monkeypatch, lambda r: httpx.Response(200, json={"request_id": "req_7", "status": "pending"})) - monkeypatch.setattr(application, "machine_fingerprint", lambda: "0123456789abcdef0123456789abcdef") + monkeypatch.setattr(application, "machine_identity", lambda: ("0123456789abcdef0123456789abcdef", "devid")) sent = await application.apply(dict(FORM), "admin") @@ -521,7 +523,7 @@ def answer(request: httpx.Request) -> httpx.Response: assert (await application.applications())["items"][0]["can_take"] is False # It was never going to be taken: a new application goes through. - monkeypatch.setattr(application, "machine_fingerprint", lambda: "0123456789abcdef0123456789abcdef") + monkeypatch.setattr(application, "machine_identity", lambda: ("0123456789abcdef0123456789abcdef", "devid")) assert (await application.apply(dict(FORM), "admin"))["request_id"] == "req_10" # Taking it all the same changes nothing on the machine, and Console hears of it if it had not. @@ -551,7 +553,7 @@ def answer(request: httpx.Request) -> httpx.Response: return httpx.Response(200, json=other) console(monkeypatch, answer) - monkeypatch.setattr(application, "machine_fingerprint", lambda: "0123456789abcdef0123456789abcdef") + monkeypatch.setattr(application, "machine_identity", lambda: ("0123456789abcdef0123456789abcdef", "devid")) assert (await application.apply(dict(FORM), "admin"))["request_id"] == "req_10" await application.take("req_9") @@ -663,7 +665,7 @@ async def test_ea7h_a_token_a_patch_revoked_does_not_offer_itself_by_its_own_dat assert (await application.applications())["items"][0]["can_take"] is False console(monkeypatch, lambda r: httpx.Response(200, json={"request_id": "req_10", "status": "pending"})) - monkeypatch.setattr(application, "machine_fingerprint", lambda: "0123456789abcdef0123456789abcdef") + monkeypatch.setattr(application, "machine_identity", lambda: ("0123456789abcdef0123456789abcdef", "devid")) assert (await application.apply(dict(FORM), "admin"))["request_id"] == "req_10" diff --git a/tests/updater/test_machine_fingerprint.py b/tests/updater/test_machine_fingerprint.py index ceb5f3452..723c7cab6 100644 --- a/tests/updater/test_machine_fingerprint.py +++ b/tests/updater/test_machine_fingerprint.py @@ -1,12 +1,19 @@ """flocks.updater.machine_fingerprint: this machine as the enterprise core names it. Case list (编号 | 场景): - MF1 the digest is the core's (activation.MachineFingerprint): sha256 of the domain and the id, trimmed - and lower-cased, its first 16 bytes in hex; no id gives none - MF2 on Linux the machine id comes from /etc/machine-id, then the D-Bus copy; none when neither has one; - one that cannot be read is MachineIdUnreadable, not none - MF3 on macOS it comes from the platform UUID ioreg reports; ioreg not running, failing or naming none + MF1 the machine-id digest is the core's: sha256 of the domain and the id, trimmed and lower-cased, its first + 16 bytes in hex; no id gives none + MF2 the device id is the core's and the library's: MD5 of "flocks" and what it hashes, the digits libdevid + printed on a Linux VM (in lower case), real UUIDs put in its SMBIOS table among them; UUIDs format as + dmidecode prints them, in lower case; the SMBIOS table walk finds the type 1 UUID and stops at a table cut + short -- the same cases as flockspro go/internal/devid + MF3 on Linux a readable SMBIOS table with the host's UUID gives the device id; without root (no table), or a + UUID the firmware leaves unset, the machine id gives the digest, from /etc/machine-id, then the D-Bus copy; + none when neither has one; one that cannot be read is MachineIdUnreadable, not none + MF4 an AWS Xen host hashes its board asset tag, else its hypervisor UUID, which any account may read + MF5 on macOS the platform UUID ioreg reports gives the device id; ioreg not running, failing or naming none is MachineIdUnreadable (every Mac has one) + MF6 elsewhere (Windows) the host is not named: applications go out unbound, as before """ from __future__ import annotations @@ -25,27 +32,107 @@ def test_mf1_the_digest_is_the_cores(): assert mf.fingerprint_of(" ") == "" -def test_mf2_linux_reads_the_machine_id_then_the_dbus_copy(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): - etc, dbus = tmp_path / "machine-id", tmp_path / "dbus-machine-id" +def test_mf2_the_device_id_is_the_librarys(): + # get_dev_id("flocks", "") of libdevid-1.2.6 on a QEMU VM whose firmware sets no UUID: none read without + # root, "Not Settable" with. + assert mf.device_id_of("") == "58ab768421a90d0fec6ecff8ea0b1bf5" + assert mf.device_id_of("Not Settable") == "a6d4534ba1eb061f2eb21438bdaec761" + # Real UUIDs as the table holds them (SMBIOS 2.8), and what libdevid printed for each once root bind-mounted + # that table over /sys/firmware/dmi/tables/DMI. Upper-case text hashes to other ids. + for raw, want in { + "44454c4c350010308030b4c04f4b4b32": "4118c84a2b529d4532ecef9d021c2ae3", + "0123456789abcdeffedcba9876543210": "c7093283e36914e17c95fb40281665fc", + "a1b2c3d4e5f60718293a4b5c6d7e8f90": "2d71ce041ce578e2da445b203efb372f", + }.items(): + assert mf.device_id_of(mf.format_smbios_uuid(bytes.fromhex(raw), 2, 8)) == want, raw + + uuid = bytes([0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]) + assert mf.format_smbios_uuid(bytes(16), 2, 8) == "Not Settable" + assert mf.format_smbios_uuid(b"\xff" * 16, 3, 0) == "Not Present" + assert mf.format_smbios_uuid(uuid, 2, 8) == "78563412-bc9a-f0de-1122-334455667788" + assert mf.format_smbios_uuid(uuid, 3, 2) == "78563412-bc9a-f0de-1122-334455667788" + assert mf.format_smbios_uuid(uuid, 2, 5) == "12345678-9abc-def0-1122-334455667788" + assert mf.format_smbios_uuid(uuid[:15], 2, 8) == "" + + bios = bytes([0, 0x12, 0, 0]) + bytes(0x0E) + b"v1\0\0" + system = bytes([1, 0x1B, 1, 0, 1, 2, 0, 0]) + uuid + bytes([6, 0, 0]) + b"QEMU\0pc\0\0" + end = bytes([127, 4, 2, 0, 0, 0]) + assert mf.smbios_system_uuid(bios + system + end, 2, 8) == "78563412-bc9a-f0de-1122-334455667788" + for name, cut in { + "no type 1": bios + end, + "type 1 before the UUID": bytes([1, 0x08, 1, 0, 1, 2, 0, 0, 0, 0]), + "length past the end": bytes([1, 0x40, 1, 0, 0, 0]), + "length under four": bytes([1, 2, 0, 0, 0, 0]), + "UUID cut short": system[:20], + "empty": b"", + }.items(): + assert mf.smbios_system_uuid(cut, 2, 8) == "", name + + +def _linux(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> dict[str, Path]: + paths = { + "etc": tmp_path / "machine-id", "dbus": tmp_path / "dbus-machine-id", "entry": tmp_path / "smbios_entry_point", + "table": tmp_path / "DMI", "hypervisor": tmp_path / "hypervisor-uuid", "tag": tmp_path / "board_asset_tag", + } monkeypatch.setattr(mf.sys, "platform", "linux") - monkeypatch.setattr(mf, "LINUX_MACHINE_ID_FILES", (etc, dbus)) - assert mf.machine_fingerprint() == "" - dbus.write_text("ABC\n") - assert mf.machine_fingerprint() == mf.fingerprint_of("abc") - etc.write_text("\n") + monkeypatch.setattr(mf, "LINUX_MACHINE_ID_FILES", (paths["etc"], paths["dbus"])) + monkeypatch.setattr(mf, "LINUX_SMBIOS_ENTRY_POINT", paths["entry"]) + monkeypatch.setattr(mf, "LINUX_SMBIOS_TABLE", paths["table"]) + monkeypatch.setattr(mf, "LINUX_HYPERVISOR_UUID", paths["hypervisor"]) + monkeypatch.setattr(mf, "LINUX_BOARD_ASSET_TAG", paths["tag"]) + return paths + + +def _table(uuid: bytes) -> bytes: + return bytes([1, 0x1B, 1, 0, 1, 2, 0, 0]) + uuid + bytes([6, 0, 0]) + b"QEMU\0pc\0\0" + bytes([127, 4, 2, 0, 0, 0]) + + +def test_mf3_linux(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + paths = _linux(monkeypatch, tmp_path) + # No SMBIOS table to read (no root here) and no machine id: nothing names the host. + assert mf.machine_identity() == ("", "") + paths["dbus"].write_text("ABC\n") + assert mf.machine_identity() == (mf.fingerprint_of("abc"), mf.KIND_MACHINE_ID) + paths["etc"].write_text("\n") assert mf.machine_fingerprint() == mf.fingerprint_of("abc"), "an empty machine-id falls through to the D-Bus copy" - etc.write_text("def\n") - assert mf.machine_fingerprint() == mf.fingerprint_of("def") + paths["etc"].write_text("def\n") + assert mf.machine_identity() == (mf.fingerprint_of("def"), mf.KIND_MACHINE_ID) + + # SMBIOS 3.0 entry point (version at bytes 7 and 8), and the table root may read. + uuid = bytes([0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]) + paths["entry"].write_bytes(b"_SM3_" + bytes([0x18, 0x18, 3, 2]) + bytes(15)) + paths["table"].write_bytes(_table(uuid)) + assert mf.machine_identity() == (mf.device_id_of("78563412-bc9a-f0de-1122-334455667788"), mf.KIND_DEVID) + # A 32-bit entry point of SMBIOS 2.4: the UUID as the firmware has it. + paths["entry"].write_bytes(b"_SM_" + bytes([0, 0x1F, 2, 4]) + bytes(23)) + assert mf.machine_fingerprint() == mf.device_id_of("12345678-9abc-def0-1122-334455667788") + # A UUID the firmware leaves unset names no host: the digest does. + paths["table"].write_bytes(_table(bytes(16))) + assert mf.machine_identity() == (mf.fingerprint_of("def"), mf.KIND_MACHINE_ID) + paths["table"].write_bytes(_table(uuid)) def unreadable(self, *args, **kwargs): raise PermissionError(13, "Permission denied") + # The machine id is not read when the device id is there; without it, it must be. monkeypatch.setattr(Path, "read_text", unreadable) + assert mf.machine_identity()[1] == mf.KIND_DEVID + paths["table"].unlink() with pytest.raises(mf.MachineIdUnreadable, match="Permission denied"): mf.machine_fingerprint() -def test_mf3_macos_reads_the_platform_uuid(monkeypatch: pytest.MonkeyPatch): +def test_mf4_an_aws_host(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + paths = _linux(monkeypatch, tmp_path) + paths["hypervisor"].write_text("ec2e1916-9099-7caf-fd21-012345abcdef\n") + assert mf.machine_identity() == (mf.device_id_of("ec2e1916-9099-7caf-fd21-012345abcdef"), mf.KIND_DEVID) + paths["tag"].write_text("i-0abc\n") + assert mf.machine_identity() == (mf.device_id_of("i-0abc"), mf.KIND_DEVID) + paths["hypervisor"].write_text("4c4c4544-0035-3010-8030-b4c04f4b4b32\n") + assert mf.machine_identity() == ("", ""), "a hypervisor UUID that is no EC2 one is no AWS host" + + +def test_mf5_macos_reads_the_platform_uuid(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(mf.sys, "platform", "darwin") calls: list[list[str]] = [] @@ -54,7 +141,7 @@ def run(args, **kwargs): return subprocess.CompletedProcess(args, 0, stdout=' "IOPlatformUUID" = "1A2B-3C4D"\n', stderr="") monkeypatch.setattr(mf.subprocess, "run", run) - assert mf.machine_fingerprint() == mf.fingerprint_of("1a2b-3c4d") + assert mf.machine_identity() == (mf.device_id_of("1a2b-3c4d"), mf.KIND_DEVID) assert calls == [["/usr/sbin/ioreg", "-rd1", "-c", "IOPlatformExpertDevice"]] monkeypatch.setattr(mf.subprocess, "run", lambda *a, **k: subprocess.CompletedProcess(a, 0, stdout="nothing", stderr="")) @@ -71,3 +158,8 @@ def timeout(*args, **kwargs): monkeypatch.setattr(mf.subprocess, "run", timeout) with pytest.raises(mf.MachineIdUnreadable): mf.machine_fingerprint() + + +def test_mf6_elsewhere_the_host_is_not_named(monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(mf.sys, "platform", "win32") + assert mf.machine_identity() == ("", "") From 5e3ad00a5cf31b8be8ae347f6e98a9edbba3d875 Mon Sep 17 00:00:00 2001 From: jamon Date: Fri, 13 Nov 2026 11:34:02 +0800 Subject: [PATCH 28/44] =?UTF-8?q?fix(webui):=20=E5=B7=A5=E4=BD=9C=E6=B5=81?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E8=BF=90=E8=A1=8C=E7=9A=84=E7=BB=93=E6=9E=9C?= =?UTF-8?q?=E5=8D=A1=E7=89=87=E8=87=AA=E5=8A=A8=E6=BB=9A=E8=BF=9B=E5=8F=B3?= =?UTF-8?q?=E4=BE=A7=E9=9D=A2=E6=9D=BF=E7=9A=84=E5=8F=AF=E8=A7=81=E5=8C=BA?= =?UTF-8?q?=E5=9F=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 结果卡片渲染在「测试运行」按钮下面。窗口高 900 或 768 时按钮贴着面板 可见区域的底边,卡片落在下面:失败卡片 72px 里只露出 18px,点完不往下 滚就看不到失败原因,成功结果也一样。 handleRun 在请求被接受或被拒绝时登记这次运行,它的记录出现或变化时把 卡片底边滚进可见区域(下面留 12px,卡片比面板高时从顶部显示)。第一次 无条件滚;之后只在卡片变高、并且卡片顶还在可见区域里时才继续滚,用户 滚走了不拉回来;运行结束就不再跟随。打开页面时从历史带出来的记录、历史 轮询刷新的记录不触发滚动。 只改最近的可滚动祖先(右侧面板)的 scrollTop,没用 scrollIntoView:它会 把 overflow-hidden 的祖先也滚动,
被它滚走过。 已知还有一种情况没接住:工作流第一次有运行记录、且这次运行是轮询结束 的,统计区随后多出一行,把卡片再往下推 24px,底部被裁 12px。 RunTab.test.tsx 补 6 条用例。 --- .../pages/WorkflowDetail/tabs/RunTab.test.tsx | 149 +++++++++++++++++- .../src/pages/WorkflowDetail/tabs/RunTab.tsx | 51 +++++- 2 files changed, 197 insertions(+), 3 deletions(-) diff --git a/webui/src/pages/WorkflowDetail/tabs/RunTab.test.tsx b/webui/src/pages/WorkflowDetail/tabs/RunTab.test.tsx index 3a65304c8..3bfd6ff2f 100644 --- a/webui/src/pages/WorkflowDetail/tabs/RunTab.test.tsx +++ b/webui/src/pages/WorkflowDetail/tabs/RunTab.test.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import RunTab from './RunTab'; @@ -560,4 +560,151 @@ describe('RunTab', () => { }); }); + describe('bringing the result of a test run into view', () => { + const acceptedRun: WorkflowExecution = { + id: 'exec-new', + workflowId: 'wf-1', + inputParams: {}, + status: 'running', + startedAt: Date.now(), + executionLog: [], + }; + const finishedRun: WorkflowExecution = { + ...acceptedRun, + status: 'success', + outputResults: { marker: 'finished' }, + duration: 1, + }; + let measure: { mockRestore: () => void } | undefined; + + afterEach(() => { + measure?.mockRestore(); + measure = undefined; + }); + + /** + * jsdom lays nothing out, so the test says where things are: the panel shows what lies between + * 100 and 500, and the result card is wherever `card` puts it. Nothing else is ever measured. + */ + function layOut(card: () => [top: number, bottom: number]) { + measure = vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) { + const [top, bottom] = this.getAttribute('data-testid') === 'panel' ? [100, 500] : card(); + return { top, bottom, left: 0, right: 320, width: 320, height: bottom - top, x: 0, y: top, toJSON: () => ({}) }; + }); + } + + /** The tab inside a panel the user scrolls, as it sits in the page. */ + function renderInPanel(ui: React.ReactElement = ) { + render(
{ui}
); + return screen.getByTestId('panel'); + } + + /** Hold back the history responses from now on; the returned function answers them. */ + function holdHistory() { + let answer!: (history: WorkflowExecution[]) => void; + const held = new Promise<{ data: WorkflowExecution[] }>((resolve) => { + answer = (history) => resolve({ data: history }); + }); + workflowAPI.getHistory.mockReturnValue(held); + return async (history: WorkflowExecution[]) => { + await waitFor(() => { + expect(workflowAPI.getHistory.mock.results.some((result) => result.value === held)).toBe(true); + }); + await act(async () => { + answer(history); + }); + }; + } + + it('shows why a run was refused without the user having to scroll down to it', async () => { + const user = userEvent.setup(); + workflowAPI.run.mockRejectedValue(new Error('Workflow not found: wf-1')); + layOut(() => [490, 562]); + const panel = renderInPanel(); + await screen.findByText('暂无执行记录'); + + await user.click(screen.getByRole('button', { name: '测试运行' })); + + expect(await screen.findByText('Workflow not found: wf-1')).toBeInTheDocument(); + expect(panel.scrollTop).toBe(562 + 12 - 500); + }); + + it('shows a result taller than the panel from its top', async () => { + const user = userEvent.setup(); + workflowAPI.run.mockRejectedValue(new Error('Workflow not found: wf-1')); + layOut(() => [490, 1200]); + const panel = renderInPanel(); + await screen.findByText('暂无执行记录'); + + await user.click(screen.getByRole('button', { name: '测试运行' })); + + expect(await screen.findByText('Workflow not found: wf-1')).toBeInTheDocument(); + expect(panel.scrollTop).toBe(490 - 100); + }); + + it('keeps the result in view as the run it started finishes and the card grows', async () => { + const user = userEvent.setup(); + workflowAPI.run.mockResolvedValue({ data: acceptedRun }); + let card: [number, number] = [490, 530]; + layOut(() => card); + const panel = renderInPanel(); + await screen.findByText('暂无执行记录'); + const answerHistory = holdHistory(); + + await user.click(screen.getByRole('button', { name: '测试运行' })); + await waitFor(() => expect(panel.scrollTop).toBe(530 + 12 - 500)); + + card = [448, 648]; + await answerHistory([finishedRun]); + expect(screen.getByText(/"marker": "finished"/)).toBeInTheDocument(); + expect(panel.scrollTop).toBe(42 + 648 + 12 - 500); + }); + + it('does not pull the panel back once the user has scrolled away from a run in progress', async () => { + const user = userEvent.setup(); + workflowAPI.run.mockResolvedValue({ data: acceptedRun }); + let card: [number, number] = [490, 530]; + layOut(() => card); + const panel = renderInPanel(); + await screen.findByText('暂无执行记录'); + const answerHistory = holdHistory(); + + await user.click(screen.getByRole('button', { name: '测试运行' })); + await waitFor(() => expect(panel.scrollTop).toBe(42)); + + panel.scrollTop = 0; + card = [560, 760]; + await answerHistory([finishedRun]); + expect(screen.getByText(/"marker": "finished"/)).toBeInTheDocument(); + expect(panel.scrollTop).toBe(0); + }); + + it('does not fight the user over the scroll position while the run has nothing new to show', async () => { + const user = userEvent.setup(); + workflowAPI.run.mockResolvedValue({ data: acceptedRun }); + let card: [number, number] = [490, 530]; + layOut(() => card); + const panel = renderInPanel(); + await screen.findByText('暂无执行记录'); + const answerHistory = holdHistory(); + + await user.click(screen.getByRole('button', { name: '测试运行' })); + await waitFor(() => expect(panel.scrollTop).toBe(42)); + + panel.scrollTop = 30; + card = [470, 510]; + await answerHistory([{ ...acceptedRun }]); + expect(panel.scrollTop).toBe(30); + }); + + it('leaves the panel where it is when the page opens on a result from the history', async () => { + workflowAPI.getHistory.mockResolvedValue({ data: [finishedRun] }); + layOut(() => [490, 700]); + const panel = renderInPanel(); + + expect(await screen.findByText(/"marker": "finished"/)).toBeInTheDocument(); + expect(panel.scrollTop).toBe(0); + }); + }); + }); diff --git a/webui/src/pages/WorkflowDetail/tabs/RunTab.tsx b/webui/src/pages/WorkflowDetail/tabs/RunTab.tsx index 824fa1700..980589e8e 100644 --- a/webui/src/pages/WorkflowDetail/tabs/RunTab.tsx +++ b/webui/src/pages/WorkflowDetail/tabs/RunTab.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect, useCallback, useRef, type Dispatch, type SetStateAction } from 'react'; +import { useState, useEffect, useLayoutEffect, useCallback, useRef, type Dispatch, type SetStateAction } from 'react'; import { Loader2, ChevronDown, ChevronRight, StopCircle, Clock, CheckCircle, XCircle, AlertCircle, FlaskConical, @@ -47,6 +47,37 @@ function isLocalRunFailure(execution: WorkflowExecution | null): boolean { return !!execution && !execution.id; } +/** Room left under the result card when the panel is scrolled to show it. */ +const RESULT_CARD_MARGIN = 12; + +/** + * Scroll the panel the result card sits in, far enough for the card's bottom edge to show but + * never past its top. Only that panel moves: `scrollIntoView` would also scroll every ancestor + * that can be scrolled from code, the page's `overflow-hidden` shell included. + * + * `shownHeight` is how tall the card was when it was last brought into view, or null when this is + * the first time. After the first time the panel only follows the card as it grows, and only + * while its top is still in view, so a user who has scrolled elsewhere is not pulled back. + * Returns how tall the card is now. + */ +function keepResultCardInView(card: HTMLElement, shownHeight: number | null): number | null { + let panel = card.parentElement; + while (panel && !/^(auto|scroll)$/.test(window.getComputedStyle(panel).overflowY)) { + panel = panel.parentElement; + } + const box = card.getBoundingClientRect(); + if (!panel || box.height === 0) return shownHeight; + const view = panel.getBoundingClientRect(); + const viewBottom = Math.min(view.bottom, window.innerHeight); + if (shownHeight !== null) { + const topInView = box.top >= view.top && box.top < viewBottom; + if (box.height <= shownHeight || !topInView) return box.height; + } + const hidden = box.bottom + RESULT_CARD_MARGIN - viewBottom; + if (hidden > 0) panel.scrollTop += Math.min(hidden, Math.max(box.top - view.top, 0)); + return box.height; +} + function getExecutionDisplayMessage( execution: WorkflowExecution | null | undefined, t: (key: string) => string, @@ -461,6 +492,20 @@ function TestSection({ const lastSavedInputsRef = useRef(inputs); const saveTimerRef = useRef(null); const saveFeedbackTimerRef = useRef(null); + const resultCardRef = useRef(null); + // The run the user has just asked for, from the answer to the request until the run ends. Its + // result card sits under the button, often below what the panel shows, so it is brought into + // view. Executions that got here another way (the latest from the history, say) are left alone. + const requestedRunRef = useRef<{ id: string; shownHeight: number | null } | null>(null); + + useLayoutEffect(() => { + const requested = requestedRunRef.current; + if (!requested || !execution || execution.id !== requested.id) return; + if (resultCardRef.current) { + requested.shownHeight = keepResultCardInView(resultCardRef.current, requested.shownHeight); + } + if (execution.status !== 'running') requestedRunRef.current = null; + }, [execution]); useEffect(() => { workflowAPI.getSampleInputs(workflow.id).then(res => { @@ -609,8 +654,10 @@ function TestSection({ setStopping(false); try { const res = await workflowAPI.run(workflow.id, { inputs: parsed }); + requestedRunRef.current = { id: res.data.id, shownHeight: null }; onExecutionChange?.(res.data); } catch (err: any) { + requestedRunRef.current = { id: '', shownHeight: null }; setRunning(false); const msg = err?.response?.data?.detail || err?.message || t('detail.run.runFailed'); onExecutionChange?.({ @@ -696,7 +743,7 @@ function TestSection({ {execution && ( -
+
{execution.duration != null && ( From f4af691a54cffdb5e4b6340fd7876698b9db718b Mon Sep 17 00:00:00 2001 From: jamon Date: Fri, 13 Nov 2026 13:19:39 +0800 Subject: [PATCH 29/44] fix(project): report directories the service account cannot reach as not readable instead of missing or a 500 (INC-61BE1F94) --- flocks/project/project.py | 62 +++++++-- .../project/test_project_directory_access.py | 118 ++++++++++++++++++ tests/server/routes/test_project_routes.py | 28 +++++ 3 files changed, 199 insertions(+), 9 deletions(-) create mode 100644 tests/project/test_project_directory_access.py diff --git a/flocks/project/project.py b/flocks/project/project.py index 5992751c5..96c6d7662 100644 --- a/flocks/project/project.py +++ b/flocks/project/project.py @@ -359,8 +359,13 @@ def worktree_for_directory(cls, directory: str) -> str: return os.path.normcase(str(worktree)) @staticmethod - def _path_status(worktree: str) -> Literal["available", "missing", "unreadable"]: - path = Path(worktree) + def _directory_access(path: Path) -> Literal["available", "missing", "unreadable"]: + """Whether the account running Flocks can open ``path`` as a directory. + + ``missing`` means nothing reachable is a directory there; ``unreadable`` + that this account may not reach or list it, whether it exists or not. + """ + try: if not path.is_dir(): return "missing" @@ -371,8 +376,22 @@ def _path_status(worktree: str) -> Literal["available", "missing", "unreadable"] return "unreadable" if not os.access(path, os.R_OK | os.X_OK): return "unreadable" + # os.access only reads permission bits; on Windows it ignores the access + # list, so a service account left out of a folder's ACL passes it. Opening + # the folder for listing is the check the system itself makes. + try: + with os.scandir(path): + pass + except (FileNotFoundError, NotADirectoryError): + return "missing" + except OSError: + return "unreadable" return "available" + @classmethod + def _path_status(cls, worktree: str) -> Literal["available", "missing", "unreadable"]: + return cls._directory_access(Path(worktree)) + @staticmethod def _detect_vcs(worktree: str) -> Optional[str]: try: @@ -424,7 +443,13 @@ def validate_worktree( requested_path = Path(os.path.abspath(requested_path)) roots = cls.allowed_roots(default_worktree) - if create_if_missing and not requested_path.exists(): + try: + needs_creation = create_if_missing and not requested_path.exists() + except PermissionError: + # It may exist: this account cannot reach it. Reported below as + # such; creating it would fail the same way. + needs_creation = False + if needs_creation: ancestor = requested_path missing_parts: List[str] = [] while not ancestor.exists() and ancestor != ancestor.parent: @@ -444,15 +469,34 @@ def validate_worktree( try: path = requested_path.resolve(strict=True) + readable = True + except PermissionError: + # A parent denies search, or on Windows the folder's access list + # leaves this account out: the folder may well exist, so this is a + # permission to grant, not a path to correct. + readable = False + try: + path = requested_path.resolve(strict=False) + except (OSError, RuntimeError): + path = requested_path except (OSError, RuntimeError) as exc: raise ValueError("Project directory does not exist") from exc - if not path.is_dir(): - raise ValueError("Project path must be a directory") - if not os.access(path, os.R_OK | os.X_OK): - raise ValueError("Project directory is not readable") - - if roots and not any(path == root or path.is_relative_to(root) for root in roots): + if readable: + access = cls._directory_access(path) + if access == "missing": + raise ValueError("Project path must be a directory") + readable = access == "available" + + # The allowed roots and this account's access are separate settings + # (FLOCKS_PROJECT_ROOTS; the folder's permissions or ACL), each fixed + # by an administrator: name every one that is missing. + allowed = not roots or any(path == root or path.is_relative_to(root) for root in roots) + if not allowed and not readable: + raise ValueError("Project directory is outside the allowed roots and is not readable") + if not allowed: raise ValueError("Project directory is outside the allowed roots") + if not readable: + raise ValueError("Project directory is not readable") return os.path.normcase(str(path)) @classmethod diff --git a/tests/project/test_project_directory_access.py b/tests/project/test_project_directory_access.py new file mode 100644 index 000000000..213802910 --- /dev/null +++ b/tests/project/test_project_directory_access.py @@ -0,0 +1,118 @@ +"""The allowed roots and the service account's access to a project directory. + +They are separate settings an administrator changes (FLOCKS_PROJECT_ROOTS; the +folder's permissions or ACL), so a directory the account running Flocks cannot +reach is reported as such, never as missing, and both are named when both are +missing (INC-61BE1F94). +""" + +import os +from contextlib import contextmanager +from pathlib import Path + +import pytest + +import flocks.project.project as project_module +from flocks.project.project import Project + +posix_permissions = pytest.mark.skipif( + os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), + reason="needs POSIX directory permissions enforced for this account", +) + + +@contextmanager +def _mode(path: Path, mode: int): + original = path.stat().st_mode & 0o777 + path.chmod(mode) + try: + yield + finally: + path.chmod(original) + + +@pytest.fixture +def allowed_root(tmp_path, monkeypatch): + root = tmp_path / "allowed" + root.mkdir() + monkeypatch.setenv("FLOCKS_PROJECT_ROOTS", str(root)) + return root + + +@posix_permissions +def test_unreachable_directory_is_not_reported_missing(allowed_root): + parent = allowed_root / "svc-denied" + worktree = parent / "repo" + worktree.mkdir(parents=True) + + with _mode(parent, 0o600): + with pytest.raises(ValueError, match=r"^Project directory is not readable$"): + Project.validate_worktree(str(worktree)) + assert Project._path_status(str(worktree)) == "unreadable" + + +@posix_permissions +def test_missing_root_and_missing_permission_are_both_named(allowed_root, tmp_path): + parent = tmp_path / "elsewhere" + worktree = parent / "repo" + worktree.mkdir(parents=True) + + with _mode(parent, 0o600): + with pytest.raises( + ValueError, + match=r"^Project directory is outside the allowed roots and is not readable$", + ): + Project.validate_worktree(str(worktree)) + with pytest.raises(ValueError, match=r"^Project directory is outside the allowed roots$"): + Project.validate_worktree(str(worktree)) + + +@posix_permissions +def test_creating_under_an_unreachable_parent_is_a_permission_error(allowed_root): + parent = allowed_root / "svc-denied" + parent.mkdir() + + with _mode(parent, 0o600): + with pytest.raises(ValueError, match=r"^Project directory is not readable$"): + Project.validate_worktree(str(parent / "repo"), create_if_missing=True) + assert not (parent / "repo").exists() + + +@posix_permissions +def test_listing_is_checked_where_permission_bits_allow_it(allowed_root, monkeypatch): + """Windows' os.access ignores the ACL that leaves the service account out.""" + + worktree = allowed_root / "acl-denied" + worktree.mkdir() + real_access = os.access + + def access_ignoring_acl(path, mode, *args, **kwargs): + if Path(path) == worktree: + return True + return real_access(path, mode, *args, **kwargs) + + monkeypatch.setattr(project_module.os, "access", access_ignoring_acl) + with _mode(worktree, 0o000): + assert Project._path_status(str(worktree)) == "unreadable" + with pytest.raises(ValueError, match=r"^Project directory is not readable$"): + Project.validate_worktree(str(worktree)) + assert Project._path_status(str(worktree)) == "available" + + +def test_what_did_not_change(allowed_root): + path = allowed_root / "file.txt" + path.write_text("x", encoding="utf-8") + readable = allowed_root / "repo" + readable.mkdir() + + with pytest.raises(ValueError, match=r"^Project path must be a directory$"): + Project.validate_worktree(str(path)) + with pytest.raises(ValueError, match=r"^Project directory does not exist$"): + Project.validate_worktree(str(allowed_root / "absent")) + assert Project.validate_worktree(str(readable)) == os.path.normcase(str(readable.resolve())) + created = allowed_root / "new" / "nested" + assert Project.validate_worktree(str(created), create_if_missing=True) == os.path.normcase( + str(created.resolve()) + ) + assert Project._path_status(str(readable)) == "available" + assert Project._path_status(str(allowed_root / "absent")) == "missing" diff --git a/tests/server/routes/test_project_routes.py b/tests/server/routes/test_project_routes.py index 65df23401..8966c2f5d 100644 --- a/tests/server/routes/test_project_routes.py +++ b/tests/server/routes/test_project_routes.py @@ -539,6 +539,34 @@ async def test_project_list_reports_unreachable_worktree_as_unreadable( assert fetched.json()["pathStatus"] == "unreadable" +@pytest.mark.skipif( + os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), + reason="needs POSIX directory search permission enforced for this account", +) +@pytest.mark.asyncio +async def test_create_project_reports_unreachable_directory_as_not_readable( + client: AsyncClient, + tmp_path: Path, +): + """INC-61BE1F94: a folder the service account cannot reach is a permission to + grant, not a missing directory, and never a 500 carrying the server's path.""" + + parent = tmp_path / "svc-denied" + worktree = parent / "repo" + worktree.mkdir(parents=True) + parent.chmod(0o600) + try: + response = await client.post( + "/api/project", + json={"name": "Denied", "worktree": str(worktree)}, + ) + finally: + parent.chmod(0o700) + + assert response.status_code == status.HTTP_400_BAD_REQUEST, response.text + assert response.json()["message"] == "Project directory is not readable" + + @pytest.mark.asyncio async def test_folder_browser_starts_at_home_when_path_is_omitted( client: AsyncClient, From 8d87b70f12bece93e819e44beb03a5c3b323f591 Mon Sep 17 00:00:00 2001 From: jamon Date: Fri, 13 Nov 2026 13:31:15 +0800 Subject: [PATCH 30/44] =?UTF-8?q?fix(provider):=20=E5=86=85=E9=83=A8=20LLM?= =?UTF-8?q?=20=E7=BD=91=E5=85=B3=E7=9A=84=20SSL=20=E6=A0=A1=E9=AA=8C?= =?UTF-8?q?=E5=8F=AF=E5=9C=A8=E6=A8=A1=E5=9E=8B=E9=A1=B5=E5=85=B3=E9=97=AD?= =?UTF-8?q?=E6=88=96=E6=8C=87=E5=AE=9A=20CA=EF=BC=8C=E5=85=B3=E9=97=AD?= =?UTF-8?q?=E5=90=8E=E5=85=BC=E5=AE=B9=E6=97=A7=E7=89=88=20TLS=20=E6=8F=A1?= =?UTF-8?q?=E6=89=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新装法自带的 python-build-standalone 用 CPython 自己的 TLS 默认,比旧装法在 RHEL 8 上用的系统 Python 严。 网关只支持 RSA 密钥交换、CBC-SHA1 或 TLS 1.0/1.1 时,verify_ssl=false 只关证书校验,握手照样失败; 模型页也一直没有这个开关,Anthropic、Azure、OpenRouter 不认它,没法指定内部 CA。 - flocks/provider/tls.py:把 verify_ssl / ca_cert 转成 httpx 的 verify;都没设时仍是 True。 关闭校验时放宽握手(DEFAULT:@SECLEVEL=0、最低 TLS 1.0、OP_LEGACY_SERVER_CONNECT), ca_cert(PEM 或绝对路径)在默认根证书之外追加信任,填错直接报错 - OpenAI 系(含 custom-*)、Anthropic、Azure、OpenRouter 和模型发现接入;BaseProvider.SUPPORTS_TLS_SETTINGS - 凭据接口和新建自定义供应商读写这两个设置,先校验 CA 再写;检查 Key / 获取模型可带未保存的设置,逐项覆盖 - 连接失败时分清证书问题和握手问题并给出提示 - 模型页新增 / 编辑供应商加「SSL 证书」区块(开关、CA 证书、关闭提示) --- flocks/provider/model_discovery.py | 71 ++- flocks/provider/provider.py | 5 + flocks/provider/sdk/anthropic.py | 18 +- flocks/provider/sdk/azure.py | 15 +- flocks/provider/sdk/openai.py | 4 +- flocks/provider/sdk/openai_base.py | 40 +- flocks/provider/sdk/openai_compatible.py | 4 +- flocks/provider/sdk/openrouter.py | 13 +- flocks/provider/tls.py | 274 ++++++++++ flocks/server/routes/custom_provider.py | 24 +- flocks/server/routes/model_discovery.py | 30 +- flocks/server/routes/provider.py | 133 ++++- tests/provider/test_model_discovery.py | 91 +++- tests/provider/test_openai_base_provider.py | 4 +- .../test_openai_compatible_provider.py | 4 +- tests/provider/test_openai_provider.py | 4 +- tests/provider/test_provider_tls.py | 488 ++++++++++++++++++ tests/provider/tls_helpers.py | 186 +++++++ .../routes/test_model_discovery_routes.py | 31 +- webui/src/api/provider.ts | 5 +- webui/src/locales/en-US/model.json | 22 +- webui/src/locales/zh-CN/model.json | 22 +- webui/src/pages/Model/ModelDiscovery.tsx | 13 +- webui/src/pages/Model/ProviderKeyCheck.tsx | 5 +- .../pages/Model/ProviderTlsSettings.test.tsx | 94 ++++ webui/src/pages/Model/ProviderTlsSettings.tsx | 117 +++++ webui/src/pages/Model/index.test.tsx | 111 ++++ webui/src/pages/Model/index.tsx | 35 +- webui/src/types/index.ts | 25 +- 29 files changed, 1804 insertions(+), 84 deletions(-) create mode 100644 flocks/provider/tls.py create mode 100644 tests/provider/test_provider_tls.py create mode 100644 tests/provider/tls_helpers.py create mode 100644 webui/src/pages/Model/ProviderTlsSettings.test.tsx create mode 100644 webui/src/pages/Model/ProviderTlsSettings.tsx diff --git a/flocks/provider/model_discovery.py b/flocks/provider/model_discovery.py index dd5d946c4..8f4bd1a6a 100644 --- a/flocks/provider/model_discovery.py +++ b/flocks/provider/model_discovery.py @@ -24,7 +24,16 @@ from flocks.provider.credential import UNSENDABLE_API_KEY_MESSAGE, api_key_is_sendable from flocks.provider.model_catalog import get_raw_catalog from flocks.provider.provider import Provider -from flocks.provider.sdk.openai_base import _coerce_bool, resolve_verify_ssl +from flocks.provider.sdk.openai_base import _coerce_bool +from flocks.provider.tls import ( + LEGACY_VERIFY_SSL_KEY, + TLS_ERROR_HINTS, + TLS_OPTION_KEYS, + VERIFY_SSL_KEY, + CACertError, + classify_tls_error, + httpx_verify, +) MAX_MODELS = 1000 MAX_PAGES = 10 @@ -157,23 +166,40 @@ def _resolve_option(value: Any, secrets: Any) -> str | None: return _usable(value) -def _transport_settings(options: dict, sdk_settings: Any) -> dict[str, bool]: +def _transport_settings(options: dict, sdk_settings: Any, tls_overrides: dict | None = None) -> dict[str, Any]: """TLS verification and proxy use, by the rules the provider's own client follows. - Same contract as sdk/openai_base.py: ``verify_ssl`` (or the older - ``ssl_verify``) in the provider options, and the ambient proxy settings - unless FLOCKS_HTTP_TRUST_ENV or the options' ``trust_env`` turn them off. + Same contract as the provider clients (flocks.provider.tls): ``verify_ssl`` + (or the older ``ssl_verify``) and ``ca_cert`` in the provider options, and + the ambient proxy settings unless FLOCKS_HTTP_TRUST_ENV or the options' + ``trust_env`` turn them off. *tls_overrides* are the TLS settings a + settings form has not saved yet; each one replaces the stored value of + that setting only, so a form that sends just the switch keeps the stored + CA certificate. """ - settings = options or (sdk_settings if isinstance(sdk_settings, dict) else {}) + settings = dict(options or (sdk_settings if isinstance(sdk_settings, dict) else {})) + overrides = {key: value for key, value in (tls_overrides or {}).items() if key in TLS_OPTION_KEYS} + if VERIFY_SSL_KEY in overrides: + settings.pop(LEGACY_VERIFY_SSL_KEY, None) # the older spelling must not outvote the new value + settings.update(overrides) trust_env = _coerce_bool(os.getenv("FLOCKS_HTTP_TRUST_ENV"), True) if "trust_env" in settings: trust_env = _coerce_bool(settings.get("trust_env"), trust_env) - return {"verify": resolve_verify_ssl(settings, default=True), "trust_env": trust_env} + try: + verify = httpx_verify(settings, trust_env=trust_env) + except CACertError as error: + raise DiscoveryError("invalid_ca_cert", str(error)) from error + return {"verify": verify, "trust_env": trust_env} async def _resolve_connection( - provider_id: str, raw: dict, catalog: dict, api_key: str | None, base_url: str | None -) -> tuple[str | None, str | None, dict[str, bool]]: + provider_id: str, + raw: dict, + catalog: dict, + api_key: str | None, + base_url: str | None, + tls_overrides: dict | None = None, +) -> tuple[str | None, str | None, dict[str, Any]]: resolved_options: dict = {} try: config = await Config.get() @@ -253,7 +279,9 @@ async def _resolve_connection( ) if provider_id in {"openai-compatible", "cherry"} and base_url is None and not (stored_url or env_url): effective_url = None - transport = _transport_settings(resolved_options or _dict(raw_options), getattr(sdk_config, "custom_settings", None)) + transport = _transport_settings( + resolved_options or _dict(raw_options), getattr(sdk_config, "custom_settings", None), tls_overrides + ) return effective_key, effective_url, transport @@ -534,9 +562,17 @@ def _catalog_result(provider_id: str, raw: dict, protocol: str | None, already_a async def discover_models( - provider_id: str, *, api_key: str | None = None, base_url: str | None = None + provider_id: str, + *, + api_key: str | None = None, + base_url: str | None = None, + tls_overrides: dict | None = None, ) -> dict[str, Any]: - """Fetch models without saving configuration or mutating a provider client.""" + """Fetch models without saving configuration or mutating a provider client. + + *tls_overrides* (``verify_ssl`` / ``ca_cert``) stand in for the stored TLS + settings, so a form can check a gateway before its settings are saved. + """ raw = ConfigWriter.get_provider_raw(provider_id) or {} catalog = get_raw_catalog().get(provider_id, {}) protocol = _protocol(provider_id, raw, catalog) @@ -547,7 +583,9 @@ async def discover_models( result = _catalog_result(provider_id, raw, protocol, already_added) else: async with asyncio.timeout(DISCOVERY_TIMEOUT_SECONDS): - key, url, transport = await _resolve_connection(provider_id, raw, catalog, api_key, base_url) + key, url, transport = await _resolve_connection( + provider_id, raw, catalog, api_key, base_url, tls_overrides + ) url = _endpoint(_validate_base_url(url), protocol) if not key and not _no_auth_allowed(provider_id, raw, protocol): raise DiscoveryError("missing_credentials", "Configure credentials before fetching models.") @@ -673,12 +711,13 @@ async def discover_models( "truncated": False, "models": [], } - except httpx.TransportError: + except httpx.TransportError as error: + tls_code = classify_tls_error(error) result = { "source": "none", "status": "error", - "code": "connection_error", - "message": "Could not connect to the provider model listing endpoint.", + "code": tls_code or "connection_error", + "message": TLS_ERROR_HINTS[tls_code] if tls_code else "Could not connect to the provider model listing endpoint.", "truncated": False, "models": [], } diff --git a/flocks/provider/provider.py b/flocks/provider/provider.py index 491b9b73a..d62afe014 100644 --- a/flocks/provider/provider.py +++ b/flocks/provider/provider.py @@ -1202,6 +1202,11 @@ class BaseProvider: # in get_model_definitions(). Leave empty for providers without a catalog entry. CATALOG_ID: str = "" + # True when the provider's HTTP client follows the ``verify_ssl`` and + # ``ca_cert`` options (flocks.provider.tls); the model settings page offers + # those settings only then. + SUPPORTS_TLS_SETTINGS: bool = False + # Per-event-loop SDK client cache; see LoopBoundClientSlot. _client = LoopBoundClientSlot() diff --git a/flocks/provider/sdk/anthropic.py b/flocks/provider/sdk/anthropic.py index fd5b80259..8cd6703b7 100644 --- a/flocks/provider/sdk/anthropic.py +++ b/flocks/provider/sdk/anthropic.py @@ -16,6 +16,7 @@ StreamChunk, ) from flocks.provider.sdk.openai_base import build_reasoning_metadata +from flocks.provider.tls import has_custom_tls, httpx_verify from flocks.provider.token_usage import normalize_usage from flocks.utils.log import Log @@ -38,6 +39,7 @@ class AnthropicProvider(BaseProvider): """Anthropic (Claude) provider with tool support.""" CATALOG_ID = "anthropic" + SUPPORTS_TLS_SETTINGS = True _INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14" _FINE_GRAINED_TOOL_STREAMING_BETA = "fine-grained-tool-streaming-2025-05-14" _THINKING_BLOCK_TYPES = frozenset({"thinking", "redacted_thinking"}) @@ -67,15 +69,23 @@ def _get_client(self): # Support custom base URL from config base_url = self._config.base_url if self._config else None - + client_kwargs: Dict[str, Any] = {"api_key": api_key} + # verify_ssl / ca_cert from the provider options; without them + # the SDK keeps building its own default client. + settings = getattr(self._config, "custom_settings", None) or {} + if has_custom_tls(settings): + from anthropic import DefaultAsyncHttpxClient + + client_kwargs["http_client"] = DefaultAsyncHttpxClient(verify=httpx_verify(settings)) + if base_url: log.info("anthropic.client.init", { "base_url": base_url, "has_api_key": bool(api_key), + "custom_tls": "http_client" in client_kwargs, }) - self._client = AsyncAnthropic(api_key=api_key, base_url=base_url) - else: - self._client = AsyncAnthropic(api_key=api_key) + client_kwargs["base_url"] = base_url + self._client = AsyncAnthropic(**client_kwargs) except ImportError: raise ImportError("anthropic package not installed. Install with: pip install anthropic") return self._client diff --git a/flocks/provider/sdk/azure.py b/flocks/provider/sdk/azure.py index cbc3d6d13..5ca746908 100644 --- a/flocks/provider/sdk/azure.py +++ b/flocks/provider/sdk/azure.py @@ -14,6 +14,7 @@ StreamChunk, ) from flocks.provider.sdk.openai_base import format_openai_messages +from flocks.provider.tls import has_custom_tls, httpx_verify from flocks.utils.log import Log log = Log.create(service="provider.azure") @@ -22,6 +23,8 @@ class AzureProvider(BaseProvider): """Azure OpenAI provider""" + SUPPORTS_TLS_SETTINGS = True + def __init__(self): super().__init__(provider_id="azure", name="Azure OpenAI") self._api_key = os.getenv("AZURE_OPENAI_API_KEY") @@ -56,13 +59,23 @@ def _get_client(self): "AZURE_OPENAI_API_VERSION", "2025-04-01-preview" ) + client_kwargs: Dict[str, Any] = {} + # verify_ssl / ca_cert from the provider options; without them + # the SDK keeps building its own default client. + settings = (self._config.custom_settings if self._config else None) or {} + if has_custom_tls(settings): + from openai import DefaultAsyncHttpxClient + + client_kwargs["http_client"] = DefaultAsyncHttpxClient(verify=httpx_verify(settings)) + # Create client self._client = AsyncAzureOpenAI( api_key=api_key, azure_endpoint=endpoint, api_version=api_version, + **client_kwargs, ) - self.log.info("azure.client.created", {"endpoint": endpoint}) + self.log.info("azure.client.created", {"endpoint": endpoint, "custom_tls": bool(client_kwargs)}) except ImportError: raise ImportError("openai package not installed. Install with: pip install openai") diff --git a/flocks/provider/sdk/openai.py b/flocks/provider/sdk/openai.py index d7f514e48..367bf5658 100644 --- a/flocks/provider/sdk/openai.py +++ b/flocks/provider/sdk/openai.py @@ -30,6 +30,7 @@ raise_if_response_body_unsafe, resolve_verify_ssl, ) +from flocks.provider.tls import httpx_verify from flocks.utils.log import Log log = Log.create(service="provider.openai") @@ -58,6 +59,7 @@ class OpenAIProvider(BaseProvider): """OpenAI (GPT) provider with tool support.""" CATALOG_ID = "openai" + SUPPORTS_TLS_SETTINGS = True def __init__(self): super().__init__(provider_id="openai", name="OpenAI") @@ -100,7 +102,7 @@ def _get_client(self): verify_ssl = resolve_verify_ssl(cfg_settings, default=True) http_client = create_openai_http_client( trust_env=trust_env, - verify=verify_ssl, + verify=httpx_verify(cfg_settings, trust_env=trust_env), timeout=DEFAULT_HTTP_TIMEOUT, custom_settings=cfg_settings, ) diff --git a/flocks/provider/sdk/openai_base.py b/flocks/provider/sdk/openai_base.py index 288374bc6..1e39a0aa4 100644 --- a/flocks/provider/sdk/openai_base.py +++ b/flocks/provider/sdk/openai_base.py @@ -8,10 +8,14 @@ """ import os -from typing import Any, AsyncIterator, Dict, List, Optional +import ssl +from typing import Any, AsyncIterator, Dict, List, Optional, Union import httpx +# ``_coerce_bool`` and ``resolve_verify_ssl`` keep being imported from here. +from flocks.provider.tls import coerce_bool as _coerce_bool +from flocks.provider.tls import httpx_verify, resolve_verify_ssl from flocks.provider.provider import ( BaseProvider, ChatMessage, @@ -132,11 +136,15 @@ async def _limit(response: httpx.Response) -> None: def create_openai_http_client( *, trust_env: bool, - verify: bool, + verify: Union[bool, ssl.SSLContext], timeout: httpx.Timeout = DEFAULT_HTTP_TIMEOUT, custom_settings: Any = None, ) -> httpx.AsyncClient: - """Build the shared OpenAI-compatible client with an ingress size cap.""" + """Build the shared OpenAI-compatible client with an ingress size cap. + + *verify* is what :func:`flocks.provider.tls.httpx_verify` gives for the + provider's options. + """ max_response_bytes = resolve_max_response_bytes(custom_settings) return httpx.AsyncClient( trust_env=trust_env, @@ -406,29 +414,6 @@ def format_openai_messages( return formatted -def _coerce_bool(value: Any, default: bool) -> bool: - """Coerce loosely-typed config values to bool.""" - if isinstance(value, bool): - return value - if isinstance(value, (int, float)): - return bool(value) - if isinstance(value, str): - return value.strip().lower() in {"1", "true", "yes", "on"} - return default - - -def resolve_verify_ssl(custom_settings: Any, default: bool = True) -> bool: - """Resolve the SSL verification flag from provider custom settings.""" - if not isinstance(custom_settings, dict): - return default - - if "verify_ssl" in custom_settings: - return _coerce_bool(custom_settings.get("verify_ssl"), default) - if "ssl_verify" in custom_settings: - return _coerce_bool(custom_settings.get("ssl_verify"), default) - return default - - def _normalize_stream_usage(raw_usage: Any, *, response_id: Any = None) -> Optional[Dict[str, Any]]: """Normalize provider usage objects to the shared usage schema. @@ -1003,6 +988,7 @@ class OpenAIBaseProvider(BaseProvider): ALLOW_NO_API_KEY: bool = False PREFER_MAX_COMPLETION_TOKENS: bool = False NO_API_KEY_PLACEHOLDER: str = "not-needed" + SUPPORTS_TLS_SETTINGS = True def __init__(self, provider_id: str, name: str): super().__init__(provider_id=provider_id, name=name) @@ -1068,7 +1054,7 @@ def _get_client(self): timeout = DEFAULT_HTTP_TIMEOUT http_client = create_openai_http_client( trust_env=trust_env, - verify=verify_ssl, + verify=httpx_verify(custom_settings, trust_env=trust_env), timeout=timeout, custom_settings=custom_settings, ) diff --git a/flocks/provider/sdk/openai_compatible.py b/flocks/provider/sdk/openai_compatible.py index 28a6d77ca..affb2bab2 100644 --- a/flocks/provider/sdk/openai_compatible.py +++ b/flocks/provider/sdk/openai_compatible.py @@ -41,6 +41,7 @@ resolve_openai_token_limit, resolve_verify_ssl, ) +from flocks.provider.tls import httpx_verify from flocks.utils.log import Log log = Log.create(service="provider.openai_compatible") @@ -49,6 +50,7 @@ class OpenAICompatibleProvider(BaseProvider): """OpenAI Compatible API provider""" + SUPPORTS_TLS_SETTINGS = True _MINIMAX_EMPTY_RESPONSE_RETRY_DELAY_SECONDS = 3 def __init__(self): @@ -112,7 +114,7 @@ def _get_client(self): trust_env = _coerce_bool(custom_settings.get("trust_env"), trust_env) http_client = create_openai_http_client( trust_env=trust_env, - verify=verify_ssl, + verify=httpx_verify(custom_settings, trust_env=trust_env), timeout=DEFAULT_HTTP_TIMEOUT, custom_settings=custom_settings, ) diff --git a/flocks/provider/sdk/openrouter.py b/flocks/provider/sdk/openrouter.py index 64a4e2599..ca058e939 100644 --- a/flocks/provider/sdk/openrouter.py +++ b/flocks/provider/sdk/openrouter.py @@ -5,13 +5,14 @@ Multi-model routing provider """ -from typing import List +from typing import Any, Dict, List from flocks.provider.provider import ( ModelInfo, ModelCapabilities, ) from flocks.provider.sdk.openai_base import OpenAIBaseProvider +from flocks.provider.tls import has_custom_tls, httpx_verify class OpenRouterProvider(OpenAIBaseProvider): @@ -42,6 +43,15 @@ def _get_client(self): else self._base_url ) + client_kwargs: Dict[str, Any] = {} + # verify_ssl / ca_cert from the provider options (SUPPORTS_TLS_SETTINGS + # is inherited); without them the SDK keeps its own default client. + settings = getattr(self._config, "custom_settings", None) or {} + if has_custom_tls(settings): + from openai import DefaultAsyncHttpxClient + + client_kwargs["http_client"] = DefaultAsyncHttpxClient(verify=httpx_verify(settings)) + self._client = AsyncOpenAI( api_key=api_key, base_url=base_url, @@ -49,6 +59,7 @@ def _get_client(self): "HTTP-Referer": "https://opencode.ai/", "X-Title": "opencode", }, + **client_kwargs, ) return self._client diff --git a/flocks/provider/tls.py b/flocks/provider/tls.py new file mode 100644 index 000000000..4b102b0eb --- /dev/null +++ b/flocks/provider/tls.py @@ -0,0 +1,274 @@ +""" +TLS settings of the HTTP clients that talk to LLM providers. + +A provider's options in flocks.json (``provider..options``) may hold: + +``verify_ssl`` (bool, default true; ``ssl_verify`` is the older spelling) + False turns off the certificate and host name checks for that provider. + It also lets the client speak the older handshakes internal gateways often + still do: RSA key exchange and CBC-SHA1 suites, TLS 1.0 and 1.1, servers + without secure renegotiation. The packaged Python (python-build-standalone) + keeps CPython's own TLS defaults, stricter than the RHEL system Python that + older installs ran on, so such a gateway would fail the handshake with the + checks off unless the handshake is relaxed too. + +``ca_cert`` (string) + A CA certificate in PEM, or the path of a PEM file or of a hashed + certificate directory on the server. It is trusted besides the default + bundle and the checks stay on. Not used while ``verify_ssl`` is false. + +``httpx_verify()`` turns them into the ``verify`` argument of an httpx client. +With neither set it returns ``True``, which leaves the client exactly as httpx +builds it on its own. +""" + +from __future__ import annotations + +import os +import ssl +from typing import Any, Iterable, Mapping, Optional, Union + +VERIFY_SSL_KEY = "verify_ssl" +LEGACY_VERIFY_SSL_KEY = "ssl_verify" +CA_CERT_KEY = "ca_cert" +TLS_OPTION_KEYS = (VERIFY_SSL_KEY, LEGACY_VERIFY_SSL_KEY, CA_CERT_KEY) + +# PEM text pasted into the settings; a bundle of a few hundred CAs fits. +MAX_CA_CERT_CHARS = 1024 * 1024 + +# OpenSSL's own default list at security level 0: RSA key exchange, CBC and +# SHA-1 suites, small keys and TLS 1.0 / 1.1 signatures are allowed again. +_COMPAT_CIPHERS = "DEFAULT:@SECLEVEL=0" + +TLS_CERTIFICATE_FAILED = "tls_certificate_failed" +TLS_HANDSHAKE_FAILED = "tls_handshake_failed" + + +class CACertError(ValueError): + """A ``ca_cert`` value that cannot be loaded; the message is shown to the user.""" + + +def coerce_bool(value: Any, default: bool) -> bool: + """Coerce loosely-typed config values to bool.""" + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + return bool(value) + if isinstance(value, str): + return value.strip().lower() in {"1", "true", "yes", "on"} + return default + + +def resolve_verify_ssl(settings: Any, default: bool = True) -> bool: + """Whether certificates are checked, from provider options (``verify_ssl`` or ``ssl_verify``).""" + if not isinstance(settings, Mapping): + return default + if VERIFY_SSL_KEY in settings: + return coerce_bool(settings.get(VERIFY_SSL_KEY), default) + if LEGACY_VERIFY_SSL_KEY in settings: + return coerce_bool(settings.get(LEGACY_VERIFY_SSL_KEY), default) + return default + + +def resolve_ca_cert(settings: Any) -> Optional[str]: + """The configured ``ca_cert`` (PEM text or a path), or ``None``.""" + if not isinstance(settings, Mapping): + return None + value = settings.get(CA_CERT_KEY) + if not isinstance(value, str): + return None + value = value.strip() + return value or None + + +def has_custom_tls(settings: Any) -> bool: + """Whether the options change anything from the default checks.""" + return not resolve_verify_ssl(settings) or resolve_ca_cert(settings) is not None + + +def is_pem_text(value: str) -> bool: + return "-----BEGIN" in value + + +def _default_verify_locations(trust_env: bool) -> dict: + """The trust httpx gives ``verify=True``: SSL_CERT_FILE / SSL_CERT_DIR, else certifi.""" + if trust_env and os.environ.get("SSL_CERT_FILE"): + return {"cafile": os.environ["SSL_CERT_FILE"]} + if trust_env and os.environ.get("SSL_CERT_DIR"): + return {"capath": os.environ["SSL_CERT_DIR"]} + import certifi + + return {"cafile": certifi.where()} + + +def _load_ca(context: ssl.SSLContext, ca_cert: str) -> None: + if "PRIVATE KEY-----" in ca_cert: + raise CACertError("CA 证书里只填证书(-----BEGIN CERTIFICATE-----),不要粘贴私钥。") + if is_pem_text(ca_cert): + if len(ca_cert) > MAX_CA_CERT_CHARS: + raise CACertError("CA 证书内容太长,请只保留需要信任的 CA 证书。") + try: + context.load_verify_locations(cadata=ca_cert) + except (ssl.SSLError, ValueError) as exc: + raise CACertError(f"CA 证书无法解析,请粘贴完整的 PEM 格式证书:{exc}") from exc + return + path = os.path.expanduser(ca_cert) + if not os.path.isabs(path): + raise CACertError("CA 证书路径要写服务器上的绝对路径,或者直接粘贴 PEM 格式的证书内容。") + try: + if os.path.isdir(path): + context.load_verify_locations(capath=path) + else: + context.load_verify_locations(cafile=path) + except FileNotFoundError as exc: + raise CACertError(f"找不到 CA 证书文件:{path}") from exc + except PermissionError as exc: + raise CACertError(f"没有权限读取 CA 证书文件:{path}") from exc + except (OSError, ssl.SSLError, ValueError) as exc: + raise CACertError(f"CA 证书文件无法加载:{path}({exc})") from exc + + +def validate_ca_cert(value: Optional[str]) -> Optional[str]: + """Check that *value* loads at least one certificate; returns it stripped, or ``None`` when empty.""" + if value is None: + return None + value = value.strip() + if not value: + return None + probe = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + _load_ca(probe, value) + # A hashed directory is read lazily, certificate by certificate, so its + # count says nothing until a handshake looks a certificate up. + is_directory = not is_pem_text(value) and os.path.isdir(os.path.expanduser(value)) + if not is_directory and not probe.cert_store_stats().get("x509"): + raise CACertError("CA 证书里没有找到证书,请粘贴 -----BEGIN CERTIFICATE----- 开头的完整内容。") + return value + + +def verifying_context(ca_cert: str, *, trust_env: bool = True) -> ssl.SSLContext: + """Default trust plus *ca_cert*; certificate and host name checks stay on.""" + context = ssl.create_default_context(**_default_verify_locations(trust_env)) + _load_ca(context, ca_cert) + # The pasted certificate may be an intermediate, or the gateway's own + # self-signed certificate: let a chain end at any certificate trusted here. + partial_chain = getattr(ssl, "VERIFY_X509_PARTIAL_CHAIN", 0) + if partial_chain: + context.verify_flags |= partial_chain + return context + + +def compat_context() -> ssl.SSLContext: + """No certificate checks, and the older handshakes accepted (see the module docstring).""" + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + try: + context.minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED + except (ValueError, ssl.SSLError): # pragma: no cover - build without the floor control + pass + try: + context.set_ciphers(_COMPAT_CIPHERS) + except ssl.SSLError: # pragma: no cover - OpenSSL without security levels + pass + context.options |= getattr(ssl, "OP_LEGACY_SERVER_CONNECT", 0) + return context + + +def httpx_verify(settings: Any, *, trust_env: bool = True) -> Union[bool, ssl.SSLContext]: + """The ``verify`` argument for an httpx client built from provider options. + + Raises :class:`CACertError` when ``ca_cert`` cannot be loaded, so a wrong + certificate fails loudly instead of quietly checking against the default + bundle only. + """ + if not resolve_verify_ssl(settings): + return compat_context() + ca_cert = resolve_ca_cert(settings) + if ca_cert is None: + return True + return verifying_context(ca_cert, trust_env=trust_env) + + +def _chain(exc: BaseException) -> Iterable[BaseException]: + seen = set() + current: Optional[BaseException] = exc + while current is not None and id(current) not in seen and len(seen) < 16: + seen.add(id(current)) + yield current + current = current.__cause__ or current.__context__ + + +_HANDSHAKE_MARKERS = ( + "HANDSHAKE_FAILURE", + "ALERT_PROTOCOL_VERSION", + "UNSUPPORTED_PROTOCOL", + "WRONG_VERSION_NUMBER", + "NO_PROTOCOLS_AVAILABLE", + "NO_CIPHERS_AVAILABLE", + "NO_SHARED_CIPHER", + "UNSAFE_LEGACY_RENEGOTIATION", + "DH_KEY_TOO_SMALL", + "EE_KEY_TOO_SMALL", + "CA_MD_TOO_WEAK", + "UNEXPECTED_EOF_WHILE_READING", +) + + +def classify_tls_error(exc: BaseException) -> Optional[str]: + """``tls_certificate_failed`` / ``tls_handshake_failed`` when TLS caused *exc*, else ``None``. + + Clients wrap the ``ssl`` error (httpcore -> httpx -> the provider SDK), so + the whole cause chain is read, and the message as well, since some + wrappers keep only the text. + """ + for error in _chain(exc): + if isinstance(error, CACertError): + return TLS_CERTIFICATE_FAILED + if isinstance(error, ssl.SSLCertVerificationError): + return TLS_CERTIFICATE_FAILED + text = str(error) + if "CERTIFICATE_VERIFY_FAILED" in text: + return TLS_CERTIFICATE_FAILED + if isinstance(error, ssl.SSLError) or any(marker in text for marker in _HANDSHAKE_MARKERS): + return TLS_HANDSHAKE_FAILED + return None + + +TLS_ERROR_HINTS = { + TLS_CERTIFICATE_FAILED: ( + "SSL 证书校验失败:网关用的是自签名或内部 CA 签发的证书。" + "可以在模型服务设置里填写 CA 证书,或关闭「校验 SSL 证书」。" + ), + TLS_HANDSHAKE_FAILED: ( + "TLS 握手失败:网关的 TLS 版本或加密套件较旧,或地址的 http/https 写错了。" + "确认地址无误后,可以在模型服务设置里关闭「校验 SSL 证书」,同时会兼容旧版 TLS。" + ), +} + + +def tls_error_hint(exc: BaseException) -> Optional[str]: + """A message telling the user what to change, when TLS caused *exc*.""" + code = classify_tls_error(exc) + return TLS_ERROR_HINTS.get(code) if code else None + + +__all__ = [ + "CA_CERT_KEY", + "CACertError", + "LEGACY_VERIFY_SSL_KEY", + "TLS_CERTIFICATE_FAILED", + "TLS_ERROR_HINTS", + "TLS_HANDSHAKE_FAILED", + "TLS_OPTION_KEYS", + "VERIFY_SSL_KEY", + "classify_tls_error", + "coerce_bool", + "compat_context", + "has_custom_tls", + "httpx_verify", + "resolve_ca_cert", + "resolve_verify_ssl", + "tls_error_hint", + "validate_ca_cert", + "verifying_context", +] diff --git a/flocks/server/routes/custom_provider.py b/flocks/server/routes/custom_provider.py index bb5bd7f22..452373b46 100644 --- a/flocks/server/routes/custom_provider.py +++ b/flocks/server/routes/custom_provider.py @@ -32,6 +32,7 @@ ProviderConfig, ) from flocks.provider.sdk.openai_compatible import OpenAICompatibleProvider +from flocks.provider.tls import CA_CERT_KEY, MAX_CA_CERT_CHARS, VERIFY_SSL_KEY, CACertError, validate_ca_cert from flocks.server.auth import require_admin from flocks.server.config_mutation import serialized_config_mutation from flocks.server.routes.provider import _get_inline_provider_api_key @@ -121,6 +122,9 @@ class CreateProviderReq(BaseModel): api_key: Optional[str] = Field(None) description: Optional[str] = Field(None) skip_catalog_bootstrap: bool = False + # TLS settings of the gateway (flocks.provider.tls). + verify_ssl: StrictBool = True + ca_cert: Optional[str] = Field(None, max_length=MAX_CA_CERT_CHARS) class ProviderResp(BaseModel): @@ -209,6 +213,15 @@ async def create_provider(body: CreateProviderReq, _admin: object = Depends(requ supplied_key = (body.api_key or "").strip() or None if supplied_key and not api_key_is_sendable(supplied_key): raise HTTPException(422, UNSENDABLE_API_KEY_MESSAGE) + tls_options: dict[str, Any] = {} + if not body.verify_ssl: + tls_options[VERIFY_SSL_KEY] = False + try: + ca_cert = validate_ca_cert(body.ca_cert) + except CACertError as exc: + raise HTTPException(422, str(exc)) from exc + if ca_cert: + tls_options[CA_CERT_KEY] = ca_cert # Check if already exists if ConfigWriter.get_provider_raw(pid) is not None: @@ -221,6 +234,7 @@ async def create_provider(body: CreateProviderReq, _admin: object = Depends(requ pid, npm="@ai-sdk/openai-compatible", base_url=base_url, + extra_options=tls_options or None, ) config_dict["name"] = body.name if body.description: @@ -242,7 +256,7 @@ async def create_provider(body: CreateProviderReq, _admin: object = Depends(requ log.warning("custom_provider.secret_save_failed", {"id": pid, "error": str(e)}) # Register in runtime - _register_provider(pid, body.name, base_url, supplied_key) + _register_provider(pid, body.name, base_url, supplied_key, custom_settings=tls_options) log.info("custom_provider.created", {"id": pid}) return ProviderResp( @@ -675,7 +689,12 @@ async def _resolve_model_limits( def _register_provider( - pid: str, name: str, base_url: str, api_key: Optional[str] = None + pid: str, + name: str, + base_url: str, + api_key: Optional[str] = None, + *, + custom_settings: Optional[dict[str, Any]] = None, ): """Register a custom provider in the runtime Provider registry.""" if Provider.get(pid): @@ -687,6 +706,7 @@ def _register_provider( provider_id=pid, api_key=api_key or "not-needed", base_url=base_url, + custom_settings=dict(custom_settings or {}), )) Provider.register(p) diff --git a/flocks/server/routes/model_discovery.py b/flocks/server/routes/model_discovery.py index 52ffd717c..6a67a113a 100644 --- a/flocks/server/routes/model_discovery.py +++ b/flocks/server/routes/model_discovery.py @@ -13,6 +13,7 @@ from flocks.provider.model_catalog import get_raw_catalog from flocks.provider.model_discovery import THREATBOOK_MODEL_LIST_PROVIDERS, discover_models, is_known_non_chat_model from flocks.provider.provider import Provider +from flocks.provider.tls import MAX_CA_CERT_CHARS from flocks.server.auth import require_admin from flocks.server.config_mutation import serialized_config_mutation from flocks.server.routes.provider import _ensure_provider_initialized, _load_dynamic_providers @@ -24,6 +25,21 @@ class DiscoverModelsRequest(BaseModel): model_config = ConfigDict(extra="forbid") api_key: str | None = Field(None, max_length=16384) base_url: str | None = Field(None, max_length=4096) + # TLS settings a form has not saved yet (flocks.provider.tls); unset ones + # keep the stored values. + verify_ssl: bool | None = None + ca_cert: str | None = Field(None, max_length=MAX_CA_CERT_CHARS) + + def tls_overrides(self) -> dict | None: + """The TLS settings this request names, to put in place of the stored ones.""" + if self.verify_ssl is None and self.ca_cert is None: + return None + overrides: dict = {} + if self.verify_ssl is not None: + overrides["verify_ssl"] = self.verify_ssl + if self.ca_cert is not None: + overrides["ca_cert"] = self.ca_cert + return overrides ModelIdentifier = Annotated[str, StringConstraints(min_length=1, max_length=512)] @@ -83,7 +99,9 @@ async def discover_provider_models( ): raise HTTPException(404, "Provider not found") body = body or DiscoverModelsRequest() - return await discover_models(provider_id, api_key=body.api_key, base_url=body.base_url) + return await discover_models( + provider_id, api_key=body.api_key, base_url=body.base_url, tls_overrides=body.tls_overrides() + ) @router.post("/{provider_id}/import-models") @@ -245,7 +263,8 @@ async def check_provider_key(provider_id: str, body: DiscoverModelsRequest, _adm await _ensure_provider_initialized() if provider_id not in get_raw_catalog() and ConfigWriter.get_provider_raw(provider_id) is None and provider_id not in Provider._providers: raise HTTPException(404, "Provider not found") - result = await discover_models(provider_id, api_key=body.api_key, base_url=body.base_url) + tls_overrides = body.tls_overrides() + result = await discover_models(provider_id, api_key=body.api_key, base_url=body.base_url, tls_overrides=tls_overrides) if result["source"] != "api" or result["status"] != "success": return {"status": "invalid" if result["code"] in {"authentication_failed", "missing_credentials"} else "unverified", "code": result["code"]} # ThreatBook uses a successful live model-list response as its validation @@ -255,6 +274,11 @@ async def check_provider_key(provider_id: str, body: DiscoverModelsRequest, _adm # A public models endpoint does not prove that a key is valid. Require # rejection of an unrelated credential before reporting authentication. import secrets - control = await discover_models(provider_id, api_key="flocks-probe-" + secrets.token_urlsafe(24), base_url=body.base_url) + control = await discover_models( + provider_id, + api_key="flocks-probe-" + secrets.token_urlsafe(24), # secret-guard: allow (random probe key, not a credential) + base_url=body.base_url, + tls_overrides=tls_overrides, + ) verified = control["code"] in {"authentication_failed", "permission_denied"} return {"status": "valid" if verified else "unverified", "code": "key_valid" if verified else "key_check_unsupported"} diff --git a/flocks/server/routes/provider.py b/flocks/server/routes/provider.py index 5a50bcf77..f2b6afb25 100644 --- a/flocks/server/routes/provider.py +++ b/flocks/server/routes/provider.py @@ -30,6 +30,17 @@ is_unsendable_header_error, ) from flocks.provider.provider import BaseProvider, Provider, ModelInfo as ProviderModelInfo +from flocks.provider.tls import ( + CA_CERT_KEY, + LEGACY_VERIFY_SSL_KEY, + MAX_CA_CERT_CHARS, + VERIFY_SSL_KEY, + CACertError, + classify_tls_error, + resolve_verify_ssl, + tls_error_hint, + validate_ca_cert, +) from flocks.security.secrets import SecretManager from flocks.server.auth import get_request_ip, get_request_user_agent, require_admin, require_user from flocks.server.config_mutation import serialized_config_mutation @@ -806,6 +817,8 @@ async def get_provider_catalog(): # Propagate allow_multiple flag (only openai-compatible has it) if raw.get("allow_multiple"): provider_data["allow_multiple"] = True + # Whether the add dialog offers the SSL certificate settings. + provider_data["tls_configurable"] = _provider_tls_configurable(provider_id, raw.get("npm")) providers.append(provider_data) @@ -1861,6 +1874,18 @@ class ProviderCredentialRequest(BaseModel): fields: Optional[Dict[str, Optional[str]]] = Field(None, description="Dynamic service credential fields") provider_name: Optional[str] = Field(None, description="Display name for the provider") skip_catalog_bootstrap: bool = Field(False, description="Keep the model inventory explicitly managed instead of adding catalog defaults") + verify_ssl: Optional[bool] = Field( + None, + description=( + "LLM providers: check the server certificate (default). False turns the checks off " + "and accepts older TLS handshakes; omitted leaves the setting unchanged." + ), + ) + ca_cert: Optional[str] = Field( + None, + max_length=MAX_CA_CERT_CHARS, + description="LLM providers: CA certificate in PEM, or its absolute path on the server; empty removes it, omitted leaves it unchanged.", + ) class ProviderCredentialResponse(BaseModel): @@ -1875,6 +1900,11 @@ class ProviderCredentialResponse(BaseModel): fields: Optional[Dict[str, Optional[str]]] = None secret_ids: Optional[Dict[str, str]] = None has_credential: bool + # LLM providers only: the TLS settings (flocks.provider.tls) and whether + # this provider's client follows them. + verify_ssl: Optional[bool] = None + ca_cert: Optional[str] = None + tls_configurable: bool = False def _load_llm_provider_credentials( @@ -1895,15 +1925,18 @@ def _load_llm_provider_credentials( api_key = _get_inline_provider_api_key(provider_id) base_url = None + options: Dict[str, Any] = {} raw_provider = ConfigWriter.get_provider_raw(provider_id) if raw_provider: - options = raw_provider.get("options", {}) + raw_options = raw_provider.get("options") + options = raw_options if isinstance(raw_options, dict) else {} base_url = options.get("baseURL") or options.get("base_url") if not base_url: base_url = secrets.get(f"{provider_id}_base_url") is_placeholder = _is_placeholder_api_key(api_key) ui_api_key = None if is_placeholder else api_key + ca_cert = options.get(CA_CERT_KEY) return ProviderCredentialResponse( secret_id=secret_id if api_key else None, @@ -1911,9 +1944,69 @@ def _load_llm_provider_credentials( api_key_masked=SecretManager.mask(ui_api_key) if ui_api_key else None, base_url=base_url, has_credential=bool(api_key), + verify_ssl=resolve_verify_ssl(options), + ca_cert=(ca_cert.strip() or None) if isinstance(ca_cert, str) else None, + tls_configurable=_provider_tls_configurable(provider_id, (raw_provider or {}).get("npm")), ) +# npm packages whose providers are built on a client that follows the TLS +# settings (flocks.provider.tls), for providers not registered yet. +_TLS_CONFIGURABLE_NPMS = frozenset({ + "@ai-sdk/openai-compatible", + "@ai-sdk/cherry", + "@ai-sdk/openai", + "@ai-sdk/anthropic", + "@ai-sdk/azure", +}) + + +def _provider_tls_configurable(provider_id: str, npm: Optional[str] = None) -> bool: + """Whether ``verify_ssl`` / ``ca_cert`` reach this provider's HTTP client.""" + provider = Provider._providers.get(provider_id) + if provider is not None: + return bool(getattr(provider, "SUPPORTS_TLS_SETTINGS", False)) + if npm is None: + try: + from flocks.provider.model_catalog import get_raw_catalog + + npm = (get_raw_catalog().get(provider_id) or {}).get("npm") + except Exception: + npm = None + return npm in _TLS_CONFIGURABLE_NPMS + + +def _requested_tls_options(request: "ProviderCredentialRequest") -> Optional[Dict[str, Any]]: + """The TLS options a credentials request sets, checked; ``None`` when it sets none. + + ``verify_ssl`` true and an empty ``ca_cert`` remove the keys, so a provider + left at the defaults keeps no TLS options at all. + """ + if request.verify_ssl is None and request.ca_cert is None: + return None + updates: Dict[str, Any] = {} + if request.verify_ssl is not None: + updates[VERIFY_SSL_KEY] = None if request.verify_ssl else False + if request.ca_cert is not None: + try: + updates[CA_CERT_KEY] = validate_ca_cert(request.ca_cert) + except CACertError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + return updates + + +def _merge_tls_options(options: Dict[str, Any], updates: Dict[str, Any]) -> Dict[str, Any]: + merged = dict(options) + if VERIFY_SSL_KEY in updates: + merged.pop(LEGACY_VERIFY_SSL_KEY, None) + for key, value in updates.items(): + if value is None: + merged.pop(key, None) + else: + merged[key] = value + return merged + + @router.get( "/{provider_id}/credentials", response_model=ProviderCredentialResponse, @@ -2020,6 +2113,12 @@ async def set_provider_credentials( # Unknown id and nothing to update: refuse before touching # .secret.json / flocks.json so no bogus provider is persisted. raise HTTPException(status_code=404, detail=f"Unknown provider: {provider_id}") + tls_updates = _requested_tls_options(request) + if tls_updates is not None: + await _ensure_provider_initialized() + raw_for_npm = ConfigWriter.get_provider_raw(provider_id) or {} + if not _provider_tls_configurable(provider_id, raw_for_npm.get("npm")): + raise HTTPException(status_code=400, detail="该模型服务不支持 SSL 证书设置。") secrets = get_secret_manager() secret_id = request.secret_id or f"{provider_id}_llm_key" effective_api_key = (request.api_key or "").strip() @@ -2117,6 +2216,14 @@ async def set_provider_credentials( ) if request.skip_catalog_bootstrap: ConfigWriter.update_provider_field(provider_id, "model_sync", "manual") + if tls_updates is not None: + current = ConfigWriter.get_provider_raw(provider_id) or {} + current_options = current.get("options") + ConfigWriter.update_provider_field( + provider_id, + "options", + _merge_tls_options(current_options if isinstance(current_options, dict) else {}, tls_updates), + ) else: # Provider not yet in flocks.json — create a minimal entry, but only # for ids the system actually knows (catalog / registered SDK @@ -2171,6 +2278,8 @@ async def set_provider_credentials( config_dict["model_sync"] = "manual" if request.provider_name: config_dict["name"] = request.provider_name + if tls_updates is not None: + config_dict["options"] = _merge_tls_options(config_dict.get("options") or {}, tls_updates) ConfigWriter.add_provider(provider_id, config_dict) # Config.get() caches resolved secret values. Invalidate it after @@ -2190,6 +2299,8 @@ async def set_provider_credentials( effective_base_url = raw.get("options", {}).get("baseURL") custom_settings = _get_provider_custom_settings(provider) + if tls_updates is not None: + custom_settings = _merge_tls_options(custom_settings, tls_updates) provider.configure(ProviderConfig( provider_id=provider_id, api_key=effective_api_key, @@ -2730,6 +2841,9 @@ def _credential_test_error_code(error: Exception) -> str: return "authentication_failed" if isinstance(error, (APITimeoutError, httpx.TimeoutException, TimeoutError)): return "connection_timeout" + tls_code = classify_tls_error(error) + if tls_code: + return tls_code if isinstance(error, (APIConnectionError, httpx.TransportError)): return "connection_error" status_code = getattr(error, "status_code", None) @@ -2785,9 +2899,26 @@ def _without_credential(text: str, api_key: Optional[str]) -> str: def _credential_test_error_text(error: Exception, api_key: Optional[str]) -> str: if is_unsendable_header_error(error): return UNSENDABLE_HEADER_MESSAGE + hint = tls_error_hint(error) + if hint: + # The SDK says only "Connection error."; name the TLS cause and what to change. + return _without_credential(f"{hint}({_tls_root_text(error)})", api_key) return _without_credential(str(error), api_key) +def _tls_root_text(error: BaseException) -> str: + """The innermost message of *error*'s cause chain, e.g. the OpenSSL reason.""" + seen = set() + current: Optional[BaseException] = error + text = str(error) + while current is not None and id(current) not in seen and len(seen) < 16: + seen.add(id(current)) + if str(current): + text = str(current) + current = current.__cause__ or current.__context__ + return text[:300] + + async def _test_provider_credentials_impl( provider_id: str, body: Optional[TestCredentialRequest] = None, diff --git a/tests/provider/test_model_discovery.py b/tests/provider/test_model_discovery.py index 0df5842c1..b958b942e 100644 --- a/tests/provider/test_model_discovery.py +++ b/tests/provider/test_model_discovery.py @@ -14,6 +14,7 @@ from flocks.config.config import Config, ConfigInfo from flocks.config.config_writer import ConfigWriter from flocks.provider.provider import Provider +from tests.provider.tls_helpers import describe_verify, make_ca @pytest.fixture @@ -127,8 +128,8 @@ async def test_id_only_lists_block_known_non_chat_families_without_blocking_audi ("options", "trust_env_var", "expected"), [ ({}, None, {"verify": True, "trust_env": True}), - ({"verify_ssl": False}, None, {"verify": False, "trust_env": True}), - ({"ssl_verify": "false"}, None, {"verify": False, "trust_env": True}), + ({"verify_ssl": False}, None, {"verify": "no-verify", "trust_env": True}), + ({"ssl_verify": "false"}, None, {"verify": "no-verify", "trust_env": True}), ({"trust_env": False}, None, {"verify": True, "trust_env": False}), ({}, "0", {"verify": True, "trust_env": False}), ({"trust_env": True}, "0", {"verify": True, "trust_env": True}), @@ -149,7 +150,91 @@ async def test_discovery_connects_the_way_the_providers_own_client_does( result = await discovery_runtime.module.discover_models("openai-compatible", api_key="key") assert result["status"] == "success" - assert {name: upstream.options[0][name] for name in expected} == expected + assert {name: describe_verify(upstream.options[0][name]) if name == "verify" else upstream.options[0][name] for name in expected} == expected + + +@pytest.mark.asyncio +async def test_unsaved_tls_settings_replace_the_stored_ones(discovery_runtime, upstream): + """A form checks a gateway with SSL settings it has not saved yet.""" + save_provider( + discovery_runtime, "openai-compatible", options={"baseURL": "https://gateway.test/v1", "ssl_verify": False} + ) + + result = await discovery_runtime.module.discover_models("openai-compatible", api_key="key") + assert result["status"] == "success" + assert describe_verify(upstream.options[-1]["verify"]) == "no-verify" + + result = await discovery_runtime.module.discover_models( + "openai-compatible", api_key="key", tls_overrides={"verify_ssl": True} + ) + assert result["status"] == "success" + assert upstream.options[-1]["verify"] is True + + result = await discovery_runtime.module.discover_models( + "openai-compatible", api_key="key", base_url="https://other.test/v1", tls_overrides={"verify_ssl": False} + ) + assert result["status"] == "success" + assert describe_verify(upstream.options[-1]["verify"]) == "no-verify" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("switch_key", ["verify_ssl", "ssl_verify"]) +async def test_sending_only_the_switch_keeps_the_stored_ca_cert(switch_key, discovery_runtime, upstream): + """The edit form sends only what changed: turning the checks back on must not drop the saved CA.""" + import ssl + + import certifi + + ca = make_ca() + save_provider( + discovery_runtime, + "openai-compatible", + options={"baseURL": "https://gateway.test/v1", switch_key: False, "ca_cert": ca.cert_pem}, + ) + + result = await discovery_runtime.module.discover_models( + "openai-compatible", api_key="key", tls_overrides={"verify_ssl": True} + ) + + assert result["status"] == "success" + verify = upstream.options[-1]["verify"] + assert isinstance(verify, ssl.SSLContext) and verify.verify_mode == ssl.CERT_REQUIRED + default_cas = ssl.create_default_context(cafile=certifi.where()).cert_store_stats()["x509_ca"] + assert verify.cert_store_stats()["x509_ca"] == default_cas + 1 + + +@pytest.mark.asyncio +async def test_a_ca_cert_that_does_not_load_is_reported_without_a_request(discovery_runtime, upstream): + save_provider(discovery_runtime, "openai-compatible", options={"baseURL": "https://gateway.test/v1"}) + + result = await discovery_runtime.module.discover_models( + "openai-compatible", api_key="key", tls_overrides={"ca_cert": "relative/ca.pem"} + ) + + assert (result["status"], result["code"]) == ("error", "invalid_ca_cert") + assert "绝对路径" in result["message"] + assert upstream.requests == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("message", "code"), + [ + ("[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate", "tls_certificate_failed"), + ("[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] ssl/tls alert handshake failure", "tls_handshake_failed"), + ("[Errno 61] Connection refused", "connection_error"), + ], +) +async def test_tls_failures_are_told_apart_from_other_connection_errors(message, code, discovery_runtime, upstream): + save_provider(discovery_runtime, "openai-compatible", options={"baseURL": "https://gateway.test/v1"}) + + def fail(request): + raise httpx.ConnectError(message, request=request) + + upstream.handler = fail + result = await discovery_runtime.module.discover_models("openai-compatible", api_key="key") + + assert (result["status"], result["code"]) == ("error", code) @pytest.mark.asyncio diff --git a/tests/provider/test_openai_base_provider.py b/tests/provider/test_openai_base_provider.py index afda5c443..6d0cb2814 100644 --- a/tests/provider/test_openai_base_provider.py +++ b/tests/provider/test_openai_base_provider.py @@ -13,6 +13,8 @@ import httpx import pytest + +from tests.provider.tls_helpers import assert_no_verify_context from openai import AsyncOpenAI import flocks.provider.sdk.openai_base as openai_base_module @@ -501,7 +503,7 @@ def test_get_client_respects_verify_ssl_false(self, mock_async_openai, mock_http # See ``OpenAIBaseProvider._get_client``. assert mock_http_client.call_count == 1 kwargs = mock_http_client.call_args.kwargs - assert kwargs["verify"] is False + assert_no_verify_context(kwargs["verify"]) assert kwargs["trust_env"] is True timeout_arg = kwargs["timeout"] # Either an httpx.Timeout instance or compatible object: assert the diff --git a/tests/provider/test_openai_compatible_provider.py b/tests/provider/test_openai_compatible_provider.py index 1ef5b20cb..70ad6ab73 100644 --- a/tests/provider/test_openai_compatible_provider.py +++ b/tests/provider/test_openai_compatible_provider.py @@ -3,6 +3,8 @@ import pytest +from tests.provider.tls_helpers import assert_no_verify_context + from flocks.provider.provider import ChatMessage, ChatResponse from flocks.provider.provider import ProviderConfig from flocks.provider.sdk.openai_compatible import OpenAICompatibleProvider @@ -52,7 +54,7 @@ def test_get_client_respects_verify_ssl_false(self, mock_async_openai, mock_http # so minor adjustments to non-critical values don't break the test. assert mock_http_client.call_count == 1 kwargs = mock_http_client.call_args.kwargs - assert kwargs["verify"] is False + assert_no_verify_context(kwargs["verify"]) assert kwargs["trust_env"] is True timeout_arg = kwargs["timeout"] assert getattr(timeout_arg, "connect", None) == 30.0 diff --git a/tests/provider/test_openai_provider.py b/tests/provider/test_openai_provider.py index bc671640b..af32e5c9c 100644 --- a/tests/provider/test_openai_provider.py +++ b/tests/provider/test_openai_provider.py @@ -3,6 +3,8 @@ import pytest +from tests.provider.tls_helpers import assert_no_verify_context + from flocks.provider.provider import ChatMessage, ProviderConfig from flocks.provider.sdk.openai import OpenAIProvider @@ -37,7 +39,7 @@ def test_get_client_respects_verify_ssl_false(self, mock_async_openai, mock_http assert mock_http_client.call_count == 1 kwargs = mock_http_client.call_args.kwargs assert kwargs["trust_env"] is True - assert kwargs["verify"] is False + assert_no_verify_context(kwargs["verify"]) timeout_arg = kwargs["timeout"] assert getattr(timeout_arg, "connect", None) == 30.0 assert getattr(timeout_arg, "read", None) == 180.0 diff --git a/tests/provider/test_provider_tls.py b/tests/provider/test_provider_tls.py new file mode 100644 index 000000000..0d3f844f4 --- /dev/null +++ b/tests/provider/test_provider_tls.py @@ -0,0 +1,488 @@ +"""SSL settings of LLM provider clients: ``verify_ssl`` and ``ca_cert`` (flocks.provider.tls). + +The handshake tests run real TLS against a gateway on 127.0.0.1 whose +certificate is made for the test: self-signed, issued by an internal CA, or +offered over RSA key exchange only, as older appliances do. +""" + +from __future__ import annotations + +import json +import ssl +from unittest.mock import MagicMock + +import certifi +import httpx +import pytest + +from flocks.config.config_writer import ConfigWriter +from flocks.provider import tls +from flocks.provider.provider import ChatMessage, Provider, ProviderConfig +from flocks.provider.sdk.anthropic import AnthropicProvider +from flocks.provider.sdk.azure import AzureProvider +from flocks.provider.sdk.openai import OpenAIProvider +from flocks.provider.sdk.openai_compatible import OpenAICompatibleProvider +from tests.provider.tls_helpers import ( + RSA_KEY_EXCHANGE_ONLY, + assert_no_verify_context, + https_gateway, + make_ca, + make_server, +) + + +@pytest.fixture(scope="module") +def internal_ca(): + return make_ca() + + +# --------------------------------------------------------------------------- +# Settings -> httpx ``verify`` +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("settings", [None, {}, {"verify_ssl": True}, {"verify_ssl": True, "ca_cert": " "}]) +def test_without_settings_httpx_keeps_its_own_checks(settings): + assert tls.httpx_verify(settings) is True + assert tls.has_custom_tls(settings) is False + + +@pytest.mark.parametrize( + "settings", + [ + {"verify_ssl": False}, + {"verify_ssl": "false"}, + {"ssl_verify": 0}, + # The certificate is not used while the checks are off. + {"verify_ssl": False, "ca_cert": "relative/path.pem"}, + ], +) +def test_checks_off_also_accepts_older_handshakes(settings): + context = tls.httpx_verify(settings) + + assert_no_verify_context(context) + assert context.minimum_version == ssl.TLSVersion.MINIMUM_SUPPORTED + assert context.options & ssl.OP_LEGACY_SERVER_CONNECT + cipher_names = {cipher["name"] for cipher in context.get_ciphers()} + assert "AES128-GCM-SHA256" in cipher_names # RSA key exchange, left out by CPython's default list + assert tls.has_custom_tls(settings) is True + + +def test_checks_off_builds_no_deprecated_protocol_setting(): + import warnings + + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + tls.compat_context() + + +def test_ca_cert_is_trusted_besides_the_default_bundle(internal_ca): + context = tls.httpx_verify({"ca_cert": internal_ca.cert_pem}) + + assert context.verify_mode == ssl.CERT_REQUIRED + assert context.check_hostname is True + default_cas = ssl.create_default_context(cafile=certifi.where()).cert_store_stats()["x509_ca"] + assert context.cert_store_stats()["x509_ca"] == default_cas + 1 + assert context.verify_flags & ssl.VERIFY_X509_PARTIAL_CHAIN + + +def test_ca_cert_path_and_ssl_cert_file_are_both_trusted(internal_ca, tmp_path, monkeypatch): + other_ca = make_ca() + bundle = tmp_path / "system-bundle.pem" + bundle.write_text(other_ca.cert_pem) + ca_file = tmp_path / "corp-ca.pem" + ca_file.write_text(internal_ca.cert_pem) + monkeypatch.setenv("SSL_CERT_FILE", str(bundle)) + monkeypatch.delenv("SSL_CERT_DIR", raising=False) + + context = tls.httpx_verify({"ca_cert": str(ca_file)}) + assert context.cert_store_stats()["x509_ca"] == 2 + + # trust_env off: certifi, as httpx itself does. + context = tls.httpx_verify({"ca_cert": str(ca_file)}, trust_env=False) + default_cas = ssl.create_default_context(cafile=certifi.where()).cert_store_stats()["x509_ca"] + assert context.cert_store_stats()["x509_ca"] == default_cas + 1 + + +@pytest.mark.parametrize( + ("value", "message"), + [ + ("certs/corp-ca.pem", "绝对路径"), + ("/nonexistent/flocks-test/corp-ca.pem", "找不到 CA 证书文件"), + ("-----BEGIN CERTIFICATE-----\nnot base64\n-----END CERTIFICATE-----\n", "无法解析"), + ("-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n", "不要粘贴私钥"), # secret-guard: allow (test value) + ], +) +def test_a_ca_cert_that_does_not_load_is_refused(value, message): + with pytest.raises(tls.CACertError, match=message): + tls.validate_ca_cert(value) + with pytest.raises(tls.CACertError): + tls.httpx_verify({"ca_cert": value}) + + +def test_a_file_without_certificates_is_refused(tmp_path): + empty = tmp_path / "empty.pem" + empty.write_text("# nothing here\n") + with pytest.raises(tls.CACertError): + tls.validate_ca_cert(str(empty)) + + +def test_validate_ca_cert_keeps_good_values(internal_ca, tmp_path): + ca_file = tmp_path / "ca.pem" + ca_file.write_text(internal_ca.cert_pem) + assert tls.validate_ca_cert(None) is None + assert tls.validate_ca_cert(" \n") is None + assert tls.validate_ca_cert("\n" + internal_ca.cert_pem) == internal_ca.cert_pem.strip() + assert tls.validate_ca_cert(f" {ca_file} ") == str(ca_file) + assert tls.validate_ca_cert(str(tmp_path)) == str(tmp_path) # hashed directory, read lazily + + +def test_tls_errors_are_recognised_through_the_wrappers(): + cert_error = ssl.SSLCertVerificationError(1, "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed") + wrapped = httpx.ConnectError("[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed") + wrapped.__cause__ = cert_error + outer = RuntimeError("Connection error.") + outer.__cause__ = wrapped + assert tls.classify_tls_error(outer) == tls.TLS_CERTIFICATE_FAILED + + handshake = httpx.ConnectError("[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] ssl/tls alert handshake failure") + assert tls.classify_tls_error(handshake) == tls.TLS_HANDSHAKE_FAILED + assert "TLS 握手失败" in tls.tls_error_hint(handshake) + + assert tls.classify_tls_error(httpx.ConnectError("[Errno 61] Connection refused")) is None + assert tls.tls_error_hint(ValueError("x")) is None + + +# --------------------------------------------------------------------------- +# Real handshakes through the provider clients +# --------------------------------------------------------------------------- + + +def _provider(cls, base_url: str, settings: dict): + provider = cls() + provider.configure( + ProviderConfig(provider_id=provider.id, api_key="sk-test", base_url=base_url, custom_settings=settings) # secret-guard: allow (test value) + ) + return provider + + +async def _ask(provider, *, stream: bool) -> str: + messages = [ChatMessage(role="user", content="capital of France?")] + if stream: + parts = [] + async for chunk in provider.chat_stream("gw-test-model", messages, max_tokens=10): + if getattr(chunk, "delta", None): + parts.append(chunk.delta) + return "".join(parts) + response = await provider.chat("gw-test-model", messages, max_tokens=10) + return response.content + + +PROVIDERS = [OpenAICompatibleProvider, OpenAIProvider] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("provider_cls", PROVIDERS) +@pytest.mark.parametrize("stream", [False, True]) +async def test_checks_off_reach_a_gateway_that_offers_rsa_key_exchange_only(provider_cls, stream, tmp_path): + with https_gateway( + make_server(), tmp_path, ciphers=RSA_KEY_EXCHANGE_ONLY, maximum_version=ssl.TLSVersion.TLSv1_2 + ) as base_url: + with pytest.raises(Exception) as caught: + await _ask(_provider(provider_cls, base_url, {}), stream=stream) + assert tls.classify_tls_error(caught.value) == tls.TLS_HANDSHAKE_FAILED + + assert await _ask(_provider(provider_cls, base_url, {"verify_ssl": False}), stream=stream) == "Paris" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("provider_cls", PROVIDERS) +@pytest.mark.parametrize("stream", [False, True]) +async def test_internal_ca_gateway_needs_the_ca_or_checks_off(provider_cls, stream, internal_ca, tmp_path): + ca_file = tmp_path / "corp-ca.pem" + ca_file.write_text(internal_ca.cert_pem) + with https_gateway(make_server(internal_ca), tmp_path) as base_url: + with pytest.raises(Exception) as caught: + await _ask(_provider(provider_cls, base_url, {}), stream=stream) + assert tls.classify_tls_error(caught.value) == tls.TLS_CERTIFICATE_FAILED + + for settings in ({"ca_cert": internal_ca.cert_pem}, {"ca_cert": str(ca_file)}, {"verify_ssl": False}): + assert await _ask(_provider(provider_cls, base_url, settings), stream=stream) == "Paris" + + # Another CA does not make the gateway trusted. + with pytest.raises(Exception) as caught: + await _ask(_provider(provider_cls, base_url, {"ca_cert": make_ca().cert_pem}), stream=stream) + assert tls.classify_tls_error(caught.value) == tls.TLS_CERTIFICATE_FAILED + + +@pytest.mark.asyncio +async def test_a_self_signed_gateway_certificate_can_be_trusted_as_is(tmp_path): + gateway = make_server() + with https_gateway(gateway, tmp_path) as base_url: + provider = _provider(OpenAICompatibleProvider, base_url, {"ca_cert": gateway.cert_pem}) + assert await _ask(provider, stream=False) == "Paris" + + +# --------------------------------------------------------------------------- +# Clients built by the provider SDKs +# --------------------------------------------------------------------------- + + +def _ssl_context(httpx_client) -> ssl.SSLContext: + return httpx_client._transport._pool._ssl_context + + +@pytest.mark.parametrize( + ("factory", "settings_key"), + [ + (lambda settings: _provider(AnthropicProvider, "https://gateway.internal", settings), "anthropic"), + ( + lambda settings: _provider(AzureProvider, "https://gateway.internal/", {**settings, "api_version": "2025-04-01-preview"}), + "azure", + ), + ], +) +def test_anthropic_and_azure_clients_follow_the_settings(factory, settings_key, internal_ca): + relaxed = factory({"verify_ssl": False})._get_client() + assert_no_verify_context(_ssl_context(relaxed._client)) + + with_ca = factory({"ca_cert": internal_ca.cert_pem})._get_client() + context = _ssl_context(with_ca._client) + assert context.verify_mode == ssl.CERT_REQUIRED + default_cas = ssl.create_default_context(cafile=certifi.where()).cert_store_stats()["x509_ca"] + assert context.cert_store_stats()["x509_ca"] == default_cas + 1 + + default = factory({})._get_client() + assert _ssl_context(default._client).verify_mode == ssl.CERT_REQUIRED + + +def _tls_provider_classes(): + """Every SDK provider class that says its client follows the settings.""" + import importlib + import inspect + import pkgutil + + import flocks.provider.sdk as sdk + from flocks.provider.provider import BaseProvider + + found = {} + for info in pkgutil.iter_modules(sdk.__path__): + module = importlib.import_module(f"flocks.provider.sdk.{info.name}") + for _, cls in inspect.getmembers(module, inspect.isclass): + if issubclass(cls, BaseProvider) and cls.__module__ == module.__name__ and cls.SUPPORTS_TLS_SETTINGS: + found[cls.__qualname__] = cls + return sorted(found.items()) + + +TLS_PROVIDER_CLASSES = _tls_provider_classes() + + +@pytest.mark.parametrize(("name", "cls"), TLS_PROVIDER_CLASSES, ids=[name for name, _ in TLS_PROVIDER_CLASSES]) +def test_every_provider_offering_the_settings_applies_them(name, cls, internal_ca): + """A subclass that builds its own client must not drop the settings it claims to follow.""" + try: + cls() + except TypeError: + pytest.skip("base class: needs constructor arguments") + + def client_for(settings): + provider = cls() + provider.configure( + ProviderConfig( + provider_id=provider.id, + api_key="sk-test", # secret-guard: allow (test value) + base_url="https://gateway.internal/v1", + custom_settings={**settings, "api_version": "2025-04-01-preview"}, + ) + ) + return provider._get_client()._client + + assert_no_verify_context(_ssl_context(client_for({"verify_ssl": False}))) + with_ca = _ssl_context(client_for({"ca_cert": internal_ca.cert_pem})) + default_cas = ssl.create_default_context(cafile=certifi.where()).cert_store_stats()["x509_ca"] + assert with_ca.verify_mode == ssl.CERT_REQUIRED + assert with_ca.cert_store_stats()["x509_ca"] == default_cas + 1 + assert _ssl_context(client_for({})).verify_mode == ssl.CERT_REQUIRED + + +def test_providers_that_offer_the_settings(): + for cls in (OpenAICompatibleProvider, OpenAIProvider, AnthropicProvider, AzureProvider): + assert cls.SUPPORTS_TLS_SETTINGS is True + from flocks.provider.sdk.deepseek import DeepSeekProvider + from flocks.provider.sdk.google import GoogleProvider + from flocks.provider.sdk.xai import XAIProvider + + assert DeepSeekProvider.SUPPORTS_TLS_SETTINGS is True # OpenAIBaseProvider + assert GoogleProvider.SUPPORTS_TLS_SETTINGS is False + assert XAIProvider.SUPPORTS_TLS_SETTINGS is False + + +# --------------------------------------------------------------------------- +# Settings saved and read through the provider routes +# --------------------------------------------------------------------------- + + +@pytest.fixture +def saved_config(tmp_path, monkeypatch): + """A flocks.json in a temporary directory, an empty registry, in-memory secrets.""" + config_file = tmp_path / "flocks.json" + config_file.write_text("{}", encoding="utf-8") + monkeypatch.setattr(ConfigWriter, "_get_config_path", lambda: config_file) + monkeypatch.setattr(Provider, "_providers", {}) + monkeypatch.setattr(Provider, "_models", {}) + monkeypatch.setattr(Provider, "_initialized", True) + store: dict = {} + secrets = MagicMock() + secrets.get.side_effect = store.get + secrets.set.side_effect = store.__setitem__ + monkeypatch.setattr("flocks.security.get_secret_manager", lambda: secrets) + from flocks.server.routes import provider as provider_routes + + monkeypatch.setattr(provider_routes.Config, "clear_cache", MagicMock()) + + def write(providers: dict) -> None: + config_file.write_text(json.dumps({"provider": providers}), encoding="utf-8") + + def read(provider_id: str) -> dict: + return json.loads(config_file.read_text(encoding="utf-8"))["provider"][provider_id] + + return MagicMock(write=write, read=read, secrets=store) + + +@pytest.mark.asyncio +async def test_credentials_save_and_read_the_tls_settings(saved_config, internal_ca): + from flocks.server.routes import provider as provider_routes + + saved_config.write({ + "custom-gw": { + "npm": "@ai-sdk/openai-compatible", + "name": "Gateway", + "options": {"apiKey": "{secret:custom-gw_llm_key}", "baseURL": "https://gw.internal/v1", "ssl_verify": True}, + "models": {}, + } + }) + saved_config.secrets["custom-gw_llm_key"] = "sk-test" + + before = provider_routes._load_llm_provider_credentials("custom-gw") + assert (before.verify_ssl, before.ca_cert, before.tls_configurable) == (True, None, True) + + await provider_routes.set_provider_credentials( + "custom-gw", provider_routes.ProviderCredentialRequest(verify_ssl=False, ca_cert=internal_ca.cert_pem) + ) + options = saved_config.read("custom-gw")["options"] + assert options["verify_ssl"] is False + assert "ssl_verify" not in options # the older spelling would contradict the new value + assert options["ca_cert"] == internal_ca.cert_pem.strip() + assert options["baseURL"] == "https://gw.internal/v1" + after = provider_routes._load_llm_provider_credentials("custom-gw") + assert (after.verify_ssl, after.ca_cert) == (False, internal_ca.cert_pem.strip()) + + # Back to the defaults: no TLS keys are left behind. + await provider_routes.set_provider_credentials( + "custom-gw", provider_routes.ProviderCredentialRequest(verify_ssl=True, ca_cert="") + ) + options = saved_config.read("custom-gw")["options"] + assert not {"verify_ssl", "ssl_verify", "ca_cert"} & set(options) + + # Leaving the fields out changes nothing. + await provider_routes.set_provider_credentials( + "custom-gw", provider_routes.ProviderCredentialRequest(verify_ssl=False) + ) + await provider_routes.set_provider_credentials( + "custom-gw", provider_routes.ProviderCredentialRequest(base_url="https://gw2.internal/v1") + ) + assert saved_config.read("custom-gw")["options"]["verify_ssl"] is False + + +@pytest.mark.asyncio +async def test_a_bad_ca_cert_is_refused_before_anything_is_saved(saved_config): + from fastapi import HTTPException + + from flocks.server.routes import provider as provider_routes + + saved_config.write({ + "custom-gw": {"npm": "@ai-sdk/openai-compatible", "options": {"baseURL": "https://gw.internal/v1"}, "models": {}} + }) + with pytest.raises(HTTPException) as caught: + await provider_routes.set_provider_credentials( + "custom-gw", + provider_routes.ProviderCredentialRequest(api_key="sk-new", ca_cert="certs/ca.pem"), # secret-guard: allow (test value) + ) + assert caught.value.status_code == 400 + assert "绝对路径" in caught.value.detail + assert saved_config.read("custom-gw")["options"] == {"baseURL": "https://gw.internal/v1"} + assert "custom-gw_llm_key" not in saved_config.secrets + + +@pytest.mark.asyncio +async def test_providers_whose_client_ignores_the_settings_refuse_them(saved_config): + from fastapi import HTTPException + + from flocks.server.routes import provider as provider_routes + + saved_config.write({"google": {"npm": "@ai-sdk/google", "options": {}, "models": {}}}) + assert provider_routes._load_llm_provider_credentials("google").tls_configurable is False + with pytest.raises(HTTPException) as caught: + await provider_routes.set_provider_credentials( + "google", provider_routes.ProviderCredentialRequest(api_key="k", verify_ssl=False) + ) + assert caught.value.status_code == 400 + + +@pytest.mark.asyncio +async def test_a_new_provider_is_created_with_its_tls_settings(saved_config): + from flocks.server.routes import provider as provider_routes + + await provider_routes.set_provider_credentials( + "anthropic", + provider_routes.ProviderCredentialRequest( + api_key="sk-ant", base_url="https://claude-gw.internal", verify_ssl=False, skip_catalog_bootstrap=True # secret-guard: allow (test value) + ), + ) + assert saved_config.read("anthropic")["options"]["verify_ssl"] is False + + +@pytest.mark.asyncio +async def test_catalog_says_which_providers_offer_the_settings(saved_config): + from flocks.server.routes import provider as provider_routes + + catalog = {entry["id"]: entry for entry in (await provider_routes.get_provider_catalog())["providers"]} + assert catalog["openai-compatible"]["tls_configurable"] is True + assert catalog["anthropic"]["tls_configurable"] is True + assert catalog["azure-openai"]["tls_configurable"] is True + assert catalog["google"]["tls_configurable"] is False + + +@pytest.mark.asyncio +async def test_custom_provider_is_created_with_its_tls_settings(saved_config, internal_ca): + from fastapi import HTTPException + + from flocks.server.routes import custom_provider + + created = await custom_provider.create_provider( + custom_provider.CreateProviderReq( + name="corp gw", base_url="https://gw.internal/v1", api_key="sk-test", ca_cert=internal_ca.cert_pem # secret-guard: allow (test value) + ), + _admin=None, + ) + options = saved_config.read(created.id)["options"] + assert options["ca_cert"] == internal_ca.cert_pem.strip() + assert "verify_ssl" not in options + runtime = Provider._providers[created.id] + assert runtime._config.custom_settings == {"ca_cert": internal_ca.cert_pem.strip()} + + created = await custom_provider.create_provider( + custom_provider.CreateProviderReq(name="old gw", base_url="https://old.internal/v1", verify_ssl=False), + _admin=None, + ) + assert saved_config.read(created.id)["options"]["verify_ssl"] is False + + with pytest.raises(HTTPException) as caught: + await custom_provider.create_provider( + custom_provider.CreateProviderReq(name="bad gw", base_url="https://bad.internal/v1", ca_cert="ca.pem"), + _admin=None, + ) + assert caught.value.status_code == 422 + assert "provider" not in json.loads(ConfigWriter._get_config_path().read_text()) or "custom-bad-gw" not in json.loads( + ConfigWriter._get_config_path().read_text() + )["provider"] diff --git a/tests/provider/tls_helpers.py b/tests/provider/tls_helpers.py new file mode 100644 index 000000000..4817c2267 --- /dev/null +++ b/tests/provider/tls_helpers.py @@ -0,0 +1,186 @@ +"""Certificates and a local HTTPS gateway for the provider TLS tests. + +Keys and certificates are made while the tests run, so none is kept in the +repository. +""" + +from __future__ import annotations + +import contextlib +import datetime +import ipaddress +import json +import ssl +import threading +from dataclasses import dataclass +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Iterator, Optional + + +def assert_no_verify_context(verify) -> None: + """``verify_ssl: false`` gives an httpx ``verify`` context that checks nothing.""" + assert isinstance(verify, ssl.SSLContext), verify + assert verify.verify_mode == ssl.CERT_NONE + assert verify.check_hostname is False + + +def describe_verify(verify): + """``True`` for httpx's default checks, ``"no-verify"`` for the relaxed context.""" + if verify is True: + return True + if isinstance(verify, ssl.SSLContext) and verify.verify_mode == ssl.CERT_NONE: + return "no-verify" + return verify + + +@dataclass +class Credential: + cert_pem: str + key_pem: str + + +def _name(common_name: str): + from cryptography import x509 + from cryptography.x509.oid import NameOID + + return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)]) + + +def _make(subject: str, *, issuer: Optional[Credential] = None, ca: bool = False, key_size: int = 2048) -> Credential: + from cryptography import x509 + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import rsa + + key = rsa.generate_private_key(public_exponent=65537, key_size=key_size) + now = datetime.datetime.now(datetime.timezone.utc) + if issuer is None: + issuer_name, signing_key = _name(subject), key + else: + issuer_cert = x509.load_pem_x509_certificate(issuer.cert_pem.encode()) + issuer_name = issuer_cert.subject + signing_key = serialization.load_pem_private_key(issuer.key_pem.encode(), password=None) + builder = ( + x509.CertificateBuilder() + .subject_name(_name(subject)) + .issuer_name(issuer_name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - datetime.timedelta(minutes=5)) + .not_valid_after(now + datetime.timedelta(days=2)) + .add_extension(x509.BasicConstraints(ca=ca, path_length=None), critical=True) + ) + if ca: + builder = builder.add_extension( + x509.KeyUsage( + digital_signature=True, content_commitment=False, key_encipherment=False, + data_encipherment=False, key_agreement=False, key_cert_sign=True, crl_sign=True, + encipher_only=False, decipher_only=False, + ), + critical=True, + ) + else: + builder = builder.add_extension( + x509.SubjectAlternativeName([x509.DNSName("localhost"), x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]), + critical=False, + ) + cert = builder.sign(signing_key, hashes.SHA256()) + return Credential( + cert_pem=cert.public_bytes(serialization.Encoding.PEM).decode(), + key_pem=key.private_bytes( + serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption() + ).decode(), + ) + + +def make_ca() -> Credential: + return _make("Flocks Test Internal CA", ca=True) + + +def make_server(issuer: Optional[Credential] = None) -> Credential: + """A gateway certificate for 127.0.0.1 / localhost: issued by *issuer*, or self-signed.""" + return _make("llm-gateway.test", issuer=issuer) + + +MODEL_ID = "gw-test-model" + + +class _Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args) -> None: # keep test output quiet + pass + + def _json(self, payload) -> None: + body = json.dumps(payload).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self) -> None: + self._json({"object": "list", "data": [{"id": MODEL_ID, "object": "model"}]}) + + def do_POST(self) -> None: + length = int(self.headers.get("Content-Length") or 0) + request = json.loads(self.rfile.read(length) or b"{}") + if request.get("stream"): + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Connection", "close") + self.end_headers() + for chunk in ( + {"id": "c1", "object": "chat.completion.chunk", "created": 0, "model": MODEL_ID, + "choices": [{"index": 0, "delta": {"role": "assistant", "content": "Paris"}, "finish_reason": None}]}, + {"id": "c1", "object": "chat.completion.chunk", "created": 0, "model": MODEL_ID, + "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}, + ): + self.wfile.write(b"data: " + json.dumps(chunk).encode() + b"\n\n") + self.wfile.write(b"data: [DONE]\n\n") + self.close_connection = True + return + self._json({ + "id": "c1", "object": "chat.completion", "created": 0, "model": MODEL_ID, + "choices": [{"index": 0, "message": {"role": "assistant", "content": "Paris"}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, + }) + + +@contextlib.contextmanager +def https_gateway( + credential: Credential, + tmp_path, + *, + ciphers: Optional[str] = None, + maximum_version: Optional[ssl.TLSVersion] = None, +) -> Iterator[str]: + """Serve an OpenAI-style API over HTTPS on 127.0.0.1; yields its ``/v1`` base URL. + + *ciphers* / *maximum_version* make it an older gateway: e.g. RSA key + exchange only, which CPython's default client settings refuse. + """ + cert_file = tmp_path / "gateway.crt" + key_file = tmp_path / "gateway.key" + cert_file.write_text(credential.cert_pem) + key_file.write_text(credential.key_pem) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(str(cert_file), str(key_file)) + if maximum_version is not None: + context.maximum_version = maximum_version + if ciphers: + context.set_ciphers(ciphers) + server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + server.socket = context.wrap_socket(server.socket, server_side=True) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"https://127.0.0.1:{server.server_address[1]}/v1" + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + + +# Only RSA key exchange (no ECDHE/DHE) in TLS 1.2: what older appliances often +# offer, and what CPython's default client cipher list leaves out. +RSA_KEY_EXCHANGE_ONLY = "AES128-GCM-SHA256:AES256-GCM-SHA384:@SECLEVEL=0" diff --git a/tests/server/routes/test_model_discovery_routes.py b/tests/server/routes/test_model_discovery_routes.py index 6622fca49..38068d750 100644 --- a/tests/server/routes/test_model_discovery_routes.py +++ b/tests/server/routes/test_model_discovery_routes.py @@ -170,6 +170,7 @@ async def test_discovery_forwards_transient_credentials_and_returns_structured_e "custom-inventory", api_key="transient-secret", base_url="https://candidate.test/v1", + tls_overrides=None, ) assert saved(inventory) == inventory.initial inventory.write.assert_not_called() @@ -177,6 +178,32 @@ async def test_discovery_forwards_transient_credentials_and_returns_structured_e assert "transient-secret" not in response.text +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("body", "overrides"), + [ + ({"verify_ssl": False}, {"verify_ssl": False}), + ({"ca_cert": ""}, {"ca_cert": ""}), + ({"verify_ssl": True, "ca_cert": "/etc/pki/corp-ca.pem"}, {"verify_ssl": True, "ca_cert": "/etc/pki/corp-ca.pem"}), + ], +) +async def test_discovery_and_key_check_use_unsaved_tls_settings(body, overrides, inventory, inventory_client, monkeypatch): + """The settings form checks a gateway with the SSL settings it has not saved yet.""" + result = {"source": "api", "status": "success", "code": "models_discovered", "message": "", "truncated": False, "models": []} + discover = AsyncMock(return_value=result) + monkeypatch.setattr(inventory.routes, "discover_models", discover) + + response = await inventory_client.post("/api/provider/custom-inventory/discover-models", json=body) + assert response.status_code == 200 + assert discover.await_args.kwargs["tls_overrides"] == overrides + + discover.reset_mock() + response = await inventory_client.post("/api/provider/custom-inventory/check-key", json={"api_key": "k", **body}) + assert response.status_code == 200 + assert [call.kwargs["tls_overrides"] for call in discover.await_args_list] == [overrides, overrides] + assert saved(inventory) == inventory.initial + + @pytest.mark.asyncio @pytest.mark.parametrize( "operation,body", @@ -615,7 +642,9 @@ async def test_threatbook_key_check_uses_one_live_inventory_request_without_savi }) assert response.status_code == 200 assert response.json() == {'status': status, 'code': expected_code} - discover.assert_awaited_once_with(provider_id, api_key='candidate-key', base_url='https://configured.test/v1') + discover.assert_awaited_once_with( + provider_id, api_key='candidate-key', base_url='https://configured.test/v1', tls_overrides=None # secret-guard: allow (test value) + ) assert saved(inventory) == inventory.initial inventory.write.assert_not_called() inventory.apply_config.assert_not_awaited() diff --git a/webui/src/api/provider.ts b/webui/src/api/provider.ts index 4dafe0c70..627d5499d 100644 --- a/webui/src/api/provider.ts +++ b/webui/src/api/provider.ts @@ -1,6 +1,7 @@ import client from './client'; import type { ProviderCredentials, + ProviderConnectionInput, ProviderCredentialInput, ProviderInfoV2, ModelDefinitionV2, @@ -90,7 +91,7 @@ function listApiServicesCached(options: { force?: boolean } = {}) { // ==================== Provider API (Legacy + Enhanced) ==================== export const providerAPI = { - discoverModels: (id: string, credentials: { api_key?: string; base_url?: string } = {}) => + discoverModels: (id: string, credentials: ProviderConnectionInput = {}) => client.post(`/api/provider/${encodeURIComponent(id)}/discover-models`, credentials), importModels: (id: string, models: ModelImportInput[]) => @@ -122,7 +123,7 @@ export const providerAPI = { getModelInventory: (id: string) => client.get<{ models: InventoryModelInput[] }>(`/api/provider/${encodeURIComponent(id)}/model-inventory`), saveModelInventory: (id: string, draft: ModelInventoryDraft) => client.post(`/api/provider/${encodeURIComponent(id)}/model-inventory`, draft), // Authentication checks can make two bounded upstream requests. - checkKey: (id: string, credentials?: { api_key?: string; base_url?: string }) => client.post<{ status: 'valid' | 'invalid' | 'unverified'; code: string }>(`/api/provider/${encodeURIComponent(id)}/check-key`, credentials ?? {}, { timeout: 60_000 }), + checkKey: (id: string, credentials?: ProviderConnectionInput) => client.post<{ status: 'valid' | 'invalid' | 'unverified'; code: string }>(`/api/provider/${encodeURIComponent(id)}/check-key`, credentials ?? {}, { timeout: 60_000 }), // Credentials management (LLM providers — uses _llm_key convention) getCredentials: (id: string) => diff --git a/webui/src/locales/en-US/model.json b/webui/src/locales/en-US/model.json index 3fdec1a30..503d880bd 100644 --- a/webui/src/locales/en-US/model.json +++ b/webui/src/locales/en-US/model.json @@ -237,7 +237,17 @@ "retry": "Retry", "compatCreateFirst": "OpenAI-compatible providers must be created first; test the connection from the configuration dialog afterwards", "providerNameHint": "Creates a separate OpenAI-compatible provider instance; existing configurations are not overwritten.", - "close": "Close" + "close": "Close", + "tls": { + "title": "SSL certificate", + "verify": "Verify SSL certificate", + "verifyHint": "If an internal gateway uses a self-signed certificate or one issued by an internal CA, add the CA certificate below or turn verification off.", + "caCert": "CA certificate", + "optional": "(optional)", + "caCertPlaceholder": "-----BEGIN CERTIFICATE-----\n…\n-----END CERTIFICATE-----\nor a path on the server, e.g. /etc/pki/ca-trust/source/anchors/corp-ca.pem", + "caCertHint": "Paste one or more CA certificates in PEM format, or enter the absolute path of a certificate file on the server. The system's root certificates stay trusted.", + "disabledWarning": "Certificate verification is off: the gateway's certificate is not checked, and older TLS (RSA key exchange, TLS 1.0/1.1, …) is accepted. Only do this for trusted gateways on your internal network." + } }, "wizard": { "providerSaved": "Provider Saved", @@ -307,7 +317,10 @@ "connection_error": "Could not connect. Check the service address and network.", "invalid_response": "The model list response could not be recognized.", "response_too_large": "The service response is too large. Reduce the returned list or add models manually.", - "redirect_not_allowed": "The service returned a redirect. To protect credentials, it was not followed. Enter the final service URL and retry." + "redirect_not_allowed": "The service returned a redirect. To protect credentials, it was not followed. Enter the final service URL and retry.", + "tls_certificate_failed": "SSL certificate verification failed: the gateway uses a self-signed certificate or one issued by an internal CA. Add the CA certificate under SSL certificate, or turn off Verify SSL certificate.", + "tls_handshake_failed": "TLS handshake failed: the gateway uses an old TLS version or cipher suite, or the address has the wrong http/https scheme. Once the address is right, turning off Verify SSL certificate also accepts older TLS.", + "invalid_ca_cert": "The CA certificate could not be loaded. Check its content or path." }, "reviewSelection": "Review fetched models", "invertVisible": "Invert filtered selection", @@ -443,7 +456,10 @@ "redirect_not_allowed": "The service returned a redirect. To protect credentials, it was not followed. Enter the final service URL and retry.", "key_valid": "The key is valid.", "model_list_verified": "Model list fetched successfully. Key verification passed.", - "key_check_unsupported": "This service cannot independently verify the key." + "key_check_unsupported": "This service cannot independently verify the key.", + "tls_certificate_failed": "SSL certificate verification failed: the gateway uses a self-signed certificate or one issued by an internal CA. Add the CA certificate under SSL certificate, or turn off Verify SSL certificate.", + "tls_handshake_failed": "TLS handshake failed: the gateway uses an old TLS version or cipher suite, or the address has the wrong http/https scheme. Once the address is right, turning off Verify SSL certificate also accepts older TLS.", + "invalid_ca_cert": "The CA certificate could not be loaded. Check its content or path." } } } diff --git a/webui/src/locales/zh-CN/model.json b/webui/src/locales/zh-CN/model.json index 6b4517686..3daf0fbab 100644 --- a/webui/src/locales/zh-CN/model.json +++ b/webui/src/locales/zh-CN/model.json @@ -237,7 +237,17 @@ "retry": "重试", "compatCreateFirst": "OpenAI-compatible Provider 需要先创建,创建后可在配置弹窗中测试连接", "providerNameHint": "用于创建独立的 OpenAI-compatible Provider 实例,不会覆盖已有配置。", - "close": "关闭" + "close": "关闭", + "tls": { + "title": "SSL 证书", + "verify": "校验 SSL 证书", + "verifyHint": "内网网关用自签名证书或内部 CA 签发的证书时,可以在下面填 CA 证书,或者关闭校验。", + "caCert": "CA 证书", + "optional": "(可选)", + "caCertPlaceholder": "-----BEGIN CERTIFICATE-----\n…\n-----END CERTIFICATE-----\n或服务器上的证书路径,例如 /etc/pki/ca-trust/source/anchors/corp-ca.pem", + "caCertHint": "粘贴 PEM 格式的 CA 证书(可以多张),或者填服务器上证书文件的绝对路径。系统自带的根证书照常信任。", + "disabledWarning": "已关闭证书校验:不再核对网关证书,同时兼容旧版 TLS(RSA 密钥交换、TLS 1.0/1.1 等)。只建议对内网里可信的网关这样设置。" + } }, "wizard": { "providerSaved": "Provider 已保存", @@ -307,7 +317,10 @@ "connection_error": "无法连接模型服务,请检查地址和网络。", "invalid_response": "服务返回的模型列表格式无法识别。", "response_too_large": "服务返回内容过大,请缩小返回范围或手动添加。", - "redirect_not_allowed": "服务返回了重定向,为保护凭据未自动跳转。请填写最终服务地址后重试。" + "redirect_not_allowed": "服务返回了重定向,为保护凭据未自动跳转。请填写最终服务地址后重试。", + "tls_certificate_failed": "SSL 证书校验失败:网关用的是自签名或内部 CA 签发的证书。请在「SSL 证书」里填 CA 证书,或者关闭「校验 SSL 证书」。", + "tls_handshake_failed": "TLS 握手失败:网关的 TLS 版本或加密套件较旧,或者地址的 http/https 写错了。确认地址无误后,可以关闭「校验 SSL 证书」来兼容旧版 TLS。", + "invalid_ca_cert": "CA 证书无法加载,请检查证书内容或路径。" }, "reviewSelection": "查看获取结果", "invertVisible": "反选筛选结果", @@ -443,7 +456,10 @@ "redirect_not_allowed": "服务返回了重定向,为保护凭据未自动跳转。请填写最终服务地址后重试。", "key_valid": "Key 有效。", "model_list_verified": "已成功获取模型列表,Key 验证通过。", - "key_check_unsupported": "该服务暂无法独立验证 Key。" + "key_check_unsupported": "该服务暂无法独立验证 Key。", + "tls_certificate_failed": "SSL 证书校验失败:网关用的是自签名或内部 CA 签发的证书。请在「SSL 证书」里填 CA 证书,或者关闭「校验 SSL 证书」。", + "tls_handshake_failed": "TLS 握手失败:网关的 TLS 版本或加密套件较旧,或者地址的 http/https 写错了。确认地址无误后,可以关闭「校验 SSL 证书」来兼容旧版 TLS。", + "invalid_ca_cert": "CA 证书无法加载,请检查证书内容或路径。" } } } diff --git a/webui/src/pages/Model/ModelDiscovery.tsx b/webui/src/pages/Model/ModelDiscovery.tsx index 2196b2dbf..f9c81f7a1 100644 --- a/webui/src/pages/Model/ModelDiscovery.tsx +++ b/webui/src/pages/Model/ModelDiscovery.tsx @@ -9,6 +9,7 @@ import type { ModelInventoryDraft, ModelImportInput, ModelImportResult, + ProviderConnectionInput, } from '@/types'; export function toModelImport(model: DiscoveredModel): ModelImportInput { @@ -196,7 +197,7 @@ function ModelEditor({ interface Props { providerId: string; - credentials?: { api_key?: string; base_url?: string }; + credentials?: ProviderConnectionInput; mode: 'stage' | 'import'; newInstance?: boolean; existingModelIds?: string[]; @@ -251,7 +252,9 @@ export default function ModelDiscovery({ deletedRef.current = deleted; const apiKey = credentials?.api_key, baseUrl = credentials?.base_url; - const previousConnection = useRef({ providerId, apiKey, baseUrl }); + // Unsaved SSL settings change the connection as much as the address does. + const tls = `${credentials?.verify_ssl ?? ''}|${credentials?.ca_cert ?? ''}`; + const previousConnection = useRef({ providerId, apiKey, baseUrl, tls }); useEffect(() => { const version = ++request.current; @@ -289,10 +292,10 @@ export default function ModelDiscovery({ useEffect(() => { const previous = previousConnection.current; - previousConnection.current = { providerId, apiKey, baseUrl }; + previousConnection.current = { providerId, apiKey, baseUrl, tls }; if ( previous.providerId !== providerId || - (previous.apiKey === apiKey && previous.baseUrl === baseUrl) || + (previous.apiKey === apiKey && previous.baseUrl === baseUrl && previous.tls === tls) || !loaded ) return; @@ -305,7 +308,7 @@ export default function ModelDiscovery({ setRows((current) => current.filter((row) => row.existing)); // Saved-model edits, switches, and explicit deletions belong to this // provider, even when the credentials for the next discovery change. - }, [providerId, apiKey, baseUrl, loaded]); + }, [providerId, apiKey, baseUrl, tls, loaded]); useEffect(() => { if (!shouldLoad || lastInventoryKey.current === inventoryKey) return; diff --git a/webui/src/pages/Model/ProviderKeyCheck.tsx b/webui/src/pages/Model/ProviderKeyCheck.tsx index 8a95162ac..cf7a241e9 100644 --- a/webui/src/pages/Model/ProviderKeyCheck.tsx +++ b/webui/src/pages/Model/ProviderKeyCheck.tsx @@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next'; import { Loader2 } from 'lucide-react'; import { providerAPI } from '@/api/provider'; import { extractErrorMessage } from '@/utils/error'; +import type { ProviderConnectionInput } from '@/types'; export default function ProviderKeyCheck({ providerId, @@ -10,7 +11,7 @@ export default function ProviderKeyCheck({ disabled, }: { providerId: string; - credentials: { api_key?: string; base_url?: string }; + credentials: ProviderConnectionInput; disabled?: boolean; }) { const { t } = useTranslation('model'); @@ -25,7 +26,7 @@ export default function ProviderKeyCheck({ return () => { version.current += 1; }; - }, [providerId, credentials.api_key, credentials.base_url]); + }, [providerId, credentials.api_key, credentials.base_url, credentials.verify_ssl, credentials.ca_cert]); const check = async () => { if (checking || disabled) return; const current = ++version.current; diff --git a/webui/src/pages/Model/ProviderTlsSettings.test.tsx b/webui/src/pages/Model/ProviderTlsSettings.test.tsx new file mode 100644 index 000000000..27f55df4b --- /dev/null +++ b/webui/src/pages/Model/ProviderTlsSettings.test.tsx @@ -0,0 +1,94 @@ +import { useState } from 'react'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { vi } from 'vitest'; +import ProviderTlsSettings, { + DEFAULT_PROVIDER_TLS, + allTlsRequestFields, + savedProviderTls, + tlsRequestFields, + type ProviderTlsValue, +} from './ProviderTlsSettings'; + +vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en-US' } }) })); + +function Harness({ initial = DEFAULT_PROVIDER_TLS, onChange }: { initial?: ProviderTlsValue; onChange?: (value: ProviderTlsValue) => void }) { + const [value, setValue] = useState(initial); + return ( + { + setValue(next); + onChange?.(next); + }} + /> + ); +} + +const PEM = '-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----'; + +it('checks certificates by default and offers a CA certificate', () => { + render(); + const toggle = screen.getByRole('switch', { name: 'form.tls.verify' }); + expect(toggle).toHaveAttribute('aria-checked', 'true'); + expect(toggle).toHaveAccessibleDescription('form.tls.verifyHint'); + expect(screen.getByLabelText(/form\.tls\.caCert/)).toHaveValue(''); + expect(screen.queryByRole('note')).not.toBeInTheDocument(); +}); + +it('warns what turning the checks off also allows, and hides the CA field meanwhile', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + render(); + + await user.click(screen.getByRole('switch', { name: 'form.tls.verify' })); + + expect(onChange).toHaveBeenLastCalledWith({ verifySsl: false, caCert: PEM }); + expect(screen.getByRole('switch', { name: 'form.tls.verify' })).toHaveAttribute('aria-checked', 'false'); + expect(screen.getByRole('note')).toHaveTextContent('form.tls.disabledWarning'); + expect(screen.queryByLabelText(/form\.tls\.caCert/)).not.toBeInTheDocument(); + + // Turning them back on keeps the certificate that was there. + await user.click(screen.getByRole('switch', { name: 'form.tls.verify' })); + expect(screen.getByLabelText(/form\.tls\.caCert/)).toHaveValue(PEM); +}); + +it('reports a pasted certificate', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + render(); + await user.type(screen.getByLabelText(/form\.tls\.caCert/), '/etc/pki/corp-ca.pem'); + expect(onChange).toHaveBeenLastCalledWith({ verifySsl: true, caCert: '/etc/pki/corp-ca.pem' }); +}); + +it('cannot be changed while disabled', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + render(); + await user.click(screen.getByRole('switch', { name: 'form.tls.verify' })); + expect(onChange).not.toHaveBeenCalled(); + expect(screen.getByLabelText(/form\.tls\.caCert/)).toBeDisabled(); +}); + +describe('request fields', () => { + it('reads the saved settings, defaults when there are none', () => { + expect(savedProviderTls(null)).toEqual(DEFAULT_PROVIDER_TLS); + expect(savedProviderTls({ verify_ssl: null, ca_cert: null })).toEqual(DEFAULT_PROVIDER_TLS); + expect(savedProviderTls({ verify_ssl: false, ca_cert: PEM })).toEqual({ verifySsl: false, caCert: PEM }); + }); + + it('sends only what changed, so stored values stay as saved', () => { + const saved = { verifySsl: true, caCert: '{env:CORP_CA}' }; + expect(tlsRequestFields(saved, saved)).toEqual({}); + expect(tlsRequestFields({ ...saved, caCert: ' {env:CORP_CA}\n' }, saved)).toEqual({}); + expect(tlsRequestFields({ ...saved, verifySsl: false }, saved)).toEqual({ verify_ssl: false }); + expect(tlsRequestFields({ ...saved, caCert: '' }, saved)).toEqual({ ca_cert: '' }); + expect(tlsRequestFields({ verifySsl: true, caCert: ` ${PEM}\n` })).toEqual({ ca_cert: PEM }); + expect(tlsRequestFields(DEFAULT_PROVIDER_TLS)).toEqual({}); + }); + + it('sends every setting for a new provider, defaults included', () => { + expect(allTlsRequestFields(DEFAULT_PROVIDER_TLS)).toEqual({ verify_ssl: true, ca_cert: '' }); + expect(allTlsRequestFields({ verifySsl: false, caCert: ` ${PEM}\n` })).toEqual({ verify_ssl: false, ca_cert: PEM }); + }); +}); diff --git a/webui/src/pages/Model/ProviderTlsSettings.tsx b/webui/src/pages/Model/ProviderTlsSettings.tsx new file mode 100644 index 000000000..10ec3f4d0 --- /dev/null +++ b/webui/src/pages/Model/ProviderTlsSettings.tsx @@ -0,0 +1,117 @@ +import { useId } from 'react'; +import { useTranslation } from 'react-i18next'; +import { ShieldAlert } from 'lucide-react'; +import type { ProviderTlsInput } from '@/types'; + +/** The SSL settings of an LLM provider as the form edits them. */ +export interface ProviderTlsValue { + verifySsl: boolean; + caCert: string; +} + +export const DEFAULT_PROVIDER_TLS: ProviderTlsValue = { verifySsl: true, caCert: '' }; + +/** The saved settings from a credentials read, defaults when the read has none. */ +export function savedProviderTls(credentials?: { verify_ssl?: boolean | null; ca_cert?: string | null } | null): ProviderTlsValue { + return { + verifySsl: credentials?.verify_ssl !== false, + caCert: credentials?.ca_cert ?? '', + }; +} + +/** + * Request fields for the settings that differ from *saved*, nothing when none do. + * + * Unchanged settings are left out so the server keeps (and resolves) what it + * stored, such as a `{env:...}` reference in place of a certificate. + */ +export function tlsRequestFields(value: ProviderTlsValue, saved: ProviderTlsValue = DEFAULT_PROVIDER_TLS): ProviderTlsInput { + const fields: ProviderTlsInput = {}; + if (value.verifySsl !== saved.verifySsl) fields.verify_ssl = value.verifySsl; + if (value.caCert.trim() !== saved.caCert.trim()) fields.ca_cert = value.caCert.trim(); + return fields; +} + +/** + * Request fields for every setting, defaults included. + * + * A new provider has nothing saved, and its checks run under the catalog id, + * whose stored settings may belong to another gateway: send the form as it is. + */ +export function allTlsRequestFields(value: ProviderTlsValue): Required { + return { verify_ssl: value.verifySsl, ca_cert: value.caCert.trim() }; +} + +export default function ProviderTlsSettings({ + value, + onChange, + disabled, +}: { + value: ProviderTlsValue; + onChange: (value: ProviderTlsValue) => void; + disabled?: boolean; +}) { + const { t } = useTranslation('model'); + const id = useId(); + const labelId = `${id}-verify-label`; + const hintId = `${id}-verify-hint`; + const caId = `${id}-ca-cert`; + const caHintId = `${id}-ca-cert-hint`; + return ( +
+
+
+ {t('form.tls.verify')} +

{t('form.tls.verifyHint')}

+
+ +
+ {value.verifySsl ? ( +
+ +