Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions docs/architecture/rfcs/app-conversation-and-async-inbox-v0.md
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,11 @@ it or starts model work. Before every write and receipt recovery, Core rechecks
the Session, current binding and audience, and the provider verifies the original
source. Posts identify the App speaker, stay in canonical append order within
that outbox and retain complete long text through the existing rich-post parts.
When Lark supplies a message link for the verified App input mirror, a new
answer includes a link to the question from the same Turn. Multipart inputs
use the last concrete post. The outbox retains the link before the first send
and reuses it when recovering the same attempt. If Lark cannot supply a link in
the original private chat, the existing body delivery proceeds.
An exact App-origin terminal error also projects a public-safe failure notice
with the original completion time. The notice is derived from the stored Turn
and its matching error row, without exporting raw diagnostics. It uses the same
Expand Down Expand Up @@ -336,10 +341,10 @@ actual provider presentation remain separate acceptance work.

Use **Continue original conversation** or the explicitly selected App steward
entry above to reach this path. Old ordinary history is retained separately.
This checkpoint covers text and bounded App image projection, not reply/thread
relation mirroring, retroactive insertion into Lark chronology or all-channel
broadcast. Canonical App images reuse the existing resource uploader and post
sender, retaining caption and ordered inline images in the original private
This checkpoint covers text, question links and bounded App image projection.
Native reply and topic placement, retroactive insertion into Lark chronology,
and all-channel broadcast remain open. Canonical App images reuse the existing
resource uploader and post sender, retaining caption and ordered inline images in the original private
chat. Long captions keep images on the final concrete post only. Every upload
and send rechecks the original source and current Core message/grant. Sends and
edits check again after provider preview, before recording the write intent;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,9 @@ Web 来源,通过已有 Core 队列及新鲜来源准入。连接列表独立
输入只提供地址来源证据;投影不会重新受理它或启动模型工作。每次发送和恢复回执前,
Core 重查 Session、当前绑定与受众,provider 核验原来源。消息标明 App 发言者,在
该 outbox 内按 canonical 追加顺序发送,长正文沿用既有富文本分段,保留完整内容。
飞书能为已核验送达的 App 提问镜像提供消息链接时,新回复会链接到同一 Turn 的提问。
长提问使用最后一条实际分段消息。outbox 在首次发送前保留链接,恢复时沿用同一发送
尝试的正文。原私聊取不到链接时,正文继续沿既有路径送达。
App 来源 Turn 的终态错误也沿原私聊补齐。根据原 Turn 与精确匹配的错误行生成
失败提示,并标注原结束时间。原始诊断留在 App。恢复时使用原 outbox 与消息身份,
已送达的输入可以补回一条历史失败提示。先前未确认的停止提示与已完成的 Turn
Expand All @@ -235,8 +238,8 @@ provider 消息;反馈失败保留可恢复回执,不阻断正文送达或
Lark 表情和 provider 呈现仍独立验收。

通过上述 **继续原会话** 或明确选定的 App 管家入口使用该路径;旧普通历史继续
独立保留。本检查点覆盖文本及有界 App 图片投影,不覆盖回复/话题关系镜像、向
Lark 历史回插旧时间或全渠道广播。Core 中的 App 图片复用既有资源上传与 post
独立保留。本检查点覆盖文本、提问链接及有界 App 图片投影。原生回复和话题位置、
向 Lark 历史回插旧时间及全渠道广播仍待处理。Core 中的 App 图片复用既有资源上传与 post
发送器,正文及有序行内图片留在原私聊;长正文只在最后一个实际分段携带图片。
每次上传和发送均重新核验原来源、当前 Core 消息与授权。发送和编辑在 provider
预检返回后、记录写入意图前再次检查;每个继续或恢复的富文本分段复用该边界。
Expand Down
2 changes: 1 addition & 1 deletion loopx/canary/module_metric_baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@
"loopx/extensions/lark/manager_returns.py": {
"any_count": 0,
"dict_any_count": 0,
"lines": 443
"lines": 497
},
"loopx/extensions/lark/presentation/explore_results.py": {
"any_count": 78,
Expand Down
73 changes: 71 additions & 2 deletions loopx/extensions/lark/manager_returns.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,27 @@

from collections.abc import Callable, Mapping, Sequence
from pathlib import Path
import re
from typing import TYPE_CHECKING, Protocol, cast

from ...capabilities.manager_context import authority
from ...capabilities.manager_context.roundtrip import ReturnResolutionBlocked
from ...chat_store import _atomic_write_json
from ...file_lock import exclusive_file_lock
from .conversation_identity import identity_ref
from .event_inbox import _load_processed, load_lark_event_inbox_config
from .goal_channel_contracts import bindings_for_goal
from .goal_channel_targets import goal_channel_target_for_name
from .goal_channel_transport import json_payload
from .goal_topic_runtime import _inbox_config
from .identity_shapes import LARK_MESSAGE_ID_PATTERN
from .inbox_reply import (
CommandRunner, _bot_identity_verified, _default_runner, _verified_reply_result,
CommandRunner, _bot_identity_verified, _call, _default_runner, _message, _verified_reply_result,
reply_lark_event_inbox, verify_lark_inbox_reply,
)
from .manager_routing import authorized_manager_goal_ids
from .outbound import present_lark_conversation_text
from .post_delivery import attachment_reply
from .return_files import uploaded_result_files, verify_result_files

if TYPE_CHECKING:
Expand Down Expand Up @@ -136,6 +141,69 @@ def _private_return_authority(
return private_transport


def _private_message_link(link: object, chat_id: str) -> bool:
return isinstance(link, str) and re.fullmatch(
r"https://applink\.(?:feishu\.cn|larksuite\.com)/client/chat/open"
r"\?openChatId=" + re.escape(chat_id) + r"&position=[0-9]+", link,
) is not None


def _app_mirror_text(message: PayloadView, phase: PayloadView, chat_id: str) -> str:
user_input = message["role"] == "user"
speaker = "你" if user_input else "LoopX"
text = _str_field(message, "text")
link = phase.get("question_link")
if link is not None:
if user_input or not _private_message_link(link, chat_id):
raise ValueError("App mirror question link changed")
text = f"[查看对应提问]({link})\n\n{text}"
return f"**{speaker}(App)**\n\n{text}"


def prepare_app_mirror_text(
transport: _PrivateTransport, path: Path, row: Payload, messages: Sequence[PayloadView], message: PayloadView,
) -> str:
"""Attach a provider-supplied link before the first answer attempt."""
deliveries = cast(dict[str, Payload], row["deliveries"])
key = "web." + _str_field(message, "message_id")
phase = deliveries.get(key, {})
chat = _str_field(_mapping(row["event"]), "chat_id")
if message["role"] != "user" and not {"question_link", "text", "started", "attempt"}.intersection(phase):
inputs = [item for item in messages if item["role"] == "user" and item["turn_id"] == message["turn_id"]]
if len(inputs) == 1:
original = deliveries.get("web." + _str_field(inputs[0], "message_id"), {})
link = _app_input_link(transport, row, original, chat)
if link is not None:
# Retain the chosen link before provider preflight. Recovery
# reproduces the same text even if the link later disappears.
phase["question_link"] = link
deliveries[key] = phase
_atomic_write_json(path, row)
return _app_mirror_text(message, phase, chat)


def _app_input_link(transport: _PrivateTransport, row: Payload, original: PayloadView, chat: str) -> str | None:
if original.get("verified") is not True or not isinstance(original.get("attempt"), Mapping):
return None
try:
_, attempt = attachment_reply(project=transport.runtime_root, config_path=transport._inbox(row),

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

独立用例先通过真实 outbox 验证长提问的多个分片,再让恢复的辅助记录保留同一 intent 和 provider receipt,分片列表为空。attachment_reply 的末分片读取抛 IndexError,这里的 fallback 没有接住,后面的正文投影未执行。精确 base 在完全相同的状态成功发送并验收一次。请校验可选定位的分片形状并回退到原正文。

text=_str_field(original, "text"), attempt=original["attempt"])
ref = _str_field(attempt, "message_ref")
except (KeyError, OSError, TypeError, ValueError):
return None
if not LARK_MESSAGE_ID_PATTERN.fullmatch(ref):
return None
result = _call(transport._reply_runner, ["lark-cli", "--profile", _str_field(row, "profile"),
"im", "+messages-mget", "--message-ids", ref, "--as", "bot", "--format", "json", "--no-reactions"])
payload = json_payload(result)
observed = _message(payload, ref) if result.get("returncode") == 0 and payload.get("ok") is True else None
if (observed is None or observed.get("chat_id") != chat or observed.get("deleted") is True
or _mapping(observed.get("sender")).get("sender_type") != "app"):
return None
link = observed.get("message_app_link")
return link if isinstance(link, str) and _private_message_link(link, chat) else None


def _verify_web_mirror(
route: PayloadView, session: PayloadView, turn: PayloadView, text: str,
private_transport: _PrivateTransport, attempt: AttemptRecord | None, record_attempt: AttemptRecorder | None,
Expand Down Expand Up @@ -170,7 +238,8 @@ def _verify_web_mirror(
mirrored = phase.get("attempt")
if phase.get("verified") is not True or not isinstance(mirrored, dict):
raise _blocked("initial_delivery_receipt_unavailable", "App mirror remains unverified")
expected, phase_text = f"**LoopX(App)**\n\n{_str_field(message, 'text')}", phase.get("text")
expected = _app_mirror_text(message, phase, _str_field(_mapping(row["event"]), "chat_id"))
phase_text = phase.get("text")
if (not isinstance(phase_text, str) or phase_text not in (expected, present_lark_conversation_text(expected))
or (attempt is not None and dict(attempt) != mirrored)):
raise ValueError("App mirror intent changed")
Expand Down
5 changes: 3 additions & 2 deletions loopx/extensions/lark/private_conversations.py
Original file line number Diff line number Diff line change
Expand Up @@ -2173,6 +2173,8 @@ def _reconcile_web_projection(self, path: Path) -> int:
for message in messages) else "delivered"
_atomic_write_json(path, row)
return 0
from .manager_returns import prepare_app_mirror_text

def authorized_source(profile: str, chat_id: str, message_id: str) -> tuple[str | None, bool]:
# Check the original provider source first. The fresh App
# grant and canonical body checks then cover any changes
Expand All @@ -2184,8 +2186,7 @@ def authorized_source(profile: str, chat_id: str, message_id: str) -> tuple[str
return name, pending in self._web_projection_messages(row)
except (OSError, ValueError, KeyError):
return None, False
who = "你" if pending["role"] == "user" else "LoopX"
text = f"**{who}(App)**\n\n{pending['text']}"
text = prepare_app_mirror_text(self, path, row, messages, pending)
if self.reaction_feedback and pending["role"] == "user":
# Persist feedback intent before a mirror write/recovery;
# old completed mirrors without it are not backfilled.
Expand Down
16 changes: 15 additions & 1 deletion tests/extensions/test_lark_private_manager_returns.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,14 @@ def test_web_result_adopts_original_mirror_and_recovers_readback_without_send(
capture = store.root.parent.parent / "requests.jsonl"
starts = capture.read_bytes()
frozen_turn = store._turn_path(session["session_id"], turn["turn_id"]).read_bytes()
question = next(item for item in store.messages(session["session_id"])
if item["role"] == "user" and item["turn_id"] == turn["turn_id"])
question_phase = _read_json(mirror)["deliveries"]["web." + question["message_id"]]
question_ref = question_phase["attempt"]["message_ref"]
question_link = ("https://applink.feishu.cn/client/chat/open?openChatId="
f"{provider.messages[question_ref]['chat_id']}&position=23")
if not legacy_result:
provider.messages[question_ref]["message_app_link"] = question_link
remainder = {"summary": "Validate installation", "resume_when": "The same worker has the original installation proof"}
body = ("完整结果与独立证据。\n" * 1200 if long_result else "Concrete original result.") + "UNIQUE_RESULT_END"
report(sender.root, route["goal_id"], route["agent_id"], route["request_id"], "conclusion", body,
Expand Down Expand Up @@ -419,7 +427,10 @@ def test_web_result_adopts_original_mirror_and_recovers_readback_without_send(
marker = f"({index}/{len(parts)})\n\n"
assert text.startswith(marker)
parts[index - 1] = text[len(marker):]
remaining = f"**LoopX(App)**\n\n{expected}"
prefix = "**LoopX(App)**\n\n"
if not legacy_result:
prefix += f"[查看对应提问]({question_link})\n\n"
remaining = prefix + expected
for index, text in enumerate(parts):
assert remaining.startswith(text)
remaining = remaining[len(text):]
Expand All @@ -430,6 +441,9 @@ def test_web_result_adopts_original_mirror_and_recovers_readback_without_send(
assert remaining == ""
original_mirror = mirror.read_bytes()
phase = _read_json(mirror)["deliveries"]["web." + message["message_id"]]
if not legacy_result:
assert phase["question_link"] == question_link
del provider.messages[question_ref]["message_app_link"]
writes = list(provider.writes)
runner = transport.runner

Expand Down
34 changes: 33 additions & 1 deletion tests/test_lark_private_conversations.py
Original file line number Diff line number Diff line change
Expand Up @@ -3876,11 +3876,29 @@ def vanished(path):
runtime.close()


def test_app_messages_and_answers_reach_the_original_chat_once_without_new_execution(ordinary): # noqa: F811
@pytest.mark.parametrize("source_link", ["original", "foreign", "unavailable"])
def test_app_messages_and_answers_reach_the_original_chat_once_without_new_execution(ordinary, source_link): # noqa: F811
store, runtime, provider, transport, original, turns, before = _app_projection_journey(ordinary)
sid = original["session_id"]
canonical = [message for message in store.messages(sid) if message.get("turn_id") in turns]
requests_before = ordinary[4].read_text()

def with_source_links(args, cwd=None, timeout=None):
response = provider(args, cwd, timeout)
if "+messages-mget" not in args:
return response
payload = json.loads(response["stdout"])
for row in payload.get("data", {}).get("items", []):
ref = row["message_id"]
if ref.startswith("om_out_") and source_link != "unavailable":
chat = row["chat_id"] if source_link == "original" else "oc_a_different_private_chat"
position = int(ref.removeprefix("om_out_"))
row["message_app_link"] = (
f"https://applink.feishu.cn/client/chat/open?openChatId={chat}&position={position}"
)
return {**response, "stdout": json.dumps(payload, ensure_ascii=False)}

transport.runner = with_source_links
try:
_drain_app_projection(transport, lambda: len(provider.writes) >= before + len(canonical))
projected = provider.writes[before:]
Expand All @@ -3889,6 +3907,20 @@ def test_app_messages_and_answers_reach_the_original_chat_once_without_new_execu
for (profile, text), message in zip(projected, canonical):
assert profile == "notes-app" and message["text"] in text
assert ("你(App)" if message["role"] == "user" else "LoopX(App)") in text
journal, = (transport.root / "web-projections").glob("*.json")
deliveries = json.loads(journal.read_text())["deliveries"]
canonical_inputs = {m["turn_id"]: m["message_id"] for m in canonical if m["role"] == "user"}
for message in canonical:
current = deliveries["web." + message["message_id"]]
if source_link == "original" and message["role"] == "agent":
parent = deliveries["web." + canonical_inputs[message["turn_id"]]]
position = int(parent["attempt"]["message_ref"].removeprefix("om_out_"))
expected = f"https://applink.feishu.cn/client/chat/open?openChatId=oc_notes_app&position={position}"
provider_message = provider.messages[current["attempt"]["message_ref"]]
contents = json.loads(provider_message["body"]["content"])["zh_cn"]["content"]
assert f"[查看对应提问]({expected})" in contents[0][0]["text"]
else:
assert "查看对应提问" not in current["text"]
restarted = LarkPrivateConversations(controller=runtime, runtime_root=transport.runtime_root,
runner=provider, cli_bin="lark-cli")
for _ in range(3):
Expand Down
Loading