Files
claude-code-gnome-extension/hooks/install.py
T
av 2565d45bb5 Act on four reviews: state machine, resource bounds, teardown
Four agents reviewed this in parallel -- correctness, GNOME integration,
edge cases, security. Everything below was reproduced before being fixed;
several findings that survived the first reading did not survive a probe
and are not here.

State machine, the two that mattered most. A pending permission prompt was
erased by any subagent bookkeeping event: SubagentStop or the next
PreToolUse recomputed the state from scratch, so a session sat at "working"
with a dialog open and nothing ever raised it again. Blocked now outlives
everything except evidence the question was answered. Separately, the
stale-event guard refused whole events, including the subagent counter's
increments and decrements -- but those are deltas and deltas commute, so a
"+1" that lost a timestamp race left the count short and the batch freed
the session while a subagent was still running. The guard now gates the
state decision only.

Corrupt or hostile state files could wedge the panel or take the hook down
for every session: a non-numeric pid raised inside sweep_dead before the
hook wrote its own file, so one bad byte stopped new sessions appearing at
all. Numbers read back from disk are coerced, one unreadable file no longer
aborts the sweep, and a stored timestamp far in the future -- corruption, or
a clock stepped backwards by NTP -- no longer refuses every later event
forever.

Resource bounds, all in the compositor process. A state file was read whole
with no size check: a symlink to /dev/zero took a test process past 4 GB in
three seconds, which in gnome-shell ends the session. Sizes are checked
before the read, sessions and zellij subprocesses are capped, labels
ellipsize, and cwd and messages are truncated at the hook.

Teardown hung off an overridden destroy(), which only runs when JS calls
it. An actor destroyed any other way -- another extension rebuilding the
panel boxes -- left the timer and the file monitor running against a
disposed actor. It is a destroy signal now. The zellij child is killed
rather than merely abandoned.

The glyph was pinned to physical pixels and rendered half-size on HiDPI;
size comes from the stylesheet, and the foreground colour is normalised by
inspection rather than assuming which colour struct the shell hands back.

Chip labels: non-Latin names all collapsed to "?", because the split
treated every Cyrillic letter as a separator -- notable for a tool whose
own README is Russian. Seniority also ranked by time-in-state rather than
session age, so after a shell restart the older session could take the
digit; the hook now records when the session began.

zellij: a dump ends with new_tab_template and swap_tiled_layout blocks
whose tab lines carry no name, and their panes were being attached to the
last real tab -- which then answered for every unmatched directory,
confidently and wrongly.

install.py no longer widens the mode of a settings.json someone narrowed to
0600, no longer overwrites the pristine .bak on a second run, no longer
replaces a symlink out of a dotfiles repository with a regular file, and
quotes the hook path. The debug log is capped and README now says plainly
that it records prompts verbatim.

Not fixed, deliberately: the panel does push the clock about 70 px left
with three labelled chips, which is inherent to putting them in the centre
box; two different projects abbreviating alike still read as one project
with a digit; GNOME 48 remains unverified for the colour struct and for
St.BoxLayout's vertical property, both flagged rather than guessed at.
2026-08-09 20:20:45 +03:00

126 lines
4.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""Register (or remove) the status hooks in ~/.claude/settings.json.
Merges into the existing file rather than rewriting it: settings.json holds
unrelated user configuration, and entries for other tools must survive both
install and uninstall. Ownership is tracked by the command path, so a repo
moved to a new location cleanly replaces its old registration.
Usage: install.py [--uninstall] [--settings PATH]
"""
import json
import os
import shlex
import shutil
import stat
import sys
HOOK = os.path.join(os.path.dirname(os.path.abspath(__file__)), "claude-status-hook.py")
# Stop and SessionEnd are deliberately synchronous. Both fire as claude is
# about to go quiet or exit, and an async child racing that exit gets killed
# 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.
EVENTS = {
"SessionStart": (True, ""),
"UserPromptSubmit": (True, ""),
"Notification": (True, ""),
"PreToolUse": (True, "^(Agent|Task)$"),
"PostToolUse": (True, ""),
"PreCompact": (True, ""),
"SubagentStop": (True, ""),
"Stop": (False, ""),
"SessionEnd": (False, ""),
}
def entry(spec):
async_, matcher = spec
# Claude Code runs the command through a shell, so a repository path
# containing a space -- or worse -- has to survive the trip.
hook = {"type": "command", "command": shlex.quote(HOOK), "timeout": 5}
if async_:
hook["async"] = True
return {"matcher": matcher, "hooks": [hook]}
def is_ours(group):
return any(
h.get("command", "").rstrip("'\"").endswith("claude-status-hook.py")
for h in group.get("hooks", [])
if isinstance(h, dict)
)
def main():
uninstall = "--uninstall" in sys.argv
path = os.path.expanduser("~/.claude/settings.json")
if "--settings" in sys.argv:
try:
path = sys.argv[sys.argv.index("--settings") + 1]
except IndexError:
sys.exit("--settings needs a path")
# Written through, not over: a settings.json symlinked out of a dotfiles
# repository would otherwise be replaced by a regular file, silently
# detaching it from the repository that is supposed to manage it.
path = os.path.realpath(path)
os.makedirs(os.path.dirname(path), exist_ok=True)
try:
with open(path) as fh:
settings = json.load(fh)
except FileNotFoundError:
settings = {}
except ValueError as exc:
sys.exit("refusing to touch malformed %s: %s" % (path, exc))
# Kept from the first run only. Overwriting it on every run would, on the
# second run, replace the pristine copy with the already-modified one --
# which is exactly when someone reaches for a backup.
if os.path.exists(path) and not os.path.exists(path + ".bak"):
shutil.copyfile(path, path + ".bak")
shutil.copymode(path, path + ".bak")
hooks = settings.setdefault("hooks", {})
for event in EVENTS:
groups = [g for g in hooks.get(event, []) if not is_ours(g)]
if not uninstall:
groups.append(entry(EVENTS[event]))
if groups:
hooks[event] = groups
else:
hooks.pop(event, None)
if not hooks:
settings.pop("hooks", None)
# Replaced atomically rather than truncated in place: claude re-reads
# settings.json as it changes, so a running session can be reading this
# exact file, and a truncate-then-stream write hands it invalid JSON.
tmp = "%s.%d.tmp" % (path, os.getpid())
with open(tmp, "w") as fh:
json.dump(settings, fh, indent=2)
fh.write("\n")
# A replace discards the original's mode. settings.json may hold API keys
# and may have been deliberately narrowed to 0600; silently widening it to
# the umask default would undo that without a word.
try:
os.chmod(tmp, stat.S_IMODE(os.stat(path).st_mode))
except OSError:
pass
os.replace(tmp, path)
print("%s %s in %s" % ("removed" if uninstall else "installed", HOOK, path))
print("running sessions pick this up on their own; no restart needed")
if __name__ == "__main__":
main()