Skip to content

fix(adopt): 修复 adopt 启动握手卡 120 秒与截图卡片不更新 - #3301

Merged
deepcoldy merged 5 commits into
masterfrom
fix/adopt-runtime-contract-init
Nov 11, 2026
Merged

deepcoldy merged 5 commits into
masterfrom
fix/adopt-runtime-contract-init

Conversation

@LeonYuanYao

@LeonYuanYao LeonYuanYao commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Adopted terminals could stall for 120 seconds during startup, and their Show output cards could remain blank even after screenshots uploaded successfully. Fix the ordering between worker initialization, runtime registration, and screenshot capture identity publication so both fresh adoption and restored sessions can initialize correctly.

The changes address three boundaries:

  • Publish the finalized adopt init configuration and hand off the environment ledger before registering IPC handlers, so the daemon acknowledges the first runtime reservation and every generation boundary retains prior environment-risk evidence. Remove the redundant post-dispatch assignment. Restore the previous configuration if synchronous initialization fails, while retaining the monotonic risk ledger.
  • Accept capture_identity from the current worker/runtime while its execution is still queued. The worker reports this identity at the CLI write boundary before turn_execution_started; accepting it does not bind or start the queued execution.
  • Record the initial capture tuple locally until a runtime scope exists, then announce it after reservation and before rendering. Announce it for every new binding, including a retry whose predecessor failed before runtime publication and lost its deferred events. Keep the revision unchanged when the tuple has not changed.

The event gateway still rejects stale workers/runtimes, mismatched execution identities, and invalid lifecycle states. Screenshot source-suppression and frame-revision checks remain in place. The capture publication changes also cover ordinary workers using the same runtime startup path; legacy workers without a session contract retain their existing behavior.

Validation:

  • 735 tests passed and 8 skipped across 10 related test files, covering session contracts, lifecycle startup, screenshot upload/display, runtime rebinding, reservation timing, recovery, and durable expiry. The earlier adopt/card-action suite also passed.
  • bun run build passed with Bun 1.4.4 on macOS arm64, including type checking and artifact audits.
  • After the environment-ledger correction: 576 related Vitest cases passed, 8 skipped; mojo-device-isolation.test.ts passed all 42 cases on both Vitest and Bun, and the full build passed. The original generation-boundary guard failed before this correction. Added behavior tests verify that prior environment-risk keys are retained before init dispatch and after a synchronous send failure.
  • Regression tests exercise the real adopt startup and daemon handlers: fresh/restored adoption, capture identity before execution start, screenshot cache updates, initial publication with and without a turn, and retry after a start fails before runtime publication.
  • Fault-injection probes used real controllers, SQLite stores, worker scopes, and fake processes/clocks. They covered pause/close and worker replacement during reservation; partial persistence failure and retry; duplicate registration; stale/forged execution scopes; suppressed screenshot sources; early-frame ordering; refused reservations; and same-worker runtime replacement.
  • Mutation checks failed when removing early init publication, synchronous failure rollback, queued capture-identity admission, runtime-scoped initial publication, or forced reannouncement after an aborted start.
  • Environment-ledger probes covered repeated init-send failures, successful retry, delayed exits from old/failed workers, and an old-worker exit during dispatch. Risk keys remained monotonic and the replacement worker retained ownership; removing the ledger handoff failed all five focused behavior/probe cases.
  • Local Feishu/Codex adopt message round trips and screenshot display after a new message were manually confirmed. The final cold-start-without-new-input and failed-start retry cases passed automated tests and were deployed locally; a separate manual cold-start check is not recorded.

Validation scope: live deployment was on macOS. Additional probes used mocked process IPC and injected persistence failures rather than real disk faults. No platform-specific behavior was added.

@LeonYuanYao LeonYuanYao changed the title fix(adopt): initialize session contract before IPC handlers fix(adopt): restore startup handshakes and screenshot updates Nov 10, 2026

@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 236bb69f0)

上一轮唯一的阻断项(ds.initConfig = initMsg 新增赋值点撞 mojo K2 护栏,CI 三项确定性红)已修:赋值后 8 行内 startNewGenerationEnvLedger 就位、重复赋值已删、catch 回滚保留。我在本地复核过:

  • CI run 42801140149 全绿(build / test(1-4) / bun-test / bun-binary×3)。
  • 定向测试 10 个文件 706 用例全绿;bun run build(含 tsc + audit)通过。
  • 变异复验:把 ledger 交接挪回 send 之后 → session-lifecycle-start + mojo-device-isolation 7 个用例咬红;bunx vitest 与 bun test 双腿一致。

不过这次新增的第三个提交(screenshot capture identity)我发现了 1 个阻断项,附可复现探针。


阻断项:setCaptureIdentity 在无 runtime scope 时吞掉一次 revision,后续帧会被 daemon 以 unknown-revision 全部丢弃

src/worker.ts 新增的提前返回分支把 captureRevision 的递增和"是否已广播"解耦了:

if (changed && captureIdentityAnnounced) captureRevision += 1;   // 先自增
if (workerSessionEventScope && !workerSessionEventScope.contextBinding()) {
  captureIdentityAnnounced = false;                              // 再决定不广播
  return;
}

于是不在 runtime scope 里发生的 tuple 变化会找到一个永远发不出去的 revision。这类调用点在 worker 里大量存在,且都是异步回调/定时器驱动的:

调用点 触发者 是否在 scope 内
retireStructuredTurnAttribution (14353) 1s codexBridgeTimer / pruneExpiredStructuredHeadsAndEmit ❌ 定时器上下文
killCli (30061) / spawnCliBody 退出路径 (29648) backend.onExit → bindSessionBackendExit(只 send,不进 scope) ❌
writeCliPidMarker (7089) / syncQueuedTurnsFromMarkerDisk (7284) / advanceQueuedTypeAheadTurn (7352) markPromptReady 等各类路径 看调用栈,至少 idle/定时器路径不在
spawnCli 里新加的一次强制广播 (23391) 在 scope.run 内 ✅

send() 只在 scope 内才带 sessionContract 信封;没有信封的帧 daemon 直接 session_event_context_missing 丢掉——所以 revision 涨了、daemon 只知道旧值,这与你们这条提交想修的"卡片一直空白"是同一个症状面。

探针证据(真实 WorkerSessionEventScope + 真实 commitCaptureIdentity / evaluateScreenshotFrame,无 mock):

// 1) 回合开始,在 runtime 内广播 rev 0 @ om_A —— daemon 收到
scope.run(binding, () => setCaptureIdentity('om_A', undefined, 'ou'));
commitCaptureIdentity(ds, 1, sent.at(-1));            // true
// 2) 1s structured-bridge tick(无 scope)退休该回合
setCaptureIdentity(undefined, undefined, undefined);
// 3) 下一帧带着 worker 的实时 revision
evaluateScreenshotFrame(ds, 1, { captureRevision: env.captureRevision })

输出:

sent = [{"type":"capture_identity","revision":0,"turnId":"om_A"}]
workerRev = 1
daemon    = {"workerGeneration":1,"revision":0,"turnId":"om_A"}
next frame verdict = {"ok":false,"reason":"unknown-revision"}

即 worker 从此发出的每一帧都带 revision: 1,daemon 停在 0,evaluateScreenshotFrame 判定 msg.captureRevision > identity.revision → unknown-revision,该 worker 后续所有截图永久被拒,直到下一次 tuple 真正变化。adopt 会话(正是本 PR 的目标场景,displayMode: 'screenshot')最容易踩:adopt 面板靠 idle/桥定时器驱动,第一次回合结束就会进入这个状态。

建议修法:提前返回分支要么不递增 revision(把递增挪到确定要广播之后),要么在拿到 scope 后补发。最小改动是把递增放到 gate 之后:

const changed = turnId !== currentBotmuxTurnId || dispatchAttempt !== currentBotmuxDispatchAttempt;
currentBotmuxTurnId = turnId;
currentBotmuxDispatchAttempt = dispatchAttempt;
currentBotmuxCallerOpenId = callerOpenId;
if (!changed && captureIdentityAnnounced && !forceAnnouncement) return;
if (workerSessionEventScope && !workerSessionEventScope.contextBinding()) {
  // 无 runtime 时不消耗 revision:推迟到真正能广播时再判定 changed
  return;
}
if (changed && captureIdentityAnnounced) captureRevision += 1;
captureIdentityAnnounced = true;

注意 captureIdentityAnnounced 也不能在这里清掉——清了会让下一条无变化的调用被当成"首次广播",发出与 daemon 现值相同的 revision,commitCaptureIdentity 走 msg.revision === current.revision 且 tuple 相同 → 幂等 true,仍会把推迟的状态丢掉。这条路径需要 regress 用例覆盖:无 scope 的 tuple 变化之后,在 scope 内再调用一次必须广播出更高的 revision(当前实现会漏)。

补充:test/session-lifecycle-start.test.ts 新增的 adopt 用例里,scope.run(binding, emit) 把每条消息都放进 scope,所以覆盖不到这条"回调在 scope 外"的路径;建议补一条不套 scope.run 的用例。


其余复核结论

  • 前两个提交(contract 顺序 + 队列态接受 capture_identity)机制正确,我逐层核过 bindWorker → setupWorkerHandlers → 首次 runtime_binding_started 的时序,以及 unboundCurrent 分支只在 execution.phase === 'queued' 且 activeRuntime 匹配时放行。
  • git merge-tree origin/master pr3301-head 干净;master 上前移的 abbf59489(antigravity)与本次改动无重叠语义。
  • mojo-launcher-env-quarantine.test.ts 有 2 个用例在本地以 root 运行时失败(chmod 0o500 后仍可写),在 PR base ef6b83a81 上同样失败,与本 PR 无关。

修掉上面的 revision 泄漏后我再过一遍即可合。

@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.

更正上一条复审:阻断项降级为「建议修」,并附我判错的两处

上一条评论里我把它写成阻断项,其中两条论证是我自己写错了,先更正:

  1. 「该 worker 后续所有截图永久被拒」——错。 我在探针里只对第一条 capture_identity 调了 commitCaptureIdentity,后续消息没有喂给 daemon,所以得到了假的「永久」结论。忠实模拟(每条 send 都过 commitCaptureIdentity)后,下一个在 runtime scope 内广播的元组会自愈:

    SCENARIO A: 无 scope 退休 → 该窗口内帧被判 unknown-revision
                下一个回合 scoped 广播 → deliveries=["accepted","accepted"],帧 ok=true
    SCENARIO B: 无 scope 改元组 → 窗口内帧 unknown-revision
                scope 内重播同一元组 → ok=true
    

    影响是有界窗口(到下一次 scoped 广播为止),不是永久失明。

  2. 「1s 定时器跑在 scope 外」——错。 实测 setInterval 在 scope.run 内创建会继承该 binding(tick saw b1=true),onExit 走的 bindSessionRuntimeCallback 同样继承。所以 codexBridgeTimer / backend.onExit 这些调用点并不会触发这个分支。

我还在 5 个相关测试文件里临时插桩统计该分支命中次数:0 次。也就是说现有测试与常见路径都碰不到它。


仍然成立的部分(建议修,不阻断)

分支里的两处簿记仍然和"推迟"语义不一致,且能被真实的可达状态触发:

if (changed && captureIdentityAnnounced) captureRevision += 1;   // 先扣一次 revision
if (noScope) { captureIdentityAnnounced = false; return; }        // 再放弃广播

(a) 扣了 daemon 收不到的 revision。 之后 worker 发帧带 rev=N,daemon 停在 N-1 → 窗口内 unknown-revision。

(b) 清 captureIdentityAnnounced 会让下一次"无变化"调用被当成首次广播。 这个更值得看:init 阶段本来就有一条 (undefined, undefined) 的无 scope 调用。实测这个组合下 daemon 会收到一条元组相同的重复 rev,commitCaptureIdentity 走 msg.revision === current.revision && tuple 相同 → 幂等返回 true,看起来无害;但若期间元组变了,就会出现"daemon 认为自己在 rev N 的 om_A、worker 认为自己在 rev N 的 om_B"的静默错配。

判别性回归用例(在 PR head 上咬红,我的修法上转绿):

h.scope.run(binding, () => setId('om_A', undefined, 'ou'));   // 广播 rev 0
h.setId('om_A', undefined, 'ou');                              // 无 scope 的 init 式空调用
expect(captureRevision).toBe(0);        // PR head: 1  ← 咬红
expect(deliveries).toEqual(['accepted']);                      // PR head: 重复广播

建议修法(本地已跑通:13 个文件 834 用例全绿、tsc 过、上面用例两版差分正确)——把 gate 提到簿记之前,并让 changed 对齐"daemon 实际持有的元组":

currentBotmuxTurnId = turnId;
currentBotmuxDispatchAttempt = dispatchAttempt;
currentBotmuxCallerOpenId = callerOpenId;
if (workerSessionEventScope && !workerSessionEventScope.contextBinding()) return;
const changed = turnId !== announcedCaptureTurnId || dispatchAttempt !== announcedCaptureAttempt;
if (!changed && captureIdentityAnnounced && !forceAnnouncement) return;
if (changed && captureIdentityAnnounced) captureRevision += 1;
announcedCaptureTurnId = turnId;
announcedCaptureAttempt = dispatchAttempt;
captureIdentityAnnounced = true;

需要同时补 announcedCaptureTurnId/Attempt 两个变量,并更新 test/worker-screenshot-upload-hardening.test.ts 里两处 harness 的变量声明(那两处用 new Function 拼字符串,不声明就会报 ReferenceError——这也是我改完后必须先修 harness 才能跑到断言的原因)。


由于上面判错,整体结论调整

  • 上一条给的阻断撤回;这条只是建议,作者可选择按上面修,或在 PR 描述里说明"推迟期间的帧本来就会被 daemon 丢掉,属于可接受窗口"并加一条用例固化这个语义。
  • 其余结论不变:上一轮 mojo K2 护栏问题确认已修(CI 全绿、变异咬红),前两个提交的时序与 unboundCurrent 放行逻辑我逐层核过,merge-tree 干净,mojo-launcher-env-quarantine.test.ts 那 2 个失败是 root 下 chmod 不生效,base 同样失败,与本 PR 无关。

抱歉上一条把结论下重了——探针写错的地方我已经在上面对应位置标明。

DeepCold review and others added 2 commits November 11, 2026 08:42
同步 master(含 #3308)后,persistent_backend_target 用例的精确事件序列
与本 PR 在 reservation 后、spawnCliBody 前强制广播的 capture_identity
共存:新序列为 runtime_binding_started → capture_identity →
persistent_backend_target → runtime_binding,放宽断言并注释顺序意图。

Co-Authored-By: Claude Fable 5 <[email protected]>
@deepcoldy deepcoldy changed the title fix(adopt): restore startup handshakes and screenshot updates fix(adopt): 修复 adopt 启动握手卡 120 秒与截图卡片不更新 Nov 11, 2026
@deepcoldy
deepcoldy merged commit 8ec2032 into master Nov 11, 2026
15 checks passed
@deepcoldy

Copy link
Copy Markdown
Owner

感谢提交!这个 PR 已合入 master。

修复内容:

  • adopt 启动时先发布 init 配置并交接 env ledger,再注册 IPC handler,新接管和重启恢复的 adopt 会话不再卡在 120 秒 runtime reservation 超时;
  • capture identity 改为在 runtime scope 内广播,契约网关允许 queued 阶段的 capture_identity,截图卡片在新消息后能正常更新;
  • 同步初始化失败时回滚到之前的 initConfig,env ledger 保持单调 fail-closed。

后续跟进(不阻断本次合入):setCaptureIdentity 在无 runtime scope 分支的 revision 簿记与推迟语义存在边界不一致,已记录在 #3327,含判别用例与建议修法,欢迎继续认领。

@github-actions

Copy link
Copy Markdown

@LeonYuanYao @deepcoldy 合入 master 后的 Midscene E2E 失败:Feishu live Midscene 失败。

这次运行覆盖 c100770…8ec203230(5 个提交),同批合入的还有 #3299 #3308 #3324 #3306,失败不一定由本 PR 引起。

用例 跑道 状态 失败信息
Pi basic bot flow feishu-core-clis failed Replanned 20 times, exceeding the limit. Please configure a larger value for replanningCycleLimit (or use MIDSCENE_REPLANNING_CYCLE_LIMIT) to handle more complex tasks.
Antigravity basic bot flow feishu-core-clis failed Failed to continue: Unable to switch the middle column to a topics list view. After clicking "话题" (Topics) in the left sidebar navigation multiple times, the middle column remains in "消息" (Messages) …

@github-actions

Copy link
Copy Markdown

🚀 Released in v3.59.2

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