fix(desktop): scope agent hooks to Superset terminals and add per-agent hooks toggle

Merged
SA
4mo ago
+3453-1219

Links

  • ExecPlan: apps/desktop/plans/done/20260729-1500-agent-hooks-guard-and-per-agent-setting.md
  • Investigation: HOOKS_INVESTIGATION.md (root cause of the reported leak)

Summary

  • Every hook command Superset registers in an agent's global config is now guarded on SUPERSET_HOME_DIR, so it no-ops instantly in agent sessions launched outside Superset terminals. Droid, Codex, and Mastra were writing raw absolute-path commands; they now use the same guarded form as Claude/Grok/Kimi/Vibe.
  • The Cursor/Gemini/Copilot hook scripts and notify.sh itself bail out unless a Superset-supplied env var is present — closing the hole where a foreign session's own session_id payload was enough to make notify.sh curl the Electron notification server.
  • New per-agent "Superset hooks" toggle in Settings → Agents: disabling removes Superset's managed entries from that agent's global config immediately and re-enforces the removal on every startup.

Why / Context

A user running Factory Droid in a plain terminal (outside Superset) saw this on every message:

Hooks Stop
└── SUPERSET_AGENT_ID=droid '/Users/<user>/.superset/hooks/notify.sh' : Exit code 0

Superset deliberately registers hooks in each tool's user-global config (since #2479, because PATH-wrapper injection broke under mise/asdf/ZDOTDIR), with runtime env-var gating as the intended scoping. Droid (#2135) predates the guard (#2621/#5552) and never got it; Codex and Mastra were also unguarded. Full chain of causes in HOOKS_INVESTIGATION.md.

How It Works

  • getManagedNotifyHookCommand(agentId) emits [ -n "$SUPERSET_HOME_DIR" ] && … || true; only Superset-spawned terminals set that var (v2 via host-service env.ts, v1 by inheriting the main process env — pinned by env.test.ts).
  • A shared DYNAMIC_NOTIFY_PATH_MARKER ($SUPERSET_HOME_DIR/hooks/notify.sh) was hoisted into agent-wrappers-common.ts and added to the droid/codex/mastra managed-command predicates. Without it every restart would append a duplicate guarded entry, since the guarded form contains neither an absolute notify path nor a /.superset/ segment. Old unguarded entries are reaped by the existing merge machinery on next startup.
  • Script markers bumped (notify v6, cursor v5, gemini v4, copilot v3) so changed content rewrites. Cursor's bail-out sits after its {"continue":true} permission auto-approve print, so a foreign cursor session is never left blocked (test pins the ordering).
  • The toggle stores a disabled-list (disabled_agent_hooks, migration 0045) so defaults are unchanged for existing installs. Startup runs each config writer's new remove*ManagedHooks() teardown for disabled agents — not just skip — so the choice survives older app versions re-adding entries. settings.setupAgent (Add-agent flow) clears the flag first. Teardowns never create files, preserve user hooks byte-for-byte, and delete wholly-owned files only behind content-signature checks (Amp plugin, Pi extension, Grok hooks file).

Follow-up commit: shared managed-hooks engines (refactor)

The per-agent teardown work made the duplication across config writers structural, so a follow-up commit (638f9ab1b) designs it out — net -781 lines:

  • managed-json-hooks.ts — one merge/remove engine for every agent whose global config is a JSON file of per-event hook entries. Claude/Codex/Droid/Mastra/Cursor/Gemini are now ~30-line declarative specs (config path, events, entry shape, managed-command predicate) instead of six hand-rolled read/strip/append/write implementations.
  • managed-toml-block.ts — marker-block engine for Kimi/Vibe/Grok config.toml (strip + orphaned-block recovery + delete-file-when-only-ours), absorbing three near-identical copies.
  • Registry collapse — the 30-string action union and both string→function runner maps are replaced by one AGENT_SETUP_DEFINITIONS record; adding an agent is now one spec + one registry entry. desktop-agent-capabilities.ts stays pure data so renderer-shared consumers don't pull in fs code.

Two behaviors unified on the safer variant: merges strip stale Superset entries from all events (Codex already did; Claude/Droid didn't), and Mastra/Cursor/Gemini merges now skip an unparseable config instead of overwriting it (matching Claude/Codex and the existing invalid-JSON tests).

Refactor verification:

  • Old vs new writers produce byte-identical output on 26 fixtures (empty / steady-state / dirty-with-stale+user / user-config TOML) — no config churn on upgrade.
  • Live dev app: second boot logs "Verified" for every config (idempotent); toggle off/on round-trip removes/restores guarded entries with user hooks untouched byte-for-byte.
  • 93 tests pass (adds 7 teardown tests — previously untested paths — each mutation-tested to fail when the engine breaks); lint + typecheck clean.

Manual QA Checklist

Guard behavior

  • After app startup, ~/.factory/settings.json / ~/.codex/hooks.json / ~/.mastracode/hooks.json entries all start with [ -n "$SUPERSET_HOME_DIR" ] and contain no absolute /Users/…/notify.sh path; second startup leaves files byte-identical (no duplicates)
  • Droid in a plain (non-Superset) terminal: no lines in /tmp/superset-agent-hooks.log, no request to the notification port; record whether Droid still renders a transcript line for the no-op (plan Decision D6)
  • Droid/Codex inside a Superset workspace terminal: status icon + Stop notification still work end-to-end
  • cursor-agent outside Superset is not left hanging on a permission request (auto-approve still printed before bail-out)

Toggle

  • Settings → Agents → Droid: toggle off removes Superset entries from ~/.factory/settings.json immediately; a hand-seeded user hook in the same file survives byte-for-byte
  • Toggle state survives app restart (entries stay gone / come back guarded)
  • Add-agent flow re-enables a previously disabled agent

Migration

  • Migration applies cleanly on an existing local DB (nullable column, no backfill)

Testing

  • bun run typecheck (desktop + local-db) — clean
  • bun run lint — exit 0
  • bun test apps/desktop/src/main/lib/agent-setup — 88 pass (includes new tests: foreign-session silent exit even with payload session_id; cursor approve-before-bail-out ordering; guarded-command merge idempotence via existing replace-stale tests)

Design Decisions

  • Guard + setting instead of project-scoped registration: only Droid and Claude support project-level hook config, so per-worktree registration can never be the uniform pattern; deferred (with lifecycle-tied registration and a Factory upstream ask for quiet hook rendering) — rationale in the ExecPlan Decision Log.
  • Disabled-list, not enabled-list: null/empty column means today's behavior; no migration backfill, no change for existing users.
  • Codex stays globally registered: its docstring's "works outside the wrapper" fallback only ever mattered for Superset terminals missing the PATH shim — those still export SUPERSET_HOME_DIR, so the guard preserves that case exactly.

Known Limitations

  • Even guarded, tools that render hook executions (Droid) still show a hook line in foreign sessions — it's just an instant no-op now. Fully hiding it needs per-session registration or a Factory-side quiet mode; the toggle is the complete opt-out.
  • The toggle is all-or-nothing per agent: disabling also turns off status icons/notifications for that agent inside Superset (stated in the UI copy).

https://claude.ai/code/session_013p1W5n94DyJaq7qYeg4rK9


Open in Stage

Summary by cubic

Scopes all agent hooks to Superset terminals and adds a per‑agent “Superset hooks” toggle. Refactors setup into shared JSON/TOML engines and hardens it to isolate failures.

  • Bug Fixes

    • Guard all managed hook commands on SUPERSET_HOME_DIR (Droid, Codex, Mastra now match Claude/Grok/Kimi/Vibe).
    • Require Superset terminal vars for cursor, gemini, copilot hooks and notify.sh; Cursor still auto‑approves before exiting. Bump markers to force rewrites: notify v6, cursor v5, gemini v4, copilot v3.
    • Prevent duplicate entries with DYNAMIC_NOTIFY_PATH_MARKER. Setup/teardown isolates per‑action failures, preserves malformed JSON, and signature‑gates deletion of Superset‑owned files (amp plugin, pi extension`, Grok compat).
  • Refactors

    • Shared engines for managed configs: managed-json-hooks.ts (Claude/Codex/Droid/Mastra/Cursor/Gemini) and managed-toml-block.ts (Kimi/Vibe/Grok) unify merge/remove logic; replace action maps with a registry and skip unparseable configs.
    • Settings → Agents: add per‑agent Superset hooks toggle backed by disabled_agent_hooks and run teardown on startup for disabled agents. Align row layout, inline prompt transport toggle, keep hooks copy in a tooltip, and give the switch an accessible name.

Summary by CodeRabbit

  • New Features
    • Added per-agent settings to enable or disable Superset hooks.
    • Added automatic cleanup of Superset-managed agent configuration when hooks are disabled.
  • Bug Fixes
    • Hooks now remain inactive outside Superset terminals.
    • User-managed agent settings and hooks are preserved during setup and cleanup.
    • Improved hook configuration handling across supported agents.
  • Documentation
    • Documented the investigation, risks, and planned safeguards for agent hooks.