diff --git a/docs/reference/goal-chat-continuation.md b/docs/reference/goal-chat-continuation.md index 8cf757f886..086f27c731 100644 --- a/docs/reference/goal-chat-continuation.md +++ b/docs/reference/goal-chat-continuation.md @@ -58,6 +58,44 @@ delivery readback verifies what was sent, not source truth or recipient access. 产物时才使用本地文件链接,否则保留文件/章节说明,并指出重要的访问或版本缺口。 引用需要可用,不构成上传或发布授权;此指导不替代来源核验或渠道实际验收。 +## Correct an active bound Lark conversation + +In an already authorized project-assistant or steward conversation, a native +`@` of that App's Bot sends a text correction to the Turn observed when the +message entered intake. It keeps the original Session and freezes that Turn +before reading the provider message. If no Turn was active, the message follows +the ordinary queue. Plain `@name` prose, mentions of another identity and quoted +mentions do not select steering. An `@` never changes the existing grant. +The steward's active-Turn authorization must still match the current Goal +scope. A stale authorization cannot be renewed by mentioning the Bot. + +When the canonical provider message cannot be verified, the captured input +waits for the existing worker to verify it again. Unknown addressing does not +become permission to queue a possible correction for a later Turn. + +The correction retains its full body and verified reply context. Live steering +accepts text only; a message with images is retained with its attachments rather +than executing its caption alone. A switched Turn or unsupported host receives +an explicit failure instead of silently queueing the correction for later work. + +“已送达当前回合” confirms native delivery, not the model's semantic adoption or +business completion. “送达状态待核实” keeps the original receipt pending: recovery +can settle matching native readback, but cannot resend an uncertain operation or +retarget a newer Turn. Reconnects and duplicate events reuse the original input +identity. The existing conversation worker returns these receipts to the source +message; no separate listener or message consumer is needed. + +已授权的项目助手或管家会话支持原生 `@Bot` 纠偏:忙时将完整文字送给接收时的 +原回合,读取飞书消息前即固定 Session 和 Turn;空闲时走普通队列。文字中的 +`@名称`、引用里的 @ 或 @ 其他身份不会触发,@ 本身也不增加权限。回复上下文随 +原文保留;带图消息不能只取文字执行,原文和附件一起保留。回合已切换或宿主不支持 +时明确说明失败,不改投后续工作。 +管家活动回合的授权必须仍与当前 Goal 范围匹配;@ 不能续签失效授权。原始飞书消息 +暂不可核验时,保留原输入由既有 worker 重新核验,不把未知 @ 当成后续任务执行。 + +“已送达”只证明原生送达,不等于模型已经采纳或业务完成。“状态待核实”保留原回执, +仅在匹配的原生读回出现后收口;断线、重投和恢复均不能盲目重发或绑定新回合。 + ## Enable LoopX mode On a local managed Codex Goal conversation, choose **Enable LoopX** in the diff --git a/loopx/canary/module_metric_baseline.json b/loopx/canary/module_metric_baseline.json index c42a77b450..9f959c1b04 100644 --- a/loopx/canary/module_metric_baseline.json +++ b/loopx/canary/module_metric_baseline.json @@ -29,6 +29,9 @@ "loopx/capabilities/issue_fix/pr_lifecycle.py": { "lines": 2056 }, + "loopx/capabilities/native_chat/external_conversations.py": { + "lines": 2111 + }, "loopx/chat_actions.py": { "any_count": 52, "dict_any_count": 0 @@ -84,7 +87,7 @@ "lines": 2760 }, "loopx/extensions/lark/private_conversations.py": { - "lines": 2583 + "lines": 2651 }, "loopx/heartbeat_prompt.py": { "any_count": 17, diff --git a/loopx/capabilities/native_chat/external_conversations.py b/loopx/capabilities/native_chat/external_conversations.py index 081e83bb6c..afa5d25983 100644 --- a/loopx/capabilities/native_chat/external_conversations.py +++ b/loopx/capabilities/native_chat/external_conversations.py @@ -1366,11 +1366,70 @@ def _automation_cadence_observation( reason="owner_read_failed", ) + def _source_session(self, selected: dict[str, Any], target: dict[str, Any] | None): + controller = self.controller + steward_candidate = authority = None + if target: + authority = self.bindings.resolve_agent_target(selected, target) + # Observation must retain failed or closed originals, so read the + # exact frozen target Session without lifecycle filtering. + current = next((candidate for candidate in controller.store.session_candidates( + goal_id=None, agent_id=selected["binding"]["executor_endpoint_id"], + channel_id=selected["channel_id"]) + if candidate.get("session_id") == target["session_id"]), + controller.store.load_session(target["session_id"])) + else: + current = controller.store.latest_session(goal_id=None, + agent_id=selected["binding"]["executor_endpoint_id"], channel_id=selected["channel_id"]) + if selected["binding"]["context_kind"] == "steward": + # A quota fallback keeps the original channel, source and Core + # Session. Agent filtering must not create another consumer or + # fork the conversation when its actual endpoint changed. + candidates = [item for item in controller.store.list_sessions(channel_id=selected["channel_id"]) + if item.get("status") in RESUMABLE_SESSION_STATES] + if candidates: + latest = max(candidates, key=lambda item: str(item.get("created_at") or "")) + steward_candidate = controller.store.load_session(latest["session_id"]) + allocation = (steward_candidate or {}).get("manager_executor_allocation") + if isinstance(allocation, dict) and allocation.get("selection_policy") == "flexible": + self.bindings.session_context(steward_candidate["steward_context"], session=steward_candidate) + current = steward_candidate + return current, steward_candidate, authority + + def capture_native_mention(self, binding: dict[str, Any], source: dict[str, Any]) -> dict[str, Any]: + """Observe local identities before provider IO, without granting input. + + Do not wait behind an in-flight source admission. Current routing and + grants are checked again before the frozen target can receive anything. + """ + choices = [item for item in self.pending() if item.get("binding_id") == binding["binding_id"] + and item["source"]["source_ref"] == source["source_ref"] and item.get("selection_recorded")] + previous = max(choices, key=lambda item: item.get("selection_order", 0)) if choices else None + target = previous.get("selection_target") if previous else None + current = self.controller.store.load_session(target["session_id"]) if target else None + if not target: + candidates = [] + for _, session in self.controller.store.iter_session_metadata(): + saved = session.get("steward_context") or session.get("project_context") or {} + allocation = session.get("manager_executor_allocation") or {} + if (saved.get("binding_id") == binding["binding_id"] + and saved.get("source_ref") == source["source_ref"] + and session.get("status") in RESUMABLE_SESSION_STATES + and (session.get("agent_id") == binding["executor_endpoint_id"] + or binding["context_kind"] == "steward" and allocation.get("selection_policy") == "flexible")): + candidates.append(session) + current = max(candidates, key=lambda item: str(item.get("created_at") or ""), default=None) + return {"session_id": (current or {}).get("session_id"), + "target_turn_id": (current or {}).get("active_turn_id") or None, + "channel_id": (current or {}).get("channel_id")} + def admit(self, *, binding_id: str, source: dict[str, Any], request_ref: str, message: str, command: str | None = None, attachments: list[dict[str, Any]] | None = None, origin: str = "lark", defer_background_stop: bool = False, - source_preflight: Callable[[dict[str, Any]], None] | None = None) -> dict[str, Any]: + source_preflight: Callable[[dict[str, Any]], None] | None = None, + native_mention: bool = False, + native_mention_capture: dict[str, Any] | None = None) -> dict[str, Any]: import re if origin not in {"lark", "external"}: raise ValueError("unsupported external conversation origin") @@ -1380,6 +1439,8 @@ def admit(self, *, binding_id: str, source: dict[str, Any], request_ref: str, raise ValueError("unsupported external conversation command") if source_preflight is not None and not callable(source_preflight): raise ValueError("source preflight must be an in-process verifier") + if type(native_mention) is not bool or native_mention and (source_preflight is None or command is not None): + raise ValueError("native mentions require their original provider preflight") # These references enter the lock path before authority is resolved. # Check path-safe shape here; the typed owner checks current grants # and provider identity after both fences are acquired. @@ -1394,9 +1455,13 @@ def admit(self, *, binding_id: str, source: dict[str, Any], request_ref: str, operation="route_external_chat_request"): # Resolve and verify the source inside both fences before # creating or replaying any canonical request. - selected = resolve_external_admission_source(self.bindings, binding_id, source, source_preflight) + # Freeze a mention's original Session/Turn before its fenced + # source IO. A slow verifier cannot retarget a later Turn. + selected = resolve_external_admission_source(self.bindings, binding_id, source, + None if native_mention else source_preflight) expected = {"binding_id": binding_id, "source": source, "message": message, "command": command, - "attachments": normalize_chat_image_attachments(attachments) or None, "origin": origin} + "attachments": normalize_chat_image_attachments(attachments) or None, "origin": origin, + **({"native_mention": True, "mention_capture": deepcopy(native_mention_capture)} if native_mention else {})} recovering_request = path.exists() if recovering_request: row = _read_json(path) @@ -1442,7 +1507,8 @@ def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, A *, recovering_request: bool = False, source_preflight: Callable[[dict[str, Any]], None] | None = None) -> dict[str, Any]: controller = self.controller - selected = ensure_external_admission_scope(self.bindings, selected, path, row, source_preflight=source_preflight) + selected = ensure_external_admission_scope(self.bindings, selected, path, row, + source_preflight=None if row.get("native_mention") else source_preflight) held_for_binding = row.get("response_code") == STEWARD_BINDING_ADOPTION_PENDING if held_for_binding: row.pop("response_code") @@ -1457,32 +1523,9 @@ def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, A row["agent_target"] = None target = row.get("agent_target") steward_candidate = None - if target: - authority = self.bindings.resolve_agent_target(selected, target) + current, steward_candidate, authority = self._source_session(selected, target) + if authority: row["agent_audience"] = authority["audience"] - # Observation must retain failed or closed originals, so read the - # exact frozen target Session without lifecycle filtering. - current = next((candidate for candidate in controller.store.session_candidates( - goal_id=None, agent_id=selected["binding"]["executor_endpoint_id"], - channel_id=selected["channel_id"]) - if candidate.get("session_id") == target["session_id"]), - controller.store.load_session(target["session_id"])) - else: - current = controller.store.latest_session(goal_id=None, - agent_id=selected["binding"]["executor_endpoint_id"], channel_id=selected["channel_id"]) - if selected["binding"]["context_kind"] == "steward": - # A quota fallback keeps the original channel, source and Core - # Session. Agent filtering must not create another consumer or - # fork the conversation when its actual endpoint changed. - candidates = [item for item in controller.store.list_sessions(channel_id=selected["channel_id"]) - if item.get("status") in RESUMABLE_SESSION_STATES] - if candidates: - latest = max(candidates, key=lambda item: str(item.get("created_at") or "")) - steward_candidate = controller.store.load_session(latest["session_id"]) - allocation = (steward_candidate or {}).get("manager_executor_allocation") - if isinstance(allocation, dict) and allocation.get("selection_policy") == "flexible": - self.bindings.session_context(steward_candidate["steward_context"], session=steward_candidate) - current = steward_candidate if row["command"] in {"status", "help"} and not target: # Observation must retain failed/closed originals. Admission still # uses the resumable selector and never resumes from this snapshot. @@ -1491,6 +1534,8 @@ def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, A agent_id=selected["binding"]["executor_endpoint_id"], channel_id=selected["channel_id"])) snapshot = max(candidates, key=lambda candidate: str(candidate.get("updated_at") or ""), default=None) current = controller.store.load_session(snapshot["session_id"]) if snapshot else None + if row.get("native_mention") and (row.get("mention_capture") or {}).get("session_id"): + row["session_id"] = row["mention_capture"]["session_id"] if row.get("session_id") and row["command"] is None: current = controller.store.load_session(row["session_id"]) if current is None: @@ -1612,6 +1657,73 @@ def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, A mode="resume_latest", conversation_binding_id=row["binding_id"], source_context=row["source"]) row["session_id"] = current["session_id"] _atomic_write_json(path, row) + if row.get("native_mention"): + from types import SimpleNamespace + from .queued_admission import deliver_native_mention + + capture = row.get("mention_capture") or {} + if source_preflight is None: + raise ValueError("native mentions require fresh original provider verification") + source_preflight(deepcopy(selected)) + fresh_source = resolve_external_admission_source(self.bindings, row["binding_id"], row["source"], None) + if any(fresh_source.get(key) != selected.get(key) for key in ("binding", "context", "channel_id")): + raise ValueError("native mention authority changed during source verification") + selected = fresh_source + selected = ensure_external_admission_scope(self.bindings, selected, path, row, + source_preflight=source_preflight) + + def steer_admitted(**kwargs): + # The public steering endpoint intentionally rejects bound + # conversations. Only this existing source-fenced admission + # can reach the native IO with its current binding grant. + saved = current.get("steward_context") or current.get("project_context") + if not saved or saved.get("audience") not in {"bound_owner", "bound_group"}: + return controller.steer_active_turn(**kwargs) + with self.bindings.input_context(saved, origin=row["origin"], session=current, + store=controller.store) as authorized: + fresh = controller.store.load_session(current["session_id"]) + if (fresh is None or fresh.get("status") == "closed" + or authorized["binding"] != selected["binding"] + or any(fresh.get(key) != current.get(key) for key in + ("channel_id", "goal_id", "agent_id", "project_context", "steward_context"))): + raise ValueError("original bound Session changed") + controller.project_contexts.runtime_context(fresh, authorized) + if fresh.get("project_context") is not None: + from .project_context import validate_project_executor_scope + validate_project_executor_scope(str(fresh["agent_id"]), + fresh["project_context"], controller.capabilities) + with controller.store.steering_delivery_lock(kwargs["session_id"], kwargs["client_ingress_id"]): + return controller._steer_active_turn(session=fresh, _queued_turn_id=None, **kwargs) + + scope_current = True + if current.get("steward_context") and capture.get("target_turn_id"): + from ...chat_manager_context import manager_authorization_scope_is_current + scope_current = manager_authorization_scope_is_current( + controller.registry_path, controller.manager_scope_resolver, current, + current.get("manager_authorization_scope_id"), runtime_root=controller.coordination_runtime_root) + decision = deliver_native_mention( + SimpleNamespace(store=controller.store, steer_active_turn=steer_admitted), + session_id=current["session_id"], ingress_id=plan["client_turn_id"], + target_turn_id=capture.get("target_turn_id"), + binding_matches=(scope_current and (capture.get("channel_id") == selected["channel_id"] + or capture.get("channel_id") is None and capture.get("session_id") is None + and capture.get("target_turn_id") is None and bool(capture)) + and current.get("status") != "closed" + and (capture.get("session_id") == current["session_id"] + or capture.get("session_id") is None and capture.get("target_turn_id") is None) + and current.get("channel_id") == selected["channel_id"]), + text_only=not row.get("attachments"), may_deliver_new=not recovering_request, + steering_text=row["message"], queued_text=row["message"], origin=row["origin"]) + row["mention_delivery"] = decision + if decision["action"] != "enqueue": + row.update(status="prepared" if decision["action"] == "unresolved" else "command_completed", + turn_id=decision.get("target_turn_id") or capture.get("target_turn_id"), + response=("已送达当前回合。" if decision["action"] == "delivered" else + "已收到,送达状态待核实。原消息已保留,不会自动改投下一回合。" if decision["action"] == "unresolved" else + "本轮调整仅支持文字,原消息和附件已保留。" if decision.get("error_code") == "queue_steering_attachments_unavailable" else + "未送达接收时的回合;原回合、授权或宿主能力已变化。原消息已保留。")) + _atomic_write_json(path, row) + return row self._record_steward_ingress(row, selected, current, plan["client_turn_id"]) try: turn, _ = controller.enqueue_turn(session_id=current["session_id"], @@ -1973,7 +2085,7 @@ def recover(self, *, request_ref: str | None = None) -> None: # queue preparation. The transport checks its source. continue if row["status"] == "prepared": - if row.get("capture_origin") == "provider_history": + if row.get("capture_origin") == "provider_history" or row.get("native_mention"): continue # Only the original provider can reverify this source. # Admission resolves current authority after both request # and route fences. A separate pre-fence network probe diff --git a/loopx/extensions/lark/private_conversations.py b/loopx/extensions/lark/private_conversations.py index 0adb10bf31..3280b6af79 100644 --- a/loopx/extensions/lark/private_conversations.py +++ b/loopx/extensions/lark/private_conversations.py @@ -625,12 +625,42 @@ def sources() -> tuple[Mapping[str, Any] | None, Mapping[str, Any] | None]: (canonical, stop_root), observation = envelopes.result(), identity.result() result, message = {"returncode": 0 if canonical else 1}, canonical else: - result = rendered() + if render_content: + # Display text cannot prove a native @. Keep the provider's + # lossless envelope beside it, using this verified App only. + with ThreadPoolExecutor(max_workers=2) as reads: + display = reads.submit(rendered) + envelope = reads.submit(self._group_source_message, record["profile"], event["message_id"]) + result, canonical = display.result(), envelope.result() + else: + result = rendered() message = _message(json_payload(result), event["message_id"]) sender = message.get("sender") if isinstance(message, Mapping) else None if (result.get("returncode") == 0 and message is not None and message.get("chat_id") == event["chat_id"] and isinstance(sender, Mapping) and sender.get("id") == event["sender_id"] and sender.get("sender_type") == "user"): + if render_content and not group: + if (not canonical or canonical.get("chat_id") != event["chat_id"] + or canonical.get("message_id") != event["message_id"] + or canonical.get("sender", {}).get("id") != sender.get("id") + or canonical.get("sender", {}).get("sender_type") != "user" + or canonical.get("deleted") is True + or canonical.get("msg_type", canonical.get("message_type")) + != message.get("msg_type", message.get("message_type")) + or any(message.get(key) and canonical.get(key) != message[key] + for key in ("root_id", "parent_id", "thread_id"))): + return None + message = {**canonical, "content": message.get("content")} + if render_content: + from .event_inbox import lark_event_mentions_bot + if observation is None: + observation = self.bindings.observe(record["profile"]) + message["_native_mention"] = ( + isinstance(canonical, Mapping) and isinstance(canonical.get("mentions"), list) + and bool(observation.get("bot_open_id") or observation.get("bot_app_id")) + and lark_event_mentions_bot(canonical, bot_display_name="", + bot_app_id=observation.get("bot_app_id"), bot_open_id=observation.get("bot_open_id"), + allow_text_fallback=False)) if group: canonical_sender = canonical.get("sender") if isinstance(canonical, Mapping) else None if (canonical is None or canonical.get("chat_id") != event["chat_id"] @@ -842,8 +872,11 @@ def _record_admission(path: Path, record: dict[str, Any], admitted: dict[str, An response=admitted.get("response"), response_code=admitted.get("response_code")) if admitted.get("context_recovery"): record["context_recovery"] = admitted["context_recovery"] + if admitted.get("mention_delivery"): + record["mention_delivery"] = admitted["mention_delivery"] _atomic_write_json(path, record) - if admitted["status"] == "prepared" and admitted.get("response_code") == STEWARD_BINDING_ADOPTION_PENDING: + if admitted["status"] == "prepared" and (admitted.get("response_code") == STEWARD_BINDING_ADOPTION_PENDING + or admitted.get("mention_delivery", {}).get("action") == "unresolved"): return {"status": "admission_deferred"} status = "durably_accepted" if admitted["status"] == "accepted" else ( "queue_rejected" if admitted["status"] == "rejected" else "command_recorded") @@ -993,6 +1026,7 @@ def admit(self, profile: str, event: dict[str, Any], *, record_event_timing(profile, event["message_id"], "binding_hint_ready") with exclusive_file_lock(path, operation="capture_private_chat_request"): record_event_timing(profile, event["message_id"], "capture_lock_acquired") + fresh_capture = not path.exists() # Retain a candidate from the locally bound owner before provider # identity IO can fail. This private receipt grants no execution: # recovery still verifies the App, current owner, source and Core @@ -1006,6 +1040,11 @@ def admit(self, profile: str, event: dict[str, Any], *, "request_ref": request, "profile": profile, "binding_id": binding["binding_id"], "source": source, "event": event, "deliveries": {}, "status": "captured", **({"capture_origin": "provider_history"} if history_review else {})}) + mention_capture = self.core.capture_native_mention(binding, source) if fresh_capture else None + if fresh_capture and path.exists(): + captured = _read_json(path) + captured["mention_capture"] = mention_capture + _atomic_write_json(path, captured) try: selected = (None if control_root else self.bindings.resolve( binding_id=binding["binding_id"], **source, include_observation=True)) @@ -1049,6 +1088,10 @@ def admit(self, profile: str, event: dict[str, Any], *, return {"status": "audience_rejected"} # Reuse this admission preflight only; Core rechecks under its # source fence, and outbound writes always perform a fresh check. + if fresh_capture: + record["mention_capture"] = mention_capture + if binding.get("audience") != "group": + _atomic_write_json(path, record) source_message = self._source_message(record, selected=selected) if source_message is None: return {"status": "source_verification_failed"} @@ -1169,9 +1212,26 @@ def read(tail: list[str]) -> Mapping[str, Any] | None: else: preflight = (steward_source_preflight(selected["binding"], source_message, lambda fresh: self._source_message(record, selected=fresh)) if command is None else None) + native_mention = command is None and source_message.get("_native_mention") is True + if native_mention: + previous_preflight = preflight + + def verify_mention(fresh: dict[str, Any]) -> None: + if previous_preflight is not None: + previous_preflight(fresh) + current = self._source_message(record, selected=fresh) + if current is None: + raise PrivateSourceUnavailable("native mention source is unavailable") + if (current.get("_native_mention") is not True + or any(current.get(key) != source_message.get(key) for key in + ("content", "parent_id", "root_id", "thread_id"))): + raise ValueError("native mention source changed") + + preflight = verify_mention admitted = self.core.admit(binding_id=binding["binding_id"], source=source, request_ref=request, message=text, command=command, attachments=attachments, - defer_background_stop=defer_background_stop, source_preflight=preflight) + defer_background_stop=defer_background_stop, source_preflight=preflight, + native_mention=native_mention, native_mention_capture=record.get("mention_capture")) record_event_timing(profile, event["message_id"], "core_admission_returned") except PrivateSourceUnavailable: return {"status": "source_verification_failed"} @@ -2373,6 +2433,15 @@ def reconcile_request(self, path: Path) -> int: row = _read_json(path) if row["status"] == "captured" and row.get("response_code") == STEWARD_BINDING_ADOPTION_PENDING: return 0 + if row["status"] == "captured" and row.get("mention_delivery", {}).get("action") == "unresolved": + # This is an input receipt, not a completed user request. + # The existing worker can settle positive native readback; + # an uncertain send never becomes a new queued Turn. + with exclusive_file_lock(path, operation="deliver_private_chat_request"): + row = _read_json(path) + self._deliver(path, row, "admission", row["response"], + inbox=lambda: self._inbox(row), finalize_source=False) + return 0 native_path = self.core.root / f"{row['request_ref']}.json" if native_path.exists(): if (self.reaction_feedback and not row.get("context_recovery") and row["status"] == "accepted" diff --git a/tests/test_lark_private_conversations.py b/tests/test_lark_private_conversations.py index bef4c20103..52d8e0e8ac 100644 --- a/tests/test_lark_private_conversations.py +++ b/tests/test_lark_private_conversations.py @@ -6343,6 +6343,362 @@ def test_legacy_group_principal_and_native_home_are_not_migrated_during_observat runtime.close() +@pytest.mark.parametrize("profile", ["notes-app", "steward-app"]) +def test_private_native_mention_steers_original_busy_turn(ordinary, profile): # noqa: F811 + store, runtime, provider, transport = connect(ordinary) + capture = ordinary[4] + try: + original = provider.event(profile, "mention-original", "wait for steer") + assert transport.admit(profile, original)["status"] == "durably_accepted" + first, = transport.core.pending() + sid, tid = first["session_id"], first["turn_id"] + deadline = time.monotonic() + 10 + while not (store.load_turn(sid, tid) or {}).get("upstream_turn_id"): + assert time.monotonic() < deadline + time.sleep(.01) + body = "@Personal assistant\nPreserve this correction.\n\nAnd this second paragraph." + event = provider.event(profile, "mention-correction", body) + provider.messages[event["message_id"]]["mentions"] = [ + {"key": "@_user_1", "name": "A renamed assistant", "id": { + "open_id": f"ou_{profile.replace('-', '_')}_bot"}}] + assert transport.admit(profile, event)["status"] == "command_recorded" + ended = runtime.wait_for_turn(session_id=sid, turn_id=tid, timeout_sec=10) + assert ended["status"] == "completed" + calls = [json.loads(line) for line in capture.read_text().splitlines()] + steer, = [call for call in calls if call["method"] == "turn/steer"] + assert steer["params"]["expectedTurnId"] == ended["upstream_turn_id"] + assert steer["params"]["input"] == [{"type": "text", "text": body}] + assert sum(call["method"] == "turn/start" for call in calls) == 1 + assert not store.queued_turns(sid) + # A later redelivery may observe an idle Session; its frozen receipt + # must still name the original Turn and never create another one. + before = capture.read_bytes() + assert transport.admit(profile, {**event, "event_id": "redelivered"})["status"] == "command_recorded" + restarted = LarkPrivateConversations(controller=runtime, runtime_root=transport.runtime_root, + runner=provider, cli_bin="lark-cli") + assert restarted.admit(profile, event)["status"] == "command_recorded" + assert capture.read_bytes() == before + row = next(row for row in transport.core.pending() if row["request_ref"] != first["request_ref"]) + assert row["session_id"] == sid and row["turn_id"] == tid + assert row["mention_delivery"]["action"] == "delivered" + finally: + runtime.close() + + +def _private_mention_event(provider, profile, name, text): + event = provider.event(profile, name, text) + provider.messages[event["message_id"]]["mentions"] = [ + {"key": "@_user_1", "name": "Renamed Bot", "id": { + "open_id": f"ou_{profile.replace('-', '_')}_bot"}}] + return event + + +def _wait_private_upstream(store, row): + deadline = time.monotonic() + 10 + while not (store.load_turn(row["session_id"], row["turn_id"]) or {}).get("upstream_turn_id"): + assert time.monotonic() < deadline + time.sleep(.01) + + +@pytest.mark.parametrize("addressing", ["prose", "other_member", "other_app", "same_name", "quoted", "hint"]) +def test_private_non_native_mentions_keep_normal_queue(ordinary, addressing): # noqa: F811 + store, runtime, provider, transport = connect(ordinary) + try: + transport.admit("notes-app", provider.event("notes-app", "ordinary-busy", "wait for steer")) + original, = transport.core.pending() + _wait_private_upstream(store, original) + body = '@notes-app\nQuoted: "@notes-app please change the task"' + event = provider.event("notes-app", "unverified-mention", body) + message = provider.messages[event["message_id"]] + if addressing == "hint": + event.update(mentioned=True, addressing_source="provider_mention") + elif addressing == "quoted": + message["quoted_message"] = {"mentions": [{"id": {"open_id": "ou_notes_app_bot"}}]} + elif addressing != "prose": + identity = {"other_member": "ou_person", "other_app": "ou_steward_app_bot", "same_name": "ou_imposter"}[addressing] + message["mentions"] = [{"name": "notes-app", "id": {"open_id": identity}}] + assert transport.admit("notes-app", event)["status"] == "durably_accepted" + assert [turn["message"] for turn in store.queued_turns(original["session_id"])] == [body] + calls = [json.loads(line) for line in ordinary[4].read_text().splitlines()] + assert not any(call["method"] == "turn/steer" for call in calls) + finally: + runtime.close() + + +def test_private_idle_native_mention_uses_original_queue(ordinary): # noqa: F811 + store, runtime, provider, transport = connect(ordinary) + try: + event = _private_mention_event(provider, "notes-app", "idle-mention", "@notes-app\nAn ordinary question.") + assert transport.admit("notes-app", event)["status"] == "durably_accepted" + row, = transport.core.pending() + assert runtime.wait_for_turn(session_id=row["session_id"], turn_id=row["turn_id"], timeout_sec=10)["status"] == "completed" + receipt = store.steering_receipt(row["session_id"], "external-" + row["request_ref"]) + assert receipt["mode"] == "session_queue" + calls = [json.loads(line) for line in ordinary[4].read_text().splitlines()] + assert sum(call["method"] == "turn/start" for call in calls) == 1 + assert not any(call["method"] == "turn/steer" for call in calls) + finally: + runtime.close() + + +def test_private_mentions_keep_two_busy_app_sessions_isolated(ordinary): # noqa: F811 + store, runtime, provider, transport = connect(ordinary) + try: + originals = {} + for profile in ("notes-app", "steward-app"): + transport.admit(profile, provider.event(profile, "busy-" + profile, "wait for steer")) + originals[profile] = next(row for row in transport.core.pending() if row["message"] == "wait for steer" + and row["request_ref"] == identity_ref(transport._binding(profile)["provider_ref"], "om_busy-" + profile)) + _wait_private_upstream(store, originals[profile]) + assert originals["notes-app"]["session_id"] != originals["steward-app"]["session_id"] + for profile in ("notes-app", "steward-app"): + event = _private_mention_event(provider, profile, "adjust-" + profile, "Correction only for " + profile) + with ThreadPoolExecutor(max_workers=2) as calls: + results = list(calls.map(lambda _: transport.admit(profile, event), range(2))) + assert all(result["status"] == "command_recorded" for result in results) + row = transport.core.read_request(identity_ref(transport._binding(profile)["provider_ref"], event["message_id"])) + assert (row["session_id"], row["turn_id"]) == (originals[profile]["session_id"], originals[profile]["turn_id"]) + peer = "steward-app" if profile == "notes-app" else "notes-app" + assert not any(message.get("text") == "Correction only for " + profile + for message in store.messages(originals[peer]["session_id"])) + captured = [json.loads(line) for line in ordinary[4].read_text().splitlines()] + assert sum(call["method"] == "turn/start" for call in captured) == 2 + assert sum(call["method"] == "turn/steer" for call in captured) == 2 + finally: + runtime.close() + + +@pytest.mark.parametrize("fault", ["turn_switched", "revoked", "source_changed", "host_unavailable"]) +def test_private_mention_keeps_frozen_target_across_failed_admission(ordinary, monkeypatch, fault): # noqa: F811 + store, runtime, provider, transport = connect(ordinary) + detached = None + try: + transport.admit("notes-app", provider.event("notes-app", "fenced-busy", "wait for steer")) + original, = transport.core.pending() + sid, tid = original["session_id"], original["turn_id"] + _wait_private_upstream(store, original) + event = _private_mention_event(provider, "notes-app", "fenced-mention", "Apply only to the original Turn.") + provider_ref = transport._binding("notes-app")["provider_ref"] + admit, changed = transport.core.admit, False + + def change_during_preflight(**kwargs): + verify = kwargs["source_preflight"] + + def preflight(selected): + nonlocal changed, detached + if not changed: + changed = True + if fault == "turn_switched": + runtime.interrupt_turn(session_id=sid, turn_id=tid) + runtime.wait_for_turn(session_id=sid, turn_id=tid, timeout_sec=10) + later, _ = runtime.enqueue_turn(session_id=sid, client_turn_id="later-turn", + message="wait for steer", work_dir=ordinary[-1], objective="", origin="lark") + _wait_private_upstream(store, later) + elif fault == "revoked": + transport.bindings.disconnect(original["binding_id"], expected_revision=transport.bindings.read()["revision"]) + elif fault == "source_changed": + provider.messages[event["message_id"]]["mentions"] = [] + else: + with runtime.lock: + detached = runtime.adapters.pop(sid) + verify(selected) + + return admit(**{**kwargs, "source_preflight": preflight}) + + monkeypatch.setattr(transport.core, "admit", change_during_preflight) + result = transport.admit("notes-app", event) + assert result["status"] in {"command_recorded", "command_rejected"} + row = transport.core.read_request(identity_ref(provider_ref, event["message_id"])) + assert row["mention_capture"]["target_turn_id"] == tid + calls = [json.loads(line) for line in ordinary[4].read_text().splitlines()] + assert not any(call["method"] == "turn/steer" for call in calls) + assert not store.queued_turns(sid) + finally: + if detached is not None: + with runtime.lock: + runtime.adapters[original["session_id"]] = detached + runtime.close() + + +@pytest.mark.parametrize("phase", ["identity", "message"]) +def test_private_mention_does_not_target_turn_started_during_provider_read(ordinary, monkeypatch, phase): # noqa: F811 + store, runtime, provider, transport = connect(ordinary) + try: + transport.admit("notes-app", provider.event("notes-app", "intake-busy", "wait for steer")) + original, = transport.core.pending() + sid, tid = original["session_id"], original["turn_id"] + _wait_private_upstream(store, original) + event = _private_mention_event(provider, "notes-app", "slow-source-mention", "Only correct the Turn that received this.") + read_source = transport.bindings.resolve if phase == "identity" else transport._source_message + switched = False + + def slow_source(*args, **kwargs): + nonlocal switched + if not switched: + switched = True + runtime.interrupt_turn(session_id=sid, turn_id=tid) + runtime.wait_for_turn(session_id=sid, turn_id=tid, timeout_sec=10) + later, _ = runtime.enqueue_turn(session_id=sid, client_turn_id="during-source-read", + message="wait for steer", work_dir=ordinary[-1], objective="", origin="lark") + _wait_private_upstream(store, later) + return read_source(*args, **kwargs) + + monkeypatch.setattr(transport.bindings if phase == "identity" else transport, + "resolve" if phase == "identity" else "_source_message", slow_source) + assert transport.admit("notes-app", event)["status"] == "command_recorded" + row = transport.core.read_request(identity_ref(transport._binding("notes-app")["provider_ref"], event["message_id"])) + assert row["mention_capture"]["target_turn_id"] == tid + assert row["mention_delivery"]["action"] == "reject" + calls = [json.loads(line) for line in ordinary[4].read_text().splitlines()] + assert not any(call["method"] == "turn/steer" for call in calls) + finally: + runtime.close() + + +def test_private_steward_native_mention_uses_original_manager_turn(tmp_path, monkeypatch): + from test_native_steward_private import steward + + fixture = steward.__wrapped__(tmp_path) + store, runtime, provider, transport, binding, capture, _ = next(fixture) + try: + event = provider.event("steward-app", "manager-original", "wait for interrupt") + assert transport.admit("steward-app", event)["status"] == "durably_accepted" + original, = transport.core.pending() + _wait_private_upstream(store, original) + session = store.load_session(original["session_id"]) + assert session["steward_context"]["audience"] == "bound_owner" + correction = _private_mention_event(provider, "steward-app", "manager-adjust", "Correct the current inspection.") + assert transport.admit("steward-app", correction)["status"] == "command_recorded" + row = transport.core.read_request(identity_ref(binding["provider_ref"], correction["message_id"])) + assert row["mention_delivery"]["action"] == "delivered" + assert row["turn_id"] == original["turn_id"] and row["session_id"] == original["session_id"] + calls = [json.loads(line) for line in capture.read_text().splitlines()] + assert sum(call["method"] in {"thread/goal/set", "turn/start"} for call in calls) == 1 + assert sum(call["method"] == "turn/steer" for call in calls) == 1 + assert not store.queued_turns(original["session_id"]) + finally: + runtime.close() + fixture.close() + + +def test_private_steward_mention_requires_current_active_turn_authorization(tmp_path): + from test_native_steward_private import steward + from loopx.chat_manager_context import manager_authorization_scope_is_current + + fixture = steward.__wrapped__(tmp_path) + store, runtime, provider, transport, binding, capture, _ = next(fixture) + try: + transport.admit("steward-app", provider.event("steward-app", "scope-original", "wait for interrupt")) + original, = transport.core.pending() + _wait_private_upstream(store, original) + sid = original["session_id"] + scope = store.load_session(sid)["manager_authorization_scope_id"] + store.update_session(sid, manager_authorization_scope_id="stale-scope") + assert not manager_authorization_scope_is_current(runtime.registry_path, runtime.manager_scope_resolver, + store.load_session(sid), "stale-scope", runtime_root=runtime.coordination_runtime_root) + correction = _private_mention_event(provider, "steward-app", "scope-denied", "Correct only with current authority.") + assert transport.admit("steward-app", correction)["status"] == "command_recorded" + row = transport.core.read_request(identity_ref(binding["provider_ref"], correction["message_id"])) + assert row["mention_delivery"]["action"] == "reject" + assert not any(json.loads(line)["method"] == "turn/steer" for line in capture.read_text().splitlines()) + # A fresh explicit correction after the original scope is restored can + # make progress; it cannot replay the previously rejected input. + store.update_session(sid, manager_authorization_scope_id=scope) + restored = _private_mention_event(provider, "steward-app", "scope-restored", "Continue under the restored original scope.") + assert transport.admit("steward-app", restored)["status"] == "command_recorded" + row = transport.core.read_request(identity_ref(binding["provider_ref"], restored["message_id"])) + assert row["mention_delivery"]["action"] == "delivered" and row["turn_id"] == original["turn_id"] + finally: + runtime.close() + fixture.close() + + +def test_private_mention_keeps_images_instead_of_steering_text_alone(ordinary): # noqa: F811 + from test_lark_private_images import image_runner + from test_chat_image_attachments import PNG_DATA_URL + + store, runtime, provider, transport = connect(ordinary) + transport.runner = image_runner(provider) + try: + transport.admit("notes-app", provider.event("notes-app", "image-busy", "wait for steer")) + original, = transport.core.pending() + _wait_private_upstream(store, original) + event = _private_mention_event(provider, "notes-app", "image-adjust", "Keep the caption\n![Image](img_example)") + event["message_type"] = "post" + provider.messages[event["message_id"]]["msg_type"] = "post" + assert transport.admit("notes-app", event)["status"] == "command_recorded" + row = next(row for row in transport.core.pending() if row["request_ref"] != original["request_ref"]) + assert row["mention_delivery"] == {"action": "reject", "error_code": "queue_steering_attachments_unavailable"} + assert row["attachments"][0]["data_url"] == PNG_DATA_URL + assert "Keep the caption" in row["message"] + assert not store.queued_turns(original["session_id"]) + calls = [json.loads(line) for line in ordinary[4].read_text().splitlines()] + assert not any(call["method"] == "turn/steer" for call in calls) + assert sum(call["method"] == "turn/start" for call in calls) == 1 + finally: + runtime.close() + + +def test_private_mention_lost_native_ack_waits_for_exact_readback_without_resending(ordinary, monkeypatch): # noqa: F811 + from loopx.capabilities.native_chat.codex_adapter import CodexAppServerAdapter + + store, runtime, provider, transport = connect(ordinary) + try: + transport.admit("notes-app", provider.event("notes-app", "uncertain-busy", "wait for steer")) + original, = transport.core.pending() + sid = original["session_id"] + _wait_private_upstream(store, original) + body = "Exact correction after an uncertain ACK." + event = _private_mention_event(provider, "notes-app", "uncertain-adjust", body) + native_steer = CodexAppServerAdapter.steer_turn + + def lose_ack(adapter, *args): + native_steer(adapter, *args) + raise RuntimeError("native response was lost after the send") + + monkeypatch.setattr(CodexAppServerAdapter, "steer_turn", lose_ack) + monkeypatch.setattr(CodexAppServerAdapter, "steering_delivery_readback", lambda *_: []) + assert transport.admit("notes-app", event)["status"] == "admission_deferred" + ref = identity_ref(transport._binding("notes-app")["provider_ref"], event["message_id"]) + first = transport.core.read_request(ref) + assert first["status"] == "prepared" and first["mention_delivery"]["action"] == "unresolved" + capture = ordinary[4] + packets = [json.loads(line) for line in capture.read_text().splitlines()] + sent, = [call for call in packets if call["method"] == "turn/steer"] + before = len(packets) + restarted = LarkPrivateConversations(controller=runtime, runtime_root=transport.runtime_root, + runner=provider, cli_bin="lark-cli") + path = restarted.root / f"{ref}.json" + restarted.reconcile_request(path) + unresolved = restarted.core.read_request(ref) + assert unresolved["mention_delivery"]["action"] == "unresolved" + assert not unresolved.get("delivery_verified") + assert any("送达状态待核实" in text for _, text in provider.writes) + # This evidence comes from the captured native request, rather than a + # proposed target or a new model turn. Wrong text cannot settle it. + visible_body = "A different correction" + def readback(_adapter, turn_id): + return [{"turnId": turn_id, "item": {"type": "userMessage", + "clientId": sent["params"]["clientUserMessageId"], + "content": [{"type": "text", "text": visible_body}]}}] + + monkeypatch.setattr(CodexAppServerAdapter, "steering_delivery_readback", readback) + restarted.reconcile_request(path) + assert restarted.core.read_request(ref)["mention_delivery"]["action"] == "unresolved" + visible_body = body + restarted.reconcile_request(path) + settled = restarted.core.read_request(ref) + assert settled["mention_delivery"]["action"] == "delivered" + assert settled["turn_id"] == original["turn_id"] and settled["delivery_verified"] + assert any(text == "已送达当前回合。" for _, text in provider.writes) + packets = [json.loads(line) for line in capture.read_text().splitlines()] + assert sum(call["method"] == "turn/steer" for call in packets) == 1 + assert sum(call["method"] == "turn/start" for call in packets) == 1 + assert len(packets) >= before and not store.queued_turns(sid) + finally: + runtime.close() + + def test_native_private_admission_queue_other_app_stop_and_verified_delivery(ordinary): # noqa: F811 store, runtime, provider, transport = connect(ordinary) try: