Resolve agent notification targets from live identity at delivery time

Merged
AU
4mo ago
+4551-373

Closes #7939

Symptom

With multiple Claude Code agents in different workspaces, a turn-complete notification (and its unread ring / status pill) intermittently lands on the wrong Claude pane in a different workspace.

Root cause

Hook → pane attribution trusted, in priority order: the persisted session record, a tty-name binding, and spawn-time CMUX_WORKSPACE_ID/CMUX_SURFACE_ID env — none verified against where the agent process actually lives at delivery time:

  • The session record wins over live identity and self-perpetuates once wrong: every later hook re-resolves starting from the stored workspace/surface, which passes validation as long as that workspace still exists. Records get polluted by stale debug.terminals tty rows after hibernation auto-resume and by resume-binding drift (#7391), and go stale on pane moves (#5781).
  • When the resolved surface is no longer listed in the resolved workspace, the CLI silently substituted the old workspace's focused surface — a wrong pane by construction whenever the workspace has more than one pane.
  • App-side, the async delivery path validated the surface against its live workspace but dropped on mismatch instead of retargeting, and the sync path recorded under the stale workspace claim.

Fix — one authoritative live resolution at delivery time

App (Sources/AgentDeliveryTargetResolution.swift, new agent.resolve_delivery_target control method):

  • {pid} probe: the pane that owns the agent process right now, from two independent live signals — the process's controlling tty device matched against every surface's pty device (unique match only), cross-checked against the process's own CMUX_SURFACE_ID environment (a panel UUID is stable pane identity for the process lifetime; only the workspace binding can go stale) re-homed through workspaceContainingPanel. Disagreement or ambiguity refuses to answer rather than guessing.
  • {surface_id} probe: the workspace that currently hosts a known surface (re-homes moved panes).
  • The same resolver now backs every in-app delivery path: queued notifications follow their surface to its current workspace instead of being dropped on a stale claim, notify_target (sync) records under the surface's current workspace instead of misfiling/erroring, and notification click-through re-homes at click time (#2792 class).

CLI (CLI/CMUXCLI+ClaudeHookDeliveryTarget.swift): all Claude hook subcommands (session-start, prompt-submit, stop, notification, push-notification; PreToolUse without probes for per-tool cheapness) route through resolveClaudeHookDeliveryTarget:

  1. live pid target — beats a polluted session record and heals it via the existing upserts + active-pointer self-heal (fixes the #7391 class, including the record being born wrong at SessionStart from a stale tty row);
  2. the #7228 legacy chain (record → caller tty → spawn env), unchanged;
  3. moved-pane re-home when the identity surface is no longer in the resolved workspace (fixes the #5781 class) — instead of borrowing the old workspace's focused surface.

Explicit --workspace/--surface flags bypass the probes, and an app without the new method degrades to the legacy chain exactly as before (covered by a regression test).

Related issues addressed by the shared fix

  • #5781 — stale spawn-time workspace id after pane move: CLI re-home + app-side delivery/click retarget (covers all senders, not just Claude hooks).
  • #7391 — resume/tty-drift record pollution: live pid target outranks and heals the record.
  • #2792 — notification click navigating by the stamped workspace: click-through now re-homes from the surface's current workspace.
  • #7132 — sidebar subtitle feed attribution is a separate telemetry path with an open PR (#7189); not duplicated here.

Tests (two-commit red/green)

Commit 1 adds failing tests, commit 2 the fix:

  • cmuxTests/ClaudeHookLiveDeliveryTargetTests.swift (+ harness): stop prefers the live pid target over a polluted record and heals it; stop follows a moved pane to its current workspace; SessionStart is not poisoned by a stale debug.terminals tty row; legacy routing survives an app without the resolver method.
  • cmuxTests/AgentNotificationLiveRetargetTests.swift: queued and sync deliveries retarget to the surface's current workspace (ring lands on the owning pane only); pure unique-tty-match decision table.

Also manually verified the three CLI scenarios end-to-end against the built binary with a mock control server (polluted record → live pane + healed store; moved pane → new workspace; method-less app → legacy routing).

Not cleanly testable here: the pid→tty kernel probe (proc_pidinfo e_tdev vs. live surface pty devices) needs a real agent process inside a real pane; it's covered indirectly by the pure-function decision-table test and the mocked v2 protocol tests, not by an end-to-end unit test.

Notes

  • Localization audit: no user-facing strings were added or changed (new code emits machine protocol payloads and DEBUG logs only); existing localized strings untouched.
  • Swift budgets: all new files are well under 500 lines; CLI/cmux.swift shrinks by ~30 lines; Sources/TerminalController.swift and Sources/TerminalNotificationQueue.swift are at or below their base line counts. No TSV changes.

🤖 Generated with Claude Code


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.


[!NOTE]
High Risk
Touches agent hook routing, notification delivery/clear semantics, and cross-workspace navigation—high user-visible impact if resolution or fail-closed paths regress; relay boundary changes need careful review.

Overview
Fixes wrong-workspace Claude notifications (#7939) by resolving where an agent lives now at delivery time instead of trusting stale session records, tty rows, or spawn env.

App: Adds agent.resolve_delivery_target (live PID → controlling tty vs pane pty, plus surface → current workspace). Queued/sync notification delivery, clears, and pending-queue discard follow a surface to its current workspace; relay create_for_target stays workspace-bound (retargetsToLiveSurfaceOwner: false). OS notification open/nav carries that flag so clicks can re-home when allowed.

CLI: New resolveClaudeHookDeliveryTarget unifies Claude hooks: prefer live PID probe (skipped on relay / PreToolUse), legacy chain, then surface re-home; SessionEnd cleanup and pane-scoped clear_notifications use the live pane.

Tests: Broad coverage for live routing, lifecycle cleanup, PID auth, and move/clear races.

Reviewed by Cursor Bugbot for commit 7c5e5c19c8c07e319b897c011f7dfedfeb731a3d. Bugbot is set up for automated code reviews on this repo. Configure here.


Summary by cubic

Resolve agent notification targets from live identity at delivery time so rings, status, opens, and clears land on the right pane/workspace across macOS, iOS, and web. Adds a provenance flag so trusted notifications can re‑home while confined ones stay workspace‑scoped; fixes #7939.

  • Bug Fixes
    • App: Adds agent.resolve_delivery_target; queued/sync deliveries retarget to the surface’s current workspace. Clears use live ownership with generation barriers so pending work can’t resurrect; tab/workspace clears resolve each queued entry’s live target. macOS open routing propagates retargetsToLiveSurfaceOwner; pid_t overflow guarded; adds localized delivery‑target error messages.
    • CLI: Routes all Claude hooks through a live target resolver; skips PID probes on relay. PreToolUse keeps cheap routing but re‑homes by surface; SessionEnd cleanup and clears act on the live pane only. Explicit flags bypass; PID auth tightened; legacy path preserved when the app lacks the new method. Success ack aligned to structured {}.
    • Phone/APNs/iOS/web: Push payloads build from stored notifications and include retargetsToLiveSurfaceOwner. Confined/relay payloads omit surfaceId; iOS taps honor the flag and do not cross workspaces; web route policy parses it; macOS open fallback uses it.
    • CI/Tests: Adds a focused CI job for notification routing regressions. Broad coverage for move/clear races, provenance boundaries, PID/auth and relay gating, in‑flight cancellation, and mutation causality; timeouts raised for CI stability.

Summary by CodeRabbit

  • New Features
    • Added fail-closed, live identity–based delivery-target resolution for agent and Claude hooks, with unified CLI routing.
    • Introduced retargetsToLiveSurfaceOwner to control whether terminal notifications can retarget to the live surface owner across opening and mobile push/tap.
  • Bug Fixes
    • Improved notification/status delivery, clearing, and session cleanup accuracy after pane/workspace moves and stale-routed identities.
  • Localization
    • Added user-facing delivery-target error messages (invalid PID, not found, unavailable).
  • Tests
    • Expanded end-to-end and regression coverage for live routing, lifecycle cleanup, PID behavior, move/clear races, and retargeting.