Repository navigation
Conversation
Claude PermissionRequest 페이로드에 tool_use_id 부재로, 직전 이벤트가 매칭 PreToolUse일 때만 id 상속 성립. 병렬 도구 배치나 훅 도착 순서 역전으로 그 인접성이 깨지면 승인 이후 모든 작업 이벤트 폐기, 턴 종료까지 "응답 필요" 표시 유지. Before: - 재개 증명이 직전 이벤트 1건에만 의존 - 상속 실패 시 승인된 도구의 PostToolUse까지 폐기 → 턴 내내 고착 - 폐기 대상에 PreToolUse 포함 → 같은 턴 다음 승인도 연쇄 실패 After: - 패인별 턴 스코프 원장에 선언 id 보관, 프롬프트가 FIFO로 자기 호출 id 청구 - 완료 id 은퇴 + 턴 경계(UserPromptSubmit·턴 종료) 소거로 이월 차단 - 리플레이 이벤트 기록 제외 - 프롬프트 시점 기준 미선언 완료를 재개 증명으로 인정하는 안전밸브 추가 개선 효과: - 승인 직후 작업 중 표시 복귀, 실제 Claude Code 훅 스트림 대조로 확인 - 형제 호출·재전송·리플레이·이전 턴 완료는 전부 거부, 다이얼로그 미응답 상태의 오해제 없음
원장이 상태 항목 삭제 경로에만 연결되어, 다른 종료 경로에서 패인 항목 잔존. 패인 키는 PTY 재시작 후에도 동일하므로 새 에이전트 프로세스가 이전 프로세스의 선언 id를 물려받는 오해제 경로 존재. Before: - deleteStatusEntry 한 곳에서만 원장 정리 - 탭 닫기·PTY 종료·서버 정지 시 패인 항목 잔존 - 패인 권한 이관 시 이전 소유자 키에 증거 고립, 이관 후 프롬프트가 id 청구 불가 After: - deleteStatusEntry·dropStatusEntriesByTabPrefix·clearPaneState·stop 정리 배선 - transferPaneAuthority에서 새 패인 키로 증거 이동 - 테스트 캐시 리셋에 원장 초기화 포함 개선 효과: - 재시작·재사용된 패인에서 이전 프로세스 id에 의한 오해제 차단 - 패인 수명 종료 후 맵 항목 잔존 제거
Greptile SummaryThis PR fixes a bug where approving a Claude permission prompt leaves the pane glyph, sidebar row, and worktree dot stuck on the amber "needs you" indicator for the rest of the turn. The root cause was that the existing single-event lookback (inheriting
Confidence Score: 5/5Safe to merge. The change is narrowly scoped to in-memory, main-process TypeScript with no new I/O, no new dependencies, and no renderer or IPC surface; all five teardown paths are correctly wired, the replay guard fires before any ledger mutation, and the cross-turn retry regression is covered by a dedicated test. The ledger logic is well-contained in the new module, the critical ordering (ledger update before suppression check) is preserved, and the 20 integration tests in the parallel-permission suite cover the failure modes identified during the adversarial review. No correctness issues were found in the current state of the diff. Files Needing Attention: No files require special attention. The only non-trivial mutation path is the late-announcement binding in applyNormalizedStatus (server.ts ~1240-1252), which correctly updates lastStatusByPaneKey and schedules a persist without re-emitting the row (intentional: state is still waiting).
|
| Filename | Overview |
|---|---|
| src/main/agent-hooks/claude-permission-tool-use-evidence.ts | New ledger module: per-pane store of announced tool-use ids with correct FIFO resolution, TTL/cap bounds, and safe deduplication on re-announced ids. All helper functions are read-only for resolution and well-guarded against empty/whitespace ids. |
| src/main/agent-hooks/server.ts | Core integration: ledger update is correctly ordered before the suppression check so PreToolUse events recorded during a sticky wait are available to the next prompt. Late-announcement binding, turn-boundary clearing, replay guard, and all five teardown paths are wired correctly. |
| src/main/agent-hooks/claude-permission-tool-use-evidence.test.ts | 14 unit tests covering the ledger in isolation: parallel-batch pairing, identical-preview ambiguity, TTL boundary, 64-entry cap, duplicate-id deduplication, and authority-transfer merge. |
| src/main/agent-hooks/server.claude-parallel-permission.test.ts | 20 integration tests against the full AgentHookServer: late PreToolUse binding, replayed rows and boundaries, cross-turn retry, authority-transfer lifecycle, and the ambiguous-batch case where the pane correctly stays waiting. |
Sequence Diagram
sequenceDiagram
participant Claude
participant HookServer as AgentHookServer
participant Ledger as ClaudeAnnouncedToolUseStore
participant UI
Note over Claude,UI: Happy path
Claude->>HookServer: "PreToolUse (id=toolu_a, Bash git status)"
HookServer->>Ledger: rememberClaudeAnnouncedToolUse(pane, toolu_a)
Claude->>HookServer: "PreToolUse (id=toolu_b, Bash git log)"
HookServer->>Ledger: rememberClaudeAnnouncedToolUse(pane, toolu_b)
Claude->>HookServer: PermissionRequest (Bash git status, no id)
HookServer->>Ledger: resolveClaudeAnnouncedToolUseId
Ledger-->>HookServer: toolu_a (unambiguous)
HookServer->>UI: "waiting (toolUseId=toolu_a)"
Claude->>HookServer: "PostToolUse (id=toolu_a)"
HookServer->>Ledger: retireClaudeAnnouncedToolUse(pane, toolu_a)
HookServer->>HookServer: isClaudePermissionResumingApprovedTool → true
HookServer->>UI: working
Note over Claude,UI: Late PreToolUse race
Claude->>HookServer: PermissionRequest (Bash git status, no id)
HookServer->>Ledger: resolve → undefined
HookServer->>UI: waiting (no id)
Claude->>HookServer: "PreToolUse (id=toolu_a) — arrives late"
HookServer->>Ledger: rememberClaudeAnnouncedToolUse
HookServer->>HookServer: lateResolvedClaudePermissionToolUseId → toolu_a
HookServer->>Ledger: "update cached row toolUseId=toolu_a"
Claude->>HookServer: "PostToolUse (id=toolu_a)"
HookServer->>HookServer: isClaudePermissionResumingApprovedTool → true
HookServer->>UI: working
Reviews (3): Last reviewed commit: "fix(agent-hooks): 권한-호출 짝짓기를 모호성 거부 방식으로..." | Re-trigger Greptile
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdded a bounded, pane-scoped ledger for Claude tool-use announcements and completions. Permission requests now claim matching announced tool IDs across pending calls. Completion handling distinguishes accounted and unaccounted tools. Ledger state updates on Claude hook events, turn boundaries, pane transfers, cleanup operations, shutdown, and test resets. Added coverage for matching, ordering, expiration, duplicate suppression, replay filtering, prompt pauses, and lifecycle behavior. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (5)
src/main/agent-hooks/claude-permission-tool-use-evidence.ts (3)
81-96: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSplit
rememberIdinto two typed helpers.
rememberIdacceptsSet<string> | Map<string, number>and branches oninstanceof Map. Theatparameter is meaningless for theSetcase. Two small helpers remove the runtime type test and make the bound explicit for each store.♻️ Proposed refactor
-function rememberId(ids: Set<string> | Map<string, number>, toolUseId: string, at?: number): void { - // Why: re-adding moves the id to the end, so the trim below drops genuinely old ids. - ids.delete(toolUseId) - if (ids instanceof Map) { - ids.set(toolUseId, at ?? 0) - } else { - ids.add(toolUseId) - } - while (ids.size > CLAUDE_PENDING_TOOL_USE_MAX_PER_PANE) { - const oldest = ids.keys().next().value - if (oldest === undefined) { - return - } - ids.delete(oldest) - } -} +// Why: re-adding moves the id to the end, so the trim drops genuinely old ids. +function trimIds(ids: { size: number; keys: () => IterableIterator<string>; delete: (id: string) => boolean }): void { + while (ids.size > CLAUDE_PENDING_TOOL_USE_MAX_PER_PANE) { + const oldest = ids.keys().next().value + if (oldest === undefined) { + return + } + ids.delete(oldest) + } +} + +function rememberAnnouncedId(announced: Map<string, number>, toolUseId: string, at: number): void { + announced.delete(toolUseId) + announced.set(toolUseId, at) + trimIds(announced) +} + +function rememberCompletedId(completed: Set<string>, toolUseId: string): void { + completed.delete(toolUseId) + completed.add(toolUseId) + trimIds(completed) +}
143-155: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueA completion for an unknown pane creates a ledger that no turn boundary removes.
retireClaudeCompletedToolUsecallsledgerFor, which inserts a new ledger for the pane. APostToolUsethat arrives after the turn boundary cleared the pane, or before anyPreToolUse, therefore leaves a ledger holding onlycompletedids. That ledger stays until pane or tab teardown. The retained data is small and bounded per pane, so this is a hygiene concern, not a leak of unbounded size. Consider callingpruneLedgerafter the filter, or skipping creation when the pane has no ledger and nothing is pending.♻️ Proposed change
const ledger = ledgerFor(store, paneKey) ledger.pending = ledger.pending.filter((entry) => entry.toolUseId !== id) rememberId(ledger.completed, id) + pruneLedger(ledger, store, paneKey) }Note:
pruneLedgeronly deletes when every collection is empty, so thecompletedid would still be kept here. If you want the entry dropped, gateledgerForon an existing ledger instead.
1-9: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueLong
Why:narrative blocks in both files exceed the concise-comment guideline. The shared root cause is design rationale written as multi-line prose inside the code instead of a one-line note.
src/main/agent-hooks/claude-permission-tool-use-evidence.ts#L1-L9: trim the nine-line header, and the blocks at lines 30-32, 35-38, 129-130, and 182-185, to one line each.src/main/agent-hooks/server.ts#L502-L506: trim the five-line fallback rationale, and the block at lines 1226-1235, to one line each.As per coding guidelines: "Comments must be concise, limited to non-obvious information, and preferably one line; do not explain obvious code or walk through implementation details."
Source: Coding guidelines
src/main/agent-hooks/claude-permission-tool-use-evidence.test.ts (1)
142-171: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a direct assertion for the
announcedbound.This test proves the
pendingqueue bound. It does not prove theannouncedmap bound, which sharesCLAUDE_PENDING_TOOL_USE_MAX_PER_PANE. AnisClaudeToolUseUnaccountedForassertion for the oldest trimmed id (toolu_0) would cover the id-history trim path, which the ledger comment at lines 30-32 calls out as safety-critical.💚 Proposed addition
expect(takeClaudePendingToolUseId(pending, PANE, request('cmd-0'), NOW + 100)).toBeUndefined() + // Why: the trimmed id must read as unaccounted for, or its prompt could never attach an id. + expect(isClaudeToolUseUnaccountedFor(pending, PANE, 'toolu_0', NOW + 100)).toBe(true)src/main/agent-hooks/server.claude-parallel-permission.test.ts (1)
158-169: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a duplicate
PermissionRequestdelivery case.The suite covers a duplicate completion at lines 171-182. It does not cover a duplicate
PermissionRequestfor a batch whose two calls share the same preview. That sequence exposes the id-stealing path flagged insrc/main/agent-hooks/server.tsatattachClaudePermissionToolUseId. Add the case so the fix is pinned.💚 Proposed test
+ it('keeps the resolved id when the same prompt is delivered twice', () => { + // Why: the hook script retries on timeout; a repeat must not claim the identically previewed sibling. + const server = new AgentHookServer() + + announce(server, 'pnpm test', 'toolu_first') + announce(server, 'pnpm test', 'toolu_second') + requestPermission(server, 'pnpm test') + requestPermission(server, 'pnpm test') + + reportBack(server, 'pnpm test', 'toolu_first') + + expect(currentState(server)).toBe('working') + })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: bf4d3ec5-a90a-4102-afa7-dc83c83e30ba
📒 Files selected for processing (4)
src/main/agent-hooks/claude-permission-tool-use-evidence.test.tssrc/main/agent-hooks/claude-permission-tool-use-evidence.tssrc/main/agent-hooks/server.claude-parallel-permission.test.tssrc/main/agent-hooks/server.ts
Greptile·CodeRabbit 리뷰에서 드러난 4개 오표시 경로 수정. Before: - 턴 경계에서 원장 전체 삭제 → 이전 턴 완료 POST 재전송이 미선언 id로 보여 새 프롬프트 오해제 - isReplay 가드가 턴 경계 처리 뒤 → 리플레이된 UserPromptSubmit·done이 진행 중 턴의 원장 삭제 - 중복 전달된 PermissionRequest가 형제 호출 id 재청구 → 그 형제는 잔여 턴 동안 재개 증명 불가 - 패인 권한 이관이 목적지 원장 덮어쓰기 → 목적지 패인 선언 증거 소실 After: - 턴 경계는 청구 큐만 비우고 목격 id 이력 유지 - isReplay 가드를 최상단으로 이동 - 중복 프롬프트는 첫 전달이 확정한 id 재사용, 신규 청구보다 우선 - 이관 시 청구 큐·선언·완료 이력 병합(중복 제거 후 상한 적용) 개선 효과: - 재전송·리플레이·중복 전달·패인 이관 4경로 오표시 제거, 경로별 회귀 테스트 6건 고정 (전부 수정 전 실패 확인) - 주석을 레포 규약(간결·1줄 우선)에 맞춰 축약, id 원장 헬퍼 타입 분리
|
Pushed 0babca1 addressing every review comment. Summary of what changed and what I pushed back on. Applied
Six regression tests were added in total, each verified to fail on the previous commit. Not applied, with reasoning
Verification on the current head: |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 60af97fa-1649-450f-86a7-79107530efc2
📒 Files selected for processing (4)
src/main/agent-hooks/claude-permission-tool-use-evidence.test.tssrc/main/agent-hooks/claude-permission-tool-use-evidence.tssrc/main/agent-hooks/server.claude-parallel-permission.test.tssrc/main/agent-hooks/server.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/agent-hooks/server.claude-parallel-permission.test.ts
- src/main/agent-hooks/server.ts
패인 이관 병합에서 pending·announced는 시각 정렬 후 상한을 적용하나, completed만 타임스탬프 없는 Set을 위치 기준으로 절단. 목적지 완료 id가 배열 앞을 차지해 방금 완료된 항목이 먼저 축출되고 이관된 패인의 더 오래된 항목이 잔존. Before: - completed: Set<string>, 병합 시 concat 후 뒤에서 상한만큼 슬라이스 - 상한 초과 시 목적지의 최신 완료가 우선 축출 → 그 id의 재전송이 미선언 호출로 보여 열린 프롬프트 오해제 After: - completed: Map<string, number>(id → 완료 시각), announced와 동일 규칙 - 병합·상한 적용을 mergeIdsByRecency로 공용화, 최신순 보존 개선 효과: - 이관 후에도 양쪽 패인의 최신 완료 이력 보존, 오해제 경로 차단 - Map/Set 분기 헬퍼 제거로 두 저장소가 동일 경로 사용, 한쪽만 어긋날 여지 제거 - 상한 초과 병합 회귀 테스트 추가 (이전 구현에서 실패 확인)
자체 3중 리뷰(기능 정확성·적대적·테스트 품질)에서 직전 설계가 만든 오표시 6건 확인. 그중 3건은 승인 대기 중인 다이얼로그를 지우는 오해제로, 사용자가 승인 요청을 인지하지 못한 채 에이전트가 계속 차단되는 최악 등급. 전제 오류 2건이 원인. FIFO 청구는 "선언된 모든 호출이 프롬프트를 띄운다"를 가정했으나 자동 허용 호출은 프롬프트 없이 선언. 안전밸브는 "프롬프트 이후 선언 = 그 프롬프트의 호출"로 봤으나 고착 중 기준 시각이 멈춰 이후 모든 호출이 후보로 편입. Before: - FIFO 소비형 청구 → 자동 허용 형제 id 오청구, 재정렬 시 오청구 - 밸브가 동일 이름·미리보기 완료를 재개 증명으로 수용 → 형제·리플레이· 상한 축출·미리보기 부재(MCP) 경로에서 열린 다이얼로그 해제 - 중복 전달 프롬프트가 형제 id 재사용, 리플레이 프롬프트가 살아있는 id 소비 - 선언·완료 이력 이중 저장으로 상한·TTL이 밸브를 재무장·무장해제 After: - 후보가 정확히 1건일 때만 짝짓기, 2건 이상이면 미부착(기존 동작 유지) - 조회를 읽기 전용으로 전환 → 중복 전달·리플레이가 아무것도 소비 불가 - 프롬프트 이후 도착한 자기 선언을 캐시된 권한 행에 지연 결합 - 밸브 제거, 저장소를 선언 목록 1개로 축소 - PostToolUseFailure는 id 일치 시 재개로 인정 개선 효과: - 오해제 경로 제거, 모호 시 대기 유지로 안전 방향 고정 - 실물 PTY 재현에서 승인 직후 복귀 확인, 지연 선언의 조기 해제 없음 - 서버 수명주기 5경로·턴 경계 테스트 신규 추가로 뮤테이션 미검출 구간 해소 - 상태 대신 id 부착을 단언하도록 교체해 무의미 통과 2건 제거
|
Pushed eb77af3, which simplifies the approach after a self-review round. Flagging it explicitly because it changes what several of the comments above apply to. What happened. Before pushing further fixes I ran three more reviewers over the branch — functional correctness, an adversarial state-machine attack, and a mutation-style test audit. They converged on six regressions the approach had introduced, three of them in the bad direction (the glyph clears while the dialog is still open, so the pane looks busy while the agent is blocked):
Two premises of mine were wrong. FIFO assumed every announced call prompts, but auto-allowed calls are announced without prompting. The valve assumed "announced after the prompt" identifies the prompted call, but the wait is sticky so its timestamp is frozen and every later call qualifies. What the branch does now. A prompt is paired with a call only when exactly one announced call matches; more than one candidate means no id and the pane keeps waiting, as it does on Where that leaves the comments above:
The mutation audit also found the five lifecycle wiring points and the turn-boundary clear could each be deleted with a fully green suite, and that two tests passed for reasons unrelated to their names. Both are fixed: there are now server-level tests asserting the pane's evidence is actually dropped on dismissal, teardown, tab close, stop and transfer, and the two hollow assertions now assert the resolved id instead of the resulting state. Verification on this head: |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/agent-hooks/server.claude-parallel-permission.test.ts (1)
165-178: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert the pane returns to
workingafter the batch's second call resolves.This test asserts
idsbut does not checkcurrentState(server)after the finalreportBack(server, 'git log', 'toolu_b'). Every sibling test that ends in an approval (Lines 94-108, 110-124, 205-221, 223-236) asserts the final'working'state. This test models the exact parallel-batch scenario from issue#11644, so add the missing assertion to verify the pane resumes for the batch case, not just for a single call.✅ Proposed addition
reportBack(server, 'git log', 'toolu_b') + + expect(currentState(server)).toBe('working') expect(ids).toEqual(['toolu_a', 'toolu_b'])
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e5bd0668-81ab-4f2a-946b-685cfd2af184
📒 Files selected for processing (4)
src/main/agent-hooks/claude-permission-tool-use-evidence.test.tssrc/main/agent-hooks/claude-permission-tool-use-evidence.tssrc/main/agent-hooks/server.claude-parallel-permission.test.tssrc/main/agent-hooks/server.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/agent-hooks/claude-permission-tool-use-evidence.test.ts
- src/main/agent-hooks/server.ts
|
Thanks for the re-review. On the one nitpick — the assertion is already there, one line below the quoted range: // src/main/agent-hooks/server.claude-parallel-permission.test.ts:176-180
reportBack(server, 'git log', 'toolu_b')
expect(ids).toEqual(['toolu_a', 'toolu_b'])
expect(currentState(server)).toBe('working') // ← line 179
})The quoted excerpt ends at 178, so the state assertion at 179 fell just outside it. Applying the proposed diff would duplicate it, so I have left the test as is. The batch case does assert both that each prompt paired with its own call and that the pane resumes. Happy to take another look if you meant a different assertion. |
Conflict resolution: main gave `applyNormalizedStatus` an `onAccepted` callback (stablyai#11838, Claude background work), and this branch inserted `updateClaudeAnnouncedToolUses` just above it. Both are kept — the new method stays and the method now takes main's signature. Checked the ordering the ledger depends on rather than only the text: the announcement update still runs before `shouldKeepClaudePermissionVisible` and before every sticky `return previous`, and main's new early return (`providerSessionOnly`) is Pi-gated, so no Claude payload can reach it and skip the ledger.
|
Thanks for digging into this difficult Claude hook-ordering problem and for the substantial test coverage.\n\nWe reproduced the reported sticky permission state on latest main with a real headed Claude 2.1.220 run, and the PR does correct that flow. However, two fresh adversarial reviews found a higher-severity false-clear that makes this implementation unsafe to land:\n\n1. Permission for call A arrives without a tool-use ID.\n2. An indistinguishable auto-allowed sibling B announces first.\n3. The PR treats B as the uniquely matching call.\n4. B completes, and Orca reports “working” while A's permission dialog is still open.\n\nThe identical oracle stays “waiting” on latest main/revert and fails on the published, rebased, and review heads. The candidate heads also share byte-identical production code. Independent authority probes found that the new evidence ledger can mix disconnected SSH connection authority and is not cleared by authority retirement or alias-only PTY teardown; IDs and retained pane ledgers are not byte-bounded.\n\nThis cannot be repaired safely with another timing or uniqueness heuristic because the permission event does not carry provider-authored call identity. A direction that would justify reopening is an exact provider-backed correlation for the permission request, with evidence scoped to connection/launch authority, bounded retention, and green coverage for the late-identical-sibling, reconnect-overwrite, authority-retirement, and alias-teardown oracles.\n\nClosing because the current implementation can hide a permission that still needs user action. We appreciate the thoughtful work and the concrete progress on the original sticky-wait case. |
|
Thanks for the detailed close — reproducing it on a real headed run and writing the failure out step by step made it easy to check rather than take on faith. The false-clear is real, and it is visible in the resolver itself rather than only under timing: // claude-permission-tool-use-evidence.ts
const matches = entries.filter((entry) => isFresh(entry, now) && matchesIdentity(entry, request))
return matches.length === 1 ? matches[0]?.toolUseId : undefined
I also accept the three ledger findings — connection authority mixing, no clearing on authority retirement or alias-only PTY teardown, and unbounded retention. My review passes covered the pairing logic and missed all three lifecycle paths. On the bar you set for reopening: I took the provider-backed identity part upstream rather than trying another heuristic. I captured the raw If that lands, the correlation becomes an equality check and every oracle you listed — late identical sibling, reconnect overwrite, authority retirement, alias teardown — can be met without inference. I would come back with a fresh issue or PR at that point rather than reopening this one, since the implementation would share nothing with what is here. Until then #11644 stays as reported. Thanks again for the time spent on it. |
Summary
Fixes #11644. After approving a Claude permission prompt, the pane glyph, sidebar agent row and worktree dot stay on the amber "needs you" question mark for the rest of the turn while the agent is visibly working, and the row keeps rendering the already-answered approval card — so jumping to the pane to handle the request lands on a pane with nothing to approve.
A cached permission wait suppresses every later
workingevent until it can prove the approved tool resumed, and that proof needs atool_use_idthePermissionRequestpayload never carries. Today it is inherited only from the immediately previous event, so anything that breaks that adjacency — a latePreToolUsePOST, a sibling call of a parallel batch — leaves the wait unprovable. The suppressed events includePreToolUse, so the next prompt of the same turn has nothing to inherit from either.This gives each pane a small, turn-scoped list of the calls Claude announced, and pairs a prompt with its own call from that list:
toolInputis a truncated preview and MCP tools have none, so two live calls can look identical. When more than one candidate matches, no id is attached and the pane keeps waiting — the same outcome as today. Guessing would let a sibling's completion clear a dialog nobody answered, which is worse than a stale amber: the pane looks busy while the agent is blocked.PreToolUse— the ordering reproduced live — the announcement that follows is bound to the waiting row, so the approval that comes after is recognised.PostToolUseFailure, whose payload carries no tool name) resumes on an id match.Screenshots
No visual change— no new or changed UI; this corrects the state an existing indicator is fed. The user-visible delta, as the pane state trace from a real Claude Code session with identical hook arrival order:Testing
pnpm lintpnpm typecheckpnpm test— 41960 passed, 71 skipped, 0 failed (3974 files)pnpm build27 tests across two files. Pairing: batch sibling in between, second prompt of a batch, late announcement, a late announcement that is not the prompted call, identical-looking calls (must refuse), re-delivered prompt, unknown completion, failure completion. Lifecycle: status-row dismissal, pane teardown, tab close, server stop, authority transfer — each asserting the pane's evidence is actually gone or moved. Evidence module: matching, ambiguity, retirement, TTL, per-pane bound, merge order and cap.
Beyond the suite, the fix was driven end to end against a real Claude Code 2.1.220 session in a PTY, with its hooks posting to a real
AgentHookServerand the approval sent by the harness. WithPreToolUsedelivery delayed so it lands after thePermissionRequest(reachable under load given the hook script's 1.5s curl timeout),mainstayswaitingfor the whole turn while this branch returns toworkingthe moment the approved call reports back — and the latePreToolUsedoes not clear the glyph before the approval.AI Review Report
Five independent AI review passes. Every finding below was reproduced with throwaway tests before being acted on, and each fix is pinned by a regression test verified to fail without it.
Correctness and adversarial reviews (first round) — flagged that completed calls were never retired (a later prompt could adopt a dead id), that newest-first lookup handed each prompt its sibling's id when two calls shared a preview, that eviction was wired into only one teardown path, and that pane transfer dropped the destination's evidence. They also killed the first draft's safety valve: matching on tool name + input preview alone cleared a prompt that was still open.
Cross-platform review (macOS / Linux / Windows, incl. WSL) — explicitly checked, no platform-sensitive surface. The diff is main-process TypeScript only: no installer, no
.sh/.cmd/.ps1, no renderer, no shortcut, label or i18n file. The evidence module imports nothing — nonode:path/node:fs/node:os/child_process, noprocess.platform— and touches no disk or shell. Hook payloads reach it in the same shape on every OS: POSIX posts raw stdin viaPOSIX_HOOK_STDIN_READER, Windows viacurl.exe --data-urlencode "payload@-"(chosen precisely to avoid code-page mangling), both landing in the same shared normalizer. WSL and SSH relay ingest re-validate the pane key and run that normalizer before reachingapplyNormalizedStatus. The only key ispaneKey(tabId:uuid, validated) — never a filesystem path. No timers added.Second round, after the bot reviews on this PR — I re-ran three reviewers (functional correctness, adversarial state-machine attack, and a mutation-style test audit) against the then-current branch. They agreed on six regressions the earlier approach had introduced, three of them the bad direction (glyph clears while the dialog is open): the valve accepted any same-name completion for preview-less tools, accepted replayed completions, and re-armed itself when the id caps evicted an old call; the FIFO claim mis-paired an auto-allowed sibling with no packet loss required; a re-delivered prompt could inherit the wrong id. The mutation audit separately showed the five lifecycle wiring points and the turn-boundary clear could all be deleted with a green suite, and that two tests passed for reasons unrelated to what they claimed.
That is what produced the last commit: the valve is gone, pairing refuses to guess, resolution no longer mutates, the two id histories collapsed into one list, the uncovered wiring got tests, and the two hollow assertions now assert the id rather than the state. Net −46 lines against the previous revision.
Security Audit
No new attack surface. Auth, command execution, path handling, secrets and dependencies are untouched.
Stopnever arrives.toolName/toolInputarrive already capped at 60/160 chars by the shared normalizer.paneKeythe status cache already uses, after alias resolution; a caller cannot address a pane it could not already overwrite inlastStatusByPaneKey.randomUUID()token and pane authority checks are untouched. The only authority interaction is the evidence migration insidetransferPaneAuthority, reachable from pane/PTY lifecycle IPC, never from the hook port.exec/spawn, no fs access, no new package. Only tool ids, a tool name, a 160-char input preview and agent id/type are stored.serializeStatusFileiterates the status cache alone, hydrate does not reconstruct it, and nothing new crosses IPC to the renderer. The one at-rest delta is that aPermissionRequestrow inlast-status.jsonnow more often carries atoolUseId— an opaque call id thatPreToolUse/PostToolUserows already persisted.Known follow-up, pre-existing and not addressed here:
tool_use_idhas no length cap in the shared normalizer.Notes
PreToolUsePOST. The previous revision had one, and three of the six regressions above came from it. Without an announcement there is nothing that distinguishes the approved call from any other call of the same tool, so the pane keeps waiting — exactly as it does today.PermissionRequestomitsagent_idwhile their tool events carry it also stay unpaired. Both are pre-existing and orthogonal; happy to follow up if you want either in scope.