Skip to content

The agent that grows with you

fix(agent): replayed images leave the window in sticky batches

Teknium6899e45dec3b
diff --git a/agent/image_replay.py b/agent/image_replay.py
index bb7be961a22..a981f570837 100644
--- a/agent/image_replay.py
+++ b/agent/image_replay.py
@@ -10,7 +10,9 @@ 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
+newest images (default 3, 0 = off) go back as ``image_url`` parts; older ones drop in whole
+batches of that size (``replay_frontier``), so the cached prefix is rewritten at most once per
+batch rather than on every new photo. 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
@@ -88,43 +90,54 @@ def _retained_data_url(ref: str) -> Optional[str]:
return _file_to_data_url(path)
+def replay_frontier(total: int, keep: int) -> int:
+ """Oldest image slot still replayed when the request holds ``total`` images.
+
+ The frontier moves forward only in whole batches of ``keep``: the newest ``keep`` to
+ ``2 * keep - 1`` images replay, and an image that drops out stays dropped as the session
+ grows. A strict newest-``keep`` window would turn one early row back into ``[screenshot]``
+ text on every new photo, rewriting the cached prefix each time; this rewrites it at most once
+ per ``keep`` new images. Counted by slot position (missing or changed files hold their slot),
+ so a swept file never moves the frontier."""
+ return (total - keep) // keep * keep if total > keep else 0
+
+
def replay_recent_images(api_messages: list[dict[str, Any]], keep: int) -> int:
- """Rebuild the newest ``keep`` images in place on ``api_messages`` (wire copies); images still
- live in the conversation count toward the window. Returns the number re-attached."""
- budget, plan = keep, []
- for msg in reversed(api_messages):
- if budget <= 0:
- break
+ """Rebuild retained images at or after ``replay_frontier`` in place on ``api_messages`` (wire
+ copies); images still live in the conversation hold slots too. Returns the number re-attached."""
+ slots = 0
+ rows: list[tuple[dict[str, Any], list[tuple[str, Any]], int]] = []
+ for msg in api_messages:
if msg.get("role") != "user":
continue
content = msg.get("content")
if isinstance(content, list):
- budget -= sum(1 for p in content if isinstance(p, dict) and p.get("type") in _IMAGE_PART_TYPES)
+ slots += sum(1 for p in content if isinstance(p, dict) and p.get("type") in _IMAGE_PART_TYPES)
continue
parts = _split_rebuilt_row(content) if isinstance(content, str) else None
if parts is None:
continue
- images = [i for i, (kind, _) in enumerate(parts) if kind == "image"]
- urls: dict[int, str] = {}
- for i in reversed(images): # a row's latest image first
- if budget > 0 and (url := _retained_data_url(parts[i][1][0])):
- urls[i] = url
- budget -= 1
- if urls:
- plan.append((msg, parts, urls))
+ rows.append((msg, parts, slots))
+ slots += sum(1 for kind, _ in parts if kind == "image")
+ frontier = replay_frontier(slots, keep)
attached = 0
- for msg, parts, urls in plan:
+ for msg, parts, slot in rows:
rebuilt: list[dict[str, Any]] = []
- for i, (kind, value) in enumerate(parts):
+ urls = 0
+ for kind, value in parts:
if kind == "text":
rebuilt.append({"type": "text", "text": value})
- elif i in urls:
- image = {"url": urls[i], **({"detail": value[1]} if value[1] else {})}
- rebuilt.append({"type": "image_url", "image_url": image})
+ continue
+ url = _retained_data_url(value[0]) if slot >= frontier else None
+ slot += 1
+ if url:
+ rebuilt.append({"type": "image_url", "image_url": {"url": url, **({"detail": value[1]} if value[1] else {})}})
+ urls += 1
else:
rebuilt.append({"type": "text", "text": value[2]})
- msg["content"] = rebuilt
- attached += len(urls)
+ if urls:
+ msg["content"] = rebuilt
+ attached += urls
return attached
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index 638a2de74dd..d143219bb9d 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -896,7 +896,8 @@ prompt_caching:
# # agent; a number applies everywhere; 0 = unlimited.
# max_calls_per_image: 3
# # Newest user images re-sent on turns rebuilt from the session DB (API server,
-# # --resume) when the model takes images natively; 0 = off.
+# # --resume) when the model takes images natively; 0 = off. Older images drop
+# # in whole batches of this size, so the cached prefix changes once per batch.
# replay_recent_images: 3
#
# auxiliary:
diff --git a/tests/agent/test_image_replay.py b/tests/agent/test_image_replay.py
index bff2c1680a0..9ff0b9afa10 100644
--- a/tests/agent/test_image_replay.py
+++ b/tests/agent/test_image_replay.py
@@ -117,7 +117,9 @@ def test_replay_window_skips_untrusted_bytes_and_typed_markers(tmp_path):
assert users[4]["content"] == newest["content"]
assert users[3]["content"].endswith("\n[screenshot]") # tampered bytes are never replayed
assert users[2]["content"] == "I literally typed\n[screenshot]"
- assert users[1]["content"] == older["content"]
+ # The tampered image still holds its window slot: a swept or changed file never pulls an
+ # older image back in (that would rewrite an earlier row of the cached prefix).
+ assert users[1]["content"].endswith("\n[screenshot]")
assert users[0]["content"].endswith("\n[screenshot]") # outside the 2-image window
@@ -153,3 +155,28 @@ def test_api_server_image_replays_with_its_position_and_detail(tmp_path, parts):
live = {"role": "user", "content": restore_api_images(parts, commit_api_images(parts))}
assert _rebuilt_request(tmp_path, [live])[0]["content"] == live["content"]
+
+
+def test_growing_session_drops_replayed_images_in_sticky_batches(tmp_path):
+ """Ten single-image turns, keep=3, one request per turn through ``build_api_messages``: earlier
+ rows change at most once per batch of ``keep`` new images, and a dropped image never returns."""
+ _config(replay_recent_images=3)
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session(session_id="s", source="api_server")
+ previous, dropped, rewrites = [], set(), 0
+ for n in range(10):
+ live, _ = _live_turn(tmp_path, f"p{n}.png", f"photo {n}", data=_PNG + bytes([n]))
+ db.append_message("s", role="user", content=_durable_content(live["content"]), timestamp=1000.0 + 2 * n)
+ db.append_message("s", role="assistant", content=f"reply {n}", timestamp=1001.0 + 2 * n)
+ history = db.get_messages_as_conversation("s") + [{"role": "user", "content": "and now?"}]
+ 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="")
+ rows = [m["content"] for m in request if m["role"] == "user"][:-1]
+ rewrites += any(old != new for old, new in zip(previous, rows))
+ replayed = {i for i, row in enumerate(rows) if isinstance(row, list)}
+ assert not dropped & replayed
+ dropped |= set(range(len(rows))) - replayed
+ assert len(replayed) >= min(3, len(rows))
+ previous = rows
+ assert rewrites <= -(-10 // 3)
diff --git a/website/docs/user-guide/features/vision.md b/website/docs/user-guide/features/vision.md
index 8e46aa528db..4b466ce0f8a 100644
--- a/website/docs/user-guide/features/vision.md
+++ b/website/docs/user-guide/features/vision.md
@@ -254,7 +254,7 @@ 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.
+- A re-sent message is byte-identical to the request that first carried the image, so the provider's prompt cache stays valid. Older images leave the window in batches: with the default 3, the newest 3 to 5 images are re-sent, and every third new image drops the oldest batch at once. An earlier message is rewritten at most once per batch, not on every new photo, and an image that left the window does not come back.
- Replay reaches only images whose kept copy still exists. On the gateway, the kept copy of an image attached in chat 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 sent to the API server stay with the API request record that carried them and are not removed by that 24-hour cleanup.
- 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.