Skip to content

Your lightweight open-source personal agent.

fix(napcat): keep a message whose image declares a non-numeric size

Lengshuang17684ca5c4a4
diff --git a/nanobot/channels/napcat/runtime.py b/nanobot/channels/napcat/runtime.py
index 515d9d870..12e4a35be 100644
--- a/nanobot/channels/napcat/runtime.py
+++ b/nanobot/channels/napcat/runtime.py
@@ -549,6 +549,16 @@ class NapcatChannel(BaseChannel):
return None
except (TypeError, KeyError):
pass
+ except ValueError:
+ # Napcat reports file_size as a string, and it is not always numeric.
+ # Skip the upfront check; the streamed download below still caps the
+ # image at max_bytes, so nothing unbounded reaches disk.
+ logger.warning(
+ "napcat: unparsable image file_size={!r} url={}, enforcing the size cap "
+ "while streaming",
+ info["file_size"],
+ url,
+ )
try:
async with self._http.get(url, allow_redirects=False) as resp:
diff --git a/nanobot/channels/napcat/tests/test_napcat_channel.py b/nanobot/channels/napcat/tests/test_napcat_channel.py
index 0b89e3a7a..46dc22cc9 100644
--- a/nanobot/channels/napcat/tests/test_napcat_channel.py
+++ b/nanobot/channels/napcat/tests/test_napcat_channel.py
@@ -1,4 +1,5 @@
import asyncio
+from pathlib import Path
import pytest
@@ -163,6 +164,59 @@ async def test_download_image_rejects_redirects(tmp_path, monkeypatch) -> None:
assert list(tmp_path.iterdir()) == []
+async def test_download_image_ignores_unparsable_declared_size(tmp_path, monkeypatch) -> None:
+ channel = _channel()
+ channel._media_root = tmp_path
+ channel._http = _FakeHttp(_FakeResponse(status=200, chunks=[b"png-bytes"]))
+ monkeypatch.setattr(
+ "nanobot.channels.napcat.runtime.validate_url_target",
+ lambda _url: (True, ""),
+ )
+
+ for declared in ("", "unknown", "12KB"):
+ result = await channel._download_image(
+ {"url": "https://example.com/a.png", "file": "a.png", "file_size": declared}
+ )
+ assert result is not None, declared
+ assert Path(result).read_bytes() == b"png-bytes"
+
+
+async def test_message_with_unparsable_image_size_still_routes(tmp_path, monkeypatch) -> None:
+ channel = _channel()
+ channel._media_root = tmp_path
+ channel._http = _FakeHttp(_FakeResponse(status=200, chunks=[b"png-bytes"]))
+ monkeypatch.setattr(
+ "nanobot.channels.napcat.runtime.validate_url_target",
+ lambda _url: (True, ""),
+ )
+
+ await channel._on_message(
+ {
+ "message_id": 7,
+ "message_type": "private",
+ "user_id": "user1",
+ "sender": {"nickname": "Alice"},
+ "message": [
+ {"type": "text", "data": {"text": "look at this"}},
+ {
+ "type": "image",
+ "data": {
+ "url": "https://example.com/a.png",
+ "file": "a.png",
+ "file_size": "",
+ },
+ },
+ ],
+ }
+ )
+
+ msg = await channel.bus.consume_inbound()
+ assert msg.content == "look at this"
+ assert msg.media == [str(tmp_path / "a.png")]
+
+
@pytest.mark.asyncio
async def test_dispatch_tracks_and_discards_background_tasks() -> None:
channel = _channel()