Skip to content

The agent that grows with you

fix(agent): resolve image replay once per turn and document the media-cache retention bound

Tekniumececd8619119
diff --git a/agent/image_replay.py b/agent/image_replay.py
index 65e9859408b..b649f3ebebd 100644
--- a/agent/image_replay.py
+++ b/agent/image_replay.py
@@ -3,17 +3,18 @@
The DB stores user rows as text (``session_persistence._durable_content``): an image part becomes a
trailing ``[screenshot]`` line. A turn rebuilt from the DB (every API-server request, ``--resume``,
a gateway restart) therefore showed the model that placeholder instead of the photo the user asked
-about one message earlier. The bytes are not gone: every native attach path (CLI, TUI, gateway,
-API server) commits them under the profile's content-addressed ``native-inputs/<sha256>/<name>``
-and names that path in the same row (``[Image attached at: <path>]``, written by
-``image_routing.build_native_content_parts`` / ``session_api_media.restore_api_images``).
+about one message earlier. The bytes are not gone: the session-authority attach paths (CLI, the
+shared-gateway TUI, messaging gateway, API server) commit them under the profile's content-addressed
+``native-inputs/<sha256>/<name>`` and name that path in the same row (``[Image attached at: <path>]``,
+written by ``image_routing.build_native_content_parts`` / ``session_api_media.restore_api_images``).
On the WIRE COPY only, when this turn sends images natively, the ``vision.replay_recent_images``
newest images (default 3, 0 = off) go back as ``image_url`` parts. The data URL comes from the same
``_file_to_data_url`` the live turn used, so the rebuilt row is byte-identical to the request that
first sent it and the prompt-cache prefix holds. Only retained bytes under this profile's
``native-inputs`` whose digest still matches are replayed; remote URLs (they can expire and 400
-every later turn), missing files and anything outside the window keep their ``[screenshot]`` text.
+every later turn), missing files (the gateway's settled-media sweep collects them after
+``MEDIA_CACHE_MAX_AGE_HOURS``) and anything outside the window keep their ``[screenshot]`` text.
"""
from __future__ import annotations
@@ -34,7 +35,8 @@ _IMAGE_PART_TYPES = {"image", "image_url", "input_image"}
def resolve_replay_recent_images(cfg: dict) -> int:
"""``vision.replay_recent_images`` as an int >= 0; an unusable value warns and disables replay."""
- raw = ((cfg or {}).get("vision") or {}).get("replay_recent_images", DEFAULT_REPLAY_RECENT_IMAGES)
+ vision = (cfg or {}).get("vision")
+ raw = (vision if isinstance(vision, dict) else {}).get("replay_recent_images", DEFAULT_REPLAY_RECENT_IMAGES)
if raw is None:
return DEFAULT_REPLAY_RECENT_IMAGES
if isinstance(raw, int) and not isinstance(raw, bool) and raw >= 0:
@@ -68,11 +70,11 @@ def _retained_data_url(ref: str) -> Optional[str]:
if not ref:
return None
from agent.image_routing import _file_to_data_url
- from gateway.session_ingress_media import _media_root
+ from gateway.session_ingress_media import native_inputs_root
path = Path(ref)
try:
- if path.parent.parent != _media_root() or path.is_symlink() or not path.is_file():
+ if path.parent.parent != native_inputs_root() or path.is_symlink() or not path.is_file():
return None
if hashlib.sha256(path.read_bytes()).hexdigest() != path.parent.name:
return None
@@ -114,24 +116,32 @@ def replay_recent_images(api_messages: list[dict[str, Any]], keep: int) -> int:
return attached
+def _turn_replay_window(agent: Any) -> int:
+ """Images to replay this turn: 0 unless the model takes images natively. Resolved once per turn
+ (keyed on the turn's frozen admission clock and the model), not per tool-loop request."""
+ provider = (getattr(agent, "provider", "") or "").strip()
+ model = (getattr(agent, "model", "") or "").strip()
+ key = (getattr(agent, "_current_turn_timestamp", None), provider, model)
+ cached = getattr(agent, "_image_replay_window", None)
+ if cached is not None and cached[0] == key:
+ return cached[1]
+ from agent.image_routing import decide_image_input_mode
+ from hermes_cli.config import load_config_readonly
+
+ cfg = load_config_readonly()
+ keep = resolve_replay_recent_images(cfg)
+ if keep > 0 and decide_image_input_mode(provider, model, cfg) != "native":
+ keep = 0
+ agent._image_replay_window = (key, keep)
+ return keep
+
+
def replay_for_agent(agent: Any, api_messages: list[dict[str, Any]]) -> None:
"""``build_api_messages`` hook: replay only when this turn's model takes images natively."""
if not any(m.get("role") == "user" and isinstance(m.get("content"), str)
and m["content"].endswith(SCREENSHOT_MARKER) for m in api_messages):
return
- try:
- from agent.image_routing import decide_image_input_mode
- from hermes_cli.config import load_config
-
- cfg = load_config()
- keep = resolve_replay_recent_images(cfg)
- if keep <= 0:
- return
- provider = (getattr(agent, "provider", "") or "").strip()
- model = (getattr(agent, "model", "") or "").strip()
- if decide_image_input_mode(provider, model, cfg) != "native":
- return
- if attached := replay_recent_images(api_messages, keep):
- logger.info("image_replay: re-attached %d earlier image(s) to the request", attached)
- except Exception:
- logger.warning("image_replay: re-attaching earlier images failed", exc_info=True)
+ if (keep := _turn_replay_window(agent)) <= 0:
+ return
+ if attached := replay_recent_images(api_messages, keep):
+ logger.info("image_replay: re-attached %d earlier image(s) to the request", attached)
diff --git a/gateway/session_ingress_media.py b/gateway/session_ingress_media.py
index 4789c26eea9..76877b48c2b 100644
--- a/gateway/session_ingress_media.py
+++ b/gateway/session_ingress_media.py
@@ -60,11 +60,15 @@ def drop_capture_lease(paths=None):
del _leases[path]
-def _media_root():
+def native_inputs_root():
+ """This profile's content-addressed store of retained native inputs (``<root>/<sha256>/<name>``)."""
from gateway.platforms.base import get_document_cache_dir
return get_document_cache_dir().resolve() / 'native-inputs'
+_media_root = native_inputs_root
+
+
# Public ``prompt.submit`` attachments: a local client stages image bytes in the
# profile image cache (where messaging adapters stage downloads), the authority
# commits them as immutable bytes at admission so no later mutation or cache
diff --git a/tests/agent/test_image_replay.py b/tests/agent/test_image_replay.py
index 0b5464e5bb1..0a0458c6b49 100644
--- a/tests/agent/test_image_replay.py
+++ b/tests/agent/test_image_replay.py
@@ -63,6 +63,31 @@ def _rebuilt_request(tmp_path, live_turns):
return [m for m in request if m["role"] == "user"]
+def test_replay_window_is_resolved_once_per_turn(tmp_path):
+ """Every request of one turn (each tool-loop iteration) sends the same bytes, even if the config
+ changes mid-turn; the next turn picks the change up."""
+ _config()
+ live, _ = _live_turn(tmp_path, "label.png", "What is on this label?")
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session(session_id="s", source="api_server")
+ db.append_message("s", role="user", content=_durable_content(live["content"]), timestamp=1000.0)
+ db.append_message("s", role="assistant", content="reply", timestamp=1001.0)
+ history = db.get_messages_as_conversation("s") + [{"role": "user", "content": "and the expiry date?"}]
+ agent = _Agent()
+
+ def first_user_row():
+ request, _ = build_api_messages(
+ agent, history, current_turn_user_idx=len(history) - 1,
+ ext_prefetch_cache="", plugin_user_context="", moa_config=None, active_system_prompt="")
+ return next(m for m in request if m["role"] == "user")["content"]
+
+ assert first_user_row() == live["content"]
+ _config(mode="text")
+ assert first_user_row() == live["content"] # same turn: unchanged wire bytes
+ agent._current_turn_timestamp += 60 # next turn
+ assert isinstance(first_user_row(), str)
+
+
@pytest.mark.parametrize("mode,replayed", [("native", True), ("text", False)])
def test_rebuilt_turn_resends_the_image_byte_identical_only_for_native_input(tmp_path, mode, replayed):
_config(mode=mode)
diff --git a/website/docs/user-guide/features/vision.md b/website/docs/user-guide/features/vision.md
index 27bb55b94fb..c46c974635b 100644
--- a/website/docs/user-guide/features/vision.md
+++ b/website/docs/user-guide/features/vision.md
@@ -255,5 +255,6 @@ vision:
- The bytes come from the copy Hermes already keeps for every attached image under `cache/documents/native-inputs/` in the profile. Nothing new is stored, and the database and session messages API stay text only.
- A re-sent message is byte-identical to the request that first carried the image, so the provider's prompt cache stays valid. The request changes only when a newer image pushes one out of the window.
+- Replay reaches only images whose kept copy still exists. On the gateway and API server, that copy is removed once it is older than the media-cache age (24 hours), so a follow-up more than a day later sees `[screenshot]` again. The removal can also happen in the middle of a session, which changes the request once.
- Images outside the window, images sent as remote URLs (they can expire, which would fail every later turn), and retained files that are missing or changed keep the `[screenshot]` text.
- With `agent.image_input_mode: text`, or a model without native vision, nothing is re-sent. A value that is not a non-negative integer logs a warning and disables the replay.