Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ def emit(event: str, data: dict) -> str:
# Vibe Island notch 状态收口(engine 的 safe_send 不走
# _push_session_event,所以这里单独埋):开关关闭时 no-op,绝不抛。
eng._vibe_island.on_turn_event(ctx.session_id, event, data)
# 流式提问直接经 safe_send 送到桌面和渠道 tap。
if event == "user.question":
from ....channels.ask_relay import on_turn_event

on_turn_event(ctx.session_id, event, data)
# frame_session is stamped on every turn frame: the client drops any
# frame whose frame_session isn't the socket's own session, making a
# cross-session render leak structurally impossible (2026-10-01).
Expand Down
67 changes: 39 additions & 28 deletions packages/runtime/src/ginno_runtime/channels/ask_relay.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,9 @@
graph 不打断、无需 resume 机制。

**B. 卡片镜像(auto 续跑等有人值守语义、但桌面无人看)**:
``on_turn_event`` 挂在 ``_push_session_event``(与 vibe_island 同型)
——user.question 事件且该 turn 无渠道 tap 时,用 push_only tap 复用
``_send_question``(发卡片 + register pending + 超时 resume)——企微
回复走 wecom adapter 现成的 ``_try_answer`` → resume_question 统一
段(qid 一次性凭证 + 墓碑重放防线),近零新机制。
两条事件出口都调用 ``on_turn_event``(流式引擎和 ``_push_session_event``)。
无渠道 tap 时主动推送问题。有绑定的企微会话使用自己的聊天地址,桌面会话
使用最近活跃地址。企微回复经 ``_try_answer`` 进入统一的 ``resume_question``。

开关:settings.json ``"ask_relay_wecom": true``(默认关;无 UI)。
fail-safe:wecom 未连接/无活跃 chat_key → A 直接回退现状回执、B 静默
Expand All @@ -29,14 +27,15 @@
from typing import Any

from ginno_runtime import paths
from ginno_runtime import server_shared as shared


def _relay_enabled() -> bool:
try:
raw = json.loads(paths.settings_path().read_text() or "{}")
except Exception: # noqa: BLE001 — settings 损坏按未开启
except (OSError, ValueError):
return False
return bool(raw.get("ask_relay_wecom"))
return isinstance(raw, dict) and bool(raw.get("ask_relay_wecom"))


def _wecom_adapter():
Expand Down Expand Up @@ -156,31 +155,43 @@ async def relay_ask(
# ---------------------------------------------------------------------------

def on_turn_event(session_id: str | None, event: str, data: dict) -> None:
"""_push_session_event 的全局钩子(与 vibe_island 同型,绝不抛)。"""
try:
_note_loop()
if event != "user.question" or not _relay_enabled() or not session_id:
return
asyncio.get_running_loop().create_task(_mirror_question(session_id, data))
except RuntimeError:
pass # 无事件循环(极端场景)——静默
"""在后台镜像提问,桌面发帧无需等待企微回执。"""
_note_loop()
if event == "user.question" and session_id and _relay_enabled():
shared.spawn_bg(_mirror_question(session_id, data))


async def _mirror_question(session_id: str, data: dict) -> None:
ad = _wecom_adapter()
chat_key = getattr(ad, "last_chat_key", None) if ad else None
if not ad or not chat_key:
from .base import ChannelTap
from .wecom.tap import WeComTap

sockets = shared._SESSION_WS.get(session_id) or []
if any(isinstance(socket, ChannelTap) for socket in sockets):
return # 正常渠道回合由自己的 tap 发送。
channel = (shared._SESSIONS.get(session_id) or {}).get("channel")
if channel and channel != "wecom":
return
# 该 turn 已有 wecom tap(企微发起)则不镜像——只有非渠道 turn 才补触达。
q_id = str(data.get("id") or "")
if q_id and q_id in getattr(ad, "_own_question_ids", frozenset()):
if data.get("multi"):
# 企微文本回执一次只能提交一个答案。
return
from .wecom.tap import WeComTap

tap = WeComTap.push_only(ad, chat_key)
payload = dict(data)
payload.setdefault("session_id", session_id)
try:
await tap._send_question(payload)
except Exception: # noqa: BLE001 — 镜像失败不影响桌面卡片
pass
ad = _wecom_adapter()
chat_key = ad.question_destination(session_id) if ad else None
if not chat_key:
shared._log.info("wecom_question_mirror_no_destination session=%s", session_id)
return
q_id = str(data.get("qid") or data.get("id") or "")
if q_id and q_id in ad._own_question_ids:
return
tap = WeComTap.push_only(ad, chat_key)
tap.session_id = session_id
if await tap._send_question(data):
shared._log.info("wecom_question_mirror_sent session=%s", session_id)
else:
shared._log.info("wecom_question_mirror_chat_busy session=%s", session_id)
except Exception as exc: # noqa: BLE001 — 镜像失败时桌面卡片仍可作答
shared._log.warning(
"wecom_question_mirror_failed session=%s error_type=%s",
session_id, type(exc).__name__,
)
43 changes: 36 additions & 7 deletions packages/runtime/src/ginno_runtime/channels/wecom/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,8 @@ async def _try_answer(self, req_id: str, chat_key: str, text: str) -> bool:
answer=str(value.get("answer") or ""),
option_index=value.get("option_index"),
skip=bool(value.get("skip")),
arm_from_checkpoint=True,
# 主动镜像关联当前进程的停车守卫。桌面已答时不再重新武装。
arm_from_checkpoint=not pending.get("proactive"),
answered_by="wecom",
)
if ok:
Expand Down Expand Up @@ -622,14 +623,42 @@ async def _dispatch_media(self, req_id: str, chat_key: str, userid: str,

# ---- ask_user 登记(tap 调用)---------------------------------------------

async def register_pending_question(self, chat_key: str, session_id: str,
question_id: str, options: list) -> None:
self._pending_q[chat_key] = {
def question_destination(self, session_id: str) -> str | None:
"""有渠道绑定时只在已绑定的聊天中选目标。"""
bindings = self._mapper.chats_for(session_id) if self._mapper is not None else []
chats = {item["chat_id"] for item in bindings if item["chat_id"]}
if not chats:
session = shared._SESSIONS.get(session_id) or {}
return None if session.get("channel") == "wecom" else self.last_chat_key
if self.last_chat_key in chats:
return self.last_chat_key
return next(iter(chats)) if len(chats) == 1 else None

async def register_pending_question(
self, chat_key: str, session_id: str, question_id: str, options: list,
*, proactive: bool = False,
) -> dict | None:
previous = self._pending_q.get(chat_key)
if previous is not None:
previous_session = previous.get("session_id")
if (
previous.get("kind") == "devswap"
or (question_id and previous.get("question_id") == question_id)
or (previous_session != session_id and previous_session in shared._PENDING_RESUME)
):
return None
pending = {
"session_id": session_id, "question_id": question_id,
"options": options,
"options": options, "proactive": proactive,
}
self._pending_q[chat_key] = pending
# 新问题作废旧墓碑:之后的拒绝提示不得误引上一问的答案
self._answered_q.pop(chat_key, None)
return pending

async def unregister_pending_question(self, chat_key: str) -> None:
self._pending_q.pop(chat_key, None)
async def unregister_pending_question(self, chat_key: str, pending: dict) -> bool:
# 超时和发送失败只能撤销本次登记。
if self._pending_q.get(chat_key) is pending:
self._pending_q.pop(chat_key, None)
return True
return False
83 changes: 43 additions & 40 deletions packages/runtime/src/ginno_runtime/channels/wecom/tap.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from pathlib import Path
from typing import TYPE_CHECKING

from ... import server_shared as shared
from ..base import ChannelTap, TurnProgressTracker
from . import protocol as p

Expand Down Expand Up @@ -108,8 +109,7 @@ def __init__(self, adapter: WeComChannelAdapter, req_id: str,
self._stream_done = False # finish=true 已发(超时强制或终态)
self._finalized = False
self._ask_timer: asyncio.TimerHandle | None = None
self._question_id: str | None = None
self._options: list = []
self._pending_question: dict | None = None
# P1 进展区:thinking/tool 帧 → markdown 引用块,流中原地更新、终稿清场
self._progress = TurnProgressTracker()
# 正文媒体补发去重(_flush_text_media):一路径一 turn 至多发一次
Expand Down Expand Up @@ -161,7 +161,9 @@ async def _finalize(self, note: str = "") -> None:
if self._finalized:
return
self._finalized = True
self._cancel_ask_timer()
# 回合在提问处暂停时也会关闭 tap。待答登记须保留到作答或超时。
if note or shared._PENDING_KIND.get(self.session_id) != "user_question":
await self._cancel_ask_timer()
self._progress.clear() # 终稿只留正文
await self._maybe_flush(force=True)
body = self._full or "(无输出)"
Expand Down Expand Up @@ -206,58 +208,60 @@ async def _flush_text_media(self) -> None:

# ---- ask_user(文本作答路径)---------------------------------------------

async def _send_question(self, data: dict) -> None:
q_id = str(data.get("id") or "")
self._question_id = q_id
self._options = list(data.get("options") or [])
# ask_relay 镜像去重:本 tap 已发的 qid 登记(wecom 自己发起的
# turn 不再镜像第二份卡片)。getattr 防御——测试 FakeAdapter 等
# 子类可能未初始化该 deque。
_ids = getattr(self.adapter, "_own_question_ids", None)
if _ids is not None and q_id:
_ids.append(q_id)
async def _send_question(self, data: dict) -> bool:
q_id = str(data.get("qid") or data.get("id") or "")
options = list(data.get("options") or [])
lines = [f"\n\n❓ **{data.get('header') or 'Ginno 提问'}**",
str(data.get("question") or "")]
for i, opt in enumerate(self._options):
for i, opt in enumerate(options):
lines.append(f"{i + 1}. {opt}")
lines.append("\n(直接回复数字或文字作答;回复「跳过」跳过)")
md = "\n".join(lines)
self._buf.append(md)
self._buf_len += len(md)
await self._maybe_flush(force=True)
# 登记待答:该会话的下一条文本消息会走 resume 而不是新 turn
await self.adapter.register_pending_question(
self.chat_key, self.session_id, q_id, self._options)
timeout_s = float(self.adapter.config.get("ask_timeout_s") or 600)
# 回执到达前就可以收到用户回复,先占用该聊天的待答位置。
pending = await self.adapter.register_pending_question(
self.chat_key, self.session_id, q_id, options, proactive=not self.req_id)
if pending is None:
return False
try:
if self._stream_done:
await self.adapter.client.send_markdown(self.chat_key, md)
else:
self._buf.append(md)
self._buf_len += len(md)
await self._maybe_flush(force=True)
except (Exception, asyncio.CancelledError):
await self.adapter.unregister_pending_question(self.chat_key, pending)
raise

ids = getattr(self.adapter, "_own_question_ids", None)
if ids is not None and q_id:
ids.append(q_id)
self._pending_question = pending
loop = asyncio.get_running_loop()
self._ask_timer = loop.call_later(
timeout_s, lambda: asyncio.create_task(self._ask_timeout()))
timeout_s, lambda: shared.spawn_bg(self._ask_timeout(pending)))
return True

async def _ask_timeout(self) -> None:
async def _ask_timeout(self, pending: dict) -> None:
from ...api.stream.resume import resume_question

await self.adapter.unregister_pending_question(self.chat_key)
# 超时跳过同样走 resume_question 共享段(relay 墓碑统一收口)。
# 刻意不带 arm_from_checkpoint:计时器是兜底不是凭证——用户可能
# 刚在桌面答完(resume 任务在跑),宽松武装会把已答问题再拉起。
ok = await resume_question(
self.session_id, skip=True, answered_by="wecom_timeout")
if not await self.adapter.unregister_pending_question(self.chat_key, pending):
return # 已作答,或此聊天已有更新的待答登记。
session_id = pending["session_id"]
ok = await resume_question(session_id, skip=True, answered_by="wecom_timeout")
if ok:
# 渠道墓碑:超时跳过也算「已答」,晚到的企微回复命中墓碑被
# 拒绝并告知,而不是回落成新 turn。
self.adapter.mark_question_answered(
self.chat_key, qid=self._question_id or "",
session_id=self.session_id, skip=True,
answered_by="wecom_timeout")
self.chat_key, qid=pending["question_id"],
session_id=session_id, skip=True, answered_by="wecom_timeout")

def _cancel_ask_timer(self) -> None:
async def _cancel_ask_timer(self) -> None:
if self._ask_timer is not None:
self._ask_timer.cancel()
self._ask_timer = None
if self._question_id:
task = asyncio.ensure_future(
self.adapter.unregister_pending_question(self.chat_key))
task.add_done_callback(lambda t: t.exception() if not t.cancelled() else None)
pending, self._pending_question = self._pending_question, None
if pending is not None:
await self.adapter.unregister_pending_question(self.chat_key, pending)

# ---- 产物上行(P1)-------------------------------------------------------

Expand Down Expand Up @@ -355,6 +359,5 @@ async def on_frame(self, event: str, data: dict) -> None:
# thinking.delta / tool.* / keepalive / artifacts.changed / …: 忽略

async def close(self) -> None:
"""turn 结束兜底:cancel 定时器 + 未终态时补一次 finalize。"""
self._cancel_ask_timer()
"""在流结束时补发定格帧,并保留暂停回合的待答登记。"""
await self._finalize()
72 changes: 72 additions & 0 deletions packages/runtime/tests/e2e/test_wecom_question_delivery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""A worker result can park a WeCom-bound session without a channel tap."""

from __future__ import annotations

import asyncio
from unittest.mock import AsyncMock

import pytest
from conftest import events_of, script, script_tool_call

from ginno_runtime import jsonx as json
from ginno_runtime import server_shared
from ginno_runtime.channels.wecom.adapter import WeComChannelAdapter
from ginno_runtime.channels.wecom.sessions import SessionMapper
from ginno_runtime.connectors import builtin
from ginno_runtime.session_meta import mark_channel_meta
from ginno_runtime.subagent_scheduler.runner import _wake_parent_turn

pytestmark = pytest.mark.e2e


def test_wake_turn_sends_once_and_wecom_answer_resumes_same_question(
client, create_session, ws_conv, isolated_home, monkeypatch,
):
sid = create_session([
script(tool_calls=[script_tool_call(
"ask_user",
{"header": "验收选择", "question": "选哪个?", "options": ["A", "B"]},
"call_wecom_question",
)]),
script(text="收到选择。"),
])
settings = isolated_home / "settings.json"
raw = json.loads(settings.read_text())
raw["ask_relay_wecom"] = True
settings.write_text(json.dumps(raw))
ad = WeComChannelAdapter()
ad._mapper = SessionMapper(isolated_home / "channels" / "test-mappings.json")
ad._mapper.bind(user_id="bound-user", chat_id="bound-user", ginno_session=sid)
ad.last_chat_key = "unrelated-user"
ad.client = AsyncMock()
monkeypatch.setattr(builtin, "_wecom_adapter", ad)
client.portal.call(mark_channel_meta, server_shared._SESSIONS[sid], "wecom")

# The fake replaces only the external network request. The graph, event
# dispatch, pending-answer registration and adapter callbacks are real.
async def send_answer():
assert ad.client.send_markdown.await_count == 1
chat, card = ad.client.send_markdown.await_args.args
assert chat == "bound-user"
assert "验收选择" in card and "1. A" in card and "2. B" in card
await ad.handle_msg(
{"from": {"userid": chat}, "chattype": "single", "msgtype": "text",
"text": {"content": "2"}},
{"headers": {"req_id": "test-answer"}},
)
assert ad.client.respond.await_count == 0 # no new channel turn

with ws_conv(sid) as conv:
assert client.portal.call(_wake_parent_turn, sid, "子代理结果", {}) == "ran"
parked = conv.recv_until("user.question", "error", "message.end")
assert events_of(parked, "user.question")[0]["id"] == "call_wecom_question"
# The managed turn has already settled at its interrupt before answering.
client.portal.call(send_answer)
resumed = conv.recv_until("message.end", "error")
assert not events_of(resumed, "error")

results = [e for e in events_of(resumed, "tool.end") if e.get("id") == "call_wecom_question"]
assert len(results) == 1
receipt = json.loads(results[0]["content"])
assert receipt["source"] == "option"
assert receipt["answer"] == "B" and receipt["option_index"] == 1
Loading
Loading