Ask the session what is running instead of counting it

A session whose main agent had stopped while a background subagent worked
showed as waiting. The count was kept by hand -- +1 on PreToolUse matched
to ^(Agent|Task)$, -1 on SubagentStop -- and the two halves do not see the
same thing. A launch reaches the hook only at the top level: a subagent
spawning its own subagents does it through events carrying agent_id, which
are dropped. SubagentStop arrives for every subagent at every depth. Each
nested one subtracted from a batch it had never joined.

Measured on the live session that showed it: one background agent, then
fourteen nested stops, the first of which took the count to zero and turned
the chip white with the batch still running. Replaying those recorded
events through the old hook reproduces it exactly, and through the new one
holds busy throughout, rising to two while two background agents ran.

The events carry the answer themselves. Stop and SubagentStop -- the two
that can end a turn, and the only two where it matters -- come with
background_tasks: every running task with its type and status. The count is
now read from there and nothing accumulates, so it cannot drift, and a
subagent that dies without sending SubagentStop no longer leaks a count
that pins the chip at busy. Events without the field leave the stored value
alone, which is what keeps an idle_prompt nudge from freeing a working
session.

A background shell is deliberately not counted. A dev server left running
says nothing about whether the session needs you, and treating it as work
would hold the chip at "working" for as long as it lives.

PreToolUse is no longer registered: counting was the only thing it was for.
It stays listed as a legacy event so that both install and uninstall sweep
it out of settings.json rather than leaving it there to spawn the hook on
every agent launch for nothing.
This commit is contained in:
av
2026-08-23 09:19:30 +03:00
parent f8e85d5703
commit d48a18ae75
4 changed files with 130 additions and 73 deletions
+50 -28
View File
@@ -48,10 +48,11 @@ NOTIFICATION_STATES = {
"agent_completed": "waiting",
}
# Tools that spawn a subagent. Matched again here, not just in the hook
# registration: the matcher is a regex and a mistake there would silently
# inflate the count with TaskCreate, TaskUpdate and the like.
AGENT_TOOLS = {"Agent", "Task"}
# Background tasks that mean the session is still working. A background shell
# is not one: a dev server left running says nothing about whether the session
# needs you, and counting it would pin the chip at "working" for as long as it
# lives.
BUSY_TASK_TYPES = {"subagent"}
# Flags that mean "run one prompt and exit" rather than "open a session". See
# is_headless: such a run has no terminal to be called over to.
@@ -140,22 +141,51 @@ def derive_state(event):
# and that is just as true when the agent that got stuck is a subagent.
if name == "Notification":
return NOTIFICATION_STATES.get(event.get("notification_type"))
# SubagentStop is the counter's decrement and carries agent_id itself, so
# it has to pass the filter below. Its state is decided in apply_event,
# which is where the count is known.
# SubagentStop carries agent_id itself, so it has to pass the filter below.
# It is the one event that can free a session whose main agent stopped a
# long time ago; which way it goes needs the snapshot and is decided in
# apply_event.
if name == "SubagentStop":
return "busy"
# A subagent's own tool calls also reach the parent session's hooks
# (measured: PostToolUse carrying agent_id and agent_type). They are
# ignored, because the count already says a subagent is running and these
# would only add write traffic.
# ignored: the session is working either way, and a single subagent's shell
# commands alone would be hundreds of writes.
if event.get("agent_id"):
return None
if name == "PreToolUse" and event.get("tool_name") not in AGENT_TOOLS:
return None
return EVENT_STATES.get(name)
def running_agents(event):
"""How many subagents the session still has running, or None if this event
does not say.
Read from the event's own ``background_tasks`` rather than counted from
starts and stops. Counting was what this did first, and it was wrong in the
direction that matters: ``PreToolUse`` only ever sees a top-level launch --
a subagent spawning its own subagents does it through hooks carrying
``agent_id``, which are dropped above -- while ``SubagentStop`` arrives for
every subagent at every depth. Each nested one therefore subtracted from a
batch it had never joined, and the session was declared free with its work
still running. Measured live: one background agent, fourteen nested stops
behind it, and a session shown as waiting from the first of them on.
The field is present exactly where it decides something: on ``Stop`` and
``SubagentStop``, the two events that can end a turn. Everywhere else it is
absent, and the stored value stands.
"""
tasks = event.get("background_tasks")
if not isinstance(tasks, list):
return None
running = 0
for task in tasks:
if not isinstance(task, dict):
continue
if task.get("type") in BUSY_TASK_TYPES and task.get("status") == "running":
running += 1
return min(running, 999)
def read_environ(pid):
"""Environment of a process as a dict, empty if it is gone or not ours."""
try:
@@ -402,25 +432,17 @@ def apply_event(event, state, path, now, claude_pid):
previous_ts = 0 # corrupt, and trusting it would freeze this session
stale = previous_ts > now
# The subagent count is different in kind: the mutations are deltas, and
# deltas commute, so every one has to land whatever order it arrives in.
# Dropping a "+1" because its timestamp lost a race leaves the count one
# short, and the batch then frees the session while a subagent is still
# running -- the exact failure counting was added to prevent. The timestamps
# cannot be trusted for this at all: each is taken when its hook process
# starts, tens of milliseconds before it reaches the lock.
if name in ("SessionStart", "UserPromptSubmit"):
# A new turn from you starts a new batch. This also bounds the damage
# when a subagent dies without its SubagentStop ever arriving: the count
# cannot leak past the next thing you type.
agents = 0
elif name == "PreToolUse":
agents += 1
elif name == "SubagentStop":
agents = max(0, agents - 1)
# Applied whether or not this event lost the race above: a snapshot says
# what was running when the event fired, and even a slightly stale one is a
# better answer than a number left over from an older event still. Nothing
# accumulates, so nothing leaks when a subagent dies without ever sending
# its SubagentStop -- the next event carrying a list corrects the count.
snapshot = running_agents(event)
if snapshot is not None:
agents = snapshot
if stale:
# Keep the stored state and flag; the delta above still gets persisted.
# Keep the stored state and flag; the snapshot above still stands.
state = previous.get("state", state)
else:
if name in ("SessionStart", "UserPromptSubmit"):
+11 -9
View File
@@ -23,17 +23,11 @@ HOOK = os.path.join(os.path.dirname(os.path.abspath(__file__)), "claude-status-h
# before it writes -- observed with `claude -p`, which left a session stuck at
# "busy" forever. They fire at most once per turn, so ~20 ms is free; the
# per-tool-call events stay async so they never sit in the agent's loop.
# (async, matcher). PreToolUse is matched to the agent-spawning tools alone:
# unmatched it would fire on every tool call in every session, and the only
# thing it is here for is to count subagents as they start. The pattern is
# anchored because it is a regex -- a bare "Task" also matches TaskCreate,
# TaskUpdate and friends, which are not subagents. The hook re-checks the name
# anyway, in case a future matcher works differently.
# (async, matcher).
EVENTS = {
"SessionStart": (True, ""),
"UserPromptSubmit": (True, ""),
"Notification": (True, ""),
"PreToolUse": (True, "^(Agent|Task)$"),
"PostToolUse": (True, ""),
"PreCompact": (True, ""),
"SubagentStop": (True, ""),
@@ -41,6 +35,14 @@ EVENTS = {
"SessionEnd": (False, ""),
}
# Registered once, no longer. PreToolUse existed to count subagents as they
# started; the count now comes from the snapshot the events carry themselves
# (see running_agents in the hook). Listed rather than forgotten because both
# install and uninstall sweep these out: an entry left behind would go on
# spawning the hook on every agent launch for nothing, and an uninstall that
# leaves our registrations in settings.json is not an uninstall.
LEGACY_EVENTS = ("PreToolUse",)
def entry(spec):
async_, matcher = spec
@@ -90,9 +92,9 @@ def main():
shutil.copymode(path, path + ".bak")
hooks = settings.setdefault("hooks", {})
for event in EVENTS:
for event in list(EVENTS) + list(LEGACY_EVENTS):
groups = [g for g in hooks.get(event, []) if not is_ours(g)]
if not uninstall:
if not uninstall and event in EVENTS:
groups.append(entry(EVENTS[event]))
if groups:
hooks[event] = groups