feat: tool progress markers in stream bubble, transient model error auto-retry, friendly error text

This commit is contained in:
openbot committed 2026-10-06 22:17:15 +08:00
1 parent 1a25790d4a
commit 2bf6b76e15
3 files changed
+57 -2

No files matched your search

+13
View File
@@ -239,6 +239,14 @@ class WecomAibotChannel:
self._stream_append(chat_id, str(payload.get("text", ""))) self._stream_append(chat_id, str(payload.get("text", "")))
elif kind == "status": elif kind == "status":
self._stream_ensure(chat_id, str(payload.get("text", ""))) self._stream_ensure(chat_id, str(payload.get("text", "")))
elif kind == "tool_start":
# show agent progress inside the stream bubble so long tool turns
# don't look stuck
tool = str(payload.get("tool") or "")
cur = self._stream_current(chat_id)
marker = f"\n🔧 {tool}" if tool and (not cur or f"🔧 {tool}" not in cur) else ""
if marker:
self._stream_append(chat_id, marker)
elif kind == "interaction": elif kind == "interaction":
# approval / choice question: close current bubble with a # approval / choice question: close current bubble with a
# structured render; user replies in chat (M1: text-based choice) # structured render; user replies in chat (M1: text-based choice)
@@ -256,6 +264,11 @@ class WecomAibotChannel:
with self._stream_lock: with self._stream_lock:
return self._streams.setdefault(chat_id, {"req_id": uuid.uuid4().hex, "buf": "", "sent": False}) return self._streams.setdefault(chat_id, {"req_id": uuid.uuid4().hex, "buf": "", "sent": False})
def _stream_current(self, chat_id: str) -> str:
with self._stream_lock:
st = self._streams.get(chat_id)
return st["buf"] if st else ""
def _stream_ensure(self, chat_id: str, text: str) -> None: def _stream_ensure(self, chat_id: str, text: str) -> None:
st = self._stream_key_states(chat_id) st = self._stream_key_states(chat_id)
if not st["sent"]: if not st["sent"]:
+17 -1
View File
@@ -129,8 +129,9 @@ def _safe_inbound(mgr: SessionManager, ch, m) -> None:
except Exception as e: # noqa: BLE001 except Exception as e: # noqa: BLE001
import logging import logging
logging.getLogger("agenthub").error(f"[{ch.name}:{m.chat_id}] inbound failed: {e}") logging.getLogger("agenthub").error(f"[{ch.name}:{m.chat_id}] inbound failed: {e}")
friendly = _friendly_agent_error(str(e))
try: try:
mgr._emit(f"{ch.name}:{m.chat_id}", "final", {"text": f"出错了:{e}"}) mgr._emit(f"{ch.name}:{m.chat_id}", "final", {"text": friendly})
except Exception: # noqa: BLE001 except Exception: # noqa: BLE001
pass pass
@@ -139,6 +140,21 @@ def _safe_inbound(mgr: SessionManager, ch, m) -> None:
threading.Thread(target=run, name=f"inbound-{ch.name}-{m.chat_id}", daemon=True).start() threading.Thread(target=run, name=f"inbound-{ch.name}-{m.chat_id}", daemon=True).start()
def _friendly_agent_error(raw: str) -> str:
"""Translate agent/ACP errors into actionable chat text (keep original in logs)."""
low = raw.lower()
if "tool call delta is missing id or name" in low:
return (
"⚠️ 模型服务这次调用出了点问题(上游返回的工具调用流不完整,多为免费模型偶发)。\n"
"请重发一次消息;若反复出现,发 /model 列表换一个模型再试。"
)
if "session not found" in low:
return "⚠️ 会话已失效(服务重启或超时)。已自动重置,请重新发送消息。"
if "timeout waiting for" in low:
return "⚠️ 任务执行超时。任务可能还在后台继续,可稍后追问;或换个更简单的问法。"
return f"⚠️ 出错了:{raw}"
def _safe_event(ch, key: str, kind: str, payload: dict[str, Any]) -> None: def _safe_event(ch, key: str, kind: str, payload: dict[str, Any]) -> None:
try: try:
chat_id = key.split(":", 1)[1] chat_id = key.split(":", 1)[1]
+27 -1
View File
@@ -20,6 +20,7 @@ from __future__ import annotations
import fnmatch import fnmatch
import json import json
import logging
import os import os
import sqlite3 import sqlite3
import threading import threading
@@ -27,7 +28,9 @@ import time
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any, Callable from typing import Any, Callable
from .acp_client import ACPClient, ACPProcessDead from .acp_client import ACPClient, ACPError, ACPProcessDead
log = logging.getLogger("agenthub.sessions")
EventSink = Callable[[str, str, dict[str, Any]], None] # (binding_key, kind, payload) EventSink = Callable[[str, str, dict[str, Any]], None] # (binding_key, kind, payload)
@@ -83,6 +86,20 @@ class PermissionRequest:
choice: str | None = None # optionId chosen, None = timeout/deny choice: str | None = None # optionId chosen, None = timeout/deny
def _is_transient_model_error(msg: str) -> bool:
"""Upstream model-provider hiccups that a same-session retry usually fixes."""
low = msg.lower()
return any(s in low for s in (
"tool call delta is missing id or name",
"internal service failure",
"upstream error",
"rate limit",
"502",
"503",
"504",
))
def _gen_request_id() -> str: def _gen_request_id() -> str:
import uuid import uuid
@@ -373,6 +390,15 @@ class SessionManager:
with self._lock: with self._lock:
self._bindings.pop(k, None) self._bindings.pop(k, None)
raise SessionError(f"session crashed: {e}") from e raise SessionError(f"session crashed: {e}") from e
except ACPError as e:
# Transient upstream model glitches (incomplete tool-call stream)
# usually succeed on an immediate retry on the same session.
if _is_transient_model_error(str(e)):
log.warning(f"[{key}] transient model error, retrying once: {e}")
self._emit(key, "status", {"text": "模型返回异常,正在重试…"})
res = client.session_prompt(b.acp_session_id, blocks, timeout=timeout_s)
else:
raise
self._append_text(key, b.agent, b.acp_session_id, {"role": "assistant", "text": str(res.get("stopReason", ""))}) self._append_text(key, b.agent, b.acp_session_id, {"role": "assistant", "text": str(res.get("stopReason", ""))})
# turn terminal: final carries the accumulated text so channels without # turn terminal: final carries the accumulated text so channels without
# an edit API (wecom-app / weixin) can deliver the whole message # an edit API (wecom-app / weixin) can deliver the whole message