fix(whatsapp): report libmagic dependency failures

Co-authored-by: Pratik Parmar <steveparmar6nov2011@gmail.com>
This commit is contained in:
chengyongruandPratik Parmar authored and chengyongru committed 2026-11-03 14:17:51 +08:00
1 parent 36094bcf2c
commit cc4dd1cebf
5 files changed
+200 -9

No files matched your search

+1
View File
@@ -97,6 +97,7 @@ Send the message again after approval. Confirm that your private chat now receiv
## Troubleshooting
- If WhatsApp cannot load `libmagic`, install it with `brew install libmagic` on macOS or `sudo apt install libmagic1` on Debian/Ubuntu. On Windows, check the `python-magic-bin` installation and Python architecture.
- If QR linking fails, rerun `nanobot channels login whatsapp`.
- If you are migrating from the old bridge, remove `bridgeUrl` and `bridgeToken`, then re-login.
- If a sender appears as a LID instead of a phone number, let nanobot learn the mapping at runtime or use `lidMappings` in the full reference.
@@ -1545,6 +1545,34 @@ async def test_channel_connect_runtime_import_error_is_not_reported_as_unsupport
assert "failed to start fake connection" in response.text
@pytest.mark.asyncio
async def test_whatsapp_connect_reports_libmagic_failure(
bus: MagicMock,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
from nanobot.channels.whatsapp import runtime as whatsapp
from nanobot.channels.whatsapp.manifest import PLUGIN
monkeypatch.setattr(
"nanobot.webui.settings_routes.load_channel_plugin", lambda _name: PLUGIN,
)
def missing_libmagic():
raise whatsapp.WhatsAppDependencyError("WhatsApp could not load libmagic.")
monkeypatch.setattr(whatsapp, "_load_neonize", missing_libmagic)
channel = _ch(bus, session_manager=_seed_session(tmp_path), port=_free_port())
response = await _webui_mutate(
channel,
"settings.channel.connect.start",
{"channel": "whatsapp", "force": True},
)
assert response.status_code == 400
assert "WhatsApp could not load libmagic" in response.text
@pytest.mark.asyncio
async def test_feishu_connect_routes_write_config_and_hot_reload(
bus: MagicMock,
+6 -1
View File
@@ -98,7 +98,12 @@ class WhatsAppConnectStore:
if session is not None:
session.qr_url = qr_data.decode("utf-8")
client, result = channel.connect_open_client(capture_qr)
from nanobot.channels.whatsapp.runtime import WhatsAppDependencyError
try:
client, result = channel.connect_open_client(capture_qr)
except WhatsAppDependencyError as exc:
raise ChannelConnectError(str(exc)) from exc
connect_task = asyncio.create_task(
self._connect(channel, client, result),
name=f"whatsapp-connect-{session_id}",
+52 -8
View File
@@ -6,6 +6,7 @@ import asyncio
import mimetypes
import re
import secrets
import sys
import time
from collections import OrderedDict
from collections.abc import Awaitable, Callable
@@ -15,6 +16,7 @@ from typing import Any, Literal, NamedTuple, cast
from urllib.parse import urlparse
import httpx
from loguru import logger
from pydantic import Field
from nanobot.bus.delivery import ChannelNotReadyError
@@ -39,6 +41,10 @@ class WhatsAppConfig(Base):
lid_mappings: dict[str, str] = Field(default_factory=dict)
class WhatsAppDependencyError(RuntimeError):
"""A dependency failure with a safe, actionable message."""
class _NeonizeAPI(NamedTuple):
NewAClient: Any
ConnectedEv: Any
@@ -80,6 +86,16 @@ def _legacy_bridge_config_fields(config: dict[str, Any]) -> list[str]:
return [field for field in _LEGACY_BRIDGE_CONFIG_FIELDS if field in config]
def _libmagic_error_message() -> str:
if sys.platform == "darwin":
hint = "Install it with: brew install libmagic"
elif sys.platform == "win32":
hint = "Check the python-magic-bin installation and Python architecture."
else:
hint = "Install your system's libmagic package (Debian/Ubuntu: sudo apt install libmagic1)."
return f"WhatsApp could not load libmagic. {hint}"
def _load_neonize() -> _NeonizeAPI:
global _NEONIZE_API
if _NEONIZE_API is not None:
@@ -87,17 +103,42 @@ def _load_neonize() -> _NeonizeAPI:
try:
import magic
except ModuleNotFoundError as exc:
if exc.name != "magic":
raise
logger.exception("Could not load WhatsApp python-magic")
raise WhatsAppDependencyError(
"WhatsApp requires python-magic (python-magic-bin on Windows). "
"Run: nanobot plugins enable whatsapp"
) from exc
except (ImportError, OSError) as exc:
detail = str(exc).lower()
if not (
isinstance(exc, ImportError) and "failed to find libmagic" in detail
or isinstance(exc, OSError) and "libmagic" in detail
):
raise
logger.exception("Could not load WhatsApp libmagic")
raise WhatsAppDependencyError(_libmagic_error_message()) from exc
detect_mime = getattr(magic, "from_file", None)
detect_buffer = getattr(magic, "from_buffer", None)
if not callable(detect_mime) or not callable(detect_buffer):
raise WhatsAppDependencyError(
"The magic module is incompatible. Check python-magic "
"(python-magic-bin on Windows) in nanobot's Python environment."
)
try:
from neonize.aioze.client import NewAClient
from neonize.aioze.events import ConnectedEv, DisconnectedEv, MessageEv, PairStatusEv
from neonize.utils.jid import build_jid
detect_mime = getattr(magic, "from_file", None)
detect_buffer = getattr(magic, "from_buffer", None)
if not callable(detect_mime) or not callable(detect_buffer):
raise ImportError("python-magic does not expose from_file/from_buffer")
except ImportError as exc:
raise RuntimeError(
"WhatsApp dependencies not installed. Run: nanobot plugins enable whatsapp"
except ModuleNotFoundError as exc:
if exc.name != "neonize":
raise
logger.exception("Could not load WhatsApp Neonize")
raise WhatsAppDependencyError(
"Neonize is not installed. Run: nanobot plugins enable whatsapp"
) from exc
_NEONIZE_API = _NeonizeAPI(
@@ -305,6 +346,9 @@ class WhatsAppChannel(BaseChannel):
def default_config(cls) -> dict[str, Any]:
return WhatsAppConfig().model_dump(by_alias=True)
def start_error_message(self, error: Exception) -> str | None:
return str(error) if isinstance(error, WhatsAppDependencyError) else None
def __init__(
self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,
):
@@ -0,0 +1,113 @@
from __future__ import annotations
import builtins
import sys
import types
import pytest
from nanobot.bus.queue import MessageBus
from nanobot.channels.whatsapp import runtime
def _fail_import(monkeypatch, module, error):
original = builtins.__import__
def import_with_failure(name, *args, **kwargs):
if name == module:
raise error
return original(name, *args, **kwargs)
monkeypatch.setattr(builtins, "__import__", import_with_failure)
monkeypatch.setattr(runtime, "_NEONIZE_API", None)
@pytest.mark.parametrize(
("module", "error", "expected", "platform", "hint"),
[
(
"magic", ModuleNotFoundError("No module named 'magic'", name="magic"),
"python-magic", "linux", "nanobot plugins enable whatsapp",
),
(
"magic", ImportError("failed to find libmagic. Check your installation"),
"libmagic", "darwin", "brew install libmagic",
),
(
"magic", ImportError("failed to find libmagic. Check your installation"),
"libmagic", "linux", "apt install libmagic1",
),
(
"magic", OSError("Could not load libmagic.dll"),
"libmagic", "win32", "python-magic-bin",
),
(
"neonize.aioze.client",
ModuleNotFoundError("No module named 'neonize'", name="neonize"),
"Neonize", "linux", "nanobot plugins enable whatsapp",
),
],
)
def test_dependency_failure_reports_the_actual_dependency(
monkeypatch, module, error, expected, platform, hint,
):
monkeypatch.setattr(runtime, "sys", types.SimpleNamespace(platform=platform))
if module != "magic":
magic = types.ModuleType("magic")
magic.from_file = lambda *args, **kwargs: "text/plain"
magic.from_buffer = lambda *args, **kwargs: "text/plain"
monkeypatch.setitem(sys.modules, "magic", magic)
_fail_import(monkeypatch, module, error)
with pytest.raises(RuntimeError, match=expected) as caught:
runtime._load_neonize()
assert caught.value.__cause__ is error
assert hint in str(caught.value)
def test_incompatible_magic_module_has_an_actionable_error(monkeypatch):
monkeypatch.setitem(sys.modules, "magic", types.ModuleType("magic"))
monkeypatch.setattr(runtime, "_NEONIZE_API", None)
with pytest.raises(RuntimeError, match="magic.*python-magic"):
runtime._load_neonize()
@pytest.mark.parametrize(
"error",
[
ModuleNotFoundError("No module named 'magic_dependency'", name="magic_dependency"),
ImportError("cannot import name 'libmagic' from 'magic'"),
],
)
def test_unrelated_magic_import_failure_is_not_misreported(monkeypatch, error):
_fail_import(monkeypatch, "magic", error)
with pytest.raises(type(error)) as caught:
runtime._load_neonize()
assert caught.value is error
@pytest.mark.asyncio
async def test_missing_libmagic_is_visible_in_gateway_status(monkeypatch, tmp_path):
from nanobot.channels import registry
from nanobot.channels.manager import ChannelManager
from nanobot.channels.whatsapp.manifest import PLUGIN
from nanobot.config.schema import Config
monkeypatch.setattr(registry, "discover_plugins", lambda: {"whatsapp": PLUGIN})
monkeypatch.setattr(
"nanobot.optional_features.ensure_enabled_channel_dependencies", lambda *_: {},
)
bus = MessageBus()
config = Config.model_validate({"channels": {"whatsapp": {"enabled": True}}})
manager = ChannelManager(config, bus, config_path=tmp_path / "config.json")
channel = manager.channels["whatsapp"]
_fail_import(
monkeypatch, "magic", ImportError("failed to find libmagic. Check your installation"),
)
await manager._start_channel("whatsapp", channel)
assert "libmagic" in manager.get_status()["whatsapp"]["error"]