mirror of
https://github.com/HKUDS/nanobot.git
synced 2026-08-07 21:08:34 +03:00
fix(weixin): harden protocol delivery, streaming, and login (#5263)
This commit is contained in:
@@ -101,6 +101,23 @@ class BaseChannel(ABC):
|
||||
"""
|
||||
pass
|
||||
|
||||
def should_retry_send_error(self, error: Exception) -> bool:
|
||||
"""Return whether the channel manager may retry a failed delivery.
|
||||
|
||||
Channels with protocol-level business errors can override this hook to
|
||||
prevent retries that cannot succeed until external state changes.
|
||||
Transport and unexpected errors remain retryable by default.
|
||||
"""
|
||||
return True
|
||||
|
||||
def start_error_message(self, error: Exception) -> str | None:
|
||||
"""Return an actionable public message for a channel startup failure.
|
||||
|
||||
Channel-specific exception handling stays in the owning channel. Returning
|
||||
``None`` keeps the manager's generic fallback.
|
||||
"""
|
||||
return None
|
||||
|
||||
async def send_delta(
|
||||
self,
|
||||
chat_id: str,
|
||||
|
||||
@@ -187,11 +187,21 @@ class ChannelManager:
|
||||
channel = cls(section, self.bus, **kwargs)
|
||||
if runtime_name and runtime_name != channel.name:
|
||||
channel.name = runtime_name
|
||||
# Channel-owned config models may deliberately choose safer transport
|
||||
# defaults than the global channel policy (for example, a quota-limited
|
||||
# platform can disable progress messages). Preserve those defaults
|
||||
# while still letting an explicit per-channel value win below.
|
||||
progress_default = getattr(
|
||||
channel.config, "send_progress", self.config.channels.send_progress,
|
||||
)
|
||||
tool_hints_default = getattr(
|
||||
channel.config, "send_tool_hints", self.config.channels.send_tool_hints,
|
||||
)
|
||||
channel.send_progress = self._resolve_bool_override(
|
||||
section, "send_progress", self.config.channels.send_progress,
|
||||
section, "send_progress", progress_default,
|
||||
)
|
||||
channel.send_tool_hints = self._resolve_bool_override(
|
||||
section, "send_tool_hints", self.config.channels.send_tool_hints,
|
||||
section, "send_tool_hints", tool_hints_default,
|
||||
)
|
||||
channel.show_reasoning = self._resolve_bool_override(
|
||||
section, "show_reasoning", self.config.channels.show_reasoning,
|
||||
@@ -347,9 +357,13 @@ class ChannelManager:
|
||||
await channel.start()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
errors[name] = "Channel failed to start. Check gateway logs."
|
||||
logger.exception("Failed to start channel {}", name)
|
||||
except Exception as exc:
|
||||
public_error = channel.start_error_message(exc)
|
||||
errors[name] = public_error or "Channel failed to start. Check gateway logs."
|
||||
if public_error:
|
||||
logger.error("Failed to start channel {}: {}", name, public_error)
|
||||
else:
|
||||
logger.exception("Failed to start channel {}", name)
|
||||
|
||||
def _start_channel_task(self, name: str, channel: BaseChannel) -> asyncio.Task[None]:
|
||||
logger.info("Starting {} channel...", name)
|
||||
@@ -912,6 +926,14 @@ class ChannelManager:
|
||||
except asyncio.CancelledError:
|
||||
raise # Propagate cancellation for graceful shutdown
|
||||
except Exception as e:
|
||||
if not channel.should_retry_send_error(e):
|
||||
logger.error(
|
||||
"Send to {} failed with a non-retryable {}: {}",
|
||||
msg.channel,
|
||||
type(e).__name__,
|
||||
e,
|
||||
)
|
||||
return
|
||||
loop = asyncio.get_running_loop()
|
||||
exhausted = (
|
||||
attempt >= max_attempts
|
||||
|
||||
@@ -47,7 +47,10 @@ class WeixinConnectStore:
|
||||
if not session_id:
|
||||
raise ChannelConnectError("missing WeChat connect session")
|
||||
if action == "poll":
|
||||
return await self.poll(session_id)
|
||||
return await self.poll(
|
||||
session_id,
|
||||
verify_code=(query_first(query, "verify_code") or "").strip(),
|
||||
)
|
||||
if action == "cancel":
|
||||
return await self.cancel(session_id)
|
||||
raise ChannelConnectError(f"unsupported WeChat connect action: {action}", status=404)
|
||||
@@ -91,7 +94,7 @@ class WeixinConnectStore:
|
||||
)
|
||||
return self._start_payload(self._sessions[session_id])
|
||||
|
||||
async def poll(self, session_id: str) -> dict[str, Any]:
|
||||
async def poll(self, session_id: str, *, verify_code: str = "") -> dict[str, Any]:
|
||||
await self._cleanup()
|
||||
session = self._sessions.get(session_id)
|
||||
if session is None:
|
||||
@@ -105,6 +108,7 @@ class WeixinConnectStore:
|
||||
status_data = await session.channel.connect_poll_qr_code(
|
||||
base_url=session.current_poll_base_url,
|
||||
qrcode_id=session.qrcode_id,
|
||||
verify_code=verify_code,
|
||||
)
|
||||
except Exception as exc:
|
||||
if session.channel.connect_poll_error_is_retryable(exc):
|
||||
@@ -120,6 +124,8 @@ class WeixinConnectStore:
|
||||
|
||||
status_payload = status_data
|
||||
status = status_payload.get("status", "")
|
||||
from nanobot.channels.weixin.runtime import MAX_QR_REFRESH_COUNT
|
||||
|
||||
if status == "confirmed":
|
||||
if self._sessions.get(session_id) is not session:
|
||||
return {
|
||||
@@ -157,9 +163,66 @@ class WeixinConnectStore:
|
||||
)
|
||||
return self._pending_payload(session)
|
||||
|
||||
if status == "expired":
|
||||
from nanobot.channels.weixin.runtime import MAX_QR_REFRESH_COUNT
|
||||
if status == "need_verifycode":
|
||||
return self._pending_payload(
|
||||
session,
|
||||
challenge="verify_code",
|
||||
message=(
|
||||
"That verification code did not match. Enter the new number shown in WeChat."
|
||||
if verify_code
|
||||
else "Enter the number shown in WeChat to continue."
|
||||
),
|
||||
verification_failed=bool(verify_code),
|
||||
)
|
||||
|
||||
if status == "verify_code_blocked":
|
||||
session.refresh_count += 1
|
||||
if session.refresh_count > MAX_QR_REFRESH_COUNT:
|
||||
self._sessions.pop(session_id, None)
|
||||
await self._close_channel(session.channel)
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"status": "failed",
|
||||
"message": "Too many incorrect verification attempts. Try again later.",
|
||||
}
|
||||
try:
|
||||
session.qrcode_id, session.qr_url = (
|
||||
await session.channel.connect_fetch_qr_code()
|
||||
)
|
||||
except Exception as exc:
|
||||
self._sessions.pop(session_id, None)
|
||||
await self._close_channel(session.channel)
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"status": "failed",
|
||||
"message": f"Could not refresh WeChat QR code: {exc}",
|
||||
}
|
||||
session.current_poll_base_url = session.channel.connect_base_url
|
||||
return self._pending_payload(
|
||||
session,
|
||||
message="Verification was blocked. Scan the refreshed QR code to try again.",
|
||||
)
|
||||
|
||||
if status == "binded_redirect":
|
||||
if not session.channel.connect_load_state():
|
||||
self._sessions.pop(session_id, None)
|
||||
await self._close_channel(session.channel)
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"status": "failed",
|
||||
"message": (
|
||||
"WeChat reports an existing binding, but no local credentials were found."
|
||||
),
|
||||
}
|
||||
self._sessions.pop(session_id, None)
|
||||
await self._close_channel(session.channel)
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"status": "succeeded",
|
||||
"message": "WeChat is already connected to this nanobot instance.",
|
||||
}
|
||||
|
||||
if status == "expired":
|
||||
session.refresh_count += 1
|
||||
if session.refresh_count > MAX_QR_REFRESH_COUNT:
|
||||
self._sessions.pop(session_id, None)
|
||||
@@ -238,15 +301,25 @@ class WeixinConnectStore:
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _pending_payload(session: WeixinConnectSession) -> dict[str, Any]:
|
||||
return {
|
||||
def _pending_payload(
|
||||
session: WeixinConnectSession,
|
||||
*,
|
||||
challenge: str = "",
|
||||
message: str = "Waiting for WeChat scan.",
|
||||
verification_failed: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
payload: dict[str, Any] = {
|
||||
"session_id": session.id,
|
||||
"status": "pending",
|
||||
"qr_url": session.qr_url,
|
||||
"interval_ms": 2000,
|
||||
"expires_at_ms": int((session.created_wall + 600) * 1000),
|
||||
"message": "Waiting for WeChat scan.",
|
||||
"message": message,
|
||||
}
|
||||
if challenge:
|
||||
payload["challenge"] = challenge
|
||||
payload["verification_failed"] = verification_failed
|
||||
return payload
|
||||
|
||||
|
||||
__all__ = ["WeixinConnectStore"]
|
||||
|
||||
@@ -10,6 +10,20 @@ SETUP_SPEC = ChannelSetupSpec(
|
||||
fields={
|
||||
"token": field("secret"),
|
||||
"allowFrom": field("list"),
|
||||
"baseUrl": field(default="https://ilinkai.weixin.qq.com"),
|
||||
"cdnBaseUrl": field(default="https://novac2c.cdn.weixin.qq.com/c2c"),
|
||||
"routeTag": field(),
|
||||
"stateDir": field(),
|
||||
"pollTimeout": field("int", default=35),
|
||||
"sendProgress": field("bool", default=False),
|
||||
"sendToolHints": field("bool", default=False),
|
||||
"replyProgressMessages": field("bool", default=False),
|
||||
"replyProgressMaxMessages": field("int", default=2),
|
||||
"contextMessageBudget": field("int", default=8),
|
||||
"streaming": field("bool", default=True),
|
||||
"blockStreaming": field("bool", default=False),
|
||||
"blockStreamingMinChars": field("int", default=1200),
|
||||
"blockStreamingMaxMessages": field("int", default=3),
|
||||
},
|
||||
required=(required("token"),),
|
||||
official_url="https://weixin.qq.com/",
|
||||
|
||||
+993
-161
File diff suppressed because it is too large
Load Diff
@@ -147,3 +147,129 @@ async def test_weixin_cancel_wins_over_inflight_confirmation(
|
||||
assert cancelled["status"] == "cancelled"
|
||||
assert completed["status"] == "cancelled"
|
||||
assert not (state_dir / "account.json").exists()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weixin_connect_store_handles_verification_code(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
state_dir = tmp_path / "weixin-state"
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(
|
||||
Config.model_validate({"channels": {"weixin": {"stateDir": str(state_dir)}}}),
|
||||
config_path,
|
||||
)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
async def fake_fetch_qr_code(self: WeixinChannel) -> tuple[str, str]:
|
||||
return "qr-verify", "https://qr.example/verify"
|
||||
|
||||
responses = [
|
||||
{"status": "need_verifycode"},
|
||||
{
|
||||
"status": "confirmed",
|
||||
"bot_token": "verified-token",
|
||||
"ilink_user_id": "wx-user",
|
||||
},
|
||||
]
|
||||
|
||||
async def fake_api_get_with_base(
|
||||
self: WeixinChannel,
|
||||
*,
|
||||
params: dict[str, Any],
|
||||
**_kwargs: Any,
|
||||
) -> dict[str, str]:
|
||||
if len(responses) == 1:
|
||||
assert params == {"qrcode": "qr-verify", "verify_code": "1234"}
|
||||
return responses.pop(0)
|
||||
|
||||
monkeypatch.setattr(WeixinChannel, "_fetch_qr_code", fake_fetch_qr_code)
|
||||
monkeypatch.setattr(WeixinChannel, "_api_get_with_base", fake_api_get_with_base)
|
||||
|
||||
store = WeixinConnectStore()
|
||||
started = await store.start()
|
||||
challenged = await store.poll(started["session_id"])
|
||||
completed = await store.handle(
|
||||
"poll",
|
||||
{
|
||||
"session_id": [started["session_id"]],
|
||||
"verify_code": ["1234"],
|
||||
},
|
||||
)
|
||||
|
||||
assert challenged["status"] == "pending"
|
||||
assert challenged["challenge"] == "verify_code"
|
||||
assert completed["status"] == "succeeded"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weixin_connect_store_treats_existing_binding_as_success(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
state_dir = tmp_path / "weixin-state"
|
||||
state_dir.mkdir()
|
||||
(state_dir / "account.json").write_text(
|
||||
json.dumps({"token": "working-token"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(
|
||||
Config.model_validate({"channels": {"weixin": {"stateDir": str(state_dir)}}}),
|
||||
config_path,
|
||||
)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
async def fake_fetch_qr_code(self: WeixinChannel) -> tuple[str, str]:
|
||||
return "qr-existing", "https://qr.example/existing"
|
||||
|
||||
async def fake_api_get_with_base(
|
||||
self: WeixinChannel,
|
||||
**_kwargs: Any,
|
||||
) -> dict[str, str]:
|
||||
return {"status": "binded_redirect"}
|
||||
|
||||
monkeypatch.setattr(WeixinChannel, "_fetch_qr_code", fake_fetch_qr_code)
|
||||
monkeypatch.setattr(WeixinChannel, "_api_get_with_base", fake_api_get_with_base)
|
||||
|
||||
store = WeixinConnectStore()
|
||||
started = await store.start(force=True)
|
||||
completed = await store.poll(started["session_id"])
|
||||
|
||||
assert completed["status"] == "succeeded"
|
||||
assert "already connected" in completed["message"]
|
||||
assert json.loads((state_dir / "account.json").read_text())["token"] == "working-token"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weixin_connect_store_rejects_existing_binding_without_local_credentials(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
state_dir = tmp_path / "weixin-state"
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(
|
||||
Config.model_validate({"channels": {"weixin": {"stateDir": str(state_dir)}}}),
|
||||
config_path,
|
||||
)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
async def fake_fetch_qr_code(self: WeixinChannel) -> tuple[str, str]:
|
||||
return "qr-missing", "https://qr.example/missing"
|
||||
|
||||
async def fake_api_get_with_base(
|
||||
self: WeixinChannel,
|
||||
**_kwargs: Any,
|
||||
) -> dict[str, str]:
|
||||
return {"status": "binded_redirect"}
|
||||
|
||||
monkeypatch.setattr(WeixinChannel, "_fetch_qr_code", fake_fetch_qr_code)
|
||||
monkeypatch.setattr(WeixinChannel, "_api_get_with_base", fake_api_get_with_base)
|
||||
|
||||
store = WeixinConnectStore()
|
||||
started = await store.start(force=True)
|
||||
completed = await store.poll(started["session_id"])
|
||||
|
||||
assert completed["status"] == "failed"
|
||||
assert "no local credentials" in completed["message"]
|
||||
|
||||
@@ -17,6 +17,7 @@ from nanobot.channels.weixin.runtime import (
|
||||
ITEM_TEXT,
|
||||
MESSAGE_TYPE_BOT,
|
||||
WEIXIN_CHANNEL_VERSION,
|
||||
WeixinAuthError,
|
||||
WeixinChannel,
|
||||
WeixinConfig,
|
||||
_decrypt_aes_ecb,
|
||||
@@ -67,11 +68,11 @@ def test_make_headers_includes_route_tag_when_configured() -> None:
|
||||
assert headers["Authorization"] == "Bearer token"
|
||||
assert headers["SKRouteTag"] == "123"
|
||||
assert headers["iLink-App-Id"] == "bot"
|
||||
assert headers["iLink-App-ClientVersion"] == str((2 << 16) | (1 << 8) | 1)
|
||||
assert headers["iLink-App-ClientVersion"] == str((2 << 16) | (4 << 8) | 6)
|
||||
|
||||
|
||||
def test_channel_version_matches_reference_plugin_version() -> None:
|
||||
assert WEIXIN_CHANNEL_VERSION == "2.1.1"
|
||||
assert WEIXIN_CHANNEL_VERSION == "2.4.6"
|
||||
|
||||
|
||||
def test_save_and_load_state_persists_context_tokens(tmp_path) -> None:
|
||||
@@ -159,6 +160,29 @@ def test_save_state_persists_explicit_config_token_over_stale_state(tmp_path) ->
|
||||
assert saved["get_updates_buf"] == "current-cursor"
|
||||
|
||||
|
||||
def test_save_state_preserves_qr_replacement_of_configured_token(tmp_path) -> None:
|
||||
config = WeixinConfig(
|
||||
enabled=True,
|
||||
allow_from=["*"],
|
||||
token="configured-token",
|
||||
state_dir=str(tmp_path),
|
||||
)
|
||||
old_runtime = WeixinChannel(config, MessageBus())
|
||||
old_runtime._token = "configured-token"
|
||||
|
||||
replacement = WeixinChannel(config, MessageBus())
|
||||
replacement.connect_commit_account(
|
||||
token="replacement-token",
|
||||
base_url="https://new.example",
|
||||
)
|
||||
|
||||
old_runtime._save_state()
|
||||
|
||||
saved = json.loads((tmp_path / "account.json").read_text())
|
||||
assert saved["token"] == "replacement-token"
|
||||
assert saved["base_url"] == "https://new.example"
|
||||
|
||||
|
||||
def test_save_state_with_empty_runtime_token_preserves_persisted_account(tmp_path) -> None:
|
||||
channel = WeixinChannel(
|
||||
WeixinConfig(enabled=True, allow_from=["*"], state_dir=str(tmp_path)),
|
||||
@@ -442,15 +466,15 @@ async def test_send_without_context_token_raises() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_raises_when_session_is_paused() -> None:
|
||||
async def test_send_raises_when_authentication_is_required() -> None:
|
||||
channel, _bus = _make_channel()
|
||||
channel._client = object()
|
||||
channel._token = "token"
|
||||
channel._context_tokens["wx-user"] = "ctx-2"
|
||||
channel._pause_session(60)
|
||||
channel._auth_required = True
|
||||
channel._send_text = AsyncMock()
|
||||
|
||||
with pytest.raises(RuntimeError, match="session paused"):
|
||||
with pytest.raises(WeixinAuthError, match="bot token is stale"):
|
||||
await channel.send(
|
||||
type("Msg", (), {"chat_id": "wx-user", "content": "pong", "media": [], "metadata": {}})()
|
||||
)
|
||||
@@ -525,20 +549,21 @@ async def test_send_still_sends_text_when_typing_ticket_missing() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_poll_once_pauses_session_on_expired_errcode() -> None:
|
||||
async def test_poll_once_requires_login_on_stale_token() -> None:
|
||||
channel, _bus = _make_channel()
|
||||
channel._client = SimpleNamespace(timeout=None)
|
||||
channel._token = "token"
|
||||
channel._api_post = AsyncMock(return_value={"ret": 0, "errcode": -14, "errmsg": "expired"})
|
||||
|
||||
await channel._poll_once()
|
||||
with pytest.raises(WeixinAuthError, match="no replacement credentials"):
|
||||
await channel._poll_once()
|
||||
|
||||
assert channel._session_pause_remaining_s() > 0
|
||||
assert channel._auth_required is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_poll_once_reloads_refreshed_state_after_session_pause(
|
||||
tmp_path, monkeypatch: pytest.MonkeyPatch
|
||||
async def test_poll_once_reloads_refreshed_state_after_stale_token(
|
||||
tmp_path,
|
||||
) -> None:
|
||||
channel = WeixinChannel(
|
||||
WeixinConfig(enabled=True, allow_from=["*"], state_dir=str(tmp_path)),
|
||||
@@ -550,8 +575,13 @@ async def test_poll_once_reloads_refreshed_state_after_session_pause(
|
||||
json.dumps({"token": "new-token", "base_url": "https://new.example"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
channel._session_pause_until = time.time() + 10
|
||||
monkeypatch.setattr(weixin_mod.asyncio, "sleep", AsyncMock())
|
||||
channel._client = object()
|
||||
channel._api_post = AsyncMock(
|
||||
side_effect=[
|
||||
{"ret": 0, "errcode": -14, "errmsg": "stale"},
|
||||
{"ret": 0},
|
||||
]
|
||||
)
|
||||
|
||||
await channel._poll_once()
|
||||
|
||||
@@ -560,8 +590,8 @@ async def test_poll_once_reloads_refreshed_state_after_session_pause(
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_poll_once_keeps_explicit_token_after_session_pause(
|
||||
tmp_path, monkeypatch: pytest.MonkeyPatch
|
||||
async def test_poll_once_keeps_explicit_token_and_requires_login(
|
||||
tmp_path,
|
||||
) -> None:
|
||||
channel = WeixinChannel(
|
||||
WeixinConfig(
|
||||
@@ -577,24 +607,132 @@ async def test_poll_once_keeps_explicit_token_after_session_pause(
|
||||
json.dumps({"token": "stale-token", "base_url": "https://stale.example"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
channel._session_pause_until = time.time() + 10
|
||||
monkeypatch.setattr(weixin_mod.asyncio, "sleep", AsyncMock())
|
||||
channel._client = object()
|
||||
channel._api_post = AsyncMock(
|
||||
return_value={"ret": 0, "errcode": -14, "errmsg": "stale"}
|
||||
)
|
||||
|
||||
await channel._poll_once()
|
||||
with pytest.raises(WeixinAuthError, match="no replacement credentials"):
|
||||
await channel._poll_once()
|
||||
|
||||
assert channel._token == "configured-token"
|
||||
assert channel.config.base_url == "https://ilinkai.weixin.qq.com"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_poll_once_loads_qr_replacement_for_configured_token(tmp_path) -> None:
|
||||
config = WeixinConfig(
|
||||
enabled=True,
|
||||
allow_from=["*"],
|
||||
token="configured-token",
|
||||
state_dir=str(tmp_path),
|
||||
)
|
||||
replacement = WeixinChannel(config, MessageBus())
|
||||
replacement.connect_commit_account(
|
||||
token="replacement-token",
|
||||
base_url="https://new.example",
|
||||
)
|
||||
|
||||
channel = WeixinChannel(config, MessageBus())
|
||||
channel._token = "configured-token"
|
||||
channel._client = object()
|
||||
channel._api_post = AsyncMock(
|
||||
side_effect=[
|
||||
{"ret": 0, "errcode": -14, "errmsg": "stale"},
|
||||
{"ret": 0},
|
||||
]
|
||||
)
|
||||
|
||||
await channel._poll_once()
|
||||
|
||||
assert channel._token == "replacement-token"
|
||||
assert channel.config.base_url == "https://new.example"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_uses_qr_replacement_for_configured_token(tmp_path) -> None:
|
||||
config = WeixinConfig(
|
||||
enabled=True,
|
||||
allow_from=["*"],
|
||||
token="configured-token",
|
||||
state_dir=str(tmp_path),
|
||||
)
|
||||
connector = WeixinChannel(config, MessageBus())
|
||||
connector.connect_commit_account(
|
||||
token="replacement-token",
|
||||
base_url="https://new.example",
|
||||
)
|
||||
|
||||
channel = WeixinChannel(config, MessageBus())
|
||||
observed_tokens: list[str] = []
|
||||
|
||||
async def stop_after_first_poll() -> None:
|
||||
observed_tokens.append(channel._token)
|
||||
channel._running = False
|
||||
|
||||
channel._notify_lifecycle = AsyncMock() # type: ignore[method-assign]
|
||||
channel._poll_once = stop_after_first_poll # type: ignore[method-assign]
|
||||
|
||||
await channel.start()
|
||||
await channel.stop()
|
||||
|
||||
assert observed_tokens == ["replacement-token"]
|
||||
assert channel.config.base_url == "https://new.example"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_manager_surfaces_actionable_weixin_auth_error_without_traceback(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
from nanobot.channels import manager as manager_mod
|
||||
|
||||
channel = WeixinChannel(
|
||||
WeixinConfig(enabled=True, allow_from=["*"], state_dir=str(tmp_path)),
|
||||
MessageBus(),
|
||||
)
|
||||
channel.start = AsyncMock( # type: ignore[method-assign]
|
||||
side_effect=WeixinAuthError(
|
||||
"getupdates",
|
||||
errcode=-14,
|
||||
errmsg="stale",
|
||||
)
|
||||
)
|
||||
errors: list[str] = []
|
||||
tracebacks: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
manager_mod.logger,
|
||||
"error",
|
||||
lambda message, *args: errors.append(message.format(*args)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
manager_mod.logger,
|
||||
"exception",
|
||||
lambda message, *args: tracebacks.append(message.format(*args)),
|
||||
)
|
||||
manager = manager_mod.ChannelManager.__new__(manager_mod.ChannelManager)
|
||||
manager._channel_errors = {}
|
||||
|
||||
await manager._start_channel("weixin", channel)
|
||||
|
||||
assert manager._channel_errors["weixin"] == (
|
||||
"WeChat login expired. Scan again to reconnect."
|
||||
)
|
||||
assert errors == [
|
||||
"Failed to start channel weixin: WeChat login expired. Scan again to reconnect."
|
||||
]
|
||||
assert tracebacks == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_qr_login_refreshes_expired_qr_and_then_succeeds(
|
||||
no_qr_poll_delay,
|
||||
) -> None:
|
||||
channel, _bus = _make_channel()
|
||||
channel._running = True
|
||||
channel._save_state = lambda: None
|
||||
channel._save_state = lambda **_kwargs: None
|
||||
channel._print_qr_code = lambda url: None
|
||||
channel._api_get = AsyncMock(
|
||||
channel._api_post = AsyncMock(
|
||||
side_effect=[
|
||||
{"qrcode": "qr-1", "qrcode_img_content": "url-1"},
|
||||
{"qrcode": "qr-2", "qrcode_img_content": "url-2"},
|
||||
@@ -627,7 +765,7 @@ async def test_qr_login_returns_false_after_too_many_expired_qr_codes(
|
||||
channel, _bus = _make_channel()
|
||||
channel._running = True
|
||||
channel._print_qr_code = lambda url: None
|
||||
channel._api_get = AsyncMock(
|
||||
channel._api_post = AsyncMock(
|
||||
side_effect=[
|
||||
{"qrcode": "qr-1", "qrcode_img_content": "url-1"},
|
||||
{"qrcode": "qr-2", "qrcode_img_content": "url-2"},
|
||||
@@ -655,7 +793,7 @@ async def test_qr_login_switches_polling_base_url_on_redirect_status(
|
||||
) -> None:
|
||||
channel, _bus = _make_channel()
|
||||
channel._running = True
|
||||
channel._save_state = lambda: None
|
||||
channel._save_state = lambda **_kwargs: None
|
||||
channel._print_qr_code = lambda url: None
|
||||
channel._fetch_qr_code = AsyncMock(return_value=("qr-1", "url-1"))
|
||||
|
||||
@@ -689,7 +827,7 @@ async def test_qr_login_redirect_without_host_keeps_current_polling_base_url(
|
||||
) -> None:
|
||||
channel, _bus = _make_channel()
|
||||
channel._running = True
|
||||
channel._save_state = lambda: None
|
||||
channel._save_state = lambda **_kwargs: None
|
||||
channel._print_qr_code = lambda url: None
|
||||
channel._fetch_qr_code = AsyncMock(return_value=("qr-1", "url-1"))
|
||||
|
||||
@@ -723,7 +861,7 @@ async def test_qr_login_resets_redirect_base_url_after_qr_refresh(
|
||||
) -> None:
|
||||
channel, _bus = _make_channel()
|
||||
channel._running = True
|
||||
channel._save_state = lambda: None
|
||||
channel._save_state = lambda **_kwargs: None
|
||||
channel._print_qr_code = lambda url: None
|
||||
channel._fetch_qr_code = AsyncMock(side_effect=[("qr-1", "url-1"), ("qr-2", "url-2")])
|
||||
|
||||
@@ -1015,7 +1153,7 @@ async def test_qr_login_treats_temporary_connect_error_as_wait_and_recovers(
|
||||
) -> None:
|
||||
channel, _bus = _make_channel()
|
||||
channel._running = True
|
||||
channel._save_state = lambda: None
|
||||
channel._save_state = lambda **_kwargs: None
|
||||
channel._print_qr_code = lambda url: None
|
||||
channel._fetch_qr_code = AsyncMock(return_value=("qr-1", "url-1"))
|
||||
|
||||
@@ -1045,7 +1183,7 @@ async def test_qr_login_treats_5xx_gateway_response_error_as_wait_and_recovers(
|
||||
) -> None:
|
||||
channel, _bus = _make_channel()
|
||||
channel._running = True
|
||||
channel._save_state = lambda: None
|
||||
channel._save_state = lambda **_kwargs: None
|
||||
channel._print_qr_code = lambda url: None
|
||||
channel._fetch_qr_code = AsyncMock(return_value=("qr-1", "url-1"))
|
||||
|
||||
@@ -1438,7 +1576,7 @@ async def test_send_text_raises_on_api_error() -> None:
|
||||
return_value={"errcode": -14, "errmsg": "session expired"}
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="WeChat send text error.*-14"):
|
||||
with pytest.raises(WeixinAuthError, match="WeChat sendmessage failed.*errcode=-14"):
|
||||
await channel._send_text("wx-user", "hello", "ctx-expired")
|
||||
|
||||
channel._api_post.assert_awaited_once()
|
||||
@@ -1471,7 +1609,7 @@ async def test_send_text_raises_on_nonzero_ret_even_when_errcode_zero() -> None:
|
||||
return_value={"ret": -100, "errcode": 0, "errmsg": "internal error"}
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="WeChat send text error.*ret=-100.*errcode=0"):
|
||||
with pytest.raises(RuntimeError, match="WeChat sendmessage failed.*ret=-100.*errcode=0"):
|
||||
await channel._send_text("wx-user", "hello", "ctx-ok")
|
||||
|
||||
channel._api_post.assert_awaited_once()
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.weixin.manifest import SETUP_SPEC
|
||||
from nanobot.channels.weixin.runtime import (
|
||||
ITEM_TOOL_CALL_RESULT,
|
||||
ITEM_TOOL_CALL_START,
|
||||
WEIXIN_MAX_MESSAGE_LEN,
|
||||
WeixinAPIError,
|
||||
WeixinAuthError,
|
||||
WeixinChannel,
|
||||
WeixinConfig,
|
||||
WeixinQuotaError,
|
||||
sanitize_weixin_markdown,
|
||||
split_weixin_message,
|
||||
)
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
|
||||
def _channel(**config: object) -> WeixinChannel:
|
||||
return WeixinChannel(
|
||||
WeixinConfig.model_validate(
|
||||
{"enabled": True, "allowFrom": ["*"], **config}
|
||||
),
|
||||
MessageBus(),
|
||||
)
|
||||
|
||||
|
||||
def _ready_channel(**config: object) -> WeixinChannel:
|
||||
channel = _channel(**config)
|
||||
channel._client = object()
|
||||
channel._token = "bot-token"
|
||||
channel._context_tokens["wx-user"] = "ctx-1"
|
||||
channel._context_token_at["wx-user"] = time.time()
|
||||
channel._typing_tickets["wx-user"] = {
|
||||
"ticket": "",
|
||||
"next_fetch_at": time.time() + 3600,
|
||||
}
|
||||
return channel
|
||||
|
||||
|
||||
def test_weixin_defaults_protect_context_quota() -> None:
|
||||
config = WeixinConfig()
|
||||
|
||||
assert WEIXIN_MAX_MESSAGE_LEN == 1800
|
||||
assert config.send_progress is False
|
||||
assert config.send_tool_hints is False
|
||||
assert config.reply_progress_messages is False
|
||||
assert config.context_message_budget == 8
|
||||
assert config.block_streaming is False
|
||||
|
||||
|
||||
def test_weixin_webui_manifest_covers_runtime_configuration() -> None:
|
||||
runtime_fields = set(WeixinConfig().model_dump(mode="json", by_alias=True))
|
||||
|
||||
assert set(SETUP_SPEC.fields) == runtime_fields - {"enabled"}
|
||||
|
||||
|
||||
def test_reply_progress_opt_in_enables_progress_transport() -> None:
|
||||
config = WeixinConfig(reply_progress_messages=True)
|
||||
|
||||
assert config.send_progress is True
|
||||
assert config.send_tool_hints is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("section", "send_progress", "send_tool_hints"),
|
||||
[
|
||||
({"enabled": True}, False, False),
|
||||
({"enabled": True, "replyProgressMessages": True}, True, True),
|
||||
({"enabled": True, "sendProgress": True, "sendToolHints": False}, True, False),
|
||||
],
|
||||
)
|
||||
def test_channel_manager_preserves_weixin_quota_defaults(
|
||||
section: dict[str, object],
|
||||
send_progress: bool,
|
||||
send_tool_hints: bool,
|
||||
) -> None:
|
||||
manager = ChannelManager.__new__(ChannelManager)
|
||||
manager.config = Config.model_validate({"channels": {"weixin": section}})
|
||||
manager.bus = MessageBus()
|
||||
|
||||
channel = manager._build_channel("weixin", WeixinChannel, section)
|
||||
|
||||
assert channel.send_progress is send_progress
|
||||
assert channel.send_tool_hints is send_tool_hints
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_channel_manager_does_not_retry_permanent_weixin_error(monkeypatch) -> None:
|
||||
manager = ChannelManager.__new__(ChannelManager)
|
||||
manager.config = Config.model_validate({"channels": {"sendMaxRetries": 3}})
|
||||
manager.bus = MessageBus()
|
||||
channel = _channel()
|
||||
channel.send = AsyncMock(
|
||||
side_effect=WeixinAPIError(
|
||||
"sendmessage",
|
||||
errcode=-1,
|
||||
errmsg="business rejection",
|
||||
retryable=False,
|
||||
)
|
||||
)
|
||||
sleep = AsyncMock()
|
||||
monkeypatch.setattr("nanobot.channels.manager.asyncio.sleep", sleep)
|
||||
|
||||
await manager._send_with_retry(
|
||||
channel,
|
||||
OutboundMessage(channel="weixin", chat_id="wx-user", content="test"),
|
||||
)
|
||||
|
||||
channel.send.assert_awaited_once()
|
||||
sleep.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weixin_http_clients_ignore_system_proxy(tmp_path, monkeypatch) -> None:
|
||||
captured: list[dict[str, object]] = []
|
||||
|
||||
class FakeClient:
|
||||
async def aclose(self) -> None:
|
||||
return None
|
||||
|
||||
def make_client(**kwargs: object) -> FakeClient:
|
||||
captured.append(kwargs)
|
||||
return FakeClient()
|
||||
|
||||
monkeypatch.setattr("nanobot.channels.weixin.runtime.httpx.AsyncClient", make_client)
|
||||
|
||||
connect_channel = _channel(stateDir=str(tmp_path / "connect"))
|
||||
connect_channel.connect_open_client()
|
||||
await connect_channel.connect_close_client()
|
||||
|
||||
login_channel = _channel(stateDir=str(tmp_path / "login"))
|
||||
login_channel._qr_login = AsyncMock(return_value=True)
|
||||
assert await login_channel.login() is True
|
||||
|
||||
start_channel = _channel(token="configured-token", stateDir=str(tmp_path / "start"))
|
||||
|
||||
async def stop_after_poll() -> None:
|
||||
start_channel._running = False
|
||||
|
||||
start_channel._notify_lifecycle = AsyncMock()
|
||||
start_channel._poll_once = AsyncMock(side_effect=stop_after_poll)
|
||||
await start_channel.start()
|
||||
await start_channel.stop()
|
||||
|
||||
assert len(captured) == 3
|
||||
assert all(kwargs["trust_env"] is False for kwargs in captured)
|
||||
|
||||
|
||||
def test_markdown_sanitizer_preserves_code_and_escapes_bare_angles() -> None:
|
||||
content = "before <tag> `x<y>`\n```python\na<b\n```\n"
|
||||
|
||||
sanitized = sanitize_weixin_markdown(content)
|
||||
|
||||
assert "before <tag>" in sanitized
|
||||
assert "`x<y>`" in sanitized
|
||||
assert "a<b" in sanitized
|
||||
assert "![drop]" not in sanitized
|
||||
|
||||
|
||||
def test_markdown_split_balances_fences_and_stays_within_limit() -> None:
|
||||
chunks = split_weixin_message("```python\n" + ("x" * 4000) + "\n```")
|
||||
|
||||
assert len(chunks) >= 3
|
||||
assert all(len(chunk) <= WEIXIN_MAX_MESSAGE_LEN for chunk in chunks)
|
||||
assert all(chunk.count("```") % 2 == 0 for chunk in chunks)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_qr_fetch_posts_known_local_tokens(tmp_path) -> None:
|
||||
state_dir = tmp_path / "weixin"
|
||||
state_dir.mkdir()
|
||||
(state_dir / "account.json").write_text(
|
||||
json.dumps({"token": "persisted-token"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
channel = _channel(stateDir=str(state_dir))
|
||||
channel._api_post = AsyncMock(
|
||||
return_value={"qrcode": "qr-1", "qrcode_img_content": "https://qr.test/1"}
|
||||
)
|
||||
|
||||
assert await channel._fetch_qr_code() == ("qr-1", "https://qr.test/1")
|
||||
channel._api_post.assert_awaited_once_with(
|
||||
"ilink/bot/get_bot_qrcode?bot_type=3",
|
||||
{"local_token_list": ["persisted-token"]},
|
||||
auth=False,
|
||||
include_base_info=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_qr_fetch_retries_without_rejected_local_tokens(tmp_path) -> None:
|
||||
state_dir = tmp_path / "weixin"
|
||||
state_dir.mkdir()
|
||||
(state_dir / "account.json").write_text(
|
||||
json.dumps({"token": "invalid-token"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
channel = _channel(stateDir=str(state_dir))
|
||||
channel._api_post = AsyncMock(
|
||||
side_effect=[
|
||||
{"ret": -3},
|
||||
{"ret": 0, "qrcode": "qr-1", "qrcode_img_content": "https://qr.test/1"},
|
||||
]
|
||||
)
|
||||
|
||||
assert await channel._fetch_qr_code() == ("qr-1", "https://qr.test/1")
|
||||
assert [call.args[1] for call in channel._api_post.await_args_list] == [
|
||||
{"local_token_list": ["invalid-token"]},
|
||||
{"local_token_list": []},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_qr_fetch_does_not_retry_invalid_request_without_local_tokens(tmp_path) -> None:
|
||||
channel = _channel(stateDir=str(tmp_path / "weixin"))
|
||||
channel._api_post = AsyncMock(return_value={"ret": -3})
|
||||
|
||||
with pytest.raises(WeixinAPIError, match="get_bot_qrcode failed.*ret=-3"):
|
||||
await channel._fetch_qr_code()
|
||||
|
||||
channel._api_post.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lifecycle_notifications_are_best_effort() -> None:
|
||||
channel = _ready_channel()
|
||||
channel._api_post = AsyncMock(return_value={"ret": 0})
|
||||
|
||||
await channel._notify_lifecycle("start")
|
||||
await channel._notify_lifecycle("stop")
|
||||
|
||||
assert [call.args[0] for call in channel._api_post.await_args_list] == [
|
||||
"ilink/bot/msg/notifystart",
|
||||
"ilink/bot/msg/notifystop",
|
||||
]
|
||||
|
||||
|
||||
def test_business_errors_have_explicit_retry_contracts() -> None:
|
||||
channel = _channel()
|
||||
|
||||
with pytest.raises(WeixinQuotaError) as quota:
|
||||
channel._raise_for_api_error("sendmessage", {"ret": -2})
|
||||
with pytest.raises(WeixinAuthError) as auth:
|
||||
channel._raise_for_api_error("getupdates", {"errcode": -14})
|
||||
with pytest.raises(WeixinAPIError) as rejected:
|
||||
channel._raise_for_api_error("sendmessage", {"ret": -100})
|
||||
|
||||
assert channel.should_retry_send_error(quota.value) is False
|
||||
assert channel.should_retry_send_error(auth.value) is False
|
||||
assert channel.should_retry_send_error(rejected.value) is False
|
||||
assert channel.should_retry_send_error(httpx.ReadTimeout("slow")) is True
|
||||
|
||||
request = httpx.Request("POST", "https://ilinkai.weixin.qq.com/send")
|
||||
for status_code in (408, 425, 429, 503):
|
||||
response = httpx.Response(status_code, request=request)
|
||||
error = httpx.HTTPStatusError(
|
||||
"retryable response",
|
||||
request=request,
|
||||
response=response,
|
||||
)
|
||||
assert channel.should_retry_send_error(error) is True
|
||||
|
||||
rejected_response = httpx.Response(400, request=request)
|
||||
rejected_http = httpx.HTTPStatusError(
|
||||
"bad request",
|
||||
request=request,
|
||||
response=rejected_response,
|
||||
)
|
||||
assert channel.should_retry_send_error(rejected_http) is False
|
||||
|
||||
|
||||
def test_error_classification_checks_ret_and_errcode_independently() -> None:
|
||||
channel = _channel()
|
||||
|
||||
with pytest.raises(WeixinQuotaError):
|
||||
channel._raise_for_api_error(
|
||||
"sendmessage",
|
||||
{"ret": -2, "errcode": -100},
|
||||
)
|
||||
with pytest.raises(WeixinAuthError):
|
||||
channel._raise_for_api_error(
|
||||
"getupdates",
|
||||
{"ret": -14, "errcode": -100},
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_cancels_inflight_long_poll() -> None:
|
||||
channel = _channel(token="configured-token")
|
||||
poll_started = asyncio.Event()
|
||||
poll_cancelled = asyncio.Event()
|
||||
|
||||
class FakeClient:
|
||||
async def aclose(self) -> None:
|
||||
return None
|
||||
|
||||
async def blocking_poll() -> None:
|
||||
poll_started.set()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
except asyncio.CancelledError:
|
||||
poll_cancelled.set()
|
||||
raise
|
||||
|
||||
channel._new_http_client = lambda _timeout: FakeClient() # type: ignore[method-assign]
|
||||
channel._notify_lifecycle = AsyncMock()
|
||||
channel._poll_once = blocking_poll # type: ignore[method-assign]
|
||||
|
||||
start_task = asyncio.create_task(channel.start())
|
||||
await asyncio.wait_for(poll_started.wait(), timeout=1)
|
||||
await asyncio.wait_for(channel.stop(), timeout=1)
|
||||
await asyncio.wait_for(start_task, timeout=1)
|
||||
|
||||
assert poll_cancelled.is_set()
|
||||
assert channel._poll_task is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_retry_reuses_client_id_and_skips_completed_chunks() -> None:
|
||||
channel = _ready_channel()
|
||||
request = httpx.Request("POST", "https://ilinkai.weixin.qq.com/ilink/bot/sendmessage")
|
||||
channel._api_post = AsyncMock(
|
||||
side_effect=[
|
||||
{"ret": 0},
|
||||
httpx.ReadTimeout("ambiguous timeout", request=request),
|
||||
{"ret": 0},
|
||||
]
|
||||
)
|
||||
msg = OutboundMessage(
|
||||
channel="weixin",
|
||||
chat_id="wx-user",
|
||||
content="x" * (WEIXIN_MAX_MESSAGE_LEN + 200),
|
||||
)
|
||||
|
||||
with pytest.raises(httpx.ReadTimeout):
|
||||
await channel.send(msg)
|
||||
await channel.send(msg)
|
||||
|
||||
bodies = [call.args[1] for call in channel._api_post.await_args_list]
|
||||
client_ids = [body["msg"]["client_id"] for body in bodies]
|
||||
assert client_ids[0] != client_ids[1]
|
||||
assert client_ids[1] == client_ids[2]
|
||||
assert channel._context_send_counts["ctx-1"] == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_quota_rejection_defers_final_until_fresh_context() -> None:
|
||||
channel = _ready_channel()
|
||||
channel._api_post = AsyncMock(side_effect=[{"ret": -2}, {"ret": 0}])
|
||||
msg = OutboundMessage(
|
||||
channel="weixin",
|
||||
chat_id="wx-user",
|
||||
content="deferred answer",
|
||||
)
|
||||
|
||||
with pytest.raises(WeixinQuotaError):
|
||||
await channel.send(msg)
|
||||
first_client_id = channel._api_post.await_args_list[0].args[1]["msg"]["client_id"]
|
||||
assert "wx-user" in channel._deferred_outbound
|
||||
|
||||
channel._context_tokens["wx-user"] = "ctx-2"
|
||||
channel._context_token_at["wx-user"] = time.time()
|
||||
await channel._retry_deferred_messages("wx-user")
|
||||
|
||||
second_client_id = channel._api_post.await_args_list[1].args[1]["msg"]["client_id"]
|
||||
assert second_client_id == first_client_id
|
||||
assert "wx-user" not in channel._deferred_outbound
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_local_context_budget_stops_before_extra_api_call() -> None:
|
||||
channel = _ready_channel(contextMessageBudget=1)
|
||||
channel._api_post = AsyncMock(return_value={"ret": 0})
|
||||
|
||||
await channel._send_text("wx-user", "one", "ctx-1")
|
||||
with pytest.raises(WeixinQuotaError, match="local safety budget"):
|
||||
await channel._send_text("wx-user", "two", "ctx-1")
|
||||
|
||||
channel._api_post.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bounded_block_streaming_reserves_one_final_message() -> None:
|
||||
channel = _ready_channel(
|
||||
blockStreaming=True,
|
||||
blockStreamingMinChars=200,
|
||||
blockStreamingMaxMessages=3,
|
||||
)
|
||||
channel._send_text = AsyncMock()
|
||||
|
||||
await channel.send_delta("wx-user", "a" * 250, stream_id="stream-1")
|
||||
await channel.send_delta("wx-user", "b" * 250, stream_id="stream-1")
|
||||
await channel.send_delta("wx-user", "c" * 250, stream_id="stream-1")
|
||||
await channel.send_delta("wx-user", "done", stream_id="stream-1", stream_end=True)
|
||||
|
||||
assert channel._send_text.await_count == 3
|
||||
assert "stream-1" not in channel._stream_buffers
|
||||
assert "stream-1" not in channel._stream_sent_counts
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_structured_progress_is_capped_and_uses_one_run_id() -> None:
|
||||
channel = _ready_channel(
|
||||
replyProgressMessages=True,
|
||||
replyProgressMaxMessages=2,
|
||||
)
|
||||
channel._send_message_item = AsyncMock()
|
||||
events = [
|
||||
{"phase": "start", "call_id": "call-1", "name": "read_file"},
|
||||
{"phase": "end", "call_id": "call-1", "name": "read_file"},
|
||||
{"phase": "start", "call_id": "call-2", "name": "exec"},
|
||||
]
|
||||
|
||||
await channel.send(
|
||||
OutboundMessage(
|
||||
channel="weixin",
|
||||
chat_id="wx-user",
|
||||
content="read_file",
|
||||
event=ProgressEvent(content="read_file", tool_hint=True, tool_events=events),
|
||||
)
|
||||
)
|
||||
|
||||
assert channel._send_message_item.await_count == 2
|
||||
first = channel._send_message_item.await_args_list[0]
|
||||
second = channel._send_message_item.await_args_list[1]
|
||||
assert first.args[1]["type"] == ITEM_TOOL_CALL_START
|
||||
assert second.args[1]["type"] == ITEM_TOOL_CALL_RESULT
|
||||
assert first.kwargs["run_id"] == second.kwargs["run_id"]
|
||||
@@ -1,25 +1,148 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import {
|
||||
channelTranslator,
|
||||
type ChannelTranslator,
|
||||
} from "@/channel-plugins/i18n";
|
||||
import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";
|
||||
import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";
|
||||
import {
|
||||
ChannelQrConnectFlow,
|
||||
type ChannelQrConnectPendingContext,
|
||||
} from "@/components/settings/channels/ChannelQrConnectFlow";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { ChannelConnectPayload } from "@/lib/types";
|
||||
|
||||
type WeixinVerificationPayload = ChannelConnectPayload & {
|
||||
challenge: "verify_code";
|
||||
verification_failed?: boolean;
|
||||
};
|
||||
|
||||
export const WEIXIN_AUTH_EXPIRED_MESSAGE =
|
||||
"WeChat login expired. Scan again to reconnect.";
|
||||
|
||||
function isVerificationChallenge(
|
||||
payload: ChannelConnectPayload,
|
||||
): payload is WeixinVerificationPayload {
|
||||
return (
|
||||
"challenge" in payload
|
||||
&& payload.challenge === "verify_code"
|
||||
&& (
|
||||
!("verification_failed" in payload)
|
||||
|| typeof payload.verification_failed === "boolean"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function weixinConnectMessage(
|
||||
payload: ChannelConnectPayload,
|
||||
tx: ChannelTranslator,
|
||||
): string {
|
||||
if (payload.status === "succeeded") {
|
||||
return tx("custom.connected", "WeChat is connected.");
|
||||
}
|
||||
if (payload.status === "expired") {
|
||||
return tx("custom.expired", WEIXIN_AUTH_EXPIRED_MESSAGE);
|
||||
}
|
||||
if (payload.status === "failed") {
|
||||
return payload.message
|
||||
?? tx("custom.failed", "Unable to connect WeChat. Try again.");
|
||||
}
|
||||
if (payload.status === "cancelled") {
|
||||
return tx("custom.stopped", "WeChat login stopped.");
|
||||
}
|
||||
if (isVerificationChallenge(payload)) {
|
||||
return payload.verification_failed
|
||||
? tx(
|
||||
"custom.verifyMismatch",
|
||||
"That code did not match. Enter the new number shown in WeChat.",
|
||||
)
|
||||
: tx(
|
||||
"custom.verifyDescription",
|
||||
"Enter the number shown in WeChat to continue.",
|
||||
);
|
||||
}
|
||||
return tx("custom.waiting", "Waiting for WeChat scan...");
|
||||
}
|
||||
|
||||
export function WeixinConnectFlow({
|
||||
token,
|
||||
feature,
|
||||
idleLabel,
|
||||
connectRequestId,
|
||||
onFeaturesUpdate,
|
||||
}: ChannelPluginConnectFlowProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = channelTranslator(t, "weixin");
|
||||
const [verificationCode, setVerificationCode] = useState("");
|
||||
const authExpired = feature.runtime_error === WEIXIN_AUTH_EXPIRED_MESSAGE;
|
||||
const scanAgainLabel = t("settings.channels.scanAgain", {
|
||||
defaultValue: "Scan again",
|
||||
});
|
||||
|
||||
const renderVerification = ({
|
||||
connect,
|
||||
busy,
|
||||
poll,
|
||||
}: ChannelQrConnectPendingContext) => {
|
||||
if (!isVerificationChallenge(connect)) return null;
|
||||
return (
|
||||
<form
|
||||
className="mt-3 space-y-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const code = verificationCode.trim();
|
||||
if (!code) return;
|
||||
void poll({ verify_code: code }).then((payload) => {
|
||||
if (payload && !isVerificationChallenge(payload)) {
|
||||
setVerificationCode("");
|
||||
}
|
||||
});
|
||||
}}
|
||||
>
|
||||
<div className="text-[12px] font-semibold text-foreground">
|
||||
{tx("custom.verifyTitle", "Verification required")}
|
||||
</div>
|
||||
<p className="text-[12px] leading-5 text-muted-foreground">
|
||||
{weixinConnectMessage(connect, tx)}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={verificationCode}
|
||||
onChange={(event) => setVerificationCode(event.target.value)}
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
placeholder={tx("custom.verifyPlaceholder", "Code")}
|
||||
className="h-8 max-w-40"
|
||||
aria-invalid={connect.verification_failed || undefined}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
disabled={busy || !verificationCode.trim()}
|
||||
>
|
||||
{tx("custom.verifySubmit", "Verify")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<ChannelQrConnectFlow
|
||||
token={token}
|
||||
channelName="weixin"
|
||||
idleLabel={idleLabel}
|
||||
startOptions={{ force: authExpired }}
|
||||
idleLabel={authExpired ? scanAgainLabel : idleLabel}
|
||||
connectRequestId={connectRequestId}
|
||||
forceOnRepeat
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
pausePolling={isVerificationChallenge}
|
||||
suppressSucceeded={feature.runtime_status === "failed"}
|
||||
renderPending={renderVerification}
|
||||
resolveMessage={(payload) => weixinConnectMessage(payload, tx)}
|
||||
labels={{
|
||||
qrAlt: tx("custom.qrAlt", "WeChat login QR code"),
|
||||
scanTitle: tx("custom.scanTitle", "Scan with WeChat"),
|
||||
@@ -31,7 +154,7 @@ export function WeixinConnectFlow({
|
||||
connected: tx("custom.connected", "WeChat is connected."),
|
||||
stopped: tx("custom.stopped", "WeChat login stopped."),
|
||||
connecting: tx("custom.connecting", "Connecting..."),
|
||||
scanAgain: t("settings.channels.scanAgain", { defaultValue: "Scan again" }),
|
||||
scanAgain: scanAgainLabel,
|
||||
connect: t("settings.channels.connect", { defaultValue: "Connect" }),
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,553 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { Check, ChevronDown, ExternalLink, Loader2, Plus } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelFieldMessageKey, channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { channelLocaleMessages } from "@/channel-plugins/locale-registry";
|
||||
import type { ChannelPluginPanelProps } from "@/channel-plugins/types";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import {
|
||||
chatAppGuideUrl,
|
||||
docsUrlWithBase,
|
||||
type ChannelConfigField,
|
||||
} from "@/components/settings/channels/catalog";
|
||||
import {
|
||||
CredentialForm,
|
||||
channelValuesForSave,
|
||||
defaultChannelFieldValues,
|
||||
} from "@/components/settings/channels/CredentialForm";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
||||
import { normalizeLocale } from "@/i18n/config";
|
||||
import { configureChannel } from "@/lib/api";
|
||||
import { logoFallbackUrls } from "@/lib/provider-brand";
|
||||
import type {
|
||||
ChannelRuntimeStatus,
|
||||
ChannelSetupContractField,
|
||||
NanobotFeatureInfo,
|
||||
} from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import {
|
||||
WEIXIN_AUTH_EXPIRED_MESSAGE,
|
||||
WeixinConnectFlow,
|
||||
} from "./WeixinConnectFlow";
|
||||
|
||||
export const WEIXIN_PRIMARY_FIELD_KEYS = [
|
||||
"channels.weixin.sendProgress",
|
||||
"channels.weixin.sendToolHints",
|
||||
"channels.weixin.streaming",
|
||||
] as const;
|
||||
|
||||
export const WEIXIN_ADVANCED_FIELD_KEYS = [
|
||||
"channels.weixin.allowFrom",
|
||||
"channels.weixin.token",
|
||||
"channels.weixin.replyProgressMessages",
|
||||
"channels.weixin.replyProgressMaxMessages",
|
||||
"channels.weixin.contextMessageBudget",
|
||||
"channels.weixin.blockStreaming",
|
||||
"channels.weixin.blockStreamingMinChars",
|
||||
"channels.weixin.blockStreamingMaxMessages",
|
||||
"channels.weixin.baseUrl",
|
||||
"channels.weixin.cdnBaseUrl",
|
||||
"channels.weixin.routeTag",
|
||||
"channels.weixin.stateDir",
|
||||
"channels.weixin.pollTimeout",
|
||||
] as const;
|
||||
|
||||
export function WeixinPanel({
|
||||
token,
|
||||
feature,
|
||||
actionKey,
|
||||
chatAppsDocsUrl,
|
||||
showBrandLogos,
|
||||
onAction,
|
||||
onFeaturesUpdate,
|
||||
}: ChannelPluginPanelProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const channelTx = channelTranslator(t, "weixin");
|
||||
const runtimeError = weixinRuntimeError(feature.runtime_error, channelTx);
|
||||
const displayName = channelTx("displayName", "WeChat");
|
||||
const enabledBusy = actionKey === `enable:${feature.name}`;
|
||||
const disabledBusy = actionKey === `disable:${feature.name}`;
|
||||
const channelBusy = enabledBusy || disabledBusy;
|
||||
const channelChecked =
|
||||
feature.runtime_status === "running" || feature.runtime_status === "starting";
|
||||
const missingSupport = feature.enabled && !feature.installed;
|
||||
const alwaysEnabled = feature.capabilities?.includes("always_enabled") ?? false;
|
||||
const toggleChecked = alwaysEnabled || channelChecked;
|
||||
const channelToggleDisabled =
|
||||
alwaysEnabled
|
||||
|| channelBusy
|
||||
|| (!feature.install_supported && !feature.installed && !feature.enabled);
|
||||
const [connectRequestId, setConnectRequestId] = useState(0);
|
||||
const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});
|
||||
const [touchedFields, setTouchedFields] = useState<Set<string>>(() => new Set());
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveRevision, setSaveRevision] = useState(0);
|
||||
const [attemptedRevision, setAttemptedRevision] = useState(0);
|
||||
const [saveState, setSaveState] = useState<"idle" | "saved">("idle");
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const configValuesKey = JSON.stringify(feature.config_values ?? {});
|
||||
const setupFieldsKey = JSON.stringify(feature.setup?.fields ?? []);
|
||||
const configuredFields = useMemo(
|
||||
() => new Set(feature.configured_fields ?? []),
|
||||
[feature.configured_fields],
|
||||
);
|
||||
const onLabel = tx("settings.values.on", "On");
|
||||
const offLabel = tx("settings.values.off", "Off");
|
||||
const setupFields = weixinSetupFields(
|
||||
feature,
|
||||
i18n.resolvedLanguage ?? i18n.language,
|
||||
);
|
||||
const primaryFields = localizeBooleanFields(setupFields.primary, onLabel, offLabel);
|
||||
const advancedFields = localizeBooleanFields(setupFields.advanced, onLabel, offLabel);
|
||||
const editableFields = [...primaryFields, ...advancedFields];
|
||||
const docsUrl = docsUrlWithBase(chatAppGuideUrl("wechat"), chatAppsDocsUrl)
|
||||
?? chatAppGuideUrl("wechat");
|
||||
const [fieldValues, setFieldValues] = useState<Record<string, string>>(() =>
|
||||
defaultChannelFieldValues(editableFields, feature.config_values),
|
||||
);
|
||||
const fieldValuesRef = useRef(fieldValues);
|
||||
const touchedFieldsRef = useRef(touchedFields);
|
||||
const editableFieldsRef = useRef(editableFields);
|
||||
const saveContextRef = useRef({
|
||||
token,
|
||||
enabled: feature.enabled,
|
||||
onFeaturesUpdate,
|
||||
});
|
||||
editableFieldsRef.current = editableFields;
|
||||
saveContextRef.current = {
|
||||
token,
|
||||
enabled: feature.enabled,
|
||||
onFeaturesUpdate,
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const nextValues = defaultChannelFieldValues(editableFields, feature.config_values);
|
||||
for (const key of touchedFieldsRef.current) {
|
||||
nextValues[key] = fieldValuesRef.current[key] ?? "";
|
||||
}
|
||||
fieldValuesRef.current = nextValues;
|
||||
setFieldValues(nextValues);
|
||||
setVisibleSecrets({});
|
||||
}, [configValuesKey, setupFieldsKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (saveState !== "saved") return;
|
||||
const timeout = window.setTimeout(() => setSaveState("idle"), 1500);
|
||||
return () => window.clearTimeout(timeout);
|
||||
}, [saveState]);
|
||||
|
||||
const saveSettings = useCallback(async (
|
||||
values: Record<string, string>,
|
||||
savedFields: Set<string>,
|
||||
) => {
|
||||
const context = saveContextRef.current;
|
||||
setSaving(true);
|
||||
setSaveError(null);
|
||||
setSaveState("idle");
|
||||
try {
|
||||
const payload = await configureChannel(
|
||||
context.token,
|
||||
"weixin",
|
||||
channelValuesForSave(editableFieldsRef.current, values),
|
||||
{ enable: context.enabled },
|
||||
);
|
||||
const remainingFields = new Set(touchedFieldsRef.current);
|
||||
for (const key of savedFields) {
|
||||
if (fieldValuesRef.current[key] === values[key]) remainingFields.delete(key);
|
||||
}
|
||||
touchedFieldsRef.current = remainingFields;
|
||||
setTouchedFields(remainingFields);
|
||||
setSaveState(remainingFields.size ? "idle" : "saved");
|
||||
if (payload.nanobot_features) context.onFeaturesUpdate(payload.nanobot_features);
|
||||
} catch (err) {
|
||||
setSaveError((err as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!editableFields.length
|
||||
|| !touchedFields.size
|
||||
|| saving
|
||||
|| saveRevision <= attemptedRevision
|
||||
) return;
|
||||
const timeout = window.setTimeout(() => {
|
||||
setAttemptedRevision(saveRevision);
|
||||
void saveSettings(
|
||||
{ ...fieldValuesRef.current },
|
||||
new Set(touchedFieldsRef.current),
|
||||
);
|
||||
}, 500);
|
||||
return () => window.clearTimeout(timeout);
|
||||
}, [
|
||||
attemptedRevision,
|
||||
editableFields.length,
|
||||
saveRevision,
|
||||
saveSettings,
|
||||
saving,
|
||||
touchedFields.size,
|
||||
]);
|
||||
|
||||
const setFieldValue = (key: string, value: string) => {
|
||||
if (fieldValuesRef.current[key] === value) return;
|
||||
const nextValues = { ...fieldValuesRef.current, [key]: value };
|
||||
const nextTouchedFields = new Set(touchedFieldsRef.current).add(key);
|
||||
fieldValuesRef.current = nextValues;
|
||||
touchedFieldsRef.current = nextTouchedFields;
|
||||
setFieldValues(nextValues);
|
||||
setTouchedFields(nextTouchedFields);
|
||||
setSaveError(null);
|
||||
setSaveState("idle");
|
||||
setSaveRevision((current) => current + 1);
|
||||
};
|
||||
|
||||
const toggleAriaLabel = t("settings.channels.toggleChannel", {
|
||||
name: displayName,
|
||||
defaultValue: "{{name}} channel",
|
||||
});
|
||||
|
||||
return (
|
||||
<aside className="min-h-full rounded-[20px] bg-settings-surface p-5">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
<WeixinLogo showBrandLogos={showBrandLogos} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<h3 className="truncate text-[18px] font-semibold leading-6 text-foreground">
|
||||
{displayName}
|
||||
</h3>
|
||||
<p className="mt-1 text-[13px] leading-5 text-muted-foreground">
|
||||
{channelTx("description", "Use nanobot from WeChat conversations.")}
|
||||
</p>
|
||||
{missingSupport && feature.install_supported ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
disabled={enabledBusy}
|
||||
onClick={() => onAction("enable", feature.name)}
|
||||
className="mt-2 h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
>
|
||||
{enabledBusy ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
) : (
|
||||
<Plus className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
)}
|
||||
{tx("settings.nanobotFeatures.installSupport", "Install support")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2 pt-1">
|
||||
<WeixinStatusBadge status={feature.runtime_status}>
|
||||
{weixinStatusLabel(feature, tx)}
|
||||
</WeixinStatusBadge>
|
||||
{channelBusy ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" aria-hidden />
|
||||
) : null}
|
||||
<ToggleButton
|
||||
checked={toggleChecked}
|
||||
disabled={channelToggleDisabled}
|
||||
ariaLabel={toggleAriaLabel}
|
||||
label={toggleChecked ? onLabel : offLabel}
|
||||
onChange={(checked) => {
|
||||
if (checked && !channelChecked && feature.configured === false) {
|
||||
setConnectRequestId((current) => current + 1);
|
||||
return;
|
||||
}
|
||||
onAction(checked ? "enable" : "disable", feature.name);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{runtimeError ? (
|
||||
<div className="mt-4 rounded-[12px] border border-destructive/20 bg-destructive/5 px-3 py-2 text-[12px] leading-5 text-destructive">
|
||||
{runtimeError}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mt-4 space-y-4">
|
||||
<WeixinConnectFlow
|
||||
token={token}
|
||||
feature={feature}
|
||||
idleLabel={channelTx("setup.primaryAction", "Connect WeChat")}
|
||||
connectRequestId={connectRequestId}
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
/>
|
||||
|
||||
{primaryFields.length ? (
|
||||
<CredentialForm
|
||||
fields={primaryFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={setFieldValue}
|
||||
onToggleSecret={(key) => {
|
||||
setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));
|
||||
}}
|
||||
compact
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
className={cn(
|
||||
"flex items-center justify-end gap-1.5 text-[11px] leading-4 text-muted-foreground",
|
||||
!saving && saveState !== "saved" && "sr-only",
|
||||
)}
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<Loader2 className="h-3 w-3 animate-spin" aria-hidden />
|
||||
{tx("settings.actions.saving", "Saving")}
|
||||
</>
|
||||
) : saveState === "saved" ? (
|
||||
<>
|
||||
<Check className="h-3 w-3" aria-hidden />
|
||||
{tx("settings.channels.savedSettings", "Saved settings.")}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{saveError ? (
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded-[12px] border border-destructive/20 bg-destructive/5 px-3 py-2 text-[12px] leading-5 text-destructive"
|
||||
>
|
||||
{saveError}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{advancedFields.length ? (
|
||||
<details className="group text-[12px] leading-5 text-muted-foreground">
|
||||
<summary className="cursor-pointer list-none text-[12px] font-semibold text-foreground">
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
{tx("settings.channels.advanced", "Advanced")}
|
||||
<ChevronDown
|
||||
className="h-3.5 w-3.5 transition-transform group-open:rotate-180"
|
||||
aria-hidden
|
||||
/>
|
||||
</span>
|
||||
</summary>
|
||||
<div className="mt-3">
|
||||
<CredentialForm
|
||||
fields={advancedFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={setFieldValue}
|
||||
onToggleSecret={(key) => {
|
||||
setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));
|
||||
}}
|
||||
compact
|
||||
/>
|
||||
</div>
|
||||
</details>
|
||||
) : null}
|
||||
|
||||
<div className="flex justify-end">
|
||||
<WeixinGuideLink
|
||||
url={docsUrl}
|
||||
label={channelTx("setup.docsLabel", "Open WeChat setup")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function weixinSetupFields(
|
||||
feature: NanobotFeatureInfo,
|
||||
locale: string,
|
||||
): { primary: ChannelConfigField[]; advanced: ChannelConfigField[] } {
|
||||
const fields = feature.setup?.fields ?? [];
|
||||
const fieldsByKey = new Map(fields.map((field) => [field.key, field]));
|
||||
const messages = channelLocaleMessages("weixin", normalizeLocale(locale))?.setup;
|
||||
const knownKeys = new Set<string>([
|
||||
...WEIXIN_PRIMARY_FIELD_KEYS,
|
||||
...WEIXIN_ADVANCED_FIELD_KEYS,
|
||||
]);
|
||||
const extraKeys = fields
|
||||
.map((field) => field.key)
|
||||
.filter((key) => !knownKeys.has(key));
|
||||
const hydrate = (keys: readonly string[]) => keys.flatMap((key) => {
|
||||
const field = fieldsByKey.get(key);
|
||||
if (!field) return [];
|
||||
const copy = messages?.fields?.[channelFieldMessageKey("weixin", key)];
|
||||
return [weixinConfigField(field, copy)];
|
||||
});
|
||||
|
||||
return {
|
||||
primary: hydrate(WEIXIN_PRIMARY_FIELD_KEYS),
|
||||
advanced: hydrate([...WEIXIN_ADVANCED_FIELD_KEYS, ...extraKeys]),
|
||||
};
|
||||
}
|
||||
|
||||
function weixinConfigField(
|
||||
field: ChannelSetupContractField,
|
||||
copy: { label: string; placeholder?: string; help?: string; choices?: Record<string, string> }
|
||||
| undefined,
|
||||
): ChannelConfigField {
|
||||
const choices = field.kind === "bool" ? ["true", "false"] : field.choices;
|
||||
return {
|
||||
key: field.key,
|
||||
label: copy?.label ?? fieldLabel(field.field),
|
||||
placeholder: copy?.placeholder,
|
||||
help: copy?.help,
|
||||
secret: field.kind === "secret",
|
||||
optional: !field.required,
|
||||
inputType: field.kind === "int" ? "number" : undefined,
|
||||
defaultValue: field.default_value,
|
||||
options:
|
||||
field.kind === "enum" || field.kind === "bool"
|
||||
? choices.map((choice) => ({
|
||||
value: choice,
|
||||
label: copy?.choices?.[choice] ?? fieldLabel(choice),
|
||||
}))
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function fieldLabel(value: string): string {
|
||||
const spaced = value
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.replace(/[_-]+/g, " ")
|
||||
.trim();
|
||||
return spaced ? spaced[0].toUpperCase() + spaced.slice(1) : value;
|
||||
}
|
||||
|
||||
function WeixinLogo({ showBrandLogos }: { showBrandLogos: boolean }) {
|
||||
const logoUrls = useMemo(() => logoFallbackUrls("https://weixin.qq.com/favicon.ico"), []);
|
||||
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);
|
||||
if (showBrandLogos && logoUrl) {
|
||||
return (
|
||||
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-[12px] bg-background">
|
||||
<img
|
||||
src={logoUrl}
|
||||
alt=""
|
||||
decoding="async"
|
||||
loading="lazy"
|
||||
className="h-5.5 w-5.5 max-h-6 max-w-6 object-contain"
|
||||
onLoad={onLogoLoad}
|
||||
onError={onLogoError}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-[12px] bg-background text-[11px] font-bold"
|
||||
style={{ color: "#07C160" }}
|
||||
aria-hidden
|
||||
>
|
||||
WX
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function WeixinGuideLink({ url, label }: { url: string; label: string }) {
|
||||
const logoUrls = useMemo(() => logoFallbackUrls("https://weixin.qq.com/favicon.ico"), []);
|
||||
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);
|
||||
return (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="inline-flex max-w-full items-center gap-2 rounded-full bg-background/80 py-1 pl-1 pr-2.5 text-[11.5px] font-semibold text-foreground transition-colors hover:bg-background"
|
||||
>
|
||||
<span
|
||||
className="grid h-5 w-5 shrink-0 place-items-center overflow-hidden rounded-full bg-muted/70 text-[9px] font-bold"
|
||||
style={{ color: "#07C160" }}
|
||||
aria-hidden
|
||||
>
|
||||
{logoUrl ? (
|
||||
<img
|
||||
src={logoUrl}
|
||||
alt=""
|
||||
decoding="async"
|
||||
loading="lazy"
|
||||
className="h-3.5 w-3.5 object-contain"
|
||||
onLoad={onLogoLoad}
|
||||
onError={onLogoError}
|
||||
/>
|
||||
) : (
|
||||
"WX"
|
||||
)}
|
||||
</span>
|
||||
<span className="truncate">{label}</span>
|
||||
<ExternalLink className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function WeixinStatusBadge({
|
||||
children,
|
||||
status,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
status?: ChannelRuntimeStatus;
|
||||
}) {
|
||||
return (
|
||||
<span className={cn(
|
||||
"shrink-0 rounded-full px-2 py-0.5 text-[11px] font-medium leading-4",
|
||||
status === "failed"
|
||||
? "bg-destructive/10 text-destructive"
|
||||
: status === "running"
|
||||
? "bg-emerald-500/10 text-emerald-700 dark:text-emerald-200"
|
||||
: "bg-muted/75 text-muted-foreground",
|
||||
)}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function weixinStatusLabel(
|
||||
feature: NanobotFeatureInfo,
|
||||
tx: (key: string, fallback: string) => string,
|
||||
): string {
|
||||
if (feature.runtime_status === "failed") {
|
||||
return tx("settings.channels.runtimeFailed", "Failed");
|
||||
}
|
||||
if (feature.runtime_status === "starting") {
|
||||
return tx("settings.channels.runtimeStarting", "Starting");
|
||||
}
|
||||
if (feature.runtime_status === "running") return tx("settings.values.on", "On");
|
||||
if (feature.enabled) return tx("settings.channels.runtimeStopped", "Not running");
|
||||
return tx("settings.values.off", "Off");
|
||||
}
|
||||
|
||||
function weixinRuntimeError(
|
||||
error: string | undefined,
|
||||
tx: (key: string, fallback: string) => string,
|
||||
): string | undefined {
|
||||
if (error === WEIXIN_AUTH_EXPIRED_MESSAGE) {
|
||||
return tx("custom.expired", error);
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
function localizeBooleanFields(
|
||||
fields: ChannelConfigField[],
|
||||
onLabel: string,
|
||||
offLabel: string,
|
||||
): ChannelConfigField[] {
|
||||
return fields.map((field) => {
|
||||
const values = new Set(field.options?.map((option) => option.value));
|
||||
if (values.size !== 2 || !values.has("true") || !values.has("false")) return field;
|
||||
return {
|
||||
...field,
|
||||
options: field.options?.map((option) => ({
|
||||
...option,
|
||||
label: option.value === "true" ? onLabel : offLabel,
|
||||
})),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -2,8 +2,14 @@ import type { ChannelUiContribution } from "@/channel-plugins/types";
|
||||
import { chatAppGuideUrl } from "@/components/settings/channels/catalog";
|
||||
|
||||
import { WeixinConnectFlow } from "./WeixinConnectFlow";
|
||||
import {
|
||||
WEIXIN_ADVANCED_FIELD_KEYS,
|
||||
WEIXIN_PRIMARY_FIELD_KEYS,
|
||||
WeixinPanel,
|
||||
} from "./WeixinPanel";
|
||||
|
||||
export default {
|
||||
Panel: WeixinPanel,
|
||||
ConnectFlow: WeixinConnectFlow,
|
||||
canConnectBeforeConfigured: true,
|
||||
aliases: {
|
||||
@@ -18,10 +24,8 @@ export default {
|
||||
mode: "connect",
|
||||
command: "nanobot channels login weixin",
|
||||
docsUrl: chatAppGuideUrl("wechat"),
|
||||
manualFields: [
|
||||
{ key: "channels.weixin.allowFrom" },
|
||||
{ key: "channels.weixin.token" },
|
||||
],
|
||||
fields: WEIXIN_PRIMARY_FIELD_KEYS.map((key) => ({ key })),
|
||||
manualFields: WEIXIN_ADVANCED_FIELD_KEYS.map((key) => ({ key })),
|
||||
},
|
||||
},
|
||||
} satisfies ChannelUiContribution;
|
||||
|
||||
@@ -20,7 +20,21 @@
|
||||
"token": {
|
||||
"label": "Token",
|
||||
"placeholder": "Saved by QR login"
|
||||
}
|
||||
},
|
||||
"sendProgress": { "label": "Send progress" },
|
||||
"sendToolHints": { "label": "Send tool hints" },
|
||||
"streaming": { "label": "Use streaming API" },
|
||||
"replyProgressMessages": { "label": "Send structured progress" },
|
||||
"replyProgressMaxMessages": { "label": "Structured progress limit" },
|
||||
"contextMessageBudget": { "label": "Context message budget" },
|
||||
"blockStreaming": { "label": "Send response blocks" },
|
||||
"blockStreamingMinChars": { "label": "Minimum block size" },
|
||||
"blockStreamingMaxMessages": { "label": "Block message limit" },
|
||||
"baseUrl": { "label": "API URL" },
|
||||
"cdnBaseUrl": { "label": "CDN URL" },
|
||||
"routeTag": { "label": "Route tag" },
|
||||
"stateDir": { "label": "State directory" },
|
||||
"pollTimeout": { "label": "Poll timeout" }
|
||||
}
|
||||
},
|
||||
"custom": {
|
||||
@@ -30,6 +44,13 @@
|
||||
"waiting": "Waiting for WeChat scan...",
|
||||
"connected": "WeChat is connected.",
|
||||
"stopped": "WeChat login stopped.",
|
||||
"connecting": "Connecting..."
|
||||
"connecting": "Connecting...",
|
||||
"verifyTitle": "Verification required",
|
||||
"verifyDescription": "Enter the number shown in WeChat to continue.",
|
||||
"verifyMismatch": "That code did not match. Enter the new number shown in WeChat.",
|
||||
"expired": "WeChat login expired. Scan again to reconnect.",
|
||||
"failed": "Unable to connect WeChat. Try again.",
|
||||
"verifyPlaceholder": "Code",
|
||||
"verifySubmit": "Verify"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,21 @@
|
||||
"token": {
|
||||
"label": "Token",
|
||||
"placeholder": "Guardado al iniciar sesión por QR"
|
||||
}
|
||||
},
|
||||
"sendProgress": { "label": "Enviar progreso" },
|
||||
"sendToolHints": { "label": "Enviar indicaciones de herramientas" },
|
||||
"streaming": { "label": "Usar API de streaming" },
|
||||
"replyProgressMessages": { "label": "Enviar progreso estructurado" },
|
||||
"replyProgressMaxMessages": { "label": "Límite de progreso estructurado" },
|
||||
"contextMessageBudget": { "label": "Presupuesto de mensajes por contexto" },
|
||||
"blockStreaming": { "label": "Enviar respuestas por bloques" },
|
||||
"blockStreamingMinChars": { "label": "Tamaño mínimo del bloque" },
|
||||
"blockStreamingMaxMessages": { "label": "Límite de mensajes por bloques" },
|
||||
"baseUrl": { "label": "URL de la API" },
|
||||
"cdnBaseUrl": { "label": "URL de la CDN" },
|
||||
"routeTag": { "label": "Etiqueta de ruta" },
|
||||
"stateDir": { "label": "Directorio de estado" },
|
||||
"pollTimeout": { "label": "Tiempo de espera de consulta" }
|
||||
}
|
||||
},
|
||||
"custom": {
|
||||
@@ -30,6 +44,13 @@
|
||||
"waiting": "Esperando el escaneo de WeChat...",
|
||||
"connected": "WeChat está conectado.",
|
||||
"stopped": "Inicio de WeChat detenido.",
|
||||
"connecting": "Conectando..."
|
||||
"connecting": "Conectando...",
|
||||
"verifyTitle": "Se requiere verificación",
|
||||
"verifyDescription": "Introduce el número que aparece en WeChat para continuar.",
|
||||
"verifyMismatch": "El código no coincide. Introduce el nuevo número que aparece en WeChat.",
|
||||
"expired": "El inicio de sesión de WeChat caducó. Escanea de nuevo para volver a conectarte.",
|
||||
"failed": "No se pudo conectar WeChat. Inténtalo de nuevo.",
|
||||
"verifyPlaceholder": "Código",
|
||||
"verifySubmit": "Verificar"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,21 @@
|
||||
"token": {
|
||||
"label": "Jeton",
|
||||
"placeholder": "Enregistré après la connexion QR"
|
||||
}
|
||||
},
|
||||
"sendProgress": { "label": "Envoyer la progression" },
|
||||
"sendToolHints": { "label": "Envoyer les indications d’outils" },
|
||||
"streaming": { "label": "Utiliser l’API de streaming" },
|
||||
"replyProgressMessages": { "label": "Envoyer la progression structurée" },
|
||||
"replyProgressMaxMessages": { "label": "Limite de progression structurée" },
|
||||
"contextMessageBudget": { "label": "Budget de messages du contexte" },
|
||||
"blockStreaming": { "label": "Envoyer la réponse par blocs" },
|
||||
"blockStreamingMinChars": { "label": "Taille minimale d’un bloc" },
|
||||
"blockStreamingMaxMessages": { "label": "Limite de messages par blocs" },
|
||||
"baseUrl": { "label": "URL de l’API" },
|
||||
"cdnBaseUrl": { "label": "URL du CDN" },
|
||||
"routeTag": { "label": "Étiquette de routage" },
|
||||
"stateDir": { "label": "Répertoire d’état" },
|
||||
"pollTimeout": { "label": "Délai d’interrogation" }
|
||||
}
|
||||
},
|
||||
"custom": {
|
||||
@@ -30,6 +44,13 @@
|
||||
"waiting": "En attente du scan WeChat...",
|
||||
"connected": "WeChat est connecté.",
|
||||
"stopped": "Connexion WeChat arrêtée.",
|
||||
"connecting": "Connexion..."
|
||||
"connecting": "Connexion...",
|
||||
"verifyTitle": "Vérification requise",
|
||||
"verifyDescription": "Saisissez le nombre affiché dans WeChat pour continuer.",
|
||||
"verifyMismatch": "Le code ne correspond pas. Saisissez le nouveau nombre affiché dans WeChat.",
|
||||
"expired": "La connexion WeChat a expiré. Scannez à nouveau pour vous reconnecter.",
|
||||
"failed": "Impossible de connecter WeChat. Réessayez.",
|
||||
"verifyPlaceholder": "Code",
|
||||
"verifySubmit": "Vérifier"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,21 @@
|
||||
"token": {
|
||||
"label": "Token",
|
||||
"placeholder": "Disimpan saat login QR"
|
||||
}
|
||||
},
|
||||
"sendProgress": { "label": "Kirim progres" },
|
||||
"sendToolHints": { "label": "Kirim petunjuk alat" },
|
||||
"streaming": { "label": "Gunakan API streaming" },
|
||||
"replyProgressMessages": { "label": "Kirim progres terstruktur" },
|
||||
"replyProgressMaxMessages": { "label": "Batas progres terstruktur" },
|
||||
"contextMessageBudget": { "label": "Anggaran pesan konteks" },
|
||||
"blockStreaming": { "label": "Kirim respons per blok" },
|
||||
"blockStreamingMinChars": { "label": "Ukuran blok minimum" },
|
||||
"blockStreamingMaxMessages": { "label": "Batas pesan blok" },
|
||||
"baseUrl": { "label": "URL API" },
|
||||
"cdnBaseUrl": { "label": "URL CDN" },
|
||||
"routeTag": { "label": "Tag rute" },
|
||||
"stateDir": { "label": "Direktori status" },
|
||||
"pollTimeout": { "label": "Batas waktu polling" }
|
||||
}
|
||||
},
|
||||
"custom": {
|
||||
@@ -30,6 +44,13 @@
|
||||
"waiting": "Menunggu pemindaian WeChat...",
|
||||
"connected": "WeChat sudah terhubung.",
|
||||
"stopped": "Login WeChat dihentikan.",
|
||||
"connecting": "Menghubungkan..."
|
||||
"connecting": "Menghubungkan...",
|
||||
"verifyTitle": "Verifikasi diperlukan",
|
||||
"verifyDescription": "Masukkan angka yang ditampilkan di WeChat untuk melanjutkan.",
|
||||
"verifyMismatch": "Kode tidak cocok. Masukkan angka baru yang ditampilkan di WeChat.",
|
||||
"expired": "Login WeChat telah kedaluwarsa. Pindai lagi untuk menghubungkan kembali.",
|
||||
"failed": "Tidak dapat menghubungkan WeChat. Coba lagi.",
|
||||
"verifyPlaceholder": "Kode",
|
||||
"verifySubmit": "Verifikasi"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,21 @@
|
||||
"token": {
|
||||
"label": "トークン",
|
||||
"placeholder": "QR ログインで保存"
|
||||
}
|
||||
},
|
||||
"sendProgress": { "label": "進捗を送信" },
|
||||
"sendToolHints": { "label": "ツールのヒントを送信" },
|
||||
"streaming": { "label": "ストリーミング API を使用" },
|
||||
"replyProgressMessages": { "label": "構造化された進捗を送信" },
|
||||
"replyProgressMaxMessages": { "label": "構造化進捗の上限" },
|
||||
"contextMessageBudget": { "label": "コンテキストのメッセージ予算" },
|
||||
"blockStreaming": { "label": "応答をブロック単位で送信" },
|
||||
"blockStreamingMinChars": { "label": "最小ブロックサイズ" },
|
||||
"blockStreamingMaxMessages": { "label": "ブロックメッセージの上限" },
|
||||
"baseUrl": { "label": "API URL" },
|
||||
"cdnBaseUrl": { "label": "CDN URL" },
|
||||
"routeTag": { "label": "ルートタグ" },
|
||||
"stateDir": { "label": "状態ディレクトリ" },
|
||||
"pollTimeout": { "label": "ポーリングタイムアウト" }
|
||||
}
|
||||
},
|
||||
"custom": {
|
||||
@@ -30,6 +44,13 @@
|
||||
"waiting": "WeChat のスキャンを待っています...",
|
||||
"connected": "WeChat に接続しました。",
|
||||
"stopped": "WeChat ログインを停止しました。",
|
||||
"connecting": "接続中..."
|
||||
"connecting": "接続中...",
|
||||
"verifyTitle": "確認が必要です",
|
||||
"verifyDescription": "WeChat に表示された数字を入力してください。",
|
||||
"verifyMismatch": "コードが一致しません。WeChat に表示された新しい数字を入力してください。",
|
||||
"expired": "WeChat のログイン期限が切れました。再接続するにはもう一度スキャンしてください。",
|
||||
"failed": "WeChat に接続できません。もう一度お試しください。",
|
||||
"verifyPlaceholder": "コード",
|
||||
"verifySubmit": "確認"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,21 @@
|
||||
"token": {
|
||||
"label": "토큰",
|
||||
"placeholder": "QR 로그인으로 저장됨"
|
||||
}
|
||||
},
|
||||
"sendProgress": { "label": "진행 상황 보내기" },
|
||||
"sendToolHints": { "label": "도구 힌트 보내기" },
|
||||
"streaming": { "label": "스트리밍 API 사용" },
|
||||
"replyProgressMessages": { "label": "구조화된 진행 상황 보내기" },
|
||||
"replyProgressMaxMessages": { "label": "구조화된 진행 메시지 한도" },
|
||||
"contextMessageBudget": { "label": "컨텍스트 메시지 예산" },
|
||||
"blockStreaming": { "label": "응답을 블록으로 보내기" },
|
||||
"blockStreamingMinChars": { "label": "최소 블록 크기" },
|
||||
"blockStreamingMaxMessages": { "label": "블록 메시지 한도" },
|
||||
"baseUrl": { "label": "API URL" },
|
||||
"cdnBaseUrl": { "label": "CDN URL" },
|
||||
"routeTag": { "label": "경로 태그" },
|
||||
"stateDir": { "label": "상태 디렉터리" },
|
||||
"pollTimeout": { "label": "폴링 제한 시간" }
|
||||
}
|
||||
},
|
||||
"custom": {
|
||||
@@ -30,6 +44,13 @@
|
||||
"waiting": "WeChat 스캔을 기다리는 중...",
|
||||
"connected": "WeChat이 연결되었습니다.",
|
||||
"stopped": "WeChat 로그인이 중지되었습니다.",
|
||||
"connecting": "연결 중..."
|
||||
"connecting": "연결 중...",
|
||||
"verifyTitle": "인증 필요",
|
||||
"verifyDescription": "계속하려면 WeChat에 표시된 숫자를 입력하세요.",
|
||||
"verifyMismatch": "코드가 일치하지 않습니다. WeChat에 표시된 새 숫자를 입력하세요.",
|
||||
"expired": "WeChat 로그인이 만료되었습니다. 다시 연결하려면 다시 스캔하세요.",
|
||||
"failed": "WeChat에 연결할 수 없습니다. 다시 시도하세요.",
|
||||
"verifyPlaceholder": "코드",
|
||||
"verifySubmit": "인증"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,21 @@
|
||||
"token": {
|
||||
"label": "Token",
|
||||
"placeholder": "Salvo pelo login via QR"
|
||||
}
|
||||
},
|
||||
"sendProgress": { "label": "Enviar progresso" },
|
||||
"sendToolHints": { "label": "Enviar dicas de ferramentas" },
|
||||
"streaming": { "label": "Usar API de streaming" },
|
||||
"replyProgressMessages": { "label": "Enviar progresso estruturado" },
|
||||
"replyProgressMaxMessages": { "label": "Limite de progresso estruturado" },
|
||||
"contextMessageBudget": { "label": "Orçamento de mensagens do contexto" },
|
||||
"blockStreaming": { "label": "Enviar resposta em blocos" },
|
||||
"blockStreamingMinChars": { "label": "Tamanho mínimo do bloco" },
|
||||
"blockStreamingMaxMessages": { "label": "Limite de mensagens em blocos" },
|
||||
"baseUrl": { "label": "URL da API" },
|
||||
"cdnBaseUrl": { "label": "URL da CDN" },
|
||||
"routeTag": { "label": "Etiqueta de rota" },
|
||||
"stateDir": { "label": "Diretório de estado" },
|
||||
"pollTimeout": { "label": "Tempo limite da consulta" }
|
||||
}
|
||||
},
|
||||
"custom": {
|
||||
@@ -30,6 +44,13 @@
|
||||
"waiting": "Aguardando leitura do WeChat...",
|
||||
"connected": "WeChat está conectado.",
|
||||
"stopped": "Login do WeChat interrompido.",
|
||||
"connecting": "Conectando..."
|
||||
"connecting": "Conectando...",
|
||||
"verifyTitle": "Verificação necessária",
|
||||
"verifyDescription": "Digite o número exibido no WeChat para continuar.",
|
||||
"verifyMismatch": "O código não corresponde. Digite o novo número exibido no WeChat.",
|
||||
"expired": "O login do WeChat expirou. Escaneie novamente para reconectar.",
|
||||
"failed": "Não foi possível conectar o WeChat. Tente novamente.",
|
||||
"verifyPlaceholder": "Código",
|
||||
"verifySubmit": "Verificar"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,21 @@
|
||||
"token": {
|
||||
"label": "Token",
|
||||
"placeholder": "Được lưu khi đăng nhập QR"
|
||||
}
|
||||
},
|
||||
"sendProgress": { "label": "Gửi tiến trình" },
|
||||
"sendToolHints": { "label": "Gửi gợi ý công cụ" },
|
||||
"streaming": { "label": "Sử dụng API phát trực tiếp" },
|
||||
"replyProgressMessages": { "label": "Gửi tiến trình có cấu trúc" },
|
||||
"replyProgressMaxMessages": { "label": "Giới hạn tiến trình có cấu trúc" },
|
||||
"contextMessageBudget": { "label": "Ngân sách tin nhắn ngữ cảnh" },
|
||||
"blockStreaming": { "label": "Gửi phản hồi theo khối" },
|
||||
"blockStreamingMinChars": { "label": "Kích thước khối tối thiểu" },
|
||||
"blockStreamingMaxMessages": { "label": "Giới hạn tin nhắn theo khối" },
|
||||
"baseUrl": { "label": "URL API" },
|
||||
"cdnBaseUrl": { "label": "URL CDN" },
|
||||
"routeTag": { "label": "Thẻ định tuyến" },
|
||||
"stateDir": { "label": "Thư mục trạng thái" },
|
||||
"pollTimeout": { "label": "Thời gian chờ thăm dò" }
|
||||
}
|
||||
},
|
||||
"custom": {
|
||||
@@ -30,6 +44,13 @@
|
||||
"waiting": "Đang chờ quét WeChat...",
|
||||
"connected": "WeChat đã kết nối.",
|
||||
"stopped": "Đăng nhập WeChat đã dừng.",
|
||||
"connecting": "Đang kết nối..."
|
||||
"connecting": "Đang kết nối...",
|
||||
"verifyTitle": "Cần xác minh",
|
||||
"verifyDescription": "Nhập số hiển thị trong WeChat để tiếp tục.",
|
||||
"verifyMismatch": "Mã không khớp. Nhập số mới hiển thị trong WeChat.",
|
||||
"expired": "Đăng nhập WeChat đã hết hạn. Hãy quét lại để kết nối lại.",
|
||||
"failed": "Không thể kết nối WeChat. Hãy thử lại.",
|
||||
"verifyPlaceholder": "Mã",
|
||||
"verifySubmit": "Xác minh"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,21 @@
|
||||
"token": {
|
||||
"label": "令牌",
|
||||
"placeholder": "二维码登录后自动保存"
|
||||
}
|
||||
},
|
||||
"sendProgress": { "label": "发送进度消息" },
|
||||
"sendToolHints": { "label": "发送工具提示" },
|
||||
"streaming": { "label": "使用流式 API" },
|
||||
"replyProgressMessages": { "label": "发送结构化进度" },
|
||||
"replyProgressMaxMessages": { "label": "结构化进度消息上限" },
|
||||
"contextMessageBudget": { "label": "上下文消息预算" },
|
||||
"blockStreaming": { "label": "分块发送回复" },
|
||||
"blockStreamingMinChars": { "label": "最小分块字符数" },
|
||||
"blockStreamingMaxMessages": { "label": "分块消息上限" },
|
||||
"baseUrl": { "label": "API 地址" },
|
||||
"cdnBaseUrl": { "label": "CDN 地址" },
|
||||
"routeTag": { "label": "路由标签" },
|
||||
"stateDir": { "label": "状态目录" },
|
||||
"pollTimeout": { "label": "轮询超时" }
|
||||
}
|
||||
},
|
||||
"custom": {
|
||||
@@ -31,6 +45,13 @@
|
||||
"waiting": "正在等待微信扫码...",
|
||||
"connected": "微信已连接。",
|
||||
"stopped": "微信登录已停止。",
|
||||
"connecting": "正在连接..."
|
||||
"connecting": "正在连接...",
|
||||
"verifyTitle": "需要验证",
|
||||
"verifyDescription": "输入手机微信中显示的数字以继续。",
|
||||
"verifyMismatch": "验证码不匹配,请输入微信中显示的新数字。",
|
||||
"expired": "微信登录已过期,请重新扫码连接。",
|
||||
"failed": "无法连接微信,请重试。",
|
||||
"verifyPlaceholder": "验证码",
|
||||
"verifySubmit": "验证"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,21 @@
|
||||
"token": {
|
||||
"label": "權杖",
|
||||
"placeholder": "二維碼登入後自動儲存"
|
||||
}
|
||||
},
|
||||
"sendProgress": { "label": "傳送進度訊息" },
|
||||
"sendToolHints": { "label": "傳送工具提示" },
|
||||
"streaming": { "label": "使用串流 API" },
|
||||
"replyProgressMessages": { "label": "傳送結構化進度" },
|
||||
"replyProgressMaxMessages": { "label": "結構化進度訊息上限" },
|
||||
"contextMessageBudget": { "label": "上下文訊息預算" },
|
||||
"blockStreaming": { "label": "分塊傳送回覆" },
|
||||
"blockStreamingMinChars": { "label": "最小分塊字元數" },
|
||||
"blockStreamingMaxMessages": { "label": "分塊訊息上限" },
|
||||
"baseUrl": { "label": "API 位址" },
|
||||
"cdnBaseUrl": { "label": "CDN 位址" },
|
||||
"routeTag": { "label": "路由標籤" },
|
||||
"stateDir": { "label": "狀態目錄" },
|
||||
"pollTimeout": { "label": "輪詢逾時" }
|
||||
}
|
||||
},
|
||||
"custom": {
|
||||
@@ -31,6 +45,13 @@
|
||||
"waiting": "正在等待微信掃碼...",
|
||||
"connected": "微信已連接。",
|
||||
"stopped": "微信登入已停止。",
|
||||
"connecting": "正在連接..."
|
||||
"connecting": "正在連接...",
|
||||
"verifyTitle": "需要驗證",
|
||||
"verifyDescription": "輸入手機微信中顯示的數字以繼續。",
|
||||
"verifyMismatch": "驗證碼不符,請輸入微信中顯示的新數字。",
|
||||
"expired": "微信登入已過期,請重新掃碼連線。",
|
||||
"failed": "無法連接微信,請重試。",
|
||||
"verifyPlaceholder": "驗證碼",
|
||||
"verifySubmit": "驗證"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import QRCode from "qrcode";
|
||||
import { Check, Loader2, Network, RotateCcw } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -34,6 +34,14 @@ export type ChannelConnectStartOptions = {
|
||||
force?: boolean;
|
||||
};
|
||||
|
||||
export type ChannelQrConnectPendingContext = {
|
||||
connect: ChannelConnectPayload;
|
||||
busy: boolean;
|
||||
poll: (
|
||||
params?: Readonly<Record<string, string>>,
|
||||
) => Promise<ChannelConnectPayload | null>;
|
||||
};
|
||||
|
||||
export function ChannelQrConnectFlow({
|
||||
token,
|
||||
channelName,
|
||||
@@ -43,6 +51,10 @@ export function ChannelQrConnectFlow({
|
||||
forceOnRepeat = false,
|
||||
labels,
|
||||
onFeaturesUpdate,
|
||||
pausePolling,
|
||||
renderPending,
|
||||
resolveMessage,
|
||||
suppressSucceeded = false,
|
||||
}: {
|
||||
token: string;
|
||||
channelName: string;
|
||||
@@ -52,6 +64,10 @@ export function ChannelQrConnectFlow({
|
||||
forceOnRepeat?: boolean;
|
||||
labels: ChannelQrConnectLabels;
|
||||
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
|
||||
pausePolling?: (payload: ChannelConnectPayload) => boolean;
|
||||
renderPending?: (context: ChannelQrConnectPendingContext) => ReactNode;
|
||||
resolveMessage?: (payload: ChannelConnectPayload) => string | undefined;
|
||||
suppressSucceeded?: boolean;
|
||||
}) {
|
||||
const pageVisible = usePageVisibility();
|
||||
const { t } = useTranslation();
|
||||
@@ -72,6 +88,10 @@ export function ChannelQrConnectFlow({
|
||||
const pending = connect?.status === "pending";
|
||||
const succeeded = connect?.status === "succeeded";
|
||||
const canStart = !pending && !busy;
|
||||
const pollingPaused = Boolean(connect && pausePolling?.(connect));
|
||||
const displayMessage = connect
|
||||
? resolveMessage?.(connect) ?? connect.message
|
||||
: undefined;
|
||||
|
||||
useEffect(() => {
|
||||
if (!connect?.qr_url) {
|
||||
@@ -96,8 +116,14 @@ export function ChannelQrConnectFlow({
|
||||
}, [connect?.qr_url]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!connect?.session_id || connect.status !== "pending" || !pageVisible) return;
|
||||
if (
|
||||
!connect?.session_id
|
||||
|| connect.status !== "pending"
|
||||
|| pollingPaused
|
||||
|| !pageVisible
|
||||
) return;
|
||||
let cancelled = false;
|
||||
const sessionId = connect.session_id;
|
||||
const poll = async () => {
|
||||
if (pollInFlight.current) return;
|
||||
pollInFlight.current = true;
|
||||
@@ -105,7 +131,7 @@ export function ChannelQrConnectFlow({
|
||||
const payload = await pollChannelConnect(
|
||||
tokenRef.current,
|
||||
channelName,
|
||||
connect.session_id,
|
||||
sessionId,
|
||||
);
|
||||
if (cancelled) return;
|
||||
setConnect((current) => ({
|
||||
@@ -142,6 +168,7 @@ export function ChannelQrConnectFlow({
|
||||
connect?.status,
|
||||
onFeaturesUpdate,
|
||||
pageVisible,
|
||||
pollingPaused,
|
||||
]);
|
||||
|
||||
const start = useCallback(async (force = false) => {
|
||||
@@ -188,6 +215,40 @@ export function ChannelQrConnectFlow({
|
||||
}
|
||||
};
|
||||
|
||||
const submitPoll = async (
|
||||
params: Readonly<Record<string, string>> = {},
|
||||
): Promise<ChannelConnectPayload | null> => {
|
||||
if (!connect?.session_id) return null;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const payload = await pollChannelConnect(
|
||||
tokenRef.current,
|
||||
channelName,
|
||||
connect.session_id,
|
||||
"",
|
||||
params,
|
||||
);
|
||||
setConnect((current) => ({
|
||||
...(current ?? payload),
|
||||
...payload,
|
||||
qr_url: payload.qr_url ?? current?.qr_url,
|
||||
}));
|
||||
if (payload.nanobot_features) {
|
||||
onFeaturesUpdate(payload.nanobot_features);
|
||||
}
|
||||
if (payload.status !== "pending") {
|
||||
setError(null);
|
||||
}
|
||||
return payload;
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
return null;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mt-3 space-y-3">
|
||||
{pending ? (
|
||||
@@ -210,10 +271,12 @@ export function ChannelQrConnectFlow({
|
||||
<p className="mt-1 text-[12.5px] leading-5 text-muted-foreground">
|
||||
{labels.scanDescription}
|
||||
</p>
|
||||
<div className="mt-3 flex items-center gap-2 text-[12px] text-muted-foreground">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
{labels.waiting}
|
||||
</div>
|
||||
{renderPending?.({ connect, busy, poll: submitPoll }) ?? (
|
||||
<div className="mt-3 flex items-center gap-2 text-[12px] text-muted-foreground">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
{labels.waiting}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-4 flex flex-wrap justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
@@ -230,16 +293,16 @@ export function ChannelQrConnectFlow({
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{succeeded ? (
|
||||
{succeeded && !suppressSucceeded ? (
|
||||
<div className="flex items-center gap-2 rounded-[12px] border border-emerald-500/20 px-3 py-2 text-[12px] font-medium text-emerald-700 dark:text-emerald-200">
|
||||
<Check className="h-3.5 w-3.5" aria-hidden />
|
||||
{connect.message ?? labels.connected}
|
||||
{displayMessage ?? labels.connected}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{connect && ["expired", "failed", "cancelled"].includes(connect.status) ? (
|
||||
<div className="rounded-[12px] border border-border/60 px-3 py-2 text-[12px] leading-5 text-muted-foreground">
|
||||
{connect.message || labels.stopped}
|
||||
{displayMessage || labels.stopped}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -627,9 +627,13 @@ export async function pollChannelConnect(
|
||||
channel: string,
|
||||
sessionId: string,
|
||||
base: string = "",
|
||||
params: Readonly<Record<string, string>> = {},
|
||||
): Promise<ChannelConnectPayload> {
|
||||
const query = new URLSearchParams();
|
||||
query.set("session_id", sessionId);
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (key !== "session_id") query.set(key, value);
|
||||
});
|
||||
return request<ChannelConnectPayload>(
|
||||
`${base}/api/settings/channels/${channel}/connect/poll?${query}`,
|
||||
token,
|
||||
|
||||
Reference in New Issue
Block a user