Skip to content

fix(herdr): close panes already running the session before a cold resume - #3621

Merged
deepcoldy merged 5 commits into
deepcoldy:masterfrom
nengqi:fix/herdr-cold-resume-live-process
Nov 19, 2026
Merged

deepcoldy merged 5 commits into
deepcoldy:masterfrom
nengqi:fix/herdr-cold-resume-live-process

Conversation

@nengqi

@nengqi nengqi commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #3611

What

With resume_agents_on_restore = true, a herdr restart relaunches every Claude pane as claude --resume <session-id> in a new pane under a new name. Botmux only looks for its recorded agent name, so it neither adopts nor kills these panes. When the next message arrives, the cold resume starts another --resume <same id> and two processes append to the same transcript.

Change

  • HerdrBackend.closePanesRunningCliSession(sessionName, cliSessionId): lists pane list in the herdr host and closes panes whose agent_session.value is the session being resumed (plain id, or a path ending in _<id>.jsonl). Panes that are working or blocked are left alone and logged.
  • HerdrBackend.spawn() calls it right before a fresh launch (not on re-attach, not for external/adopt targets) when the new SpawnOpts.resumeCliSessionId is set.
  • worker.ts passes resumeCliSessionId only when the launch is a resume, and not for /fork children (--fork-session writes a new transcript, so the parent's pane must stay).
  • Scope: only panes in the current herdr session are scanned; working / blocked panes are only logged. One extra pane list per cold resume (5 s timeout; failures are ignored and the launch continues).

The startup orphan sweep is not changed; this only guarantees a cold resume never adds a second writer.

Tests

  • test/herdr-backend.test.ts, new cold resume with a pane already running the same CLI session block:
    • closes the idle restored pane before agent start, and leaves other sessions' panes alone;
    • leaves a busy pane alone and still launches;
    • does not scan panes when the launch is not a resume.
  • The first case fails on master (no pane close) and passes with this change.
  • test/herdr-backend.test.ts and test/test-hygiene.test.ts pass (164 tests); typecheck has no new errors (the only error is a missing @supabase/supabase-js in my environment, same on master).
  • Full suite on the same machine: 56 failing files / 159 failing tests on both this branch and origin/master (identical file list, environment-related); this branch adds 3 passing tests.

Final behavior after review (head a6490d0003)

The review found that leaving a live writer in place still reproduced the
double-writer bug, so the sweep is now a safety precondition rather than a
best-effort cleanup:

  • A matching pane whose agent_status is not idle/done (including
    working, blocked, unknown) aborts the launch with an error instead
    of starting a second writer; the error goes through the worker's fatal-start
    path (visible in chat, retried by the daemon).
  • A failed pane list (via the required-list parser) or a failed pane close
    also aborts the launch — failures are no longer swallowed.
  • Before closing each pane of a multi-pane cohort, the pane set is re-read so a
    pane that became busy after the first snapshot is not force-closed.
  • A per-(herdr session, CLI session) file lock (withFileLockSync,
    maxWaitMs: 0) serializes the whole cleanup-and-launch window across
    workers; a contended cold resume fails fast and is retried rather than
    observing an empty pane set.
  • The cached stable-pane identity is reset unconditionally at the top of
    spawn(), so a lock-contention failure cannot leave the previous
    generation's PID frozen.

Verification on the final head: 273 targeted unit tests across 5 files, 12/12
real-herdr e2e tests, and a real herdr 0.9.5 probe covering selective close,
multi-pane close, the busy-pane refusal, and list-failure fail-closed;
typecheck and build clean; every new guard has a mutation test that fails when
the guard is removed.

With resume_agents_on_restore, herdr relaunches Claude panes as
`claude --resume <id>` under names Botmux does not track. The next
cold resume then started a second process on the same transcript.
Before launching a resumed CLI, close idle herdr panes whose
agent_session is the session being resumed.

Fixes deepcoldy#3611
- closePanesRunningCliSession 的 _<id>.jsonl 路径形态与 blocked 状态
  之前无测试守住(摘掉后缀匹配全量测试仍绿),补上对应用例
- worker 侧 forkSession 排除线同样无覆盖,抽成可导出纯函数
  resolveHerdrResumeCliSessionId 后按 resume/fork/无 id 三值穷举测试

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

Copy link
Copy Markdown
Owner

自动评审代修(测试补强,生产行为等价),已追加一个 commit 到本分支(fast-forward,未改写原有提交):

发现的测试缺口(变异复验:摘掉对应守卫后全量测试仍绿)

  1. closePanesRunningCliSession 的 _<id>.jsonl 路径形态匹配没有测试守住。herdr 对部分 CLI(如 pi)会在 agent_session.value 给出 path 形态(仓库内 session-discovery 的 UUID 正则与既有 fixture 均可佐证),这条分支真实可达且守的是「同一 transcript 两个写入者」的数据损坏场景。已补对应用例,并加一个 near-miss(_<id>x.jsonl)对照断言不会误关。
  2. worker 侧 forkSession 排除线(--fork-session 子会话只读源 transcript、写新 id,不能关源 pane)同样零覆盖,在 3 个相关测试文件共 639 个用例下变异全部存活。已把三值判定抽成可导出纯函数 resolveHerdrResumeCliSessionId,按普通 resume / 非 resume / fork / 无 id 四种情形穷举测试。
  3. 顺手给 busy-pane 用例补上 blocked 状态断言(真实 herdr 二进制确认 working/blocked/idle/done/unknown 五个状态枚举都存在)。

验证:test/herdr-backend.test.ts 141 全绿、tsc --noEmit 无错误、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.

复审 f3d9584a68,发现 1 个合前需要修复的问题:

  • [P1] 已发现旧 writer 仍未清退时,不能继续 agent start — src/adapters/backend/herdr-backend.ts:701-707,772-773。匹配 pane 为 working / blocked 时只记日志并跳过;pane close 失败也只导致返回值少一个 id。调用方忽略返回值,随后仍无条件用同一个 session id 冷恢复,于是旧进程存活、新进程又以 --resume <同一 id> 启动,正好保留 #3611 的双 writer / transcript 损坏场景。pane list 失败被吞成空列表时也同样 fail-open。

    现有 test/herdr-backend.test.ts:1343-1347 还明确断言 busy pane 存在时 agent start 成功;我单独运行该用例通过,确认这是当前实际行为,不只是静态推断。建议只在确认不存在匹配活 writer 后启动新 CLI:遇到 busy/blocked 或清理失败时应中止/延迟启动(或接管现有 pane),不要 fall through;同时把 busy 用例改为断言不调用 agent start,并补 close/list 失败的安全分支覆盖。

其余新增的 _<id>.jsonl 路径匹配、near-miss 与 fork 排除测试覆盖了对应判定线,未见的生产逻辑变化不需要扩大后端影响面。

验证:在等价 rebase 审查树(8304b0c616)上,herdr-backend + herdr-session-discovery + test-hygiene 共 209 个用例通过,bun run typecheck、bun run build 通过;CI run 44533756022 的 network-boundary 也已通过。

list/close 失败及非 settled 状态均 fail closed;按 native session 串行化清理与启动,并在每次关窗前重读状态,避免同 transcript 出现第二个写入者。

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

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

已推送修复提交 314b8f05c338a2c72efd0cd798b4ed9e31b2876a(在 f3d9584a68 上快进)。

修复内容

  • pane list / pane close 失败,以及匹配 pane 为 working / blocked / unknown 或其他非 settled 状态时,均在 agent start 前抛错;只有明确的 idle / done 可关闭。
  • 多 pane 清理时,每次 close 前重新读取目标状态;预检发现冲突时不做部分清理。
  • 以 HOME + Herdr session + CLI session id 为键,用跨进程文件锁覆盖整个冷恢复 spawn,防止两个 worker 在“旧 pane 已关闭、新 agent 未启动”的窗口同时通过检查。
  • 复用 requiredHerdrList,同时支持 wrapped 与 top-level panes 响应,读取失败不再当成空列表。

验证

  • bun run test -- test/herdr-backend.test.ts test/herdr-session-discovery.test.ts test/test-hygiene.test.ts test/restart-paths-worker-ready.test.ts:4 文件、231 用例通过。
  • bun run build:通过(含 typecheck)。
  • 隔离临时 worktree 变异复验:移除状态白名单、close 前重读、跨进程锁、list fail-closed、close fail-closed,5 个变异均使对应测试变红。
  • 对抗探针覆盖:人工输入导致 sibling 状态翻转、部分关闭失败后重试、同 key 重入、不同 key 不错误互斥、非 resume/fork 不扫描、reattach/external 不取锁;8/8 符合预期。

剩余边界

Herdr 0.9.5 没有原子 compare-and-close,逐次 close 前重读只能缩小人工输入竞争窗口,不能宣称彻底消除 TOCTOU。另一个既有范围外场景是:初始 snapshot 之后才由 Herdr 新恢复出的匹配 pane 不会加入本轮清理;若要求覆盖 Herdr 持续 restore 的完整竞态,需要另外做恢复完成同步或启动前最终校验。

…me-live-process

冲突仅 src/adapters/backend/herdr-backend.ts 两处:
1. import:保留本 PR 的 withFileLockSync 与 master 新增的 sessionEnvUnsetFlags
2. spawn:保留本 PR 的 resume 锁外壳与 spawnWithResumeExclusion 抽取,
   master deepcoldy#3624 的 lastKnownStablePanePid 重置移入 spawnWithResumeExclusion
   首行(每次 spawn 仍恰好执行一次,语义等价)

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

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

复审 merge commit bdd5196712556125c6271e6ae95c2371ae21f131,发现 1 个 P2,建议 squash 前修正;其余合并增量未发现问题。

  • [P2] lastKnownStablePanePid 的重置必须放在取锁之前 — src/adapters/backend/herdr-backend.ts:782-800。master 在 public spawn() 首行无条件清空该字段;merge 后重置位于 spawnWithResumeExclusion(),而 withFileLockSync(..., { maxWaitMs: 0 }) 可以在进入 helper 前抛错。因此锁冲突路径会从 master 的一次重置变成零次,保留上一代 stable-pane 身份。

    我用真实 HerdrBackend 和同 key 持锁做了探针:spawn() 按预期抛出 FileLockTimeoutError 后,lastKnownStablePanePid 仍为预置的 12345;在后续 process-info 探测失败时,getStablePanePid() 也实际返回了 12345,而不是 null。若该 backend 被后续 stable-pane consumer 继续使用,就会把旧 generation 当成当前身份。

    建议把 this.lastKnownStablePanePid = null 移到 public spawn() 首行,并删除 helper 内重复重置;增加一个“同 key 锁已被持有”的回归用例,断言失败后缓存及失败 probe 下的 getStablePanePid() 都不会返回旧 PID。

其余核验:

  • combined diff 仅见所述两处冲突解析;withFileLockSync 与 sessionEnvUnsetFlags 均保留,锁外壳结构正确。
  • 以 -U0 比较合并前后 PR 相对各自 master 的实际增删行:265/265 逐字一致(原始 patch 的 blob index、行号和上下文差异不影响净增量)。
  • bun run test -- test/herdr*.test.ts:9 文件、256 用例通过。
  • herdr-backend + session-discovery + hygiene + file-lock + restart-paths 合跑:5 文件、272 用例通过。
  • bun run build:通过,含 typecheck;PR 文件范围 git diff --check 通过。
  • 查询时 network-boundary 与 bun-binary-darwin 已成功;主 CI run 44610434766 其余 job 仍在排队,未把 CI 视为全绿。

merge master 时 lastKnownStablePanePid 的重置被放进
spawnWithResumeExclusion,导致 resume 锁竞争(maxWaitMs:0)在进入
helper 前抛 FileLockTimeoutError 时重置一次都不执行,旧 generation
的 PID 被冻结,后续 process-info 探测失败时 getStablePanePid 会返回
上一代身份。重置移回 public spawn() 首行无条件执行,恢复 master
「每次 spawn 恰好重置一次」的语义;补同 key 持锁回归用例。

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

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

复审增量 bdd5196712..a6490d0003aeee3815b3a0b367036fcaba68fde5:此前 P2 已修复,未发现新增阻断问题,技术面可合;最终仍以首跑 CI 全绿为准。

  • lastKnownStablePanePid = null 已回到 public spawn() 首行、任何 resume 锁判断之前;helper 内重复重置已删除。helper 只有 public spawn() 的两个调用点,因此锁成功、锁失败、非 resume、reattach/external 路径均保持每次入口恰好一次重置。
  • 新回归用例通过真实同 key 持锁覆盖 FileLockTimeoutError,并继续验证失败 process-info probe 下 getStablePanePid() 返回 null,断言的是最终 stable-pane 行为而非仅检查字段。
  • herdrResumeLockTarget 同时用于生产锁与测试构造,不是仅供测试的死导出;提交为 bdd5196712 上的单父快进,增量仅这两个文件。

独立验证:

  • bun run test -- test/herdr-backend.test.ts test/herdr-session-discovery.test.ts test/file-lock.test.ts test/restart-paths-worker-ready.test.ts test/test-hygiene.test.ts:5 文件、273 用例通过。
  • bun run build:通过,含 typecheck。
  • 在隔离 worktree 保留新测试、仅把重置挪回 helper:基线先通过,变异后该用例按预期变红,关键断言为 expected 12345 to be null,确认测试能识别原缺陷。
  • git diff --check bdd5196712..a6490d0003 通过,worktree 干净。

查询时 CI run 44615072584 的 network-boundary 仍在排队,未将 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.

G7 非相邻豁免背书:同意当前合并树可合,可按 a6490d0003 走 squash-pr。

本结论严格绑定以下三个输入;head 或 master 再前进时需重新计算:

  • PR head:a6490d0003aeee3815b3a0b367036fcaba68fde5
  • master:467daa2d8f2687a612099d077a544a0e4a9eaeba
  • 预测合并 tree:7fd49023c933ee3792904402d48537522618c9bf

独立核验:

  • git merge-tree --write-tree a6490d0003 origin/master 无冲突,输出 tree 与上述值逐字一致;GitHub 刷新后为 MERGEABLE。
  • 合并前后 PR 文件集合一致;以 -U0 比较相对各自 master 的 PR 实际增删行,289/289 逐字相同。
  • worker.ts 的 Herdr import / resumeCliSessionId 与新 master 改动分属不同 hunk;types.ts 的 SpawnOpts.resumeCliSessionId 与 SessionBackend.captureViewportCells 分属不同 interface。合并 tree 中双方定义均存在;新 master 未改 Herdr 后端或 Herdr 测试。
  • 用该 tree 创建仅供本地 checkout 的临时提交,在隔离 worktree 直接验证:bun run build 通过;指定 11 个测试文件、483 用例全部通过(含本 PR 5 文件及 captured-screen-rows、turn-terminal-receipt、turn-terminal-receipt-card、next-step-suggestion、idle-auto-compact、worker-terminal-authority-release)。
  • 当前 PR statusCheckRollup 全部为 SUCCESS。

因此该 master 增量不需要触发重跑 CI;squash 时若生成的 tree 不再是 7fd49023c933ee3792904402d48537522618c9bf,本背书即失效。

@deepcoldy

Copy link
Copy Markdown
Owner

感谢 @nengqi 的修复,已合入 master(squash 为 b42201b)。

核心设计(冷恢复前用 pane list 的 agent_session.value 定位同 CLI session 的旧 pane 并清退)方向正确。评审过程中补强了两块:把清退从 best-effort 改成安全前置条件(busy/blocked/unknown 或 list/close 失败时拒绝启动,避免复现双 writer),以及跨 worker 的 resume 文件锁和配套回归测试。

未尽事项:issue 里提到的「daemon 启动孤儿清扫覆盖 restored pane」不在本 PR 范围,已开 #3640 跟踪。再次感谢,欢迎继续贡献。

这是自动评审流程的收尾说明,最终以维护者审阅为准。

@deepcoldy

Copy link
Copy Markdown
Owner

合并后跟进一项合并前已存在、需要后续 PR 修复的缺口(不影响本次 squash tree 的 G7 等价验证):

  • [P2] adapter fallback resume id 会绕过 Herdr 清理与锁 — src/worker.ts:28792,31298 只把 effectiveCliSessionId 同时交给 adapter 的 resumeSessionId 和 Herdr 守卫;但 Claude 在 src/adapters/cli/claude-code.ts:1273 实际使用 resumeSessionId ?? sessionId。因此 transcript 存在、但持久化 native id 缺失时,CLI 会以 effectiveAdapterSessionId 恢复,Herdr 的 resumeCliSessionId 却为 undefined,不扫描也不加锁,旧 restored pane 存活时仍可形成双 writer。

    真实适配器探针:先创建 <botmux-session-id>.jsonl,checkResumeTargetExists 返回 true;buildArgs({ resume: true, resumeSessionId: undefined }) 实际生成 --resume <botmux-session-id>,同输入下 resolveHerdrResumeCliSessionId(...) 为 undefined。这不是仅靠静态推测的不可达组合。

    建议由 launch planning / adapter 明确返回实际选择的 native resume target,再交给 Herdr;至少需要覆盖 Claude / Genius / Grok / Hermes 的 adapter-session fallback,同时避免把 Codex / TraeX 的动态发现 id 错当成 Botmux id。适合单独 follow-up,并补“native id 未持久化但 transcript 存在”的冷恢复测试。

@deepcoldy

Copy link
Copy Markdown
Owner

独立复核确认这个 P2 既有缺口成立(真实适配器探针,非静态推断):

  • 仅造 <botmux-sid>.jsonl(无 native id)→ claude checkResumeTargetExists({ cliSessionId: undefined }) 返回 true,tier-0/tier-1 都不降级,effectiveResume 保持 true;
  • buildArgs({ resume: true, resumeSessionId: undefined }) 实际生成 --resume <botmux-sid>;
  • 同输入 resolveHerdrResumeCliSessionId(true, undefined, undefined) === undefined → Herdr 不扫描、不加锁。

确属 master 既有问题,不在 #3621 引入/覆盖范围内,按既有问题另开跟踪:#3641(含 claude/genius/grok/hermes 回退族与 codex/traex 动态发现 id 的区分,以及「让 launch planning 返回实际 native target」的修法建议和回归测试要求)。与启动孤儿清扫 #3640 相互独立。

@github-actions

Copy link
Copy Markdown

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

这次运行覆盖 f93f5f9…a1770e7d0(6 个提交),同批合入的还有 #3626 #3518 #3625 #3637 #3622,失败不一定由本 PR 引起。

用例 跑道 状态 失败信息
Claude basic bot flow feishu-core-claude failed Node "feishu.showStreamingOutput" timed out after 180000ms.
Claude group reply mode chat answers inline and folds topics into the group session feishu-core-group-modes failed Reply "ACK-e2e-gr-chat-claude-1-1795133658190 RECALL ACK-e2e-gr-chat-claude-1-1795133658190" appeared 0 time(s) within 240000ms, expected 1 (clicked 直接开启会话 2×; re-opened 0×; repo card buttons 1 visib…

@github-actions

Copy link
Copy Markdown

🚀 Released in v3.59.23

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.

herdr backend: cold-resume ignores a live CLI already running the same session id (two processes on one transcript)

2 participants