fix(session): replay user images from stored attachments (#6720)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-19 15:53:57 +08:00
1 parent 488b657ee1
commit 3025a01cf0
29 files changed
+453 -278

No files matched your search

+1
View File
@@ -60,6 +60,7 @@ def _isolate_runtime_stores(
return path
monkeypatch.setattr(session_location, "get_runtime_subdir", runtime_subdir)
monkeypatch.setattr("nanobot.session.image_attachments.get_data_dir", data_dir)
monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: runtime_subdir("webui"))
monkeypatch.setattr(star_prompt, "get_webui_dir", lambda: runtime_subdir("webui"))
monkeypatch.setattr(pairing_store, "_store_path", lambda: data_dir() / "pairing.json")
+8 -10
View File
@@ -19,7 +19,7 @@ from nanobot.runtime_context import (
from nanobot.security.workspace_access import WorkspaceScopeResolver
from nanobot.session.manager import Session
from nanobot.session.summary import SessionSummary
from nanobot.utils.helpers import detect_image_mime, image_placeholder_text, load_bundled_template
from nanobot.utils.helpers import detect_image_mime, load_bundled_template
from nanobot.utils.prompt_templates import render_template
@@ -354,28 +354,26 @@ class ContextBuilder:
image_paths: list[str] | None,
) -> str | list[dict[str, Any]]:
"""Build user message content from prefiltered image paths."""
if not image_paths:
return text
media_blocks: list[dict[str, Any]] = []
for path in image_paths:
for path in image_paths or ():
p = Path(path)
try:
if not p.is_file():
continue
raw = p.read_bytes()
# Re-detect from the bytes used for the request: the file may have
# changed since attachment routing, and the data URL needs its MIME.
except OSError:
continue
mime = detect_image_mime(raw) or mimetypes.guess_type(path)[0]
if not mime or not mime.startswith("image/"):
continue
b64 = base64.b64encode(raw).decode()
media_blocks.append({"type": "text", "text": image_placeholder_text(str(p))})
media_blocks.append({
"type": "image_url",
"image_url": {"url": f"data:{mime};base64,{b64}"},
"_meta": {"path": str(p)},
})
if not media_blocks:
return text
return media_blocks + [{"type": "text", "text": text}]
if text:
media_blocks.append({"type": "text", "text": text})
return media_blocks
+33 -25
View File
@@ -86,6 +86,7 @@ from nanobot.security.workspace_access import (
from nanobot.session import turn_continuation
from nanobot.session.automation_turns import automation_history_overrides
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from nanobot.session.image_attachments import persist_user_image_blocks
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, Session, SessionManager, SessionPolicy
from nanobot.session.message_metadata import input_history_metadata, persisted_message
from nanobot.session.model_selection import (
@@ -110,7 +111,7 @@ from nanobot.session.summary import (
SessionSummaryCheckpoint,
)
from nanobot.triggers.local_turns import LocalTriggerTurnCoordinator
from nanobot.utils.cancellation import task_is_cancelling
from nanobot.utils.cancellation import shield_and_drain, task_is_cancelling
from nanobot.utils.document import reference_non_image_attachments
from nanobot.utils.helpers import image_placeholder_text
from nanobot.utils.llm_runtime import LLMRuntime
@@ -748,10 +749,12 @@ class AgentLoop:
if text_override is not None:
text = text_override
extra.update(automation_extra)
text, runtime_context_meta = append_runtime_context(
text,
runtime_context_blocks or (),
)
user_content = await self.runner.prepare_prompt(
self.context.build_user_content, text, image_paths=media_paths,
) if media_paths else text
if isinstance(user_content, list) and session.policy.persist:
user_content = await shield_and_drain(asyncio.to_thread(persist_user_image_blocks, user_content))
content, runtime_context_meta = append_runtime_context(user_content, runtime_context_blocks or ())
if runtime_context_meta is not None:
extra[RUNTIME_CONTEXT_HISTORY_META] = runtime_context_meta
if INBOUND_META_MODEL_OPTIONS in msg.metadata:
@@ -762,7 +765,7 @@ class AgentLoop:
session.metadata.update(SessionModelPreset(
selection.base_preset, ModelOptions.parse(msg.metadata[INBOUND_META_MODEL_OPTIONS]),
).metadata_update())
session.add_message("user", text, **extra)
session.add_message("user", content, **extra)
self._mark_pending_user_turn(session)
followup_id = msg.metadata.get(PENDING_FOLLOWUP_ID_KEY)
if isinstance(followup_id, str) and followup_id:
@@ -776,7 +779,7 @@ class AgentLoop:
return TranscriptInput(
history=ctx.history,
current_message=ctx.msg.content,
media=ctx.msg.media if ctx.kind is TurnKind.USER and ctx.msg.media else None,
media=ctx.msg.media if ctx.kind is TurnKind.USER else None,
session_summary=ctx.pending_summary,
runtime_context_blocks=ctx.runtime_context_blocks,
input_metadata=(
@@ -1058,11 +1061,15 @@ class AgentLoop:
if image_paths:
content, image_paths = reference_non_image_attachments(content, image_paths)
image_paths = image_paths or None
user_content = self.context.build_user_content(content, image_paths=image_paths)
user_content = await self.runner.prepare_prompt(
self.context.build_user_content, content, image_paths=image_paths,
) if image_paths else content
row: dict[str, Any] = {
"role": "user", "content": user_content,
"_meta": input_history_metadata(message),
}
if image_paths:
row["_meta"]["media"] = image_paths
if HIDDEN_HISTORY_META in message.metadata:
row[HIDDEN_HISTORY_META] = message.metadata[HIDDEN_HISTORY_META]
metadata_value = cast(object, message.metadata)
@@ -1117,8 +1124,10 @@ class AgentLoop:
async def _checkpoint_turn(self, session: Session, payload: AgentCheckpoint) -> None:
public_payload: dict[str, Any] = dict(payload)
preceding = Session(key=session.key)
self._save_turn(preceding, payload["preceding_messages"], skip=0)
preceding = Session(key=session.key, policy=session.policy)
await shield_and_drain(asyncio.to_thread(
self._save_turn, preceding, payload["preceding_messages"], skip=0,
))
public_payload["preceding_messages"] = preceding.messages
public_payload["consumed_followup_ids"] = sorted(preceding.consumed_followup_ids)
public_payload.pop("provider_state", None)
@@ -2185,9 +2194,9 @@ class AgentLoop:
stored_state,
runtime.model,
):
current_provider_message = self.context.build_current_message(
ctx.msg.content,
media=ctx.msg.media if ctx.kind is TurnKind.USER and ctx.msg.media else None,
current_provider_message = await self.runner.prepare_prompt(
self.context.build_current_message, ctx.msg.content,
media=ctx.msg.media if ctx.kind is TurnKind.USER else None,
runtime_context_blocks=ctx.runtime_context_blocks,
include_memory=session.policy.persist,
has_cron=(ctx.tools if ctx.tools is not None else self.tools).has("cron"),
@@ -2312,12 +2321,13 @@ class AgentLoop:
turn_continuation.record_iteration_limit(
session.metadata, ctx.stop_reason,
)
self._save_turn(
session, ctx.all_messages, ctx.save_skip,
await shield_and_drain(asyncio.to_thread(
self._save_turn, session, ctx.all_messages, ctx.save_skip,
turn_latency_ms=ctx.turn_latency_ms,
summary_checkpoint=None if ctx.ephemeral else ctx.summary_checkpoint,
input_persisted_early=ctx.input_persisted_early,
)
store_images=ctx.commit_session,
))
if (
not ctx.ephemeral
and ctx.provider_compaction_applied
@@ -2364,7 +2374,7 @@ class AgentLoop:
if ctx.ephemeral and ctx.outbound is not None:
ctx.outbound.metadata["_stop_reason"] = ctx.stop_reason
def _sanitize_persisted_blocks(
def _redact_persisted_tool_images(
self,
content: list[object],
) -> list[object]:
@@ -2422,6 +2432,7 @@ class AgentLoop:
turn_latency_ms: int | None = None,
summary_checkpoint: SessionSummaryCheckpoint | None = None,
input_persisted_early: bool = False,
store_images: bool = True,
) -> None:
declared_tool_call_ids = {
str(tc["id"])
@@ -2484,7 +2495,7 @@ class AgentLoop:
fulfilled_tool_call_ids.add(tool_call_id_str)
# Preserve model-visible text for replay; redact only inline images.
if isinstance(content, list):
filtered = self._sanitize_persisted_blocks(
filtered = self._redact_persisted_tool_images(
cast(list[object], content),
)
if not filtered:
@@ -2493,14 +2504,11 @@ class AgentLoop:
{"type": "text", "text": "[tool result omitted during persistence]"}
]
entry["content"] = filtered
elif role == "user":
if isinstance(content, list):
filtered = self._sanitize_persisted_blocks(
cast(list[object], content),
)
if not filtered:
elif role == "user" and isinstance(content, list):
if not content:
continue
entry["content"] = filtered
if store_images and session.policy.persist:
entry["content"] = persist_user_image_blocks(cast(list[object], content))
entry.setdefault("timestamp", datetime.now().isoformat())
session.messages.append(entry)
if role == "user" and isinstance(followup_id, str) and followup_id:
+6 -19
View File
@@ -25,12 +25,12 @@ from nanobot.providers.base import LLMResponse, ProviderConversationState
from nanobot.providers.conversation_state import ProviderConversationStateController
from nanobot.runtime_context import public_history_messages
from nanobot.session.manager import Session, SessionManager
from nanobot.session.message_content import history_message_text
from nanobot.session.summary import is_summary_checkpoint, session_summary_from_metadata
from nanobot.utils.gitstore import MEMORY_CONTENT_PATHS, MEMORY_WIKI_PATH, GitStore
from nanobot.utils.helpers import (
atomic_write_lines,
build_assistant_message,
content_with_media_breadcrumbs,
ensure_dir,
estimate_prompt_tokens_chain,
strip_think,
@@ -615,11 +615,7 @@ class MemoryStore:
def _format_messages(messages: list[dict[str, Any]]) -> str:
lines: list[str] = []
for message in messages:
content = content_with_media_breadcrumbs(
message.get("role"),
message.get("content", ""),
message.get("media"),
)
content = history_message_text(message)
if not content:
continue
tools_used = message.get("tools_used")
@@ -1002,11 +998,11 @@ class MemoryArchiver:
messages=list(session.messages[:archive_end]),
last_consolidated=session.last_archived,
)
history = prefix.get_history(max_tokens=input_token_budget)
history = prefix.get_text_history(max_tokens=input_token_budget)
archive_history = Session(
key=session.key,
messages=messages,
).get_history()
).get_text_history()
if not archive_history or history[-len(archive_history):] != archive_history:
logger.debug(
"Memory archive cannot replay the full chunk for {}; raw-dumping",
@@ -1137,15 +1133,6 @@ class Consolidator:
persist=persist,
)
@staticmethod
def _full_replay_history(
session: Session,
) -> list[dict[str, Any]]:
"""Return all messages that can reach the next model prompt."""
if not session.messages:
return []
return session.get_history()
def estimate_session_prompt_tokens(
self,
session: Session,
@@ -1153,7 +1140,7 @@ class Consolidator:
runtime: LLMRuntime,
) -> tuple[int, str]:
"""Estimate prompt size from the full replayable session history."""
history = self._full_replay_history(session)
history = session.get_text_history()
channel = session.key.split(":", 1)[0] if ":" in session.key else None
summary = session_summary_from_metadata(
session.metadata,
@@ -1265,7 +1252,7 @@ class Consolidator:
"Idle-session compact for {}: archived={}, visible={}, retained={}, summary={}",
session_key,
len(messages_to_archive),
len(session.get_history()),
len(session.get_text_history()),
len(session.messages),
bool(summary),
)
@@ -190,7 +190,7 @@ async def test_filename_collision_never_unlinks_existing_file(tmp_path, monkeypa
assert existing.read_bytes() == b"keep"
async def test_committed_paths_persist_and_replay_without_reference_format(tmp_path):
async def test_committed_paths_persist_as_media_metadata(tmp_path):
from nanobot.session.manager import SessionManager
store = AttachmentStore(tmp_path / "media")
@@ -205,9 +205,7 @@ async def test_committed_paths_persist_and_replay_without_reference_format(tmp_p
replay = replay_manager.get_or_create("websocket:binary-upload")
assert replay.messages[0]["media"] == paths
assert reference not in str(replay.messages)
assert replay.get_history()[0] == {
"role": "user", "content": f"look\n[image: {paths[0]}]",
}
assert replay.get_history()[0] == {"role": "user", "content": "look"}
store.clear()
assert Path(paths[0]).exists()
+1 -1
View File
@@ -220,7 +220,7 @@ async def cmd_status(ctx: CommandContext) -> OutboundMessage:
version=__version__, model=runtime.model,
start_time=loop._start_time, last_usage=last_usage, # pyright: ignore[reportPrivateUsage]
context_window_tokens=runtime.context_window_tokens,
session_msg_count=len(session.get_history(max_messages=0)),
session_msg_count=len(session.get_text_history()),
context_tokens_estimate=ctx_est,
search_usage_text=search_usage_text,
active_task_count=task_count,
+3
View File
@@ -34,6 +34,7 @@ from nanobot.providers.compaction import (
provider_compaction_scope,
)
from nanobot.providers.generation import GenerationSettings as GenerationSettings
from nanobot.providers.image_input import replace_replayed_images
from nanobot.providers.model_options import ModelOptions
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.helpers import sanitize_surrogates_deep
@@ -1384,6 +1385,8 @@ class LLMProvider(ABC):
should_retry_guard: Callable[[], bool] | None = None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse:
if not self.supports_images:
kw = {**kw, "messages": replace_replayed_images(kw["messages"])}
if error := self._image_input_error(kw["messages"], kw.get("provider_context")):
return error
call = self._safe_chat_stream if stream else self._safe_chat
+10 -4
View File
@@ -22,6 +22,7 @@ from nanobot.providers.base import (
RetryStatusCallback,
)
from nanobot.providers.compaction import ProviderStateCommitError, provider_compaction_scope
from nanobot.providers.image_input import replace_replayed_images
from nanobot.providers.model_options import ModelOptions
from nanobot.providers.oauth_catalog_cache import oauth_catalog_auth_rejected
from nanobot.providers.registry import find_by_name
@@ -503,15 +504,19 @@ class FallbackProvider(LLMProvider):
# continuation, so the incoming primary state remains reusable.
preserve_primary_state = True
has_images = self._request_contains_images(kwargs["messages"], kwargs.get("provider_context"))
image_error = self._primary._image_input_error(kwargs["messages"], kwargs.get("provider_context"))
messages = kwargs["messages"]
text_messages = replace_replayed_images(messages)
primary_messages = messages if self._primary.supports_images else text_messages
provider_context = kwargs.get("provider_context")
has_fresh_images = self._request_contains_images(text_messages, provider_context)
image_error = self._primary._image_input_error(primary_messages, provider_context)
if image_error is not None:
primary_response = image_error
primary_error = image_error.content or primary_error
elif self._primary_available():
primary_was_attempted = True
response, primary_exception = await self._call_provider(
call, self._primary, kwargs
call, self._primary, {**kwargs, "messages": primary_messages}
)
if primary_exception is not None:
logger.warning(
@@ -565,7 +570,7 @@ class FallbackProvider(LLMProvider):
last_response = primary_response
primary_skipped = not primary_was_attempted
for idx, fallback in enumerate(self._fallback_presets):
if has_images and not fallback.supports_images:
if has_fresh_images and not fallback.supports_images:
continue
fallback_model = fallback.model
if has_streamed is not None and has_streamed[0]:
@@ -613,6 +618,7 @@ class FallbackProvider(LLMProvider):
fallback_kwargs = {
**kwargs,
"messages": messages if fallback.supports_images else text_messages,
"model": fallback_model,
"max_tokens": fallback.max_tokens,
"temperature": fallback.temperature,
+34
View File
@@ -0,0 +1,34 @@
"""Historical image annotations and the input a text-only candidate can accept."""
from typing import Any, cast
REPLAYED_IMAGE_META = "replayed_user_image"
def replace_replayed_images(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Omit only historical user images for a text-only provider candidate."""
projected: list[dict[str, Any]] = []
for message in messages:
content = message.get("content")
if message.get("role") == "user" and isinstance(content, list):
blocks = cast(list[object], content)
# Fresh and replayed images can share one merged user row.
updated = [_replace_replayed_image(block) for block in blocks]
if any(before is not after for before, after in zip(blocks, updated, strict=True)):
message = {**message, "content": updated}
projected.append(message)
return projected
def _replace_replayed_image(value: object) -> object:
if not isinstance(value, dict):
return value
block = cast(dict[str, object], value)
meta = block.get("_meta")
if (
block.get("type") == "image_url"
and isinstance(meta, dict)
and cast(dict[str, object], meta).get(REPLAYED_IMAGE_META) is True
):
return {"type": "text", "text": "[Previous image omitted: model does not support images]"}
return block
+79
View File
@@ -0,0 +1,79 @@
"""Durable user image blocks and their model-facing replay projection."""
from __future__ import annotations
import re
from collections.abc import Sequence
from hashlib import sha256
from typing import TypedDict, cast
from nanobot.config.paths import get_data_dir
from nanobot.providers.image_input import REPLAYED_IMAGE_META
from nanobot.session.message_content import IMAGE_ATTACHMENT_TYPE
from nanobot.utils.atomic_file import atomic_write_text, io_path, read_atomic_bytes
_IMAGE_ID = re.compile(r"[0-9a-f]{64}")
IMAGE_UNAVAILABLE = "[Previous image unavailable]"
class ImageAttachment(TypedDict):
type: str
id: str
def persist_user_image_blocks(content: Sequence[object]) -> list[object]:
"""Replace inline images with attachment references for session replay."""
stored: list[object] = []
for value in content:
block = cast(dict[str, object], value) if isinstance(value, dict) else {}
image = block.get("image_url")
url = cast(dict[str, object], image).get("url") if isinstance(image, dict) else None
if block.get("type") != "image_url" or not isinstance(url, str) or not url.startswith("data:image/"):
stored.append(cast(object, value))
continue
image_id = sha256(url.encode("ascii")).hexdigest()
directory = io_path(get_data_dir() / "session-images")
path = directory / image_id
if not path.is_file():
directory.mkdir(mode=0o700, exist_ok=True)
atomic_write_text(path, url)
ref: ImageAttachment = {"type": IMAGE_ATTACHMENT_TYPE, "id": image_id}
stored.append(ref)
return stored
def replay_user_image_blocks(content: Sequence[object]) -> list[object]:
"""Materialize the selected user blocks for a model request."""
replay: list[object] = []
for value in content:
block = cast(dict[str, object], value) if isinstance(value, dict) else {}
if block.get("type") == IMAGE_ATTACHMENT_TYPE:
url = _load_image(block.get("id"))
if url is not None:
replay.append({
"type": "image_url", "image_url": {"url": url},
"_meta": {REPLAYED_IMAGE_META: True},
})
else:
replay.append({"type": "text", "text": IMAGE_UNAVAILABLE})
elif block.get("type") == "image_url":
# Temporary sessions keep their images in memory only.
replay.append({**block, "_meta": {REPLAYED_IMAGE_META: True}})
else:
replay.append(cast(object, value))
return replay
def _load_image(image_id: object) -> str | None:
if not isinstance(image_id, str) or not _IMAGE_ID.fullmatch(image_id):
return None
try:
path = io_path(get_data_dir() / "session-images" / image_id)
if not path.is_file():
return None
data = read_atomic_bytes(path)
if data.startswith(b"data:image/") and sha256(data).hexdigest() == image_id:
return data.decode("ascii")
except (OSError, UnicodeError):
pass
return None
+28 -29
View File
@@ -8,7 +8,7 @@ from copy import deepcopy
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, TypedDict, TypeVar, cast
from typing import TYPE_CHECKING, Any, Callable, Literal, TypedDict, TypeVar, cast
from uuid import uuid4
from nanobot.providers.base import ProviderConversationState
@@ -18,11 +18,12 @@ from nanobot.runtime_context import (
)
from nanobot.session.display_history import HistoryFact, HistoryReader
from nanobot.session.history_visibility import HIDDEN_HISTORY_META, is_hidden_history_message
from nanobot.session.image_attachments import replay_user_image_blocks
from nanobot.session.location import SessionLocation
from nanobot.session.message_content import message_text, text_history_blocks
from nanobot.session.summary import SUMMARY_CONTINUATION_TEXT, is_summary_checkpoint
from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY, SessionTypes
from nanobot.utils.helpers import (
content_with_media_breadcrumbs,
estimate_message_tokens,
find_legal_message_start,
recent_message_start_index,
@@ -51,22 +52,7 @@ _FORK_VOLATILE_METADATA_KEYS = {
def _text_preview(content: object) -> str:
if isinstance(content, str):
text = content
elif isinstance(content, list):
parts: list[str] = []
for block in cast(list[object], content):
if isinstance(block, dict):
block_data = cast(dict[object, object], block)
if block_data.get("type") != "text":
continue
value = block_data.get("text")
if isinstance(value, str):
parts.append(value)
text = " ".join(parts)
else:
return ""
text = re.sub(r"\s+", " ", text).strip()
text = re.sub(r"\s+", " ", message_text(content)).strip()
if len(text) > _SESSION_PREVIEW_MAX_CHARS:
text = text[: _SESSION_PREVIEW_MAX_CHARS - 1].rstrip() + "…"
return text
@@ -155,7 +141,7 @@ class Session:
def last_archived(self, value: int) -> None:
self.last_consolidated = value
def add_message(self, role: str, content: str, **kwargs: Any) -> None:
def add_message(self, role: str, content: str | list[_T], **kwargs: Any) -> None:
"""Add a message to the session."""
msg = {
"role": role,
@@ -202,6 +188,22 @@ class Session:
is not a user request and must not resume an old task on the next turn.
A positive ``max_messages`` applies an additional caller-owned count limit.
"""
return self._history(
max_messages, max_tokens=max_tokens, extend_to_user=extend_to_user,
view="model" if include_runtime_context else "public",
)
def get_text_history(
self, *, max_tokens: int = 0, include_runtime_context: bool = True,
) -> list[dict[str, Any]]:
"""Return the replayable context for archives and estimates without loading images."""
return self._history(max_tokens=max_tokens, view="text" if include_runtime_context else "public")
def _history(
self, max_messages: int = 0, *, max_tokens: int = 0, extend_to_user: bool = False,
view: Literal["model", "text", "public"],
) -> list[dict[str, Any]]:
include_runtime_context = view != "public"
replayable = self.messages[self.last_archived:]
if max_messages <= 0:
start_idx = 0
@@ -239,16 +241,8 @@ class Session:
message = public_history_message(message)
content = message.get("content", "")
role = message.get("role")
# Synthesize an ``[image: path]`` breadcrumb from the persisted
# ``media`` kwarg so LLM replay still sees *something* where the
# image used to be. Without this, an image-only user turn
# replays as an empty user message — the assistant's reply then
# looks like it's responding to nothing.
content = content_with_media_breadcrumbs(
role,
content,
message.get("media"),
)
if role == "user" and view != "model" and isinstance(content, list):
content = text_history_blocks(cast(list[object], content))
cli_apps = cast(object, message.get("cli_apps"))
if (
include_runtime_context
@@ -322,6 +316,11 @@ class Session:
if start:
kept = kept[start:]
out = kept
if view == "model":
for entry in out:
content = entry["content"]
if entry["role"] == "user" and isinstance(content, list):
entry["content"] = replay_user_image_blocks(cast(list[object], content))
return out
def clear(self) -> None:
+44
View File
@@ -0,0 +1,44 @@
"""Text views of session messages. None of these projections resolves attachments."""
from collections.abc import Mapping, Sequence
from typing import cast
from nanobot.utils.helpers import stringify_text_blocks
IMAGE_ATTACHMENT_TYPE = "image_attachment"
def text_history_blocks(blocks: Sequence[object]) -> list[object]:
"""Keep block order and replace each inline or stored image with a text marker."""
return [
{"type": "text", "text": "[image]"}
if isinstance(block, dict) and cast(dict[str, object], block).get("type") in (
IMAGE_ATTACHMENT_TYPE, "image_url",
) else block
for block in blocks
]
def message_text(content: object) -> str:
"""Visible text only; an image is not part of its caption."""
if isinstance(content, str):
return content
if not isinstance(content, list):
return ""
parts: list[str] = []
for value in cast(list[object], content):
if isinstance(value, dict):
block = cast(dict[str, object], value)
if block.get("type") == "text" and isinstance(text := block.get("text"), str):
parts.append(text)
return "\n".join(parts)
def history_message_text(message: Mapping[str, object]) -> str:
"""Text for an archive line, including markers for image-only user turns."""
content = message.get("content")
if message.get("role") == "user" and isinstance(content, list):
blocks = text_history_blocks(cast(list[object], content))
text = stringify_text_blocks(blocks)
return str(blocks) if text is None else text
return str(content) if content else ""
+3
View File
@@ -40,6 +40,9 @@ def persisted_message(message: dict[str, Any]) -> dict[str, Any]:
for key in ("timestamp", INBOUND_META_TURN_ID):
if isinstance(value := metadata.get(key), str) and value:
entry[key] = value
for key in ("media", INBOUND_META_LOCAL_MEDIA):
if isinstance(paths := metadata.get(key), list):
entry[key] = [path for path in cast(list[object], paths) if isinstance(path, str)]
if isinstance(source := metadata.get("session_message"), dict):
entry["session_message"] = source
if isinstance(context := metadata.get(RUNTIME_CONTEXT_MESSAGE_META), dict):
+2 -1
View File
@@ -42,6 +42,7 @@ from nanobot.runtime_context import public_history_message
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import Session, SessionManager
from nanobot.session.message_content import message_text
from nanobot.session.session_messages import (
SESSION_MESSAGE_METADATA_KEY,
session_message_envelope,
@@ -136,7 +137,7 @@ def _title_inputs(session: Session) -> tuple[str, str]:
continue
message = public_history_message(message)
role = message.get("role")
content = message.get("content")
content = message_text(message.get("content")) if role == "user" else message.get("content")
if not isinstance(content, str) or not content.strip():
continue
content = strip_think(content)
-18
View File
@@ -373,24 +373,6 @@ def image_placeholder_text(path: str | None, *, empty: str = "[image]") -> str:
return f"[image: {path}]" if path else empty
def content_with_media_breadcrumbs(
role: str | None,
content: Any,
media: Any,
) -> Any:
"""Append persisted user-media breadcrumbs to plain-text content."""
if role != "user" or not isinstance(content, str) or not isinstance(media, list):
return content
breadcrumbs = "\n".join(
image_placeholder_text(path)
for path in cast(list[object], media)
if isinstance(path, str) and path
)
if not breadcrumbs:
return content
return f"{content}\n{breadcrumbs}" if content else breadcrumbs
def truncate_text(text: str, max_chars: int) -> str:
"""Truncate text with a stable suffix."""
if max_chars <= 0 or len(text) <= max_chars:
+1 -1
View File
@@ -16,7 +16,7 @@ def session_context_payload(session: Session) -> dict[str, Any]:
model-specific token budget. This projection deliberately reports only the
session-owned part: archived summary plus the replayable raw suffix.
"""
replay = session.get_history(max_messages=0, include_runtime_context=False)
replay = session.get_text_history(include_runtime_context=False)
raw_summary = session.metadata.get("_last_summary")
summary = ""
summary_preview = ""
+2 -2
View File
@@ -36,6 +36,7 @@ from nanobot.session.history_graph import (
)
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import Session, SessionManager
from nanobot.session.message_content import message_text
from nanobot.session.session_messages import (
session_message_envelope,
session_message_public_metadata,
@@ -835,8 +836,7 @@ def _session_user_event(
message = public_history_message(message)
if _is_legacy_raw_subagent_result(message):
return None
content = message.get("content")
text = content if isinstance(content, str) else ""
text = message_text(message.get("content"))
media = message.get("media")
cli_apps = message.get("cli_apps")
mcp_presets = message.get("mcp_presets")
+61 -18
View File
@@ -1,9 +1,12 @@
import asyncio
import base64
import json
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
import httpx
import pytest
from openai import AsyncOpenAI
from nanobot.agent.context import TranscriptInput
from nanobot.agent.loop import AgentLoop, TurnContext, TurnKind
@@ -13,6 +16,8 @@ from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.config.schema import ChannelsConfig
from nanobot.providers.base import LLMResponse
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
from nanobot.providers.registry import ModelAPICapabilities
from nanobot.runtime_context import public_history_message
from nanobot.utils.document import reference_non_image_attachments
@@ -237,28 +242,66 @@ async def test_borrowed_image_origin_survives_canonical_reload(tmp_path: Path) -
augment = MagicMock(return_value=[{"kind": "image", "url": "/borrowed"}])
response = build_session_thread_response(persisted, augment_user_media=augment)
augment.assert_called_once_with([str(source)], [str(source)])
assert response["events"][0]["text"] == "look"
assert response["events"][0]["media_urls"][0]["url"] == "/borrowed"
@pytest.mark.asyncio
async def test_image_path_remains_visible_once_after_session_reload(tmp_path: Path) -> None:
image = tmp_path / "original.png"
image.write_bytes(base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+yF9kAAAAASUVORK5CYII="
))
loop = _make_loop(tmp_path)
loop.provider.aclose = AsyncMock()
@pytest.mark.parametrize("prompt", ["Compare these images", ""])
async def test_user_images_replay_in_order_after_cold_reload(tmp_path: Path, prompt: str) -> None:
png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+yF9kAAAAASUVORK5CYII="
gif = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
first, second = tmp_path / "first.png", tmp_path / "second.gif"
first.write_bytes(base64.b64decode(png))
second.write_bytes(base64.b64decode(gif))
expected = [
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{png}"}},
{"type": "image_url", "image_url": {"url": f"data:image/gif;base64,{gif}"}},
]
if prompt:
expected.append({"type": "text", "text": prompt})
key = "websocket:image-reference"
requests = []
def handle(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
requests.append(body["messages"])
event = {
"id": "chat_1", "created": 1, "object": "chat.completion.chunk", "model": body["model"],
"choices": [{"index": 0, "delta": {"content": "answer"}, "finish_reason": "stop"}],
}
return httpx.Response(
200, headers={"content-type": "text/event-stream"},
text=f"data: {json.dumps(event)}\n\ndata: [DONE]\n\n",
)
def new_loop() -> AgentLoop:
provider = OpenAICompatProvider(
api_key="fixture", default_model="gpt-4o",
model_api=ModelAPICapabilities(("chat_completions",), "chat_completions"),
)
provider._client = AsyncOpenAI(
api_key="fixture", http_client=httpx.AsyncClient(transport=httpx.MockTransport(handle)),
)
return AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="gpt-4o")
loop = new_loop()
try:
await loop.process_direct("edit this image", session_key="websocket:image-reference", channel="websocket", chat_id="image-reference", media=[str(image)])
initial = loop.provider.chat_stream_with_retry.call_args.kwargs["messages"]
current = initial[-1]["content"]
assert any(block.get("type") == "image_url" for block in current)
assert sum(block.get("text", "").count(str(image)) for block in current) == 1
loop.sessions.invalidate("websocket:image-reference")
await loop.process_direct("which file was that?", session_key="websocket:image-reference", channel="websocket", chat_id="image-reference")
following = loop.provider.chat_stream_with_retry.call_args.kwargs["messages"]
previous = next(message["content"] for message in following if message["role"] == "user")
previous_text = previous if isinstance(previous, str) else "\n".join(block.get("text", "") for block in previous)
assert previous_text.count(str(image)) == 1
await loop.process_direct(prompt, session_key=key, media=[str(first), str(second)])
finally:
await loop.aclose()
first.unlink()
cold = new_loop()
try:
await cold.process_direct("What was in the first image?", session_key=key)
initial, following = requests
first_request = initial[-1]["content"]
assert first_request[:len(expected)] == expected
previous = next(message for message in following if message["role"] == "user")
assert previous["content"] == first_request
stored = cold.sessions.get_or_create(key).messages[0]
assert stored["media"] == [str(first), str(second)]
assert "base64," not in repr(stored)
finally:
await cold.aclose()
+37 -11
View File
@@ -276,19 +276,18 @@ class TestTurnTranscriptSummary:
class TestConsolidatorSummarize:
def test_format_messages_keeps_media_only_user_turn(self):
path = "/home/user/.nanobot/media/websocket/clip.mp4"
formatted = MemoryStore._format_messages([
{
"role": "user",
"content": "",
"media": [path],
"timestamp": "2026-07-27",
}
def test_raw_archive_keeps_captions_and_path_free_image_markers(self, store):
checkpoint = store.raw_archive([
{"role": "user", "content": "look", "media": ["/m/pic.png"]},
{"role": "user", "content": [{"type": "image_attachment", "id": "a" * 64}]},
{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": "data:image/png;base64,YQ=="}},
{"type": "text", "text": "a caption"},
]},
])
assert formatted == f"[2026-07-27] USER: [image: {path}]"
assert checkpoint == "[RAW] 3 messages\n[?] USER: look\n[?] USER: [image]\n[?] USER: [image]\na caption"
assert store.read_unprocessed_history(since_cursor=0)[0]["content"] == checkpoint
async def test_archive_uses_captured_generation(
self, consolidator, mock_provider, runtime
@@ -590,6 +589,33 @@ class TestCompactIdleSession:
get_tool_definitions=MagicMock(return_value=[]),
)
async def test_archive_and_token_probe_use_image_markers_without_reading_attachments(
self, real_consolidator, runtime, mock_provider, monkeypatch,
):
from nanobot.session.image_attachments import persist_user_image_blocks
session = Session(key="cli:archive-images")
session.add_message("user", persist_user_image_blocks([
{"type": "image_url", "image_url": {"url": "data:image/png;base64,YQ=="}},
{"type": "text", "text": "compare"},
{"type": "image_url", "image_url": {"url": "data:image/png;base64,Yg=="}},
]))
monkeypatch.setattr(
"nanobot.session.image_attachments.read_atomic_bytes",
lambda *_: pytest.fail("text history opened an image"),
)
mock_provider.chat_stream_with_retry.return_value = LLMResponse(content="Compared two images.")
real_consolidator.estimate_session_prompt_tokens(session, runtime=runtime)
summary = await real_consolidator.archive_session(session, archive_end=1, runtime=runtime)
assert summary == "Compared two images."
assert mock_provider.chat_stream_with_retry.await_args.kwargs["messages"][1]["content"] == [
{"type": "text", "text": "[image]"},
{"type": "text", "text": "compare"},
{"type": "text", "text": "[image]"},
]
async def test_partial_raw_write_does_not_advance_checkpoint(
self, real_consolidator, store, runtime, mock_provider, monkeypatch
):
+7 -18
View File
@@ -247,14 +247,12 @@ class TestBuildUserContent:
builder = _builder(tmp_path)
result = builder.build_user_content("hello", [str(png)])
assert isinstance(result, list)
assert len(result) == 3
assert result[0] == {"type": "text", "text": f"[image: {png}]"}
assert result[1]["type"] == "image_url"
assert result[1]["image_url"]["url"].startswith("data:image/png;base64,")
assert result[2]["type"] == "text"
assert result[2]["text"] == "hello"
assert len(result) == 2
assert result[0]["type"] == "image_url"
assert result[0]["image_url"]["url"].startswith("data:image/png;base64,")
assert result[1] == {"type": "text", "text": "hello"}
def test_images_keep_paired_paths_in_provider_visible_content(self, tmp_path):
def test_images_convert_to_structured_provider_content(self, tmp_path):
from nanobot.providers.base import LLMProvider
from nanobot.providers.openai_responses.converters import convert_user_message
@@ -266,17 +264,8 @@ class TestBuildUserContent:
converted = convert_user_message(clean["content"])["content"]
image_indexes = [index for index, block in enumerate(converted) if block["type"] == "input_image"]
assert len(image_indexes) == 2
for index, path in zip(image_indexes, paths, strict=True):
assert index > 0
assert converted[index - 1] == {"type": "input_text", "text": f"[image: {path}]"}
assert converted[-1] == {"type": "input_text", "text": "compare these"}
def test_image_meta_includes_path(self, tmp_path):
png = tmp_path / "test.png"
png.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 16)
builder = _builder(tmp_path)
result = builder.build_user_content("hello", [str(png)])
assert result[1]["_meta"]["path"] == str(png)
assert image_indexes == [0, 1]
assert converted[2:] == [{"type": "input_text", "text": "compare these"}]
class TestBuildSystemPrompt:
+23 -36
View File
@@ -367,7 +367,11 @@ async def test_generate_webui_title_only_for_marked_webui_sessions(tmp_path: Pat
)
session = loop.sessions.get_or_create("websocket:chat-title")
session.metadata[WEBUI_SESSION_METADATA_KEY] = True
session.add_message("user", "帮我优化一下 webui 的 sidebar")
caption = "帮我优化一下 webui 的 sidebar"
session.add_message("user", [
{"type": "image_attachment", "id": "a" * 64},
{"type": "text", "text": caption},
])
session.add_message("assistant", "可以,我会先调整布局和视觉层级。")
loop.sessions.save(session)
@@ -382,6 +386,8 @@ async def test_generate_webui_title_only_for_marked_webui_sessions(tmp_path: Pat
session = await loop.sessions.state.get(session.key)
assert session.metadata[WEBUI_TITLE_METADATA_KEY] == "优化 WebUI 侧边栏"
loop.provider.chat_stream_with_retry.assert_awaited_once()
title_prompt = loop.provider.chat_stream_with_retry.await_args.args[0][-1]["content"]
assert f"User: {caption}\nAssistant:" in title_prompt
assert loop.provider.chat_stream_with_retry.await_args.kwargs["max_tokens"] == TITLE_GENERATION_MAX_TOKENS
assert (
loop.provider.chat_stream_with_retry.await_args.kwargs["reasoning_effort"]
@@ -530,7 +536,7 @@ def test_save_turn_commits_summary_boundary_without_rewriting_raw_history() -> N
]
def test_save_turn_keeps_image_placeholder_and_runtime_context() -> None:
def test_save_turn_keeps_user_image_and_runtime_context() -> None:
loop = _mk_loop()
session = Session(key="test:image")
block = RuntimeContextBlock(source="test", content="provider context")
@@ -545,33 +551,11 @@ def test_save_turn_keeps_image_placeholder_and_runtime_context() -> None:
)],
skip=0,
)
assert session.messages[0]["content"] == [
{"type": "text", "text": "[image: /media/feishu/photo.jpg]"},
{"type": "text", "text": "provider context"},
]
assert public_history_message(session.messages[0])["content"] == [
{"type": "text", "text": "[image: /media/feishu/photo.jpg]"}
]
def test_save_turn_keeps_image_placeholder_without_meta() -> None:
loop = _mk_loop()
session = Session(key="test:image-no-meta")
block = RuntimeContextBlock(source="test", content="provider context")
loop._save_turn(
session,
[_runtime_message(
[
{"type": "image_url", "image_url": {"url": "data:image/png;base64,abc"}},
],
[block],
)],
skip=0,
)
assert session.messages[0]["content"] == [
content = session.get_history()[0]["content"]
assert content[0]["image_url"] == {"url": "data:image/png;base64,abc"}
assert content[1:] == [{"type": "text", "text": "provider context"}]
assert session.get_history(include_runtime_context=False)[0]["content"] == [
{"type": "text", "text": "[image]"},
{"type": "text", "text": "provider context"},
]
@@ -1196,18 +1180,17 @@ async def test_process_message_persists_media_paths_on_user_turn(tmp_path: Path)
loop.sessions.invalidate("websocket:c-media")
persisted = loop.sessions.get_or_create("websocket:c-media")
assert [m["role"] for m in persisted.messages] == ["user"]
assert public_history_message(persisted.messages[0])["content"] == "look"
assert persisted.get_history(include_runtime_context=False)[0]["content"] == [
{"type": "text", "text": "[image]"},
{"type": "text", "text": "[image]"},
{"type": "text", "text": "look"},
]
assert persisted.messages[0]["media"] == [str(img_a), str(img_b)]
@pytest.mark.asyncio
async def test_process_message_persists_media_only_turn_without_text(tmp_path: Path) -> None:
"""A turn with images but no text still persists (previously silent-dropped).
The old early-persist gate skipped messages without text, leaving pure
image turns un-checkpointed. They now materialise as an empty-content
user row with ``media`` attached.
"""
"""The image-only input is replayable even if the first model call never finishes."""
img = tmp_path / "only.png"
img.write_bytes(_PNG_1X1)
@@ -1228,7 +1211,11 @@ async def test_process_message_persists_media_only_turn_without_text(tmp_path: P
persisted = loop.sessions.get_or_create("websocket:c-images-only")
assert len(persisted.messages) == 1
assert persisted.messages[0]["role"] == "user"
assert public_history_message(persisted.messages[0])["content"] == ""
content = persisted.get_history()[0]["content"]
assert [block["type"] for block in content].count("image_url") == 1
assert persisted.get_history(include_runtime_context=False)[0]["content"] == [
{"type": "text", "text": "[image]"},
]
assert persisted.messages[0]["media"] == [str(img)]
+1
View File
@@ -28,6 +28,7 @@ def configured_override(monkeypatch):
provider = MagicMock(spec=LLMProvider)
provider._image_input_error.return_value = None
provider.generation = preset.to_generation_settings()
provider.supports_images = preset.supports_images
provider.provider_name = owned.get_provider_name(preset=preset)
provider.get_default_model.return_value = model or preset.model
provider.chat = AsyncMock(return_value=LLMResponse(content="ok"))
+1
View File
@@ -1007,6 +1007,7 @@ async def test_runner_does_not_compact_primary_request_from_fallback_usage(monke
primary = MagicMock(spec=LLMProvider)
primary._image_input_error.return_value = None
primary.provider_name = "primary"
primary.supports_images = True
primary.generation = GenerationSettings(max_tokens=100)
primary.supports_native_compaction.return_value = False
primary.chat_stream_with_retry = AsyncMock(side_effect=[
+14 -28
View File
@@ -396,37 +396,26 @@ def test_window_cuts_mid_tool_group():
assert history[0]["role"] == "user"
def test_get_history_synthesizes_image_breadcrumb_from_media_kwarg():
"""Persisted user turns carry image paths as a ``media`` kwarg; LLM
replay must still see an ``[image: path]`` breadcrumb so the assistant's
follow-up reply has a referent instead of trailing an empty user row."""
def test_get_history_preserves_user_text_with_media_metadata():
session = Session(key="test:media")
session.messages.append(
{"role": "user", "content": "look", "media": ["/m/a.png", "/m/b.png"]}
)
session.messages.append({"role": "assistant", "content": "nice"})
session.add_message("user", "look", media=["/m/pic.png"])
history = session.get_history(max_messages=500)
assert session.get_history() == [{"role": "user", "content": "look"}]
assert history == [
{"role": "user", "content": "look\n[image: /m/a.png]\n[image: /m/b.png]"},
{"role": "assistant", "content": "nice"},
def test_get_history_marks_missing_image_snapshot():
session = Session(key="test:missing-image")
session.add_message("user", [
{"type": "image_attachment", "id": "a" * 64},
{"type": "text", "text": "look"},
])
assert session.get_history()[0]["content"] == [
{"type": "text", "text": "[Previous image unavailable]"},
{"type": "text", "text": "look"},
]
def test_get_history_synthesizes_breadcrumb_for_image_only_turn():
"""Turns with no text but attached images must not replay as empty
strings — the LLM would otherwise see a bare user turn followed by an
unexplained assistant answer."""
session = Session(key="test:image-only")
session.messages.append({"role": "user", "content": "", "media": ["/m/pic.png"]})
session.messages.append({"role": "assistant", "content": "I see a cat"})
history = session.get_history(max_messages=500)
assert history[0] == {"role": "user", "content": "[image: /m/pic.png]"}
def test_get_history_synthesizes_cli_app_attachment_breadcrumb():
session = Session(key="test:cli-app")
session.messages.append(
@@ -657,9 +646,6 @@ def test_fork_session_drops_summary_when_fork_point_is_inside_archived_prefix(tm
def test_get_history_ignores_media_kwarg_on_non_user_rows():
"""``media`` only ever appears on user entries in practice, but the
synthesizer must be defensive: assistants / tools with list content
don't get the breadcrumb pasted on top."""
session = Session(key="test:defensive")
session.messages.append(
{
+9 -9
View File
@@ -235,8 +235,10 @@ class TestRestartCommand:
@pytest.mark.asyncio
async def test_status_reports_runtime_info(self):
loop, _bus = _make_loop()
session = MagicMock()
session.get_history.return_value = [{"role": "user"}] * 3
session = Session("telegram:c1")
session.add_message("user", [{"type": "image_attachment", "id": "a" * 64}])
session.add_message("assistant", "Image received")
session.add_message("user", "Continue")
session.metadata = {
"_last_usage": LLMUsage.reported(input_tokens=0, output_tokens=0).to_dict()
}
@@ -275,8 +277,8 @@ class TestRestartCommand:
@pytest.mark.asyncio
async def test_status_counts_running_dispatch_and_subagent_tasks(self):
loop, _bus = _make_loop()
session = MagicMock()
session.get_history.return_value = [{"role": "user"}]
session = Session("telegram:c1")
session.add_message("user", "Hello")
loop.sessions.state.get = AsyncMock(return_value=session)
loop.consolidator.estimate_session_prompt_tokens = MagicMock(
return_value=(1000, "tiktoken")
@@ -327,8 +329,8 @@ class TestRestartCommand:
@pytest.mark.asyncio
async def test_status_falls_back_to_session_usage_when_context_estimate_missing(self):
loop, _bus = _make_loop()
session = MagicMock()
session.get_history.return_value = [{"role": "user"}]
session = Session("telegram:c1")
session.add_message("user", "Hello")
session.metadata = {
"_last_usage": LLMUsage.reported(input_tokens=1200, output_tokens=34).to_dict()
}
@@ -350,9 +352,7 @@ class TestRestartCommand:
@pytest.mark.asyncio
async def test_process_direct_preserves_render_metadata(self):
loop, _bus = _make_loop()
session = MagicMock()
session.get_history.return_value = []
loop.sessions.state.get = AsyncMock(return_value=session)
loop.sessions.state.get = AsyncMock(return_value=Session("cli:test"))
loop.subagents.get_running_count.return_value = 0
loop.subagents.get_running_count_by_session.return_value = 0
+34
View File
@@ -12,6 +12,7 @@ from nanobot.providers.base import (
)
from nanobot.providers.factory import make_provider, provider_signature
from nanobot.providers.fallback_provider import FallbackProvider
from nanobot.providers.image_input import REPLAYED_IMAGE_META
_IMAGE = {"type": "image_url", "image_url": {"url": "data:image/png;base64,c3ludGhldGlj"}}
@@ -53,6 +54,39 @@ async def test_text_only_preset_rejects_images_before_request(stream, native):
assert len(provider.calls) == 1
async def test_text_only_preset_omits_history_but_still_rejects_fresh_images():
provider = ImageProvider(False)
history = {**_IMAGE, "_meta": {REPLAYED_IMAGE_META: True}}
prompt = {"type": "text", "text": "Continue"}
messages = [{"role": "user", "content": [history, prompt]}]
response = await provider.chat_with_retry(messages=messages)
assert response.content == "accepted"
forwarded = provider.calls[0]["messages"][0]["content"]
assert forwarded == [
{"type": "text", "text": "[Previous image omitted: model does not support images]"},
prompt,
]
assert messages[0]["content"] == [history, prompt]
response = await provider.chat_with_retry(messages=[{"role": "user", "content": [history, _IMAGE]}])
assert response.error_code == "unsupported_image"
assert len(provider.calls) == 1
async def test_text_fallback_accepts_history_after_vision_provider_fails():
vision = ImageProvider(True, LLMResponse("unavailable", finish_reason="error", error_status_code=503))
text = ImageProvider(False)
chain = FallbackProvider(vision, [ModelPresetConfig(model="text", supports_images=False)], lambda _: text)
messages = [{"role": "user", "content": [{**_IMAGE, "_meta": {REPLAYED_IMAGE_META: True}}]}]
assert (await chain.chat(messages=messages)).content == "accepted"
assert vision.calls[0]["messages"] == messages
assert text.calls[0]["messages"][0]["content"] == [
{"type": "text", "text": "[Previous image omitted: model does not support images]"},
]
@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize("primary_supports", [False, True])
async def test_image_fallback_skips_text_only_candidates_without_counting_capability_as_outage(stream, primary_supports):
+2 -8
View File
@@ -7,10 +7,10 @@ import threading
from collections.abc import Callable, Iterator
from contextlib import closing
from dataclasses import asdict
from types import SimpleNamespace
import pytest
from nanobot.config.schema import ModelPresetConfig
from nanobot.llm_usage.context import current_llm_usage_source, llm_usage_source
from nanobot.llm_usage.models import LLMCallRecord
from nanobot.llm_usage.service import record_llm_call
@@ -473,13 +473,7 @@ async def test_fallback_provider_propagates_observer_to_every_leaf() -> None:
]
)
)
preset = SimpleNamespace(
model="fallback-model",
max_tokens=256,
temperature=0.2,
reasoning_effort=None,
context_window_tokens=4_096,
)
preset = ModelPresetConfig(model="fallback-model")
provider = FallbackProvider(primary, [preset], lambda _preset: fallback)
events: list[LLMCallRecord] = []
provider.set_llm_call_observer(events.append)
@@ -239,9 +239,8 @@ async def test_codex_exports_langfuse_usage(codex_peer, reject_upgrade):
async def test_gateway_continues_image_then_pdf_attachment_turn(codex_peer, tmp_path):
provider, server, _ = codex_peer
image = tmp_path / "image.png"
image.write_bytes(base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aP1kAAAAASUVORK5CYII="
))
png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aP1kAAAAASUVORK5CYII="
image.write_bytes(base64.b64decode(png))
pdf = tmp_path / "report.pdf"
writer = PdfWriter()
writer.add_blank_page(width=100, height=100)
@@ -263,11 +262,11 @@ async def test_gateway_continues_image_then_pdf_attachment_turn(codex_peer, tmp_
assert len(server.peers) == 1
assert len(server.requests) == 2
initial, continued = [body for _, body in server.requests]
assert "input_image" in json.dumps(initial["input"])
assert any(
block.get("type") == "input_text" and str(image) in block["text"]
for item in initial["input"] for block in item.get("content", [])
)
content = next(item["content"] for item in initial["input"] if item.get("role") == "user")
assert [b["image_url"] for b in content if b["type"] == "input_image"] == [f"data:image/png;base64,{png}"]
texts = [b["text"] for b in content if b["type"] == "input_text"]
assert "Describe this image." in texts
assert all(str(image) not in text for text in texts)
assert continued["previous_response_id"] == "resp_1"
assert "input_image" not in json.dumps(continued["input"])
assert f"[Attachment: {pdf}]" in continued["input"][0]["content"][0]["text"]
-28
View File
@@ -10,7 +10,6 @@ from nanobot.utils.helpers import (
_write_text_atomic,
atomic_write_lines,
atomic_write_text,
content_with_media_breadcrumbs,
split_message,
truncate_text_to_tokens,
)
@@ -124,33 +123,6 @@ def test_truncate_text_to_tokens_non_positive_budget_returns_text():
assert truncate_text_to_tokens(text, 0) == text
def test_content_with_media_breadcrumbs_preserves_valid_paths():
assert content_with_media_breadcrumbs(
"user",
"review these",
["/media/report.pdf", "/media/clip.mp4"],
) == (
"review these\n"
"[image: /media/report.pdf]\n"
"[image: /media/clip.mp4]"
)
def test_content_with_media_breadcrumbs_only_rewrites_plain_user_content():
structured = [{"type": "text", "text": "hello"}]
assert content_with_media_breadcrumbs(
"assistant",
"done",
["/media/output.png"],
) == "done"
assert content_with_media_breadcrumbs(
"user",
structured,
["/media/input.png"],
) is structured
def test_write_text_atomic_fsyncs_file_and_parent_directory(
tmp_path: Path, monkeypatch
) -> None: