feat: mid-turn follow-ups queue and append as supplement on next step

This commit is contained in:
openbot-coder committed 2026-10-22 18:17:46 +08:00
1 parent c7497f0c4a
commit 89aee65ddc
2 files changed
+221 -2

No files matched your search

+81 -2
View File
@@ -157,6 +157,7 @@ class SessionManager:
self.permission_timeout_s = 300 # 5min to answer; timeout -> deny
self._deltas: dict[str, list[str]] = {} # binding_key -> accumulated turn text
self._media_seen: dict[str, dict[str, float]] = {} # agent -> workspace file snapshot
self._pending_followups: dict[tuple[str, str], list[dict[str, Any]]] = {} # chat key -> queued messages (mid-turn supplements)
self._db: sqlite3.Connection | None = None
if db_path:
@@ -363,9 +364,87 @@ class SessionManager:
files: list[dict[str, Any]] | None = None,
timeout_s: float | None = None,
) -> dict[str, Any]:
"""Run one turn on the bound (or newly created) session."""
"""Run one turn on the bound (or newly created) session.
If a turn is already in flight for this chat, the message is queued
as a follow-up: the caller returns immediately with {"queued": True}
and the queued texts are appended (as "[用户补充] …") in the next
prompt round once the current turn finishes — the agent sees them
with the conversation context intact.
"""
k = self.key(channel, chat_id)
with self._lock_for(k): # serialize turns per chat
lock = self._lock_for(k)
if not lock.acquire(blocking=False):
# turn in flight: queue as follow-up, ack at once
with self._lock:
self._pending_followups.setdefault(k, []).append({
"text": text, "images": images or [], "files": files or [],
})
key = f"{channel}:{chat_id}"
self._emit(key, "status", {"text": "已收到,将在当前回答结束后作为补充追加给 agent。"})
log.info(f"[{key}] follow-up queued mid-turn ({len(text)} chars)")
return {"queued": True, "session_id": None, "agent": None}
try:
return self._prompt_locked(channel, chat_id, text, agent, cwd,
images, files, timeout_s)
finally:
lock.release()
def _prompt_locked(
self,
channel: str,
chat_id: str,
text: str,
agent: str | None = None,
cwd: str | None = None,
images: list[bytes] | None = None,
files: list[dict[str, Any]] | None = None,
timeout_s: float | None = None,
) -> dict[str, Any]:
"""Caller holds the per-chat prompt lock. Runs one turn; then, while
follow-ups are queued, keeps prompting with the queued supplements
joined into a single "[用户补充]" block per round."""
k = self.key(channel, chat_id)
result: dict[str, Any] = {}
while True:
result = self._run_one_turn(channel, chat_id, text, agent, cwd,
images, files, timeout_s)
with self._lock:
pending = self._pending_followups.pop(k, [])
if not pending:
break
# join all queued follow-ups (in arrival order) into one supplement
parts: list[str] = []
sup_images: list[bytes] = []
sup_files: list[dict[str, Any]] = []
for m in pending:
if m["images"]:
sup_images.extend(m["images"])
if m["files"]:
sup_files.extend(m["files"])
parts.append(m["text"])
supplement = "\n".join(parts)
text = f"[用户补充] {supplement}"
images = sup_images or None
files = sup_files or None
agent = None
cwd = None
timeout_s = None
return result
def _run_one_turn(
self,
channel: str,
chat_id: str,
text: str,
agent: str | None = None,
cwd: str | None = None,
images: list[bytes] | None = None,
files: list[dict[str, Any]] | None = None,
timeout_s: float | None = None,
) -> dict[str, Any]:
k = self.key(channel, chat_id)
if True: # keep indentation of the original single-turn body
if agent and agent not in self.agents:
raise UnknownAgent(f"agent {agent!r} not configured")
with self._lock:
+140
View File
@@ -0,0 +1,140 @@
"""Follow-up messages arriving mid-turn are queued and appended as a
supplement in the next prompt, instead of waiting behind the lock as an
independent turn.
Flow (per chat):
1. prompt() while a turn is in flight -> message is queued, caller gets
{"queued": True} immediately; a status event "…将合并到本轮结束后追加"
is emitted so the user sees an ack.
2. when the in-flight turn finishes, the queue is drained inside the same
lock: all pending texts are joined and prompted as one supplement turn
("[用户补充] …"). The channel's own inbound thread that queued the
message is released immediately (it does not block waiting).
"""
import threading
import time
def _make_mgr(tmp_path, monkeypatch, stub):
from agenthub.session import SessionManager
mgr = SessionManager({"opencode": {"cmd": "opencode acp"}},
db_path=str(tmp_path / "s.db"))
monkeypatch.setattr(mgr, "_client_for", lambda name: stub)
monkeypatch.setattr(mgr, "_ensure_session", lambda k, a, cwd=None: (stub, "s9"))
monkeypatch.setattr(mgr, "_agent_cwd", lambda agent: str(tmp_path / "ws"))
(tmp_path / "ws").mkdir(exist_ok=True)
events: list[tuple] = []
monkeypatch.setattr(mgr, "_sink", lambda k, kind, payload: events.append((k, kind, payload)))
mgr._test_events = events
monkeypatch.setattr("agenthub.session.scan_new_files", lambda *a, **k: [],
raising=False)
return mgr
class StubClient:
def __init__(self):
self._notif_handlers = []
self._req_handlers = []
self.prompts = []
self.gate = threading.Event() # when set, session_prompt returns
self.lock = threading.Lock()
def is_alive(self):
return True
def register_notification_handler(self, h):
self._notif_handlers.append(h)
def register_request_handler(self, h):
self._req_handlers.append(h)
def session_prompt(self, sid, blocks, timeout=None):
with self.lock:
self.prompts.append([dict(b) for b in blocks])
self.gate.wait(timeout=10)
return {"stopReason": "end_turn"}
def session_new(self, cwd=None, mcp_servers=None):
return "s9"
def set_config_option(self, sid, config_id, value):
return {"currentValue": value}
def list_config_options(self, sid):
return {"configOptions": []}
def close(self, timeout: float = 2.0):
pass
def test_second_message_queues_and_appends(tmp_path, monkeypatch):
"""While turn 1 is in flight, prompt() returns queued=True at once;
after turn 1 finishes the queued text is prompted as [用户补充]."""
stub = StubClient()
mgr = _make_mgr(tmp_path, monkeypatch, stub)
t1_done = threading.Event()
def turn1():
mgr.prompt("wecom", "c1", "第一问")
t1_done.set()
threading.Thread(target=turn1, daemon=True).start()
deadline = time.time() + 5
while len(stub.prompts) < 1 and time.time() < deadline:
time.sleep(0.02)
assert len(stub.prompts) == 1
# second message arrives mid-turn: must queue, not block
res2 = mgr.prompt("wecom", "c1", "补充内容")
assert res2.get("queued") is True
time.sleep(0.1)
assert len(stub.prompts) == 1, "queued message must not hit the agent yet"
assert any(kind == "status" for _, kind, _ in mgr._test_events)
# release turn 1 -> the supplement turn must fire automatically
stub.gate.set()
assert t1_done.wait(timeout=5)
deadline = time.time() + 5
while len(stub.prompts) < 2 and time.time() < deadline:
time.sleep(0.05)
assert len(stub.prompts) == 2, "supplement turn should auto-fire"
text = stub.prompts[1][0]["text"]
assert "[用户补充]" in text and "补充内容" in text
def test_queue_drains_multiple_messages_in_one_turn(tmp_path, monkeypatch):
stub = StubClient()
mgr = _make_mgr(tmp_path, monkeypatch, stub)
threading.Thread(target=lambda: mgr.prompt("wecom", "c1", "主问"),
daemon=True).start()
deadline = time.time() + 5
while len(stub.prompts) < 1 and time.time() < deadline:
time.sleep(0.02)
mgr.prompt("wecom", "c1", "补充一")
mgr.prompt("wecom", "c1", "补充二")
stub.gate.set()
deadline = time.time() + 5
while len(stub.prompts) < 2 and time.time() < deadline:
time.sleep(0.05)
assert len(stub.prompts) == 2
text = stub.prompts[1][0]["text"]
assert text.index("补充一") < text.index("补充二")
def test_no_queue_when_turn_finished(tmp_path, monkeypatch):
class FastStub(StubClient):
def session_prompt(self, sid, blocks, timeout=None):
with self.lock:
self.prompts.append([dict(b) for b in blocks])
return {"stopReason": "end_turn"} # no gate: turns finish at once
stub = FastStub()
mgr = _make_mgr(tmp_path, monkeypatch, stub)
res = mgr.prompt("wecom", "c1", "单独一条")
assert res.get("queued") is None
assert len(stub.prompts) == 1
assert "[用户补充]" not in stub.prompts[0][0]["text"]