Skip to content

fix(agent-hooks): heal stuck permission wait after a denied Claude tool - #15078

Closed
shanchen97 wants to merge 1 commit into
stablyai:mainfrom
shanchen97:fix/claude-permission-deny-stuck-status
Closed

shanchen97 wants to merge 1 commit into
stablyai:mainfrom
shanchen97:fix/claude-permission-deny-stuck-status

Conversation

@shanchen97

Copy link
Copy Markdown

Summary

Denying a Claude Code permission request (Esc / "No") emits no hook event, so the pane's agent status stayed stuck in waiting ("needs permission") until the next prompt or the 30-minute staleness cutoff. User-visible symptom: after denying a permission, review-note send targets ("send to session") stay grayed out with "Agent needs permission" even though the agent is idle.

Fix: watch the Claude session transcript for the structural deny signal. A denied tool never runs, so an is_error tool_result for the pending tool_use_id can only mean the user rejected it (an approved tool resumes through PreToolUse first, which replaces the waiting entry and invalidates the baseline). When the deny record appears, the hook server re-validates the captured baseline (paneKey, prompt, agentType, timestamps) and heals the status to done + interrupted — a racing real hook always wins.

Delivery is fs.watch-driven (reusing createTranscriptNativeWatcher) with no polling fallback: this is best-effort healing, so if a watch cannot bind or the filesystem never delivers events, the pane keeps the pre-existing behavior. Watchers exist only while a Claude tool-permission wait is active and are released on heal, replacement, or the staleness deadline.

Screenshots

No visual change (existing send-target rows simply become clickable once the status heals, driven by already-covered derivation logic).

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build (additionally verified via pnpm build:mac: the packaged app contains the watcher and was used for the real-binary verification below)
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

New tests:

  • claude-permission-deny-transcript-watch.test.ts (11): real temp transcripts — fs.watch-only detection, append detection, backscan of a deny already on disk, different-tool_use_id and success-result ignored, newer status stops the watcher, no-watch guards (no tool_use_id / remote pane / no transcript path / AskUserQuestion), bind-failure gives up without polling, dispose.
  • server.claude-permission-deny.test.ts (5): heals to done+interrupted through ingestRemote, next UserPromptSubmit revives the pane, refuses AskUserQuestion / stale-baseline / non-waiting entries.
  • claude-permission-deny-intent.test.ts (2): wait-classification guard.

Manually verified end to end against a real claude binary (2.1.233) driven inside an Orca e2e instance: real PermissionRequest → pane waiting → Esc deny (zero hook events) → status healed to done+interrupted within seconds via the transcript watch, and the denied file was never written. (The throwaway spec was intentionally not kept in-tree.)

AI Review Report

Review focus and outcomes:

  • Correctness of the deny signal: verified against a captured real transcript that a deny writes {type:"user", message.content[]: {type:"tool_result", tool_use_id, is_error:true}}; approval replaces the waiting entry via PreToolUse before any tool_result lands, so false positives require both a matching tool_use_id and a stale-proof baseline match, which the server re-validates before applying. AskUserQuestion waits are excluded by tool name (they clear via the existing answered-question inference).
  • Race safety: a 1.5 s settle window lets a racing PostToolUse/PreToolUse hook land first; the server-side baseline check (agentType/prompt/receivedAt/stateStartedAt + freshness) makes the inference lose to any newer real event. Watcher lifecycle is subscription-driven; a newer status for the pane stops it.
  • Cross-platform (macOS/Linux/Windows): file access uses node:fs promises with paths taken verbatim from hook payloads (no separator assumptions); createTranscriptNativeWatcher is the existing cross-platform primitive (watches the parent directory, survives file replacement, unref'd so it never blocks shutdown). No shortcuts, labels, or shell behavior involved. Windows panes work like other local panes; WSL transcript paths are unreadable from the host process, fail stat/bind, and the watcher releases without side effects.
  • SSH/remote and folder workspaces: remote panes are excluded up front (connectionId !== null), documented as a known limit — they keep today's behavior. No git or workspace-type assumptions; the watcher keys on pane identity only.
  • Agent/provider neutrality: strictly scoped to agentType === 'claude' tool-permission waits; no other agent's pipeline is touched.
  • Performance: watchers exist only during a Claude permission wait (rare, short-lived, one per pane); no periodic polling — fs events coalesce through a 25 ms debounce; reads are incremental from a stored offset with a 64 KB backscan cap and a 512 KB partial-line cap.

Security Audit

  • Input handling: transcript lines are parsed with a cheap substring pre-filter, then JSON.parse inside try/catch; malformed or hostile lines are ignored. Reads are bounded (64 KB backscan, offset-ranged incremental reads, 512 KB pending-line cap), so a huge transcript cannot balloon memory.
  • Path handling: the watched path comes from Claude's own hook payload (transcript_path) delivered over the token-authenticated localhost hook endpoint; it is only ever read, never written or executed, and only for local panes.
  • No command execution, no new IPC surface, no new dependencies, no secrets. The inference entry point is an internal main-process method (not exposed to the renderer), and applying it requires an exact baseline match on server-held state.
  • Failure modes are fail-safe: unreadable/missing transcript → watcher gives up and the pane keeps the pre-existing (pre-fix) behavior.

Notes

  • Known limit (documented in the module): panes whose transcript this process cannot read — SSH remotes and WSL — keep the stuck waiting state until the next prompt or staleness. The clean upstream fix would be a Claude Code hook fired on permission decision; this PR is the structural workaround available today.
  • The deny signal depends on Claude Code continuing to record rejected tools as is_error tool_results in the transcript. The failure mode if that ever changes is the pre-existing behavior (stuck until next prompt/staleness), not a wrong status.

🤖 Generated with Claude Code

Denying a Claude Code permission request emits no hook event, so the
pane stayed 'waiting' (send targets grayed out) until the next prompt or
30-minute staleness. Watch the session transcript for the structural
deny signal — an is_error tool_result for the pending tool_use_id — and
heal the status to done+interrupted after server-side baseline
revalidation. Delivery is fs.watch-driven with no polling fallback;
local panes only (SSH/WSL transcripts are unreadable from this process).

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

coderabbitai Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds Claude permission-wait detection and a request type for denial inference. AgentHookServer validates inference requests and changes matching waits to interrupted completed turns. A transcript watcher detects denied Claude tool results through filesystem events and targeted reads. It handles initial scans, partial lines, truncation, rebinding, cleanup, and stale events. Main-process startup installs the watcher. Vitest coverage covers inference, filtering, cancellation, replacement, and failure cases.

Merge Risk: 🟡 Moderate · up to 54e8e

This change can incorrectly clear a newer permission request or fail to heal a restored waiting session, leaving agent actions disabled or showing the wrong status. The PR is not merge-ready until the permission baseline includes the specific tool identity and restored waits reliably start transcript monitoring.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes healing a stuck permission wait after Claude denies a tool.
Description check ✅ Passed The description thoroughly covers the problem, implementation, scope, testing, security, and limitations, but omits the required linked issue entry.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

🧹 Nitpick comments (1)
src/main/agent-hooks/claude-permission-deny-transcript-watch.ts (1)

9-19: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten the file header comment.

Reduce this control-flow description to one concise invariant. Keep detailed operational limits in documentation or tests.

As per coding guidelines, comments must be concise, non-obvious, and brief—prefer one line.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2ed1f19b-5a0d-4ea2-a583-77ca2a9ce723

📥 Commits

Reviewing files that changed from the base of the PR and between be07b43 and 54e8ea0.

📒 Files selected for processing (7)
  • src/main/agent-hooks/claude-permission-deny-transcript-watch.test.ts
  • src/main/agent-hooks/claude-permission-deny-transcript-watch.ts
  • src/main/agent-hooks/server.claude-permission-deny.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/index.ts
  • src/shared/claude-permission-deny-intent.test.ts
  • src/shared/claude-permission-deny-intent.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 9 remain after this review.

Comment thread src/main/index.ts
Comment on lines +840 to +842
// Why: denying a Claude permission emits no hook; the transcript's
// rejected tool_result is the structural deny signal for local panes.
installClaudePermissionDenyTranscriptWatch(agentHookServer)

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.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Start watchers for hydrated permission waits.

agentHookServer.start() hydrates status before this call. subscribeEnrichedStatus does not replay cached entries. A local Claude pane restored as waiting never starts a watcher, so a deny already in its transcript cannot heal the pane.

Expose an enriched-status snapshot or add an opt-in replay mode. Subscribe before scanning the snapshot to avoid a startup race. Add a restart test with a hydrated permission wait and an existing denied tool_result.

Comment on lines +7 to +13
export type ClaudePermissionDenyInferenceRequest = {
paneKey: string
baselineUpdatedAt: number
baselineStateStartedAt: number
baselinePrompt: string
baselineAgentType: AgentType | undefined
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Include toolUseId in the permission-wait baseline.

The request does not identify the pending tool. A new local permission wait can retain the same pane, prompt, state, and millisecond timestamps. A delayed deny for the prior tool can then complete the newer wait.

Add a required baseline tool-use ID. Validate it against existing.toolUseId in AgentHookServer.inferClaudePermissionDenied. Replace the watcher timestamp-only duplicate check with a full baseline comparison. Add a same-timestamp replacement test.

@nwparker

Copy link
Copy Markdown
Contributor

Thanks for this, @shanchen97. Since this was opened, main gained OSC 7501 program-status support (#30261), which clears the permission wait when Claude reports idle after a declined prompt — verified with real Claude Code (Escape and No both return the row to Done). This branch also conflicts with the current agent-hooks server, so closing as superseded.

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.

4 participants