Skip to content

The agent that grows with you

fix(photon): keep the user's words when they reply in an iMessage thread (#100663)

David Uche348a68bb4e88
diff --git a/plugins/platforms/photon/adapter.py b/plugins/platforms/photon/adapter.py
index 5f8ada9998c..e19790af803 100644
--- a/plugins/platforms/photon/adapter.py
+++ b/plugins/platforms/photon/adapter.py
@@ -509,6 +509,31 @@ def _normalize_content(content: Dict[str, Any]) -> _Normalized:
return normalize(content)
+def _sent_text_key(chat_id: Optional[str]) -> Optional[str]:
+ """DM GUID (``any;-;+1555...``) and bare E.164 address one space; index under the phone."""
+ if not chat_id:
+ return None
+ match = re.match(r"^any;-;(\+\d{6,})$", chat_id)
+ return match.group(1) if match else chat_id
+
+
+async def _record_sent_text_async(chat_id: Optional[str], message_id: Optional[str], text: Optional[str]) -> None:
+ """Remember what we sent so a later threaded reply to it carries the quoted text. Never raises."""
+ try:
+ from gateway import rich_sent_store
+ await rich_sent_store.record_async(_sent_text_key(chat_id), message_id, text)
+ except Exception:
+ logger.debug("[photon] sent-text index record failed", exc_info=True)
+
+
+def _lookup_sent_text(chat_id: Optional[str], message_id: Optional[str]) -> Optional[str]:
+ try:
+ from gateway import rich_sent_store
+ return rich_sent_store.lookup(_sent_text_key(chat_id), message_id)
+ except Exception:
+ return None
+
+
def _attachment_body(space_id: str, safe_path: str, *, kind: str, name: Optional[str] = None,
mime_type: Optional[str] = None, caption: Optional[str] = None) -> Dict[str, Any]:
"""``/send-attachment`` body; spectrum-ts infers name/mimeType from the extension,
@@ -802,11 +827,29 @@ class PhotonAdapter(BasePlatformAdapter):
sender_id = sender.get("id") or space.get("phone") or space_id
timestamp = _parse_timestamp(event.get("timestamp") or "")
message_id = event.get("messageId")
+ # iMessage threaded reply (spectrum 12.x): unwrap to the inner content so the user's
+ # words go through the normal ladder, and keep the quoted target as reply context
+ # (#100663). Malformed envelopes fall through to the unknown-type marker.
+ reply_ctx: Dict[str, Any] = {}
+ if content.get("type") == "reply" and isinstance(content.get("content"), dict) \
+ and content["content"].get("type") not in (None, "unknown"):
+ target_id = content.get("targetMessageId")
+ reply_ctx = {"reply_to_message_id": target_id,
+ "reply_to_text": content.get("targetText") or None,
+ "reply_to_is_own_message": content.get("targetDirection") == "outbound" or bool(
+ target_id and target_id in self._sent_message_ids)}
+ if target_id and not reply_ctx["reply_to_text"]:
+ # spectrum often can't hydrate the target's text (e.g. our own sends, older
+ # bubbles): fall back to the local index of what we sent.
+ reply_ctx["reply_to_text"] = _lookup_sent_text(space_id, target_id)
+ content = content["content"]
ctype = content.get("type")
def _event(text: str, mtype: MessageType = MessageType.TEXT, **kwargs: Any) -> MessageEvent:
source = self.build_source(chat_id=space_id, chat_name=space_id, chat_type=chat_type,
user_id=sender_id, user_name=sender_id or None, message_id=message_id)
+ for key, value in reply_ctx.items():
+ kwargs.setdefault(key, value)
return MessageEvent(text=text, message_type=mtype, source=source, message_id=message_id,
raw_message=event, timestamp=timestamp, **kwargs)
if ctype in {"read", "read_receipt"}: # presence signal, not a user turn (receipts for our sends)
@@ -1208,7 +1251,11 @@ class PhotonAdapter(BasePlatformAdapter):
async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None) -> SendResult:
- return await self._sidecar_send(chat_id, self.format_message(content))
+ formatted = self.format_message(content)
+ result = await self._sidecar_send(chat_id, formatted)
+ if result.success:
+ await _record_sent_text_async(chat_id, result.message_id, formatted)
+ return result
async def send_clarify(self, chat_id: str, question: str, choices: Optional[list], clarify_id: str,
session_key: str, metadata: Optional[Dict[str, Any]] = None) -> SendResult:
@@ -1468,7 +1515,11 @@ class PhotonAdapter(BasePlatformAdapter):
return SendResult(success=False, error=f"unsafe or missing attachment path: {path}")
body = _attachment_body(
space_id, safe_path, kind=kind, name=name, mime_type=mime_type or _guess_mime(safe_path), caption=caption)
- return await self._post_send("/send-attachment", body, structured=True)
+ result = await self._post_send("/send-attachment", body, structured=True)
+ if result.success:
+ label = caption or f"[{kind}: {name or os.path.basename(safe_path)}]"
+ await _record_sent_text_async(space_id, result.message_id, label)
+ return result
async def _sidecar_call(self, path: str, body: Dict[str, Any]) -> Dict[str, Any]:
if self._http_client is None:
@@ -1615,6 +1666,7 @@ async def _standalone_send(
if not data:
return _standalone_error(resp)
last_message_id = data.get("messageId")
+ await _record_sent_text_async(chat_id, last_message_id, message)
# 2. Each attachment as a separate /send-attachment call; media_files is
# List[Tuple[path, is_voice]] (filter_media_delivery_paths).
for media_path, is_voice in media_files or []:
diff --git a/plugins/platforms/photon/sidecar/index.mjs b/plugins/platforms/photon/sidecar/index.mjs
index 27109508ea4..beb4ad5a5ac 100644
--- a/plugins/platforms/photon/sidecar/index.mjs
+++ b/plugins/platforms/photon/sidecar/index.mjs
@@ -572,6 +572,24 @@ async function normalizeContent(content) {
targetText: reactionTargetText(target),
};
}
+ // iMessage threaded (swipe) reply: spectrum 12.x wraps it as
+ // {type: "reply", content: <inner Content>, target: <Message>}. Normalise the
+ // inner content with the normal ladder and carry a light pointer to the
+ // quoted message, so Python can unwrap it instead of dropping the user's
+ // words as "content type not handled" (#100663).
+ if (content.type === "reply") {
+ const target = content.target;
+ return {
+ type: "reply",
+ content:
+ content.content && typeof content.content === "object"
+ ? await normalizeContent(content.content)
+ : { type: "unknown" },
+ targetMessageId: target?.id ?? null,
+ targetDirection: target?.direction ?? null,
+ targetText: reactionTargetText(target),
+ };
+ }
// A user tapping a poll choice arrives as `poll_option` carrying the chosen
// option title + whether it was selected (true) or deselected (false). This
// is how a native iMessage poll's vote streams back — Python turns a
diff --git a/tests/plugins/platforms/photon/test_threaded_replies.py b/tests/plugins/platforms/photon/test_threaded_replies.py
new file mode 100644
index 00000000000..d97cf0d5100
--- /dev/null
+++ b/tests/plugins/platforms/photon/test_threaded_replies.py
@@ -0,0 +1,222 @@
+"""Inbound iMessage threaded (swipe) replies for PhotonAdapter (#100663).
+
+spectrum-ts 12.x wraps a threaded reply as ``{type: "reply", content, target}``. The
+sidecar normalises it to ``{type: "reply", content, targetMessageId, targetDirection,
+targetText}``; the adapter must unwrap it instead of emitting
+"[Photon content type not handled: reply]", and carry the quoted message as reply
+context. spectrum usually can't hydrate the text of our own outbound bubbles, so the
+adapter records what it sends in ``gateway.rich_sent_store`` and falls back to that.
+"""
+from __future__ import annotations
+
+import os
+from typing import Any, Dict, List, Tuple
+
+import pytest
+
+from gateway.config import PlatformConfig
+from gateway.platforms.event import MessageEvent, MessageType
+from plugins.platforms.photon import adapter as photon_adapter
+from plugins.platforms.photon.adapter import PhotonAdapter
+
+PHONE = "+15550001234"
+DM = f"any;-;{PHONE}"
+
+
[email protected](autouse=True)
+def _isolated_sent_index(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
+ # rich_sent_store writes under HERMES_HOME/state; keep each test's index private.
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+
+
+def _make_adapter(monkeypatch: pytest.MonkeyPatch, **extra: Any) -> PhotonAdapter:
+ monkeypatch.setenv("PHOTON_PROJECT_ID", "test-project-id")
+ monkeypatch.setenv("PHOTON_PROJECT_SECRET", "test-project-secret")
+ return PhotonAdapter(PlatformConfig(enabled=True, token="", extra=dict(extra)))
+
+
+def _capture_handled(adapter: PhotonAdapter, monkeypatch: pytest.MonkeyPatch) -> List[MessageEvent]:
+ captured: List[MessageEvent] = []
+
+ async def fake_handle(event: MessageEvent) -> None:
+ captured.append(event)
+
+ monkeypatch.setattr(adapter, "handle_message", fake_handle)
+ return captured
+
+
+def _capture_sidecar(adapter: PhotonAdapter, message_id: str = "out-1") -> List[Tuple[str, Dict[str, Any]]]:
+ calls: List[Tuple[str, Dict[str, Any]]] = []
+
+ async def fake_call(path: str, body: Dict[str, Any]) -> Dict[str, Any]:
+ calls.append((path, body))
+ return {"ok": True, "messageId": message_id}
+
+ adapter._sidecar_call = fake_call # type: ignore[assignment]
+ return calls
+
+
+def _reply_event(inner: Dict[str, Any], *, message_id: str = "in-2", target_id: str = "out-0",
+ direction: str = "outbound", target_text: str | None = "earlier answer") -> Dict[str, Any]:
+ return {
+ "messageId": message_id,
+ "space": {"id": DM, "type": "dm", "phone": PHONE},
+ "sender": {"id": PHONE},
+ "timestamp": "2026-09-25T18:00:00Z",
+ "content": {"type": "reply", "content": inner, "targetMessageId": target_id,
+ "targetDirection": direction, "targetText": target_text},
+ }
+
+
+async def test_threaded_text_reply_reaches_agent_with_context(monkeypatch):
+ adapter = _make_adapter(monkeypatch)
+ handled = _capture_handled(adapter, monkeypatch)
+
+ await adapter._dispatch_inbound(_reply_event({"type": "text", "text": "yes do it"}))
+
+ assert len(handled) == 1
+ event = handled[0]
+ assert event.text == "yes do it"
+ assert event.reply_to_message_id == "out-0"
+ assert event.reply_to_text == "earlier answer"
+ assert event.reply_to_is_own_message is True
+
+
+# 1x1 transparent PNG (passes the base adapter's image magic check).
+_PNG_1X1_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
+
+
+async def test_threaded_photo_reply_keeps_the_photo(monkeypatch):
+ """The inner content goes through the normal ladder, so a threaded photo is not reduced to text."""
+ adapter = _make_adapter(monkeypatch)
+ handled = _capture_handled(adapter, monkeypatch)
+
+ inner = {"type": "attachment", "name": "pic.png", "mimeType": "image/png", "size": 68,
+ "data": _PNG_1X1_B64, "encoding": "base64"}
+ await adapter._dispatch_inbound(_reply_event(inner))
+
+ event = handled[0]
+ assert event.message_type == MessageType.PHOTO
+ assert event.media_types == ["image/png"]
+ assert len(event.media_urls) == 1
+ assert event.reply_to_message_id == "out-0"
+
+
+async def test_reply_to_users_own_message_is_not_marked_own(monkeypatch):
+ adapter = _make_adapter(monkeypatch)
+ handled = _capture_handled(adapter, monkeypatch)
+
+ await adapter._dispatch_inbound(_reply_event({"type": "text", "text": "ctx"}, direction="inbound"))
+
+ assert handled[0].text == "ctx"
+ assert handled[0].reply_to_is_own_message is False
+
+
+async def test_malformed_reply_envelope_keeps_fallback_marker(monkeypatch):
+ adapter = _make_adapter(monkeypatch)
+ handled = _capture_handled(adapter, monkeypatch)
+
+ await adapter._dispatch_inbound(_reply_event({"type": "unknown"}))
+
+ assert handled[0].text == "[Photon content type not handled: reply]"
+
+
+async def test_reply_to_our_message_hydrates_quoted_text_from_sent_index(monkeypatch):
+ adapter = _make_adapter(monkeypatch)
+ handled = _capture_handled(adapter, monkeypatch)
+ calls = _capture_sidecar(adapter, message_id="out-1")
+
+ # We send, the user later swipe-replies to that bubble; spectrum gives no target text.
+ await adapter.send(DM, "the plan is A then B")
+ assert calls[-1][0] == "/send"
+ await adapter._dispatch_inbound(
+ _reply_event({"type": "text", "text": "do B first"}, target_id="out-1", target_text=None))
+
+ assert handled[-1].text == "do B first"
+ assert handled[-1].reply_to_message_id == "out-1"
+ assert handled[-1].reply_to_text == "the plan is A then B"
+ assert handled[-1].reply_to_is_own_message is True
+
+
+async def test_send_to_bare_phone_is_found_from_dm_guid(monkeypatch):
+ """Cron/standalone sends often target the bare E.164; replies arrive in the DM GUID space."""
+ adapter = _make_adapter(monkeypatch)
+ handled = _capture_handled(adapter, monkeypatch)
+ _capture_sidecar(adapter, message_id="out-7")
+
+ await adapter.send(PHONE, "morning briefing")
+ await adapter._dispatch_inbound(
+ _reply_event({"type": "text", "text": "more on item 2"}, target_id="out-7", target_text=None))
+
+ assert handled[-1].reply_to_text == "morning briefing"
+
+
+async def test_attachment_send_is_recorded_as_label(monkeypatch, tmp_path):
+ monkeypatch.setattr(PhotonAdapter, "validate_media_delivery_path",
+ staticmethod(lambda p: p if os.path.exists(p) else None))
+ img = tmp_path / "chart.png"
+ img.write_bytes(b"\x89PNG fake")
+ adapter = _make_adapter(monkeypatch)
+ handled = _capture_handled(adapter, monkeypatch)
+ _capture_sidecar(adapter, message_id="out-3")
+
+ await adapter.send_image_file(DM, str(img))
+ await adapter._dispatch_inbound(
+ _reply_event({"type": "text", "text": "what is this"}, target_id="out-3", target_text=None))
+
+ assert handled[-1].reply_to_text == "[attachment: chart.png]"
+
+
+async def test_standalone_send_records_text(monkeypatch):
+ monkeypatch.setenv("PHOTON_SIDECAR_TOKEN", "tok")
+
+ class _Resp:
+ status_code = 200
+
+ @staticmethod
+ def json() -> Dict[str, Any]:
+ return {"ok": True, "messageId": "cron-1"}
+
+ class _FakeClient:
+ def __init__(self, *a, **k):
+ pass
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *a):
+ return False
+
+ async def post(self, url: str, json: Dict[str, Any], headers=None):
+ return _Resp()
+
+ monkeypatch.setattr(photon_adapter.httpx, "AsyncClient", _FakeClient)
+ cfg = PlatformConfig(enabled=True, token="", extra={})
+ result = await photon_adapter._standalone_send(cfg, PHONE, "daily digest")
+ assert result.get("success") is True
+
+ adapter = _make_adapter(monkeypatch)
+ handled = _capture_handled(adapter, monkeypatch)
+ await adapter._dispatch_inbound(
+ _reply_event({"type": "text", "text": "thanks"}, target_id="cron-1", target_text=None))
+
+ assert handled[-1].reply_to_text == "daily digest"
+
+
+async def test_unknown_reply_target_leaves_text_empty(monkeypatch):
+ adapter = _make_adapter(monkeypatch)
+ handled = _capture_handled(adapter, monkeypatch)
+
+ await adapter._dispatch_inbound(_reply_event({"type": "text", "text": "?"}, target_text=None))
+
+ assert handled[-1].text == "?"
+ assert handled[-1].reply_to_text is None