Skip to content

fix(bridge): 兼容结构化转录跨daemon重启恢复与Pi时间戳解析 - #1755

Merged
deepcoldy merged 2 commits into
masterfrom
fix/structured-bridge-daemon-restart-recovery
Oct 9, 2026
Merged

deepcoldy merged 2 commits into
masterfrom
fix/structured-bridge-daemon-restart-recovery

Conversation

@deepcoldy

@deepcoldy deepcoldy commented Oct 9, 2026 •

Copy link
Copy Markdown
Owner

改了什么

  1. 修复 Pi 转录时间戳解析:在 src/services/pi-transcript.ts 中兼容解析毫秒数字(number)和 ISO 字符串(string),避免数字时间戳被 Date.parse 解析为 NaN 并回退为 Date.now(),保证事件切分保留真实的事件发生时间。
  2. 支持通用结构化 Bridge 跨重启待处理回合(pending turn)持久化与恢复:
    • 在 src/worker.ts 中引入 structuredBridgeJournalPath()(${sessionId}.json.structured),覆盖所有启用结构化转录兜底的托管会话(Pi、Grok、TraeX、普通 Codex 等),与 adopted Codex 的 .codex-adopt 相互独立;
    • 在回合标记(codexBridgeMarkPendingTurn)、attach 完成、以及完成闭合(emitReadyCodexTurns / clear)时自动同步 checkpoint;
    • 在 codexBridgeAttach 的 baseline-existing 模式下:若检测到未决 journal 记录,不再直接跳至文件末尾(EOF),而是从起始位置 drain 并在 mark 截断时间切分 history(吸收)与 live(处理),还原 pending turn;
    • 无论是「重启期间模型已输出完成」还是「重启后模型在未来某一时刻输出完成」,均能准确归属到原飞书回合并通过 final_output 交付到飞书群;
    • 守卫排除打墙钟时间的 drainer(如 Cursor 无逐行真实时间戳),继续沿用字节偏移 EOF baseline,避免历史重复发送;
    • 会话结束或主动清理时同步清理 .structured 日志文件。

为什么

在长耗时任务(如 Pi 执行数十秒到数十分钟)过程中遭遇 daemon 重启时:

  • 新 worker 通过 tmux re-attach 时采用 baseline-existing 模式直接将游标移至文件末尾,且内存队列中无 pending turn;
  • 当底层模型输出最终结果时,由于队列无对应 turn 承接,输出沦为无主事件被丢弃,导致飞书上无法通过转录兜底收到最终回复;
  • 加上 Pi 的 jsonl 时间戳为数字,回退为 Date.now() 会导致历史重放无法按截止时间区分,影响恢复的准确性。

影响面

  • 模块:src/services/pi-transcript.ts、src/worker.ts
  • 涉及 CLI 与会话类型:使用结构化转录兜底且具备逐行真实事件时间戳的 CLI(Pi、Grok、TraeX、普通 Codex、零注入模式下的 Antigravity 等)在长任务执行遇到 daemon 重启 / worker 重连场景;Cursor 由于无逐行真实时间戳,显式排除在重放之外保持 EOF baseline。
  • 对原有 adopted Codex 逻辑保持完全正交与兼容。

验证

  • 单测验证:
    • npx vitest run test/pi-transcript.test.ts(25/25 通过,包含新增的毫秒数字时间戳解析测试)
    • npx vitest run test/codex-adopt-recovery.test.ts(15/15 通过,包含新增的托管非 adopt 会话跨重启恢复测试与墙钟 drainer 排除测试)
    • npx vitest run test/worker-structured-lifecycle-status.test.ts(35/35 通过,包含结构化转录 checkpoint 与 attach 恢复接线断言)
    • npx vitest run test/bridge-turn-journal.test.ts(13/13 通过)
  • 构建验证:
    • bun run build 0 error,产物审计通过。

@deepcoldy deepcoldy left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Summary

This change journals structured-bridge pending turns (.structured, with adopt Codex still on .codex-adopt only) and, on a new process's first baseline-existing attach, replays the jsonl from offset 0, splits it at min(markTime) - 5s, absorbs history, ingests the live tail, and emits. For Pi, Grok, TraeX, and the other drainers that keep real event timestamps, already-delivered turns stay behind that cutoff, and emitReadyCodexTurns still checkpoints before send, so a normal daemon restart does not double-post. stopCodexBridge nulls the rollout path before the new checkpoint calls, so shutdown does not persist an empty queue or delete the journal this recovery reads. The Pi numeric-timestamp branch is a sound fallback; real Pi session files already store an ISO string on the entry, so Date.parse was not returning NaN on those transcripts. The break is zero-prompt Cursor, whose drainer stamps every line with Date.now() and therefore cannot be split by that cutoff.

Issue counts by severity

  • bugs: 1
  • suggestions: 1
  • nits: 0

Comment thread src/worker.ts
if (restorable.length > 0 && journalPath) {
const result = structuredBridgeIngestPath(rolloutPath, 0);
const minMarkTime = Math.min(...restorable.map(e => e.markTimeMs));
const cutoff = minMarkTime - 5_000;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

[bug] Zero-prompt Cursor resume calls codexBridgeAttach(path, 'baseline-existing') directly (spawnCli, when effectiveCliSessionId is already known). Fallback is active for promptInjection === 'none', so the previous process's .structured journal is selected and this branch drains the chat jsonl from offset 0. drainCursorTranscript has no per-event timestamp and sets every event's timestampMs to Date.now() (src/services/cursor-transcript.ts). cutoff = minMarkTime - 5_000 is in the past, splitCodexEventsByCutoff therefore puts the entire transcript in live, and ingest at the next line treats it as new. zeroPromptTerminalSync() has already called setLocalTurns(true, Date.now()) before attach, so historical user lines that do not match the restored fingerprint are synthesized as local turns; their text-only assistant lines close those turns. emitReadyCodexTurns() then posts them (forwardLocalFinal is set, and historical botmux send markers sit before the new markTimeMs, so they fall outside the suppression window). A multi-turn Cursor chat is re-posted to Feishu on every daemon restart while a turn is still pending. If an earlier user line shares the pending turn's 30-character fingerprint, that older line starts the restored Lark turn and an old assistant final is emitted as its answer, after which the post-drain checkpoint drops the real pending mark. Adopt Cursor still goes through cursorBridgeAttach → skip-tail and does not take this replay. The new recovery tests call restoreCodexAdoptTurns with caller-supplied timestamps, and the lifecycle source slice never runs this attach branch against a Date.now()-stamping drainer, so the failure is untested.

Suggestion: Do not apply the timestamp-cutoff replay to drainers that stamp wall-clock time. Keep Cursor on the byte-offset EOF baseline (the skip-tail / baselineJsonlCursor path) so history is not re-ingested. Add an attach-level test whose drainer stamps Date.now() and assert that prior finals are not passed to emitReadyCodexTurns.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

已修复:在 baseline-existing attach 中加入 !codexBridgeIsCursor() 守卫,Cursor 缺少逐行真实时间戳,继续沿用字节偏移 EOF baseline,不参与时间戳 cutoff 重放;同时在 test/codex-adopt-recovery.test.ts 补充单测。

Comment thread src/worker.ts Outdated
mtrBridgeOffset = 0;
mtrBridgeBaselineDone = false;
codexBridgeQueue.clearPending();
checkpointCodexAdoptRecovery();

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

[suggestion] stopCodexBridge sets codexBridgeRolloutPath = undefined (line 9055) and then clearPending() before these two new checkpoint calls. Both checkpointCodexAdoptRecovery and checkpointStructuredBridgeRecovery return immediately when the rollout path is unset, so the calls neither save a pending turn nor delete .structured / .codex-adopt. They are dead. Moving them above the path clear, which is what the call order appears to intend, would checkpoint the queue after clearPending() and clearBridgeTurnJournal the file this recovery depends on.

Suggestion: Remove the two calls from stopCodexBridge, or comment that they must stay after the path is cleared and therefore no-op. Do not reorder them above line 9055.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

已清理:移除了 stopCodexBridge 中在 codexBridgeRolloutPath 已置为 undefined 之后的冗余 checkpoint 调用。

@deepcoldy deepcoldy left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Re-review of 53dc89b

The two findings on e78f9cc are addressed.

  • canRecover now requires !codexBridgeIsCursor(). Zero-prompt Cursor resume falls through to baselineJsonlCursor and does not drain the transcript from offset 0, so wall-clock Date.now() stamps can no longer pull the whole chat into live.
  • The stopCodexBridge checkpoints that ran after codexBridgeRolloutPath was cleared are gone. Mark, emit, and the end of codexBridgeAttach still checkpoint.

Cursor zero-prompt still does not recover a pending turn across a daemon restart. That is the intended limit of this guard: without real per-event timestamps the replay is unsafe. Pi, Grok, TraeX, and non-adopt Codex keep the timestamp-cutoff path.

The PR body still lists zero-prompt Cursor as covered by restart recovery. Worth a one-line update so the description matches the guard.

No new blocking issues. GitHub approval is not submitted from this account because it is the PR author.

@deepcoldy
deepcoldy merged commit 68675ad into master Oct 9, 2026
14 checks passed
@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown

🚀 Released in v3.38.0

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.

1 participant