diff --git a/core/openmate_core/agent.py b/core/openmate_core/agent.py index 9218a85..eda7761 100644 --- a/core/openmate_core/agent.py +++ b/core/openmate_core/agent.py @@ -21,10 +21,9 @@ Progress the Agent marks as such (progress=true) goes into one message that is edited in place instead of a new message each time, and is marked done once the answer went out; the answer itself is always a new message, so it notifies. -The hub is reached over a network that drops now and then. A request waits for it (`agent_hub_wait`), and a start that -failed on the way is tried again. A new conversation has no idempotency key, so a start that may have reached the hub -is tried again under a new request id (`.`): a conversation the lost start may have opened can then never -reply into the chat, so the user never gets two answers. +A conversation start retries under the same hub operation id. An uncertain receipt is reconciled against Persona's +transcript. If stable, fresh lookups establish absence, a fresh /agent request can re-open once with a new operation +and reply ref. A follow-up whose send may have reached Persona waits for its input in the transcript. """ from __future__ import annotations @@ -46,7 +45,7 @@ from . import cards, images, modelimages, placement, views from .backend import BackendError -from .hub import HubError +from .hub import HubError, hub_time from .textutil import clip, local_stamp, mention_spans, strip_leading_mentions from .wire import RPCError @@ -179,7 +178,6 @@ def _with_lead(text: str, lead: str) -> str: FORWARDED_NOTE = "已转给正在做这件事的 Agent" NOTE_RETRY = 60.0 # seconds between tries of a note that surely did not go out HELD_NOTE = ";它那台电脑上有个确认还没处理,处理后它才会看到这条" -FORWARD_CHECK = "请先在 Persona 里打开这个待办的 Agent 会话,看看有没有收到这条追问;没有的话再重新发送。" ASK_ASSISTANT = re.compile(r"问\s*(?:persona|助手)", re.IGNORECASE) # a follow-up the conversation is asked, not the task _CONTROL = re.compile("[\x00-\x08\x0b-\x1f\x7f-\x9f]") # what agents.control refuses in a message (newline, tab kept) ACTIVE = ("starting", "running") @@ -427,6 +425,16 @@ def start(self) -> None: def _resume_cut_off(self) -> None: """The starts a restart cut off (runs made before this start): those that can go on do, the others are told.""" + if self.enabled and self.hub.available: + now = time.time() + for run in self.store.runs_in_state(["starting", "running", "done", "failed", "stopped", "superseded"]): + doubt = run.get("start_doubt") or {} + if doubt.get("cleanup_until", 0) > now: + self._watch_old_start(run, doubt["cleanup_ref"], doubt["cleanup_until"]) + if run["state"] == "stopped" and not run.get("session_id") and self._start_uncertain(run): + until = (doubt["at"] or doubt["op_sent_at"]) + self.app.timing.agent_doubt_cleanup + if until > now: + self._watch_old_start(run, doubt["ref"], until) lost = [] for run in sorted(self.store.runs_in_state(["starting"]), key=lambda r: float(r.get("created") or 0)): if run["id"] not in self._cut_off if self._cut_off is not None else float(run.get("created") or 0) >= self._born: @@ -459,9 +467,13 @@ def _resume_how(self, run: dict) -> str: if not (self.enabled and self.hub.available): return "" age = time.time() - float(run.get("created") or 0) + if run.get("send_pending"): + return "send" + if run.get("waiting_start") or self._start_needs_lookup(run): + return "reconcile" + if self._start_uncertain(run): + return "op" if run.get("forward_pending") and age < self.app.timing.agent_keep: - # a follow-up on its way to the task's Agent: sent again under its client_msg_id (the hub sends each - # once), so it is never handed on twice and never half handed on return "forward" if run.get("forwarding") and age < self.app.timing.agent_fresh: # cut off while the task's Agent was looked up: nothing went out anywhere, so it starts again @@ -731,6 +743,9 @@ def on_message(self, row: dict, epoch: Optional[int] = None) -> None: return run = self._new_run(row, req, now) run["placement"] = row.get("placement") or "" # where it was asked: the replies go back there (_where) + earlier = self._topic_doubt(run) + if earlier: + run["waiting_start"] = earlier self.store.run_put(run) self._prune() threading.Thread(target=self._start_run, args=(run, row, epoch), name="openmate-agent-start", @@ -1324,10 +1339,27 @@ def _start_once_now(self, run: dict, row: dict, epoch: Optional[int] = None) -> if not self.hub.available: self._fail(run["id"], "没能处理 /agent:扩展拿不到 Persona hub 的地址或令牌") return + if run.get("send_pending"): + pending = run["send_pending"] + fields = pending["fields"] + if self._send_seen(run, fields, fields["client_msg_id"], time.monotonic() + self.app.timing.agent_hub_wait): + self._finish_start(run, dict(fields, reconciled_at=time.time()), pending["at"]) + else: + self._start_go(run, row, self.store.run_get(fields["continued"]), epoch) + return + if self._start_needs_lookup(run): + run = self._reconcile_start(run, epoch) + if run is None: + return + if not self._wait_topic_start(run): + return waited = self._wait_handed(run) # a follow-up before it being handed on first if waited and self._state(run["id"]) != "starting": return # stopped (or wiped) while it waited prev = None if run.get("start_op") else self._previous(run) # one with an operation: a new conversation + if prev is None and run.get("waiting_start"): + self._fail(run["id"], "这条追问没有发出,上一条 /agent 的会话还没有确认。") + return if waited and prev is not None and prev.get("session_id") and \ self._stopped_since(dict(run, session_id=prev["session_id"]), float(run["created"])): # its conversation was stopped after it was asked (it waited its turn meanwhile): stopped with it @@ -1354,7 +1386,12 @@ def _start_once_now(self, run: dict, row: dict, epoch: Optional[int] = None) -> self._start_go(run, row, prev, epoch) def _start_go(self, run: dict, row: dict, prev: Optional[dict], epoch: Optional[int] = None) -> None: - if prev is None and not run.get("start_op"): + pending = run.get("send_pending") or {} + fields = dict(pending["fields"], reconciled_at=time.time()) if pending else None + sending = fields is not None or prev is not None + if fields is not None: + run = dict(run, remote=fields["remote"]) + elif prev is None and not run.get("start_op"): # where a new conversation starts, chosen before its first message: on another computer it is told what # it cannot do there (_instructions); kept with the run at once (another request of its thread follows # it) and with the operation (_start_op), so every try asks the same @@ -1366,7 +1403,9 @@ def _start_go(self, run: dict, row: dict, prev: Optional[dict], epoch: Optional[ elif prev is not None: run = dict(run, remote=str(prev.get("remote") or "")) # the conversation's computer, for its instructions self._keep_remote(run["id"], run["remote"]) # before it is sent: a reply may come before the send's answer - if run.get("start_prompt"): + if pending.get("prompt"): + prompt = pending["prompt"] + elif run.get("start_prompt"): prompt = run["start_prompt"] # the very request sent before else: try: @@ -1376,12 +1415,10 @@ def _start_go(self, run: dict, row: dict, prev: Optional[dict], epoch: Optional[ prompt = self._instructions(run) + "\n" + (run["request_text"] or self.prefix) t = self.app.timing deadline = time.time() + t.agent_hub_wait - cmid = "openmate-" + run["id"] guest = self._guest(run) images = [] if guest or row is None else self._request_images(run, row) - baseline: Optional[int] = None op = "" - if prev is not None: + if prev is not None and not pending: # the runs that wait for the conversation's turn (a follow-up handed to the task's Agent waits for none): # prev's, and any other of the thread's waiting on it (one asked while a follow-up was looked up) waiting = [self._asked_last(prev)["id"]] + [ @@ -1389,146 +1426,423 @@ def _start_go(self, run: dict, row: dict, prev: Optional[dict], epoch: Optional[ if r["id"] != run["id"] and r["state"] == "running" and r.get("session_id") == prev.get("session_id")] if not all([self._supersede(w, run["id"], epoch) for w in dict.fromkeys(waiting)]): return # another account's sign-in took the store: prev may be that account's, never gone on in - else: - # a new conversation is started once: one operation id and the very same request on every try, and after - # a restart too (the hub answers a repeat with the first answer), never a second start under a new ref - # where it starts is chosen once too, kept with the operation: every try and a resume ask the same - run, op, prompt = self._start_op(run, prompt) + elif not sending: + # The hub answers retries with the receipt for this operation and request body. + run, op, prompt = self._start_op(run, prompt, epoch) + if not op: + return # (one kept before start_machine was: agent_machine, agent_launcher as they are now) machine = str(run.get("start_machine", self.machine) or "") launcher = str(run.get("start_launcher", self.launcher) or "") - tries = 1 - maybe = False - first_try = 0.0 # when a try first went to the hub: the conversation may have it from then on - refused = "" # the id the hub answered "nothing ran": the next ask goes under a new one (see the except) - while True: - if self._stop.is_set(): # shutting down: the next start tells the user to send it again - return - if self._state(run["id"]) in ("stopped", ""): # stopped, or wiped by another account's sign-in - return - if not self._hub_up(run["id"], deadline): - if not self._stop.is_set() and self._state(run["id"]) != "stopped": - self._fail(run["id"], "这台电脑和 Persona 之间的网络断了,等了 %s 还没恢复,这个 /agent 请求没有开始处理。" - "网络恢复后请重新发送。" % _span(t.agent_hub_wait)) - return - attempt = 0.0 # when this try's request went out (right before the call) - if refused and prev is None: - # Right before asking again, and only within the request's own wait: a new id, kept with the run. One a - # restart resumes later (overnight) keeps its old id, whose kept refusal ends it as before; and a stop - # during the wait leaves the old id stored, so nothing new is ever asked for a stale request. - created = float(run.get("created") or 0) - if created <= time.time() < created + t.agent_hub_wait: # (a clock that went back: never) + reopened = bool(run.get("start_doubt", {}).get("reopens")) + if reopened and not self._start_uncertain(run): + deadline = min(deadline, run["created"] + t.agent_fresh) + refused = "" + last_error = None + while not self._stop.is_set() and self._may_submit(run, epoch): + attempt = 0.0 + if time.time() < deadline and self._hub_up(run["id"], deadline) and time.time() < deadline: + retry_until = run["created"] + (t.agent_fresh if reopened else t.agent_hub_wait) + if refused and run["created"] <= time.time() < retry_until: nxt = self._new_start_op(run, refused, epoch) if nxt is None: - return # the other start of this run goes on, or closing, another account, stopped or started + return run, op = nxt - tries = 1 # the new id gets its own tries (the deadline stays) refused = "" - try: - if prev is not None: - mid, sid = prev["machine_id"], prev["session_id"] - if baseline is None: - baseline = self._latest_seq(mid, sid) - if not self._may_submit(run, epoch): + timeout = min(120.0, max(0.01, deadline - time.time())) + try: + if sending: + if fields is None: + mid, sid = prev["machine_id"], prev["session_id"] + fields = {"machine_id": mid, "session_id": sid, "last_seq": self._latest_seq(mid, sid), + "client_msg_id": "openmate-" + run["id"], "ours_seen": False, + "continued": prev["id"], "remote": run["remote"]} + attempt = time.time() + if attempt >= deadline: + continue + if not self._record_submit(run, epoch, send=fields, prompt=prompt, at=attempt): + return + res = self.hub.send_message(fields["machine_id"], fields["session_id"], prompt, + fields["client_msg_id"], images=images, + timeout=min(timeout, max(0.01, deadline - time.time()))) or {} + if res.get("delivered") in ("later", "unknown"): + self._watch_send(run, fields, attempt, res["delivered"]) + else: + self._finish_start(run, fields, attempt) return - attempt = time.time() - self.hub.send_message(mid, sid, prompt, cmid, images=images) # each client_msg_id once - fields = {"machine_id": mid, "session_id": sid, "last_seq": baseline, "client_msg_id": cmid, - "ours_seen": False, "continued": prev["id"], "remote": str(prev.get("remote") or "")} - elif guest: - if not self._guest_supported(): - log.warning("%s: the hub has no guest conversations; nothing started", run.get("kind")) + if guest and not self._guest_supported(): self._fail(run["id"], "hub 不支持访客会话") return - if not self._may_submit(run, epoch): - return attempt = time.time() - sess = self.hub.start_conversation(prompt, self.purpose, False, machine, launcher, - guest_tools=["%s_agent_reply" % self.app.cid], op_id=op) - fields = {"machine_id": sess.get("machine_id") or "", "session_id": sess["session_id"], "last_seq": 0, - "ours_seen": True, "guest": True, "remote": str(run.get("start_remote") or "")} - else: - if not self._may_submit(run, epoch): + if attempt >= deadline: + continue + if not self._record_submit(run, epoch, at=attempt): return - attempt = time.time() - sess = self.hub.start_conversation(prompt, self.purpose, True, machine, launcher, op_id=op, - images=images) - fields = {"machine_id": sess.get("machine_id") or "", "session_id": sess["session_id"], "last_seq": 0, - "ours_seen": True, "remote": str(run.get("start_remote") or "")} - break - except HubError as e: - log.warning("/agent could not start: HTTP %s %s", e.status, e.code) - if op and prev is None and e.delivered == "none" and e.retryable is True: - # The hub's own answer to this operation: nothing ran (the machine was away for a moment). The hub - # keeps that answer as the operation's receipt, so the same id asked again only gets it back until - # the deadline (2026-11-23: a node restarted for 9 s, the request then waited out its 5 minutes). - # The next try goes under a new id (taken right before it): the old one started nothing, so it - # cannot start a second conversation, and nothing asked under it may have run. - refused = op - maybe, first_try = False, 0.0 - elif not e.unsent and attempt: - first_try = first_try or attempt # it may have reached the hub - if op and e.code in ("unknown", "assistant_in_doubt", "op_id_reused"): - self._fail(run["id"], "Persona 不确定这个 /agent 有没有开始处理(网络中途断了)。请先在 Persona 里看看有没有" - "新开的会话;没有的话再重新发送。") + sess = self.hub.start_conversation( + prompt, self.purpose, not guest, machine, launcher, + guest_tools=["%s_agent_reply" % self.app.cid] if guest else None, op_id=op, + images=images, timeout=min(timeout, max(0.01, deadline - time.time()))) + self._finish_start(run, self._start_fields(run, sess, guest), run["start_doubt"]["op_sent_at"]) return - if op and e.code == "pending": # under way at the hub: ask again with the same operation - if time.time() >= deadline: - self._fail(run["id"], "Persona 迟迟没有确认这个 /agent 有没有开始处理。请先在 Persona 里看看有没有" - "新开的会话;没有的话再重新发送。") + except HubError as e: + last_error = e + log.info("/agent submit %s: HTTP %s %s", run["id"], e.status, e.code) + if sending and e.send_uncertain: + self._watch_send(run, fields, attempt, e.code or "unknown") + return + if op and (e.code in ("unknown", "assistant_in_doubt", "op_id_reused") or e.delivered == "unknown"): + break + if op and e.delivered == "none" and e.retryable is True: + # The hub may keep this refusal as its receipt. It establishes that this op did nothing. + refused = op + if sending or e.delivered == "none" or ((e.unsent or e.token_refused) and + run["start_doubt"]["op_sent_at"] == attempt): + self._clear_submit(run, sending) + if not (e.transient or e.token_refused or e.code == "pending"): + if op and run["start_doubt"]["op_sent_at"] and ( + e.status >= 500 or run["start_doubt"]["op_sent_at"] < attempt): + break + self._clear_submit(run, sending) + self._fail(run["id"], "没能启动 Agent:%s" % (e.message or "hub 拒绝了请求")) return self._stop.wait(min(t.agent_hub_probe, max(0.0, deadline - time.time()))) continue - if not e.transient: - self._fail(run["id"], "没能启动 Agent:%s" % (e.message or "hub 拒绝了请求")) - return - if prev is None and not e.unsent: - maybe = True # this try may have reached the hub - if time.time() >= deadline: - if maybe: - self._fail(run["id"], "没能确认 Agent 有没有启动:%s,等了 %s。%s" - % (_hub_words(e), _span(t.agent_hub_wait), CHECK)) - else: - self._fail(run["id"], "没能启动 Agent:%s。等了 %s 还是不行,请稍后重新发送。" - % (_hub_words(e), _span(t.agent_hub_wait))) - return - if prev is None and not e.unsent: - # it may have reached the hub: the same operation again gets its first answer, never a second start - if tries >= t.agent_start_tries: - self._fail(run["id"], "没能确认 Agent 有没有启动:这台电脑和 Persona 之间的网络不稳定,试了 %d 次。" - "请先在 Persona 里看看有没有新开的会话;没有的话再重新发送。" % tries) - return - tries += 1 - self._stop.wait(min(t.agent_hub_probe, max(0.0, deadline - time.time()))) + if op and self._start_uncertain(run): + break + if self._stop.is_set() or not self._may_submit(run, epoch): + return + if pending and last_error is None: + self._watch_send(run, fields, pending["at"], "resume without receipt") + elif last_error is not None: + self._fail(run["id"], "没能启动 Agent:%s。等了 %s 还是不行,请稍后重新发送。" + % (_hub_words(last_error), _span(t.agent_hub_wait))) + elif reopened: + self._fail(run["id"], "已核对 Persona,没找到这个请求开的会话,已过重新启动的时间。") + else: + self._fail(run["id"], "这台电脑和 Persona 之间的网络断了,等了 %s 还没恢复,这个 /agent 请求没有开始处理。" + "网络恢复后请重新发送。" % _span(t.agent_hub_wait)) + return + if not self._stop.is_set() and op and self._start_uncertain(run): + next_run = self._reconcile_start(run, epoch) + if next_run is not None: + self._start_go(next_run, row, None, epoch) + + def _record_submit(self, run: dict, epoch: Optional[int], *, at: float, send: Optional[dict] = None, + prompt: str = "") -> bool: + """Keep what may reach Persona before issuing the write, including a restart during the HTTP call.""" + with self._lock(run["id"]), self.app.owned(epoch) as ok: + cur = self.store.run_get(run["id"]) if ok else None + if cur is None or cur["state"] != "starting": + return False + if send is None: + doubt = dict(cur.get("start_doubt") or {}, ref=self._ref(cur)) + doubt.setdefault("reopens", 0) + doubt.setdefault("at", 0.0) + doubt["first_sent"] = doubt.get("first_sent") or at + doubt["op_sent_at"] = doubt.get("op_sent_at") or at + cur["start_doubt"] = run["start_doubt"] = doubt + else: + cur["send_pending"] = {"fields": send, "at": at, "prompt": prompt} + return self.store.run_put(cur) + + def _clear_submit(self, run: dict, sending: bool) -> None: + with self._lock(run["id"]): + cur = self.store.run_get(run["id"]) + if cur is None: + return + if sending: + cur.pop("send_pending", None) + else: + doubt = dict(cur["start_doubt"], op_sent_at=0.0) + if not doubt.get("reopens"): + doubt["first_sent"] = 0.0 + cur["start_doubt"] = run["start_doubt"] = doubt + self.store.run_put(cur) + + @staticmethod + def _start_fields(run: dict, sess: dict, guest: bool = False) -> dict: + fields = {"machine_id": sess.get("machine_id") or "", "session_id": sess["session_id"], "last_seq": 0, + "ours_seen": True, "remote": str(run.get("start_remote") or "")} + if guest: + fields["guest"] = True + return fields + + def _finish_start(self, run: dict, fields: dict, submitted: float) -> None: stopped = False with self._lock(run["id"]): cur = self.store.run_get(run["id"]) if cur is not None: - cur.update(fields) - # when its conversation may first have got it (a try that surely reached nothing does not count) - cur["submitted"] = first_try or attempt or time.time() - if cur["state"] == "stopped": - stopped = True - else: + cur.pop("send_pending", None) + cur.update(fields, submitted=submitted) + stopped = cur["state"] != "starting" + if not stopped: cur["state"] = "running" if cur is None or not self.store.run_put(cur): - stopped = True # gone meanwhile (another account's sign-in wiped it): nothing here can answer it - log.info("an /agent request gone while it started (the account signed out): its conversation is stopped") - if stopped: # a stop arrived while the start was in flight + stopped = True # another account's sign-in wiped it + if stopped: if cur is not None and cur.get("stop_reason") == USER_REPLY_STOP: self._interrupt_auto(cur) return if cur is not None and cur.get("stop_reason") == RECALL_STOP and self._can_have_draft(cur): self._interrupt_auto(cur) - try: - self.hub.stop_conversation(fields["session_id"]) - except HubError: - pass + if not self._stop_found_start(run["id"], fields) and run.get("start_doubt"): + self._watch_old_start(run, self._ref(run)) return - log.info("/agent request started (%s%s)", "continued" if prev is not None else "new conversation", - ", try %d" % tries if tries > 1 else "") + log.info("/agent request started %s (%s)", run["id"], "continued" if fields.get("continued") else "new conversation") self._wake.set() + def _watch_send(self, run: dict, fields: dict, submitted: float, outcome: str) -> None: + log.info("/agent send reconciliation %s: %s", run["id"], outcome) + self._finish_start(run, dict(fields, send_wait_until=time.time() + self.app.timing.agent_send_wait), submitted) + + def _send_seen(self, run: dict, target: dict, cmid: str, deadline: float) -> bool: + """Check for a pending message before resending it under the same delivery ID.""" + try: + items, _ = self._transcript(target["machine_id"], target["session_id"], target.get("last_seq", 0), deadline) + except HubError as e: + log.info("/agent send resume %s: lookup HTTP %s", run["id"], e.status) + return False + return any(_matches_send(it, cmid, self._ref(run)) for it in items) + + def _start_needs_lookup(self, run: dict) -> bool: + doubt = run.get("start_doubt") or {} + # A change of auto-reply mode also forbids replaying the stored start body. + return bool(doubt.get("at") or (doubt.get("op_sent_at") and run.get("kind") in QUIET_KINDS + and bool(run.get("guest", True)) != self._guest(run))) + + @staticmethod + def _start_uncertain(run: dict) -> bool: + doubt = run.get("start_doubt") or {} + return bool(doubt.get("at") or doubt.get("op_sent_at")) + + def _topic_doubt(self, run: dict) -> str: + if run.get("kind") in QUIET_KINDS or self.app.platform.name != "飞书" or not run.get("root_id"): + return "" + for earlier in self.store.runs_in_thread(run["chat_id"], run["thread_key"]): + if earlier["created"] < run["created"] and earlier["state"] == "starting": + doubt = earlier.get("start_doubt") or {} + if doubt.get("at") or doubt.get("reopens"): + return earlier["id"] + return "" + + def _wait_topic_start(self, run: dict) -> bool: + earlier = run.get("waiting_start") or self._topic_doubt(run) + if not earlier: + return True + run["waiting_start"] = earlier + t = self.app.timing + deadline = time.monotonic() + 3 * t.agent_hub_wait + log.info("/agent start reconciliation %s: waiting for %s", run["id"], earlier) + while not self._stop.is_set() and self._state(run["id"]) == "starting": + current = self.store.run_get(earlier) + if current is None or time.monotonic() >= deadline or current["state"] in ("failed", "stopped"): + self._fail(run["id"], "这条追问没有发出,上一条 /agent 的会话还没有确认。") + return False + if current.get("session_id"): + return True + self._stop.wait(t.agent_hub_probe) + return False + + @staticmethod + def _lookup_timeout(deadline: float) -> float: + left = deadline - time.monotonic() + if left <= 0: + raise HubError(0, "核对已到期") + return min(10.0, left) + + def _find_start(self, run: dict, ref: str, deadline: float) -> tuple: + """Match only the first user text. An unreadable or incomplete view cannot establish absence.""" + created = float(run["created"]) + cutoff = created - self.app.timing.agent_doubt_lookback + candidates = {} # key by machine and session, keep reporter candidates first + complete = True + try: + for row in self.hub.reporters(self._lookup_timeout(deadline)): + if hub_time(row.get("at")) >= created: + candidates[(row.get("machine_id"), row.get("session_id"))] = None + except HubError: + complete = False + try: + doc = self.hub.start_candidates(self._lookup_timeout(deadline)) + rows = doc["sessions"] + if doc.get("has_more") and (not rows or hub_time(rows[-1].get("updated_at")) >= cutoff): + complete = False # the first page does not cover the time window + for row in rows: + if row.get("assistant") and hub_time(row.get("updated_at")) >= cutoff: + candidates[(row.get("machine_id"), row.get("session_id"))] = None + except HubError: + complete = False + + pending = False + for (mid, sid) in candidates: + if not mid or not sid: + complete = False + continue + after = 0 + try: + while not self._stop.is_set(): + res = self.hub.items(mid, sid, after_seq=after, timeout=self._lookup_timeout(deadline), + lazy_images=True) + if (not isinstance(res, dict) or not isinstance(res.get("items"), list) + or res.get("partial") or res.get("fallback")): + complete = False + break + page = res["items"] + first = next((it for it in page if it.get("role") == "user" and it.get("kind") == "text"), None) + if first is not None: + if _has_ref(first, ref): + return {"machine_id": mid, "session_id": sid}, "found" + break + if not page or not res.get("more_after"): + pending = True + break + next_seq = max(int(it.get("seq") or 0) for it in page) + if next_seq <= after: + complete = False + break + after = next_seq + except HubError: + complete = False + return None, "incomplete" if not complete else "first item pending" if pending else "clear" + + def _reconcile_start(self, run: dict, epoch: Optional[int]) -> Optional[dict]: + t = self.app.timing + with self._lock(run["id"]): + cur = self.store.run_get(run["id"]) + doubt = dict((cur or run)["start_doubt"]) + doubt["at"] = doubt.get("at") or time.time() + if cur is not None: + cur["start_doubt"] = doubt + self.store.run_put(cur) + ref = doubt["ref"] + log.info("/agent start reconciliation %s: begin (%s)", run["id"], ref) + # An overdue resume gets a bounded lookup window. Freshness for re-opening is still based on creation. + left = doubt["at"] + t.agent_hub_wait - time.time() + deadline = time.monotonic() + (left if left > 0 else t.agent_hub_wait) + stable_since = previous_probe = first_clear = next_lookup = None + absent = False + quiet = run.get("kind") in QUIET_KINDS + while not self._stop.is_set() and time.monotonic() < deadline: + try: + self.hub.assistant_probe(self._lookup_timeout(deadline)) + except HubError as e: + log.info("/agent start reconciliation %s: probe HTTP %s", run["id"], e.status) + stable_since = previous_probe = first_clear = next_lookup = None + absent = False + else: + log.info("/agent start reconciliation %s: probe OK", run["id"]) + now = time.monotonic() + if previous_probe is None or now - previous_probe > 2 * t.agent_hub_probe: + stable_since, first_clear, absent = now, None, False + previous_probe = now + if next_lookup is None or now >= next_lookup: + found, outcome = self._find_start(run, ref, deadline) + checked = time.monotonic() + next_lookup = checked + t.agent_doubt_lookup + log.info("/agent start reconciliation %s: lookup %s", run["id"], outcome) + if found: + if quiet: + if not self._stop_found_start(run["id"], found): + self._watch_old_start(run, ref) + self._fail(run["id"], "启动回执不确定,已找到对应会话。", silent=True) + else: + fields = self._start_fields(run, found) + fields["reconciled_at"] = time.time() + self._finish_start(run, fields, doubt["op_sent_at"]) + return None + if outcome != "clear" or checked - now > t.agent_hub_probe: + first_clear, absent = None, False + else: + first_clear = now if first_clear is None else first_clear + absent = (time.time() - doubt["at"] >= t.agent_doubt_age + and now - stable_since >= t.agent_doubt_stable + and now - first_clear >= t.agent_doubt_lookup) + if absent and not quiet and not doubt["reopens"]: + reopened = self._reopen_start(run, doubt, epoch) + if reopened is not None: + log.info("/agent start reconciliation %s: re-open", run["id"]) + self._watch_old_start(reopened, ref, reopened["start_doubt"]["cleanup_until"]) + return reopened + self._stop.wait(max(0.0, min(t.agent_hub_probe, deadline - time.monotonic()))) + if not self._stop.is_set(): + log.info("/agent start reconciliation %s: deadline (%s)", run["id"], "clear" if absent else "uncertain") + current = self.store.run_get(run["id"]) + if current and current.get("replies"): # the reply tool already proved this conversation ran + with self._lock(run["id"]): + current = self.store.run_get(run["id"]) + if current and current["state"] == "starting": + current["state"] = "done" + self.store.run_put(current) + return None + if current is None or current["state"] == "stopped": + until = ((current or {}).get("stopped_at") or doubt["at"]) + t.agent_doubt_cleanup + if until > time.time(): + self._watch_old_start(run, ref, until) + return None + absent = absent and not current.get("progress_id") + self._fail(run["id"], "网络中断,已核对 Persona,没找到这个请求开的会话。" if absent else + "网络中断,还没法确认 Persona 有没有为这条请求开会话。", silent=quiet) + return None + + def _reopen_start(self, run: dict, doubt: dict, epoch: Optional[int]) -> Optional[dict]: + with self._lock("progress:" + run["id"]), self._lock(run["id"]), self.app.owned(epoch) as ok: + cur = self.store.run_get(run["id"]) if ok else None + now = time.time() + if (cur is None or cur["state"] != "starting" or cur.get("replies") or cur.get("reply_inflight") + or cur.get("progress_id") + or not cur["created"] <= now < cur["created"] + self.app.timing.agent_fresh): + return None + old, new = doubt["ref"], run["id"] + ".2" + prompt = cur["start_prompt"].replace('request 填 "%s"' % old, 'request 填 "%s"' % new, 1) + prompt = prompt.replace("id 是 %s。" % old, "id 是 %s。" % new, 1) + cur.update(ref=new, start_op=str(uuid.uuid4()), start_prompt=prompt) + cur["start_doubt"] = dict(first_sent=doubt["first_sent"], op_sent_at=0.0, at=0.0, reopens=1, ref=new, cleanup_ref=old, + cleanup_until=now + self.app.timing.agent_doubt_cleanup) + return cur if self.store.run_put(cur) else None + + def _stop_found_start(self, run_id: str, sess: dict) -> bool: + sid = sess["session_id"] + try: + try: + self.hub.stop_conversation(sid) + except HubError as e: + if e.status != 404 or not sess.get("machine_id"): + raise + # The stop route only knows registered reporters. Guests and starts cut off before registration + # can be interrupted by agents.control once the hub lists them. + self.hub.interrupt(sess["machine_id"], sid) + except HubError as e: + log.info("/agent start reconciliation %s: stop HTTP %s", run_id, e.status) + return False + log.info("/agent start reconciliation %s: stopped matched conversation", run_id) + return True + + def _watch_old_start(self, run: dict, ref: str, until: Optional[float] = None) -> None: + t = self.app.timing + until = until if until is not None else time.time() + t.agent_doubt_cleanup + + def watch(): + deadline = time.monotonic() + max(0.0, until - time.time()) + while not self._stop.is_set() and time.monotonic() < deadline: + try: + self.hub.assistant_probe(self._lookup_timeout(deadline)) + found, outcome = self._find_start(run, ref, deadline) + log.info("/agent start reconciliation %s: cleanup %s (%s)", run["id"], outcome, ref) + if found and self._stop_found_start(run["id"], found): + with self._lock(run["id"]), self.app.owned(None) as ok: + cur = self.store.run_get(run["id"]) if ok else None + doubt = (cur or {}).get("start_doubt") or {} + if doubt.get("cleanup_ref") == ref: + doubt.pop("cleanup_ref") + doubt.pop("cleanup_until", None) + self.store.run_put(cur) + return + except HubError as e: + log.info("/agent start reconciliation %s: cleanup probe HTTP %s", run["id"], e.status) + self._stop.wait(min(t.agent_doubt_lookup, max(0.0, deadline - time.monotonic()))) + + threading.Thread(target=watch, name="openmate-agent-start-cleanup", daemon=True).start() + def _images_dir(self, run_id: str) -> str: return os.path.join(str(getattr(self.app, "data_dir", "") or ""), "agent-images", run_id) @@ -1666,13 +1980,13 @@ def _hub_up(self, run_id: str, deadline: float) -> bool: return False self._stop.wait(min(t.agent_hub_probe, left)) - def _start_op(self, run: dict, prompt: str): + def _start_op(self, run: dict, prompt: str, epoch: Optional[int]): """(run, op id, prompt) of a new conversation's start: made once and kept with the run, so every try (and a resume after a restart) sends the same operation and the same body: with the prompt, the computer _start_go placed it on (start_machine, start_remote) and the launcher.""" - with self._lock(run["id"]): - cur = self.store.run_get(run["id"]) - if cur is None: # gone (another account's sign-in wiped it): the start loop ends at its first check + with self._lock(run["id"]), self.app.owned(epoch) as ok: + cur = self.store.run_get(run["id"]) if ok else None + if cur is None or cur["state"] != "starting": return run, "", prompt if not cur.get("start_op"): cur["start_op"] = str(uuid.uuid4()) @@ -1832,6 +2146,7 @@ def _forward_text(self, run: dict, row: Optional[dict], target: dict) -> str: quoted = store.message(chat_id, row["parent_id"]) if row.get("parent_id") else None if quoted is not None: lines.append("- 引用的消息(id=%s):%s" % (quoted["id"], clip(views.log_line(quoted, app.tz, app.me_name()), 2000))) + lines.append('- 这条追问的编号是 "%s"。' % self._ref(run)) lines.append("- 做完后照常汇报,Persona 会把结果发回这个话题;不要自己往%s里发消息。" % p) text = _block("context", "%s里的追问" % p, "\n".join(lines)) + "\n" + (run["request_text"] or self.prefix) return _CONTROL.sub("", text) @@ -1857,12 +2172,17 @@ def _forward(self, run: dict, row: Optional[dict], prev: dict, epoch: Optional[i target = self._forward_target(prev) if target is not None and self._forward_send(run["id"], row, target, epoch): return True - with self._lock(run["id"]): # the conversation is asked: unless a /stop came for it meanwhile - cur = self.store.run_get(run["id"]) + return self._clear_forward(run["id"]) + + def _clear_forward(self, run_id: str) -> bool: + """Clear the routing to the task's Agent. True if the run cannot go on in its conversation.""" + with self._lock(run_id): # the conversation is asked: unless a /stop came for it meanwhile + cur = self.store.run_get(run_id) if cur is None or cur["state"] != "starting": return True cur.pop("forwarding", None) cur.pop("forward_pending", None) + cur.pop("forward_wait_until", None) stopped = self._stopped_since(cur, float(cur["created"])) for k in ("machine_id", "session_id", "continued", "asked", "remote"): # its own once it is sent, as before cur.pop(k, None) @@ -1870,30 +2190,32 @@ def _forward(self, run: dict, row: Optional[dict], prev: dict, epoch: Optional[i cur["state"], cur["stopped_at"] = "stopped", time.time() self.store.run_put(cur) if stopped: - self._end_reaction(run["id"], "stopped") + self._end_reaction(run_id, "stopped") return True return False def _resume_forward(self, run: dict) -> None: - row = self.store.message(run["chat_id"], run["request_id"]) + row = self.store.message(run["chat_id"], run["request_id"]) or {"chat_id": run["chat_id"], "id": run["request_id"]} self._handing_add(run) try: - if not self._forward_send(run["id"], row, run["forward_pending"], None, resumed=True): - self._fail(run["id"], "没能确认这条追问有没有转给正在做这件事的 Agent。" + FORWARD_CHECK) + if not self._forward_send(run["id"], row, run["forward_pending"], resumed=True): + if self._clear_forward(run["id"]): + return + prev = self.store.run_get(run.get("continued") or "") + if prev is None: + self._fail(run["id"], "没能把这条追问转给 Agent,原 Persona 会话也找不到了。") + return + self._start_go(run, row, prev) except Exception: log.exception("/agent follow-up could not be handed on after a restart") - self._fail(run["id"], "没能确认这条追问有没有转给正在做这件事的 Agent:扩展内部错误。" + FORWARD_CHECK) + self._fail(run["id"], "没法确认追问有没有送到 Agent 会话,消息可能已经送达。") finally: self._handing_done(run["id"]) self._drop_request_images(run["id"]) def _forward_send(self, run_id: str, row: Optional[dict], target: dict, epoch: Optional[int] = None, resumed: bool = False) -> bool: - """Send the follow-up to the task's Agent (agents.control) under one client_msg_id, which the hub sends once: - a try whose answer was lost, or one cut off by a restart (resumed), is sent again as it is, never twice. The - target is kept with the run first, so a restart sends it to the same Agent, and looked at again right before - every try (a session moved to another to-do never gets it). False (the conversation is asked) only when - nothing can have gone out: the hub surely refused it, or the Agent moved before any try.""" + """Hand it to the task's Agent. Only a refusal that establishes no delivery allows a fallback.""" t = self.app.timing deadline = time.time() + t.agent_hub_wait run = self.store.run_get(run_id) @@ -1901,121 +2223,92 @@ def _forward_send(self, run_id: str, row: Optional[dict], target: dict, epoch: O return True conv = run.get("session_id") or "" cmid = "openmate-" + run_id - text = self._forward_text(run, row, target) - maybe = resumed # sent before the restart, perhaps - tries = 0 - held = False # in, but held at the Agent's computer till something there is answered - - def unsure(why: str) -> None: - if maybe: - self._fail(run_id, "没能确认这条追问有没有转给正在做这件事的 Agent:%s。%s" % (why, FORWARD_CHECK)) - else: - self._fail(run_id, "没能把这条追问转给正在做这件事的 Agent:%s。请稍后重新发送。" % why) - - def gone() -> bool: - """The run is no more the user's to go on with (stopped, or wiped by another account's sign-in): what may - have reached the Agent is stopped with the conversation, as a stop after it would (unless the user asked - the conversation again since: that stop is not undone by an older send).""" - if maybe and conv and not self._asked_since(run): - self._stop_conversation(conv) + held = False + if resumed and (self._stopped_since(run, run["created"]) or self._reporting(conv) == "stopped"): + self._fail(run_id, "没法确认追问有没有送到 Agent 会话,消息可能已经送达。") return True - - first = self.store.run_get(run_id) or {} - pictures = self._request_images(first, row or {}) if first else [] # fetched before its checks, kept for a resume - while True: - state = self._state(run_id) - if self._stop.is_set() or state in ("stopped", "") or not self.app.owns(epoch): - return True if self._stop.is_set() else gone() - if not self._hub_up(run_id, deadline): - if self._stop.is_set(): + check_delivery = resumed and not self._send_seen(run, target, cmid, time.monotonic() + t.agent_hub_wait) + if not resumed or check_delivery: + if resumed: + deadline = time.time() + t.agent_hub_wait + pictures = self._request_images(run, row or {}) + text = self._forward_text(run, row, target) + retry = resumed + while self._may_submit(run, epoch) and not self._stop.is_set(): + if time.time() >= deadline or not self._hub_up(run_id, deadline) or time.time() >= deadline: + if check_delivery: + break + self._fail(run_id, "没能把这条追问转给 Agent:Persona 网络还没恢复,请稍后重新发送。") return True - if self._state(run_id) in ("stopped", ""): - return gone() - unsure("这台电脑和 Persona 之间的网络断了,等了 %s 还没恢复" % _span(t.agent_hub_wait)) - return True - # looked at right before every try (the wait may have been long); after a restart, all of it again - reporting = "reporting" if tries == 0 else self._reporting(conv) - if reporting is None: # not known now (the network): asked again, under the same deadline - if time.time() >= deadline: - unsure("这台电脑和 Persona 之间的网络不稳,等了 %s" % _span(t.agent_hub_wait)) + if retry: + reporting = self._reporting(conv) + if reporting is None: + self._stop.wait(min(t.agent_hub_probe, max(0.0, deadline - time.time()))) + continue + if reporting == "stopped": + self._mark_forward_stopped(run_id) + return True + if (retry and reporting != "reporting") or not self._still_on(target): + if check_delivery: + break # the task changed while this message may have been in flight + return False + if self._stopped_since(run, run["created"]): + self._mark_forward_stopped(run_id) return True - self._stop.wait(min(t.agent_hub_probe, max(0.0, deadline - time.time()))) - continue - if reporting not in ("reporting", "stopped"): - # no more a reporting conversation (its task notices go elsewhere) - if not maybe: - return False # nothing went out: the conversation is asked - unsure("这个对话已经不再接收任务的汇报") - return True - if reporting == "stopped": - # stopped in the app since it was asked: stopped with it (asking the conversation would wake it) - with self._lock(run_id): - cur = self.store.run_get(run_id) - if cur is not None and cur["state"] == "starting": - cur["state"], cur["stopped_at"] = "stopped", time.time() - cur.pop("forward_pending", None) - self.store.run_put(cur) - self._end_reaction(run_id, "stopped") - return True - if resumed and tries == 0: - fresh = self._forward_target(run) == target - else: - fresh = self._still_on(target) - if not fresh: - if not maybe: - return False # moved before anything went out: the conversation is asked - unsure("这件事的 Agent 已经换了任务、不在了,或者对话已经停了") - return True - if not self._may_submit(run, epoch): - return gone() - if self._stopped_since(run, float(run["created"])): - # a /stop in the thread since it was asked: it stopped the conversation and its tasks - with self._lock(run_id): - cur = self.store.run_get(run_id) - if cur is not None and cur["state"] == "starting": - cur["state"], cur["stopped_at"] = "stopped", time.time() - cur.pop("forward_pending", None) - self.store.run_put(cur) - self._end_reaction(run_id, "stopped") - return gone() - if tries == 0 and not resumed: - with self._lock(run_id): # on its way from now: a restart sends it again to this very Agent - cur = self.store.run_get(run_id) + with self._lock(run_id), self.app.owned(epoch) as ok: + cur = self.store.run_get(run_id) if ok else None if cur is None or cur["state"] != "starting": - return gone() + return True cur["forward_pending"] = dict(target) if not self.store.run_put(cur): - return gone() - tries += 1 - try: - res = self.hub.send_message(target["machine_id"], target["session_id"], text, cmid, - images=pictures) or {} - held = bool(isinstance(res, dict) and res.get("waits_on_computer")) - break - except HubError as e: - log.warning("/agent follow-up could not reach the task's Agent: HTTP %s %s", e.status, e.code) - if e.code == "peer_held": - held = True - break # in the Agent's session, held for approval at its computer: handed on - refused = (not e.unsent and not e.unreachable and 400 <= e.status < 500 # an answer read whole - and e.status not in (408, 429) and e.delivered in ("", "none")) - if refused and not maybe: - return False # nothing went out: the conversation is asked - if refused: - unsure(e.message or "hub 拒绝了") - return True - if not e.unsent: - maybe = True # it may have gone out: only the same client_msg_id again from now on - if time.time() >= deadline: - unsure("%s,等了 %s" % (_hub_words(e), _span(t.agent_hub_wait))) - return True - self._stop.wait(min(t.agent_hub_probe, max(0.0, deadline - time.time()))) + return True + try: + res = self.hub.send_message(target["machine_id"], target["session_id"], text, cmid, images=pictures, + timeout=min(120.0, max(0.01, deadline - time.time()))) or {} + held = bool(res.get("waits_on_computer")) + check_delivery = not held and res.get("delivered") in ("later", "unknown") + break + except HubError as e: + log.info("/agent forward %s: HTTP %s %s", run_id, e.status, e.code) + if e.code == "peer_held": + held = True + check_delivery = False + break + if e.send_uncertain: + check_delivery = True + break + with self._lock(run_id): + cur = self.store.run_get(run_id) + if cur is not None: + cur.pop("forward_pending", None) + self.store.run_put(cur) + if e.status == 401 and not e.token_refused or ( + 400 <= e.status < 500 and not e.token_refused and not e.transient and e.status != 429): + return False + if not (e.transient or e.token_refused or e.status == 429): + self._fail(run_id, "没能把这条追问转给 Agent:%s。" % _hub_words(e)) + return True + retry = True + self._stop.wait(min(t.agent_hub_probe, max(0.0, deadline - time.time()))) + else: + return True + if check_delivery: + with self._lock(run_id), self.app.owned(epoch) as ok: + cur = self.store.run_get(run_id) if ok else None + if cur is None or cur["state"] != "starting": + until = time.time() # confirm handles cleanup if it was stopped or wiped + else: + until = cur.setdefault("forward_wait_until", time.time() + t.agent_send_wait) + self.store.run_put(cur) + if not self._confirm_forward(run, target, cmid, epoch, until): + return True with self._lock(run_id): cur = self.store.run_get(run_id) stopped = cur is None or cur["state"] == "stopped" or self._stopped_since(cur, float(cur["created"])) if cur is not None: cur.pop("forward_pending", None) cur.pop("forwarding", None) + cur.pop("forward_wait_until", None) cur.update({"forward": dict(target), "ours_seen": True}) if held: cur["forward_held"] = True # it reads it once what holds it is answered at its computer @@ -2038,6 +2331,40 @@ def gone() -> bool: self._forward_noted(run_id) return True + def _mark_forward_stopped(self, run_id: str) -> None: + with self._lock(run_id): + cur = self.store.run_get(run_id) + if cur is not None and cur["state"] == "starting": + cur.update(state="stopped", stopped_at=time.time()) + cur.pop("forward_pending", None) + self.store.run_put(cur) + self._end_reaction(run_id, "stopped") + + def _confirm_forward(self, run: dict, target: dict, cmid: str, epoch: Optional[int], until: float) -> bool: + t = self.app.timing + deadline = time.monotonic() + max(0.1, until - time.time()) + after = 0 + log.info("/agent send reconciliation %s: checking forwarded message", run["id"]) + while not self._stop.is_set() and time.monotonic() < deadline: + if not self._may_submit(run, epoch): + if run.get("session_id") and not self._asked_since(run): + self._stop_conversation(run["session_id"]) + return False + try: + items, after = self._transcript(target["machine_id"], target["session_id"], after, deadline) + except HubError as e: + log.info("/agent send reconciliation %s: lookup HTTP %s", run["id"], e.status) + else: + if any(_matches_send(it, cmid, self._ref(run)) for it in items): + log.info("/agent send reconciliation %s: found", run["id"]) + return True + log.info("/agent send reconciliation %s: not seen", run["id"]) + self._stop.wait(min(t.agent_hub_probe, max(0.0, deadline - time.monotonic()))) + if not self._stop.is_set(): + log.info("/agent send reconciliation %s: deadline", run["id"]) + self._fail(run["id"], "在 Agent 会话里还没看到这条追问,消息可能稍后送达。") + return False + def _asked_since(self, run: dict) -> bool: """The user asked the conversation again after run and after its last stop (a request of the thread not handed to a task's Agent, and not stopped itself).""" @@ -2420,21 +2747,44 @@ def _loop(self) -> None: log.exception("/agent poll failed") self._prune() - def _poll(self, run: dict) -> None: - if time.time() - run["created"] > self.app.timing.agent_timeout: - self._timeout(run["id"]) - return - mid, sid = run["machine_id"], run["session_id"] - after = int(run.get("last_seq") or 0) + def _transcript(self, mid: str, sid: str, after: int, deadline: Optional[float] = None) -> tuple: items: List[dict] = [] for _ in range(20): - res = self.hub.items(mid, sid, after_seq=after) or {} + timeout = self._lookup_timeout(deadline) if deadline is not None else None + try: + res = self.hub.items(mid, sid, after_seq=after, timeout=timeout) or {} + except HubError: + if not items: + raise + break # consume the pages already read before retrying the remaining items page = res.get("items") or [] items += page - if page: - after = max(after, max(int(it.get("seq") or 0) for it in page)) - if not page or not res.get("more_after"): + if not page: break + next_seq = max(int(it.get("seq") or 0) for it in page) + if next_seq <= after: + break + after = next_seq + if not res.get("more_after"): + break + if deadline is not None and time.monotonic() >= deadline: + break # preserve the pages already read + return items, after + + def _poll(self, run: dict) -> None: + send_until = run.get("send_wait_until") or 0 + if not send_until and time.time() - (run.get("reconciled_at") or run["created"]) > self.app.timing.agent_timeout: + self._timeout(run["id"]) + return + mid, sid = run["machine_id"], run["session_id"] + try: + deadline = time.monotonic() + max(0.1, send_until - time.time()) if send_until else None + items, after = self._transcript(mid, sid, int(run.get("last_seq") or 0), deadline) + except HubError: + if send_until and time.time() >= send_until: + self._send_unseen(run) + return + raise ended = interrupted = False interrupted_at = 0.0 if items: @@ -2447,9 +2797,10 @@ def _poll(self, run: dict) -> None: answered = bool(cur.get("answered")) for it in items: if not ours: - if (cur.get("client_msg_id") and it.get("client_msg_id") == cur["client_msg_id"]) or ( - it.get("role") == "user" and cur["id"] in (it.get("text") or "")): + if _matches_send(it, cur.get("client_msg_id") or "", self._ref(cur)): ours = True + if cur.pop("send_wait_until", None): + log.info("/agent send reconciliation %s: found", cur["id"]) continue kind, role = it.get("kind") or "", it.get("role") or "" if role == "assistant": @@ -2468,6 +2819,9 @@ def _poll(self, run: dict) -> None: cur["last_seq"] = after self.store.run_put(cur) run = cur + if send_until and not run.get("ours_seen") and time.time() >= send_until: + self._send_unseen(run) + return if not ended and not interrupted and self._settled(run): ended = True if interrupted: @@ -2483,6 +2837,13 @@ def _poll(self, run: dict) -> None: elif ended: self._turn_ended(run["id"]) + def _send_unseen(self, run: dict) -> None: + log.info("/agent send reconciliation %s: deadline", run["id"]) + if run.get("replies"): + self._turn_ended(run["id"]) + return + self._fail(run["id"], "在 Persona 会话里还没看到这条追问,消息可能稍后送达。", silent=run.get("kind") in QUIET_KINDS) + def _settled(self, run: dict) -> bool: """The turn ended without its turn_duration item: the session answered our request, has been quiet for agent_settle (so the session list's status, which lags the transcript, has caught up) and is done or idle.""" @@ -2694,7 +3055,7 @@ def _timeout(self, run_id: str) -> None: cur["notice_id"] = mid # a /stop quoting it finds the run (in the main stream there is no thread) self.store.run_put(cur) - def _fail(self, run_id: str, message: str) -> None: + def _fail(self, run_id: str, message: str, *, silent: bool = False) -> None: with self._lock(run_id): cur = self.store.run_get(run_id) if cur is None or cur["state"] not in ACTIVE: @@ -2703,8 +3064,9 @@ def _fail(self, run_id: str, message: str) -> None: cur["error"] = message if not self.store.run_put(cur): return # wiped by another account's sign-in meanwhile: nothing is said for it - self._end_reaction(run_id, "failed") - self._post_once(cur, "agent:%s:failed" % run_id, message, **self._where(cur)) + self._end_reaction(run_id, "stopped" if silent else "failed") + if not silent: + self._post_once(cur, "agent:%s:failed" % run_id, message, **self._where(cur)) # ---------------------------------------------------------------- sending as the user @@ -3067,8 +3429,7 @@ def _reply_tool(self, request: str, text: str, progress: bool = False, image: st raise RPCError("没有这个 /agent 请求:request 不对,或者已经过期") if request != self._ref(run): raise RPCError("这个 /agent 请求已经交给另一个会话处理了,这里不用再回复") - if run["state"] in ("stopped", "failed"): - raise RPCError("这个 /agent 请求已经停止了,不再回复") + self._check_reply_state(run) named = run["id"] # a reply's key is the request it names: asked again, it is the same reply wherever it went if run.get("kind") not in QUIET_KINDS and run.get("session_id") and self._stopped_since_asked(run): raise RPCError("这个 /agent 请求已经停止了,不再回复") # its conversation was stopped since it was asked @@ -3112,7 +3473,7 @@ def _reply_tool(self, request: str, text: str, progress: bool = False, image: st if progress and run.get("kind") != "doc": # a document's comment has no progress message if not self._can_edit(): # every update would be one more message in the chat, as the user return "%s不能编辑消息,进度不发;做完后不带 progress 回复一次最终结果" % self.app.platform.name - return self._progress(run, text) + return self._progress(run, text, request if named == run["id"] else "") if run.get("kind") == "doc": key = "agent:%s:doc" % run["id"] # one comment per task, whatever its words (a retry may reword it) else: @@ -3121,8 +3482,9 @@ def _reply_tool(self, request: str, text: str, progress: bool = False, image: st cur = self.store.run_get(run["id"]) if cur is None: # wiped by another account's sign-in meanwhile raise RPCError("这个 /agent 请求已经不在了(换了%s账号),不再回复" % self.app.platform.name) - if cur["state"] in ("stopped", "failed"): - raise RPCError("这个 /agent 请求已经停止了,不再回复") + if named == cur["id"] and request != self._ref(cur): + raise RPCError("这个 /agent 请求已经交给另一个会话处理了,这里不用再回复") + self._check_reply_state(cur) # what took the one reply: a reply, a fallback being sent, or a fallback / timeout notice in the send # journal (sent or uncertain; one that surely failed is released, a quiet run's is never posted) posted = lambda what: self.store.send_get("agent:%s:%s" % (cur["id"], what)) is not None # noqa: E731 @@ -3302,13 +3664,22 @@ def _mark_view(self, text: str) -> str: def _can_edit(self) -> bool: return bool(getattr(self.app.platform, "can_edit", True)) - def _progress(self, run: dict, text: str) -> str: + @staticmethod + def _check_reply_state(run: dict) -> None: + if run["state"] in ("stopped", "failed") or ( + run.get("kind") in QUIET_KINDS and (run.get("start_doubt") or {}).get("at")): + raise RPCError("这个 /agent 请求已经停止了,不再回复") + + def _progress(self, run: dict, text: str, request: str = "") -> str: """A progress update: the run's one progress message, sent the first time and edited in place after (a new one when the edit is refused). Never the answer: a turn that ends with only progress still posts its last words.""" with self._lock("progress:" + run["id"]): # two updates at once never make two progress messages cur = self.store.run_get(run["id"]) if cur is None: # wiped by another account's sign-in meanwhile raise RPCError("这个 /agent 请求已经不在了(换了%s账号),不再回复" % self.app.platform.name) + if request and request != self._ref(cur): + raise RPCError("这个 /agent 请求已经交给另一个会话处理了,这里不用再回复") + self._check_reply_state(cur) self._reject_recalled(cur["chat_id"], cur["request_id"]) body = self.with_suffix(PROGRESS_MARK + "\n" + text.strip(), cur) pid = str(cur.get("progress_id") or "") @@ -3554,16 +3925,17 @@ def _hub_words(e: HubError) -> str: return (e.message or "hub 没有回答").rstrip("。.") +def _has_ref(it: dict, ref: str) -> bool: + return it.get("role") == "user" and it.get("kind") == "text" and ('"%s"' % ref) in (it.get("text") or "") + + +def _matches_send(it: dict, cmid: str, ref: str) -> bool: + # Persona can attach its delivery ID to the text, an image, or a notice made by the input. + return bool(cmid and it.get("kind") != "tool_result" and it.get("client_msg_id") == cmid) or _has_ref(it, ref) + + def _item_time(it: dict) -> float: - """A transcript item's time (its ts, RFC 3339) as a timestamp; 0 when it has none that reads.""" - from datetime import datetime - ts = str(it.get("ts") or "").strip() - if not ts: - return 0.0 - try: - return datetime.fromisoformat(ts.replace("Z", "+00:00")).timestamp() - except ValueError: - return 0.0 + return hub_time(it.get("ts")) def _interrupted(text: str) -> bool: diff --git a/core/openmate_core/agents.py b/core/openmate_core/agents.py index 3f222d8..2834d40 100644 --- a/core/openmate_core/agents.py +++ b/core/openmate_core/agents.py @@ -8,14 +8,12 @@ from __future__ import annotations -import datetime as _dt import logging -import re import time from typing import Any, Callable, Dict, List, Optional, Tuple from .agent import model_label -from .hub import HubError +from .hub import HubError, hub_time as ts from .textutil import clip, one_line from .ui import Fresh, NotYet, Page, day_start, empty, row, snapshot_notice, snapshot_source, stat, state_of, state_text, tile, when @@ -44,19 +42,6 @@ TITLES = {k: t for k, t, *_ in GROUPS} -def ts(v: Any) -> float: - """A hub time (RFC 3339, Go's zero time for none) as a timestamp; 0 when none.""" - s = str(v or "").strip() - if not s or s.startswith("0001-"): - return 0.0 - # Go writes 0–9 fraction digits (".49", ".123456789"); Python before 3.11 takes only 3 or 6 - s = re.sub(r"\.(\d+)", lambda m: "." + (m.group(1) + "000000")[:6], s.replace("Z", "+00:00"), count=1) - try: - return _dt.datetime.fromisoformat(s).timestamp() - except ValueError: - return 0.0 - - def span(seconds: float) -> str: """How long, as people say it: 3 分钟, 1 小时 20 分, 2 天.""" m = int(max(0, seconds) // 60) diff --git a/core/openmate_core/hub.py b/core/openmate_core/hub.py index 24eb7b9..73f7b85 100644 --- a/core/openmate_core/hub.py +++ b/core/openmate_core/hub.py @@ -24,11 +24,13 @@ from __future__ import annotations import http.client +import re import json import socket import urllib.error import urllib.parse import urllib.request +from datetime import datetime from typing import Any, Dict, List, Optional _LOOPBACK = {"127.0.0.1", "localhost", "::1", "[::1]"} @@ -45,15 +47,28 @@ MACHINE_UNSURE = ("node_unreachable", "timeout") +def hub_time(v: Any) -> float: + """A hub time (RFC 3339, Go's zero time for none) as a timestamp; 0 when none.""" + s = str(v or "").strip() + if not s or s.startswith("0001-"): + return 0.0 + # Go writes 0–9 fraction digits (".49", ".123456789"); Python before 3.11 takes only 3 or 6 + s = re.sub(r"\.(\d+)", lambda m: "." + (m.group(1) + "000000")[:6], s.replace("Z", "+00:00"), count=1) + try: + return datetime.fromisoformat(s).timestamp() + except ValueError: + return 0.0 + class HubError(Exception): def __init__(self, status: int, message: str, code: str = "", retryable: Optional[bool] = None, - delivered: str = ""): + delivered: str = "", token_refused: bool = False): super().__init__(message) self.status = status self.message = message self.code = code self.retryable = retryable # the hub's "retryable" and "delivered" ("none": nothing ran), when it said them self.delivered = delivered + self.token_refused = token_refused @property def unreachable(self) -> bool: @@ -72,6 +87,14 @@ def transient(self) -> bool: Unless unsent, it may also have run.""" return self.unsent or self.unreachable or (self.code in MACHINE_UNSURE and self.status >= 500) + @property + def send_uncertain(self) -> bool: + """The send may already be in the session or held by its manager.""" + if self.token_refused or self.unsent or self.delivered == "none": + return False + return (self.delivered == "unknown" or self.status in (0, 408, 502, 504) + or self.code in ("internal", "timeout", "unknown") or self.transient) + class HubAPI: def __init__(self, base_url: str, token: str, timeout: float = 30.0): @@ -108,6 +131,7 @@ def request(self, method: str, path: str, body: Optional[dict] = None, query: Op with self._opener.open(req, timeout=timeout or self.timeout) as resp: raw = resp.read() except urllib.error.HTTPError as e: + token_refused = e.code == 401 and e.headers.get("X-Persona-Auth-Refused") == "token" raw = b"" cut = False try: @@ -117,7 +141,8 @@ def request(self, method: str, path: str, body: Optional[dict] = None, query: Op finally: e.close() if cut: - raise HubError(e.code, "和 Persona hub 的连接中途断了(HTTP %d)" % e.code, NETWORK) + raise HubError(e.code, "和 Persona hub 的连接中途断了(HTTP %d)" % e.code, NETWORK, + token_refused=token_refused) message, code, retryable, delivered = "", "", None, "" try: doc = json.loads(raw or b"{}") @@ -131,7 +156,7 @@ def request(self, method: str, path: str, body: Optional[dict] = None, query: Op code = str(doc["state"]) # a receipt the hub could not settle (503 state unknown) except ValueError: pass - raise HubError(e.code, message or ("hub 回答 HTTP %d" % e.code), code, retryable, delivered) + raise HubError(e.code, message or ("hub 回答 HTTP %d" % e.code), code, retryable, delivered, token_refused) except http.client.HTTPException as e: # cut off mid-answer (IncompleteRead, a bad status line): it may have run raise HubError(0, "和 Persona hub 的连接中途断了(%s)" % type(e).__name__, NETWORK) except (urllib.error.URLError, OSError) as e: @@ -143,7 +168,7 @@ def request(self, method: str, path: str, body: Optional[dict] = None, query: Op try: return json.loads(raw) except ValueError: - raise HubError(0, "hub 的回答不是 JSON") + raise HubError(0, "hub 的回答不是 JSON", NETWORK) # ---- the routes ---- @@ -162,7 +187,7 @@ def capabilities(self) -> dict: def start_conversation(self, prompt: str, purpose: str, report_tasks: bool, machine_id: str = "", launcher: str = "", guest_tools: Optional[List[str]] = None, op_id: str = "", - images: Optional[List[dict]] = None) -> dict: + images: Optional[List[dict]] = None, timeout: float = 120) -> dict: """A conversation; with guest_tools a guest one (docs/assistant/assistant.md "Guest conversations"): it answers someone else for the user, with none of the assistant's powers but these connector tools. With op_id the hub starts it once however often it is asked (assistant_start_ops): the same op_id and body get the first answer. @@ -177,15 +202,24 @@ def start_conversation(self, prompt: str, purpose: str, report_tasks: bool, mach body["machine_id"] = machine_id if launcher: body["launcher"] = launcher - out = self.request("POST", "/api/v1/assistant/conversations", body, timeout=120, op_id=op_id) + out = self.request("POST", "/api/v1/assistant/conversations", body, timeout=timeout, op_id=op_id) state = str((out or {}).get("state") or "") if isinstance(out, dict) else "" if state in ("pending", "unknown") and not (out or {}).get("session"): raise HubError(202, "hub 还在处理这次启动" if state == "pending" else "hub 不确定这次有没有启动", state) sess = (out or {}).get("session") or {} if not sess.get("session_id"): - raise HubError(0, "hub 没有给出会话 id") + raise HubError(0, "hub 没有给出会话 id", NETWORK) return sess + def assistant_probe(self, timeout: float) -> None: + self.request("GET", "/api/v1/assistant", timeout=timeout) + + def start_candidates(self, timeout: float) -> dict: + doc = self.request("GET", "/api/v1/sessions", query={"include_hidden": 1, "limit": 200}, timeout=timeout) + if not isinstance(doc, dict) or not isinstance(doc.get("sessions"), list): + raise HubError(0, "hub 的会话列表不是列表") + return doc + def assistant_machine(self, timeout: float = 10.0) -> str: """The computer the assistant runs on (assistant.ask): where a conversation started without a machine goes.""" doc = self.request("GET", "/api/v1/assistant", timeout=timeout) @@ -225,17 +259,22 @@ def working_sessions(self, timeout: float = 10.0) -> Dict[str, int]: return out def send_message(self, machine_id: str, session_id: str, text: str, client_msg_id: str = "", - images: Optional[List[dict]] = None) -> dict: + images: Optional[List[dict]] = None, timeout: float = 120) -> dict: body: Dict[str, Any] = {"text": text} if images: # [{mime, data (base64)}]: pictures with it (only when some) body["images"] = list(images) if client_msg_id: body["client_msg_id"] = client_msg_id - return self.request("POST", "/api/v1/sessions/%s/%s/messages" % (_seg(machine_id), _seg(session_id)), body, timeout=120) + return self.request("POST", "/api/v1/sessions/%s/%s/messages" % (_seg(machine_id), _seg(session_id)), + body, timeout=timeout) - def items(self, machine_id: str, session_id: str, after_seq: Optional[int] = None) -> dict: + def items(self, machine_id: str, session_id: str, after_seq: Optional[int] = None, *, + timeout: Optional[float] = None, lazy_images: bool = False) -> dict: query = {"after_seq": after_seq} if after_seq is not None else {"turns": 1} - return self.request("GET", "/api/v1/sessions/%s/%s/items" % (_seg(machine_id), _seg(session_id)), query=query) + if lazy_images: + query["lazy_images"] = 1 + return self.request("GET", "/api/v1/sessions/%s/%s/items" % (_seg(machine_id), _seg(session_id)), + query=query, timeout=timeout) def item_full(self, machine_id: str, session_id: str, item_id: str) -> dict: return self.request("GET", "/api/v1/sessions/%s/%s/items/%s/full" % (_seg(machine_id), _seg(session_id), _seg(item_id))) @@ -254,17 +293,23 @@ def todos(self) -> List[dict]: res = self.request("GET", "/api/v1/todos", timeout=10) or {} # optional: a slow answer asks the conversation return [t for t in (res.get("todos") or []) if isinstance(t, dict)] if isinstance(res, dict) else [] + def reporters(self, timeout: float = 15) -> List[dict]: + doc = self.request("GET", "/api/v1/assistant/reporters", timeout=timeout) + if not isinstance(doc, dict) or not isinstance(doc.get("reporters"), list): + raise HubError(0, "hub 的汇报会话列表不是列表") + return doc["reporters"] + def reporter_state(self, session_id: str) -> str: """Whether the hub tells the conversation about the tasks it opened: "reporting"; "stopped" (its task notices are dropped until it is asked again); "absent" (not, or no more, a reporting conversation: they go to the main conversation); "unknown" from a hub without the list (404).""" try: - res = self.request("GET", "/api/v1/assistant/reporters", timeout=15) or {} + rows = self.reporters() except HubError as e: if e.status == 404: return "unknown" raise - for r in (res.get("reporters") or []) if isinstance(res, dict) else []: + for r in rows: if isinstance(r, dict) and r.get("session_id") == session_id: return "stopped" if r.get("stopped_at") else "reporting" return "absent" diff --git a/core/openmate_core/platform.py b/core/openmate_core/platform.py index 94d9db6..ddd8f1a 100644 --- a/core/openmate_core/platform.py +++ b/core/openmate_core/platform.py @@ -138,9 +138,14 @@ class Timing: agent_keep_most: int = 200 agent_hub_wait: float = 300.0 # how long a /agent request waits for the hub to be reachable before it fails agent_hub_probe: float = 5.0 # meanwhile the hub is asked this often whether it answers + agent_doubt_lookback: float = 600.0 # include sessions listed shortly before run creation + agent_doubt_age: float = 90.0 # bus disconnect detection plus startup and transcript lag + agent_doubt_stable: float = 30.0 # successful bus probes before trusting a negative lookup + agent_doubt_lookup: float = 20.0 # minimum interval between fresh snapshots used as negative evidence + agent_doubt_cleanup: float = 300.0 # keep looking for the replaced or stopped start + agent_send_wait: float = 120.0 # time to see an uncertain or queued follow-up in the transcript warm_pages: bool = True # the pages read what they show in the background right after the start agent_model_wait: float = 4.0 # a reply waits this long at most for the hub to list its session's model - agent_start_tries: int = 3 # starts that may have reached the hub (each with a new request id) before it fails agent_settle: float = 8.0 # a session quiet this long after it answered: its status says whether the turn ended secrets_retry: float = 2.0 sent_retry: Tuple[float, ...] = (5.0, 30.0, 120.0) # waits before sent.record is tried again (the hub was busy) diff --git a/extensions/openmate-feishu/persona-extension.json b/extensions/openmate-feishu/persona-extension.json index a5adc75..d8078e2 100644 --- a/extensions/openmate-feishu/persona-extension.json +++ b/extensions/openmate-feishu/persona-extension.json @@ -2,7 +2,7 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.80", + "version": "0.11.81", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", diff --git a/extensions/openmate-wechat/persona-extension.json b/extensions/openmate-wechat/persona-extension.json index 2943420..fdee7c0 100644 --- a/extensions/openmate-wechat/persona-extension.json +++ b/extensions/openmate-wechat/persona-extension.json @@ -2,7 +2,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.73", + "version": "0.1.74", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", diff --git a/packages/openmate-feishu/0.11.81/openmate-feishu-0.11.81.tar.gz b/packages/openmate-feishu/0.11.81/openmate-feishu-0.11.81.tar.gz new file mode 100644 index 0000000..018db0a Binary files /dev/null and b/packages/openmate-feishu/0.11.81/openmate-feishu-0.11.81.tar.gz differ diff --git a/packages/openmate-wechat/0.1.74/openmate-wechat-0.1.74.tar.gz b/packages/openmate-wechat/0.1.74/openmate-wechat-0.1.74.tar.gz new file mode 100644 index 0000000..0e16c2a Binary files /dev/null and b/packages/openmate-wechat/0.1.74/openmate-wechat-0.1.74.tar.gz differ diff --git a/persona-extensions.json b/persona-extensions.json index 30c1de3..d5f30c5 100644 --- a/persona-extensions.json +++ b/persona-extensions.json @@ -9,7 +9,7 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.80", + "version": "0.11.81", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -540,9 +540,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-feishu/0.11.80/openmate-feishu-0.11.80.tar.gz", - "sha256": "85ca0b8e31a6cf6d47d87434b89360070ed2582e165b5c57e89fac8afe7a4878", - "size": 415117 + "url": "packages/openmate-feishu/0.11.81/openmate-feishu-0.11.81.tar.gz", + "sha256": "851f0d2b8803408bda48551e38d699c766aa6fc74bc1408fa7d18738dec1d8c6", + "size": 419375 } ] }, @@ -551,7 +551,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.73", + "version": "0.1.74", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -848,9 +848,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-wechat/0.1.73/openmate-wechat-0.1.73.tar.gz", - "sha256": "3c3db8c37498fec862f109c5e86d18c4896fa7884f4f32fa342adf0972e3cd3f", - "size": 311944 + "url": "packages/openmate-wechat/0.1.74/openmate-wechat-0.1.74.tar.gz", + "sha256": "dcae7d4e7b59bc6ef6a8f4d7a9d8868578fee234a7c2eb608918f4363fe05f77", + "size": 316149 } ] } diff --git a/tests/harness.py b/tests/harness.py index f71b217..a047b24 100644 --- a/tests/harness.py +++ b/tests/harness.py @@ -14,6 +14,7 @@ import tempfile import threading import time +from datetime import datetime, timezone import urllib.parse from typing import Any, Callable, Dict, List, Optional @@ -43,6 +44,12 @@ def fast(**kw) -> Timing: return Timing(**base) +def stamp(at=None) -> str: + # Go marshals timestamps with up to nine fractional digits. + return datetime.fromtimestamp(time.time() if at is None else at, timezone.utc).isoformat( + timespec="microseconds").replace("+00:00", "789Z") + + def wait_until(cond: Callable[[], Any], timeout: float = 5.0, what: str = "condition") -> Any: deadline = time.monotonic() + timeout while True: @@ -234,6 +241,17 @@ def __init__(self, token: str = TOKEN): self.ops: Dict[str, dict] = {} # X-Persona-Op-Id of conversation starts → their receipt (assistant_start_ops) self.start_pending = 0 # the next this many asks about a start find it still under way (202 pending) self.start_unknown = False # the next start ends with nobody knowing whether it started (202 unknown) + self.start_doubts: List[tuple] = [] # (code, opened) for successive new operations + self.start_auth: List[bool] = [] # a 401 for each entry, with the refusal header when True + self.send_auth: List[bool] = [] + self.send_outcomes: List[tuple] = [] # (status, code, delivered, wrote transcript) + self.probe_status = 200 # independent of /health + self.list_sessions = True + self.list_more = False + self.session_pages: List[List[str]] = [] # candidate snapshots already built by the fake hub + self.list_reporters = True + self.hide_first_item = False + self.clip_start = 0 self.todos: List[dict] = [] # GET /api/v1/todos (todos.read): the to-dos, as the hub lists them self.todos_status: Optional[int] = None # an HTTP status GET /api/v1/todos answers instead (403: no todos.read) self.todos_delay = 0.0 # seconds GET /api/v1/todos takes @@ -259,11 +277,13 @@ class Handler(http.server.BaseHTTPRequestHandler): def log_message(self, *a): pass - def _reply(self, status: int, obj: Any) -> None: + def _reply(self, status: int, obj: Any, headers: Optional[dict] = None) -> None: raw = json.dumps(obj, ensure_ascii=False).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(raw))) + for k, v in (headers or {}).items(): + self.send_header(k, v) self.end_headers() self.wfile.write(raw) @@ -281,8 +301,7 @@ def _handle(self, method: str) -> None: hub.requests.append(rec) if rec["auth"] != "Bearer " + hub.token: return self._reply(401, {"error": "bad token"}) - status, obj = hub.route(method, rec["path"].split("/")[1:], query, body, rec["op"]) - self._reply(status, obj) + self._reply(*hub.route(method, rec["path"].split("/")[1:], query, body, rec["op"])) def do_GET(self): self._handle("GET") @@ -322,6 +341,16 @@ def finish(self, sid: str) -> None: with self.lock: self.sessions[sid]["working"] = False + def add_conversation(self, body: dict, sid: Optional[str] = None) -> str: + with self.lock: + sid = sid or ("sess-%d" % next(self._n)) + mid = body.get("machine_id") or "mac-example" + self.sessions[sid] = {"machine": mid, "items": [], "assistant": True, "at": stamp(), + "reporter": bool(body.get("report_tasks")), "guest": bool(body.get("guest")), + "working": True, "stopped": False} + self.add(sid, "user", "text", (body.get("prompt") or "")[:self.clip_start or None]) + return sid + def add_agent(self, sid: str, machine: str = "mac-agent", working: bool = True) -> dict: """An Agent's session a task runs in (not a conversation /agent started).""" with self.lock: @@ -381,6 +410,8 @@ def route(self, method: str, parts: List[str], query: dict, body: Any, op: str = if method == "GET" and p == "/api/v1/assistant/capabilities": return (404, {"error": "no route"}) if self.no_guest else (200, {"guest_conversations": True}) if method == "POST" and p == "/api/v1/assistant/conversations": + if self.start_auth: + return 401, {"error": "令牌无效"}, {"X-Persona-Auth-Refused": "token"} if self.start_auth.pop(0) else {} if op and op in self.ops: # a start asked again: its receipt, never a second conversation rec = self.ops[op] if rec["body"] != body: @@ -412,11 +443,17 @@ def route(self, method: str, parts: List[str], query: dict, body: Any, op: str = if op: # as the hub does (clientOpRetry lets only assistant_offline go): the refusal is the receipt self.ops[op] = {"body": body, "state": "done", "status": 503, "answer": refusal} return 503, refusal - sid = "sess-%d" % next(self._n) - mid = (body or {}).get("machine_id") or "mac-example" - self.sessions[sid] = {"machine": mid, "items": [], "reporter": bool((body or {}).get("report_tasks")), - "working": True, "stopped": False} - self.add(sid, "user", "text", (body or {}).get("prompt") or "") + if self.start_doubts: + code, opened = self.start_doubts.pop(0) + if opened: + self.add_conversation(body or {}) + status = 202 if code == "unknown" else 409 if code == "op_id_reused" else 502 + answer = {"state": code} if code == "unknown" else {"error": code, "code": code} + if op: + self.ops[op] = {"body": body, "state": "done", "status": status, "answer": answer} + return status, answer + sid = self.add_conversation(body or {}) + mid = self.sessions[sid]["machine"] answer = {"session": {"machine_id": mid, "session_id": sid, "title": ""}} if op: self.ops[op] = {"body": body, "state": "done", "status": 200, "answer": answer} @@ -437,14 +474,16 @@ def route(self, method: str, parts: List[str], query: dict, body: Any, op: str = if sid in self.stop_status: return self.stop_status[sid], {"error": "not a reporting conversation"} s = self.sessions.get(sid) - if s is None: - return 404, {"error": "unknown"} + if s is None or s.get("guest"): + return 404, {"error": "not a reporting conversation"} was = s["working"] and not s["stopped"] s["stopped"], s["working"] = True, False tasks = s.get("tasks") or [] return 200, {"conversation": was, "tasks": tasks, "already": not was and not tasks} - if method == "GET" and p == "/api/v1/assistant" and self.assistant_mid is not None: - return 200, {"assistant": {"machine_id": self.assistant_mid}} + if method == "GET" and p == "/api/v1/assistant": + if self.probe_status != 200: + return self.probe_status, {"error": "manager offline", "code": "assistant_offline"} + return 200, {"assistant": {"machine_id": self.assistant_mid or ""}} if method == "GET" and p == "/api/v1/machines" and self.machine_list is not None: return 200, {"machines": [dict(m) for m in self.machine_list]} if method == "GET" and len(parts) == 5 and parts[:3] == ["api", "v1", "machines"] and parts[4] == "metrics": @@ -452,10 +491,10 @@ def route(self, method: str, parts: List[str], query: dict, body: Any, op: str = return 200, {"metrics": dict(self.metrics[parts[3]]), "range": query.get("range"), "step": 10} return 404, {"error": "unknown machine"} if method == "GET" and p == "/api/v1/assistant/reporters": - return 200, {"reporters": [dict({"session_id": sid, "machine_id": s["machine"], "at": "2026-11-19T00:00:00Z"}, + return 200, {"reporters": [dict({"session_id": sid, "machine_id": s["machine"], "at": s.get("at") or stamp()}, **({"stopped_at": "2026-11-19T00:00:01Z", "stopped_by": "lark"} if s.get("stopped") else {})) - for sid, s in self.sessions.items() if s.get("reporter")]} + for sid, s in self.sessions.items() if self.list_reporters and s.get("reporter")]} if method == "GET" and p == "/api/v1/interactions/history": # newest first, paged by limit with a cursor (the hub's next_before / next_before_id: here a position) recs = [dict(r) for r in reversed(self.history) @@ -495,6 +534,14 @@ def route(self, method: str, parts: List[str], query: dict, body: Any, op: str = return 200, {"sessions": rows, "total": len(rows), "has_more": self.working_more} if method == "GET" and p == "/api/v1/sessions": sid, mid = query.get("session_id"), query.get("machine_id") + if not sid: + rows = [{"session_id": k, "machine_id": s["machine"], "updated_at": s["at"], + "assistant": s["assistant"]} for k, s in self.sessions.items() + if self.list_sessions and s.get("assistant") and (not s.get("hidden") or query.get("include_hidden") == "1")] + rows.sort(key=lambda r: r["updated_at"], reverse=True) + self.session_pages.append([row["session_id"] for row in rows]) + return 200, {"sessions": rows, "total": len(rows), "has_more": self.list_more, + "next_cursor": "frozen" if self.list_more else ""} s = self.sessions.get(sid or "") if s is None or s["machine"] != mid: return 200, {"sessions": [], "total": 0, "has_more": False} @@ -522,6 +569,8 @@ def route(self, method: str, parts: List[str], query: dict, body: Any, op: str = return 404, {"error": "no such session"} rest = parts[5:] if method == "POST" and rest == ["messages"]: + if self.send_auth: + return 401, {"error": "令牌无效"}, {"X-Persona-Auth-Refused": "token"} if self.send_auth.pop(0) else {} hook = self.send_hook.pop(sid, None) if hook is not None: answer = hook() @@ -540,6 +589,11 @@ def route(self, method: str, parts: List[str], query: dict, body: Any, op: str = kw["client_msg_id"] = cmid if any(it.get("client_msg_id") == cmid for it in s["items"]): return 200, {"ok": True} # the hub sends each client_msg_id once + if self.send_outcomes: + status, code, delivered, wrote = self.send_outcomes.pop(0) + if wrote: + self.add(sid, "user", "text", (body or {}).get("text") or "", **kw) + return status, {"code": code, "delivered": delivered, "error": "回包丢了"} s["working"] = True s["stopped"] = False # asked again: its task notices are told again (the hub's reporter book) self.add(sid, "user", "text", (body or {}).get("text") or "", **kw) @@ -555,6 +609,8 @@ def route(self, method: str, parts: List[str], query: dict, body: Any, op: str = return 200, {"ok": True} if method == "GET" and rest == ["items"]: items = s["items"] + if self.hide_first_item and s.get("assistant"): + items = [it for it in items if it["seq"] != 1] if "after_seq" in query: after = int(query["after_seq"]) page = [it for it in items if it["seq"] > after] diff --git a/tests/test_agent.py b/tests/test_agent.py index 40d7e0e..31c88fb 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -1288,28 +1288,6 @@ def test_a_start_still_under_way_is_waited_for(self): self.assertEqual(len(h.http.sessions), 1) self.assertEqual(run["session_id"], "sess-1") - def test_a_start_nobody_knows_about_is_not_sent_again(self): - h = agent(self) - h.http.start_unknown = True - m = ask(h, "/agent 不知道有没有开始") - wait_until(lambda: replies(h), what="the explanation") - self.assertIn("在 Persona 里看看", replies(h)[0]["text"]) - self.assertEqual(len(h.http.starts()), 1, "never asked again on its own") - self.assertEqual(run_of(h, m)["state"], "failed") - - def test_lost_starts_are_tried_three_times(self): - h = agent(self) - h.http.lost_starts = 10 - m = ask(h, "/agent 一直丢") - wait_until(lambda: replies(h), what="the explanation") - self.assertIn("试了 3 次", replies(h)[0]["text"]) - self.assertIn("在 Persona 里看看", replies(h)[0]["text"]) - self.assertEqual(len(h.http.starts()), 3) - self.assertEqual(len({s["op"] for s in h.http.starts()}), 1, "the same operation each time") - self.assertEqual(len(h.http.sessions), 1, "one conversation at most") - run = run_of(h, m) - self.assertEqual((run["state"], run.get("ref")), ("failed", None), "never a new ref") - def test_a_continuation_whose_answer_was_lost_is_sent_once(self): h = agent(self) first = ask(h, "/agent 第一个问题") @@ -1322,7 +1300,7 @@ def test_a_continuation_whose_answer_was_lost_is_sent_once(self): second = ask(h, "/agent 接着问", root_id=first.id) run2 = running(h, second) posts = h.http.posts("/api/v1/sessions/mac-example/%s/messages" % sid) - self.assertEqual(len(posts), 2) + self.assertEqual(len(posts), 1) self.assertEqual({p["body"]["client_msg_id"] for p in posts}, {"openmate-" + run2["id"]}) typed = [it for it in h.http.sessions[sid]["items"] if it.get("client_msg_id")] self.assertEqual(len(typed), 1) @@ -1412,7 +1390,7 @@ def test_two_starts_of_one_run_change_its_id_once(self): def test_the_new_id_gets_its_own_tries(self): from openmate_core.hub import HubError - h = agent(self, timing=fast(agent_hub_wait=60.0, agent_start_tries=2)) + h = agent(self, timing=fast(agent_hub_wait=60.0)) real = h.app.agent.hub.start_conversation ops = [] script = [HubError(502, "回包丢了", "hub_unreachable"), # A: may have reached it (a try counted) @@ -1598,7 +1576,7 @@ def test_a_restart_while_it_waits_asks_the_hub_again_under_its_operation(self): self.assertEqual([x for x in h2.sent() if "重新发送" in x["text"]], []) def test_a_restart_after_the_hub_started_it_gets_that_conversation(self): - h = agent(self, timing=fast(agent_hub_wait=60.0, agent_start_tries=10 ** 6)) + h = agent(self, timing=fast(agent_hub_wait=60.0)) h.http.lost_starts = 10 ** 6 # it starts at the hub, every answer is lost on the way back m = ask(h, "/agent 回执丢了又重启") wait_until(lambda: len(h.http.starts()) >= 2, what="asked again") diff --git a/tests/test_agent_forward.py b/tests/test_agent_forward.py index 69f994f..f36aea9 100644 --- a/tests/test_agent_forward.py +++ b/tests/test_agent_forward.py @@ -461,12 +461,12 @@ def test_a_stopped_conversation_is_asked_again(self): wait_until(lambda: h.http.posts("/api/v1/assistant/conversations/%s/stop" % sid), what="the stop") went_to_the_assistant(self, h, first, sid, "/agent 继续做吧") - def test_an_answer_lost_on_the_way_is_sent_again_once(self): + def test_an_answer_lost_on_the_way_is_confirmed_in_items(self): h, first, run1, sid = dispatched(self) h.http.lost_sends, h.http.lost_send_status = 1, (500, "internal") # it went out; the answer did not come msg, run = forwarded(self, h, first, sid) posts = h.http.messages_to("mac-agent", "agent-1") - self.assertEqual(len(posts), 2) + self.assertEqual(len(posts), 1) self.assertEqual({p["body"]["client_msg_id"] for p in posts}, {"openmate-" + run["id"]}) self.assertEqual(len([it for it in h.http.sessions["agent-1"]["items"] if it.get("client_msg_id")]), 1) diff --git a/tests/test_agent_network.py b/tests/test_agent_network.py new file mode 100644 index 0000000..16dc976 --- /dev/null +++ b/tests/test_agent_network.py @@ -0,0 +1,525 @@ +"""Lost replies and disconnects around /agent writes, through the scoped HTTP client.""" + +import threading +import time +import unittest +from dataclasses import fields +from types import SimpleNamespace +from unittest.mock import patch + +from harness import HubSideError, fast, wait_until +from openmate_core.hub import HubError +from test_agent import agent, ask, replies, run_of, running, started +from test_agent_forward import FORWARDED, dispatched, follow_up, forwarded + + +def timing(**overrides): + options = dict(agent_hub_wait=0.8, agent_hub_probe=0.035, agent_doubt_age=0.24, agent_doubt_stable=0.12, + agent_doubt_lookup=0.10, agent_doubt_cleanup=0.9, agent_send_wait=0.4) + options.update(overrides) + # The same tests run against origin/main, whose Timing doesn't have these fields yet. + available = {f.name for f in fields(fast())} + return fast(**{k: v for k, v in options.items() if k in available}) + + +def settle(h, msg, state): + def matches(): + run = run_of(h, msg) + return run if run["state"] == state else None + try: + run = wait_until(matches, timeout=2.5, what=state) + if state == "failed" and run.get("error"): + wait_until(lambda: any(run["error"] in sent["text"] for sent in replies(h)), what="failure notice") + return run + except AssertionError as e: + run = run_of(h, msg) + raise AssertionError("wanted %s, got %s (ours_seen=%s, error=%s)" % + (state, run["state"], run.get("ours_seen"), run.get("error"))) from e + + +def resolve(h, msg, sid="sess-1", text="对账后的回答"): + run = running(h, msg) + assert run["session_id"] == sid, run + h.http.add(sid, "assistant", "text", text) + h.http.end_turn(sid) + wait_until(lambda: any(x["text"].startswith(text) for x in replies(h)), what=text) + return run + + +def list_lookups(h): + return [r for r in h.http.session_rows() if r["query"].get("include_hidden") == "1" and + "state" not in r["query"] and "session_id" not in r["query"]] + + +class RestartWriteTest(unittest.TestCase): + def cut_off(self, h, method, *, post=False): + """Exit the worker at the HTTP boundary, after the pending write has been saved.""" + runner = h.app.agent + submit = getattr(runner.hub, method) + cut = threading.Event() + responses = [] + + def interrupted(*args, **kwargs): + try: + if post: + responses.append(submit(*args, **kwargs)) + except HubError as e: + responses.append(e.code) + runner._stop.set() + cut.set() + raise SystemExit + + interceptor = patch.object(runner.hub, method, side_effect=interrupted) + call = interceptor.start() + self.addCleanup(interceptor.stop) + return cut, call, responses + + def test_restart_before_start_post_uses_the_kept_op_and_body(self): + h = agent(self, timing=timing()) + cut, call, _ = self.cut_off(h, "start_conversation") + msg = ask(h, "/agent 启动发出前重启") + self.assertTrue(cut.wait(2)) + kept = run_of(h, msg) + self.assertTrue(kept["start_doubt"]["op_sent_at"]) + self.assertFalse(kept["start_doubt"].get("at")) + self.assertEqual(h.http.starts(), []) + + h2 = h.restart() + h2.wait_ok() + resumed = resolve(h2, msg) + self.assertEqual([p["op"] for p in h.http.starts()], [call.call_args.kwargs["op_id"]]) + self.assertEqual(h.http.starts()[0]["body"]["prompt"], call.call_args.args[0]) + self.assertEqual(resumed.get("ref", kept["id"]), kept["id"]) + self.assertFalse(resumed.get("error")) + self.assertFalse(list_lookups(h2)) + + def test_restart_after_lost_success_adopts_the_same_op_receipt(self): + h = agent(self, timing=timing()) + h.http.lost_starts = 1 + cut, _, responses = self.cut_off(h, "start_conversation", post=True) + msg = ask(h, "/agent 成功回执丢失后重启") + self.assertTrue(cut.wait(2)) + self.assertEqual(responses, ["hub_unreachable"]) + first = h.http.starts()[0] + self.assertEqual(h.http.ops[first["op"]]["answer"]["session"]["session_id"], "sess-1") + self.assertFalse(run_of(h, msg)["start_doubt"].get("at")) + + h2 = h.restart() + h2.wait_ok() + resumed = resolve(h2, msg) + self.assertEqual([(p["op"], p["body"]) for p in h.http.starts()], [(first["op"], first["body"])] * 2) + self.assertEqual(list(h.http.sessions), ["sess-1"]) + self.assertFalse(resumed.get("reconciled_at")) + self.assertFalse(list_lookups(h2)) + + def test_restart_after_unknown_reasks_before_reconciling(self): + h = agent(self, timing=timing()) + h.http.start_unknown = True + cut, _, responses = self.cut_off(h, "start_conversation", post=True) + msg = ask(h, "/agent 收到 unknown 时重启") + self.assertTrue(cut.wait(2)) + self.assertEqual(responses, ["unknown"]) + first = h.http.starts()[0] + self.assertFalse(run_of(h, msg)["start_doubt"].get("at")) + + h2 = h.restart() + h2.wait_ok() + resumed = resolve(h2, msg) + starts = h.http.starts() + self.assertEqual([(p["op"], p["body"]) for p in starts], [(first["op"], first["body"])] * 2) + self.assertEqual(h.http.ops[first["op"]]["state"], "unknown") + self.assertTrue(resumed["reconciled_at"]) + lookup = h.http.requests.index(list_lookups(h2)[0]) + self.assertEqual(sum(p is starts[0] or p is starts[1] for p in h.http.requests[:lookup]), 2) + self.assertEqual(list(h.http.sessions), ["sess-1"]) + + def test_restart_before_followup_post_sends_once_to_the_original_session(self): + h = agent(self, timing=timing()) + first = ask(h, "/agent 开会话") + resolve(h, first) + cut, _, _ = self.cut_off(h, "send_message") + msg = follow_up(h, first, "/agent 问助手 续聊发出前重启") + self.assertTrue(cut.wait(2)) + fields = run_of(h, msg)["send_pending"]["fields"] + self.assertFalse(h.http.messages_to("mac-example", "sess-1")) + before = len(h.http.requests) + + h2 = h.restart() + h2.wait_ok() + resumed = resolve(h2, msg, text="续聊的回答") + done = settle(h2, msg, "done") + sends = h.http.messages_to("mac-example", "sess-1") + self.assertEqual([p["body"]["client_msg_id"] for p in sends], [fields["client_msg_id"]]) + self.assertIn("续聊发出前重启", sends[0]["body"]["text"]) + self.assertTrue(any(p["path"].endswith("/sess-1/items") and p["query"].get("after_seq") == str(fields["last_seq"]) + for p in h.http.requests[before:h.http.requests.index(sends[0])])) + self.assertEqual(resumed["continued"], fields["continued"]) + self.assertFalse(done.get("error")) + self.assertEqual(len(h.http.starts()), 1) + + def test_restart_before_forward_post_sends_once_to_the_task_agent(self): + h, first, original, sid = dispatched(self, timing=timing()) + cut, call, _ = self.cut_off(h, "send_message") + msg = follow_up(h, first, "/agent 转交发出前重启") + self.assertTrue(cut.wait(2)) + target = run_of(h, msg)["forward_pending"] + self.assertFalse(h.http.messages_to("mac-agent", "agent-1")) + before = len(h.http.requests) + + h2 = h.restart() + h2.wait_ok() + resumed = settle(h2, msg, "forwarded") + sends = h.http.messages_to("mac-agent", "agent-1") + self.assertEqual([p["body"]["client_msg_id"] for p in sends], [call.call_args.args[3]]) + self.assertIn("转交发出前重启", sends[0]["body"]["text"]) + self.assertTrue(any(p["path"].endswith("/agent-1/items") + for p in h.http.requests[before:h.http.requests.index(sends[0])])) + self.assertEqual(resumed["forward"], target) + self.assertFalse(resumed.get("error")) + self.assertFalse(h.http.messages_to("mac-example", sid)) + self.assertEqual(len(h.http.starts()), 1) + wait_until(lambda: any(FORWARDED in p["text"] and p["reply_to"] == msg.id for p in h2.sent()), what="forward note") + h2.tool("agent_reply", request=original["id"], text="转交的回答") + self.assertTrue(any(p["text"].startswith("转交的回答") and p["reply_to"] == msg.id for p in replies(h2))) + + +class StartNetworkTest(unittest.TestCase): + def test_in_doubt_adopts_reporter_and_delivers_answer(self): + h = agent(self, timing=timing()) + h.http.list_sessions = False + h.http.start_doubts = [("assistant_in_doubt", True)] + msg = ask(h, "/agent 这一单的状态") + run = resolve(h, msg) + self.assertEqual(run["start_doubt"]["ref"], run["id"]) + self.assertEqual(len(h.http.starts()), 1) + self.assertEqual(len(replies(h)), 1) + + def test_unknown_and_reused_receipts_adopt_from_hidden_session_list(self): + for code in ("unknown", "op_id_reused"): + with self.subTest(code=code): + h = agent(self, timing=timing()) + h.http.probe_status = 503 + h.http.list_reporters = False + if code == "unknown": + h.http.start_unknown = True + else: + h.http.start_doubts = [(code, True)] + msg = ask(h, "/agent 隐藏会话") + started(h) + wait_until(lambda: h.http.sessions, what="session created") + h.http.sessions["sess-1"]["hidden"] = True + h.http.probe_status = 200 + resolve(h, msg) + self.assertEqual(len(h.http.starts()), 1) + self.assertTrue(list_lookups(h)) + self.assertTrue(all("cursor" not in p["query"] for p in list_lookups(h))) + + def test_clear_lookups_reopen_once_even_after_original_wait(self): + h = agent(self, timing=timing(agent_hub_wait=0.38, agent_doubt_age=0.22)) + h.http.lost_starts = 1000 + msg = ask(h, "/agent 等回执") + first = started(h) + # Hide the first conversation from the hub permanently to exercise two negative snapshots after the POST deadline. + wait_until(lambda: h.http.sessions, what="hub received first start") + with h.http.lock: + h.http.sessions.clear() + wait_until(lambda: list_lookups(h), what="POST deadline led to lookup") + h.http.lost_starts = 0 + run = resolve(h, msg, "sess-2") + ops = {r["op"] for r in h.http.starts()} + self.assertEqual(len(ops), 2) + self.assertEqual(run["ref"], run["id"] + ".2") + self.assertNotEqual(run["start_op"], first["op"]) + self.assertGreaterEqual(len(list_lookups(h)), 2) + + def test_second_lookup_discovers_the_original(self): + h = agent(self, timing=timing(agent_doubt_lookup=0.18)) + h.http.start_doubts = [("assistant_in_doubt", False)] + msg = ask(h, "/agent 会话晚一点登记") + post = started(h) + wait_until(lambda: h.http.session_pages, what="first snapshot built") + self.assertEqual(h.http.session_pages[0], []) + h.http.add_conversation(post["body"]) + resolve(h, msg) + self.assertEqual(h.http.session_pages[1], ["sess-1"]) + self.assertEqual(len(h.http.starts()), 1) + + def test_first_item_pending_disqualifies_negative_lookups(self): + h = agent(self, timing=timing()) + h.http.hide_first_item = True + h.http.start_doubts = [("assistant_in_doubt", True)] + msg = ask(h, "/agent 会话已有,首条未到") + self.assertIn("还没法确认", settle(h, msg, "failed")["error"]) + self.assertGreaterEqual(len(list_lookups(h)), 2) + self.assertEqual(len(h.http.starts()), 1) + + def test_health_without_bus_never_counts_as_clear(self): + h = agent(self, timing=timing()) + h.http.probe_status = 503 + h.http.start_doubts = [("assistant_in_doubt", False)] + msg = ask(h, "/agent bus 掉线") + self.assertIn("还没法确认", settle(h, msg, "failed")["error"]) + self.assertTrue(any(r["path"] == "/api/v1/health" for r in h.http.requests)) + self.assertTrue(any(r["path"] == "/api/v1/assistant" for r in h.http.requests)) + self.assertEqual(list_lookups(h), []) + self.assertEqual(len(h.http.starts()), 1) + + def test_stability_gate_prevents_reopen(self): + h = agent(self, timing=timing(agent_doubt_stable=3)) + h.http.start_doubts = [("assistant_in_doubt", False)] + msg = ask(h, "/agent bus 刚通") + self.assertIn("还没法确认", settle(h, msg, "failed")["error"]) + self.assertGreaterEqual(len(list_lookups(h)), 2) + self.assertEqual(len(h.http.starts()), 1) + + def test_truncated_first_page_cannot_establish_absence(self): + h = agent(self, timing=timing()) + h.http.start_doubts = [("assistant_in_doubt", False)] + h.http.list_more = True + h.http.add_conversation({"prompt": "无关的首条消息"}) + msg = ask(h, "/agent snapshot 装不下") + self.assertIn("还没法确认", settle(h, msg, "failed")["error"]) + self.assertTrue(all("cursor" not in p["query"] for p in list_lookups(h))) + self.assertEqual(len(h.http.starts()), 1) + + def test_ignores_tool_result_and_later_user_text(self): + h = agent(self, timing=timing()) + h.http.list_reporters = False + h.http.probe_status = 503 + h.http.start_doubts = [("assistant_in_doubt", False)] + msg = ask(h, "/agent 不认后面的引用") + first = started(h) + ref = run_of(h, msg)["id"] + h.http.add_conversation(first["body"], "real") + other = h.http.add_conversation({"prompt": "另一个请求"}) + h.http.add(other, "user", "tool_result", 'request 填 "%s"' % ref) + h.http.add(other, "user", "text", 'request 填 "%s"' % ref) + h.http.probe_status = 200 + resolve(h, msg, "real") + self.assertEqual(h.http.session_pages[0], [other, "real"]) + self.assertTrue(any(r["path"].endswith("/%s/items" % other) for r in h.http.requests)) + self.assertEqual(len(h.http.starts()), 1) + + def test_clipped_first_text_with_image_matches(self): + h = agent(self, timing=timing()) + h.http.start_doubts = [("assistant_in_doubt", True)] + h.http.clip_start = 2400 + h.app.agent._request_images = lambda run, row: [{"mime": "image/png", "data": "aW1hZ2U="}] + original = h.app.agent.build_prompt + h.app.agent.build_prompt = lambda *args: original(*args) + "长" * 26000 + msg = ask(h, "/agent 读图与长文本") + run = resolve(h, msg) + self.assertTrue(started(h)["body"]["images"]) + self.assertGreater(len(run["start_prompt"]), len(h.http.sessions["sess-1"]["items"][0]["text"])) + + def test_reopened_op_rejects_old_reply_and_stops_late_original(self): + h = agent(self, timing=timing()) + h.http.start_doubts = [("assistant_in_doubt", False)] + msg = ask(h, "/agent 原请求后来才到") + original = started(h) + run = running(h, msg) + self.assertNotEqual(started(h, 2)["op"], original["op"]) + self.assertIn('request 填 "%s.2"' % run["id"], started(h, 2)["body"]["prompt"]) + with self.assertRaisesRegex(HubSideError, "另一个会话"): + h.tool("agent_reply", request=run["id"], text="旧回答") + old = h.http.add_conversation(original["body"]) + wait_until(lambda: h.http.sessions[old]["stopped"], what="late original stopped") + h.tool("agent_reply", request=run["ref"], text="重开的回答") + self.assertEqual(len(replies(h)), 1) + + def test_second_doubt_cannot_reopen(self): + h = agent(self, timing=timing()) + h.http.start_doubts = [("assistant_in_doubt", False), ("assistant_in_doubt", False)] + msg = ask(h, "/agent 重开之后又断") + run = settle(h, msg, "failed") + self.assertIn("没找到", run["error"]) + self.assertEqual(len(h.http.starts()), 2) + self.assertEqual(run["start_doubt"]["reopens"], 1) + + def test_only_marked_start_401_is_retried(self): + h = agent(self, timing=timing()) + h.http.start_auth = [True] + msg = ask(h, "/agent hub 拒绝令牌") + run = running(h, msg) + self.assertEqual(len(h.http.starts()), 2) + self.assertEqual({p["op"] for p in h.http.starts()}, {run["start_op"]}) + h.http.start_auth = [False] + msg2 = ask(h, "/agent 普通 401") + self.assertIn("令牌无效", settle(h, msg2, "failed")["error"]) + self.assertEqual(len(h.http.starts()), 3) + + def test_same_op_survives_three_relay_eofs(self): + h = agent(self, timing=timing()) + h.http.lost_starts = 3 + msg = ask(h, "/agent 回包丢三次") + run = resolve(h, msg) + self.assertEqual(len(h.http.starts()), 4) + self.assertEqual({p["op"] for p in h.http.starts()}, {run["start_op"]}) + + def test_pending_at_deadline_adopts_the_session(self): + h = agent(self, timing=timing(agent_hub_wait=0.28)) + h.http.start_pending = 1000 + msg = ask(h, "/agent 期限到还在 pending") + run = resolve(h, msg) + self.assertTrue(list_lookups(h)) + self.assertEqual({p["op"] for p in h.http.starts()}, {run["start_op"]}) + + def test_restart_resumes_lookup_without_posting_old_op(self): + h = agent(self, timing=timing()) + h.http.probe_status = 503 + h.http.start_doubts = [("assistant_in_doubt", True)] + msg = ask(h, "/agent 对账时重启") + first = wait_until(lambda: run_of(h, msg).get("start_doubt", {}).get("at"), timeout=1.5, what="persisted doubt") + h2 = h.restart() + h2.wait_ok() + h.http.probe_status = 200 + run = resolve(h2, msg) + self.assertGreaterEqual(first, run["start_doubt"]["first_sent"]) + self.assertEqual(len(h.http.starts()), 1) + + def test_overnight_resume_adopts_or_reports_absence_without_reopening(self): + for opened in (True, False): + with self.subTest(opened=opened): + h = agent(self, timing=timing()) + h.http.probe_status = 503 + h.http.start_doubts = [("assistant_in_doubt", opened)] + msg = ask(h, "/agent 隔夜恢复") + started(h) + rid = run_of(h, msg)["id"] + wait_until(lambda: run_of(h, msg).get("start_doubt", {}).get("at"), timeout=1.5, what="doubt") + h.app.store._tx(lambda db: db.execute("UPDATE runs SET created = ? WHERE id = ?", + (time.time() - 86400, rid))) + cur = run_of(h, msg) + cur["start_doubt"]["at"] -= 86400 + h.app.store.run_put(cur) + h2 = h.restart() + h2.wait_ok() + h.http.probe_status = 200 + if opened: + self.assertEqual(resolve(h2, msg)["session_id"], "sess-1") + else: + self.assertIn("没找到", settle(h2, msg, "failed")["error"]) + self.assertEqual(len(h.http.starts()), 1) + + def test_stop_during_lookup_stops_late_session(self): + h = agent(self, timing=timing()) + h.http.probe_status = 503 + h.http.start_doubts = [("assistant_in_doubt", False)] + msg = ask(h, "/agent 一会停掉") + first = started(h) + wait_until(lambda: run_of(h, msg).get("start_doubt", {}).get("at"), timeout=1.5, what="doubt") + ask(h, "/stop", root_id=msg.id, parent_id=msg.id, placement="thread") + settle(h, msg, "stopped") + sid = h.http.add_conversation(first["body"]) + h.http.probe_status = 200 + wait_until(lambda: h.http.sessions[sid]["stopped"], what="late original stopped") + + def test_wiped_run_stops_late_session_without_chat_message(self): + h = agent(self, timing=timing()) + h.http.probe_status = 503 + h.http.start_doubts = [("assistant_in_doubt", False)] + msg = ask(h, "/agent 换账号以后要停") + first = started(h) + wait_until(lambda: run_of(h, msg).get("start_doubt", {}).get("at"), timeout=1.5, what="doubt") + h.app.store.wipe_account_data() + sid = h.http.add_conversation(first["body"]) + h.http.probe_status = 200 + wait_until(lambda: h.http.sessions[sid]["stopped"], what="late original stopped") + self.assertFalse(replies(h)) + + def test_quiet_guest_and_document_doubts_fail_silently(self): + for kind, opened in (("auto", True), ("doc", True), ("auto", False), ("doc", False)): + with self.subTest(kind=kind, opened=opened): + h = agent(self, timing=timing(), auto_reply_full=False) + h.http.start_doubts = [("assistant_in_doubt", opened)] + row = {"id": "message", "chat_id": "chat_example_team", "text": "请代答", "position": 0} + if kind == "doc": + m = SimpleNamespace(id="comment", doc_url="https://example.org/doc", doc_title="例", + text="请代答", comment_id="c") + run = h.app.agent._doc_run(m, "doc:example", "同事", time.time()) + else: + run = dict(h.app.agent._new_run(row, "请代答", time.time()), kind=kind) + h.app.store.run_put(run) + h.app.agent._start(run, row) + self.assertEqual(h.app.store.run_get(run["id"])["state"], "failed") + self.assertEqual(len(h.http.starts()), 1) + self.assertTrue(list_lookups(h)) + if opened: + self.assertTrue(h.http.sessions["sess-1"].get("interrupted")) + self.assertFalse(h.sent()) + + def test_topic_followup_waits_then_continues_in_recovered_session(self): + h = agent(self, timing=timing()) + h.http.probe_status = 503 + h.http.start_doubts = [("assistant_in_doubt", True)] + first = ask(h, "/agent 话题里的首条") + started(h) + wait_until(lambda: run_of(h, first).get("start_doubt", {}).get("at"), timeout=1.5, what="doubt") + second = follow_up(h, first, "/agent 问助手 接着说") + run_of(h, second) + time.sleep(0.08) + self.assertEqual(len(h.http.starts()), 1) + h.http.probe_status = 200 + run = running(h, second) + self.assertEqual(run["session_id"], "sess-1") + self.assertEqual(len(h.http.starts()), 1) + self.assertEqual(len(h.http.messages_to("mac-example", "sess-1")), 1) + + +class SendNetworkTest(unittest.TestCase): + def test_unknown_continuation_observes_delivery_and_relays_answer(self): + h = agent(self, timing=timing()) + first = ask(h, "/agent 开会话") + resolve(h, first) + h.http.send_outcomes = [(502, "internal", "unknown", True)] + second = follow_up(h, first, "/agent 问助手 再问一下") + resolve(h, second, text="续聊答案") + self.assertEqual(len(h.http.messages_to("mac-example", "sess-1")), 1) + + def test_unknown_or_later_continuation_times_out_without_resending(self): + for outcome in ((502, "internal", "unknown", False), (504, "timeout", "", False), + (202, "", "later", False)): + with self.subTest(outcome=outcome): + h = agent(self, timing=timing()) + first = ask(h, "/agent 开会话") + resolve(h, first) + h.http.send_outcomes = [outcome] + second = follow_up(h, first, "/agent 问助手 再问一下") + run = run_of(h, second) + wait_until(lambda: not h.http.send_outcomes, what="hub answered the send") + h.http.add("sess-1", "user", "tool_result", '"%s"' % run["id"], + client_msg_id="openmate-" + run["id"]) + h.http.add("sess-1", "user", "text", '"%s.2"' % run["id"]) + self.assertIn("可能稍后送达", settle(h, second, "failed")["error"]) + self.assertEqual(len(h.http.messages_to("mac-example", "sess-1")), 1) + + def test_unknown_forward_does_not_resend_when_seen(self): + h, first, _, sid = dispatched(self, timing=timing()) + h.http.send_outcomes = [(502, "internal", "unknown", True)] + forwarded(self, h, first, sid) + self.assertEqual(len(h.http.messages_to("mac-agent", "agent-1")), 1) + + def test_unknown_or_later_forward_times_out_without_fallback(self): + for outcome in ((502, "internal", "unknown", False), (202, "", "later", False)): + with self.subTest(outcome=outcome): + h, first, _, sid = dispatched(self, timing=timing()) + h.http.send_outcomes = [outcome] + second = follow_up(h, first, "/agent 转交给任务") + self.assertIn("可能稍后送达", settle(h, second, "failed")["error"]) + self.assertEqual(len(h.http.messages_to("mac-agent", "agent-1")), 1) + self.assertFalse(h.http.messages_to("mac-example", sid)) + + def test_only_marked_send_401_is_retried(self): + h = agent(self, timing=timing()) + first = ask(h, "/agent 开会话") + resolve(h, first) + h.http.send_auth = [True] + second = follow_up(h, first, "/agent 问助手 重试令牌") + run = running(h, second) + self.assertEqual(len(h.http.messages_to("mac-example", "sess-1")), 2) + self.assertEqual({p["body"]["client_msg_id"] for p in h.http.messages_to("mac-example", "sess-1")}, + {run["client_msg_id"]}) + h.http.send_auth = [False] + third = follow_up(h, first, "/agent 问助手 普通 401") + self.assertIn("令牌无效", settle(h, third, "failed")["error"]) + self.assertEqual(len(h.http.messages_to("mac-example", "sess-1")), 3)