Skip to content

The agent that grows with you

fix(line): keep progress heartbeats and stale mappings out of the postback cache (#106446)

Tranquil-Flow77c994bab29e
diff --git a/plugins/platforms/line/adapter.py b/plugins/platforms/line/adapter.py
index 6c0dfe08da6..c88c3a5d8db 100644
--- a/plugins/platforms/line/adapter.py
+++ b/plugins/platforms/line/adapter.py
@@ -3,7 +3,9 @@
* Reply token preferred (free, single-use, ~60s TTL), metered Push as fallback.
* Slow-LLM postback button past ``slow_response_threshold`` (45s; 0 disables): the reply
token is burned on a Template Buttons bubble; the tap yields a fresh free token that
- delivers the cached answer (PENDING → READY → DELIVERED, ERROR on cancel).
+ delivers the cached answer (PENDING → READY → DELIVERED, ERROR on cancel). Mid-turn
+ progress/status sends (``_interim_send`` metadata / busy-ack prefixes) bypass the cache;
+ a stale or vanished mapping falls through to a live wire send (#106446).
* Three allowlists (users U…, groups C…, rooms R…); ``LINE_ALLOW_ALL_USERS`` is dev-only.
* Media via public HTTPS only: local files served under ``/line/media/<token>/<name>``
(allowed-roots guard); ``LINE_PUBLIC_URL`` overrides host:port behind tunnels/wildcards.
@@ -67,6 +69,7 @@ DEFAULT_PENDING_REPLY_TEXT = "🤔 Still thinking. Tap below to fetch the answer
DEFAULT_BUTTON_LABEL = "Get answer"
DEFAULT_DELIVERED_TEXT = "Already replied ✅"
DEFAULT_INTERRUPTED_TEXT = "Run was interrupted before completion."
+DEFAULT_EXPIRED_TEXT = "That request has expired — send your message again."
MEDIA_TOKEN_TTL_SECONDS = 1800 # 30 minutes; LINE caches the URL aggressively
LINE_IMAGE_MAX_BYTES = 10 * 1024 * 1024 # 10 MB per LINE docs
LINE_AV_MAX_BYTES = 200 * 1024 * 1024 # 200 MB for voice/video
@@ -315,15 +318,28 @@ def build_postback_button_message(text: str, button_label: str, request_id: str)
return {"type": "template", "altText": alt, "template": {"type": "buttons", "text": truncated, "actions": [action]}}
-# Gateway busy-ack prefixes (interrupting / queued / steered / background review);
-# these bypass a PENDING postback cache so they land as visible bubbles.
-_SYSTEM_BYPASS_PREFIXES: Tuple[str, ...] = ("⚡ Interrupting", "⏳ Queued", "⏩ Steered", "💾")
+# Gateway busy-ack prefixes (interrupting / queued / steered / background review / working
+# heartbeat); these bypass a PENDING postback cache so they land as visible bubbles.
+_SYSTEM_BYPASS_PREFIXES: Tuple[str, ...] = ("⚡ Interrupting", "⏳ Queued", "⏩ Steered", "💾", "⏳ Working")
def _is_system_bypass(content: str) -> bool:
return bool(content) and any(content.startswith(p) for p in _SYSTEM_BYPASS_PREFIXES)
+def _is_interim_send(content: str, metadata: Optional[Dict[str, Any]] = None) -> bool:
+ """True for mid-turn progress/status sends that must not become the cached answer.
+
+ Purpose-first: the gateway stamps every mid-turn send with ``_interim_send`` metadata
+ (``gateway.run._interim_metadata``), which survives to the adapter and is stripped
+ before the wire. The text prefixes remain a fallback for callers that pass no
+ metadata. See #106446.
+ """
+ if (metadata or {}).get("_interim_send"):
+ return True
+ return _is_system_bypass(content)
+
+
def _csv_set(value: str) -> Set[str]:
return {x.strip() for x in (value or "").split(",") if x.strip()}
@@ -395,7 +411,8 @@ class LineAdapter(BasePlatformAdapter):
("pending_text", "LINE_PENDING_TEXT", DEFAULT_PENDING_REPLY_TEXT),
("button_label", "LINE_BUTTON_LABEL", DEFAULT_BUTTON_LABEL),
("delivered_text", "LINE_DELIVERED_TEXT", DEFAULT_DELIVERED_TEXT),
- ("interrupted_text", "LINE_INTERRUPTED_TEXT", DEFAULT_INTERRUPTED_TEXT)):
+ ("interrupted_text", "LINE_INTERRUPTED_TEXT", DEFAULT_INTERRUPTED_TEXT),
+ ("expired_text", "LINE_EXPIRED_TEXT", DEFAULT_EXPIRED_TEXT)):
setattr(self, attr, env_or(env, attr, default))
# Runtime state
self._client: Optional[_LineClient] = None
@@ -577,7 +594,20 @@ class LineAdapter(BasePlatformAdapter):
return
request_id = parsed.get("request_id", "") if parsed.get("action") == "show_response" else ""
entry = self._cache.get(request_id) if request_id else None
- if not self._client or not reply_token or not entry:
+ if not self._client or not reply_token:
+ return
+ if entry is None:
+ # The tap targets a button whose entry is gone (expired / lost with
+ # process state). Tell the user instead of leaving the chat stuck,
+ # and drop any mapping that still points at the dead request so
+ # later answers reach the wire. See #106446.
+ if request_id and self._pending_buttons.get(chat_id) == request_id:
+ self._pending_buttons.pop(chat_id, None)
+ messages = [_text_message(self.expired_text)]
+ try:
+ await self._client.reply(reply_token, messages)
+ except Exception as exc:
+ logger.debug("LINE: postback expired-notice reply failed: %s", exc)
return
state = entry.state
if state is State.READY:
@@ -630,14 +660,24 @@ class LineAdapter(BasePlatformAdapter):
) -> SendResult:
if not self._client:
return SendResult(success=False, error="LINE adapter not connected")
- # A PENDING postback button caches the response for the tap — except system
- # busy-acks, which must land as visible bubbles.
+ # A PENDING postback button caches the response for the tap — except interim /
+ # system sends (progress heartbeats, busy-acks), which must land as visible
+ # bubbles. Interim detection is purpose-first: the gateway marks every mid-turn
+ # status send with ``_interim_send`` (see ``gateway.run._interim_metadata``);
+ # the text prefixes stay as belt-and-suspenders for metadata-less callers.
pending_rid = self._pending_buttons.get(chat_id)
- if pending_rid and not _is_system_bypass(content):
- self._cache.set_ready(pending_rid, content)
- return SendResult(success=True, message_id=pending_rid)
- # System busy-acks (interrupting / queued / steered) bypass the postback cache and route directly to
- # LINE so they reach the user as visible bubbles. Source: PR #18153.
+ if pending_rid and not _is_interim_send(content, metadata):
+ entry = self._cache.get(pending_rid)
+ if entry is not None and entry.state is State.PENDING:
+ self._cache.set_ready(pending_rid, content)
+ return SendResult(success=True, message_id=pending_rid)
+ # Stale mapping: the entry is READY/DELIVERED/ERROR or gone entirely —
+ # absorbing this send would silently swallow the answer behind a dead
+ # button. Clear the mapping and deliver on the wire. See #106446.
+ self._pending_buttons.pop(chat_id, None)
+ # System busy-acks (interrupting / queued / steered) and progress heartbeats
+ # bypass the postback cache and route directly to LINE so they reach the user
+ # as visible bubbles. Source: PR #18153, #106446.
return await self._send_text_chunks(chat_id, content, force_push=False)
async def _send_text_chunks(self, chat_id: str, content: str, *, force_push: bool) -> SendResult:
diff --git a/tests/gateway/test_line_plugin.py b/tests/gateway/test_line_plugin.py
index 5a6386a7be9..af94d6d1bf2 100644
--- a/tests/gateway/test_line_plugin.py
+++ b/tests/gateway/test_line_plugin.py
@@ -310,6 +310,148 @@ class TestRegister:
assert ctx.kwargs["max_message_length"] <= 5000
+class TestSlowLLMPostbackRegression:
+ """Regression coverage for #106446: the slow-LLM postback cache must never
+ capture progress heartbeats as the final answer, never silently swallow a
+ later turn's answer behind a stale mapping, and never leave a chat stuck
+ after the postback target vanished.
+
+ Every test drives the REAL production paths — ``LineAdapter.send()`` and
+ ``LineAdapter._handle_postback_event()`` — with only the HTTP client
+ mocked, mirroring the reported symptoms from the issue.
+ """
+
+ EXPIRED_TEXT = "That request has expired — send your message again."
+
+ @pytest.fixture
+ def adapter(self, monkeypatch):
+ monkeypatch.delenv("LINE_CHANNEL_ACCESS_TOKEN", raising=False)
+ monkeypatch.delenv("LINE_CHANNEL_SECRET", raising=False)
+ monkeypatch.delenv("LINE_EXPIRED_TEXT", raising=False)
+ from gateway.config import PlatformConfig
+ cfg = PlatformConfig(enabled=True, extra={
+ "channel_access_token": "tok",
+ "channel_secret": "sec",
+ })
+ ad = LineAdapter(cfg)
+ ad._client = MagicMock()
+ ad._client.reply = AsyncMock()
+ ad._client.push = AsyncMock()
+ return ad
+
+ def _arm(self, adapter, chat_id="Uchat", payload=None, drop=False):
+ """Register a PENDING postback button the way ``_keep_typing`` does."""
+ rid = adapter._cache.register_pending(chat_id)
+ if payload is not None:
+ adapter._cache.set_ready(rid, payload)
+ if not drop:
+ adapter._pending_buttons[chat_id] = rid
+ return rid
+
+ # -- Layer 1: progress must not capture the cache --------------------
+
+ def test_heartbeat_prefix_does_not_capture_pending_cache(self, adapter):
+ rid = self._arm(adapter)
+ result = asyncio.run(adapter.send("Uchat", "⏳ Working — 3 min — iteration 1/60, research_market"))
+ assert result.success
+ entry = adapter._cache.get(rid)
+ assert entry.state is State.PENDING, "heartbeat must not transition PENDING → READY"
+ assert entry.payload is None
+ # and it must land as a visible bubble on the wire
+ assert adapter._client.push.await_count >= 1 or adapter._client.reply.await_count >= 1
+
+ def test_interim_metadata_send_does_not_capture_pending_cache(self, adapter):
+ rid = self._arm(adapter)
+ result = asyncio.run(adapter.send(
+ "Uchat", "working on it", metadata={"_interim_send": True}))
+ assert result.success
+ entry = adapter._cache.get(rid)
+ assert entry.state is State.PENDING, "interim (mid-turn) sends must not transition PENDING → READY"
+ assert adapter._client.push.await_count >= 1
+
+ def test_final_answer_still_caches_when_pending(self, adapter):
+ # The core feature must survive the fix: a genuine final answer
+ # (no interim marker, no system prefix) still fills the PENDING cache.
+ rid = self._arm(adapter)
+ result = asyncio.run(adapter.send("Uchat", "Final answer: task completed"))
+ assert result.success
+ entry = adapter._cache.get(rid)
+ assert entry.state is State.READY
+ assert entry.payload == "Final answer: task completed"
+ adapter._client.push.assert_not_awaited()
+ adapter._client.reply.assert_not_awaited()
+
+ # -- Layer 2: stale mapping must not swallow later answers ------------
+
+ def test_stale_ready_mapping_falls_through_to_wire(self, adapter):
+ # The outstanding mapping references an entry that is already READY
+ # (a previous answer waiting for a tap). The next turn's answer must
+ # NOT be absorbed into that entry — it must reach the wire.
+ rid = self._arm(adapter, payload="Previous answer")
+ result = asyncio.run(adapter.send("Uchat", "Answer to the NEXT user message"))
+ assert result.success
+ assert adapter._cache.get(rid).payload == "Previous answer", "stale entry untouched"
+ assert adapter._client.push.await_count >= 1, "later answer must be delivered on the wire"
+ # The stale mapping must be cleared so subsequent sends aren't stuck.
+ assert "Uchat" not in adapter._pending_buttons
+
+ def test_missing_entry_mapping_falls_through_to_wire(self, adapter):
+ # The mapping references an entry that no longer exists at all.
+ self._arm(adapter, drop=True)
+ adapter._pending_buttons["Uchat"] = "ghost-rid"
+ result = asyncio.run(adapter.send("Uchat", "Answer to the NEXT user message"))
+ assert result.success
+ assert adapter._client.push.await_count >= 1
+ assert "Uchat" not in adapter._pending_buttons
+
+ # -- Layer 3: missing postback target must not leave the chat stuck --
+
+ def test_postback_for_missing_entry_clears_mapping_and_notifies(self, adapter):
+ # A tap on a button whose cache entry vanished must produce a user-
+ # visible notice (not silence) and clean up the dead mapping.
+ adapter._pending_buttons["Uchat"] = "ghost-rid"
+ event = {
+ "type": "postback",
+ "replyToken": "reply-token",
+ "source": {"type": "user", "userId": "Uchat"},
+ "postback": {"data": json.dumps({"action": "show_response", "request_id": "ghost-rid"})},
+ }
+ asyncio.run(adapter._handle_postback_event(event))
+ adapter._client.reply.assert_awaited_once()
+ sent = adapter._client.reply.await_args.args[1]
+ assert any("expired" in (m.get("text") or "").lower() for m in sent), (
+ "missing postback target must yield an expiry notice, not silence"
+ )
+ assert "Uchat" not in adapter._pending_buttons, "dead mapping must be cleaned"
+
+ def test_postback_for_pending_entry_keeps_mapping(self, adapter):
+ # Guard the feature: a tap while the LLM is still running must NOT
+ # clear the mapping — the eventual final answer still needs it.
+ rid = self._arm(adapter)
+ event = {
+ "type": "postback",
+ "replyToken": "reply-token",
+ "source": {"type": "user", "userId": "Uchat"},
+ "postback": {"data": json.dumps({"action": "show_response", "request_id": rid})},
+ }
+ asyncio.run(adapter._handle_postback_event(event))
+ assert adapter._cache.get(rid).state is State.PENDING
+ assert adapter._pending_buttons.get("Uchat") == rid
+
+ def test_expired_text_config_overrides_default(self, monkeypatch):
+ monkeypatch.delenv("LINE_CHANNEL_ACCESS_TOKEN", raising=False)
+ monkeypatch.delenv("LINE_CHANNEL_SECRET", raising=False)
+ monkeypatch.delenv("LINE_EXPIRED_TEXT", raising=False)
+ from gateway.config import PlatformConfig
+ cfg = PlatformConfig(enabled=True, extra={
+ "channel_access_token": "tok",
+ "channel_secret": "sec",
+ "expired_text": self.EXPIRED_TEXT,
+ })
+ ad = LineAdapter(cfg)
+ assert ad.expired_text == self.EXPIRED_TEXT
+
+
class TestEnvEnablement:
def test_returns_none_without_credentials(self, monkeypatch):