读 Octop 源码(9):Dashboard 其实是个「虚拟 IM 通道」

文章目录

前几篇一直在往上走:进程怎么起、Agent 怎么活、谁能碰谁的数据。这篇横向切一刀,读 infra/gateway/——13,857 行,第二大模块,负责所有消息的进出口。

打开 ws_channel.py 的第一行,我笑了:

"""Virtual IM channel that delivers Dashboard chat over WebSocket."""

Dashboard 不是"主入口",它是一个虚拟 IM 通道。 网页聊天的消息也要包成 InboundMessage、走和飞书完全相同的管道。

这句话是整个模块的设计前提,也是我读完之后最想写的一点。

版本锚点:本文基于 octop v1.0.2(commit dd9dce4),octop-gateway 1.0.3。infra/gateway/ 共 13,857 行,其中平台适配的绝大部分不在本仓库——这点后面会讲。

环境准备

这个模块涉及三张表,先看清它们的关系再读代码。

三张表的分工:

sqlite3 .home/.octop/octop.db ".schema sessions"
sqlite3 .home/.octop/octop.db ".schema threads"
  • sessions:session_key → thread_id 的当前绑定,外加未读数、channel 元数据
  • threads:对话本体的元信息,标题、置顶、上次活跃、composer 状态
  • thread_messages:具体消息(这个由 harness 侧的 checkpoint 管,不是这里)

关键在 sessions 和 threads 是 N:1:

# 一个 thread 被多少个 session 绑着(人工验证 N:1)
sqlite3 .home/.octop/octop.db \
  "select thread_id, count(*) c from sessions group by thread_id having c > 1 limit 5;"

看当前的会话键长什么样:

sqlite3 .home/.octop/octop.db "select session_key, channel_type, chat_type from sessions limit 10;"

会长这样:

aaaaa:dashboard:1:dm          | dashboard | dm
aaaaa:cli:1:dm                | cli       | dm
hello:feishu:ou_xxx:dm        | feishu    | dm

四个冒号分段,最后那段是"聊天类型"。这个键的生成规则是下一篇一切讨论的基础。

流程

一、Dashboard 就是一个虚拟 IM 通道

Gateway.boot() 的顺序很说明问题:

self._channel_manager = ChannelManager(channels={})
self._channel_manager.set_pre_lock_handler(self._preempt_cancel_on_stop)
await self._channel_manager.start()

self._ws_channel = WebSocketChannel(self._processor, hub=self._ws_hub,
                                    steer=self._steer, channel_id=WS_CHANNEL_ID)
await self._channel_manager.add_channel(self._ws_channel)

self._cli_channel = CliChannel(self._processor, hub=self._cli_hub,
                                channel_id=CLI_CHANNEL_ID)
await self._channel_manager.add_channel(self._cli_channel)

rows = self._repos.channel_repo.list_all(include_disabled=False)
if rows:
    await asyncio.gather(*(self._safe_register_channel(row) for row in rows))

空的管理器先起来,然后先挂两个内存通道(WS、CLI),再从数据库并发加载 IM 通道。三类东西在同一个 ChannelManager 里平起平坐。

三个通道都实现同一个 BaseChannel 接口,都吃同一个 InboundMessage:

from octop_gateway.channel import BaseChannel, MessageProcessor
from octop_gateway.models import (
    AudioContent, ChannelSubject, ContentPart, FileContent,
    ImageContent, InboundMessage, TextContent, VideoContent,
)

所以"三端一致"不是三个 if 分支写得一致,是三个入口真的走同一套抽象。 这个区别很大:前者靠自觉维护,后者是编译期就一致的。

代价也真实:Dashboard 从此要背 IM 的全部约束。 你在网页聊天里看到消息被切成好几段发出来、看到"正在输入"状态、看到超时 180 秒的回复保护——那些都是为 IM 设计的,网页本来不需要。

refresh_media_backends() 的注释还暴露了一个顺序坑:

Called after agents finish booting (gateway boots before agents) to resolve the startup ordering gap.

gateway 比 agent 先启动(第一篇讲过 _boot_runtime 里的顺序),所以媒体后端要等 agent 就绪后再回填一遍。单进程装配顺序不是随便排的。

二、三张表和一个键

会话键格式写在一行里:

@staticmethod
def make_key(*, agent_id, channel_type, channel_subject_id, channel_chat_type=CHAT_TYPE_DM) -> str:
    """Globally unique session key: agent:channel:subject:chat_type."""
    return f"{agent_id}:{channel_type}:{channel_subject_id}:{channel_chat_type}"

chat_type 有四种取值,前两种是常规的,后两种是内部用的:

chat_type含义生成方
dm私聊dashboard_key() / cli_key() / IM 默认
group群聊IM 平台元数据
peer:<room_id>对等 Agent 调用peer_room_session_key()
team:<room_id>团队协作房间同上,group=True
call-<call_id>外部 MCP 会话mcp_key()

thread_id 和 session_key 的关系是 N:1,这点在代码里几个方法上体现得最清楚:

def sessions_for_thread(self, thread_id: str) -> list[SessionRow]:
    """Return every session still bound to *thread_id*."""
    return self._sessions.list_by_thread(tid)

rebind() 允许把一个 session 重新指到另一个 thread——「继续之前那段对话」就是调这个。所以:

thread 是对话本体,session_key 是"从哪个门进来的"。 同一个对话可以从网页、从 CLI、从飞书进来,被三个 session 指向。

这也解释了为什么第 5 篇那个 _thread_execution_lock(agent_id, thread_id) 锁的粒度是 thread 不是 session——并发冲突发生在对话本体上,不在入口上。

有个防御写得很细,值得单独拎出来:

def get_bound_thread_id(self, session_key: str) -> str | None:
    """Return the live thread bound to *session_key*, or None when unbound.

    A session whose thread was deleted reads as unbound so callers fall
    back to the create path instead of writing turns to a dead thread.
    """
    row = self._sessions.get(session_key)
    if row is None or self._threads.get(row.thread_id) is None:
        return None
    return row.thread_id

“绑着一个已删除的 thread"要读作 unbound,不能返回死 id。 不做这个检查,用户删了对话之后发下一句,消息会写进一个不存在的 thread——要么报错,要么更糟,悄悄写丢。

get_or_create 那边是标准的双重检查(锁外查一次、锁内再查一次),没什么好展开的。

三、会话键里埋着三个坑

这个键看着简单,实际有三处需要额外处理。

坑一:对等调用会撞车。 peer_session_key() 只是把 agent 段替换掉:

def peer_session_key(source_session_key: str, agent_id: str) -> str | None:
    """Rewrite the agent segment of a session key; keep channel / subject / chat type."""
    parts = source_session_key.split(":", 3)
    ...
    return ThreadRegistry.make_key(agent_id=agent_id, channel_type=channel_type,
                                   channel_subject_id=subject_id, channel_chat_type=chat_type)

问题来了:A 调用 B,生成的键是 B:dashboard:1:dm——和 B 自己的 1:1 私聊键一模一样。A 的提问会混进 B 的个人对话历史里。

所以还有第二个函数:

def peer_room_session_key(source_session_key, agent_id, *, room_thread_id, group) -> str | None:
    """Session for a peer thread that must not collide with the callee's 1:1 DM."""
    kind = "team" if group else "peer"
    return ThreadRegistry.make_key(..., channel_chat_type=f"{kind}:{room}")

把 room_id 塞进 chat_type 段,用掉的还是那四段格式,但第四段变成 peer:<room>。这样 A 和 B 的每一次跨 Agent 协作,在 B 那边都是独立的一条会话,不会污染 B 的个人 DM。

注释就一句 “must not collide with the callee’s 1:1 DM”,但它指出的是一个很容易踩的设计陷阱:键空间的设计要考虑"同一对实体之间可能有多种关系”。

坑二:IM 里的"用户"是塌缩的。 这段 docstring 我读了两遍:

def resolve_user_id_for_message(msg: InboundMessage, *, agent_owner_id: int | None) -> int:
    """Resolve Octop ``users.id`` for thread/session persistence.

    Dashboard and CLI use numeric ``subject_id`` values as Octop user ids.
    External IM subject ids belong to a platform-specific identity domain and
    may also be numeric, so those sessions always belong to the agent owner.
    Browser cookies follow this same id (``user-<id>``): IM members of one
    agent share the owner's profile, they are not isolated from each other.
    """

翻译关键最后一句:同一个 Agent 的多个 IM 成员,共享 owner 的 profile,彼此之间不隔离。

原因也说了:飞书的 ou_xxx、微信的 openid 都是平台自己的身份域,可能恰好也是数字,直接当 Octop 的 user_id 会撞。所以 IM 会话的 user_id 统一取 Agent 的所有者。

后果是:十个人在同一个企业微信群里用同一个 Agent,他们在 Octop 眼里是同一个人。第 8 篇说的"行级归属"在这种情况下不起作用——因为根本只有一个用户。这是设计取舍,不是 bug,但用的时候必须知道。

坑三:平台字段根本不统一。 sanitize_im_metadata() 用了白名单 + 黑名单双重过滤:

_PERSISTED_META_KEYS = (
    "msg_type", "message_type", "chat_type", "chat_id", "chatid",
    "conversation_id", "user_openid", "group_openid", "to_handle",
    "event_type", "guild_id", "channel_id_native", "group_id",
    "account_id", "from_user_id", "ilink_user_id",
    "ws_connection_id", "session_id", "task_id",
)

这 19 个字段名就是一张平台清单:user_openid / group_openid(微信)、to_handle(飞书)、guild_id(Discord)、ilink_user_id(企业微信)、event_type(钉钉)。

然后还有黑名单,剥掉一次性的:

_EPHEMERAL_SESSION_META = frozenset({"msg_id", "message_id", "_frame", "_ws_client",
                                      "response_url", "context_token", "webhook_url"})

顺手做了两个归一化:chatid → chat_id(微信拼写),chat_type == "single" → dm(有平台把私聊叫 single)。

“白名单取值 + 黑名单剔除 + 别名归一”,这是处理多平台字段差异的标准配方,比到处写 if platform == "weixin" 好太多。

四、群聊不是每句话都算输入

这是我认为整个模块里产品思考最密集的一块。群聊场景有个根本问题:bot 在群里看到的消息,哪些算"用户在跟我说话"?

octop-gateway 里把它拆成两个正交的维度:

class GroupVisibility(StrEnum):
    """Group messages that the platform is expected to expose to the bot."""
    AUTO = "auto"
    ALL = "all"
    MENTION_RECENT = "mention_recent"
    MENTION_ONLY = "mention_only"

class GroupActivation(StrEnum):
    """When a visible group message starts an agent turn."""
    MENTION = "mention"
    ALWAYS = "always"

class GroupHistoryMode(StrEnum):
    """Whether passive group chatter is attached to the next agent turn."""
    RECENT = "recent"
    NONE = "none"
  • visibility 是"平台愿意给我看多少"(有些平台不 @ 就根本不推消息,这是平台能力,不是选择)
  • activation 是"看到的这些里,哪些触发一轮对话"
  • history 是"没触发对话的闲聊,要不要作为上下文挂到下一轮"

三者分开的好处是能表达"能看到全部、只在 @ 我时回复、但把前面的聊天记录当上下文“这种真实需求。合成一个开关就表达不出来。

默认策略也定了边界:

@dataclass(frozen=True)
class GroupContextPolicy:
    enabled: bool = False
    visibility: GroupVisibility = GroupVisibility.AUTO
    activation: GroupActivation = GroupActivation.MENTION
    history: GroupHistoryMode = GroupHistoryMode.RECENT
    history_limit: int = 10
    history_ttl_seconds: float = 300.0
    clear_after_reply: bool = True

默认只在被 @ 时回复、最多挂 10 条历史、300 秒过期、回完就清。

history_ttl_seconds=300 和 clear_after_reply=True 这两个默认值,是被成本教出来的。 不留 TTL,一个活跃群的上下文会越滚越大,每轮都把这堆闲聊塞进 prompt,token 直接烧穿。第 8 篇讲过 token_quota 是终身累计——这两个设置其实是在保护那个配额。

五、“中途插话"为什么要做成八状态机

steer 这个目录 890 行,做的事情一句话能说完:用户在 Agent 正在回答时又发了一条消息,怎么办?

不是简单排队,也不能简单打断。types.py 里第一行就引了 issue 号:

"""Mid-turn steering types (issue #1300 soft boundary-drain)."""

答案是"软边界排空”——记下来,等当前这一步跑完再插进去。为此定义了 8 个状态:

TurnPhase = Literal[
    "streaming_text", "awaiting_tools", "between_model_steps",
    "hitl_paused", "cancelling", "compacting", "terminal", "idle",
]

因为"能不能插"完全取决于现在在哪个阶段。streaming_text 时插进去,用户看到的就是话说到一半被打断;between_model_steps 插进去最自然;hitl_paused 时要先把插话"寄存"起来。

拒绝原因分成两组,看得出打磨的细致程度:

GatewayRejectReason = Literal[
    "client_pending_id_required", "empty_input", "input_too_large", "forbidden",
]
HarnessRejectReason = Literal[
    "no_active_turn", "expected_turn_id_required", "expected_turn_id_mismatch",
    "turn_not_steerable", "turn_already_cancelled", "turn_active",
    "queue_full", "hitl_paused",
]

网关层拒绝是"你的请求有问题”,harness 层拒绝是"现在不行"。 分开的好处是前端能给出不同的话术——前者让用户改输入,后者让用户等一会儿。

还有个常量值得注意:

STEER_DEPTH_CAP = 8
STEER_CONTINUATION_CAP = 8
HITL_PARK_TTL_SECONDS = 30 * 60

STEER_DEPTH_CAP = 8 意思是插话最多嵌套 8 层。不做这个限制,用户疯狂连发能把一轮对话无限延长,最后变成 token 炸弹。HITL 暂停期间寄存的插话 30 分钟清掉,因为审批可能永远不来。

六、广播模型:一个对话,多个窗口

ws/ 目录一共 765 行,其中 ws_hub.py 只有 167 行——核心就是一张 thread_id → connection_id 集合 的表:

def subscribe(self, thread_id: str, connection_id: str) -> None: ...
def unsubscribe_connection(self, connection_id: str) -> None: ...
async def push(self, connection_id: str, frame: dict[str, Any]) -> None: ...
async def push_to_thread(self, thread_id: str, frame: dict[str, Any]) -> None: ...
async def push_to_user(self, user_id: int, frame: dict[str, Any]) -> None: ...

三个推送目标各有用处:push 精确到连接,push_to_thread 广播给所有在看这段对话的窗口,push_to_user 给某个人的所有连接——比如"你有新消息"这类通知。

连接和订阅是分开的,所以一个人可以同时在手机、电脑、平板上打开同一个 thread,三个窗口同步看 Agent 打字。这也解释了为什么 ws.py 里那段注释说"Keep forwarding after host turn.ended. Member tokens use this same subscriber; handing the room to a second listen drops them."——多端订阅时不能因为第一个看的人走了就换订阅者,否则其他人的流会断。

七、IM 的脏活都藏在 constraints.py 里

octop_gateway/constraints.py 里有三个类,名字就是三个真实痛点:

class RateLimiter: ...
class ReplyTimeoutGuard: ...
class TypingKeepalive: ...
  • RateLimiter:平台有发送频率限制,超了会封。企业微信的主动消息额度尤其紧。
  • ReplyTimeoutGuard:IM 平台对"被动回复"有硬超时,超了这条消息就发不出去。所以 AI 回答太慢时必须有兜底话术,不能干等。
  • TypingKeepalive:一直显示"正在输入",否则用户以为机器人死了。

这三个问题网页端一个都没有。但因为 Dashboard 是虚拟 IM 通道,它被一起继承了——这也回答了第一节留的那个问题:代价是什么。

还有一个微信特有的坑,代码里处理得很直接:

def session_metadata_from_message(msg: InboundMessage) -> dict[str, object]:
    """Durable routing fields for a session row.

    ``context_token`` stays ephemeral for every channel. WeChat also keeps a
    separate copy so a later cron push can still address the conversation.
    """
    meta = sanitize_im_metadata(msg)
    if (msg.channel_type or "") != "weixin":
        return meta
    token = str((msg.metadata or {}).get("context_token") or "").strip()
    if not token:
        return meta
    return with_weixin_send_token(meta, token, int(time.time() * 1000))

微信公众号的"被动回复"必须带 context_token,而这个 token 是跟着上一条用户消息来的。所以要"定时主动推送"就必须把这个 token 存下来,否则过一段时间就再也发不出去了。

这是平台生态的硬约束,不是设计选择。看到这种代码就知道作者被微信坑过。

八、平台适配一行都不在本仓库

最后说个我没想到的:src/octop/infra/gateway/channels/ 只有 194 行,而且两个文件干的事情完全不是适配——

  • dingtalk_registration.py:钉钉 Device Flow,一键创建应用(扫个码自动建机器人)
  • qr_bind.py:企业微信 / 微信扫码绑定

真正的平台适配在 octop_gateway/channels/ 里,装完依赖才看得到:

平台行数
飞书 feishu.py1,313
钉钉 dingtalk.py817
企业微信 wecom.py711
Discord discord.py443
MQTT mqtt.py286
另有 qq/ weixin/ telegram/ xiaoyi/ yuanbao/ 子目录—
合计3,755

加上第一篇算过的 octop-gateway 总共 16,047 行——这个项目最脏最累的活(和一堆国内 IM 平台对接),被完整地关在一个独立发布的库里。 主仓库只保留了"怎么让用户轻松创建机器人"这部分(扫码、Device Flow),因为这属于产品体验,不属于协议适配。

这个边界划得相当清醒:协议会变、平台会加,但产品体验的代码不该跟着一起改。

总结

infra/gateway 读完,五条我认为最该记住的:

  1. Dashboard 是虚拟 IM 通道,不是特殊入口。 ws_channel.py 第一行就写着。三类通道都实现 BaseChannel、都吃 InboundMessage,所以"三端一致"是抽象带来的,不是三份代码写得像。代价是网页要背 IM 的全部约束(限流、被动回复超时、正在输入)。
  2. session_key 是入口标识,thread_id 是对话本体,两者 N:1。 一个对话可以被网页、CLI、飞书三个 session 同时指向。这也解释了执行锁为什么按 thread 而不是 session 加。
  3. 会话键里埋着三个坑,每个都有对应补丁。 跨 Agent 调用会和被调方的私聊撞车(用 peer:<room> 规避);IM 成员共享 owner 身份、彼此不隔离(resolve_user_id_for_message 的 docstring 明说了);平台字段名完全不统一(19 项白名单 + 黑名单 + 别名归一)。
  4. 群聊拆成 visibility / activation / history 三个正交维度。 默认只在 @ 时回复、最多挂 10 条历史、300 秒过期、回完就清——后两个默认值是在防 token 烧穿。
  5. “中途插话"是八状态机,不是队列。 TurnPhase 8 个状态决定能不能插,拒绝原因分网关层(请求有问题)和 harness 层(现在不行)两组,STEER_DEPTH_CAP=8 防无限嵌套。

加一条关于边界划分的:3,755 行平台适配全在 octop-gateway 库里,主仓库只留 194 行"怎么让用户一键创建机器人”。 协议归协议,体验归体验。

到这里九篇齐了。按编号 1→9 的完整顺序是:全景地图、数据层、配置与引导、中间件、Agent 运行时、对话链路、扩展层、多用户隔离、IM 通道。再往里就是 octop-harness 本体了——那块已经不在这个仓库,值得另起一个系列。

参考链接