Skip to content

Commit f9bb5e3

Browse files
authored
Merge pull request loopx-project#8999 from loopx-project/codex/lark-historical-native-reply-images-20261118
Recover captured images from legacy Lark private replies
2 parents 4cb0625 + d80c1d1 commit f9bb5e3

3 files changed

Lines changed: 151 additions & 21 deletions

File tree

‎loopx/capabilities/native_chat/file_discovery.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ def rows(self, directory: Path, paths: Iterable[Path], *,
149149
".gif": "image/gif", ".webp": "image/webp",
150150
}
151151
_REPLY_IMAGE_SIGNATURES = {"image/png": b"\x89PNG\r\n\x1a\n", "image/jpeg": b"\xff\xd8\xff", "image/gif": b"GIF8"}
152+
REPLY_IMAGE_NAME_PATTERN = re.compile(r"[a-zA-Z0-9][a-zA-Z0-9_.-]{0,119}")
152153

153154

154155
def reply_image_directory(turn_id: str) -> Path:
@@ -189,7 +190,7 @@ def reply_image_attachment(data: bytes, mime: str, index: int) -> dict[str, Any]
189190
def read_reply_image(workspace: Path, turn_id: str, name: str) -> tuple[str, bytes]:
190191
from ...control_plane.collaboration.result_files import _workspace_file
191192

192-
if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]{0,119}", name):
193+
if not REPLY_IMAGE_NAME_PATTERN.fullmatch(name):
193194
raise ValueError("invalid reply image name")
194195
mime = _REPLY_IMAGE_TYPES.get(Path(name).suffix.lower())
195196
if mime is None:

‎loopx/extensions/lark/private_conversations.py‎

Lines changed: 44 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,9 @@
2727
STEWARD_BINDING_ADOPTION_PENDING,
2828
)
2929
from ...capabilities.native_chat.conversation_bindings import ChatConversationBindings
30-
from ...capabilities.native_chat.file_discovery import FileChatDiscovery, file_change_fingerprint, reply_image_workspace
30+
from ...capabilities.native_chat.file_discovery import (
31+
REPLY_IMAGE_NAME_PATTERN, FileChatDiscovery, file_change_fingerprint, reply_image_workspace,
32+
)
3133
from ...chat_attachments import CHAT_IMAGE_MAX_COUNT, normalize_chat_image_attachments
3234
from ...chat_store import CHAT_MESSAGE_SCHEMA_VERSION, ChatSessionStore, TERMINAL_TURN_STATES, _atomic_write_json, _read_json
3335
from ...control_plane.collaboration import conversation_reply_context
@@ -1567,35 +1569,45 @@ def _historical_image_source(self, record: Mapping[str, Any], plan: Mapping[str,
15671569
for key in ("request_ref", "binding_id", "source", "session_id", "turn_id"))):
15681570
raise ValueError("original request no longer matches")
15691571
turn = self.core.controller.store.load_turn(record["session_id"], record["turn_id"]) or {}
1570-
if (not isinstance(answer := (turn.get("response") or {}).get("message"), str)
1572+
response = turn.get("response") or {}
1573+
if (not isinstance(answer := response.get("message"), str)
15711574
or hashlib.sha256(answer.encode()).hexdigest() != plan["answer_sha256"]
15721575
or terminal.get("text") != _presentation_text(answer)
1573-
or not private_answer_images(answer)[1]
15741576
or (session := resumable_answer_image_session(self.core, native, turn)) is None):
15751577
raise ValueError("original completed answer or its authority changed")
1578+
image_targets = private_answer_images(answer)[1]
1579+
if "captured_images" in plan:
1580+
if image_targets or response.get("answer_image_plan") or reply_image_workspace(session, turn) is None:
1581+
raise ValueError("original reply is not a qualified legacy project answer")
1582+
elif not image_targets:
1583+
raise ValueError("original remote image reply unavailable")
15761584
return session
15771585

15781586
def _historical_image_plan(self, record: Mapping[str, Any], plan: Mapping[str, Any]) -> dict:
15791587
from ..public_source_reader import public_url
15801588

1581-
if set(plan) != {"binding_id", "turn_id", "message_id", "answer_sha256", "images"}:
1589+
captured = "captured_images" in plan
1590+
image_field, reference_field = ("captured_images", "name") if captured else ("images", "url")
1591+
if set(plan) != {"binding_id", "turn_id", "message_id", "answer_sha256", image_field}:
15821592
raise ValueError("invalid original image repair fields")
15831593
if (not isinstance(plan["message_id"], str) or not LARK_MESSAGE_ID_PATTERN.fullmatch(plan["message_id"])
15841594
or not isinstance(plan["answer_sha256"], str)
15851595
or not BARE_SHA256_PATTERN.fullmatch(plan["answer_sha256"])
1586-
or not isinstance(plan["images"], list) or not 1 <= len(plan["images"]) <= CHAT_IMAGE_MAX_COUNT):
1596+
or not isinstance(plan[image_field], list) or not 1 <= len(plan[image_field]) <= CHAT_IMAGE_MAX_COUNT):
15871597
raise ValueError("invalid original image repair target")
15881598
images = []
1589-
for image in plan["images"]:
1590-
if (not isinstance(image, dict) or set(image) != {"url", "sha256"}
1591-
or not isinstance(image["sha256"], str) or not BARE_SHA256_PATTERN.fullmatch(image["sha256"])
1592-
or not isinstance(image["url"], str)):
1593-
raise ValueError("each original image requires a URL and its SHA-256")
1594-
images.append({"url": public_url(image["url"]), "sha256": image["sha256"]})
1595-
if len({image["url"] for image in images}) != len(images):
1596-
raise ValueError("duplicate original image URL")
1599+
for image in plan[image_field]:
1600+
if (not isinstance(image, dict) or set(image) != {reference_field, "sha256"}
1601+
or not isinstance(reference := image[reference_field], str)
1602+
or not isinstance(image["sha256"], str) or not BARE_SHA256_PATTERN.fullmatch(image["sha256"])):
1603+
raise ValueError("each original image requires a reference and its SHA-256")
1604+
if captured and not REPLY_IMAGE_NAME_PATTERN.fullmatch(reference):
1605+
raise ValueError("invalid original image snapshot name")
1606+
images.append({reference_field: reference if captured else public_url(reference), "sha256": image["sha256"]})
1607+
if len({image[reference_field] for image in images}) != len(images):
1608+
raise ValueError("duplicate original image reference")
15971609
self._historical_image_source(record, plan)
1598-
return {**plan, "images": images}
1610+
return {**plan, image_field: images}
15991611

16001612
def _load_historical_image_plan(self, path: Path, record: dict[str, Any]) -> dict | None:
16011613
if record.get("historical_answer_images") is not None:
@@ -1652,17 +1664,30 @@ def original_pair_matches() -> bool:
16521664
if not original_pair_matches():
16531665
return 0
16541666
phase = "answer_images.historical"
1667+
snapshots = plan.get("captured_images")
1668+
if snapshots is None:
1669+
images = plan["images"]
1670+
targets = [item["url"] for item in images]
1671+
local_scope = None
1672+
verification_key = "source_urls_verified"
1673+
else:
1674+
# The operator stages the exact Turn's snapshots in this private host
1675+
# directory. Paths from the project and model text are never opened here.
1676+
images = snapshots
1677+
targets = snapshots
1678+
local_scope = (self.root / "historical-answer-images", plan["turn_id"])
1679+
verification_key = "captured_images_verified"
16551680
attachments = state.get("attachments")
1656-
recheck_sources = attachments is None or state.get("source_urls_verified") is not True
1681+
recheck_sources = attachments is None or state.get(verification_key) is not True
16571682
if recheck_sources:
1658-
attachments = read_answer_images(event["content"], [item["url"] for item in plan["images"]],
1659-
attachments, record["deliveries"].get(phase, {}))
1683+
attachments = read_answer_images(event["content"], targets, attachments,
1684+
record["deliveries"].get(phase, {}), local_scope=local_scope)
16601685
digests = [hashlib.sha256(base64.b64decode(
16611686
picture["data_url"].split(",", 1)[1], validate=True)).hexdigest() for picture in attachments]
1662-
if digests != [item["sha256"] for item in plan["images"]]:
1687+
if digests != [item["sha256"] for item in images]:
16631688
return 0
16641689
if recheck_sources:
1665-
state.update(attachments=attachments, source_urls_verified=True)
1690+
state.update(attachments=attachments, **{verification_key: True})
16661691
_atomic_write_json(path, record)
16671692
def authorized() -> bool:
16681693
try:

‎tests/test_lark_private_conversations.py‎

Lines changed: 105 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1560,7 +1560,7 @@ def restart():
15601560
# Produce an actual legacy reply and provider receipt before installing
15611561
# the media-only repair. The stored answer and Core are real.
15621562
with monkeypatch.context() as legacy:
1563-
legacy.setattr(transport, "_deliver_completed_answer", lambda p, row, text, *, inbox:
1563+
legacy.setattr(transport, "_deliver_completed_answer", lambda p, row, text, *, inbox, answer_image_plan=None:
15641564
transport._deliver(p, row, "terminal", text, inbox=inbox))
15651565
assert transport.reconcile_request(path) == 1
15661566
saved = json.loads(path.read_text())
@@ -1753,6 +1753,110 @@ def edit_source_before_lock(path, **kwargs):
17531753
runtime.close()
17541754

17551755

1756+
@pytest.mark.parametrize("fault", [
1757+
"none", "bad_digest", "different_turn", "symlink", "foreign_name",
1758+
"edited_reply", "stopped", "revoked", "unknown_upload", "unknown_send",
1759+
])
1760+
def test_legacy_local_reply_images_are_recovered_only_by_the_original_worker(ordinary, source_https, fault): # noqa: F811
1761+
from hashlib import sha256
1762+
1763+
from loopx.capabilities.native_chat.file_discovery import reply_image_directory
1764+
from loopx.chat_store import _atomic_write_json
1765+
from test_chat_image_attachments import PNG_BYTES
1766+
from test_lark_app_image_projection import ImageIO
1767+
1768+
_, _, contexts, _, capture, fake, _ = ordinary
1769+
contexts.workspace_grant = "workspace_write"
1770+
store, runtime, provider, transport = connect(ordinary)
1771+
io = ImageIO(provider)
1772+
transport.runner = io
1773+
fetched, _ = source_https(lambda _: (None, "image/png", PNG_BYTES))
1774+
answer = "Original explanation.\n\nFirst figure\n\nSecond figure"
1775+
marker = '"message": "Runtime response.",'
1776+
fake.write_text(fake.read_text().replace(marker, f'"message": {answer!r},', 1))
1777+
try:
1778+
event = provider.event("notes-app", "historical-captured-images", "Read the requested figures.")
1779+
assert transport.admit("notes-app", event)["status"] == "durably_accepted"
1780+
request = transport.core.pending()[0]
1781+
sid, tid, ref = (request[key] for key in ("session_id", "turn_id", "request_ref"))
1782+
completed = runtime.wait_for_turn(session_id=sid, turn_id=tid, timeout_sec=10)
1783+
assert completed["status"] == "completed" and not completed["response"].get("answer_image_plan")
1784+
path = transport.root / f"{ref}.json"
1785+
assert transport.reconcile_request(path) == 1
1786+
original = json.loads(path.read_text())
1787+
terminal = original["deliveries"]["terminal"]
1788+
message_id = terminal["attempt"]["message_ref"]
1789+
core_before = transport.core.read_request(ref), completed, store.messages(sid)
1790+
assert terminal["verified"] and not terminal.get("image_keys")
1791+
1792+
private = transport.root / "historical-answer-images"
1793+
staged = private / reply_image_directory("f" * 32 if fault == "different_turn" else tid)
1794+
staged.mkdir(parents=True)
1795+
raw_images = [PNG_BYTES + b"first", PNG_BYTES + b"second"]
1796+
names = ["figure-first.png", "figure-second.png"]
1797+
for name, data in zip(names, raw_images, strict=True):
1798+
output = staged / name
1799+
if fault == "symlink":
1800+
other = staged.parent / name
1801+
other.write_bytes(data)
1802+
output.symlink_to(other)
1803+
else:
1804+
output.write_bytes(data)
1805+
manifest = {"binding_id": original["binding_id"], "turn_id": tid, "message_id": message_id,
1806+
"answer_sha256": sha256(answer.encode()).hexdigest(),
1807+
"captured_images": [{"name": name, "sha256": sha256(data).hexdigest()}
1808+
for name, data in zip(names, raw_images, strict=True)]}
1809+
if fault == "bad_digest":
1810+
(staged / names[1]).write_bytes(PNG_BYTES + b"changed")
1811+
if fault == "foreign_name":
1812+
manifest["captured_images"][0]["name"] = str(staged / names[0])
1813+
_atomic_write_json(private / path.name, manifest)
1814+
1815+
if fault == "edited_reply":
1816+
provider.messages[message_id]["body"]["content"] = '{"zh_cn":{"content":[[{"tag":"text","text":"Changed"}]]}}'
1817+
elif fault == "stopped":
1818+
transport.admit("notes-app", provider.event("notes-app", "stop-legacy-captured-images", "/stop"))
1819+
elif fault == "revoked":
1820+
contexts.workspace_grant = "workspace_read"
1821+
elif fault == "unknown_upload":
1822+
io.unknown_upload = True
1823+
elif fault == "unknown_send":
1824+
provider.lose_next_reply = True
1825+
1826+
writes = len(provider.writes)
1827+
def restart():
1828+
return LarkPrivateConversations(controller=runtime, runtime_root=transport.runtime_root,
1829+
runner=io, cli_bin="lark-cli")
1830+
1831+
worker = restart()
1832+
assert path not in worker.pending_body_paths()
1833+
assert path in worker.pending_delivery_paths()
1834+
assert worker.reconcile_request(path) == int(fault == "none")
1835+
saved = json.loads(path.read_text())
1836+
assert saved["deliveries"]["terminal"] == terminal
1837+
if fault == "none":
1838+
media = saved["deliveries"]["answer_images.historical"]
1839+
assert media["images_verified"] and io.downloads == 2
1840+
post = provider.messages[media["attempt"]["message_ref"]]
1841+
assert post["chat_id"] == event["chat_id"]
1842+
assert post["sender"]["id"] == provider.profile_apps["notes-app"]
1843+
assert [io.resources[key] for key in media["image_keys"]] == raw_images
1844+
assert saved["historical_answer_images"]["status"] == "delivered"
1845+
elif fault in {"unknown_upload", "unknown_send"}:
1846+
saved["historical_answer_images"]["next_check_at"] = 0
1847+
_atomic_write_json(path, saved)
1848+
io.unknown_upload = False
1849+
assert restart().reconcile_request(path) == 0
1850+
assert len(provider.writes) == writes + int(fault in {"none", "unknown_send"})
1851+
assert io.uploads == {"none": 2, "unknown_upload": 1, "unknown_send": 2}.get(fault, 0)
1852+
assert fetched == []
1853+
assert sum(json.loads(line).get("method") == "turn/start" for line in capture.read_text().splitlines()) == 1
1854+
if fault != "stopped":
1855+
assert core_before == (transport.core.read_request(ref), store.load_turn(sid, tid), store.messages(sid))
1856+
finally:
1857+
runtime.close()
1858+
1859+
17561860
def test_private_delivery_keeps_retired_steward_cards_out_of_image_recovery(
17571861
ordinary, # noqa: F811
17581862
):

0 commit comments

Comments
 (0)