fix(session): require user anchor for delivery retention

This commit is contained in:
chengyongru 2026-08-07 10:28:59 +08:00 committed by chengyongru
parent 60282d1588
commit 8dfce4c162
2 changed files with 20 additions and 4 deletions

View File

@ -352,12 +352,14 @@ class Session:
start_idx = max(0, len(self.messages) - max_messages)
if extend_to_user:
start_idx = next(
recovered_user = next(
(i for i in range(start_idx, -1, -1) if self.messages[i].get("role") == "user"),
start_idx,
None,
)
if start_idx > 0 and self.messages[start_idx - 1].get("_channel_delivery"):
start_idx -= 1
if recovered_user is not None:
start_idx = recovered_user
if start_idx > 0 and self.messages[start_idx - 1].get("_channel_delivery"):
start_idx -= 1
retained = self.messages[start_idx:]

View File

@ -120,6 +120,20 @@ def test_retain_extend_to_user_matches_get_history_boundary():
assert _contents(session.messages) == _contents(expected)
def test_retain_extend_to_user_does_not_extend_delivery_only_tail():
session = Session(key="test:extend-no-user")
for i in range(4):
session.messages.append(_delivery(f"notification {i}"))
session.retain_recent_legal_suffix(3, extend_to_user=True)
assert _contents(session.messages) == [
"notification 1",
"notification 2",
"notification 3",
]
# --- Only the immediately-preceding delivery is part of the anchor ---