Skip to content

fix(agent-hooks): resume a Claude pane after an approval instead of pinning it on "needs you" - #11711

Closed
giirrr wants to merge 6 commits into
stablyai:mainfrom
giirrr:fix/claude-permission-resume-evidence
Closed

giirrr wants to merge 6 commits into
stablyai:mainfrom
giirrr:fix/claude-permission-resume-evidence

Conversation

@giirrr

@giirrr giirrr commented Jul 31, 2026 •

Copy link
Copy Markdown

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 working event until it can prove the approved tool resumed, and that proof needs a tool_use_id the PermissionRequest payload never carries. Today it is inherited only from the immediately previous event, so anything that breaks that adjacency — a late PreToolUse POST, a sibling call of a parallel batch — leaves the wait unprovable. The suppressed events include PreToolUse, 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:

  • Pairing is unambiguous or it does not happen. toolInput is 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.
  • Resolution is read-only. A re-delivered prompt resolves to the same call, and a replayed row can neither resolve nor record.
  • Late announcements still bind. When the prompt reaches the server before its own PreToolUse — the ordering reproduced live — the announcement that follows is bound to the waiting row, so the approval that comes after is recognised.
  • A call reporting a failure (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:

                                       main                 this branch
UserPromptSubmit                    →  working              working
PermissionRequest  Bash             →  waiting              waiting
PreToolUse         id=toolu_…       →  (dropped)            (bound to the waiting row, still waiting)
[user approves]
PostToolUse        id=toolu_…       →  (dropped)            working      ← resumes
PermissionRequest  Bash             →  waiting              waiting
… rest of turn                      →  waiting (stuck)      follows the agent

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — 41960 passed, 71 skipped, 0 failed (3974 files)
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

27 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 AgentHookServer and the approval sent by the harness. With PreToolUse delivery delayed so it lands after the PermissionRequest (reachable under load given the hook script's 1.5s curl timeout), main stays waiting for the whole turn while this branch returns to working the moment the approved call reports back — and the late PreToolUse does 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 — no node:path/node:fs/node:os/child_process, no process.platform — and touches no disk or shell. Hook payloads reach it in the same shape on every OS: POSIX posts raw stdin via POSIX_HOOK_STDIN_READER, Windows via curl.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 reaching applyNormalizedStatus. The only key is paneKey (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.

  • Input handling / bounds — ids are trimmed and required non-empty before storage; a re-announced call refreshes its entry rather than queueing a duplicate; the per-pane list is capped at 64 with the oldest dropped, and entries expire after an hour as a backstop for a turn whose Stop never arrives. toolName/toolInput arrive already capped at 60/160 chars by the shared normalizer.
  • Pane-key confusion — the evidence keys on the same normalized, length-validated paneKey the status cache already uses, after alias resolution; a caller cannot address a pane it could not already overwrite in lastStatusByPaneKey.
  • Authentication — the hook token check, per-start randomUUID() token and pane authority checks are untouched. The only authority interaction is the evidence migration inside transferPaneAuthority, reachable from pane/PTY lifecycle IPC, never from the hook port.
  • Command execution / paths / secrets / dependencies — none added; no 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.
  • Persistence and exposure — in-memory only: serializeStatusFile iterates the status cache alone, hydrate does not reconstruct it, and nothing new crosses IPC to the renderer. The one at-rest delta is that a PermissionRequest row in last-status.json now more often carries a toolUseId — an opaque call id that PreToolUse/PostToolUse rows already persisted.
  • DoS / eviction — per event the cost is a ≤64-entry scan plus O(1) map operations, and every teardown path plus each turn boundary drops the pane's entry.

Known follow-up, pre-existing and not addressed here: tool_use_id has no length cap in the shared normalizer.

Notes

  • Why ambiguity is refused rather than resolved. Every heuristic that picks between identical-looking calls has a case where it picks the sibling, and the cost is asymmetric: a wrongly cleared glyph hides a blocked agent, while a wrongly kept glyph resolves itself when the turn ends. So the pairing only fires on an exact, single match.
  • Why there is no fallback for a lost PreToolUse POST. 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.
  • Not addressed here. A denied permission still leaves the pane amber until the turn ends, since no completion ever arrives for it. Subagent prompts whose PermissionRequest omits agent_id while their tool events carry it also stay unpaired. Both are pre-existing and orthogonal; happy to follow up if you want either in scope.

giirrr added 2 commits July 31, 2026 15:31
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-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This 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 tool_use_id only from the immediately-preceding event) broke whenever the PreToolUse POST arrived late or a parallel batch sibling sat between the announcement and the PermissionRequest.

  • New ledger module (claude-permission-tool-use-evidence.ts): a per-pane, turn-scoped store of announced tool_use_ids with a 64-entry cap, 1-hour TTL, and FIFO one-shot claiming, so any PermissionRequest can resolve its id from the full batch regardless of delivery order.
  • Late-announcement binding: when a PreToolUse POST arrives after the dialog is already open, lateResolvedClaudePermissionToolUseId attaches the id to the cached waiting row in place so the subsequent approval is recognised.
  • Five teardown paths wired: deleteStatusEntry, dropStatusEntriesByTabPrefix, clearPaneState, stop(), and transferPaneAuthority all evict or migrate the ledger; the isReplay guard runs before any ledger mutation so relay replays cannot wipe or pollute the live stream's evidence.

Confidence Score: 5/5

Safe 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).

Important Files Changed

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
Loading

Reviews (3): Last reviewed commit: "fix(agent-hooks): 권한-호출 짝짓기를 모호성 거부 방식으로..." | Re-trigger Greptile

Comment thread src/main/agent-hooks/server.ts Resolved
Comment thread src/main/agent-hooks/server.ts Resolved
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b15f175e-b6b2-484f-aab3-66cb630b4e82

📥 Commits

Reviewing files that changed from the base of the PR and between eb77af3 and c344e66.

📒 Files selected for processing (1)
  • src/main/agent-hooks/server.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/agent-hooks/server.ts

📝 Walkthrough

Walkthrough

Added 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)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the primary fix: resuming a Claude pane after approval instead of leaving it in the needs-you state.
Description check ✅ Passed The description covers the user-visible change, testing, review, security, platform compatibility, risks, and follow-up notes required by the template.
Linked Issues check ✅ Passed The implementation addresses issue #11644 through exact tool-call pairing, late announcement handling, completion retirement, and lifecycle cleanup.
Out of Scope Changes check ✅ Passed The changes remain within Claude permission correlation, bounded evidence tracking, lifecycle handling, and regression coverage for issue #11644.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 value

Split rememberId into two typed helpers.

rememberId accepts Set<string> | Map<string, number> and branches on instanceof Map. The at parameter is meaningless for the Set case. 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 value

A completion for an unknown pane creates a ledger that no turn boundary removes.

retireClaudeCompletedToolUse calls ledgerFor, which inserts a new ledger for the pane. A PostToolUse that arrives after the turn boundary cleared the pane, or before any PreToolUse, therefore leaves a ledger holding only completed ids. 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 calling pruneLedger after 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: pruneLedger only deletes when every collection is empty, so the completed id would still be kept here. If you want the entry dropped, gate ledgerFor on an existing ledger instead.


1-9: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Long 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 win

Add a direct assertion for the announced bound.

This test proves the pending queue bound. It does not prove the announced map bound, which shares CLAUDE_PENDING_TOOL_USE_MAX_PER_PANE. An isClaudeToolUseUnaccountedFor assertion 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 win

Add a duplicate PermissionRequest delivery case.

The suite covers a duplicate completion at lines 171-182. It does not cover a duplicate PermissionRequest for a batch whose two calls share the same preview. That sequence exposes the id-stealing path flagged in src/main/agent-hooks/server.ts at attachClaudePermissionToolUseId. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 94cf2f1 and c995eaf.

📒 Files selected for processing (4)
  • src/main/agent-hooks/claude-permission-tool-use-evidence.test.ts
  • src/main/agent-hooks/claude-permission-tool-use-evidence.ts
  • src/main/agent-hooks/server.claude-parallel-permission.test.ts
  • src/main/agent-hooks/server.ts

Comment thread src/main/agent-hooks/server.ts Resolved
Comment thread src/main/agent-hooks/server.ts Resolved
Greptile·CodeRabbit 리뷰에서 드러난 4개 오표시 경로 수정.

Before:
- 턴 경계에서 원장 전체 삭제 → 이전 턴 완료 POST 재전송이 미선언 id로 보여
  새 프롬프트 오해제
- isReplay 가드가 턴 경계 처리 뒤 → 리플레이된 UserPromptSubmit·done이
  진행 중 턴의 원장 삭제
- 중복 전달된 PermissionRequest가 형제 호출 id 재청구 → 그 형제는 잔여 턴
  동안 재개 증명 불가
- 패인 권한 이관이 목적지 원장 덮어쓰기 → 목적지 패인 선언 증거 소실
After:
- 턴 경계는 청구 큐만 비우고 목격 id 이력 유지
- isReplay 가드를 최상단으로 이동
- 중복 프롬프트는 첫 전달이 확정한 id 재사용, 신규 청구보다 우선
- 이관 시 청구 큐·선언·완료 이력 병합(중복 제거 후 상한 적용)
개선 효과:
- 재전송·리플레이·중복 전달·패인 이관 4경로 오표시 제거, 경로별 회귀 테스트
  6건 고정 (전부 수정 전 실패 확인)
- 주석을 레포 규약(간결·1줄 우선)에 맞춰 축약, id 원장 헬퍼 타입 분리
@giirrr

giirrr commented Jul 31, 2026

Copy link
Copy Markdown
Author

Pushed 0babca1 addressing every review comment. Summary of what changed and what I pushed back on.

Applied

  • Replay guard moved ahead of the turn-boundary clear (Greptile, CodeRabbit).
  • Turn boundaries now drop only what is claimable; the seen-id history carries over, so a completion retried from the previous turn is still recognised as a repeat instead of answering the new prompt (Greptile).
  • A re-delivered permission request reuses the id its first delivery resolved, before any new claim (CodeRabbit).
  • moveClaudePendingToolUses merges into a live destination pane instead of replacing its ledger (CodeRabbit).
  • rememberId split into rememberAnnouncedId / rememberCompletedId, dropping the instanceof Map branch and the meaningless at parameter for the set (CodeRabbit nitpick).
  • Comments trimmed to one line where possible across both files, per AGENTS.md (CodeRabbit nitpick).
  • Both suggested tests added: a direct announced bound assertion, and the duplicate PermissionRequest delivery case — which is what surfaced the id-stealing bug above.

Six regression tests were added in total, each verified to fail on the previous commit.

Not applied, with reasoning

retireClaudeCompletedToolUse creating a ledger for a pane that never announced anything is deliberate. When delivery reorders and a completion arrives before its announcement — or before any announcement at all — that id has to be remembered, otherwise its retry looks like an unannounced call and clears a prompt that is still open. That is exactly the failure mode of the Greptile comment on the safety valve. Skipping creation would reintroduce it. The retained data stays inside the per-pane 64-id bound and is dropped at pane teardown; I have added a line at the function explaining why.

Verification on the current head: pnpm lint, pnpm typecheck, pnpm build clean; pnpm test 41952 passed / 71 skipped / 0 failed.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between c995eaf and 0babca1.

📒 Files selected for processing (4)
  • src/main/agent-hooks/claude-permission-tool-use-evidence.test.ts
  • src/main/agent-hooks/claude-permission-tool-use-evidence.ts
  • src/main/agent-hooks/server.claude-parallel-permission.test.ts
  • src/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

giirrr added 2 commits July 31, 2026 16:54
패인 이관 병합에서 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건 제거
@giirrr

giirrr commented Jul 31, 2026

Copy link
Copy Markdown
Author

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):

  • the safety valve accepted any same-name completion for tools without an input preview, i.e. every MCP tool;
  • it accepted replayed completions, since a replay is by construction "never announced";
  • it re-armed itself once the 64-id caps evicted an older call;
  • the FIFO claim mis-paired an auto-allowed sibling — no packet loss, reordering or duplication required, only that the prompted call was not the oldest announced one sharing its preview;
  • a re-delivered prompt could inherit an id belonging to a different call.

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 main. Resolution is read-only, so a re-delivered or replayed prompt consumes nothing. An announcement arriving after the prompt binds to the waiting row, which is what fixes the ordering this issue was reported for. The valve is gone, and the two id histories collapsed into one list. Net −46 lines against the previous revision.

Where that leaves the comments above:

  • Replay guard before the turn-boundary clear — still in place, still tested.
  • Timed-out PostToolUse retry from the previous turn — structurally gone: nothing but a call paired at prompt time can clear a wait, and turn boundaries drop the previous turn's calls.
  • A re-delivered permission request can claim a sibling's id — structurally gone: resolution no longer claims anything.
  • Merge ledgers on pane authority transfer — still implemented, recency-ordered, and now covered by a server-level test as well.
  • Recency ordering for completed ids — the separate completion history no longer exists; a completed call is simply removed from the list.

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: pnpm lint, pnpm typecheck, pnpm build clean; pnpm test 41960 passed / 71 skipped / 0 failed; and the live PTY reproduction still resumes the pane the moment the approved call reports back, with the late PreToolUse not clearing it beforehand.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/main/agent-hooks/server.claude-parallel-permission.test.ts (1)

165-178: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the pane returns to working after the batch's second call resolves.

This test asserts ids but does not check currentState(server) after the final reportBack(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

📥 Commits

Reviewing files that changed from the base of the PR and between 0babca1 and eb77af3.

📒 Files selected for processing (4)
  • src/main/agent-hooks/claude-permission-tool-use-evidence.test.ts
  • src/main/agent-hooks/claude-permission-tool-use-evidence.ts
  • src/main/agent-hooks/server.claude-parallel-permission.test.ts
  • src/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

@giirrr

giirrr commented Jul 31, 2026

Copy link
Copy Markdown
Author

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

OrcaWin commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

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.

@giirrr

giirrr commented Aug 4, 2026

Copy link
Copy Markdown
Author

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

matchesIdentity compares tool name and the truncated input preview. When an identical auto-allowed sibling is the only live announcement, it is by construction the unique match, so the prompt gets paired with a call that was never its own — and that call's completion then retires a dialog nobody answered. The "refuses to guess" guard I added only covers the case where both look-alikes are already announced; it does nothing when the prompt's own announcement has not landed yet, which is exactly the delivery order the original report is about.

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 PermissionRequest hook payload on Claude Code 2.1.221 — 8 captures, two sessions, default and acceptEdits — and tool_use_id is absent from all of them, while PreToolUse and PostToolUse both carry it. The changelog suggests an ordering accident rather than a decision: 2.0.43 added tool_use_id to PreToolUseHookInput and PostToolUseHookInput, and the PermissionRequest hook itself only arrived in 2.0.45. Filed as anthropics/claude-code#83748, with the measurement, the repro, and this PR's review as the evidence that the client side cannot close it safely.

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.

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.

[Bug]: Claude permission wait stays sticky after approval when the approved tool came from a parallel tool batch

4 participants