Skip to content

feat(session): 新增只读结构化会话轮次接口 - #3597

Merged
deepcoldy merged 9 commits into
deepcoldy:masterfrom
tongyihao1233:feat/session-turns
Nov 20, 2026
Merged

deepcoldy merged 9 commits into
deepcoldy:masterfrom
tongyihao1233:feat/session-turns

Conversation

@tongyihao1233

@tongyihao1233 tongyihao1233 commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Refs #3595

改动

  • 两步中的第一步。新增仅本机 Dashboard 管理员令牌可读的 GET /api/sessions/:sessionId/turns,返回 botmux.session-turns.v1。能力列表为空,owner actor 留在第二步。
  • 在入站解析和提示渲染附近收集结构化消息,在 CLI 投递后记录锚点,在 botmux send 成功后追加回执。游标按更新序号推进,迟到回复会重新返回同一轮的快照。
  • 记录跨进程重启保留,关闭会话清空。同一个 session ID 重新启用后从新轮次开始,序号继续递增。部署前的轮次不回填。
  • 影响面为飞书话题和群的 CLI 提示、现有 trigger 输入、发送回执、会话清理和 Dashboard 只读路由。入站附件只保留元数据。标准 Markdown 复用发送时已有的文本。自定义卡片、附件正文及完整的全文归档接口递延。

验证

  • bun run build(含 typecheck 和公开域名审计)通过。仓库没有独立 lint 脚本,git diff --check 通过。
  • 轮次、Dashboard 门禁、Codex 输入相关及 daemon IPC 定向测试 426 通过、3 跳过。覆盖话题和群、Claude Code/Codex 锚点投影、合并、迟到回执、关闭后重新启用、存储重开、游标和身份拒绝。未调用真实飞书。
  • 复核使用真实 SQLite 复现了关闭与迟到写入交叠、原生锚点先于投递回执、输入哈希回到先前值等场景。增加回归用例验证关闭栅栏、重启补清理和追加序号。
  • 本地全量单测有环境失败。干净基线已复现同组 18 项,其中包括本机 Git 2.20 不支持 git init -b。以 PR CI 为准。

待维护者确认

  1. 关闭会话后的保留期应该多长?本 PR 暂定随关闭清理,关闭后保留期为零。
  2. 回复全文应在哪一步补齐?本 PR 记录发送时已经可用的 Markdown 或纯文本。自定义卡片、附件正文和其他无法直接取得的全文暂留后续增量,这些回复仍提供回执元数据。

最新验证

- turns.sqlite 改用 WAL + busy_timeout 3000ms,与 session-store 等跨进程
  存储对齐:多进程饱和竞争下复现过 SQLITE_BUSY 逃逸(DELETE 日志 + 500ms),
  WAL 下同负载对照零错误,读不再阻塞写
- reactivateClosedSession 的 resumeSessionTurns 包 try/catch,与其余所有
  调用点一致:损坏/锁故障的只读旁路存储不再阻断会话重开(NOTADB 探针复现)
- 补两条回归用例,摘除守卫均咬红

Co-Authored-By: Claude Fable 5 <[email protected]>
@deepcoldy

Copy link
Copy Markdown
Owner

自动评审初步意见(首审)

整体评价:这是「结构化会话轮次」两步计划的第一步,只读接口 + 事件溯源式 SQLite 存储,设计克制(capabilities 为空、owner actor 留第二步),鉴权边界 fail-closed,测试覆盖了合并、迟到回执、关闭栅栏、重启补清理、游标和身份拒绝等关键行为。以下两处 P2 已按仓库约定直接追加修复到本分支(commit 3b594cd9f6,未改动作者原有提交、非 force-push),最终以维护者审阅为准。

P2-1:turns.sqlite 未启用 WAL,busy_timeout 仅 500ms

src/services/session-turns.ts 的 accessTurns 使用默认 DELETE 日志模式 + 500ms busy_timeout,而本仓库所有跨进程 SQLite 存储(session-store、output-delivery-journal、final-output-handoff-store、grant-state-store、group-context-store)统一是 WAL + 3000/5000ms。该库被 daemon、worker、dashboard 三方进程并发打开。

探针证据(bun 引擎、fenced 环境、2 写者各 50 轮 + 1 读者):

  • 修复前:修正后的 harness 下 3 轮中 1 轮有写者逃逸 SQLITE_BUSY(更早的同 turnId 高强度竞争下读者也报过 BUSY);DELETE 模式下读者与写者互相阻塞。
  • 修复后(WAL + 3000ms):4 轮全部进程退出码 0、零 BUSY,交错读者能读到全部 100 个轮次、游标正常推进;库头持久化为 journal_mode=wal。
  • 附带收益:WAL 消除了每条入站消息在受理热路径上的 DELETE 模式 fsync 开销。

P2-2:reactivateClosedSession 中 resumeSessionTurns 无异常保护

其余所有调用点(closeSession、daemon/worker/trigger 的写入包装)都对该旁路存储做了 try/catch best-effort,唯独 session-store.ts 的重开路径直接调用。用损坏库探针实测:resumeSessionTurns 对 NOTADB 直接抛 SQLITE_NOTADB,会让整个会话重开失败——一个非关键只读存储的磁盘故障会永久阻断用户重开会话(只能手工删库)。已包上 try/catch + warn,与关闭路径对齐。

修复与验证

  • 改动:两处 pragma(busy_timeout=3000、写连接 journal_mode=WAL)+ 一处 try/catch,共 2 个 src 文件;新增 2 条回归测试。
  • 变异复验:摘除 WAL 行 → WAL 用例咬红;摘除 try/catch → 损坏库重开用例咬红;其余 190 用例保持绿。
  • 本地定向:vitest 221 通过(session-turns / session-store / queue-merge / receipt-wiring 等),bun 引擎单文件 7 通过,bun run build 通过。

不阻断的观察项(供后续增量参考)

  1. events 表对永不关闭的长会话无上限/TTL 增长(PR 描述的待确认问题 1 已涉及保留期)。
  2. publicMessageText 的路径脱敏对全角冒号等非空白引导符后的本地路径不覆盖;密钥类仍由 safeScrubAndTruncate 兜底,属 best-effort 第二层。
  3. 跨 daemon 任务群 kickoff(bot 发送方)、定时/本地轮次未入读模型,与 PR 声明的入站范围一致;无 inbound 时记录侧静默跳过,不报错。
  4. pendingStructuredOpeningTurnId 为内存态,daemon 在受理后、worker init 前崩溃的窄窗口里,折叠缓冲开场的后续消息不会进入读模型。

另外:评审前已在本地基于最新 origin/master 做过 rebase 核对(无冲突),该 rebase 仅用于本地评审,未推送到作者远端。

- events 表新增按整轮(turn_id)粒度的单会话上限(默认 2000 条)与 TTL(默认 7 天)增量裁剪,写入时按需触发:优先淘汰已过期或最旧的已完成轮次,保护当前/最新及未完成活跃轮次,同步清理对应 pending_inbound / pending_native,保持 seq 游标单调递增与读模型一致
- publicMessageText 扩展本地路径匹配边界,覆盖全角/半角冒号、等号、中英文括号与引号等非空白引导符后的本地路径与 Windows 盘符路径,同时保留闭合标点且不误伤 http/https 等协议 URL
- 补齐单测覆盖上限/TTL 裁剪、活跃轮次保护、游标分页单调性、关闭重开一致性及路径脱敏正反例
@tongyihao1233

Copy link
Copy Markdown
Contributor Author

已基于 3b594cd9f6 补充处理评论中的第 1、2 条观察项(commit ee1a218fdd):

  1. events 表长会话上限与 TTL 裁剪:在 src/services/session-turns.ts 写入路径(recordSessionTurnInput / updateSessionTurnNativeAnchor / recordSessionTurnReply)按需执行按整轮(turn_id)粒度的增量裁剪(默认单会话上限 2000 条事件 + 7 天 TTL):
    • 先按 TTL 淘汰过期未活跃整轮,再在超上限时优先按最旧活动顺序淘汰已完成轮次(含 reply:final:%),保护当前写入、最新及未完成活跃轮次;仅在未完成轮次本身仍超上限时兜底裁剪最旧非保护轮次。
    • 同步清理被淘汰轮次的 pending_inbound / pending_native,并在 reconcileClosedSessionTurns 合并扫描三张表;借助 AUTOINCREMENT 与整轮删除保持 seq 游标单调递增、读模型完整及关闭/重开一致。
  2. publicMessageText 非空白引导符路径脱敏:扩展本地路径匹配边界,覆盖全角/半角冒号(:/:)、等号(=)及中英文括号/引号((、[、「、【、"、' 等)后紧跟的本地路径与 Windows 盘符路径,同时保留闭合标点且不误伤 http:// / https:// / ssh:// / s3:// 等协议 URL。

本地验证

  • bunx vitest run test/session-turns.test.ts test/worker-queue-merge.test.ts test/worker-ordinary-im-receipt-wiring.test.ts test/session-store-sqlite.test.ts test/test-hygiene.test.ts:108/108 通过(含新增 3 条定向回归用例)
  • bunx vitest run test/session-store.test.ts -t "session-turns|reactivateClosedSession|corrupt|closeSession":47/47 通过
  • bun test test/session-turns.test.ts test/worker-queue-merge.test.ts test/worker-ordinary-im-receipt-wiring.test.ts:39/39 通过
  • bun run build:通过

@deepcoldy deepcoldy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复审结论(head ee1a218fdd71)

发现 3 个 P2,均有实际探针复现;前两处会让已经执行的用户消息在只读轮次接口中永久漏记,第三处使新增的事件硬上限在单轮次会话中失效。

1. P2 — deferred submit 确认成功后没有补记轮次输入

位置:src/worker.ts:24637、src/worker.ts:22633-22669

正常写入只有在 result?.submitted !== false 时才调用 recordStructuredInput。当 Codex 的 3.2 秒 in-band history 轮询未命中、返回 { submitted: false, recheck } 后,后续 scheduleSubmitFailureNotify 的 suppress-confirmed 分支只补 acknowledgeNativeInputConsumed / onConfirmed,没有调用 recordStructuredInput。而 updateSessionTurnNativeAnchor 在没有既有 anchor 时只写 pending_native,读接口又要求存在 input:* 事件,因此该轮次始终不可见;后续回执也无法让它出现在快照中。

探针:复用真实 worker + fake Codex 的 lazy-rollout 夹具,让 history 延迟 6 秒,确保只有 deferred recheck 能看到提交。探针中 CLI final、native_input_consumed 和 cli_session_id 均正常产生,但 readSessionTurns(...).turns 为 []。

建议在 deferred 确认成功路径补记当时准备好的 submittedText 与 structuredSourceTurnIds(不要改用 logicalMsg,Codex 准备阶段可能追加 correlation marker),并覆盖 observeQueuedActivationReceipt 这条独立确认通道;可用上述现有 integration 夹具加读模型断言。

2. P2 — opening activation 合并多条缓冲消息时只保留最后一条 inbound

位置:src/daemon.ts:22667-22721

releaseQueuedActivationReservationNow 把 pendingFollowUps 合成一个 CLI turn,并用 bufferedTurnIds 的最后一只作为 turnId,但这里既没有像 buildReservedInitialInput 那样调用 mergeStagedSessionTurnInputs,也没有把来源 ID 传到 worker。worker 最终只按最后的 turnId 读取 pending_inbound,所以同一次执行中的较早消息不会进入该轮次的 inbound。

探针:在现有 R7 coalesced-serial (two buffered) 场景中,实际 worker IPC 的 content 同时包含 BUFFERED_ONE / BUFFERED_TWO,但 structuredSourceTurnIds 为 undefined;按当前 worker 的默认来源解析只会载入 om_buf_2。

最简修法是在 durable admission 前把 bufferedTurnIds 预合并到最后一只 turn 的 staged payload(也可完整贯穿 CliTurnPayload / queued tail / worker IPC 的来源 ID 字段)。回归测试应验证实际读模型包含两条 inbound,而不只验证合并后的 prompt 文本。

3. P2 — 单轮次会话完全绕过事件数硬上限

位置:src/services/session-turns.ts:166

pruneSessionEvents 在 turns.length <= 1 时直接返回,因此一个长期活跃、不断收到 progress/anchor 事件的 turn 可以无限增长,maxEventsPerSession 不会生效。第三阶段的“守住硬上限”也无法覆盖这种形状。

fenced Bun 探针:设置 maxEventsPerSession: 4,同一 turn 写入 1 条 inbound、1 条 anchor 和 6 条 progress 后,读回仍为 8 条事件(replyCount=6),超出上限没有被裁剪。

建议为保护中的最新轮次增加轮内裁剪策略(至少保留 input、最新 anchor 和最新回执快照),并增加“只有一个 turn、事件数超过 cap”的回归用例。

验证

  • 最新 head:bun run build 通过。
  • 最新 head:bun run test -- test/session-turns.test.ts test/session-store.test.ts,195 条通过。
  • 最新 head:bun test test/session-turns.test.ts test/worker-codex-instance.integration.test.ts,14 条通过。
  • WAL、重开兜底、dashboard 管理 token 门禁及 CLI 回执的既有定向测试均通过;上述 3 个场景是现有测试未覆盖的缺口。
  • 最新 CI 的 Node test (1/4..4/4) 及其余检查通过,但 bun-test (1/4) 中 worker-codex-instance.integration.test.ts 有一次 12 秒启动等待超时;同一 Bun 测试在本地方向重跑通过,建议重跑该 shard 确认是否为瞬时启动延迟。

- activation 合并多条缓冲消息时,先把各 bufferedTurnId 的 staged inbound
  合并进最后归属 turnId 再持久化,避免读模型只剩最后一条消息
- pruneSessionEvents 新增第四阶段轮内裁剪:单轮次会话超上限时删被取代的
  旧 anchor、较早 progress 与其他旧回执,始终保留全部 input、最新 anchor
  与最新回执,守住 maxEventsPerSession 硬上限
- 两条回归用例,摘除守卫均咬红(R7 two-buffered / 单轮次 cap=4)

Co-Authored-By: Claude Fable 5 <[email protected]>
@deepcoldy

Copy link
Copy Markdown
Owner

对复审 #pullrequestreview-5986202849 的独立复核与代修(head 4ca3a1700)

三条 P2 已逐条独立复现,全部成立。P2-2、P2-3 已在本分支追加修复(非 force-push,作者提交未动);P2-1 涉及 worker 提交确认状态机与懒加载集成夹具,交由 Kimi 接手。

P2-3 单轮次会话绕过事件硬上限 —— 已修复

复现:fenced Bun 探针,maxEventsPerSession: 4,单轮次写入 1 inbound + 1 anchor + 6 progress,修复前读回 8 事件(pruneSessionEvents 的 turns.length <= 1 早退使整段裁剪失效)。

修复(src/services/session-turns.ts):删除单轮次早退,新增第四阶段「轮内裁剪」——当受保护的当前/最新轮次无法整轮淘汰且仍超上限时,按顺序删除①被取代的旧 anchor ②较早的 progress 回执 ③其他旧回执;全部 input 事件、最新 anchor、最新回执永不删除(input 自身超上限时以此为底线)。探针复验:同场景裁剪后恰为 4 事件(1 input + 最新 anchor native-s2/entry-2 + 最新两条回执 r4/r5)。

P2-2 activation 合并消息丢失较早 inbound —— 已修复

代码确认:releaseQueuedActivationReservationNow 把 pendingFollowUps 合成一个 CLI turn、仅以最后一只 turnId 归属,既没有 mergeStagedSessionTurnInputs 也未贯穿来源 ID,worker 默认只载入最后一条 staged payload。

修复(src/daemon.ts):durable admission 前将 bufferedTurnIds 的 staged inbound 合并进归属 turnId,与 buildReservedInitialInput 的开场合并同一机制、同一 best-effort 容错。回归在现有 R7 coalesced-serial 夹具上补读模型断言:staging → release → 模拟 worker 默认解析(不带 source ids)→ 断言快照 inbound 与缓冲消息逐条一致;单消息用例同样通过。

P2-1 deferred 确认成功后整轮漏记 —— 待 Kimi 接手

代码确认两个缺口均存在:

  • scheduleSubmitFailureNotify 的 suppress-confirmed 分支只做 acknowledgeNativeInputConsumed(无 anchor 时仅落 pending_native)与 onConfirmed,没有 recordStructuredInput,而读接口要求存在 input:* 事件,该轮永久不可见;
  • observeQueuedActivationReceipt 的 onConfirmed 独立确认通道同样缺记录。

flushPending 调用点闭包内 submittedText、item.structuredSourceTurnIds 均可用。修复需覆盖两条确认通道、按评审建议补记准备好的 submittedText(非 logicalMsg,Codex 准备阶段可能追加 correlation marker),并用 lazy-rollout 集成夹具(history 延迟 6s)加读模型断言验证。

验证

  • 变异复验:摘除轮内裁剪 → 单轮次 cap 用例咬红;摘除 activation 合并 → 仅 R7 two-buffered 用例咬红(单消息用例保持绿,符合预期);其余 224 用例不受影响。
  • 定向:vitest 411 通过(session-turns / daemon-rename-route / session-store),Bun 引擎 session-turns 11 通过,bun run build 通过。
  • 上一轮的 WAL、重开兜底、门禁、回执链路测试保持绿。

- deferred submit 确认成功后按当时准备好的 submittedText 与来源 turnId 补记输入,避免整轮只落 pending_native 而不可见
- queued activation 独立 receipt watcher 走同一补记边界,保留 adapter 注入内容与正式 cliSessionId
- deferred 结果仅有 unproven candidate 时禁止继承旧 native thread,待 owned proof 再补锚
- 增加 history 延迟 6 秒的真实 worker 子进程读模型回归、真实 SQLite 锚点及可控 timer 用例;各条补记与回退守卫的变异均咬红

Co-Authored-By: Kimi Code <[email protected]>
@deepcoldy

Copy link
Copy Markdown
Owner

P2-1 已修复并追加提交 2642417de05d2a837eb02899d30ba4159ff51072(fast-forward,未改动既有提交)。

修复内容

  • src/worker.ts:正常写入被跳过、scheduleSubmitFailureNotify 后续确认成功时,按本次写入捕获的 submittedText 和 structuredSourceTurnIds 补记结构化输入;不使用可能丢失 adapter correlation marker 的 logicalMsg。
  • observeQueuedActivationReceipt 的独立确认通道执行同样补记。两条通道重复确认时沿用现有 input/anchor 去重。
  • 对抗探针额外复现了一个交叠问题:deferred 结果只有 unprovenCliSessionId 时,补记会回退绑定到旧 native thread。现已把该状态贯穿两条确认通道,此时保留 input hash 但不继承旧 session id,后续 owned proof 再通过 updateSessionTurnNativeAnchor 补齐。

回归与变异

  • lazy-rollout history 延迟 6 秒的真实 worker 子进程用例新增读模型断言:turn、inbound、正式 cliSessionId 和 inputSha256 均落库。
  • 独立 watcher 使用真实 receipt observer + 可控 timer,验证 prepared text、来源 turnId 和正式 session id。
  • 真实 SQLite 用例验证:默认路径仍继承既有 native id;unproven 路径不继承旧 id,owned proof 后补新 id。
  • 分别摘除 schedule 补记、watcher 补记、回退抑制、watcher candidate 传递、schedule candidate 传递,相关用例均咬红;变异后已恢复。

异常场景探针

  • 两条 deferred 通道在已有 old-native-thread 时,unproven 阶段均无 native id,后续 owned proof 补上 candidate-new-thread,input hash 不变、inbound 不重复。
  • recheck await 中 generation 换代:迟到确认不写 turn、不 ACK。
  • recheck await 中 close 并清理:迟到确认不复活记录。
  • false → throw → confirmed 周期确认:最终一条 input、一个 anchor、一次 ACK。
  • 普通 deferred 链与 activation watcher 同 tick 重复确认:仍只有一条 input、一个 anchor。
  • session-turns 写入异常不阻断 activation ACK。

实际验证

  • bun run build:通过。
  • 相关 10 个 vitest 文件(session-turns/session-store/daemon activation/worker receipts/lazy-rollout/submit confirmation/queue merge/Traex RPC):508/508 通过。
  • bun test test/session-turns.test.ts test/worker-ordinary-im-receipt-wiring.test.ts test/queued-activation-receipts.test.ts test/worker-submit-program-status.test.ts:41/41 通过。
  • 新 head CI 已触发,最终结果以 CI 为准。

@deepcoldy deepcoldy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

合并增量复审(head 9ba5e41d31415b751fe40859a3a3bdf66a2cca6e)

结论:未发现新的阻断问题,可以按 merge-standard 继续。

  • 合并双亲为 2642417de / 189f370dfc,tree 为 095f8c0a6d86140591ea78aaf4b65884d1e7e20b,与预测树一致;src/services/session-turns.ts 在合并前后未发生变化。
  • #3606(dispatch 个人工具):新增 consent/身份校验和 relay 分流不改变 daemon staging、worker 输入锚点或 CLI 回执归属。dispatch consent 的附加卡片不会作为用户任务输入进入轮次;目标会话仍沿既有 trigger/turn 身份接线。
  • #3631(限额快照):recordLimitedFailedTurn 只增加 terminalIdentityTurnIds 终态保护,作用于 failed-turn recovery,不改变轮次事件、游标或回执读写语义,未发现串扰。
  • 额外用真实 startOutboxWatcher + 宿主 cmdSend(provider mock)验证 sandbox relay:在正确的 worker/turn 身份绑定下,消息 id、response kind 和正文均写入宿主 turns.sqlite。未把“沙盒内直接访问共享 DB 不可达”误判为生产 relay 问题。

范围说明

提交图显示 2642417de 与 189f370dfc 的共同祖先是 f5e3b0485d,且 a1770e7d0c 不在 2642417de 的祖先链上。因此这次 merge 实际带入 29 个主干提交,不是文字中的 4 个;本次已按实际合并树检查所有 session-turns 相交文件,而不是只检查最后 4 个提交。

实际验证

  • CI run 44672488857:attempt=1,15/15 全绿,无重跑。
  • bun run build:通过。
  • PR / dispatch / recovery / CLI 28 文件:968/968。
  • 额外 CLI 回执交叉 6 文件:144/144。
  • event-dispatcher.test.ts:整文件复跑 757/757(首次并行混跑有一个慢插件 ACK 时序失败,隔离及整文件复跑均通过)。
  • Bun 按文件隔离运行:PR receipt 41、failed-turn recovery 66、限额终态 2、turn-cli-identity 87、dispatch consent 6 + 18、lazy-rollout 8,合计 228/228。
  • 工作树干净,未追加或修改提交。

@deepcoldy deepcoldy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

第二次合并增量复审(head 016eab3c7f196aec7ef1aadab703945993312767)

结论:合并增量未发现新的阻断问题,可以按 merge-standard 继续。

  • 合并双亲为 9ba5e41d3 / 411e9d032,tree 为 9ca25bbf5d0469e59ba53d5f9647d253e848b18c,与预测树一致;src/services/session-turns.ts 未因合并改变。
  • #3567 / WebTerminal 首次输入:dirty wire、协议回包和提交前拒绝均发生在 recordStructuredInput 之前,不会把未实际写入的输入记成已提交。onInputPrepared 仍捕获实际发送内容;submitGuard、steerable 和 WebTerminal 字段只影响准入。
  • #3635 / sandbox 叶子身份:收紧进程与叶子发布围栏不改变 input hash 的生成方式;native session 仍要求正式证明,和本 PR 的 unproven 不回退旧 thread 防线一致。
  • #3632 / credentialsSourceDir:只改变 hook/envelope 与 CLI home 的选择,worker 继续 hash 实际提交文本,未发现 staging 或回执归属变化。
  • #3610 / tmux outage:死 pane 与 backend loss 的拒绝、重排队路径不会提前生成锚点;恢复输入仍沿用 PendingCliInput 的来源 turnId。
  • harness 同时保留 WebTerminal 依赖解析与 recordStructuredInput / updateSessionTurnNativeAnchor 空绑定。#3642 的启动卡终态改动不涉及轮次读模型。

实际验证

  • CI run 44678382439:attempt=1,15/15 全绿,无重跑。
  • bun run build:通过。
  • PR + WebTerminal + sandbox + credential + tmux overlap 25 文件:1266/1266。
  • worker 输入准备相邻 5 文件:89/89。
  • 启动卡、rename、command-handler、dashboard 4 文件:914/914。
  • Bun 按文件隔离:PR receipt 41、WebTerminal input 175、raw input 21、credential source 39、lazy-rollout 8,合计 284/284。
  • 工作树干净,未追加或修改提交。

@tongyihao1233

Copy link
Copy Markdown
Contributor Author

@deepcoldy 你好,最新提交 016eab3c 合并主干后 15/15 项 CI 已全部通过且无冲突,目前处于等待 Review 状态,方便的时候麻烦复查合入,谢谢!

@deepcoldy deepcoldy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

非相邻豁免合并树背书(016eab3c7 + 881cc9608f)

认可该豁免合并树,可以按既定流程 squash-pr;落地树应等于 864efa9b2c57e58a201fcec4ac86b11fa5421936。

  • 独立执行指定 git merge-tree --write-tree --no-messages 881cc9608f 016eab3c7,输出与预测 tree 864efa9b 完全一致。
  • 在工作树临时生成同一合并结果,git write-tree 也等于 864efa9b;验证后已 merge --abort 恢复 016eab3c7,未保留 merge commit,作者分支未改动。
  • 合并后 hunk 位置与 PR 轮次接线无交叠;src/services/session-turns.ts 在 016eab3c7 与 864efa9b 之间逐字不变。
  • #3529:只影响 tmux socket/root 的兼容选择、持久化与恢复,不改变输入准备、提交确认或轮次事件。
  • #3634:只增加 Antigravity 限额历史、过期去重与恢复状态,不改变 turnId、input hash 或回执归属;与本 PR 的 failed-turn / native anchor 边界无串扰。

合成树验证

  • bun run build:通过。
  • PR + quota + tmux 21 文件:807/807。
  • Bun 隔离运行 session-turns / receipts / antigravity-ansi-usage-limit:53/53。
  • 016eab3c7 既有 CI run 44678382439:attempt=1,15/15 全绿,无重跑。

@deepcoldy
deepcoldy merged commit afea99e into deepcoldy:master Nov 20, 2026
15 checks passed
@deepcoldy

Copy link
Copy Markdown
Owner

已合并(squash,落地 afea99e4b),感谢作者的两轮快速跟进:

  • 首版保留期裁剪(maxEventsPerSession 默认 2000、7 天 TTL)与全角引导符路径脱敏两个方向都采纳了评审反馈
  • 配合完成 WAL/重开兜底、activation 合并、单轮次轮内裁剪、deferred 提交确认补记五处修复的验证
  • 落地树与 merge-tree(881cc9608, 016eab3c7) 预测树 864efa9b 逐字一致,session-turns 核心文件 patch-id 不变

未尽事项(不阻断,供后续增量):

  1. 跨 daemon 任务群 kickoff(bot 发送方)、定时/本地轮次暂不进入读模型,与本 PR 声明的 lark/trigger 入站范围一致,owner actor 能力在后续 PR 承接。
  2. pendingStructuredOpeningTurnId 为内存态,daemon 在受理后、worker init 前崩溃的窄窗口会丢折叠缓冲开场的后续消息,后续可考虑持久化。
  3. 路径脱敏是 best-effort 第二层,密钥类仍以 safeScrubAndTruncate 为权威兜底。

再次感谢贡献,欢迎继续参与。

deepcoldy pushed a commit to peiquan/botmux that referenced this pull request Nov 20, 2026
@github-actions

Copy link
Copy Markdown

🚀 Released in v3.59.23

chyroc pushed a commit to nwverse/persona that referenced this pull request Nov 26, 2026
… and send as owner (#10770)

Closes #10764
Implements #10874

Upstream BotMux support in deepcoldy/botmux#3597 (`GET /api/sessions/:id/turns`, `botmux.session-turns.v1`) and deepcoldy/botmux#3599 (`/api/trigger` top-level `actor: "owner"`) merged on 2026-11-20; older BotMux versions (before `3.59.23`) automatically fall back to wrapper parsing and external-event triggers with a one-line composer notice.

## What changed and why

Combines #10764 (wrapper and `botmux send` decoding) and #10874 (structured turn reads and owner-actor sending) into one PR so reading and sending ship together with automatic version detection and per-turn fallback.

- **Version auto-detection (read-only probe, cached per BotMux instance).** `server/internal/node/hostbotmux_turns.go` probes capabilities via read-only `GET /api/sessions/:id/turns` (never probing with a real message and never retrying a delivered turn). Results are cached per BotMux instance (dashboard loopback URL, token, and CLI binary file stamp, bounded by TTL) and re-probed after dashboard restart, token rotation, or CLI upgrade; `externalTriggerNotice` preserves the last known negative result for the same dashboard instance and CLI stamp across TTL expiry while the session list re-probes stale capabilities in the background. A `404` without `unknown_session` caches the older-BotMux fallback; a `200` with `schema: "botmux.session-turns.v1"` enables structured reads and checks `capabilities` for `ownerActor`.
- **Bounded, off-hot-path turn caching and live re-push.** `session.items` reads use a 200 ms budget (`botmuxTurnsReadTimeout`), live pushes read only the in-memory cache and refresh asynchronously (re-pushing changed items or whole folds when late or updated turns arrive), dashboard CLI refresh runs only on 401/403/redirect (not transport errors or caller cancellation), transport/non-OK/`unknown_session` errors back off, and the turn cache is bounded by idle expiry, an LRU session cap, and a per-session turn cap.
- **Structured turn reads first, wrapper parsing as per-turn fallback.** `server/internal/transcript/botmux_turns.go` and `server/internal/node/hostbotmux_turns.go` incrementally fetch `GET /api/sessions/:id/turns` by `seq` cursor and decorate only BotMux sessions (including offline BotMux transcripts). `ApplyBotmuxTurns` matches entry IDs (exact, then `#`-prefix) across all loaded user items before falling back to untruncated `anchor.inputSha256` (only when unambiguous and not anchored to another loaded entry). Page, fold-expand, and `after_seq` reads decorate through a bounded `File.TurnWindow` so reply-only slices keep their enclosing user anchor. Matched turns populate `Item.botmux` (inbound text, sender display name/type, attachment count and safe `attachment_meta`, thread placement, mentions, and full reply text including `--content-file` / `--card-file` replies) before `FoldWork` runs. Replies attach only to `botmux send` calls with a succeeded tool result (skipping running/errored/non-OK sends) via receipt `messageId` and structural shell parsing (`mvdan.cc/sh`, supporting multiple sends in one Bash call, media-only sends, and conservative rejection of unquoted shell expansions). Turns without a structured record and `404` older BotMux instances fall back per turn to wrapper and `botmux send` parsing (`server/internal/transcript/botmux.go`), leaving unknown trigger sources empty rather than fabricating Persona. `Item.text` stays untouched (full original text loadable on demand for **Original**); `openId` and `messageId` never leave the node.
- **Send as owner when supported.** When probed capabilities include `ownerActor`, `botmuxHost.Prompt` (`server/internal/node/hostbotmux.go`) pins `/api/trigger` to the probed dashboard base/token, sends top-level `actor: "owner"` with `target.kind: "turn"`, `botId`, and `sessionId` (without `envelope.payload` or `envelope.rawText`), and verifies the echoed `actor: "owner"` in the response. If an instance fails to echo `actor: "owner"`, no resend occurs and that negative state survives subsequent structured reads for the same dashboard instance until re-probe or restart.
- **Web UI and first-screen budget.** Keeps the persisted three-mode sidebar botmux chip (`decoded` → `botmux · raw` → `hidden`, sharing the legacy display key and reading narrow display state so the quick filter bar stays memoized across session pushes) and lazy-loaded Lark message/reply rendering. When `Session.botmux_external_trigger` is set (older BotMux before `3.59.23` or `ownerActor` absent; stored on `SessionHierarchy` to keep `Session` inside its 1,528-byte size class while emitting the same top-level `"botmux_external_trigger"` wire key), `AgentStatusLine` (lazy-loaded) renders a one-line notice under the composer recommending BotMux `3.59.23+`. Conditional composer notices (`AttentionNote`, `ConflictNote`, `FailureNote`, `StoppedAgentLine`, `CodexReadOnlyLine`) and `QueueStrip` are lazy-loaded to keep the first screen within `FIRST_SCREEN_BUDGET` without raising the budget.
- **Fixtures and docs.** `spec/fixtures/botmux/cases.json` retains all existing wrapper/send cases and adds synthetic `turns_cases` covering `botmux.session-turns.v1`, `ownerActor` present/absent, `cliEntryId` and `inputSha256` matching, `--content-file` / `--card-file` replies, mixed old/new turns with per-turn fallback, and `404` fallback. Updated `docs/protocol/protocol.md`, `docs/integrations/engines.md`, and `docs/web/web.md` to document the order: structured turns first, wrapper parsing as fallback.

## Verification

Verified at current PR head `538bc0852a` (merged with `upstream/main` `e8b934017f`):

- Conflict resolution in `538bc0852a`:
  - `docs/web/web.md` — kept the three-mode `botmux` quick-filter chip description and Hub visibility sync from this PR while incorporating the updated per-computer inventory switch location (`**botmux · On / Off** under machine Configuration, **Also show botmux sessions**`) from `upstream/main` (`#16205`).
- Earlier merge resolutions preserved (`d3ddd38dba`, `629d638d63`, `6901818d1c`):
  - `web/src/views/chat/ChatView.tsx` (`defaultManager` / `decisionLaterKey` kept without unused `alsoOpenText`), `web/src/views/chat/FailureNote.tsx` (`FailureNoteProps` controlled props + `failure-note-state.ts` split), `server/internal/proto/session_hierarchy.go` and `session_wire.go` (`View`/`SetView` + `BotmuxExternalTrigger`/`SetBotmuxExternalTrigger`, `hierarchyWireLayout`), and named wire types in `server/internal/proto/item.go` (`BotmuxKind`, `BotmuxSenderType`, `BotmuxAttachmentKind`, `MIMEType`).
- Go:
  - `cd server && go build ./...` — pass
  - `cd server && go test ./internal/proto/ ./internal/transcript/ -count=1` — pass (includes `TestSessionFitsItsSizeClass`, `TestSessionWireMatchesReflect`, `TestSessionViewWire`, `TestSessionBotmuxExternalTriggerWire`, `TestBotmuxFixtures`, `TestBotmuxParseAndFold`, `TestBotmuxTurnsFixtures`, `TestBotmuxInputHashRequiresCompatibleAnchor`, `TestBotmuxDecorateAndFoldSkipRunningAndErroredSends`, and `TurnWindow` tests)
  - `cd server && go test -run TestBotmux ./internal/node/ -count=1` — pass
  - `cd server && go test -run TestToolView ./internal/node/ -count=1` — pass (verifying `toolViews.attach` coexistence with `applyBotmuxTurns`)
  - `cd server && go vet ./internal/proto/ ./internal/transcript/ ./internal/node/` — clean
- Web:
  - `cd web && npx tsc -b && npm run lint` — pass
  - `cd web && npx vitest run src/lib/botmux-mode.test.ts src/lib/botmux.test.ts src/lib/agents-display.test.tsx src/views/chat/botmux-messages.test.tsx src/views/chat/FailureNote.test.tsx src/views/chat/FailureNote.controlled.test.tsx src/views/chat/CodexReadOnlyLine.test.tsx src/views/chat/StoppedAgentLine.test.tsx src/views/SidebarPagedTodo.test.tsx src/views/agents/HistoryBrowser.test.tsx src/startup-preload.test.ts src/views/chat/ToolViews.test.tsx src/lib/turns.test.ts src/views/chat/ChatView.*.test.tsx src/views/chat/SegmentView.*.test.tsx` — 43 files, 459 tests passed
  - `cd web && npm run build` — pass (`first screen en 479,102 B, ja 481,660 B, zh-Hans 479,766 B; 4,749 B left under FIRST_SCREEN_BUDGET (ja)`)
- Repo guards:
  - `git diff --check upstream/main..HEAD` — clean
  - `python3 scripts/privacy_check.py` and `python3 scripts/privacy_check.py --range upstream/main..HEAD` — pass (`privacy_check: clean (2 values checked)`)
  - `python3 scripts/test/test_doc_paths.py` (21 tests), `python3 scripts/test/test_doc_sections.py` (6 tests), `python3 scripts/test/test_doc_go_paths.py` (3 tests), `python3 scripts/test/test_doc_wire.py` (16 tests) — all pass
  - `python3 scripts/ci/web_font_ratchet.py` — pass (exit 0; `3213 hard-coded px font size(s) in the baseline, none above it`)
  - `python3 scripts/ci/wire_types_ratchet.py --base upstream/main` and `python3 scripts/ci/merge_wire_types.py --base upstream/main --head 538bc08` — pass (`none above the baseline`, `the merge adds no weak type`)
- Not run:
  - Full web test suite (`npm test`), Apple/Android/HarmonyOS/Desktop builds, and hosted CI (explicit-dispatch only).

## Apple performance

Not applicable (no `apple/` changes).

## Design principles self-check

- [x] 1 Defaults first: decoded mode by default, automatic capability detection with zero new configuration.
- [x] 2 Progressive disclosure: original transcript text stays one click away; external-trigger notice is a single quiet line only on older BotMux.
- [x] 3 User control: three-mode botmux chip preserved and reversible.
- [x] 4 Consistency first: reuses existing user bubble, Markdown, status line, and tokens.
- [x] 5 Model and product separate: read decoding is display-only; `actor: "owner"` is used only when BotMux explicitly advertises `ownerActor`.
- [x] 6 Checkable: covered by shared fixtures (`spec/fixtures/botmux/cases.json`), Go unit/integration tests, and web unit tests.
- [x] 7 Fast, local-first and stateful: read-only capability probe cached per BotMux instance; incremental `seq` cursor reads; first screen stays within `FIRST_SCREEN_BUDGET`.
- [x] Other platforms: not applicable in this PR (node transcript/send and web UI; mobile clients are out of scope here).
- [x] Parity list row updated: not applicable (no parity table row for BotMux display decoding).


## Why this must change the core

Transcript decoding is shared product truth: `server/internal/transcript` turns a runtime's on-disk turns into the one conversation every client and the assistant read, so structural botmux decoding and its fallback have to land in the core next to the other runtime decoders.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants