Skip to content

fix(agent-status): register and handle Claude SessionEnd - #14376

Closed
brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/sta-3149-claude-session-end
Closed

brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/sta-3149-claude-session-end

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When a Claude session ends, it can tell Orca so — via a SessionEnd hook. Orca was never listening for it, so a session that quit mid-turn left its spinner running forever. This starts listening.

It is not a complete safety net: two of the most common exit paths don't fire the event at all (upstream bugs, below). It strictly improves coverage on the paths that do work.

What Changed

  • src/main/claude/hook-settings.ts — register SessionEnd in CLAUDE_EVENTS (11 events → 12)
  • src/shared/agent-hook-listener.ts — add the SessionEnd branch to normalizeClaudeEvent
  • src/main/claude/hook-service.test.ts — pin SessionEnd in the remote-install assertion
  • src/shared/agent-hook-listener-claude-session-end.test.ts — new coverage

On SessionEnd the pane is retired: clear the subagent roster, running background tasks, and session crons — otherwise resolveClaudePaneState gates the pane straight back up to working — then land a session-boundary done so notifications and automation runs don't read it as a turn completing.

Two deliberate asymmetries vs SessionStart:

  • Accepts every reason. SessionStart fails closed on unknown sources because it can fire mid-turn. SessionEnd cannot: the session is over. The documented reasons are clear | resume | logout | prompt_input_exit | bypass_permissions_disabled | other, and failing closed on an unrecognized one would forfeit the point of a backstop.
  • Ignores child-attributed events. A SessionEnd carrying agent_id is a subagent's and must not retire the lead's turn.

Why

normalizeClaudeEvent maps unknown event names to null, so before this change SessionEnd was dropped twice over — never registered, and unhandled if it had arrived. Every other lifecycle-complete provider already registers it (devin/hook-settings.ts, grok/hook-service.ts, copilot/hook-service.ts).

Consequence today: a session that exits mid-turn leaves its last non-done row standing. AGENT_STATUS_STALE_AFTER_MS only decays the sidebar dot after 30 minutes; the stored row stays working and re-hydrates on next launch. Orca's own shell wrappers name this gap — the OSC-133 workaround is commented as covering "a stuck 'working' spinner for up to 30 min after the CLI exits without sending a Stop/SessionEnd hook" — and that workaround is disabled for SSH/WSL/remote PTYs.

The SessionEnd contract, as measured on 2.1.231

I verified this rather than assuming it, because it determines what this PR can honestly claim.

Exit path Fires? Evidence
Print mode (-p) session end yes measured: SessionStart, UserPromptSubmit, Stop, SessionEnd all fired
Ctrl+D yes documented + upstream issue #17885
/exit no measured twice (real TTY via pty, and in-app); upstream bug #17885, closed as not planned
/clear no upstream bug #6428, closed as not planned
Ctrl+C no suspends rather than ends; resumes via SessionStart:resume
SIGKILL / terminal close / crash no no opportunity to run

Two further constraints worth knowing:

  • SessionEnd hooks share a ~1.5s budget (raisable via an explicit per-hook timeout). Orca's managed hook shells out to curl with --connect-timeout 0.5 --max-time 1.5, which fits only if the shell spawn is fast. On a loaded machine this could be cut off. Not a regression — the current behavior is that nothing is sent at all — but it argues for an explicit timeout on this entry if we see flakiness.
  • Hooks are snapshotted at session start. Editing settings.json mid-session has no effect, so this only takes effect for sessions started after install.

What this means for STA-3149: the ticket's premise — that registering SessionEnd is "the last line of defense for every missed Stop" — does not hold. The two most common interactive exits are exactly the ones that don't fire. This PR is a real but partial improvement; a complete backstop has to come from a liveness signal (process-exit / foreground-pgroup) rather than a hook. I'd suggest rewriting STA-3149 accordingly and tracking the liveness backstop separately.

Linked Issue

Linear STA-3149 (premise needs correcting — see above). No GitHub issue exists.

Companion PR #14375 fixes a different mechanism behind the same symptom (start-less SubagentStop minting a phantom working); that one is reproduced and verified end to end. The two are independent.

Upstream: anthropics/claude-code #17885 (/exit), #6428 (/clear), #41577 (async work in SessionEnd hooks killed early).

Visual Proof

N/A — no UI or copy change. The user-visible effect is an existing status row resolving to done on session exit rather than persisting.

Registration is observable in a fresh ~/.claude/settings.json written by this build:

before: SessionStart UserPromptSubmit Stop StopFailure SubagentStart SubagentStop
        TeammateIdle PreToolUse PostToolUse PostToolUseFailure PermissionRequest
after:  ... Stop StopFailure SessionEnd SubagentStart ...   (12 events)

Testing

Automated — 5 new normalizer cases plus the remote-install assertion. Verified non-vacuous: removing the registration and the normalizer branch fails exactly 5 tests.

  • npx vitest — 1061 passed / 6 skipped across 64 agent-hook, agent-status, and claude files
  • oxlint + oxfmt clean (pre-commit hook)

Manual (macOS, isolated dev instance, throwaway repo)

  1. Registration lands: a fresh HOME gets SessionEnd in settings.json. ✅
  2. Control — real Claude Code's own hooks reach Orca: SessionStart landed a sessionBoundary: true done row. ✅
  3. Forced the pane to working, exited with /exit. Process exited, PTY stayed alive, row stayed working. ❌ — now explained: /exit does not emit the event (e2e: "ssh docker watcher isolation" is flaky and fails across unrelated SSH PRs #17885).
  4. Isolated confirmation outside Orca: a print-mode session with probe hooks fired SessionEnd; a pty-driven interactive session exited with /exit fired only SessionStart.

Note for reviewers: an earlier round of test 3 was invalid — I had hand-edited the managed settings.json mid-session, which both broke hook delivery and, per the snapshot-at-start rule, could not have taken effect anyway. The runs above are the clean redo with a control.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Review

  • Security — no new input surface. SessionEnd posts through the existing authenticated hook endpoint with the same token, paneKey validation, and fail-closed parsing as every other event.
  • Cross-platform (Linux/Windows/Mac) — CLAUDE_EVENTS drives the POSIX script, the Windows .cmd, and the PowerShell branch from one list, so all three hosts get the event with no per-platform code. Normalizer logic is platform-independent.
  • Remote SSH — no wire change: no new opcode, no new field, and the normalized status crossing the wire is an existing done. A new host with an old client publishes an ordinary done; a new client against an old host simply never receives the event, since old hosts drop unknown names. Remote panes benefit most, as the OSC-133 exit fallback is disabled for SSH/WSL PTYs. Covered by the updated installRemote test.
  • Mobile — no mobile surface changed; mobile consumes the same normalized status.
  • Backwards compatibility — additive. Older Claude builds ignore unregistered event names (the StopFailure precedent), and applyManagedHooks installs idempotently, so existing configs converge on next install.
  • Performance — one additional hook invocation per session exit, and one fewer permanently-stuck row.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred) — targeted lint/tests run locally as listed; full build and remaining typecheck projects left to CI

Author

  • X / Twitter: @BrennanKB5

Orca registered 11 Claude hook events but not SessionEnd, and normalizeClaudeEvent
had no branch for it, so the event was dropped even if it arrived. A session that
exits mid-turn emits no Stop, leaving the pane's non-done row standing until the
30-minute display decay -- which never clears the stored state at all.

Register SessionEnd alongside the other lifecycle events and retire the pane on
it: clear the subagent roster, running background tasks and session crons so
resolveClaudePaneState cannot gate the pane back up, and land a session-boundary
'done' so completion-reactive consumers do not read it as a turn finishing.

Unlike SessionStart this accepts every reason -- failing closed on an unknown one
would forfeit the backstop the event exists to provide -- but a child-attributed
SessionEnd is ignored so a subagent cannot retire the lead's turn.

Live testing did not observe Claude Code 2.1.231 emitting SessionEnd on /exit,
so this does not on its own resolve the stuck-status reports; see the PR body.
@brennanb2025
brennanb2025 marked this pull request as ready for review August 13, 2026 23:58
@coderabbitai

coderabbitai Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Claude hook settings now include a SessionEnd event. The agent hook listener ignores child-attributed session ends, clears session-scoped state, retires the lead turn, and emits a terminal session-boundary status. Tests cover turn retirement, subagent cleanup, boundary metadata, session-end reasons, child-event filtering, and remote hook installation.

Mergeability Score: 🔵 Low · up to befeb

The change registers SessionEnd and resolves qualifying session-end states to done, improving cleanup on supported exit paths. Mergeability is otherwise good, with limited follow-up needed to correct exit-path wording and strengthen regression coverage for task and cron cleanup.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes registering and handling Claude's SessionEnd event.
Description check ✅ Passed The description is detailed, structured, and covers the change, rationale, testing, limitations, and review considerations.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

🧹 Nitpick comments (1)
src/shared/agent-hook-listener-claude-session-end.test.ts (1)

39-54: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert cleanup of task and cron state.

This test only verifies roster cleanup. Populate claudeRunningNonAgentTaskPaneKeys and claudeActiveSessionCronPaneKeys before SessionEnd. Assert that both collections no longer contain paneKey after normalization.

Proposed test extension
     claudeEvent(state, paneKey, {
       hook_event_name: 'SubagentStart',
       agent_id: 'achild-0000000000000011',
       agent_type: 'reviewer'
     })
+    state.claudeRunningNonAgentTaskPaneKeys.add(paneKey)
+    state.claudeActiveSessionCronPaneKeys.add(paneKey)
 
     const ended = claudeEvent(state, paneKey, { hook_event_name: 'SessionEnd', reason: 'other' })
 
     expect(ended?.payload.state).toBe('done')
     expect(state.claudeSubagentRosterByPaneKey.has(paneKey)).toBe(false)
+    expect(state.claudeRunningNonAgentTaskPaneKeys.has(paneKey)).toBe(false)
+    expect(state.claudeActiveSessionCronPaneKeys.has(paneKey)).toBe(false)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 690ae8f7-7e69-4492-b19f-5c9ebd4d5340

📥 Commits

Reviewing files that changed from the base of the PR and between a27d046 and befebae.

📒 Files selected for processing (4)
  • src/main/claude/hook-service.test.ts
  • src/main/claude/hook-settings.ts
  • src/shared/agent-hook-listener-claude-session-end.test.ts
  • src/shared/agent-hook-listener.ts

Comment on lines +43 to +45
// Why: last line of defense for every missed Stop (STA-3149). A session that exits
// mid-turn — /exit, Ctrl+D, crash, interrupt — emits no Stop, so without this the pane
// keeps its non-done row indefinitely. Older Claude builds ignore it (StopFailure precedent).

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Do not state that SessionEnd covers exit paths that do not emit it.

  • src/main/claude/hook-settings.ts#L43-L45: state that SessionEnd handles terminal paths that emit SessionEnd; remove /exit, Ctrl+D, crashes, and interrupts as covered examples.
  • src/main/claude/hook-service.test.ts#L422-L423: state that remote panes benefit only when Claude emits SessionEnd.
  • src/shared/agent-hook-listener-claude-session-end.test.ts#L19-L20: describe the test as handling a received SessionEnd after a missing Stop; do not claim it handles /exit, Ctrl+D, or crashes.

The PR objectives state that /exit, /clear, crashes, and forced termination do not emit SessionEnd. As per coding guidelines, comments must be concise, non-obvious, and brief.

📍 Affects 3 files
  • src/main/claude/hook-settings.ts#L43-L45 (this comment)
  • src/main/claude/hook-service.test.ts#L422-L423
  • src/shared/agent-hook-listener-claude-session-end.test.ts#L19-L20

Source: Coding guidelines

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing this. It isn't worth landing on its own.

Measured on Claude Code 2.1.231: SessionEnd fires on Ctrl+D and non-interactive
session end, but not on /exit or /clear (upstream anthropics/claude-code#17885
and #6428, both closed as not planned), and not on crash or SIGKILL. So it closes
roughly a third of exit paths and cannot be the backstop STA-3149 describes.

Reviewing how comparable agent-workspace implementations handle this: registering a
session-end hook is common, but none of them rely on it to clear run state — the real
mechanism is always a liveness signal (process-exit watch, or a join against
session-alive on read). Registration is a latency optimization on a path those
implementations have already closed by other means.

The right fix is that liveness backstop, which closes every exit path at once —
including the ones no hook covers. Registering SessionEnd becomes a two-line
optimization afterwards, if it's worth anything at all.

The measured hook contract is preserved in the PR body above for whoever picks that up.
STA-3149 needs its premise corrected: "register SessionEnd and you have a backstop for
every missed Stop" does not hold.

Superseded by the real fix in #14375 for the reproduced case.

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