fix(init): raise the ensure hook's timeout above cold-start latency (#3438)

## Latest branch refresh

Refreshed cleanly from upstream main to incorporate its Bash
classification fix, which addresses the two inherited failing Bash
tests. All 86 Bash/init/plugin-manifest tests pass after the refresh.
The tested npm installer pin also addresses the Docker OpenClaw
installation crash. New-head CI is running.

## Description

The `headroom init <agent>` Claude Code plugin (and the equivalent hooks
Headroom writes directly for Copilot and Codex) registers `headroom init
hook ensure` on `SessionStart` and `PreToolUse` with a **15-second**
timeout. Starting the proxy from cold measures **15.9-36.9 seconds**,
and the hook's own internal `wait_ready()` call after spawning the proxy
already allows up to **45 seconds**. The external 15s timeout kills the
hook process well before either of those can complete.

Because `PreToolUse` matches `Bash|PowerShell`, this becomes a
**permanent 15-second stall on every single shell tool call, in every
project, in every session**, with no path to self-recovery — the hook
can never win from a cold start.

Closes #3417

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `plugins/headroom-agent-hooks/hooks/hooks.json`: raised both
`SessionStart` and `PreToolUse` hook timeouts from `15` to `60` seconds.
This is the file installed into
`~/.claude/plugins/cache/headroom-marketplace/...` that the issue's
reproduction quotes directly.
- `headroom/cli/init.py`: added `_HOOK_ENSURE_TIMEOUT_SECONDS = 60` and
used it in `_ensure_claude_hooks`, `_ensure_copilot_hooks`, and
`_ensure_codex_hooks` instead of the hardcoded `15`, so the hooks
Headroom writes into a user's own `settings.json` / `hooks.json` carry
the same fixed timeout as the plugin-provided one.
- 60s was chosen to sit comfortably above the existing internal
`wait_ready(timeout_seconds=45)` ceiling in `_ensure_profile_running`,
so the host never kills the hook before that internal wait could have
succeeded on its own.
- `tests/test_cli/test_init_cli.py`: added regression tests asserting
each of the three hook-writing functions emits a timeout greater than
the internal 45s wait.
- `tests/test_plugin_manifests.py`: added a regression test asserting
every hook in the shipped
`plugins/headroom-agent-hooks/hooks/hooks.json` carries a timeout
greater than 45s.

Out of scope for this PR (tracked separately as other aggravating
factors in #3417): `unwrap` not disabling the plugin, hooks being
written in two places at once, and adding a direct-to-upstream fallback
when the proxy is unreachable. Those are independent fixes with their
own risk surface; this PR addresses only the timeout mismatch that makes
the hook unwinnable by construction.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`) — not run; local `mypy`
hits an unrelated numpy-stub/Python-version incompatibility in this
environment, independent of this change
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ python3 -m pytest tests/test_cli/test_init_cli.py tests/test_plugin_manifests.py -q
81 passed in 0.47s

$ python3 -m pytest tests/test_cli/ -q
740 passed, 1 skipped in 10.93s

$ ruff check headroom/cli/init.py tests/test_cli/test_init_cli.py tests/test_plugin_manifests.py
All checks passed!

# Manual run against a sandboxed HOME (real `claude` CLI + real headroom init claude,
# no side effects on the actual machine config):
$ HOME=/tmp/fakehome HEADROOM_MARKETPLACE_SOURCE=$(pwd) python3 -m headroom.cli init --global claude
Configured Claude Code (user scope).
$ cat /tmp/fakehome/.claude/settings.json
{
  "hooks": {
    "SessionStart": [{"hooks": [{"command": "... headroom init hook ensure ...", "timeout": 60}]}],
    "PreToolUse":   [{"hooks": [{"command": "... headroom init hook ensure ...", "timeout": 60}]}]
  },
  ...
}
```

## Real Behavior Proof

- Environment: macOS (Darwin 24.6.0), Python 3.12.3, real `claude` CLI
on PATH, `HOME` sandboxed to a throwaway directory so the run could not
touch the actual machine's `~/.claude` config.
- Exact command / steps: `HOME=<scratch>
HEADROOM_MARKETPLACE_SOURCE=<repo> python3 -m headroom.cli init --global
claude`, then inspected the written `<scratch>/.claude/settings.json`.
- Observed result: the command ran end-to-end (added the marketplace,
installed the plugin, wrote hooks), and the written `settings.json`
carries `"timeout": 60` on both the `SessionStart` and `PreToolUse`
`headroom init hook ensure` entries, confirming the fix takes effect
through the real `headroom init claude` code path, not just the unit
tests. Verified afterward that the real `~/.claude/settings.json` on
this machine was untouched (unchanged mtime, no `headroom-marketplace`
entry).
- Not tested: an actual cold proxy start under a live Claude Code
session timing out (or not) at the old vs. new limit — that requires a
real multi-second proxy cold-start reproduction end-to-end inside Claude
Code itself, which wasn't run. The 15.9-36.9s cold-start figures are
taken from the issue's own measurements; this PR does not independently
re-measure them, it only widens the external timeout to comfortably
exceed the code's own internal 45s wait ceiling.

## Runtime Rollout Safety

- Rollout-managed feature(s): None. The hook timeout is a static value
written into user-owned config files (`settings.json` / `hooks.json`) by
`headroom init`, and in the plugin's bundled `hooks.json` — it is not
behind a feature flag or rollout channel.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: Yes, for new/re-run `headroom init`
invocations and for anyone picking up the updated bundled plugin: the
ensure-hook timeout goes from 15s to 60s. Users who already ran `init`
keep their existing `15` in their local config until they re-run
`headroom init` (this is not auto-migrated).
- Kill switch / disable path: None needed / a user can hand-edit the
`timeout` value in their own `settings.json` or `hooks.json` at any
time.
- Unsafe override required: No.
- Qualification impact: None — this changes only how long the host waits
before killing the `ensure` subprocess; it does not change the proxy's
request/response behavior, pricing, or compression paths.
- Rollback path: Revert this PR; existing users' local config is
unaffected until they re-run `headroom init`, and anyone who already has
`60` written can hand-edit it back to `15` if needed.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation — N/A, no
existing docs reference the 15s hook timeout value
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

The issue (#3417) also flags three other problems with the same hook
system (`unwrap` not disabling the plugin, hooks being registered in two
places at once, and no direct-to-upstream fallback when the proxy is
unreachable). Those are left for separate PRs since each has its own
risk surface and review scope; this PR fixes only the timeout mismatch
that makes the hook unwinnable from a cold start.

---------

Co-authored-by: Jerrett Davis <mxjerrett@gmail.com>
This commit is contained in:
Sudhindra Desai
2026-09-23 21:03:20 -05:00
committed by GitHub
co-authored by Jerrett Davis
parent b958509452
commit 9a1110997a
4 changed files with 78 additions and 5 deletions
+22 -3
View File
@@ -63,6 +63,12 @@ _SUPPORTED_TARGETS = ("claude", "copilot", "codex", "openclaw")
_LOCAL_TARGETS = {"claude", "codex"}
_GLOBAL_TARGETS = {"claude", "copilot", "codex", "openclaw"}
_STARTUP_READY_TIMEOUT_SECONDS = 15
# External kill timeout Claude/Copilot/Codex apply to the `headroom init hook
# ensure` command itself. Must stay above the internal wait_ready(45s) call in
# _ensure_profile_running for a cold start (measured 15.9-36.9s in #3417) --
# otherwise the host kills the hook before a first-ever proxy start can ever
# report ready, and every session is permanently cold.
_HOOK_ENSURE_TIMEOUT_SECONDS = 60
_TOML_TABLE_HEADER_RE = re.compile(r"^[ \t]*(?:\[\[[^\]\r\n]+\]\]|\[[^\]\r\n]+\])[ \t]*(?:#.*)?$")
_TOML_FEATURES_NAME_RE = r"(?:features|\"features\"|'features')"
_TOML_CODEX_HOOKS_NAME_RE = r"(?:codex_hooks|\"codex_hooks\"|'codex_hooks')"
@@ -221,7 +227,7 @@ def _ensure_claude_hooks(path: Path, profile: str, port: int) -> None:
{
"type": "command",
"command": f"{command} --marker {_CLAUDE_HOOK_MARKER}",
"timeout": 15,
"timeout": _HOOK_ENSURE_TIMEOUT_SECONDS,
}
],
}
@@ -245,7 +251,14 @@ def _ensure_copilot_hooks(path: Path, profile: str) -> None:
isinstance(entry, dict) and _COPILOT_HOOK_MARKER in str(entry.get("command", ""))
)
]
retained.append({"type": "command", "command": command, "cwd": ".", "timeout": 15})
retained.append(
{
"type": "command",
"command": command,
"cwd": ".",
"timeout": _HOOK_ENSURE_TIMEOUT_SECONDS,
}
)
hooks[event] = retained
payload["hooks"] = hooks
_write_json(path, payload)
@@ -524,7 +537,13 @@ def _ensure_codex_hooks(path: Path, profile: str) -> None:
retained.append(
{
"matcher": matcher,
"hooks": [{"type": "command", "command": command, "timeout": 15}],
"hooks": [
{
"type": "command",
"command": command,
"timeout": _HOOK_ENSURE_TIMEOUT_SECONDS,
}
],
}
)
hooks[event] = retained
@@ -8,7 +8,7 @@
{
"type": "command",
"command": "headroom init hook ensure",
"timeout": 15
"timeout": 60
}
]
}
@@ -20,7 +20,7 @@
{
"type": "command",
"command": "headroom init hook ensure",
"timeout": 15
"timeout": 60
}
]
}
+40
View File
@@ -452,6 +452,46 @@ def test_ensure_claude_hooks_rewrites_existing_entries(monkeypatch, tmp_path: Pa
assert session_entries[-1]["hooks"][0]["command"].endswith("--marker headroom-init-claude")
def test_ensure_claude_hooks_timeout_exceeds_cold_start_wait(monkeypatch, tmp_path: Path) -> None:
"""The external hook timeout must stay above the internal wait_ready(45s)
call _ensure_profile_running makes after a cold start (#3417), or the host
kills the hook before a first-ever proxy start can ever report ready."""
init_cli, _ = _load_init_module(monkeypatch)
settings_path = tmp_path / "settings.json"
monkeypatch.setattr(init_cli, "_hook_command", lambda *parts: "headroom init hook ensure")
init_cli._ensure_claude_hooks(settings_path, "init-local-demo", 9001)
payload = json.loads(settings_path.read_text(encoding="utf-8"))
for event in ("SessionStart", "PreToolUse"):
timeout = payload["hooks"][event][-1]["hooks"][0]["timeout"]
assert timeout > 45
def test_ensure_copilot_hooks_timeout_exceeds_cold_start_wait(monkeypatch, tmp_path: Path) -> None:
init_cli, _ = _load_init_module(monkeypatch)
config_path = tmp_path / "copilot.json"
monkeypatch.setattr(init_cli, "_hook_command", lambda *parts: "headroom init hook ensure")
init_cli._ensure_copilot_hooks(config_path, "init-user")
payload = json.loads(config_path.read_text(encoding="utf-8"))
for event in ("SessionStart", "PreToolUse"):
assert payload["hooks"][event][-1]["timeout"] > 45
def test_ensure_codex_hooks_timeout_exceeds_cold_start_wait(monkeypatch, tmp_path: Path) -> None:
init_cli, _ = _load_init_module(monkeypatch)
path = tmp_path / "hooks.json"
monkeypatch.setattr(init_cli, "_hook_command", lambda *parts: "headroom init hook ensure")
init_cli._ensure_codex_hooks(path, "init-user")
payload = json.loads(path.read_text(encoding="utf-8"))
for event in ("SessionStart", "PreToolUse"):
assert payload["hooks"][event][-1]["hooks"][0]["timeout"] > 45
def test_ensure_copilot_hooks_replaces_existing_marker(monkeypatch, tmp_path: Path) -> None:
init_cli, _ = _load_init_module(monkeypatch)
config_path = tmp_path / "copilot.json"
+14
View File
@@ -27,6 +27,20 @@ def test_plugin_manifests_share_core_metadata() -> None:
assert copilot["hooks"] == "./hooks"
def test_plugin_hooks_timeout_exceeds_cold_start_wait() -> None:
"""The plugin's `ensure` hooks are killed by the host (Claude Code, etc.)
at their declared `timeout`, independent of anything inside the process.
Headroom's own cold-start path can take up to wait_ready's 45s ceiling
(headroom/cli/init.py), so a shorter external timeout makes the hook
unwinnable by construction on every session start (#3417)."""
hooks = _load_json("plugins/headroom-agent-hooks/hooks/hooks.json")
assert isinstance(hooks, dict)
for event in ("SessionStart", "PreToolUse"):
for entry in hooks["hooks"][event]:
for hook in entry["hooks"]:
assert hook["timeout"] > 45
def test_marketplace_entry_points_to_plugin_root() -> None:
marketplace = _load_json(".claude-plugin/marketplace.json")
assert isinstance(marketplace, dict)