Keep headless runs out of the panel

`claude -p` was showing up as a session. It prints one answer and exits:
there is no input line, it cannot be blocked on you, and there is nowhere
to walk over to. A script that runs a few dozen of them turned the panel
into a flicker of chips that were gone before they could be read. The Agent
SDK and editor integrations drive claude the same way and are covered by
the same rule.

The flag is looked for in the arguments of the already-identified claude
process, by exact token, so nothing new has to be discovered -- the pid was
resolved on every event anyway. That resolution moved from apply_event up
into main, which is where the decision has to be made: a headless run is
dropped before the state file is touched at all, so it never creates one
and correspondingly never deletes one on SessionEnd. Its events still reach
the debug log, otherwise "why is my session missing from the panel" would
have nothing to answer with.

Arguments are now read by splitting /proc/<pid>/cmdline on its NUL
separators rather than on spaces. A prompt is an ordinary argument, and
`claude "when do I need -p"` is an interactive session that keeps its chip;
the old space-joined string could not tell the two apart. looks_like_claude
takes the list too, which is what it always wanted -- it was splitting the
joined string back apart itself.

Verified end to end as well as in the classifier: a fake claude runs the
hook as a child through /proc, with -p leaving no file and without -p
leaving one. A real `claude -p` against the installed hook added nothing to
the state directory.
This commit is contained in:
av
2026-08-09 21:35:04 +03:00
parent 2565d45bb5
commit 67d7b14cf5
3 changed files with 118 additions and 35 deletions
+21 -2
View File
@@ -137,8 +137,9 @@ gnome-extensions enable claude-code-status@git.vakhrushev.me
`Stop` и `SessionEnd` зарегистрированы синхронно, в отличие от остальных. Оба
срабатывают, когда процесс вот-вот затихнет, и асинхронный хук, проигравший гонку
с выходом, убивается раньше, чем успевает записать: у `claude -p` это наблюдалось
как сессия, навсегда застрявшая в `busy`.
с выходом, убивается раньше, чем успевает записать. Наблюдалось это на `claude -p`
— теперь такие запуски вообще не отслеживаются (см. ниже), но гонка та же самая у
любой сессии, закрытой сразу после ответа, и стоила бы навсегда застрявшего `busy`.
Хуки одной сессии выполняются параллельно, поэтому весь цикл «прочитать — решить —
записать» идёт под `flock` на `<session_id>.json.lock`, а событие старше
@@ -146,6 +147,24 @@ gnome-extensions enable claude-code-status@git.vakhrushev.me
всё ещё позволяет хуку, прочитавшему старое состояние до `Stop`, записать своё
устаревшее решение после него.
## Неинтерактивные запуски
`claude -p``--print`) в панель не попадает. Такой запуск печатает один ответ
и завершается: строки ввода у него нет, заблокироваться на вас он не может, идти
к нему некуда. Скрипт из пары десятков таких вызовов превращал бы панель в
мельтешение чипов, исчезающих раньше, чем их успеешь прочесть; так же ведут себя
Agent SDK и интеграции с редакторами.
Флаг ищется в аргументах опознанного процесса claude, по точному совпадению
токена. Аргументы читаются из `/proc/<pid>/cmdline` по разделителю `\0`, а не
разбиением по пробелам: промпт — обычный аргумент, и `claude "когда нужен -p"`
это интерактивная сессия, которая свой чип сохраняет.
Отбрасывание происходит до всякой работы с файлом состояния — headless-сессия не
создаёт его и, соответственно, ничего не удаляет на `SessionEnd`. В отладочный
лог (см. ниже) её события при этом попадают: иначе «почему сессии нет в панели»
было бы нечем объяснить.
## Сабагенты
Типичный сценарий: вы просите запустить батч, основной агент разворачивает его и