diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 52c4486d3ff0..298883c980a1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -558,6 +558,29 @@ jobs: echo "::warning::Passwordless sudo unavailable; XCTest will use its default automation-mode setup" fi + - name: Run notification routing regressions + if: ${{ matrix.shard == fromJSON(env.CMUX_APP_HOST_FOCUSED_REGRESSION_SHARD) }} + run: | + # The tolerant full-suite step can accept assertion failures or stop + # after an app-host crash before this suite runs. Keep notification + # move/clear causality coverage on a non-tolerant focused invocation. + set -euo pipefail + SOURCE_PACKAGES_DIR="$PWD/.ci-source-packages" + scripts/ci/run-in-console-session.sh \ + scripts/ci/run-app-host-xcodebuild.sh \ + -project cmux.xcodeproj -scheme cmux-unit -configuration Debug \ + -derivedDataPath "$CMUX_DERIVED_DATA_PATH" \ + -clonedSourcePackagesDirPath "$SOURCE_PACKAGES_DIR" \ + -disableAutomaticPackageResolution \ + -destination "platform=macOS" \ + CMUX_SKIP_ZIG_BUILD=1 \ + -only-testing:cmuxTests/AgentNotificationRegressionTests \ + -only-testing:cmuxTests/ClaudeHookLifecycleCleanupTests \ + -only-testing:cmuxTests/ClaudeHookLiveDeliveryTargetTests \ + -only-testing:cmuxTests/ClaudeHookPIDAuthenticationTests \ + -only-testing:cmuxTests/PhonePushPresenceGateTests \ + test + - name: Run remote tmux mirror detach and placement regressions if: ${{ matrix.shard == fromJSON(env.CMUX_APP_HOST_FOCUSED_REGRESSION_SHARD) }} run: | diff --git a/CLI/CMUXCLI+ClaudeHookDeliveryTarget.swift b/CLI/CMUXCLI+ClaudeHookDeliveryTarget.swift new file mode 100644 index 000000000000..64b03794be77 --- /dev/null +++ b/CLI/CMUXCLI+ClaudeHookDeliveryTarget.swift @@ -0,0 +1,295 @@ +// One authoritative hook-event → live pane resolution for Claude hooks. +// +// Invariant (https://github.com/manaflow-ai/cmux/issues/7939): an agent that +// finishes in pane P of workspace W gets its notification, unread ring, and +// status on exactly P in W. Live identity therefore outranks every persisted +// or spawn-time claim: +// +// 1. current-invocation agent-pid target (`agent.resolve_delivery_target +// {pid}`) — the surface that owns the agent process RIGHT NOW; wins over a polluted +// session record (#7391 resume/tty drift) and heals it via the caller's +// subsequent upsert. Local direct-socket hooks only: a relay-backed +// connection carries a remote host's pid namespace. +// 2. the legacy chain (session record → caller tty → spawn env), each +// validated against a live workspace (unchanged from #7228). +// 3. identity-surface re-home (`agent.resolve_delivery_target +// {surface_id}`) — when the legacy chain would fall back to the resolved +// workspace's focused surface, ask the app which workspace currently +// owns the identity surface and deliver to that pane instead (#5781 +// pane moves; also heals a workspace listing that lags the app's panel +// map when the owner is the same workspace). +// +// Explicit --workspace/--surface flags bypass the live probes entirely, and an +// app without the resolver method degrades to the legacy chain unchanged. + +import Foundation + +extension CMUXCLI { + struct ClaudeHookDeliveryTarget { + let workspaceId: String + let surfaceId: String + /// Resolved from the hook's own identity (live pid target, session + /// record, explicit value, or caller tty) rather than the + /// focused/first-surface fallback. + let isAuthoritative: Bool + } + + /// The per-invocation routing inputs shared by every Claude hook + /// subcommand: explicit flags, spawn-time env fallbacks, the lazy caller + /// binding, and the live agent pid. + struct ClaudeHookRoutingContext { + let workspaceArg: String? + let surfaceArg: String? + let surfaceFlagIsExplicit: Bool + let preferCallerTTYRouting: Bool + let callerTerminalBinding: (() -> CallerTerminalBinding?)? + let agentPid: Int? + /// Frequent events (per-tool PreToolUse) skip the pid/tty scan and + /// rely on records healed by the turn-level hooks. This does NOT gate + /// the cheap `{surface_id}` re-home probe: that probe only fires when + /// the resolved surface was a non-authoritative guess, and disabling + /// it would let a stale record mutate (and, via upsert, re-record) the + /// wrong pane mid-turn. + var allowsPidProbe: Bool = true + } + + private enum LiveAgentDeliveryTargetProbeResult { + case notAttempted + case unsupported + case failed + case resolved(ClaudeHookDeliveryTarget) + } + + func resolveClaudeHookDeliveryTarget( + mappedSession: ClaudeHookSessionRecord?, + routing: ClaudeHookRoutingContext, + client: SocketClient + ) throws -> ClaudeHookDeliveryTarget? { + let pidProbeAllowed = routing.allowsPidProbe && routing.preferCallerTTYRouting + let rehomeAllowed = routing.preferCallerTTYRouting + if pidProbeAllowed { + switch liveAgentPidDeliveryTarget(pid: routing.agentPid, client: client) { + case .resolved(let live): + return live + case .failed: + // A present resolver rejected the current invocation pid. Do + // not promote spawn-environment identity for a fresh session: + // only matching persisted-record + invocation surface identity + // may be re-homed through the app's live ownership map. + let invocationSurfaceId = nonEmptyClaudeHookIdentifier(routing.surfaceArg) + let recordedSurfaceId = nonEmptyClaudeHookIdentifier(mappedSession?.surfaceId) + guard let invocationSurfaceId, + recordedSurfaceId == invocationSurfaceId, + let corroborated = rehomedClaudeHookDeliveryTarget( + surfaceId: invocationSurfaceId, + claimedWorkspaceId: mappedSession?.workspaceId ?? routing.workspaceArg, + client: client + ) else { return nil } + return corroborated + case .notAttempted, .unsupported: + break + } + } + // Surface UUIDs are valid across a relay (unlike pids, which stay + // host-local — that restriction lives in liveAgentPidDeliveryTarget), + // so the surface-only re-home probe runs for relay-backed hooks too. + // Over the restricted cloud CLI bridge the resolver method is denied + // (`remote_cli_method_denied`), which surfaces here as `.failed` and + // stays fail-closed exactly as before. + if !routing.allowsPidProbe, rehomeAllowed { + let invocationSurfaceId = nonEmptyClaudeHookIdentifier(routing.surfaceArg) + let recordedSurfaceId = nonEmptyClaudeHookIdentifier(mappedSession?.surfaceId) + guard let invocationSurfaceId else { return nil } + if let recordedSurfaceId, recordedSurfaceId != invocationSurfaceId { + guard let recordedWorkspaceId = nonEmptyClaudeHookIdentifier(mappedSession?.workspaceId), + !claudeHookSurfaceIsListed( + recordedSurfaceId, + workspaceId: recordedWorkspaceId, + client: client + ) else { return nil } + } + switch liveAgentSurfaceDeliveryTarget( + surfaceId: invocationSurfaceId, + claimedWorkspaceId: mappedSession?.workspaceId ?? routing.workspaceArg, + client: client + ) { + case .resolved(let live): + return live + case .unsupported: + // Older apps do not expose the resolver. Preserve the + // validated legacy chain used before live re-homing existed. + break + case .failed, .notAttempted: + // A present resolver rejected this invocation identity (or + // the identity could not be formed), so stay fail-closed. + return nil + } + } + guard let workspaceId = try resolvePreferredWorkspaceIdForClaudeHook( + preferred: mappedSession?.workspaceId, + fallback: routing.workspaceArg, + preferCallerTTYOverFallback: routing.preferCallerTTYRouting, + callerTerminalBinding: routing.callerTerminalBinding, + client: client + ) else { + // Every workspace claim is dead (e.g. the recorded workspace was + // closed after its pane moved out): follow the identity surface to + // whichever workspace owns it now, else stay a no-op. + guard rehomeAllowed else { return nil } + return rehomedClaudeHookDeliveryTarget( + surfaceId: mappedSession?.surfaceId, + claimedWorkspaceId: mappedSession?.workspaceId, + client: client + ) ?? rehomedClaudeHookDeliveryTarget( + surfaceId: routing.surfaceArg, + claimedWorkspaceId: routing.workspaceArg, + client: client + ) + } + // The record's workspace died (the legacy chain resolved a DIFFERENT + // workspace than the session recorded): the record surface's current + // owner outranks whatever the caller-tty fallback would pick, which + // can be an unrelated pane via a stale tty row. Only if the record + // surface is gone too does the legacy fallback proceed. + if rehomeAllowed, + let recordedWorkspaceId = nonEmptyClaudeHookIdentifier(mappedSession?.workspaceId), + recordedWorkspaceId != workspaceId, + let rehomed = rehomedClaudeHookDeliveryTarget( + surfaceId: mappedSession?.surfaceId, + claimedWorkspaceId: nil, + client: client + ) { + return rehomed + } + let resolvedSurface = try resolvePreferredSurfaceForClaudeHookDetailed( + preferred: mappedSession?.surfaceId, + fallback: routing.surfaceArg, + fallbackIsExplicit: routing.surfaceFlagIsExplicit, + workspaceId: workspaceId, + callerTerminalBinding: routing.callerTerminalBinding, + client: client + ) + if !resolvedSurface.isAuthoritative, rehomeAllowed { + // The legacy chain fell back to a focused-surface guess: the + // identity surface was not in the resolved workspace's listing. + // If the app confirms which workspace currently owns the identity + // surface, that answer wins — whether the pane moved workspaces + // (#5781) or the listing merely lagged the app's panel map and + // the owner is the same workspace (a same-workspace answer still + // outranks the focused-surface guess). + let rehomed = rehomedClaudeHookDeliveryTarget( + surfaceId: mappedSession?.surfaceId, + claimedWorkspaceId: workspaceId, + client: client + ) ?? rehomedClaudeHookDeliveryTarget( + surfaceId: routing.surfaceArg, + claimedWorkspaceId: workspaceId, + client: client + ) + if let rehomed { + return rehomed + } + } + return ClaudeHookDeliveryTarget( + workspaceId: workspaceId, + surfaceId: resolvedSurface.surfaceId, + isAuthoritative: resolvedSurface.isAuthoritative + ) + } + + /// `{pid}` probe: only the current hook invocation's pid may be promoted + /// to live identity. An older app may fall back; a present resolver's + /// rejection must fail closed unless the caller supplies corroborated + /// surface identity (handled by the caller). + private func liveAgentPidDeliveryTarget( + pid: Int?, + client: SocketClient + ) -> LiveAgentDeliveryTargetProbeResult { + // A relay-backed connection means this hook is not running in the + // app's process namespace (SSH/cloud host): its CMUX_CLAUDE_PID is a + // REMOTE pid, and resolving that number against the Mac's local + // process table could match an unrelated local process attached to + // some other pane. Surface/workspace UUIDs are machine-independent, + // so the legacy chain and the {surface_id} re-home probe still apply. + guard !client.isRelayBacked, let pid, pid > 0 else { return .notAttempted } + let payload: [String: Any] + do { + payload = try client.sendV2( + method: "agent.resolve_delivery_target", + params: ["pid": pid], + responseTimeout: 2.0 + ) + } catch let error as CLIError where error.v2Code == "method_not_found" + || error.v2Code == "unrecognized_method" { + return .unsupported + } catch { + return .failed + } + guard + (payload["source"] as? String) == "pid", + let workspaceId = normalizedHandleValue(payload["workspace_id"] as? String), + isUUID(workspaceId), + let surfaceId = normalizedHandleValue(payload["surface_id"] as? String), + isUUID(surfaceId) else { + return .failed + } + return .resolved(ClaudeHookDeliveryTarget( + workspaceId: workspaceId, + surfaceId: surfaceId, + isAuthoritative: true + )) + } + + /// `{surface_id}` probe: the workspace that CURRENTLY owns a known + /// identity surface. Only a `source == "surface"` answer counts. + private func rehomedClaudeHookDeliveryTarget( + surfaceId: String?, + claimedWorkspaceId: String?, + client: SocketClient + ) -> ClaudeHookDeliveryTarget? { + guard case .resolved(let target) = liveAgentSurfaceDeliveryTarget( + surfaceId: surfaceId, + claimedWorkspaceId: claimedWorkspaceId, + client: client + ) else { return nil } + return target + } + + private func liveAgentSurfaceDeliveryTarget( + surfaceId: String?, + claimedWorkspaceId: String?, + client: SocketClient + ) -> LiveAgentDeliveryTargetProbeResult { + guard let surfaceId = nonEmptyClaudeHookIdentifier(surfaceId), isUUID(surfaceId) else { + return .notAttempted + } + var params: [String: Any] = ["surface_id": surfaceId] + if let claimedWorkspaceId = nonEmptyClaudeHookIdentifier(claimedWorkspaceId), isUUID(claimedWorkspaceId) { + params["workspace_id"] = claimedWorkspaceId + } + let payload: [String: Any] + do { + payload = try client.sendV2( + method: "agent.resolve_delivery_target", + params: params, + responseTimeout: 2.0 + ) + } catch let error as CLIError where error.v2Code == "method_not_found" + || error.v2Code == "unrecognized_method" { + return .unsupported + } catch { + return .failed + } + guard + (payload["source"] as? String) == "surface", + let workspaceId = normalizedHandleValue(payload["workspace_id"] as? String), + isUUID(workspaceId) else { + return .failed + } + return .resolved(ClaudeHookDeliveryTarget( + workspaceId: workspaceId, + surfaceId: surfaceId, + isAuthoritative: true + )) + } +} diff --git a/CLI/CMUXCLI+ClaudePushNotificationHook.swift b/CLI/CMUXCLI+ClaudePushNotificationHook.swift index 461e3fb296bf..2032993f2dff 100644 --- a/CLI/CMUXCLI+ClaudePushNotificationHook.swift +++ b/CLI/CMUXCLI+ClaudePushNotificationHook.swift @@ -6,11 +6,7 @@ extension CMUXCLI { telemetry: CLISocketSentryTelemetry, parsedInput: ClaudeHookParsedInput, sessionStore: ClaudeHookSessionStore, - workspaceArg: String?, - surfaceArg: String?, - hookSurfaceFlagIsExplicit: Bool, - preferCallerTTYRouting: Bool, - callerTTYBindingProvider: (() -> CallerTerminalBinding?)?, + routing: ClaudeHookRoutingContext, markFeedTelemetryHandled: () -> Void, sendFeedTelemetry: (String?, String?) -> Void ) throws { @@ -36,11 +32,9 @@ extension CMUXCLI { return } let mappedSession = parsedInput.sessionId.flatMap { try? sessionStore.lookup(sessionId: $0) } - guard let workspaceId = try resolvePreferredWorkspaceIdForClaudeHook( - preferred: mappedSession?.workspaceId, - fallback: workspaceArg, - preferCallerTTYOverFallback: preferCallerTTYRouting, - callerTerminalBinding: callerTTYBindingProvider, + guard let resolvedTarget = try resolveClaudeHookDeliveryTarget( + mappedSession: mappedSession, + routing: routing, client: client ) else { markFeedTelemetryHandled() @@ -48,14 +42,8 @@ extension CMUXCLI { printClaudeHookAck() return } - let resolvedSurface = try resolvePreferredSurfaceForClaudeHookDetailed( - preferred: mappedSession?.surfaceId, - fallback: surfaceArg, - fallbackIsExplicit: hookSurfaceFlagIsExplicit, - workspaceId: workspaceId, - callerTerminalBinding: callerTTYBindingProvider, - client: client - ) + let workspaceId = resolvedTarget.workspaceId + let resolvedSurface = resolvedTarget let surfaceId = resolvedSurface.surfaceId sendFeedTelemetry(workspaceId, surfaceId) guard shouldApplyClaudeHookVisibleMutation( diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 2dc507a0cc1e..45ee73a1a440 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -23946,6 +23946,14 @@ struct CMUXCLI { return callerTTYBindingCache } let callerTTYBindingProvider: (() -> CallerTerminalBinding?)? = preferCallerTTYRouting ? callerTTYBinding : nil + let hookRouting = ClaudeHookRoutingContext( + workspaceArg: workspaceArg, + surfaceArg: surfaceArg, + surfaceFlagIsExplicit: hookSurfaceFlag != nil, + preferCallerTTYRouting: preferCallerTTYRouting, + callerTerminalBinding: callerTTYBindingProvider, + agentPid: claudeAgentPID(from: ProcessInfo.processInfo.environment) + ) let rawInput = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8) ?? "" let parsedInput = parseClaudeHookInput(rawInput: rawInput) let sessionStore = ClaudeHookSessionStore() @@ -23958,7 +23966,6 @@ struct CMUXCLI { "has_surface_flag": optionValue(hookArgs, name: "--surface") != nil ] ) - var didSendFeedTelemetry = false func sendClaudeFeedTelemetry(workspaceId: String? = nil, surfaceId: String? = nil) { didSendFeedTelemetry = true @@ -23980,11 +23987,9 @@ struct CMUXCLI { switch subcommand { case "session-start", "active": telemetry.breadcrumb("claude-hook.session-start") - guard let workspaceId = try resolvePreferredWorkspaceIdForClaudeHook( - preferred: nil, - fallback: workspaceArg, - preferCallerTTYOverFallback: preferCallerTTYRouting, - callerTerminalBinding: callerTTYBindingProvider, + guard let resolvedTarget = try resolveClaudeHookDeliveryTarget( + mappedSession: nil, + routing: hookRouting, client: client ) else { didSendFeedTelemetry = true @@ -23992,14 +23997,8 @@ struct CMUXCLI { printClaudeHookAck() return } - let resolvedSurface = try resolvePreferredSurfaceForClaudeHookDetailed( - preferred: nil, - fallback: surfaceArg, - fallbackIsExplicit: hookSurfaceFlag != nil, - workspaceId: workspaceId, - callerTerminalBinding: callerTTYBindingProvider, - client: client - ) + let workspaceId = resolvedTarget.workspaceId + let resolvedSurface = resolvedTarget let surfaceId = resolvedSurface.surfaceId sendClaudeFeedTelemetry(workspaceId: workspaceId, surfaceId: surfaceId) let claudePid = claudeAgentPID(from: ProcessInfo.processInfo.environment) @@ -24090,7 +24089,7 @@ struct CMUXCLI { ) } if isClearSessionStart, !suppressVisibleMutations { - _ = try? sendV1Command("clear_notifications --tab=\(workspaceId)", client: client) + _ = try? sendV1Command("clear_notifications --tab=\(workspaceId)\(socketPanelOption(surfaceId))", client: client) setAgentLifecycle( client: client, key: Self.claudeCodeStatusKey, @@ -24116,11 +24115,9 @@ struct CMUXCLI { // Turn ended. Don't consume session or clear PID — Claude is still alive. // Notification hook handles user-facing notifications; SessionEnd handles cleanup. let mappedSession = parsedInput.sessionId.flatMap { try? sessionStore.lookup(sessionId: $0) } - guard let workspaceId = try resolvePreferredWorkspaceIdForClaudeHook( - preferred: mappedSession?.workspaceId, - fallback: workspaceArg, - preferCallerTTYOverFallback: preferCallerTTYRouting, - callerTerminalBinding: callerTTYBindingProvider, + guard let resolvedTarget = try resolveClaudeHookDeliveryTarget( + mappedSession: mappedSession, + routing: hookRouting, client: client ) else { didSendFeedTelemetry = true @@ -24128,14 +24125,8 @@ struct CMUXCLI { printClaudeHookAck() return } - let resolvedSurface = try resolvePreferredSurfaceForClaudeHookDetailed( - preferred: mappedSession?.surfaceId, - fallback: surfaceArg, - fallbackIsExplicit: hookSurfaceFlag != nil, - workspaceId: workspaceId, - callerTerminalBinding: callerTTYBindingProvider, - client: client - ) + let workspaceId = resolvedTarget.workspaceId + let resolvedSurface = resolvedTarget let surfaceId = resolvedSurface.surfaceId let claudePid = mappedSession?.pid ?? claudeAgentPID(from: ProcessInfo.processInfo.environment) let suppressVisibleMutations = shouldSuppressNestedAgentVisibleMutations( @@ -24259,11 +24250,9 @@ struct CMUXCLI { case "prompt-submit": telemetry.breadcrumb("claude-hook.prompt-submit") let mappedSession = parsedInput.sessionId.flatMap { try? sessionStore.lookup(sessionId: $0) } - guard let workspaceId = try resolvePreferredWorkspaceIdForClaudeHook( - preferred: mappedSession?.workspaceId, - fallback: workspaceArg, - preferCallerTTYOverFallback: preferCallerTTYRouting, - callerTerminalBinding: callerTTYBindingProvider, + guard let resolvedTarget = try resolveClaudeHookDeliveryTarget( + mappedSession: mappedSession, + routing: hookRouting, client: client ) else { didSendFeedTelemetry = true @@ -24271,14 +24260,8 @@ struct CMUXCLI { printClaudeHookAck() return } - let resolvedSurface = try resolvePreferredSurfaceForClaudeHookDetailed( - preferred: mappedSession?.surfaceId, - fallback: surfaceArg, - fallbackIsExplicit: hookSurfaceFlag != nil, - workspaceId: workspaceId, - callerTerminalBinding: callerTTYBindingProvider, - client: client - ) + let workspaceId = resolvedTarget.workspaceId + let resolvedSurface = resolvedTarget let surfaceId = resolvedSurface.surfaceId let claudePid = mappedSession?.pid ?? claudeAgentPID(from: ProcessInfo.processInfo.environment) let suppressVisibleMutations = shouldSuppressNestedAgentVisibleMutations( @@ -24350,7 +24333,7 @@ struct CMUXCLI { launchCommand: mappedSession?.launchCommand ?? firstSightingLaunchCommand ) } - _ = try sendV1Command("clear_notifications --tab=\(workspaceId)", client: client) + _ = try sendV1Command("clear_notifications --tab=\(workspaceId)\(socketPanelOption(surfaceId))", client: client) setAgentLifecycle( client: client, key: Self.claudeCodeStatusKey, @@ -24419,11 +24402,9 @@ struct CMUXCLI { let classifiedSubtitle = summary.subtitle let mappedSession = parsedInput.sessionId.flatMap { try? sessionStore.lookup(sessionId: $0) } - guard let workspaceId = try resolvePreferredWorkspaceIdForClaudeHook( - preferred: mappedSession?.workspaceId, - fallback: workspaceArg, - preferCallerTTYOverFallback: preferCallerTTYRouting, - callerTerminalBinding: callerTTYBindingProvider, + guard let resolvedTarget = try resolveClaudeHookDeliveryTarget( + mappedSession: mappedSession, + routing: hookRouting, client: client ) else { didSendFeedTelemetry = true @@ -24431,19 +24412,13 @@ struct CMUXCLI { printClaudeHookAck() return } + let workspaceId = resolvedTarget.workspaceId let claudePid = mappedSession?.pid ?? claudeAgentPID(from: ProcessInfo.processInfo.environment) let suppressVisibleMutations = shouldSuppressNestedAgentVisibleMutations( currentAgentPID: claudePid, env: ProcessInfo.processInfo.environment ) - let resolvedSurface = try resolvePreferredSurfaceForClaudeHookDetailed( - preferred: mappedSession?.surfaceId, - fallback: surfaceArg, - fallbackIsExplicit: hookSurfaceFlag != nil, - workspaceId: workspaceId, - callerTerminalBinding: callerTTYBindingProvider, - client: client - ) + let resolvedSurface = resolvedTarget let surfaceId = resolvedSurface.surfaceId sendClaudeFeedTelemetry(workspaceId: workspaceId, surfaceId: surfaceId) guard shouldApplyClaudeHookVisibleMutation( @@ -24566,7 +24541,7 @@ struct CMUXCLI { } _ = try sendV1Command("notify_target_async \(workspaceId) \(surfaceId) \(payload)", client: client) printClaudeHookAck() - case "push-notification": try runClaudePushNotificationHook(client: client, telemetry: telemetry, parsedInput: parsedInput, sessionStore: sessionStore, workspaceArg: workspaceArg, surfaceArg: surfaceArg, hookSurfaceFlagIsExplicit: hookSurfaceFlag != nil, preferCallerTTYRouting: preferCallerTTYRouting, callerTTYBindingProvider: callerTTYBindingProvider, markFeedTelemetryHandled: { didSendFeedTelemetry = true }, sendFeedTelemetry: sendClaudeFeedTelemetry) + case "push-notification": try runClaudePushNotificationHook(client: client, telemetry: telemetry, parsedInput: parsedInput, sessionStore: sessionStore, routing: hookRouting, markFeedTelemetryHandled: { didSendFeedTelemetry = true }, sendFeedTelemetry: sendClaudeFeedTelemetry) case "session-end": telemetry.breadcrumb("claude-hook.session-end") // A fork launch that exits before its first prompt fires SessionEnd @@ -24593,25 +24568,18 @@ struct CMUXCLI { currentAgentPID: forkClaudePid, env: ProcessInfo.processInfo.environment ) + // Resolve through the live target resolver so the cleanup + // follows the fork pane even after a pane move (live pid + // probe, then legacy chain, then identity-surface re-home). if !suppressForkVisibleMutations, - let forkWorkspaceId = try? resolvePreferredWorkspaceIdForClaudeHook( - preferred: nil, - fallback: workspaceArg, - preferCallerTTYOverFallback: preferCallerTTYRouting, - callerTerminalBinding: callerTTYBindingProvider, - client: client - ), - let forkSurface = try? resolvePreferredSurfaceForClaudeHookDetailed( - preferred: nil, - fallback: surfaceArg, - fallbackIsExplicit: hookSurfaceFlag != nil, - workspaceId: forkWorkspaceId, - callerTerminalBinding: callerTTYBindingProvider, + let forkTarget = try? resolveClaudeHookDeliveryTarget( + mappedSession: nil, + routing: hookRouting, client: client ), - forkSurface.isAuthoritative { + forkTarget.isAuthoritative { _ = try? sendV1Command( - "clear_agent_pid \(Self.claudeCodeStatusKey) --tab=\(forkWorkspaceId)\(socketPanelOption(forkSurface.surfaceId)) --clear-status", + "clear_agent_pid \(Self.claudeCodeStatusKey) --tab=\(forkTarget.workspaceId)\(socketPanelOption(forkTarget.surfaceId)) --clear-status", client: client ) } @@ -24623,48 +24591,72 @@ struct CMUXCLI { // If Stop already consumed the session, consumedSession is nil and we skip // to avoid wiping the completion notification that Stop just delivered. let mappedSession = parsedInput.sessionId.flatMap { try? sessionStore.lookup(sessionId: $0) } - let fallbackWorkspaceId = try? resolvePreferredWorkspaceIdForClaudeHook( - preferred: mappedSession?.workspaceId, - fallback: workspaceArg, - preferCallerTTYOverFallback: preferCallerTTYRouting, - callerTerminalBinding: callerTTYBindingProvider, + // Resolve the pane's CURRENT owner before consuming the record: + // SessionEnd can be the only hook after a pane move (Ctrl-C exit + // with no later Stop/Notification to heal the record), and cleanup + // must clear status/notifications where the pane lives NOW. + // Clearing the record's stale workspace instead leaves the moved + // pane stuck and `clear_notifications --tab=` would wipe unrelated + // panes' notifications in the old workspace. + guard let liveEndTarget = try? resolveClaudeHookDeliveryTarget( + mappedSession: mappedSession, + routing: hookRouting, client: client - ) - let fallbackSurfaceId: String? = { - guard let fallbackWorkspaceId else { return nil } - return try? resolvePreferredSurfaceIdForClaudeHook( - preferred: mappedSession?.surfaceId, - fallback: surfaceArg, - fallbackIsExplicit: hookSurfaceFlag != nil, - workspaceId: fallbackWorkspaceId, - callerTerminalBinding: callerTTYBindingProvider, - client: client - ) - }() + ) else { + // Keep the persisted route so a later authoritative cleanup + // can still clear the visible state this attempt could not. + didSendFeedTelemetry = true + telemetry.breadcrumb("claude-hook.session-end.unresolved") + printClaudeHookAck() + return + } let consumedSession = try? sessionStore.consume( sessionId: parsedInput.sessionId, - workspaceId: fallbackWorkspaceId, - surfaceId: fallbackSurfaceId, + workspaceId: liveEndTarget.workspaceId, + surfaceId: liveEndTarget.surfaceId, turnId: parsedInput.turnId ) // consume() calls clearActiveSessionIfMatching before returning // consumedSession, so isCurrent can treat consumedSession.sessionId // as current only when the consumed session was the active one. if let consumedSession { - let workspaceId = consumedSession.workspaceId + // App-visible cleanup targets the live owner of the session's + // pane when the resolver answered authoritatively; the + // consumed record's address is the fallback. Store-side calls + // keep the record's own address. + let workspaceId: String + let cleanupSurfaceId: String + if liveEndTarget.isAuthoritative { + workspaceId = liveEndTarget.workspaceId + cleanupSurfaceId = liveEndTarget.surfaceId + } else { + workspaceId = consumedSession.workspaceId + cleanupSurfaceId = consumedSession.surfaceId + } clearAgentSurfaceResumeBinding( client: client, workspaceId: workspaceId, - surfaceId: consumedSession.surfaceId, + surfaceId: cleanupSurfaceId, sessionId: consumedSession.sessionId ) - sendClaudeFeedTelemetry(workspaceId: workspaceId, surfaceId: consumedSession.surfaceId) + if cleanupSurfaceId != consumedSession.surfaceId { + clearAgentSurfaceResumeBinding( + client: client, + workspaceId: consumedSession.workspaceId, + surfaceId: consumedSession.surfaceId, + sessionId: consumedSession.sessionId + ) + } + sendClaudeFeedTelemetry(workspaceId: workspaceId, surfaceId: cleanupSurfaceId) + // Staleness is judged on the pane being CLEANED: gating on a + // polluted record surface (#7391) could false-skip cleanup of + // the real pane, stranding its ring/status after exit. let shouldClearVisibleState = shouldApplyClaudeHookVisibleMutation( sessionStore: sessionStore, sessionId: consumedSession.sessionId, turnId: parsedInput.turnId, workspaceId: workspaceId, - surfaceId: consumedSession.surfaceId, + surfaceId: cleanupSurfaceId, telemetry: telemetry ) let claudePid = consumedSession.pid ?? claudeAgentPID(from: ProcessInfo.processInfo.environment) @@ -24674,15 +24666,20 @@ struct CMUXCLI { ) if shouldClearVisibleState, !suppressVisibleMutations { _ = try? sendV1Command( - "clear_agent_pid \(Self.claudeCodeStatusKey) --tab=\(workspaceId)\(socketPanelOption(consumedSession.surfaceId)) --clear-status", + "clear_agent_pid \(Self.claudeCodeStatusKey) --tab=\(workspaceId)\(socketPanelOption(cleanupSurfaceId)) --clear-status", client: client ) try? sessionStore.clearAgentLifecycleIfPresent( sessionId: consumedSession.sessionId, - workspaceId: workspaceId, + workspaceId: consumedSession.workspaceId, surfaceId: consumedSession.surfaceId ) - _ = try? sendV1Command("clear_notifications --tab=\(workspaceId)", client: client) + // Lifecycle cleanup is always pane-scoped: a workspace can + // host multiple agents whose notifications are independent. + _ = try? sendV1Command( + "clear_notifications --tab=\(workspaceId)\(socketPanelOption(cleanupSurfaceId))", + client: client + ) } else { telemetry.breadcrumb("claude-hook.session-end.stale") } @@ -24701,11 +24698,15 @@ struct CMUXCLI { // Clears "Needs input" status and notification when Claude resumes work // (e.g. after permission grant). Runs async so it doesn't block tool execution. let mappedSession = parsedInput.sessionId.flatMap { try? sessionStore.lookup(sessionId: $0) } - guard let workspaceId = try resolvePreferredWorkspaceIdForClaudeHook( - preferred: mappedSession?.workspaceId, - fallback: workspaceArg, - preferCallerTTYOverFallback: preferCallerTTYRouting, - callerTerminalBinding: callerTTYBindingProvider, + // Skip only the pid/tty scan per tool call; the cheap + // `{surface_id}` re-home probe stays enabled so a mid-turn pane + // move cannot make this hook mutate (and re-record) the old + // workspace's focused pane. + var preToolUseRouting = hookRouting + preToolUseRouting.allowsPidProbe = false + guard let resolvedTarget = try resolveClaudeHookDeliveryTarget( + mappedSession: mappedSession, + routing: preToolUseRouting, client: client ) else { didSendFeedTelemetry = true @@ -24713,14 +24714,8 @@ struct CMUXCLI { printClaudeHookAck() return } - let resolvedSurface = try resolvePreferredSurfaceForClaudeHookDetailed( - preferred: mappedSession?.surfaceId, - fallback: surfaceArg, - fallbackIsExplicit: hookSurfaceFlag != nil, - workspaceId: workspaceId, - callerTerminalBinding: callerTTYBindingProvider, - client: client - ) + let workspaceId = resolvedTarget.workspaceId + let resolvedSurface = resolvedTarget let surfaceId = resolvedSurface.surfaceId sendClaudeFeedTelemetry(workspaceId: workspaceId, surfaceId: surfaceId) let claudePid = mappedSession?.pid ?? claudeAgentPID(from: ProcessInfo.processInfo.environment) @@ -24776,9 +24771,14 @@ struct CMUXCLI { } else { needsInputBody = describeExitPlanMode(parsedInput.object) ?? waitingBody } - // Preserve a non-empty surfaceId from SessionStart; passing "" - // would overwrite it and cause notifications to target the wrong workspace. - let existingSurfaceId = nonEmptyClaudeHookIdentifier(mappedSession?.surfaceId) ?? surfaceId + // An authoritative live resolution outranks the persisted + // session surface (stale after a pane move); re-preferring it + // would re-pollute the record and pin the blocking prompt on + // the wrong pane. A focused-guess resolution keeps the + // recorded surface ("" would overwrite it and misroute). + let existingSurfaceId = resolvedSurface.isAuthoritative + ? surfaceId + : (nonEmptyClaudeHookIdentifier(mappedSession?.surfaceId) ?? surfaceId) try? sessionStore.upsert( sessionId: sessionId, workspaceId: workspaceId, @@ -24853,7 +24853,7 @@ struct CMUXCLI { agentLifecycle: .running ) } - _ = try? sendV1Command("clear_notifications --tab=\(workspaceId)", client: client) + _ = try? sendV1Command("clear_notifications --tab=\(workspaceId)\(socketPanelOption(surfaceId))", client: client) setAgentLifecycle( client: client, key: Self.claudeCodeStatusKey, diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobilePushCoordinator.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobilePushCoordinator.swift index 27fb8019e5b0..b0cf101aa08d 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobilePushCoordinator.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobilePushCoordinator.swift @@ -57,7 +57,9 @@ public final class MobilePushCoordinator { let workspaceId: String? let surfaceId: String? let macDeviceId: String? + let retargetsToLiveSurfaceOwner: Bool let createdAt: Date + let lastNavigatedWorkspaceId: MobileWorkspacePreview.ID? } @ObservationIgnored private var pendingDeeplink: PendingDeeplink? @@ -216,17 +218,36 @@ public final class MobilePushCoordinator { /// immediately in those states is what stranded users on the workspaces /// home screen. public func handleTap(workspaceId: String?, surfaceId: String?) { - handleTap(workspaceId: workspaceId, surfaceId: surfaceId, macDeviceId: nil) + handleTap( + workspaceId: workspaceId, + surfaceId: surfaceId, + macDeviceId: nil, + retargetsToLiveSurfaceOwner: true + ) } /// Deep-link to the workspace/terminal a tapped notification refers to, /// using the sending Mac id to disambiguate duplicate Mac-local ids. - public func handleTap(workspaceId: String?, surfaceId: String?, macDeviceId: String?) { + /// - Parameters: + /// - workspaceId: The Mac-local workspace claim carried by the push. + /// - surfaceId: The exact terminal claim carried by the push. + /// - macDeviceId: The Mac that owns the claimed ids. + /// - retargetsToLiveSurfaceOwner: Whether a moved terminal may resolve in + /// a workspace other than the explicit claim. Defaults to `true` for + /// pushes from older Mac clients that predate confinement provenance. + public func handleTap( + workspaceId: String?, + surfaceId: String?, + macDeviceId: String?, + retargetsToLiveSurfaceOwner: Bool = true + ) { pendingDeeplink = PendingDeeplink( workspaceId: workspaceId, surfaceId: surfaceId, macDeviceId: macDeviceId, - createdAt: now() + retargetsToLiveSurfaceOwner: retargetsToLiveSurfaceOwner, + createdAt: now(), + lastNavigatedWorkspaceId: nil ) applyPendingDeeplinkIfReady() } @@ -242,12 +263,16 @@ public final class MobilePushCoordinator { return } guard let store else { return } + guard pending.retargetsToLiveSurfaceOwner || pending.workspaceId != nil else { + pendingDeeplink = nil + return + } // Resolve the workspace to navigate to: the explicit target, or for a // surface-only tap the workspace that owns the terminal. Unresolvable // means "not loaded yet": stay parked for the next topology change so // the tap is never spent on a selection that cannot navigate. - let workspaceTarget: MobileWorkspacePreview.ID + var workspaceTarget: MobileWorkspacePreview.ID if let workspaceId = pending.workspaceId { guard let resolved = store.workspaceID( matchingRemoteWorkspaceID: workspaceId, @@ -264,24 +289,55 @@ public final class MobilePushCoordinator { pendingDeeplink = nil return } + if pending.retargetsToLiveSurfaceOwner, + let surfaceId = pending.surfaceId, + let liveOwner = store.workspaceID( + containingSurfaceID: surfaceId, + macDeviceID: pending.macDeviceId + ) { + workspaceTarget = liveOwner + } if let surfaceId = pending.surfaceId, !store.workspace(workspaceTarget, containsSurfaceID: surfaceId) { // The workspace is here but its terminal snapshot is not (still - // loading, or the terminal was closed). Land the user in the right - // workspace now and keep only the surface part parked so it can - // resolve if the terminal arrives, bounded by the same expiry. - store.navigateToWorkspaceForDeeplink(workspaceTarget) + // loading, closed, or moved). Land the user in the right workspace. + if pending.lastNavigatedWorkspaceId != workspaceTarget { + store.navigateToWorkspaceForDeeplink(workspaceTarget) + } + if !pending.retargetsToLiveSurfaceOwner, + let liveOwner = store.workspaceID( + containingSurfaceID: surfaceId, + macDeviceID: pending.macDeviceId + ), + liveOwner != workspaceTarget { + // The loaded topology proves the terminal moved elsewhere. A + // confined tap cannot follow it, and retaining the request + // would replay navigation to the authorized workspace on every + // topology update. + pendingDeeplink = nil + analytics.capture("ios_push_deeplink_resolved", [ + "resolved_workspace": .bool(true), + "resolved_surface": .bool(false), + ]) + return + } + // No live owner is loaded yet. Keep the surface parked so a pending + // snapshot can still arrive, bounded by the original expiry. pendingDeeplink = PendingDeeplink( - workspaceId: nil, + workspaceId: pending.retargetsToLiveSurfaceOwner ? nil : pending.workspaceId, surfaceId: surfaceId, macDeviceId: pending.macDeviceId, - createdAt: pending.createdAt + retargetsToLiveSurfaceOwner: pending.retargetsToLiveSurfaceOwner, + createdAt: pending.createdAt, + lastNavigatedWorkspaceId: workspaceTarget ) return } - store.navigateToWorkspaceForDeeplink(workspaceTarget) + if pending.lastNavigatedWorkspaceId != workspaceTarget { + store.navigateToWorkspaceForDeeplink(workspaceTarget) + } if let surfaceId = pending.surfaceId { store.selectTerminal(MobileTerminalPreview.ID(rawValue: surfaceId)) } diff --git a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationDeliveryCoordinator.swift b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationDeliveryCoordinator.swift index 0a4b6072e6d3..73af93359fad 100644 --- a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationDeliveryCoordinator.swift +++ b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationDeliveryCoordinator.swift @@ -265,6 +265,9 @@ public final class NotificationDeliveryCoordinator { return UUID(uuidString: surfaceIdString) }() let notificationId = notificationId(response) + let retargetsToLiveSurfaceOwner = response.userInfo[ + terminalIdentifiers.retargetsToLiveSurfaceOwnerUserInfoKey + ] as? Bool ?? true if let clickAction = NotificationNavClickAction(userInfo: response.userInfo) { let didPerform = terminalNavigation.performClickAction(clickAction) if didPerform, let notificationId { @@ -276,7 +279,8 @@ public final class NotificationDeliveryCoordinator { _ = terminalNavigation.openNotification( id: notificationId, fallbackTabId: tabId, - fallbackSurfaceId: surfaceId + fallbackSurfaceId: surfaceId, + fallbackRetargetsToLiveSurfaceOwner: retargetsToLiveSurfaceOwner ) } else { _ = terminalNavigation.open(tabId: tabId, surfaceId: surfaceId, notificationId: nil) diff --git a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationDeliveryTerminalNavigating.swift b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationDeliveryTerminalNavigating.swift index 43ce5897cf5b..3ac88035f6f6 100644 --- a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationDeliveryTerminalNavigating.swift +++ b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationDeliveryTerminalNavigating.swift @@ -10,9 +10,16 @@ public protocol NotificationDeliveryTerminalNavigating: AnyObject { func open(tabId: UUID, surfaceId: UUID?, notificationId: UUID?) -> Bool /// Opens a stored terminal notification, preserving any app-side context - /// that was not included in the delivered OS notification payload. + /// that was not included in the delivered OS notification payload. The + /// fallback provenance controls whether a missing stored notification may + /// follow its surface into another workspace. @discardableResult - func openNotification(id: UUID, fallbackTabId: UUID, fallbackSurfaceId: UUID?) -> Bool + func openNotification( + id: UUID, + fallbackTabId: UUID, + fallbackSurfaceId: UUID?, + fallbackRetargetsToLiveSurfaceOwner: Bool + ) -> Bool /// Performs a terminal notification click action. @discardableResult diff --git a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationNavSnapshot.swift b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationNavSnapshot.swift index 9e75958570dc..cc5e0d1f7391 100644 --- a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationNavSnapshot.swift +++ b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationNavSnapshot.swift @@ -17,6 +17,10 @@ public struct NotificationNavSnapshot: Sendable, Equatable, Identifiable { public let surfaceId: UUID? /// The owning terminal panel id, when known by the app target. public let panelId: UUID? + /// Whether navigation may follow the surface to its current owning workspace. + /// Source-confined relay notifications set this to `false` so opening them + /// cannot cross the workspace boundary authorized at delivery time. + public let retargetsToLiveSurfaceOwner: Bool /// Whether the notification has already been read. public let isRead: Bool /// The notification's click action, if any. When present the notification @@ -29,11 +33,25 @@ public struct NotificationNavSnapshot: Sendable, Equatable, Identifiable { public let scrollTotalRows: Int? /// Creates a navigation snapshot of a notification. + /// + /// - Parameters: + /// - id: Stable notification identity. + /// - tabId: Workspace id recorded for the notification. + /// - surfaceId: Surface id recorded for the notification, when any. + /// - panelId: App-target terminal panel id, when known. + /// - retargetsToLiveSurfaceOwner: Whether navigation may follow the surface + /// into its current owning workspace. Defaults to `true` for trusted + /// local notifications and backward compatibility. + /// - isRead: Whether the notification has already been read. + /// - clickAction: Side effect to perform instead of terminal navigation. + /// - scrollRow: Captured bottom-relative terminal scrollback row. + /// - scrollTotalRows: Total scrollback rows at capture time. public init( id: UUID, tabId: UUID, surfaceId: UUID?, panelId: UUID? = nil, + retargetsToLiveSurfaceOwner: Bool = true, isRead: Bool, clickAction: NotificationNavClickAction?, scrollRow: Int? = nil, @@ -43,6 +61,7 @@ public struct NotificationNavSnapshot: Sendable, Equatable, Identifiable { self.tabId = tabId self.surfaceId = surfaceId self.panelId = panelId + self.retargetsToLiveSurfaceOwner = retargetsToLiveSurfaceOwner self.isRead = isRead self.clickAction = clickAction self.scrollRow = scrollRow diff --git a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationNavigationCoordinator.swift b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationNavigationCoordinator.swift index 1d881a17dfdf..a2b76fec7f18 100644 --- a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationNavigationCoordinator.swift +++ b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationNavigationCoordinator.swift @@ -208,6 +208,7 @@ public final class NotificationNavigationCoordinator: NotificationDeliveryTermin tabId: notification.tabId, surfaceId: notification.surfaceId, panelId: notification.panelId, + retargetsToLiveSurfaceOwner: notification.retargetsToLiveSurfaceOwner, notificationId: notification.id, scrollRow: notification.scrollRow, scrollTotalRows: notification.scrollTotalRows @@ -217,12 +218,32 @@ public final class NotificationNavigationCoordinator: NotificationDeliveryTermin /// Opens a notification response from the OS notification center by first /// resolving the stored notification snapshot. This preserves panel and /// scroll context that is app-local and not serialized into `userInfo`. + /// + /// - Parameters: + /// - id: Stable notification id used to find the stored snapshot. + /// - fallbackTabId: Workspace id from the delivered OS notification. + /// - fallbackSurfaceId: Surface id from the delivered OS notification. + /// - fallbackRetargetsToLiveSurfaceOwner: Whether a missing stored + /// notification may follow its surface into another workspace. @discardableResult - public func openNotification(id: UUID, fallbackTabId: UUID, fallbackSurfaceId: UUID?) -> Bool { + public func openNotification( + id: UUID, + fallbackTabId: UUID, + fallbackSurfaceId: UUID?, + fallbackRetargetsToLiveSurfaceOwner: Bool = true + ) -> Bool { if let notification = store.orderedNotifications.first(where: { $0.id == id }) { return openNotification(notification) } - return open(tabId: fallbackTabId, surfaceId: fallbackSurfaceId, notificationId: id) + return open( + tabId: fallbackTabId, + surfaceId: fallbackSurfaceId, + panelId: nil, + retargetsToLiveSurfaceOwner: fallbackRetargetsToLiveSurfaceOwner, + notificationId: id, + scrollRow: nil, + scrollTotalRows: nil + ) } private func openNotificationViaClickRouting(_ notification: NotificationNavSnapshot) -> Bool { @@ -258,6 +279,8 @@ public final class NotificationNavigationCoordinator: NotificationDeliveryTermin /// - surfaceId: Surface id to focus when the notification is surface-scoped. /// - panelId: App-target terminal panel id used only to restore scroll /// context when it differs from, or is more precise than, `surfaceId`. + /// - retargetsToLiveSurfaceOwner: Whether the app-side route may follow a + /// moved surface into its current owning workspace. /// - notificationId: Notification id to mark read after focus succeeds. /// - scrollRow: Bottom-relative terminal scrollback row captured when the /// notification was recorded. @@ -269,6 +292,7 @@ public final class NotificationNavigationCoordinator: NotificationDeliveryTermin tabId: UUID, surfaceId: UUID?, panelId: UUID?, + retargetsToLiveSurfaceOwner: Bool = true, notificationId: UUID?, scrollRow: Int?, scrollTotalRows: Int? @@ -277,6 +301,7 @@ public final class NotificationNavigationCoordinator: NotificationDeliveryTermin tabId: tabId, surfaceId: surfaceId, panelId: panelId, + retargetsToLiveSurfaceOwner: retargetsToLiveSurfaceOwner, notificationId: notificationId, scrollRow: scrollRow, scrollTotalRows: scrollTotalRows diff --git a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationOpenRouting.swift b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationOpenRouting.swift index e829c1605dd5..0d3587202003 100644 --- a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationOpenRouting.swift +++ b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationOpenRouting.swift @@ -18,11 +18,13 @@ public protocol NotificationOpenRouting: AnyObject { /// falling back to the active window when none owns it. Returns whether /// focus succeeded. Mirrors the full `openNotification(tabId:surfaceId:notificationId:)` /// routing, including its `#if DEBUG` UI-test recorders, which the coordinator - /// must not duplicate. + /// must not duplicate. `retargetsToLiveSurfaceOwner` controls whether the + /// app-side route may follow a moved surface across workspace boundaries. func openRouted( tabId: UUID, surfaceId: UUID?, panelId: UUID?, + retargetsToLiveSurfaceOwner: Bool, notificationId: UUID?, scrollRow: Int?, scrollTotalRows: Int? diff --git a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/TerminalNotificationDeliveryIdentifiers.swift b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/TerminalNotificationDeliveryIdentifiers.swift index 6d21b7f395a5..afa8d8f8588e 100644 --- a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/TerminalNotificationDeliveryIdentifiers.swift +++ b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/TerminalNotificationDeliveryIdentifiers.swift @@ -8,10 +8,23 @@ public struct TerminalNotificationDeliveryIdentifiers: Sendable, Equatable { /// The explicit "show" action identifier used by terminal notifications. public let showActionIdentifier: String + /// The `userInfo` key carrying whether a notification may follow its live surface owner. + public let retargetsToLiveSurfaceOwnerUserInfoKey: String + /// Creates terminal notification identifiers for category installation and /// response routing. - public init(categoryIdentifier: String, showActionIdentifier: String) { + /// + /// - Parameters: + /// - categoryIdentifier: Category identifier for terminal notifications. + /// - showActionIdentifier: Explicit show-action identifier. + /// - retargetsToLiveSurfaceOwnerUserInfoKey: `userInfo` key for routing provenance. + public init( + categoryIdentifier: String, + showActionIdentifier: String, + retargetsToLiveSurfaceOwnerUserInfoKey: String + ) { self.categoryIdentifier = categoryIdentifier self.showActionIdentifier = showActionIdentifier + self.retargetsToLiveSurfaceOwnerUserInfoKey = retargetsToLiveSurfaceOwnerUserInfoKey } } diff --git a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDeliveryCoordinatorTests.swift b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDeliveryCoordinatorTests.swift index f6b34e358af0..18eedda7b56f 100644 --- a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDeliveryCoordinatorTests.swift +++ b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDeliveryCoordinatorTests.swift @@ -28,7 +28,12 @@ private final class FakeTerminalNavigation: NotificationDeliveryTerminalNavigati var openSucceeds = true var performSucceeds = true private(set) var opens: [OpenCall] = [] - private(set) var storedOpens: [(id: UUID, fallbackTabId: UUID, fallbackSurfaceId: UUID?)] = [] + private(set) var storedOpens: [( + id: UUID, + fallbackTabId: UUID, + fallbackSurfaceId: UUID?, + fallbackRetargetsToLiveSurfaceOwner: Bool + )] = [] private(set) var performedClickActions: [NotificationNavClickAction] = [] private(set) var markedReadIds: [UUID] = [] @@ -37,8 +42,13 @@ private final class FakeTerminalNavigation: NotificationDeliveryTerminalNavigati return openSucceeds } - func openNotification(id: UUID, fallbackTabId: UUID, fallbackSurfaceId: UUID?) -> Bool { - storedOpens.append((id: id, fallbackTabId: fallbackTabId, fallbackSurfaceId: fallbackSurfaceId)) + func openNotification( + id: UUID, + fallbackTabId: UUID, + fallbackSurfaceId: UUID?, + fallbackRetargetsToLiveSurfaceOwner: Bool + ) -> Bool { + storedOpens.append((id, fallbackTabId, fallbackSurfaceId, fallbackRetargetsToLiveSurfaceOwner)) return openSucceeds } @@ -250,6 +260,7 @@ struct NotificationDeliveryCoordinatorTests { "tabId": tabId.uuidString, "surfaceId": surfaceId.uuidString, "notificationId": notificationId.uuidString, + "retargetsToLiveSurfaceOwner": false, ] )) @@ -257,8 +268,21 @@ struct NotificationDeliveryCoordinatorTests { #expect(terminal.storedOpens.first?.id == notificationId) #expect(terminal.storedOpens.first?.fallbackTabId == tabId) #expect(terminal.storedOpens.first?.fallbackSurfaceId == surfaceId) + #expect(terminal.storedOpens.first?.fallbackRetargetsToLiveSurfaceOwner == false) #expect(terminal.opens.isEmpty) #expect(terminal.markedReadIds.isEmpty) + + coordinator.handle(NotificationDeliveryResponse( + categoryIdentifier: "terminal.category", + actionIdentifier: "terminal.show", + requestIdentifier: UUID().uuidString, + userInfo: [ + "tabId": tabId.uuidString, + "surfaceId": surfaceId.uuidString, + ] + )) + + #expect(terminal.storedOpens.last?.fallbackRetargetsToLiveSurfaceOwner == true) } @Test("terminal default response without notification id opens raw tab and surface") @@ -331,7 +355,8 @@ struct NotificationDeliveryCoordinatorTests { applicationActivation: applicationActivation, terminalIdentifiers: TerminalNotificationDeliveryIdentifiers( categoryIdentifier: "terminal.category", - showActionIdentifier: "terminal.show" + showActionIdentifier: "terminal.show", + retargetsToLiveSurfaceOwnerUserInfoKey: "retargetsToLiveSurfaceOwner" ), actionTitles: NotificationDeliveryActionTitles( show: "Show", diff --git a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationNavigationCoordinatorTests.swift b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationNavigationCoordinatorTests.swift index 03ffd5994ca8..81f701f6b978 100644 --- a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationNavigationCoordinatorTests.swift +++ b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationNavigationCoordinatorTests.swift @@ -66,15 +66,18 @@ private final class FakeOpenRouting: NotificationOpenRouting { var routedSucceeds = true var titles: [UUID: String] = [:] private(set) var log: [String] = [] + private(set) var routedRetargetingValues: [Bool] = [] func openRouted( tabId: UUID, surfaceId: UUID?, panelId: UUID?, + retargetsToLiveSurfaceOwner: Bool, notificationId: UUID?, scrollRow: Int?, scrollTotalRows: Int? ) -> Bool { + routedRetargetingValues.append(retargetsToLiveSurfaceOwner) log.append("routed(tab=\(short(tabId)),surf=\(short(surfaceId))\(panel(panelId)),notif=\(short(notificationId)),row=\(row(scrollRow)),total=\(row(scrollTotalRows)))") return routedSucceeds } @@ -146,6 +149,7 @@ private func snapshot( tabId: UUID, surfaceId: UUID? = nil, panelId: UUID? = nil, + retargetsToLiveSurfaceOwner: Bool = true, isRead: Bool = false, clickAction: NotificationNavClickAction? = nil, scrollRow: Int? = nil, @@ -157,6 +161,7 @@ private func snapshot( tabId: tabId, surfaceId: surfaceId, panelId: panelId, + retargetsToLiveSurfaceOwner: retargetsToLiveSurfaceOwner, isRead: isRead, clickAction: clickAction, scrollRow: scrollRow, @@ -386,6 +391,20 @@ struct NotificationNavigationCoordinatorTests { #expect(openRouting.log == ["routed(tab=\(short(notif.tabId)),surf=\(short(notif.surfaceId)),panel=\(short(panelId)),notif=\(short(notif.id)),row=42,total=100)"]) } + @Test("source-confined notification navigation preserves its workspace boundary") + func sourceConfinedNotificationDoesNotEnableLiveRetargeting() { + let openRouting = FakeOpenRouting() + let notification = snapshot( + tabId: UUID(), + surfaceId: UUID(), + retargetsToLiveSurfaceOwner: false + ) + let coordinator = makeCoordinator(openRouting: openRouting) + + #expect(coordinator.openNotification(notification)) + #expect(openRouting.routedRetargetingValues == [false]) + } + @Test("openNotification by id preserves stored panel and scroll context") func openNotificationByIdPreservesStoredContext() { let store = FakeStore() @@ -419,11 +438,13 @@ struct NotificationNavigationCoordinatorTests { let opened = coordinator.openNotification( id: notificationId, fallbackTabId: fallbackTabId, - fallbackSurfaceId: fallbackSurfaceId + fallbackSurfaceId: fallbackSurfaceId, + fallbackRetargetsToLiveSurfaceOwner: false ) #expect(opened) #expect(openRouting.log == ["routed(tab=\(short(fallbackTabId)),surf=\(short(fallbackSurfaceId)),notif=\(short(notificationId)),row=nil,total=nil)"]) + #expect(openRouting.routedRetargetingValues == [false]) } // MARK: - Focus signal (the #if DEBUG recorder hook) diff --git a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift index ba4cb7fb4488..cc0dd432084b 100644 --- a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift +++ b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift @@ -45,6 +45,11 @@ public final class SurfaceRegistryModel { /// by panel id (legacy `Workspace.surfaceTTYNames`). public var surfaceTTYNames: [UUID: String] = [:] + /// The indexed character-device identifier for each reported surface TTY. + /// The workspace updates this beside ``surfaceTTYNames`` so live agent + /// routing never performs per-surface filesystem work on the main actor. + public var surfaceTTYDevices: [UUID: Int64] = [:] + /// The shell-activity classification reported for each terminal panel, /// keyed by panel id (legacy `Workspace.panelShellActivityStates`). public var panelShellActivityStates: [UUID: PanelShellActivityState] = [:] diff --git a/Packages/macOS/CmuxWorkspaces/Tests/CmuxWorkspacesTests/Core/SurfaceRegistryModelTests.swift b/Packages/macOS/CmuxWorkspaces/Tests/CmuxWorkspacesTests/Core/SurfaceRegistryModelTests.swift index 7e122e426d98..2694382c1b83 100644 --- a/Packages/macOS/CmuxWorkspaces/Tests/CmuxWorkspacesTests/Core/SurfaceRegistryModelTests.swift +++ b/Packages/macOS/CmuxWorkspaces/Tests/CmuxWorkspacesTests/Core/SurfaceRegistryModelTests.swift @@ -17,6 +17,7 @@ struct SurfaceRegistryModelTests { #expect(model.pendingNonFocusSplitFocusReassert == nil) #expect(model.nonFocusSplitFocusReassertGeneration == 0) #expect(model.surfaceTTYNames.isEmpty) + #expect(model.surfaceTTYDevices.isEmpty) #expect(model.panelShellActivityStates.isEmpty) } @@ -56,13 +57,16 @@ struct SurfaceRegistryModelTests { let kept = UUID() let dropped = UUID() model.surfaceTTYNames = [kept: "/dev/ttys001", dropped: "/dev/ttys002"] + model.surfaceTTYDevices = [kept: 1, dropped: 2] model.panelShellActivityStates = [kept: .commandRunning, dropped: .promptIdle] let valid: Set = [kept] model.surfaceTTYNames = model.surfaceTTYNames.filter { valid.contains($0.key) } + model.surfaceTTYDevices = model.surfaceTTYDevices.filter { valid.contains($0.key) } model.panelShellActivityStates = model.panelShellActivityStates.filter { valid.contains($0.key) } #expect(model.surfaceTTYNames == [kept: "/dev/ttys001"]) + #expect(model.surfaceTTYDevices == [kept: 1]) #expect(model.panelShellActivityStates == [kept: .commandRunning]) } } diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index a4408d758e63..70523c3e3d75 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -1633,6 +1633,57 @@ } } }, + "agent.deliveryTarget.error.invalidPid": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "PID must be a positive integer" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "PID は正の整数でなければなりません。" + } + } + } + }, + "agent.deliveryTarget.error.notFound": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No live delivery target" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "有効な配信先が見つかりません。" + } + } + } + }, + "agent.deliveryTarget.error.unavailable": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Delivery target resolution is unavailable; retry after cmux finishes starting." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "配信先の解決を利用できません。cmux の起動が完了してから再試行してください。" + } + } + } + }, "agent.generic.notification.body.approvalNeeded": { "extractionState": "manual", "localizations": { diff --git a/Sources/AgentDeliveryTargetResolution.swift b/Sources/AgentDeliveryTargetResolution.swift new file mode 100644 index 000000000000..49f05b9d1d0e --- /dev/null +++ b/Sources/AgentDeliveryTargetResolution.swift @@ -0,0 +1,267 @@ +import AppKit +import Darwin +import Foundation + +/// Live delivery-target resolution for agent hook events. +/// +/// Invariant (https://github.com/manaflow-ai/cmux/issues/7939): an agent that +/// finishes in pane P of workspace W gets its notification, unread ring, and +/// status on exactly P in W. Attribution therefore resolves from LIVE identity +/// at delivery time — the exact live process's controlling terminal and +/// start-time-keyed environment, plus the surface's current workspace — never +/// from a stale tty registry row or a persisted session record alone. +/// +/// Two lookups implement this: +/// - pid → surface: the agent process's controlling tty device +/// (`proc_bsdinfo.e_tdev`) matched against every live surface's reported +/// tty. A pane's pty device is fixed for the pane's lifetime and the +/// process's controlling terminal is a live kernel fact, so a unique match +/// is authoritative regardless of where the pane has been moved. +/// - surface → workspace: `AppDelegate.workspaceContainingPanel`, which finds +/// the workspace that CURRENTLY owns the panel (issue #5781 pane moves). +/// +/// The CLI reaches this through the `agent.resolve_delivery_target` control +/// method; in-app notification delivery reaches it through +/// `agentNotificationDeliveryTarget` so stale-addressed notifications are +/// retargeted rather than dropped or misfiled. +nonisolated struct AgentDeliveryTargetCandidate: Equatable { + let workspaceId: UUID + let surfaceId: UUID +} + +/// Combines the two live pid signals. The start-time-keyed process environment +/// covers nested PTYs whose controlling TTY differs from the cmux pane. When +/// both signals resolve, disagreement still fails closed. +nonisolated func agentDeliveryTargetCombining( + ttyTarget: AgentDeliveryTargetCandidate?, + envTarget: AgentDeliveryTargetCandidate? +) -> AgentDeliveryTargetCandidate? { + guard let ttyTarget else { return envTarget } + if let envTarget, envTarget.surfaceId != ttyTarget.surfaceId { return nil } + return ttyTarget +} + +/// Pure core of the pid → surface lookup: the unique surface whose pty device +/// matches the process's controlling terminal. Multiple matches (tty device +/// reuse across mirrors) or none refuse to guess. +nonisolated func agentDeliveryTargetMatchingTTYDevice( + _ ttyDevice: Int64, + surfaceTTYDevices: [(workspaceId: UUID, surfaceId: UUID, ttyDevice: Int64)] +) -> AgentDeliveryTargetCandidate? { + let matches = surfaceTTYDevices.filter { $0.ttyDevice == ttyDevice } + guard let first = matches.first, + matches.allSatisfy({ $0.workspaceId == first.workspaceId && $0.surfaceId == first.surfaceId }) else { + return nil + } + return AgentDeliveryTargetCandidate(workspaceId: first.workspaceId, surfaceId: first.surfaceId) +} + +/// Live identity of a process: its controlling-terminal device +/// (`proc_bsdinfo.e_tdev`) and its start-time-keyed scope cache key. nil when +/// the process is gone. +nonisolated func agentLiveProcessIdentity(pid: pid_t) -> (ttyDevice: Int64?, scopeCacheKey: CmuxTopProcessScopeCacheKey)? { + guard pid > 0 else { return nil } + var info = proc_bsdinfo() + let expectedSize = MemoryLayout.stride + let size = proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, Int32(expectedSize)) + guard size == expectedSize else { return nil } + let device = Int64(info.e_tdev) + return (device > 0 ? device : nil, CmuxTopProcessSnapshot.scopeCacheKey(from: info)) +} + +@MainActor +extension Workspace { + /// Reported TTY names and their device-id index share one mutation path so + /// live agent resolution never stats every surface on the main actor. + var surfaceTTYNames: [UUID: String] { + get { surfaceRegistry.surfaceTTYNames } + set { + let previous = surfaceRegistry.surfaceTTYNames + var devices = surfaceRegistry.surfaceTTYDevices.filter { newValue[$0.key] != nil } + for (panelId, ttyName) in newValue where previous[panelId] != ttyName { + devices[panelId] = CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: ttyName) + } + surfaceRegistry.surfaceTTYNames = newValue + surfaceRegistry.surfaceTTYDevices = devices + } + } + + /// Cached TTY character-device ids, updated with ``surfaceTTYNames``. + var surfaceTTYDevices: [UUID: Int64] { surfaceRegistry.surfaceTTYDevices } + + /// Host-local TTY bindings eligible to identify a process running on this + /// Mac. Remote workspaces and remote terminal surfaces use a different + /// `/dev` namespace and must never participate in local device matching. + var localAgentDeliveryTTYDevices: [(surfaceId: UUID, ttyDevice: Int64)] { + guard !isRemoteWorkspace, !isRemoteTmuxMirror else { return [] } + return surfaceTTYDevices.compactMap { panelId, device in + guard panels[panelId] != nil, !isRemoteTerminalSurface(panelId) else { return nil } + return (panelId, device) + } + } +} + +@MainActor +extension AppDelegate { + /// The live pane that owns the given agent process right now: the + /// process's controlling tty matched against every surface's pty device + /// (unique-match only), with the exact live process's start-time-keyed + /// `CMUX_SURFACE_ID` environment re-homed through + /// `workspaceContainingPanel` as a nested-PTY fallback. Disagreement fails + /// closed. + func liveAgentDeliveryTarget(forAgentPID pid: pid_t) -> AgentDeliveryTargetCandidate? { + guard let identity = agentLiveProcessIdentity(pid: pid) else { return nil } + + var ttyTarget: AgentDeliveryTargetCandidate? + if let ttyDevice = identity.ttyDevice { + // TTY device ids are indexed when each surface reports or moves, + // so hook delivery only walks in-memory bindings on MainActor. It + // never stats every live surface while UI work is serialized. + var bindings: [(workspaceId: UUID, surfaceId: UUID, ttyDevice: Int64)] = [] + for manager in agentDeliveryTabManagers() { + for workspace in manager.tabs { + for binding in workspace.localAgentDeliveryTTYDevices { + bindings.append((workspace.id, binding.surfaceId, binding.ttyDevice)) + } + } + } + ttyTarget = agentDeliveryTargetMatchingTTYDevice(ttyDevice, surfaceTTYDevices: bindings) + } + + let processScope: CmuxTopProcessScope? + switch CmuxTopProcessSnapshot.cmuxScopeProbe( + for: Int(pid), + expectedCacheKey: identity.scopeCacheKey + ) { + case .resolved(let scope): processScope = scope + case .unavailable: processScope = nil + } + var envTarget: AgentDeliveryTargetCandidate? + if let envSurfaceId = processScope?.surfaceID, + let owner = workspaceContainingPanel(panelId: envSurfaceId) { + envTarget = AgentDeliveryTargetCandidate(workspaceId: owner.workspace.id, surfaceId: envSurfaceId) + } + + return agentDeliveryTargetCombining(ttyTarget: ttyTarget, envTarget: envTarget) + } + + /// Delivery-time target for a notification addressed to + /// (`claimedTabId`, `surfaceId`). A surface-scoped notification follows + /// the surface to whichever workspace currently owns it; a workspace-only + /// notification requires the claimed workspace to still exist. Returns nil + /// when the target is gone (surface closed, workspace closed) — the + /// notification is undeliverable, matching the previous drop semantics. + func agentNotificationDeliveryTarget( + claimedTabId: UUID, + surfaceId: UUID? + ) -> (tabId: UUID, surfaceId: UUID?)? { + guard let surfaceId else { + let manager = tabManagerFor(tabId: claimedTabId) ?? tabManager + guard manager?.tabs.contains(where: { $0.id == claimedTabId }) == true else { return nil } + return (claimedTabId, nil) + } + guard let owner = workspaceContainingPanel( + panelId: surfaceId, + preferredWorkspaceId: claimedTabId + ) else { + return nil + } + return (owner.workspace.id, surfaceId) + } + + private func agentDeliveryTabManagers() -> [TabManager] { + var managers: [TabManager] = [] + func append(_ manager: TabManager?) { + guard let manager, !managers.contains(where: { $0 === manager }) else { return } + managers.append(manager) + } + listMainWindowSummaries().forEach { append(tabManagerFor(windowId: $0.windowId)) } + append(tabManager) + return managers + } +} + +@MainActor +extension TerminalController { + /// `agent.resolve_delivery_target` — resolve the live pane/workspace for a + /// hook event. Probes: + /// - `{pid}`: the surface that owns the agent process right now + /// (`source: "pid"`); refuses to answer instead of guessing. + /// - `{surface_id, workspace_id?}`: the workspace that currently hosts a + /// known surface (`source: "surface"`), re-homing moved panes. + /// - `{workspace_id}`: existence check only (`source: "workspace"`). + func v2AgentResolveDeliveryTarget(params: [String: Any]) -> V2CallResult { + let claimedWorkspaceId = v2UUID(params, "workspace_id") + let claimedSurfaceId = v2UUID(params, "surface_id") + guard let appDelegate = AppDelegate.shared else { + return .err( + code: "unavailable", + message: String( + localized: "agent.deliveryTarget.error.unavailable", + defaultValue: "Delivery target resolution is unavailable; retry after cmux finishes starting." + ), + data: nil + ) + } + if params.keys.contains("pid") { + // A socket caller controls both the value and its JSON type. Do + // not coerce fractional/lossy NSNumber values, trap while + // narrowing, or let an invalid pid fall through to a different + // surface/workspace claim in the same request. + guard let pid = v2StrictInt(params, "pid"), + pid > 0, + let agentPid = pid_t(exactly: pid) else { + return .err( + code: "invalid_params", + message: String( + localized: "agent.deliveryTarget.error.invalidPid", + defaultValue: "PID must be a positive integer" + ), + data: nil + ) + } + if let target = appDelegate.liveAgentDeliveryTarget(forAgentPID: agentPid) { + return .ok([ + "workspace_id": target.workspaceId.uuidString, + "surface_id": target.surfaceId.uuidString, + "source": "pid", + ]) + } + return .err( + code: "not_found", + message: String( + localized: "agent.deliveryTarget.error.notFound", + defaultValue: "No live delivery target" + ), + data: nil + ) + } + if let claimedSurfaceId, + let owner = appDelegate.workspaceContainingPanel( + panelId: claimedSurfaceId, + preferredWorkspaceId: claimedWorkspaceId + ) { + return .ok([ + "workspace_id": owner.workspace.id.uuidString, + "surface_id": claimedSurfaceId.uuidString, + "source": "surface", + ]) + } + if let claimedWorkspaceId, + appDelegate.agentNotificationDeliveryTarget(claimedTabId: claimedWorkspaceId, surfaceId: nil) != nil { + return .ok([ + "workspace_id": claimedWorkspaceId.uuidString, + "surface_id": NSNull(), + "source": "workspace", + ]) + } + return .err( + code: "not_found", + message: String( + localized: "agent.deliveryTarget.error.notFound", + defaultValue: "No live delivery target" + ), + data: nil + ) + } +} diff --git a/Sources/AppDelegate+NotificationNavSeams.swift b/Sources/AppDelegate+NotificationNavSeams.swift index e07b98e08bbf..cef9c61570a8 100644 --- a/Sources/AppDelegate+NotificationNavSeams.swift +++ b/Sources/AppDelegate+NotificationNavSeams.swift @@ -99,6 +99,7 @@ final class NotificationNavSeamAdapter: tabId: UUID, surfaceId: UUID?, panelId: UUID?, + retargetsToLiveSurfaceOwner: Bool, notificationId: UUID?, scrollRow: Int?, scrollTotalRows: Int? @@ -107,6 +108,7 @@ final class NotificationNavSeamAdapter: tabId: tabId, surfaceId: surfaceId, panelId: panelId, + retargetsToLiveSurfaceOwner: retargetsToLiveSurfaceOwner, notificationId: notificationId, scrollRow: scrollRow, scrollTotalRows: scrollTotalRows @@ -256,6 +258,7 @@ extension AppDelegate { tabId: notification.tabId, surfaceId: notification.surfaceId, panelId: notification.panelId, + retargetsToLiveSurfaceOwner: notification.retargetsToLiveSurfaceOwner, isRead: notification.isRead, clickAction: notification.clickAction.map(Self.navClickAction), scrollRow: notification.scrollPosition?.row, @@ -305,6 +308,7 @@ extension AppDelegate { tabId: notification.tabId, surfaceId: notification.surfaceId, panelId: notification.panelId, + retargetsToLiveSurfaceOwner: notification.retargetsToLiveSurfaceOwner, isRead: notification.isRead, clickAction: notification.clickAction.map(navClickAction), scrollRow: notification.scrollPosition?.row, @@ -384,6 +388,7 @@ extension AppDelegate { tabId: UUID, surfaceId: UUID?, panelId: UUID?, + retargetsToLiveSurfaceOwner: Bool, notificationId: UUID?, scrollRow: Int?, scrollTotalRows: Int? @@ -392,6 +397,7 @@ extension AppDelegate { tabId: tabId, surfaceId: surfaceId, panelId: panelId, + retargetsToLiveSurfaceOwner: retargetsToLiveSurfaceOwner, notificationId: notificationId, scrollPosition: navScrollPosition(row: scrollRow, totalRows: scrollTotalRows) ) diff --git a/Sources/AppDelegate+NotificationOpen.swift b/Sources/AppDelegate+NotificationOpen.swift index 92968c09ccc3..e538b056a8eb 100644 --- a/Sources/AppDelegate+NotificationOpen.swift +++ b/Sources/AppDelegate+NotificationOpen.swift @@ -8,9 +8,28 @@ extension AppDelegate { tabId: UUID, surfaceId: UUID?, panelId: UUID? = nil, + retargetsToLiveSurfaceOwner: Bool = true, notificationId: UUID?, scrollPosition: TerminalNotificationScrollPosition? = nil ) -> Bool { + // Resolve move provenance at click time. Trusted local notifications + // follow the pane's live owner; source-confined notifications open only + // their authorized workspace and drop a surface that moved elsewhere. + var tabId = tabId + var surfaceId = surfaceId + var panelId = panelId + var scrollPosition = scrollPosition + if let liveSurfaceId = panelId ?? surfaceId, + let owner = workspaceContainingPanel(panelId: liveSurfaceId, preferredWorkspaceId: tabId), + owner.workspace.id != tabId { + if retargetsToLiveSurfaceOwner { + tabId = owner.workspace.id + } else { + surfaceId = nil + panelId = nil + scrollPosition = nil + } + } #if DEBUG let isJumpUnreadUITest = ProcessInfo.processInfo.environment["CMUX_UI_TEST_JUMP_UNREAD_SETUP"] == "1" if isJumpUnreadUITest { diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index e0c3bd5ef023..82a2fc179dce 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -704,7 +704,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent )?.id } ) - /// OS notification delivery/response coordination, extracted into /// `CmuxNotifications`. The app target injects the concrete /// `UNUserNotificationCenter`, terminal identifiers from @@ -719,7 +718,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent applicationActivation: notificationDeliverySeams, terminalIdentifiers: TerminalNotificationDeliveryIdentifiers( categoryIdentifier: TerminalNotificationStore.categoryIdentifier, - showActionIdentifier: TerminalNotificationStore.actionShowIdentifier + showActionIdentifier: TerminalNotificationStore.actionShowIdentifier, + retargetsToLiveSurfaceOwnerUserInfoKey: TerminalNotificationStore.retargetsToLiveSurfaceOwnerUserInfoKey ), actionTitles: notificationDeliveryActionTitles ) @@ -16363,6 +16363,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent tabId: notification.tabId, surfaceId: notification.surfaceId, panelId: notification.panelId, + retargetsToLiveSurfaceOwner: notification.retargetsToLiveSurfaceOwner, isRead: notification.isRead, clickAction: notification.clickAction.map(Self.navClickAction), scrollRow: notification.scrollPosition?.row, @@ -16370,7 +16371,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent ) ) } - /// Performs a notification click action. Forwards to the shared /// `NotificationClickPerformer` (which owns the tilde-expansion and /// file-vs-directory reveal logic); `AppDelegate` only supplies the diff --git a/Sources/Cloud/PhonePushClient.swift b/Sources/Cloud/PhonePushClient.swift index a997c66048e8..21567f37b56d 100644 --- a/Sources/Cloud/PhonePushClient.swift +++ b/Sources/Cloud/PhonePushClient.swift @@ -153,15 +153,8 @@ final class PhonePushClient { let hideContent = UserDefaults.standard.bool(forKey: PhonePushSettings.hideContentKey) let payload = PhonePushPayload( - kind: .notify, - title: notification.title, - subtitle: notification.subtitle, - body: notification.body, - workspaceId: notification.tabId.uuidString, - surfaceId: notification.surfaceId?.uuidString, + notification: notification, macDeviceId: MobileHostIdentity.deviceID(), - notificationId: notification.id.uuidString, - notificationIds: [], badgeCount: badgeCount, hideContent: hideContent ) @@ -202,6 +195,7 @@ final class PhonePushClient { body: "", workspaceId: nil, surfaceId: nil, + retargetsToLiveSurfaceOwner: false, macDeviceId: nil, notificationId: nil, notificationIds: chunk, @@ -243,6 +237,7 @@ final class PhonePushClient { bodyDict["body"] = payload.hideContent ? "New terminal activity" : payload.body if let workspaceId = payload.workspaceId { bodyDict["workspaceId"] = workspaceId } if let surfaceId = payload.surfaceId { bodyDict["surfaceId"] = surfaceId } + bodyDict["retargetsToLiveSurfaceOwner"] = payload.retargetsToLiveSurfaceOwner if let macDeviceId = payload.macDeviceId { bodyDict["macDeviceId"] = macDeviceId } // Opaque UUID, not content: safe to send even when hideContent is on. if let notificationId = payload.notificationId { bodyDict["notificationId"] = notificationId } diff --git a/Sources/Cloud/PhonePushPayload.swift b/Sources/Cloud/PhonePushPayload.swift index d10133a4095b..02e33327c850 100644 --- a/Sources/Cloud/PhonePushPayload.swift +++ b/Sources/Cloud/PhonePushPayload.swift @@ -7,6 +7,8 @@ struct PhonePushPayload: Sendable { let body: String let workspaceId: String? let surfaceId: String? + /// Whether iOS may resolve `surfaceId` outside the explicit workspace. + let retargetsToLiveSurfaceOwner: Bool /// Stable Mac device id for routing notification taps in multi-Mac aggregates. let macDeviceId: String? /// Stable notification id (the Mac store ``TerminalNotification/id``). @@ -20,3 +22,28 @@ struct PhonePushPayload: Sendable { let badgeCount: Int let hideContent: Bool } + +extension PhonePushPayload { + /// Builds the phone banner payload from the stored notification identity. + init( + notification: TerminalNotification, + macDeviceId: String, + badgeCount: Int, + hideContent: Bool + ) { + self.init( + kind: .notify, + title: notification.title, + subtitle: notification.subtitle, + body: notification.body, + workspaceId: notification.tabId.uuidString, + surfaceId: notification.surfaceId?.uuidString, + retargetsToLiveSurfaceOwner: notification.retargetsToLiveSurfaceOwner, + macDeviceId: macDeviceId, + notificationId: notification.id.uuidString, + notificationIds: [], + badgeCount: badgeCount, + hideContent: hideContent + ) + } +} diff --git a/Sources/SessionNotificationSnapshot.swift b/Sources/SessionNotificationSnapshot.swift index dfd3545de48a..ce57eb8a4f38 100644 --- a/Sources/SessionNotificationSnapshot.swift +++ b/Sources/SessionNotificationSnapshot.swift @@ -8,6 +8,7 @@ struct SessionNotificationSnapshot: Codable, Sendable { var createdAt: TimeInterval var isRead: Bool var paneFlash: Bool? + var retargetsToLiveSurfaceOwner: Bool? var scrollPosition: TerminalNotificationScrollPosition? var clickAction: TerminalNotificationClickAction? @@ -19,6 +20,7 @@ struct SessionNotificationSnapshot: Codable, Sendable { createdAt: TimeInterval, isRead: Bool, paneFlash: Bool? = nil, + retargetsToLiveSurfaceOwner: Bool? = nil, scrollPosition: TerminalNotificationScrollPosition? = nil, clickAction: TerminalNotificationClickAction? = nil ) { @@ -29,6 +31,7 @@ struct SessionNotificationSnapshot: Codable, Sendable { self.createdAt = createdAt self.isRead = isRead self.paneFlash = paneFlash + self.retargetsToLiveSurfaceOwner = retargetsToLiveSurfaceOwner self.scrollPosition = scrollPosition self.clickAction = clickAction } @@ -42,6 +45,7 @@ struct SessionNotificationSnapshot: Codable, Sendable { createdAt: notification.createdAt.timeIntervalSince1970, isRead: notification.isRead, paneFlash: notification.paneFlash, + retargetsToLiveSurfaceOwner: notification.retargetsToLiveSurfaceOwner, scrollPosition: notification.scrollPosition, clickAction: notification.clickAction ) @@ -53,6 +57,7 @@ struct SessionNotificationSnapshot: Codable, Sendable { tabId: tabId, surfaceId: surfaceId, panelId: panelId, + retargetsToLiveSurfaceOwner: retargetsToLiveSurfaceOwner ?? true, title: title, subtitle: subtitle, body: body, diff --git a/Sources/TerminalController+ControlNotificationContext.swift b/Sources/TerminalController+ControlNotificationContext.swift index 947b970fbd31..a89d0225295e 100644 --- a/Sources/TerminalController+ControlNotificationContext.swift +++ b/Sources/TerminalController+ControlNotificationContext.swift @@ -22,9 +22,20 @@ extension TerminalController: ControlNotificationContext { return .tabManagerUnavailable } guard let ws = resolveWorkspace(routing: routing, tabManager: tabManager) else { + if let explicitSurfaceID, + let rehomed = controlNotificationRehomedDelivery( + surfaceID: explicitSurfaceID, title: title, subtitle: subtitle, body: body + ) { + return .delivered(workspaceID: rehomed.workspaceID, surfaceID: explicitSurfaceID) + } return .workspaceNotFound } if let explicitSurfaceID, ws.panels[explicitSurfaceID] == nil { + if let rehomed = controlNotificationRehomedDelivery( + surfaceID: explicitSurfaceID, title: title, subtitle: subtitle, body: body + ) { + return .delivered(workspaceID: rehomed.workspaceID, surfaceID: explicitSurfaceID) + } return .surfaceNotFound(explicitSurfaceID) } let surfaceId = explicitSurfaceID ?? ws.focusedPanelId @@ -48,10 +59,31 @@ extension TerminalController: ControlNotificationContext { guard let tabManager = resolveTabManager(routing: routing) else { return .tabManagerUnavailable } + // Moved pane (issue #7939): a pane keeps its surface id across + // workspace moves, so resolve the surface's CURRENT owner before + // rejecting a claim the routing selectors no longer satisfy — whether + // the surface left the claimed workspace or that workspace was closed. + // `notification.create_for_surface` is NOT relay-reachable. The cloud + // tunnel rewrites scoped `notification.create` calls to the confined + // `create_for_target` path before they reach this trusted local path. guard let ws = resolveWorkspace(routing: routing, tabManager: tabManager) else { + if let rehomed = controlNotificationRehomedDelivery( + surfaceID: surfaceID, title: title, subtitle: subtitle, body: body + ) { + return .delivered( + workspaceID: rehomed.workspaceID, surfaceID: surfaceID, windowID: rehomed.windowID + ) + } return .workspaceNotFound(workspaceID: nil) } guard ws.panels[surfaceID] != nil else { + if let rehomed = controlNotificationRehomedDelivery( + surfaceID: surfaceID, title: title, subtitle: subtitle, body: body + ) { + return .delivered( + workspaceID: rehomed.workspaceID, surfaceID: surfaceID, windowID: rehomed.windowID + ) + } return .surfaceNotFound(surfaceID) } deliverNotificationSynchronously( @@ -68,6 +100,26 @@ extension TerminalController: ControlNotificationContext { ) } + /// Shared trusted-local path for a surface that moved after its caller + /// captured a workspace address. Relay callers are rewritten to the + /// membership-confined `create_for_target` entrypoint before dispatch. + private func controlNotificationRehomedDelivery( + surfaceID: UUID, + title: String, + subtitle: String, + body: String + ) -> (workspaceID: UUID, windowID: UUID?)? { + guard let owner = AppDelegate.shared?.workspaceContainingPanel(panelId: surfaceID) else { return nil } + deliverNotificationSynchronously( + tabId: owner.workspace.id, + surfaceId: surfaceID, + title: title, + subtitle: subtitle, + body: body + ) + return (owner.workspace.id, AppDelegate.shared?.windowId(for: owner.tabManager)) + } + func controlNotificationCreateForTarget( routing: ControlRoutingSelectors, workspaceID: UUID, @@ -79,6 +131,16 @@ extension TerminalController: ControlNotificationContext { guard let tabManager = resolveTabManager(routing: routing) else { return .tabManagerUnavailable } + // SECURITY: no live re-homing here. `notification.create_for_target` + // is reachable through the cloud relay (`RemoteDaemonProxyTunnel`), + // whose authorization only checks that the supplied workspace_id + // equals the relay's owner workspace — this membership guard is what + // actually confines a VM's deliveries to its authorized workspace. A + // global surface lookup would let a relay caller inject notifications + // into any workspace from a leaked pane UUID. Moved-pane re-homing + // for relayed notifications needs a trusted surface binding from the + // relay (follow-up); trusted local callers get it via + // `create_for_caller`/`create_for_surface`. guard let ws = tabManager.tabs.first(where: { $0.id == workspaceID }) else { return .workspaceNotFound(workspaceID: workspaceID) } @@ -90,7 +152,8 @@ extension TerminalController: ControlNotificationContext { surfaceId: surfaceID, title: title, subtitle: subtitle, - body: body + body: body, + retargetsToLiveSurfaceOwner: false ) return .delivered( workspaceID: ws.id, diff --git a/Sources/TerminalController+ControlSidebarContext.swift b/Sources/TerminalController+ControlSidebarContext.swift index b2f70eec2905..659a3f68da06 100644 --- a/Sources/TerminalController+ControlSidebarContext.swift +++ b/Sources/TerminalController+ControlSidebarContext.swift @@ -29,10 +29,7 @@ extension TerminalController: ControlSidebarContext { pid: Int32? ) { let appFormat = SidebarMetadataFormat(rawValue: format.rawValue) ?? .plain - controlSidebarScheduleMutation(target: target) { _, tab in - if let panelId = panelID, !tab.panels.keys.contains(panelId) { - return - } + controlSidebarSchedulePanelOwnedMutation(target: target, panelID: panelID) { _, tab in guard Self.shouldReplaceStatusEntry( current: tab.statusEntries[key], key: key, @@ -78,10 +75,7 @@ extension TerminalController: ControlSidebarContext { pid: Int32, panelID: UUID? ) { - controlSidebarScheduleMutation(target: target) { _, tab in - if let panelId = panelID, !tab.panels.keys.contains(panelId) { - return - } + controlSidebarSchedulePanelOwnedMutation(target: target, panelID: panelID) { _, tab in let didReplaceAgentRuntime = tab.recordAgentPID( key: key, pid: pid, @@ -165,10 +159,7 @@ extension TerminalController: ControlSidebarContext { // Unreachable: the coordinator only forwards a value this app produced. return } - controlSidebarScheduleMutation(target: target) { _, tab in - if let panelId = panelID, !tab.panels.keys.contains(panelId) { - return - } + controlSidebarSchedulePanelOwnedMutation(target: target, panelID: panelID) { _, tab in tab.setAgentLifecycle(key: key, panelId: panelID, lifecycle: lifecycle) } } @@ -229,10 +220,7 @@ extension TerminalController: ControlSidebarContext { panelID: UUID?, clearStatus: Bool ) { - controlSidebarScheduleMutation(target: target) { _, tab in - if let panelId = panelID, !tab.panels.keys.contains(panelId) { - return - } + controlSidebarSchedulePanelOwnedMutation(target: target, panelID: panelID) { _, tab in tab.clearAgentPID( key: key, panelId: panelID, diff --git a/Sources/TerminalController+ControlSidebarContextSupport.swift b/Sources/TerminalController+ControlSidebarContextSupport.swift index 975d59bc3405..de81d5ecb6a1 100644 --- a/Sources/TerminalController+ControlSidebarContextSupport.swift +++ b/Sources/TerminalController+ControlSidebarContextSupport.swift @@ -118,6 +118,27 @@ extension TerminalController { } } + /// Resolves a UUID-addressed panel's owner inside the deferred mutation so + /// agent runtime updates follow a pane that moved after the socket request. + nonisolated func controlSidebarSchedulePanelOwnedMutation( + target: ControlSidebarTabTarget, + panelID: UUID?, + mutation: @escaping @MainActor (TerminalController, Workspace) -> Void + ) { + TerminalMutationBus.shared.enqueueMainActorMutation { [weak self] in + guard let self else { return } + var tab = self.controlSidebarResolveMutationTab(target) + if let panelID, case .workspace = target, + tab?.panels.keys.contains(panelID) != true, + let owner = AppDelegate.shared?.workspaceContainingPanel(panelId: panelID) { + tab = owner.workspace + } + guard let tab else { return } + if let panelID, !tab.panels.keys.contains(panelID) { return } + mutation(self, tab) + } + } + /// The enqueue halves of the deleted file-private /// `schedulePanelMetadataMutation(args:options:missingPanelUsage:mutation:)` /// (the parse-level head moved into the coordinator's diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 5534f4d78566..a77cac5270cc 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -2236,6 +2236,7 @@ class TerminalController { // ControlCommandCoordinator (create_for_caller keeps its app-side resolver). case "notification.create_for_caller": return v2Result(id: id, self.v2NotificationCreateForCaller(params: params)) + case "agent.resolve_delivery_target": return v2Result(id: id, self.v2AgentResolveDeliveryTarget(params: params)) // App focus (app.focus_override.set/app.simulate_active) handled by ControlCommandCoordinator. @@ -2465,7 +2466,7 @@ class TerminalController { "pane.join", "pane.last", "notification.create", - "notification.create_for_caller", + "notification.create_for_caller", "agent.resolve_delivery_target", "notification.create_for_surface", "notification.create_for_target", "notification.list", @@ -12161,10 +12162,9 @@ class TerminalController { guard deliver else { return "OK" } if let fastPath { - guard let tab = self.tabForSidebarMutation(id: fastPath.workspaceId) else { - return "ERROR: Tab not found" - } - guard tab.panels[fastPath.panelId] != nil else { + // The surface's current workspace wins over the claimed one (the + // sync deliverer retargets); only a target gone everywhere errors. + guard AppDelegate.shared?.agentNotificationDeliveryTarget(claimedTabId: fastPath.workspaceId, surfaceId: fastPath.panelId) != nil else { return "ERROR: Panel not found" } self.deliverNotificationSynchronously( @@ -12187,7 +12187,7 @@ class TerminalController { return "ERROR: Tab not found" } guard let panelId = UUID(uuidString: panelArg), - tab.panels[panelId] != nil else { + AppDelegate.shared?.agentNotificationDeliveryTarget(claimedTabId: tab.id, surfaceId: panelId) != nil else { return "ERROR: Panel not found" } self.deliverNotificationSynchronously( @@ -12328,7 +12328,7 @@ class TerminalController { TerminalNotificationStore.shared.clearNotifications( forTabId: tab.id, surfaceId: panelId, - discardQueuedNotifications: false + discardQueuedNotifications: false, throughNotificationGeneration: clearBoundary ) } else { TerminalMutationBus.shared.discardPendingNotifications( @@ -12337,7 +12337,7 @@ class TerminalController { ) TerminalNotificationStore.shared.clearNotifications( forTabId: tab.id, - discardQueuedNotifications: false + discardQueuedNotifications: false, throughNotificationGeneration: clearBoundary ) } } diff --git a/Sources/TerminalNotification.swift b/Sources/TerminalNotification.swift index 7fd9f0c212d7..ed78e6fd249c 100644 --- a/Sources/TerminalNotification.swift +++ b/Sources/TerminalNotification.swift @@ -5,6 +5,7 @@ struct TerminalNotification: Identifiable, Hashable, Sendable { let tabId: UUID let surfaceId: UUID? let panelId: UUID? + let retargetsToLiveSurfaceOwner: Bool let title: String let subtitle: String let body: String @@ -19,6 +20,7 @@ struct TerminalNotification: Identifiable, Hashable, Sendable { tabId: UUID, surfaceId: UUID?, panelId: UUID? = nil, + retargetsToLiveSurfaceOwner: Bool = true, title: String, subtitle: String, body: String, @@ -32,6 +34,7 @@ struct TerminalNotification: Identifiable, Hashable, Sendable { self.tabId = tabId self.surfaceId = surfaceId self.panelId = panelId + self.retargetsToLiveSurfaceOwner = retargetsToLiveSurfaceOwner self.title = title self.subtitle = subtitle self.body = body @@ -49,4 +52,10 @@ struct TerminalNotification: Identifiable, Hashable, Sendable { } return surfaceId == targetSurfaceId || panelId == targetSurfaceId } + + /// Matches a clear without letting live-owner expansion cross a confined notification's workspace boundary. + func matchesClear(tabId targetTabId: UUID, liveTabId: UUID, surfaceId targetSurfaceId: UUID?) -> Bool { + let matchesWorkspace = tabId == targetTabId || (retargetsToLiveSurfaceOwner && tabId == liveTabId) + return matchesWorkspace && matches(tabId: tabId, surfaceId: targetSurfaceId) + } } diff --git a/Sources/TerminalNotificationCallerResolver.swift b/Sources/TerminalNotificationCallerResolver.swift index afbafcc70e33..399382178ba1 100644 --- a/Sources/TerminalNotificationCallerResolver.swift +++ b/Sources/TerminalNotificationCallerResolver.swift @@ -70,6 +70,14 @@ extension TerminalController { if let preferredSurfaceId, workspace.panels[preferredSurfaceId] != nil { return TerminalCallerNotificationTarget(workspace: workspace, surfaceId: preferredSurfaceId) } + // Moved pane (issue #7939): the explicit surface identity outranks + // the stale spawn-time workspace claim — follow the surface to the + // workspace that owns it NOW instead of falling back to the old + // workspace's focused pane. + if let preferredSurfaceId, + let surfaceTarget = targetForSurface(preferredSurfaceId, tabManagers: managers) { + return surfaceTarget + } if let ttyTarget, ttyTarget.workspace.id == workspace.id { return ttyTarget } return TerminalCallerNotificationTarget(workspace: workspace, surfaceId: workspace.focusedPanelId) } diff --git a/Sources/TerminalNotificationLiveRetargetDelivery.swift b/Sources/TerminalNotificationLiveRetargetDelivery.swift new file mode 100644 index 000000000000..c4a0ec11c163 --- /dev/null +++ b/Sources/TerminalNotificationLiveRetargetDelivery.swift @@ -0,0 +1,192 @@ +import Foundation + +/// Live-retargeting delivery and clear semantics for agent notifications +/// (https://github.com/manaflow-ai/cmux/issues/7939): a notification addressed +/// with a stale claimed workspace follows its surface to the workspace that +/// CURRENTLY owns it, and clears must use the same live identity so a +/// stale-keyed pending entry can never outlive a clear and resurrect. Split +/// from `TerminalNotificationQueue.swift` for the file-length budget. + +extension TerminalController { + func deliverNotificationSynchronously( + tabId: UUID, + surfaceId: UUID?, + title: String, + subtitle: String, + body: String, + retargetsToLiveSurfaceOwner: Bool = true + ) { + let target: (tabId: UUID, surfaceId: UUID?) + if retargetsToLiveSurfaceOwner { + // Trusted local delivery follows the surface's CURRENT workspace. + // A missing live target fails closed instead of filing under a + // stale claimed address. + guard let liveTarget = AppDelegate.shared?.agentNotificationDeliveryTarget( + claimedTabId: tabId, + surfaceId: surfaceId + ) else { return } + target = liveTarget + } else { + // `notification.create_for_target` is relay-reachable and already + // validated membership in its authorized workspace. Never global- + // rehome that source-confined claim from an untrusted surface UUID. + target = (tabId, surfaceId) + } + if retargetsToLiveSurfaceOwner, let liveSurfaceId = target.surfaceId { + // Supersede by canonical surface identity: stale-keyed local + // entries would retarget to this same pane at drain. + TerminalMutationBus.shared.discardPendingNotifications(forSurfaceId: liveSurfaceId) + } else { + // Source-confined relay delivery may supersede only its authorized + // enqueue key, not another workspace's entry for the same UUID. + TerminalMutationBus.shared.discardPendingNotifications( + forTabId: target.tabId, + surfaceId: target.surfaceId + ) + } +#if DEBUG + cmuxDebugLog( + "notification.sync.deliver workspace=\(target.tabId.uuidString.prefix(8)) surface=\(target.surfaceId?.uuidString.prefix(8) ?? "nil") claimedWorkspace=\(tabId.uuidString.prefix(8)) titleLen=\(title.count) subtitleLen=\(subtitle.count) bodyLen=\(body.count)" + ) +#endif + TerminalNotificationStore.shared.addNotification( + tabId: target.tabId, + surfaceId: target.surfaceId, + title: title, + subtitle: subtitle, + body: body, + retargetsToLiveSurfaceOwner: retargetsToLiveSurfaceOwner + ) + } +} + +extension TerminalNotificationStore { + /// Drain-time delivery of a queued notification. Resolves the LIVE target + /// at delivery time: a surface-scoped notification follows its surface to + /// the workspace that currently owns it (issues #7939/#5781) instead of + /// being dropped on a stale workspace claim; only a gone target (closed + /// surface/workspace) skips. + func deliverQueuedNotification( + claimedTabId: UUID, + surfaceId: UUID?, + title: String, + subtitle: String, + body: String, + notificationGeneration: UInt64 + ) { + guard let target = AppDelegate.shared?.agentNotificationDeliveryTarget( + claimedTabId: claimedTabId, + surfaceId: surfaceId + ) else { +#if DEBUG + cmuxDebugLog( + "notification.queue.deliver.skip workspace=\(claimedTabId.uuidString.prefix(8)) surface=\(surfaceId?.uuidString.prefix(8) ?? "nil") reason=targetMissing titleLen=\(title.count) subtitleLen=\(subtitle.count) bodyLen=\(body.count)" + ) +#endif + return + } +#if DEBUG + cmuxDebugLog( + "notification.queue.deliver workspace=\(target.tabId.uuidString.prefix(8)) surface=\(target.surfaceId?.uuidString.prefix(8) ?? "nil") claimedWorkspace=\(claimedTabId.uuidString.prefix(8)) titleLen=\(title.count) subtitleLen=\(subtitle.count) bodyLen=\(body.count)" + ) +#endif + addNotification( + tabId: target.tabId, + surfaceId: target.surfaceId, + title: title, + subtitle: subtitle, + body: body, + retargetsToLiveSurfaceOwner: true, + notificationGeneration: notificationGeneration + ) + } + + /// Re-resolves canonical surface identity at the final apply boundary, + /// after any asynchronous notification-policy hooks have finished. + func notificationPolicyRequestAtLiveOwner( + _ request: TerminalNotificationPolicyRequest + ) -> TerminalNotificationPolicyRequest? { + guard request.retargetsToLiveSurfaceOwner else { return request } + guard let target = AppDelegate.shared?.agentNotificationDeliveryTarget( + claimedTabId: request.tabId, + surfaceId: request.surfaceId + ) else { return nil } + return TerminalNotificationPolicyRequest( + tabId: target.tabId, + surfaceId: target.surfaceId, + panelId: request.panelId, + retargetsToLiveSurfaceOwner: true, + title: request.title, + subtitle: request.subtitle, + body: request.body, + cwd: request.cwd, + isAppFocused: request.isAppFocused, + isFocusedPanel: request.isFocusedPanel + ) + } +} + +@MainActor +extension TerminalMutationBus { + /// A workspace-wide clear for `tabId` must also drop pending entries + /// queued under a STALE claimed workspace whose surface's CURRENT owner is + /// `tabId` — drain-time delivery retargets them there (#7939), so a + /// claimed-key-only match would let the notification reappear right after + /// the clear. Two-phase: snapshot the pending addresses under the bus + /// lock, resolve each UNIQUE pending surface's live owner on the main + /// actor (mirroring `agentNotificationDeliveryTarget`'s + /// preferred-workspace resolution), then discard exactly the snapshotted + /// sequences. Repeated non-coalescing notifications for one pane share a + /// cached lookup, keeping the global workspace scan bounded by unique live + /// surfaces instead of total backlog length. Entries enqueued between + /// snapshot and discard are newer than the clear and are deliberately + /// preserved. + func pendingNotificationSequencesResolvingLiveOwner(forTabId tabId: UUID) -> Set { + pendingNotificationSequencesResolvingLiveOwner( + forTabId: tabId, + liveOwnerResolver: { claimedTabId, surfaceId in + AppDelegate.shared?.agentNotificationDeliveryTarget( + claimedTabId: claimedTabId, + surfaceId: surfaceId + )?.tabId + } + ) + } + + func pendingNotificationSequencesResolvingLiveOwner( + forTabId tabId: UUID, + liveOwnerResolver: (_ claimedTabId: UUID, _ surfaceId: UUID) -> UUID? + ) -> Set { + var sequences: Set = [] + var liveOwnerBySurfaceId: [UUID: UUID] = [:] + var unresolvedSurfaceIds: Set = [] + for entry in pendingNotificationAddressesSnapshot() { + guard let surfaceId = entry.surfaceId else { + if entry.tabId == tabId { sequences.insert(entry.sequence) } + continue + } + let liveOwner: UUID? + if let cached = liveOwnerBySurfaceId[surfaceId] { + liveOwner = cached + } else if unresolvedSurfaceIds.contains(surfaceId) { + liveOwner = nil + } else if let resolved = liveOwnerResolver(entry.tabId, surfaceId) { + liveOwnerBySurfaceId[surfaceId] = resolved + liveOwner = resolved + } else { + unresolvedSurfaceIds.insert(surfaceId) + liveOwner = nil + } + if liveOwner == tabId { + sequences.insert(entry.sequence) + } + } + return sequences + } + + func discardPendingNotificationsResolvingLiveOwner(forTabId tabId: UUID) { + discardPendingNotifications( + sequences: pendingNotificationSequencesResolvingLiveOwner(forTabId: tabId) + ) + } +} diff --git a/Sources/TerminalNotificationPolicy.swift b/Sources/TerminalNotificationPolicy.swift index 33516d4d15d1..d01373cb5074 100644 --- a/Sources/TerminalNotificationPolicy.swift +++ b/Sources/TerminalNotificationPolicy.swift @@ -184,22 +184,22 @@ struct TerminalNotificationPolicyEnvelope: Codable, Sendable, Equatable { var effects: TerminalNotificationPolicyEffects = TerminalNotificationPolicyEffects() var stop: Bool? } - struct TerminalNotificationPolicyRequest: Sendable { let tabId: UUID let surfaceId: UUID? let panelId: UUID? + let retargetsToLiveSurfaceOwner: Bool let title: String let subtitle: String let body: String let cwd: String? let isAppFocused: Bool let isFocusedPanel: Bool - init( tabId: UUID, surfaceId: UUID?, panelId: UUID? = nil, + retargetsToLiveSurfaceOwner: Bool = false, title: String, subtitle: String, body: String, @@ -210,6 +210,7 @@ struct TerminalNotificationPolicyRequest: Sendable { self.tabId = tabId self.surfaceId = surfaceId self.panelId = panelId + self.retargetsToLiveSurfaceOwner = retargetsToLiveSurfaceOwner self.title = title self.subtitle = subtitle self.body = body @@ -218,7 +219,6 @@ struct TerminalNotificationPolicyRequest: Sendable { self.isFocusedPanel = isFocusedPanel } } - struct TerminalNotificationPolicyFailure: Error, Sendable, Hashable { let hookId: String let sourcePath: String? @@ -442,8 +442,8 @@ private final class NotificationHookProcessRun: @unchecked Sendable { private var killSource: DispatchSourceTimer? private var didComplete = false private var didRequestTermination = false + private var didRequestCancellation = false private var pendingFailure: TerminalNotificationPolicyFailure? - init( hook: CmuxResolvedNotificationHook, envelope: TerminalNotificationPolicyEnvelope, @@ -455,17 +455,23 @@ private final class NotificationHookProcessRun: @unchecked Sendable { self.inputData = inputData self.maxOutputBytes = maxOutputBytes } - func run() async -> Result { - await withCheckedContinuation { continuation in - queue.async { [self] in - self.continuation = continuation - self.start() + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + queue.async { [self] in + self.continuation = continuation + self.start() + } } + } onCancel: { [self] in + queue.async { [self] in requestCancellation() } } } - private func start() { + guard !didRequestCancellation else { + complete(.failure(cancellationFailure())) + return + } do { try spawnHook() installReadSources() @@ -480,7 +486,6 @@ private final class NotificationHookProcessRun: @unchecked Sendable { ))) } } - private func spawnHook() throws { var stdinFDs = [Int32](repeating: -1, count: 2) var stdoutFDs = [Int32](repeating: -1, count: 2) @@ -493,11 +498,9 @@ private final class NotificationHookProcessRun: @unchecked Sendable { try throwIfPOSIXError(pipe(&stdinFDs), operation: "create stdin pipe") try throwIfPOSIXError(pipe(&stdoutFDs), operation: "create stdout pipe") try throwIfPOSIXError(pipe(&stderrFDs), operation: "create stderr pipe") - var fileActions: posix_spawn_file_actions_t? try throwIfPOSIXError(posix_spawn_file_actions_init(&fileActions), operation: "initialize spawn file actions") defer { posix_spawn_file_actions_destroy(&fileActions) } - try hook.cwd.withCString { cwd in try throwIfPOSIXError( posix_spawn_file_actions_addchdir_np(&fileActions, cwd), @@ -513,14 +516,12 @@ private final class NotificationHookProcessRun: @unchecked Sendable { operation: "close inherited hook pipe" ) } - var attributes: posix_spawnattr_t? try throwIfPOSIXError(posix_spawnattr_init(&attributes), operation: "initialize spawn attributes") defer { posix_spawnattr_destroy(&attributes) } let flags = Int16(POSIX_SPAWN_SETPGROUP) try throwIfPOSIXError(posix_spawnattr_setflags(&attributes, flags), operation: "set spawn flags") try throwIfPOSIXError(posix_spawnattr_setpgroup(&attributes, 0), operation: "set process group") - let arguments = ["/bin/sh", "-c", hook.command] let environment = environmentStrings() var spawnedPID: pid_t = 0 @@ -532,7 +533,6 @@ private final class NotificationHookProcessRun: @unchecked Sendable { } } try throwIfPOSIXError(spawnResult, operation: "spawn notification hook") - processId = spawnedPID stdinWriteFD = stdinFDs[1] stdoutReadFD = stdoutFDs[0] @@ -549,7 +549,6 @@ private final class NotificationHookProcessRun: @unchecked Sendable { makeNonBlocking(stdoutReadFD) makeNonBlocking(stderrReadFD) } - private func environmentStrings() -> [String] { var env = ProcessInfo.processInfo.environment env["CMUX_NOTIFICATION_TITLE"] = envelope.notification.title @@ -560,7 +559,6 @@ private final class NotificationHookProcessRun: @unchecked Sendable { env["CMUX_NOTIFICATION_POLICY_JSON"] = String(data: inputData, encoding: .utf8) ?? "" return env.map { "\($0.key)=\($0.value)" } } - private func addDup2( _ fileActions: inout posix_spawn_file_actions_t?, from source: Int32, @@ -571,12 +569,10 @@ private final class NotificationHookProcessRun: @unchecked Sendable { operation: "configure hook pipe" ) } - private func throwIfPOSIXError(_ result: Int32, operation: String) throws { guard result != 0 else { return } throw POSIXError(.init(rawValue: result) ?? .EIO) } - private func withCStringArray( _ strings: [String], _ body: (UnsafeMutablePointer?>) throws -> T @@ -592,18 +588,15 @@ private final class NotificationHookProcessRun: @unchecked Sendable { try body(buffer.baseAddress!) } } - private func makeNonBlocking(_ fileDescriptor: Int32) { let flags = fcntl(fileDescriptor, F_GETFL) guard flags >= 0 else { return } _ = fcntl(fileDescriptor, F_SETFL, flags | O_NONBLOCK) } - private func installReadSources() { stdoutSource = makeReadSource(fileDescriptor: stdoutReadFD, stream: .stdout) stderrSource = makeReadSource(fileDescriptor: stderrReadFD, stream: .stderr) } - private func makeReadSource( fileDescriptor: Int32, stream: NotificationHookOutputStream @@ -627,7 +620,6 @@ private final class NotificationHookProcessRun: @unchecked Sendable { source.resume() return source } - private func installWaitSource() { let source = DispatchSource.makeProcessSource( identifier: processId, @@ -640,7 +632,6 @@ private final class NotificationHookProcessRun: @unchecked Sendable { waitSource = source source.resume() } - private func installTimeoutSource() { let source = DispatchSource.makeTimerSource(queue: queue) source.schedule(deadline: .now() + hook.timeoutSeconds) @@ -650,7 +641,6 @@ private final class NotificationHookProcessRun: @unchecked Sendable { timeoutSource = source source.resume() } - private func writeInputAndCloseStdin() { guard stdinWriteFD >= 0 else { return } let fileDescriptor = stdinWriteFD @@ -675,7 +665,6 @@ private final class NotificationHookProcessRun: @unchecked Sendable { close(fileDescriptor) } } - private func timeoutReached() { guard !didComplete else { return } if let status = reapProcessIfExited() { @@ -688,6 +677,17 @@ private final class NotificationHookProcessRun: @unchecked Sendable { )) } + private func requestCancellation() { + guard !didComplete else { return } + didRequestCancellation = true + guard continuation != nil else { return } + requestTermination(cancellationFailure()) + } + + private func cancellationFailure() -> TerminalNotificationPolicyFailure { + TerminalNotificationPolicyEngine.failure(hook: hook, message: "Notification hook cancelled") + } + private func requestTermination(_ failure: TerminalNotificationPolicyFailure) { guard !didComplete else { return } if pendingFailure == nil { diff --git a/Sources/TerminalNotificationPolicyInFlightStore.swift b/Sources/TerminalNotificationPolicyInFlightStore.swift new file mode 100644 index 000000000000..c2214f769737 --- /dev/null +++ b/Sources/TerminalNotificationPolicyInFlightStore.swift @@ -0,0 +1,111 @@ +import Foundation + +/// Tracks notification-policy evaluations across their asynchronous hook +/// boundary so a clear can invalidate work that has left the mutation queue +/// but has not yet applied to the notification store. +@MainActor +final class TerminalNotificationPolicyInFlightStore { + private struct Entry { + let request: TerminalNotificationPolicyRequest + let generation: UInt64 + let onDiscard: @MainActor @Sendable () -> Void + var task: Task? + } + private let maximumRequestCount = 1_024 + private var requests: [UUID: Entry] = [:] + private var requestOrder: [UUID] = [] + private var requestOrderOffset = 0 + + func register( + _ request: TerminalNotificationPolicyRequest, + generation: UInt64, + onDiscard: @escaping @MainActor @Sendable () -> Void + ) -> UUID { + compactRequestOrderIfNeeded() + while requests.count >= maximumRequestCount, requestOrderOffset < requestOrder.count { + discardRequest(requestOrder[requestOrderOffset]) + requestOrderOffset += 1 + } + let id = UUID() + requests[id] = Entry(request: request, generation: generation, onDiscard: onDiscard, task: nil) + requestOrder.append(id) + return id + } + + func attach(task: Task, to id: UUID) { + guard var entry = requests[id] else { task.cancel(); return } + entry.task = task + requests[id] = entry + } + + func claim(_ id: UUID?) -> Bool { + guard let id else { return true } + return requests.removeValue(forKey: id) != nil + } + + func discardAll(through generation: UInt64? = nil) { + let ids: [UUID] = requests.compactMap { id, entry -> UUID? in + if let generation, entry.generation > generation { return nil } + return id + } + ids.forEach(discardRequest) + if generation == nil { + requestOrder.removeAll(keepingCapacity: true) + requestOrderOffset = 0 + } + } + + /// Discards requests by their delivery identity: source-confined requests + /// keep their original workspace key, while trusted local requests follow + /// their surface's live owner. + func discard(forTabId tabId: UUID, surfaceId: UUID?, through generation: UInt64? = nil) { + var resolvedSurfaces = Set() + var liveOwnersBySurface: [UUID: UUID] = [:] + var idsToDiscard: [UUID] = [] + for (id, entry) in requests { + if let generation, entry.generation > generation { continue } + let request = entry.request + if !request.retargetsToLiveSurfaceOwner { + if let surfaceId { + if request.tabId == tabId, request.surfaceId == surfaceId { idsToDiscard.append(id) } + } else if request.tabId == tabId { + idsToDiscard.append(id) + } + continue + } + if let surfaceId { + if request.surfaceId == surfaceId { idsToDiscard.append(id) } + continue + } + guard let requestSurfaceId = request.surfaceId else { + if request.tabId == tabId { idsToDiscard.append(id) } + continue + } + let liveTabId: UUID + if resolvedSurfaces.insert(requestSurfaceId).inserted { + let owner = AppDelegate.shared?.agentNotificationDeliveryTarget( + claimedTabId: request.tabId, + surfaceId: requestSurfaceId + )?.tabId + if let owner { liveOwnersBySurface[requestSurfaceId] = owner } + liveTabId = owner ?? request.tabId + } else { + liveTabId = liveOwnersBySurface[requestSurfaceId] ?? request.tabId + } + if liveTabId == tabId { idsToDiscard.append(id) } + } + idsToDiscard.forEach(discardRequest) + } + + private func discardRequest(_ id: UUID) { + guard let entry = requests.removeValue(forKey: id) else { return } + entry.task?.cancel() + entry.onDiscard() + } + + private func compactRequestOrderIfNeeded() { + guard requestOrder.count > maximumRequestCount * 2 else { return } + requestOrder = requestOrder.dropFirst(requestOrderOffset).filter { requests[$0] != nil } + requestOrderOffset = 0 + } +} diff --git a/Sources/TerminalNotificationQueue.swift b/Sources/TerminalNotificationQueue.swift index ccbcbbace767..b0c56eb308b0 100644 --- a/Sources/TerminalNotificationQueue.swift +++ b/Sources/TerminalNotificationQueue.swift @@ -15,9 +15,9 @@ fileprivate struct QueuedTerminalNotification: Sendable { fileprivate enum TerminalSocketMutation { case deliverNotification(QueuedTerminalNotification) - case clearAllNotifications - case clearNotificationsForTab(UUID) - case clearNotificationsForSurface(UUID, UUID) + case clearAllNotifications(through: UInt64) + case clearNotificationsForTab(UUID, through: UInt64) + case clearNotificationsForSurface(UUID, UUID, through: UInt64) case perform(@MainActor () -> Void) } @@ -78,18 +78,21 @@ final class TerminalMutationBus: @unchecked Sendable { } nonisolated func enqueueClearAllNotifications() { - enqueueClear(.clearAllNotifications) { _ in true } + enqueueClear({ .clearAllNotifications(through: $0) }) { _ in true } } nonisolated func enqueueClearNotifications(forTabId tabId: UUID) { - enqueueClear(.clearNotificationsForTab(tabId)) { notification in - notification.key.tabId == tabId + // Surface-addressed entries may have moved since enqueue. Keep them + // ahead of the barrier so delivery can resolve their live owner first. + enqueueClear({ .clearNotificationsForTab(tabId, through: $0) }) { notification in + notification.key.tabId == tabId && notification.key.surfaceId == nil } } nonisolated func enqueueClearNotifications(forTabId tabId: UUID, surfaceId: UUID) { - enqueueClear(.clearNotificationsForSurface(tabId, surfaceId)) { notification in - notification.key.tabId == tabId && notification.key.surfaceId == surfaceId + // Canonical surface identity: a stale-keyed entry would retarget here at drain. + enqueueClear({ .clearNotificationsForSurface(tabId, surfaceId, through: $0) }) { notification in + notification.key.surfaceId == surfaceId } } @@ -105,6 +108,8 @@ final class TerminalMutationBus: @unchecked Sendable { return boundary } + nonisolated func notificationGenerationSnapshot() -> UInt64 { lock.withLock { currentNotificationGeneration } } + nonisolated func discardPendingNotifications(forTabId tabId: UUID, through boundary: UInt64) { discardPendingNotifications { notification, generation in notification.key.tabId == tabId && generation <= boundary @@ -129,12 +134,57 @@ final class TerminalMutationBus: @unchecked Sendable { } } + /// Exact enqueue-key discard. Use for source-scoped operations like + /// `rebindSurfaceNotifications`, where a surface-wide discard could drop a + /// newer entry legitimately queued under the destination key mid-move. nonisolated func discardPendingNotifications(forTabId tabId: UUID, surfaceId: UUID?) { discardPendingNotifications { notification, _ in notification.key.tabId == tabId && notification.key.surfaceId == surfaceId } } + /// Canonical-identity discard for clears and supersedes: pending entries + /// are keyed by their enqueue-time (claimed) workspace but DELIVER to the + /// surface's live owner (#7939), so a clear that matched only the claimed + /// key would let a stale-keyed entry resurrect the notification at drain. + nonisolated func discardPendingNotifications(forSurfaceId surfaceId: UUID) { + discardPendingNotifications { notification, _ in + notification.key.surfaceId == surfaceId + } + } + + /// Clear-scoped discard: canonical surface identity when surface-scoped; + /// live destination workspace when workspace-scoped. + @MainActor + func discardPendingNotificationsForClear(tabId: UUID, surfaceId: UUID?) { + if let surfaceId { discardPendingNotifications(forSurfaceId: surfaceId) } + else { discardPendingNotificationsResolvingLiveOwner(forTabId: tabId) } + } + + /// Phase 1 of the live-owner workspace clear (see + /// `discardPendingNotificationsResolvingLiveOwner(forTabId:)`): the + /// pending notification addresses, identified by their exact sequence. + nonisolated func pendingNotificationAddressesSnapshot() -> [(sequence: UInt64, tabId: UUID, surfaceId: UUID?)] { + lock.lock() + defer { lock.unlock() } + return pending.compactMap { entry in + guard case .deliverNotification(let notification) = entry.mutation else { return nil } + return (entry.sequence, notification.key.tabId, notification.key.surfaceId) + } + } + + /// Phase 2: discard exactly the snapshotted entries; anything enqueued + /// after the snapshot keeps its place. + nonisolated func discardPendingNotifications(sequences: Set) { + guard !sequences.isEmpty else { return } + lock.lock() + pending.removeAll { entry in + guard case .deliverNotification = entry.mutation else { return false } + return sequences.contains(entry.sequence) + } + lock.unlock() + } + private func enqueueNotification(_ notification: QueuedTerminalNotification, coalesces: Bool) { let shouldScheduleDrain: Bool let removedCount: Int @@ -183,11 +233,13 @@ final class TerminalMutationBus: @unchecked Sendable { } private func enqueueClear( - _ mutation: TerminalSocketMutation, + _ mutation: (UInt64) -> TerminalSocketMutation, dropping shouldDrop: (QueuedTerminalNotification) -> Bool ) { let shouldScheduleDrain: Bool lock.lock() + let boundary = currentNotificationGeneration + currentNotificationGeneration &+= 1 pending.removeAll { entry in if case .deliverNotification(let notification) = entry.mutation { return shouldDrop(notification) @@ -197,7 +249,7 @@ final class TerminalMutationBus: @unchecked Sendable { nextSequence &+= 1 pending.append(TerminalSocketMutationEntry( sequence: nextSequence, - mutation: mutation, + mutation: mutation(boundary), notificationGeneration: nil, notificationCoalescingKey: nil, performReplaceKey: nil @@ -381,19 +433,28 @@ final class TerminalMutationBus: @unchecked Sendable { "notification.queue.perform seq=\(entry.sequence) workspace=\(notification.key.tabId.uuidString.prefix(8)) surface=\(notification.key.surfaceId?.uuidString.prefix(8) ?? "nil") titleLen=\(notification.title.count) subtitleLen=\(notification.subtitle.count) bodyLen=\(notification.body.count)" ) #endif - TerminalNotificationStore.shared.deliverQueuedNotification(notification) - case .clearAllNotifications: - TerminalNotificationStore.shared.clearAll(discardQueuedNotifications: false) - case .clearNotificationsForTab(let tabId): + TerminalNotificationStore.shared.deliverQueuedNotification( + claimedTabId: notification.key.tabId, + surfaceId: notification.key.surfaceId, + title: notification.title, + subtitle: notification.subtitle, + body: notification.body, + notificationGeneration: entry.notificationGeneration ?? 0 + ) + case .clearAllNotifications(let boundary): + TerminalNotificationStore.shared.clearAll(discardQueuedNotifications: false, throughNotificationGeneration: boundary) + case .clearNotificationsForTab(let tabId, let boundary): TerminalNotificationStore.shared.clearNotifications( forTabId: tabId, - discardQueuedNotifications: false + discardQueuedNotifications: false, + throughNotificationGeneration: boundary ) - case .clearNotificationsForSurface(let tabId, let surfaceId): + case .clearNotificationsForSurface(let tabId, let surfaceId, let boundary): TerminalNotificationStore.shared.clearNotifications( forTabId: tabId, surfaceId: surfaceId, - discardQueuedNotifications: false + discardQueuedNotifications: false, + throughNotificationGeneration: boundary ) case .perform(let mutation): mutation() @@ -402,70 +463,7 @@ final class TerminalMutationBus: @unchecked Sendable { } } -extension TerminalController { - func deliverNotificationSynchronously( - tabId: UUID, - surfaceId: UUID?, - title: String, - subtitle: String, - body: String - ) { - TerminalMutationBus.shared.discardPendingNotifications(forTabId: tabId, surfaceId: surfaceId) -#if DEBUG - cmuxDebugLog( - "notification.sync.deliver workspace=\(tabId.uuidString.prefix(8)) surface=\(surfaceId?.uuidString.prefix(8) ?? "nil") titleLen=\(title.count) subtitleLen=\(subtitle.count) bodyLen=\(body.count)" - ) -#endif - TerminalNotificationStore.shared.addNotification( - tabId: tabId, - surfaceId: surfaceId, - title: title, - subtitle: subtitle, - body: body - ) - } -} - extension TerminalNotificationStore { - fileprivate func deliverQueuedNotification(_ notification: QueuedTerminalNotification) { - guard shouldDeliverQueuedNotification(notification) else { -#if DEBUG - cmuxDebugLog( - "notification.queue.deliver.skip workspace=\(notification.key.tabId.uuidString.prefix(8)) surface=\(notification.key.surfaceId?.uuidString.prefix(8) ?? "nil") reason=targetMissing titleLen=\(notification.title.count) subtitleLen=\(notification.subtitle.count) bodyLen=\(notification.body.count)" - ) -#endif - return - } -#if DEBUG - cmuxDebugLog( - "notification.queue.deliver workspace=\(notification.key.tabId.uuidString.prefix(8)) surface=\(notification.key.surfaceId?.uuidString.prefix(8) ?? "nil") titleLen=\(notification.title.count) subtitleLen=\(notification.subtitle.count) bodyLen=\(notification.body.count)" - ) -#endif - addNotification( - tabId: notification.key.tabId, - surfaceId: notification.key.surfaceId, - title: notification.title, - subtitle: notification.subtitle, - body: notification.body - ) - } - - private func shouldDeliverQueuedNotification(_ notification: QueuedTerminalNotification) -> Bool { - guard let appDelegate = AppDelegate.shared else { return false } - guard let surfaceId = notification.key.surfaceId else { - let tabManager = appDelegate.tabManagerFor(tabId: notification.key.tabId) ?? appDelegate.tabManager - return tabManager?.tabs.contains(where: { $0.id == notification.key.tabId }) == true - } - - guard let target = appDelegate.workspaceContainingPanel( - panelId: surfaceId, - preferredWorkspaceId: notification.key.tabId - ) else { - return false - } - return target.workspace.id == notification.key.tabId - } - static func cachedDeliveryAuthorizationDecision( for state: NotificationAuthorizationState, isAppActive: Bool diff --git a/Sources/TerminalNotificationStore.swift b/Sources/TerminalNotificationStore.swift index 59edf14463e4..492bd95093bc 100644 --- a/Sources/TerminalNotificationStore.swift +++ b/Sources/TerminalNotificationStore.swift @@ -192,7 +192,7 @@ final class TerminalNotificationStore: ObservableObject { static let categoryIdentifier = "com.cmuxterm.app.userNotification" static let actionShowIdentifier = "com.cmuxterm.app.userNotification.show" - + nonisolated static let retargetsToLiveSurfaceOwnerUserInfoKey = "retargetsToLiveSurfaceOwner" /// Mobile-host event topic the Mac emits when one or more delivered /// notifications are dismissed/cleared on this Mac, so an attached phone can /// clear the matching banners it is mirroring. Payload carries the stable @@ -463,7 +463,7 @@ final class TerminalNotificationStore: ObservableObject { var lastNotificationDateByCooldownKey: [String: Date] = [:] var lastNotificationHookFailureDateByKey: [NotificationHookFailureThrottleKey: Date] = [:] private var indexes = NotificationIndexes() - + private let inFlightPolicyRequests = TerminalNotificationPolicyInFlightStore() private init() { indexes = Self.buildIndexes(for: notifications) userDefaultsObserver = NotificationCenter.default.addObserver( @@ -832,9 +832,10 @@ final class TerminalNotificationStore: ObservableObject { title: String, subtitle: String, body: String, + retargetsToLiveSurfaceOwner: Bool = true, cooldownKey: String? = nil, cooldownInterval: TimeInterval? = nil, - clickAction: TerminalNotificationClickAction? = nil + clickAction: TerminalNotificationClickAction? = nil, notificationGeneration: UInt64? = nil ) { #if DEBUG cmuxDebugLog( @@ -866,13 +867,13 @@ final class TerminalNotificationStore: ObservableObject { if let cooldownReservation { lastNotificationDateByCooldownKey[cooldownReservation.key] = now } - let policyContext = makeNotificationPolicyContext( tabId: tabId, surfaceId: surfaceId, title: title, subtitle: subtitle, - body: body + body: body, + retargetsToLiveSurfaceOwner: retargetsToLiveSurfaceOwner ) guard !policyContext.hooks.isEmpty else { applyNotification( @@ -885,13 +886,14 @@ final class TerminalNotificationStore: ObservableObject { ) return } - - Task { @MainActor [weak self] in + let policyRequestId = inFlightPolicyRequests.register(policyContext.request, generation: notificationGeneration ?? TerminalMutationBus.shared.notificationGenerationSnapshot(), onDiscard: { [weak self] in self?.restoreCooldownReservation(cooldownReservation) }) + let task = Task { @MainActor [weak self] in guard let self else { return } let authorizedHooks = await NotificationPolicyHookAuthorizer.authorize( policyContext.hooks, globalConfigPath: policyContext.globalConfigPath ) + guard !Task.isCancelled else { return } guard !authorizedHooks.isEmpty else { self.applyNotification( request: policyContext.request, @@ -899,15 +901,15 @@ final class TerminalNotificationStore: ObservableObject { now: Date(), cooldownReservation: cooldownReservation, scrollPosition: policyContext.scrollPosition, - clickAction: clickAction + clickAction: clickAction, policyRequestId: policyRequestId ) return } - let result = await TerminalNotificationPolicyEngine.evaluate( request: policyContext.request, hooks: authorizedHooks ) + guard !Task.isCancelled else { return } switch result { case .success(let envelope): self.applyNotification( @@ -916,7 +918,7 @@ final class TerminalNotificationStore: ObservableObject { now: Date(), cooldownReservation: cooldownReservation, scrollPosition: policyContext.scrollPosition, - clickAction: clickAction + clickAction: clickAction, policyRequestId: policyRequestId ) case .failure(let failure): self.applyNotification( @@ -925,25 +927,23 @@ final class TerminalNotificationStore: ObservableObject { now: Date(), cooldownReservation: cooldownReservation, scrollPosition: policyContext.scrollPosition, - clickAction: clickAction + clickAction: clickAction, policyRequestId: policyRequestId ) self.reportNotificationHookFailure(failure) } } + inFlightPolicyRequests.attach(task: task, to: policyRequestId) } - private struct NotificationCooldownReservation: Sendable { let key: String let previousDate: Date? } - private struct NotificationPolicyContext: Sendable { let request: TerminalNotificationPolicyRequest let scrollPosition: TerminalNotificationScrollPosition? let hooks: [CmuxResolvedNotificationHook] let globalConfigPath: String? } - private func makeCooldownReservation( key: String?, interval: TimeInterval? @@ -954,7 +954,6 @@ final class TerminalNotificationStore: ObservableObject { previousDate: lastNotificationDateByCooldownKey[key] ) } - private func commitCooldownReservation( _ reservation: NotificationCooldownReservation?, at date: Date @@ -962,7 +961,6 @@ final class TerminalNotificationStore: ObservableObject { guard let reservation else { return } lastNotificationDateByCooldownKey[reservation.key] = date } - private func restoreCooldownReservation(_ reservation: NotificationCooldownReservation?) { guard let reservation else { return } if let previousDate = reservation.previousDate { @@ -977,7 +975,8 @@ final class TerminalNotificationStore: ObservableObject { surfaceId: UUID?, title: String, subtitle: String, - body: String + body: String, + retargetsToLiveSurfaceOwner: Bool ) -> NotificationPolicyContext { let appDelegate = AppDelegate.shared let context = appDelegate?.contextContainingTabId(tabId) @@ -1014,6 +1013,7 @@ final class TerminalNotificationStore: ObservableObject { tabId: tabId, surfaceId: surfaceId, panelId: panelId, + retargetsToLiveSurfaceOwner: retargetsToLiveSurfaceOwner, title: title, subtitle: subtitle, body: body, @@ -1026,14 +1026,13 @@ final class TerminalNotificationStore: ObservableObject { globalConfigPath: cmuxConfigStore?.globalConfigPath ) } - private func applyNotification( request: TerminalNotificationPolicyRequest, envelope: TerminalNotificationPolicyEnvelope, now: Date, cooldownReservation: NotificationCooldownReservation?, scrollPosition: TerminalNotificationScrollPosition?, - clickAction: TerminalNotificationClickAction? + clickAction: TerminalNotificationClickAction?, policyRequestId: UUID? ) { let payload = envelope.notification applyNotification( @@ -1041,6 +1040,7 @@ final class TerminalNotificationStore: ObservableObject { tabId: request.tabId, surfaceId: request.surfaceId, panelId: request.panelId, + retargetsToLiveSurfaceOwner: request.retargetsToLiveSurfaceOwner, title: payload.title, subtitle: payload.subtitle, body: payload.body, @@ -1052,7 +1052,7 @@ final class TerminalNotificationStore: ObservableObject { now: now, cooldownReservation: cooldownReservation, scrollPosition: scrollPosition, - clickAction: clickAction + clickAction: clickAction, policyRequestId: policyRequestId ) } @@ -1062,8 +1062,10 @@ final class TerminalNotificationStore: ObservableObject { now: Date, cooldownReservation: NotificationCooldownReservation?, scrollPosition: TerminalNotificationScrollPosition?, - clickAction: TerminalNotificationClickAction? + clickAction: TerminalNotificationClickAction?, policyRequestId: UUID? = nil ) { + guard inFlightPolicyRequests.claim(policyRequestId) else { return } + guard let request = notificationPolicyRequestAtLiveOwner(request) else { restoreCooldownReservation(cooldownReservation); return } let shouldSuppressExternalDelivery = shouldSuppressExternalDelivery( tabId: request.tabId, surfaceId: request.surfaceId @@ -1073,6 +1075,7 @@ final class TerminalNotificationStore: ObservableObject { tabId: request.tabId, surfaceId: request.surfaceId, panelId: request.panelId, + retargetsToLiveSurfaceOwner: request.retargetsToLiveSurfaceOwner, title: request.title, subtitle: request.subtitle, body: request.body, @@ -1082,7 +1085,6 @@ final class TerminalNotificationStore: ObservableObject { scrollPosition: scrollPosition, clickAction: clickAction ) - if effects.record { recordNotification( notification, @@ -1115,7 +1117,6 @@ final class TerminalNotificationStore: ObservableObject { effects: effects ) } - private func recordNotification( _ notification: TerminalNotification, shouldSuppressExternalDelivery: Bool, @@ -1551,12 +1552,12 @@ final class TerminalNotificationStore: ObservableObject { while !usedIds.insert(replacementId).inserted { replacementId = UUID() } - return TerminalNotification( id: replacementId, tabId: notification.tabId, surfaceId: notification.surfaceId, panelId: notification.panelId, + retargetsToLiveSurfaceOwner: notification.retargetsToLiveSurfaceOwner, title: notification.title, subtitle: notification.subtitle, body: notification.body, @@ -1569,8 +1570,8 @@ final class TerminalNotificationStore: ObservableObject { } private func replaceNotificationsForClear(_ next: [TerminalNotification]) { suppressNotificationDiffPublishing = true; notifications = next; suppressNotificationDiffPublishing = false } - - func clearAll(discardQueuedNotifications: Bool = true) { + func clearAll(discardQueuedNotifications: Bool = true, throughNotificationGeneration: UInt64? = nil) { + inFlightPolicyRequests.discardAll(through: throughNotificationGeneration) if discardQueuedNotifications { TerminalMutationBus.shared.discardPendingNotifications() } guard !notifications.isEmpty || !focusedReadIndicatorByTabId.isEmpty || @@ -1594,20 +1595,20 @@ final class TerminalNotificationStore: ObservableObject { func clearNotifications( forTabId tabId: UUID, surfaceId: UUID?, - discardQueuedNotifications: Bool = true + discardQueuedNotifications: Bool = true, throughNotificationGeneration: UInt64? = nil ) { - if discardQueuedNotifications { TerminalMutationBus.shared.discardPendingNotifications(forTabId: tabId, surfaceId: surfaceId) } - let hadFocusedReadIndicator = focusedReadIndicatorByTabId[tabId].map { $0 == surfaceId } ?? false + let liveTabId = surfaceId.flatMap { AppDelegate.shared?.agentNotificationDeliveryTarget(claimedTabId: tabId, surfaceId: $0)?.tabId } ?? tabId + let tabIds = Set([tabId, liveTabId]) + inFlightPolicyRequests.discard(forTabId: tabId, surfaceId: surfaceId, through: throughNotificationGeneration) + if discardQueuedNotifications { TerminalMutationBus.shared.discardPendingNotificationsForClear(tabId: liveTabId, surfaceId: surfaceId) } let hadRestoredWorkspaceUnread = surfaceId == nil && restoredUnreadWorkspaceIds.contains(tabId) var updated: [TerminalNotification] = [] updated.reserveCapacity(notifications.count) - var idsToClear: [String] = [] - var supersededDrained = supersededPhoneDismissBuffer.flush( - forKey: SupersededPhoneDismissBuffer.key(tabId: tabId, surfaceId: surfaceId) - ) + var idsToClear: [String] = [], indicatorTabIds: Set = [tabId] + var supersededDrained: [String] = [] for notification in notifications { - if notification.matches(tabId: tabId, surfaceId: surfaceId) { - idsToClear.append(notification.id.uuidString) + if notification.matchesClear(tabId: tabId, liveTabId: liveTabId, surfaceId: surfaceId) { + idsToClear.append(notification.id.uuidString); indicatorTabIds.insert(notification.tabId) supersededDrained.append(contentsOf: supersededPhoneDismissBuffer.flush( forKey: SupersededPhoneDismissBuffer.key( tabId: notification.tabId, @@ -1618,6 +1619,7 @@ final class TerminalNotificationStore: ObservableObject { updated.append(notification) } } + let hadFocusedReadIndicator = indicatorTabIds.contains { focusedReadIndicatorByTabId[$0].map { $0 == surfaceId } ?? false } guard !idsToClear.isEmpty || hadFocusedReadIndicator || hadRestoredWorkspaceUnread else { return } if !idsToClear.isEmpty { replaceNotificationsForClear(updated) @@ -1625,9 +1627,9 @@ final class TerminalNotificationStore: ObservableObject { if surfaceId == nil { setWorkspaceRestoredUnread(false, forTabId: tabId) } - clearFocusedReadIndicator(forTabId: tabId, surfaceId: surfaceId) + indicatorTabIds.forEach { clearFocusedReadIndicator(forTabId: $0, surfaceId: surfaceId) } if !idsToClear.isEmpty { - CmuxEventBus.shared.publishNotificationCleared(ids: idsToClear, workspaceId: tabId, surfaceId: surfaceId) + CmuxEventBus.shared.publishNotificationCleared(ids: idsToClear, workspaceId: tabIds.count == 1 ? tabId : nil, surfaceId: surfaceId) center.removeDeliveredNotificationsOffMain(withIdentifiers: idsToClear) center.removePendingNotificationRequestsOffMain(withIdentifiers: idsToClear) emitNotificationsDismissed(ids: idsToClear, drainedSuperseded: supersededDrained) @@ -1636,11 +1638,10 @@ final class TerminalNotificationStore: ObservableObject { func rebindSurfaceNotifications(fromTabId sourceTabId: UUID, toTabId destinationTabId: UUID, surfaceId: UUID) { guard sourceTabId != destinationTabId else { return } - TerminalMutationBus.shared.discardPendingNotifications(forTabId: sourceTabId, surfaceId: surfaceId) - var didMoveNotification = false let updated = notifications.map { notification -> TerminalNotification in - guard notification.matches(tabId: sourceTabId, surfaceId: surfaceId) else { + guard notification.retargetsToLiveSurfaceOwner, + notification.matches(tabId: sourceTabId, surfaceId: surfaceId) else { return notification } didMoveNotification = true @@ -1662,17 +1663,16 @@ final class TerminalNotificationStore: ObservableObject { if didMoveNotification { notifications = updated } - - if focusedReadIndicatorByTabId[sourceTabId] == surfaceId { + if didMoveNotification, focusedReadIndicatorByTabId[sourceTabId] == surfaceId { focusedReadIndicatorByTabId.removeValue(forKey: sourceTabId) if focusedReadIndicatorByTabId[destinationTabId] == nil { focusedReadIndicatorByTabId[destinationTabId] = surfaceId } } } - - func clearNotifications(forTabId tabId: UUID, discardQueuedNotifications: Bool = true) { - if discardQueuedNotifications { TerminalMutationBus.shared.discardPendingNotifications(forTabId: tabId) } + func clearNotifications(forTabId tabId: UUID, discardQueuedNotifications: Bool = true, throughNotificationGeneration: UInt64? = nil) { + inFlightPolicyRequests.discard(forTabId: tabId, surfaceId: nil, through: throughNotificationGeneration) + if discardQueuedNotifications { TerminalMutationBus.shared.discardPendingNotificationsForClear(tabId: tabId, surfaceId: nil) } let hadFocusedReadIndicator = focusedReadIndicatorByTabId[tabId] != nil var updated: [TerminalNotification] = [] updated.reserveCapacity(notifications.count) @@ -1732,9 +1732,9 @@ final class TerminalNotificationStore: ObservableObject { let notificationId = notification.id let notificationTabId = notification.tabId let notificationSurfaceId = notification.surfaceId + let retargetsToLiveSurfaceOwner = notification.retargetsToLiveSurfaceOwner let clickActionUserInfo = notification.clickAction?.userInfo ?? [:] let categoryIdentifier = Self.categoryIdentifier - let handleAuthorization: NativeNotificationDeliveryHooks.AuthorizationCompletion = { authorized, effectiveAuthorizationState in let content = UNMutableNotificationContent() content.title = notificationTitle @@ -1751,6 +1751,7 @@ final class TerminalNotificationStore: ObservableObject { content.userInfo = [ "tabId": notificationTabId.uuidString, "notificationId": notificationId.uuidString, + Self.retargetsToLiveSurfaceOwnerUserInfoKey: retargetsToLiveSurfaceOwner, ] if let surfaceId = notificationSurfaceId { content.userInfo["surfaceId"] = surfaceId.uuidString @@ -1758,7 +1759,6 @@ final class TerminalNotificationStore: ObservableObject { for (key, value) in clickActionUserInfo { content.userInfo[key] = value } - let request = UNNotificationRequest( identifier: notificationId.uuidString, content: content, diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index f1fdec5bdc6e..8ea7c348c28a 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -2080,7 +2080,7 @@ final class Workspace: Identifiable, ObservableObject { /// and the transient tab-selection/focus-reassert request state. The /// legacy accessors below forward here. None of the moved properties /// were `@Published`, so no observer hooks are required. - private let surfaceRegistry = SurfaceRegistryModel() + let surfaceRegistry = SurfaceRegistryModel() /// The split-layout sub-model (CmuxPanes): owns the split/detach /// choreography bookkeeping (programmatic-split flag, detaching surface @@ -2291,12 +2291,6 @@ final class Workspace: Identifiable, ObservableObject { @Published var remoteLastHeartbeatAt: Date? @Published var listeningPorts: [Int] = [] @Published private(set) var activeRemoteTerminalSessionCount: Int = 0 - /// The controlling-terminal device name per panel id; stored in the - /// surface-registry sub-model. - var surfaceTTYNames: [UUID: String] { - get { surfaceRegistry.surfaceTTYNames } - set { surfaceRegistry.surfaceTTYNames = newValue } - } private var remoteSessionController: RemoteSessionCoordinator? private enum RemoteForegroundAuthenticationPhase: Equatable { case readyBeforeConfiguration(token: String), authenticating(token: String) @@ -3341,7 +3335,7 @@ final class Workspace: Identifiable, ObservableObject { /// The pending tab-selection request payload. Stays app-side (it carries /// AppKit hosted-view references); the surface-registry sub-model stores /// it opaquely as its `TabSelectionRequest` generic binding. - private struct PendingTabSelectionRequest { + struct PendingTabSelectionRequest { let tabId: TabID let pane: PaneID let reassertAppKitFocus: Bool diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 85fe223dca50..1c1e5db27229 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -32,6 +32,7 @@ C7A52F000000000000000002 /* AgentChatTranscriptService+Wire.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A52F000000000000000001 /* AgentChatTranscriptService+Wire.swift */; }; ACA7C4A7000000000000000B /* AgentChatTranscriptService.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACA7C4A7000000000000000C /* AgentChatTranscriptService.swift */; }; ACA7C4A70000000000000009 /* AgentChatTranscriptTailer.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACA7C4A7000000000000000A /* AgentChatTranscriptTailer.swift */; }; + 79390005AA11BB22CC33DD05 /* AgentDeliveryTargetResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79390006AA11BB22CC33DD06 /* AgentDeliveryTargetResolution.swift */; }; A9F200000000000000000001 /* AgentExecutableResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9F100000000000000000001 /* AgentExecutableResolver.swift */; }; A9F200000000000000000002 /* AgentExecutableResolverError.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9F100000000000000000002 /* AgentExecutableResolverError.swift */; }; A9E020000000000000000005 /* AgentExecutableResolverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9E010000000000000000005 /* AgentExecutableResolverTests.swift */; }; @@ -73,6 +74,9 @@ 0A1107110000000000000010 /* AgentNotificationDelivery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A1107110000000000000011 /* AgentNotificationDelivery.swift */; }; A5D41234A1B2C3D4E5F60718 /* AgentNotificationGate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D41235A1B2C3D4E5F60718 /* AgentNotificationGate.swift */; }; A5D41230A1B2C3D4E5F60718 /* AgentNotificationGateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D41231A1B2C3D4E5F60718 /* AgentNotificationGateTests.swift */; }; + 79390003AA11BB22CC33DD03 /* AgentNotificationLiveRetargetTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79390004AA11BB22CC33DD04 /* AgentNotificationLiveRetargetTests.swift */; }; + 7939000FAA11BB22CC33DD0F /* AgentNotificationMoveRaceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79390010AA11BB22CC33DD10 /* AgentNotificationMoveRaceTests.swift */; }; + 79460001AA11BB22CC33EE01 /* AgentNotificationMutationBoundaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79460002AA11BB22CC33EE02 /* AgentNotificationMutationBoundaryTests.swift */; }; C3744E030000000000000001 /* AgentPIDProcessIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3744E040000000000000001 /* AgentPIDProcessIdentity.swift */; }; B79500130000000000000001 /* AgentPortPublicationHistory.swift in Sources */ = {isa = PBXBuildFile; fileRef = B79500130000000000000002 /* AgentPortPublicationHistory.swift */; }; B79500120000000000000001 /* AgentPortRootIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = B79500120000000000000002 /* AgentPortRootIdentity.swift */; }; @@ -348,6 +352,10 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources A5D41232A1B2C3D4E5F60718 /* ClaudeBackgroundWorkNotifyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D41233A1B2C3D4E5F60718 /* ClaudeBackgroundWorkNotifyTests.swift */; }; C13519000000000000000007 /* ClaudeConfigDirectoryPathTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C13519000000000000000008 /* ClaudeConfigDirectoryPathTests.swift */; }; C7A534000000000000000002 /* ClaudeHookFeedTelemetrySwiftTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A534000000000000000001 /* ClaudeHookFeedTelemetrySwiftTests.swift */; }; + 7939000BAA11BB22CC33DD0B /* ClaudeHookLifecycleCleanupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7939000CAA11BB22CC33DD0C /* ClaudeHookLifecycleCleanupTests.swift */; }; + 79390001AA11BB22CC33DD01 /* ClaudeHookLiveDeliveryTargetTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79390002AA11BB22CC33DD02 /* ClaudeHookLiveDeliveryTargetTests.swift */; }; + 79390009AA11BB22CC33DD09 /* ClaudeHookLiveDeliveryTargetTestSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7939000AAA11BB22CC33DD0A /* ClaudeHookLiveDeliveryTargetTestSupport.swift */; }; + 79390011AA11BB22CC33DD11 /* ClaudeHookPIDAuthenticationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79390012AA11BB22CC33DD12 /* ClaudeHookPIDAuthenticationTests.swift */; }; A5D41220A1B2C3D4E5F60718 /* ClaudeHookSurfaceResolutionSwiftTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D41221A1B2C3D4E5F60718 /* ClaudeHookSurfaceResolutionSwiftTests.swift */; }; A5D41222A1B2C3D4E5F60718 /* ClaudeNotificationStatusLifecycleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D41223A1B2C3D4E5F60718 /* ClaudeNotificationStatusLifecycleTests.swift */; }; C7A533000000000000000002 /* ClaudeSessionCanonicalizationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A533000000000000000001 /* ClaudeSessionCanonicalizationContext.swift */; }; @@ -433,6 +441,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources B9000078A1B2C3D4E5F60719 /* CMUXCLI+CampfireExtensionInstall.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000079A1B2C3D4E5F60719 /* CMUXCLI+CampfireExtensionInstall.swift */; }; B9000076A1B2C3D4E5F60719 /* CMUXCLI+CampfireNotifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000077A1B2C3D4E5F60719 /* CMUXCLI+CampfireNotifications.swift */; }; C79630010000000000000002 /* CMUXCLI+ClaudeHookAck.swift in Sources */ = {isa = PBXBuildFile; fileRef = C79630010000000000000001 /* CMUXCLI+ClaudeHookAck.swift */; }; + 79390007AA11BB22CC33DD07 /* CMUXCLI+ClaudeHookDeliveryTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79390008AA11BB22CC33DD08 /* CMUXCLI+ClaudeHookDeliveryTarget.swift */; }; C72280000000000000000002 /* CMUXCLI+ClaudeHookWorkspaceRouting.swift in Sources */ = {isa = PBXBuildFile; fileRef = C72280000000000000000001 /* CMUXCLI+ClaudeHookWorkspaceRouting.swift */; }; 2DA8D48D99FB520EB179B015 /* CMUXCLI+ClaudePushNotificationHook.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CF59318F1D5B2195AC77C28 /* CMUXCLI+ClaudePushNotificationHook.swift */; }; C0D3F1F00000000000000101 /* CMUXCLI+CodexFireAndForgetHooks.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0D3F1F00000000000000102 /* CMUXCLI+CodexFireAndForgetHooks.swift */; }; @@ -1543,8 +1552,10 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources A5C41103A1B2C3D4E5F60718 /* TerminalNotificationCallerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5C41104A1B2C3D4E5F60718 /* TerminalNotificationCallerTests.swift */; }; A5A5A507A1B2C3D4E5F60718 /* TerminalNotificationClearAllTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5A5A508A1B2C3D4E5F60718 /* TerminalNotificationClearAllTests.swift */; }; A5A5A505A1B2C3D4E5F60718 /* TerminalNotificationDirectInteractionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5A5A506A1B2C3D4E5F60718 /* TerminalNotificationDirectInteractionTests.swift */; }; + 7939000DAA11BB22CC33DD0D /* TerminalNotificationLiveRetargetDelivery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7939000EAA11BB22CC33DD0E /* TerminalNotificationLiveRetargetDelivery.swift */; }; A5E380710000000000000001 /* TerminalNotificationOpenPanelFallbackTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5E380710000000000000002 /* TerminalNotificationOpenPanelFallbackTests.swift */; }; A5001096 /* TerminalNotificationPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001097 /* TerminalNotificationPolicy.swift */; }; + 79390013AA11BB22CC33DD13 /* TerminalNotificationPolicyInFlightStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79390014AA11BB22CC33DD14 /* TerminalNotificationPolicyInFlightStore.swift */; }; A5A5A501A1B2C3D4E5F60718 /* TerminalNotificationQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5A5A502A1B2C3D4E5F60718 /* TerminalNotificationQueue.swift */; }; A5A5A503A1B2C3D4E5F60718 /* TerminalNotificationQueueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5A5A504A1B2C3D4E5F60718 /* TerminalNotificationQueueTests.swift */; }; A5001098 /* TerminalNotificationScrollPosition.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001099 /* TerminalNotificationScrollPosition.swift */; }; @@ -1879,6 +1890,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources C7A52F000000000000000001 /* AgentChatTranscriptService+Wire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptService+Wire.swift"; sourceTree = ""; }; ACA7C4A7000000000000000C /* AgentChatTranscriptService.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptService.swift"; sourceTree = ""; }; ACA7C4A7000000000000000A /* AgentChatTranscriptTailer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptTailer.swift"; sourceTree = ""; }; + 79390006AA11BB22CC33DD06 /* AgentDeliveryTargetResolution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentDeliveryTargetResolution.swift; sourceTree = ""; }; A9F100000000000000000001 /* AgentExecutableResolver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentExecutableResolver.swift; sourceTree = ""; }; A9F100000000000000000002 /* AgentExecutableResolverError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentExecutableResolverError.swift; sourceTree = ""; }; A9E010000000000000000005 /* AgentExecutableResolverTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentExecutableResolverTests.swift; sourceTree = ""; }; @@ -1918,6 +1930,9 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources 0A1107110000000000000011 /* AgentNotificationDelivery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentNotificationDelivery.swift; sourceTree = ""; }; A5D41235A1B2C3D4E5F60718 /* AgentNotificationGate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentNotificationGate.swift; sourceTree = ""; }; A5D41231A1B2C3D4E5F60718 /* AgentNotificationGateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentNotificationGateTests.swift; sourceTree = ""; }; + 79390004AA11BB22CC33DD04 /* AgentNotificationLiveRetargetTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentNotificationLiveRetargetTests.swift; sourceTree = ""; }; + 79390010AA11BB22CC33DD10 /* AgentNotificationMoveRaceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentNotificationMoveRaceTests.swift; sourceTree = ""; }; + 79460002AA11BB22CC33EE02 /* AgentNotificationMutationBoundaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentNotificationMutationBoundaryTests.swift; sourceTree = ""; }; C3744E040000000000000001 /* AgentPIDProcessIdentity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentPIDProcessIdentity.swift; sourceTree = ""; }; B79500130000000000000002 /* AgentPortPublicationHistory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentPortPublicationHistory.swift; sourceTree = ""; }; B79500120000000000000002 /* AgentPortRootIdentity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentPortRootIdentity.swift; sourceTree = ""; }; @@ -2192,6 +2207,10 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5D41233A1B2C3D4E5F60718 /* ClaudeBackgroundWorkNotifyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeBackgroundWorkNotifyTests.swift; sourceTree = ""; }; C13519000000000000000008 /* ClaudeConfigDirectoryPathTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeConfigDirectoryPathTests.swift; sourceTree = ""; }; C7A534000000000000000001 /* ClaudeHookFeedTelemetrySwiftTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeHookFeedTelemetrySwiftTests.swift; sourceTree = ""; }; + 7939000CAA11BB22CC33DD0C /* ClaudeHookLifecycleCleanupTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeHookLifecycleCleanupTests.swift; sourceTree = ""; }; + 79390002AA11BB22CC33DD02 /* ClaudeHookLiveDeliveryTargetTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeHookLiveDeliveryTargetTests.swift; sourceTree = ""; }; + 7939000AAA11BB22CC33DD0A /* ClaudeHookLiveDeliveryTargetTestSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeHookLiveDeliveryTargetTestSupport.swift; sourceTree = ""; }; + 79390012AA11BB22CC33DD12 /* ClaudeHookPIDAuthenticationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeHookPIDAuthenticationTests.swift; sourceTree = ""; }; A5D41221A1B2C3D4E5F60718 /* ClaudeHookSurfaceResolutionSwiftTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeHookSurfaceResolutionSwiftTests.swift; sourceTree = ""; }; A5D41223A1B2C3D4E5F60718 /* ClaudeNotificationStatusLifecycleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeNotificationStatusLifecycleTests.swift; sourceTree = ""; }; C7A533000000000000000001 /* ClaudeSessionCanonicalizationContext.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "ClaudeSessionCanonicalizationContext.swift"; sourceTree = ""; }; @@ -2265,6 +2284,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B9000079A1B2C3D4E5F60719 /* CMUXCLI+CampfireExtensionInstall.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+CampfireExtensionInstall.swift"; sourceTree = ""; }; B9000077A1B2C3D4E5F60719 /* CMUXCLI+CampfireNotifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+CampfireNotifications.swift"; sourceTree = ""; }; C79630010000000000000001 /* CMUXCLI+ClaudeHookAck.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+ClaudeHookAck.swift"; sourceTree = ""; }; + 79390008AA11BB22CC33DD08 /* CMUXCLI+ClaudeHookDeliveryTarget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+ClaudeHookDeliveryTarget.swift"; sourceTree = ""; }; C72280000000000000000001 /* CMUXCLI+ClaudeHookWorkspaceRouting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+ClaudeHookWorkspaceRouting.swift"; sourceTree = ""; }; 4CF59318F1D5B2195AC77C28 /* CMUXCLI+ClaudePushNotificationHook.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+ClaudePushNotificationHook.swift"; sourceTree = ""; }; C0D3F1F00000000000000102 /* CMUXCLI+CodexFireAndForgetHooks.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CMUXCLI+CodexFireAndForgetHooks.swift"; sourceTree = ""; }; @@ -3314,8 +3334,10 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5C41104A1B2C3D4E5F60718 /* TerminalNotificationCallerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalNotificationCallerTests.swift; sourceTree = ""; }; A5A5A508A1B2C3D4E5F60718 /* TerminalNotificationClearAllTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalNotificationClearAllTests.swift; sourceTree = ""; }; A5A5A506A1B2C3D4E5F60718 /* TerminalNotificationDirectInteractionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalNotificationDirectInteractionTests.swift; sourceTree = ""; }; + 7939000EAA11BB22CC33DD0E /* TerminalNotificationLiveRetargetDelivery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalNotificationLiveRetargetDelivery.swift; sourceTree = ""; }; A5E380710000000000000002 /* TerminalNotificationOpenPanelFallbackTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalNotificationOpenPanelFallbackTests.swift; sourceTree = ""; }; A5001097 /* TerminalNotificationPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalNotificationPolicy.swift; sourceTree = ""; }; + 79390014AA11BB22CC33DD14 /* TerminalNotificationPolicyInFlightStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalNotificationPolicyInFlightStore.swift; sourceTree = ""; }; A5A5A502A1B2C3D4E5F60718 /* TerminalNotificationQueue.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalNotificationQueue.swift; sourceTree = ""; }; A5A5A504A1B2C3D4E5F60718 /* TerminalNotificationQueueTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalNotificationQueueTests.swift; sourceTree = ""; }; A5001099 /* TerminalNotificationScrollPosition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalNotificationScrollPosition.swift; sourceTree = ""; }; @@ -4457,6 +4479,9 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5001097 /* TerminalNotificationPolicy.swift */, F1A0C0DE0000000000000001 /* FindTextFieldSupport.swift */, A5A5A502A1B2C3D4E5F60718 /* TerminalNotificationQueue.swift */, + 79390006AA11BB22CC33DD06 /* AgentDeliveryTargetResolution.swift */, + 7939000EAA11BB22CC33DD0E /* TerminalNotificationLiveRetargetDelivery.swift */, + 79390014AA11BB22CC33DD14 /* TerminalNotificationPolicyInFlightStore.swift */, A5C41102A1B2C3D4E5F60718 /* TerminalNotificationCallerResolver.swift */, A5001301 /* SurfaceSearchOverlay.swift */, C0DE53350000000000000002 /* TerminalSearchOverlayHostingView.swift */, @@ -4950,6 +4975,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 5257257034CA4729B1211168 /* CMUXCLI+AutoNamingHooks.swift */, 5257257034CA4729B1211169 /* CMUXCLI+AutoNamingSummarizers.swift */, C72280000000000000000001 /* CMUXCLI+ClaudeHookWorkspaceRouting.swift */, + 79390008AA11BB22CC33DD08 /* CMUXCLI+ClaudeHookDeliveryTarget.swift */, B9000069A1B2C3D4E5F60719 /* CMUXCLI+AmpExtension.swift */, C0D3F1F00000000000000102 /* CMUXCLI+CodexFireAndForgetHooks.swift */, B9000073A1B2C3D4E5F60719 /* CMUXCLI+OmpExtension.swift */, @@ -5386,6 +5412,13 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5A5A506A1B2C3D4E5F60718 /* TerminalNotificationDirectInteractionTests.swift */, A5C41104A1B2C3D4E5F60718 /* TerminalNotificationCallerTests.swift */, A5D41221A1B2C3D4E5F60718 /* ClaudeHookSurfaceResolutionSwiftTests.swift */, + 79390002AA11BB22CC33DD02 /* ClaudeHookLiveDeliveryTargetTests.swift */, + 7939000CAA11BB22CC33DD0C /* ClaudeHookLifecycleCleanupTests.swift */, + 7939000AAA11BB22CC33DD0A /* ClaudeHookLiveDeliveryTargetTestSupport.swift */, + 79390004AA11BB22CC33DD04 /* AgentNotificationLiveRetargetTests.swift */, + 79390010AA11BB22CC33DD10 /* AgentNotificationMoveRaceTests.swift */, + 79460002AA11BB22CC33EE02 /* AgentNotificationMutationBoundaryTests.swift */, + 79390012AA11BB22CC33DD12 /* ClaudeHookPIDAuthenticationTests.swift */, C7A534000000000000000001 /* ClaudeHookFeedTelemetrySwiftTests.swift */, A5D41223A1B2C3D4E5F60718 /* ClaudeNotificationStatusLifecycleTests.swift */, A5D41231A1B2C3D4E5F60718 /* AgentNotificationGateTests.swift */, @@ -5897,6 +5930,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C7A52F000000000000000002 /* AgentChatTranscriptService+Wire.swift in Sources */, ACA7C4A7000000000000000B /* AgentChatTranscriptService.swift in Sources */, ACA7C4A70000000000000009 /* AgentChatTranscriptTailer.swift in Sources */, + 79390005AA11BB22CC33DD05 /* AgentDeliveryTargetResolution.swift in Sources */, A9F200000000000000000001 /* AgentExecutableResolver.swift in Sources */, A9F200000000000000000002 /* AgentExecutableResolverError.swift in Sources */, C0DEF0C10000000000000001 /* AgentForkSupport.swift in Sources */, @@ -6806,7 +6840,9 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5001542 /* TerminalImageTransfer.swift in Sources */, A5F10000000000000000000B /* TerminalNotification.swift in Sources */, A5C41101A1B2C3D4E5F60718 /* TerminalNotificationCallerResolver.swift in Sources */, + 7939000DAA11BB22CC33DD0D /* TerminalNotificationLiveRetargetDelivery.swift in Sources */, A5001096 /* TerminalNotificationPolicy.swift in Sources */, + 79390013AA11BB22CC33DD13 /* TerminalNotificationPolicyInFlightStore.swift in Sources */, A5A5A501A1B2C3D4E5F60718 /* TerminalNotificationQueue.swift in Sources */, A5001098 /* TerminalNotificationScrollPosition.swift in Sources */, 7490C0107490C0107490C010 /* TerminalNotificationStore+MemoryPressure.swift in Sources */, @@ -7002,6 +7038,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B9000078A1B2C3D4E5F60719 /* CMUXCLI+CampfireExtensionInstall.swift in Sources */, B9000076A1B2C3D4E5F60719 /* CMUXCLI+CampfireNotifications.swift in Sources */, C79630010000000000000002 /* CMUXCLI+ClaudeHookAck.swift in Sources */, + 79390007AA11BB22CC33DD07 /* CMUXCLI+ClaudeHookDeliveryTarget.swift in Sources */, C72280000000000000000002 /* CMUXCLI+ClaudeHookWorkspaceRouting.swift in Sources */, 2DA8D48D99FB520EB179B015 /* CMUXCLI+ClaudePushNotificationHook.swift in Sources */, C0D3F1F00000000000000101 /* CMUXCLI+CodexFireAndForgetHooks.swift in Sources */, @@ -7145,6 +7182,9 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A76110010000000000000003 /* AgentHookNotificationPolicy.swift in Sources */, A76110020000000000000001 /* AgentHookNotificationPolicyTests.swift in Sources */, A5D41230A1B2C3D4E5F60718 /* AgentNotificationGateTests.swift in Sources */, + 79390003AA11BB22CC33DD03 /* AgentNotificationLiveRetargetTests.swift in Sources */, + 7939000FAA11BB22CC33DD0F /* AgentNotificationMoveRaceTests.swift in Sources */, + 79460001AA11BB22CC33EE01 /* AgentNotificationMutationBoundaryTests.swift in Sources */, D3610B010000000000000001 /* AgentSessionAutoResumeSettingsTests.swift in Sources */, D3610B020000000000000001 /* AgentSessionAutoResumeSwiftTests.swift in Sources */, A9E030000000000000000002 /* AgentSessionSocketSurfaceTests.swift in Sources */, @@ -7216,6 +7256,10 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5D41232A1B2C3D4E5F60718 /* ClaudeBackgroundWorkNotifyTests.swift in Sources */, C13519000000000000000007 /* ClaudeConfigDirectoryPathTests.swift in Sources */, C7A534000000000000000002 /* ClaudeHookFeedTelemetrySwiftTests.swift in Sources */, + 7939000BAA11BB22CC33DD0B /* ClaudeHookLifecycleCleanupTests.swift in Sources */, + 79390001AA11BB22CC33DD01 /* ClaudeHookLiveDeliveryTargetTests.swift in Sources */, + 79390009AA11BB22CC33DD09 /* ClaudeHookLiveDeliveryTargetTestSupport.swift in Sources */, + 79390011AA11BB22CC33DD11 /* ClaudeHookPIDAuthenticationTests.swift in Sources */, A5D41220A1B2C3D4E5F60718 /* ClaudeHookSurfaceResolutionSwiftTests.swift in Sources */, A5D41222A1B2C3D4E5F60718 /* ClaudeNotificationStatusLifecycleTests.swift in Sources */, CE7000000000000000000001 /* ClaudeWrapperResumeEnvironmentTests.swift in Sources */, diff --git a/cmuxTests/AgentNotificationLiveRetargetTests.swift b/cmuxTests/AgentNotificationLiveRetargetTests.swift new file mode 100644 index 000000000000..20eaccd152f6 --- /dev/null +++ b/cmuxTests/AgentNotificationLiveRetargetTests.swift @@ -0,0 +1,495 @@ +import AppKit +import CmuxControlSocket +import Testing +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +/// Regression tests for https://github.com/manaflow-ai/cmux/issues/7939 / +/// https://github.com/manaflow-ai/cmux/issues/5781: a notification addressed +/// with a stale workspace id but a live surface id must be retargeted to the +/// surface's CURRENT workspace at delivery time — not dropped (async path) and +/// not recorded against the stale workspace (sync path). The unread ring and +/// the stored notification must land on the pane that owns the surface. +extension AgentNotificationRegressionTests { + private struct LiveRetargetFixture { + let store: TerminalNotificationStore + let appDelegate: AppDelegate + let manager: TabManager + let claimedWorkspace: Workspace + let owningWorkspace: Workspace + let panelId: UUID + let restore: () -> Void + } + + private func makeLiveRetargetFixture() throws -> LiveRetargetFixture { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = appDelegate.tabManager ?? TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + store.configureSuppressedNotificationFeedbackHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + + let claimedWorkspace = manager.addWorkspace(select: false) + let owningWorkspace = manager.addWorkspace(select: true) + let panelId = try #require(owningWorkspace.focusedPanelId) + + let restore = { + for workspace in [claimedWorkspace, owningWorkspace] where manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + store.resetSuppressedNotificationFeedbackHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + } + return LiveRetargetFixture( + store: store, + appDelegate: appDelegate, + manager: manager, + claimedWorkspace: claimedWorkspace, + owningWorkspace: owningWorkspace, + panelId: panelId, + restore: restore + ) + } + + @Test + func testQueuedNotificationRetargetsToSurfaceCurrentWorkspace() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + // Claimed workspace is stale (e.g. captured at spawn, pane since moved): + // the surface lives in `owningWorkspace`. + TerminalMutationBus.shared.enqueueNotification( + tabId: fixture.claimedWorkspace.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "All done" + ) + TerminalMutationBus.shared.drainForTesting() + + let recorded = fixture.store.notifications.filter { $0.title == "Claude Code" } + #expect( + recorded.map(\.tabId) == [fixture.owningWorkspace.id], + "Queued notification must be retargeted to the surface's current workspace, not dropped or misfiled" + ) + #expect(recorded.first?.surfaceId == fixture.panelId) + #expect( + fixture.store.hasUnreadNotification(forTabId: fixture.owningWorkspace.id, surfaceId: fixture.panelId), + "Unread ring must appear on the pane that owns the surface" + ) + #expect( + !fixture.store.hasUnreadNotification(forTabId: fixture.claimedWorkspace.id, surfaceId: fixture.panelId), + "Unread ring must not appear under the stale workspace" + ) + } + + @Test + func testSyncDeliveredNotificationRetargetsToSurfaceCurrentWorkspace() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + TerminalController.shared.deliverNotificationSynchronously( + tabId: fixture.claimedWorkspace.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "All done" + ) + + let recorded = fixture.store.notifications.filter { $0.title == "Claude Code" } + #expect( + recorded.map(\.tabId) == [fixture.owningWorkspace.id], + "Synchronously delivered notification must be recorded under the surface's current workspace" + ) + #expect(recorded.first?.surfaceId == fixture.panelId) + #expect( + fixture.store.hasUnreadNotification(forTabId: fixture.owningWorkspace.id, surfaceId: fixture.panelId) + ) + } + + @Test + func testSyncDeliverySupersedesPendingNotificationUnderStaleClaimedKey() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + // An older async notification still queued under the stale claimed + // workspace key... + TerminalMutationBus.shared.enqueueNotification( + tabId: fixture.claimedWorkspace.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Working", + body: "Old queued" + ) + // ...must be superseded by a newer synchronous notification for the + // same surface, even though sync delivery retargets to the owning + // workspace — a different queue key than the stale claim. + TerminalController.shared.deliverNotificationSynchronously( + tabId: fixture.claimedWorkspace.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "New sync" + ) + TerminalMutationBus.shared.drainForTesting() + + let recorded = fixture.store.notifications.filter { $0.title == "Claude Code" } + #expect( + recorded.map(\.body) == ["New sync"], + "A stale-keyed pending notification must not survive (or replace) the newer synchronous one for the same surface" + ) + #expect(recorded.map(\.tabId) == [fixture.owningWorkspace.id]) + } + + @Test + func testResolveDeliveryTargetRejectsOutOfRangePid() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + // A 64-bit pid beyond pid_t range (any socket caller controls this + // value) must neither trap nor fall through to a different routing + // claim supplied in the same untrusted request. + let result = TerminalController.shared.v2AgentResolveDeliveryTarget(params: [ + "pid": Int(Int32.max) + 1, + "surface_id": fixture.panelId.uuidString, + ]) + guard case .err(let code, _, _) = result else { + Issue.record("Expected invalid_params for an out-of-range pid, got \(result)") + return + } + #expect(code == "invalid_params") + } + + @Test + func testSurfaceScopedClearDiscardsStaleKeyedPendingNotification() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + // Queued under the stale claimed workspace key... + TerminalMutationBus.shared.enqueueNotification( + tabId: fixture.claimedWorkspace.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Stale queued" + ) + // ...then the pane (live workspace) is cleared BEFORE the queue + // drains: the stale-keyed pending entry must not outlive the clear + // and resurrect the notification the user just dismissed. + fixture.store.clearNotifications( + forTabId: fixture.owningWorkspace.id, + surfaceId: fixture.panelId + ) + TerminalMutationBus.shared.drainForTesting() + + #expect( + fixture.store.notifications.filter { $0.title == "Claude Code" }.isEmpty, + "A cleared pane must stay cleared; the stale-keyed pending entry must not deliver after the clear" + ) + #expect( + !fixture.store.hasUnreadNotification(forTabId: fixture.owningWorkspace.id, surfaceId: fixture.panelId) + ) + } + + @Test + func testWorkspaceWideClearDiscardsStaleKeyedPendingNotification() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + // Queued under a stale claimed workspace, but its surface's CURRENT + // owner is the workspace being cleared: a tab-wide clear must drop it + // (drain-time delivery would retarget it right back into the cleared + // workspace). + TerminalMutationBus.shared.enqueueNotification( + tabId: fixture.claimedWorkspace.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Stale queued" + ) + fixture.store.clearNotifications(forTabId: fixture.owningWorkspace.id) + TerminalMutationBus.shared.drainForTesting() + + #expect( + fixture.store.notifications.filter { $0.title == "Claude Code" }.isEmpty, + "A tab-wide clear of the live workspace must discard stale-keyed pending entries destined for it" + ) + #expect( + !fixture.store.hasUnreadNotification(forTabId: fixture.owningWorkspace.id, surfaceId: fixture.panelId) + ) + } + + @Test + func testWorkspaceWideClearPreservesNotificationRetargetedAwayFromClearedWorkspace() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + // The enqueue-time workspace is stale and is the one being cleared, + // but delivery follows the surface to `owningWorkspace`. Clearing the + // old workspace must not discard a notification whose live owner is a + // different workspace. + TerminalMutationBus.shared.enqueueNotification( + tabId: fixture.claimedWorkspace.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Moved away" + ) + fixture.store.clearNotifications(forTabId: fixture.claimedWorkspace.id) + TerminalMutationBus.shared.drainForTesting() + + let recorded = fixture.store.notifications.filter { $0.title == "Claude Code" } + #expect(recorded.map(\.tabId) == [fixture.owningWorkspace.id]) + #expect(recorded.first?.surfaceId == fixture.panelId) + } + + @Test + func testAsyncTabWideClearEndsWithNoResurrectedNotification() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + // v1 `clear_notifications --tab` path: the bus is FIFO, so the + // stale-keyed entry drains (retargeted into the live workspace) + // BEFORE the clear barrier wipes the store — end state must be clean. + TerminalMutationBus.shared.enqueueNotification( + tabId: fixture.claimedWorkspace.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Stale queued" + ) + TerminalMutationBus.shared.enqueueClearNotifications(forTabId: fixture.owningWorkspace.id) + TerminalMutationBus.shared.drainForTesting() + + #expect( + fixture.store.notifications.filter { $0.title == "Claude Code" }.isEmpty, + "An async tab-wide clear must not leave a resurrected notification behind" + ) + } + + @Test + func testAsyncSurfaceScopedClearDiscardsStaleKeyedPendingNotification() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + // Same resurrection race as the store-clear test, via the async + // `clear_notifications --tab --panel` socket path. + TerminalMutationBus.shared.enqueueNotification( + tabId: fixture.claimedWorkspace.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Stale queued" + ) + TerminalMutationBus.shared.enqueueClearNotifications( + forTabId: fixture.owningWorkspace.id, + surfaceId: fixture.panelId + ) + TerminalMutationBus.shared.drainForTesting() + + #expect( + fixture.store.notifications.filter { $0.title == "Claude Code" }.isEmpty, + "An async surface-scoped clear must discard the stale-keyed pending entry, not let it re-deliver" + ) + } + + @Test + func testCreateForCallerFollowsMovedPreferredSurface() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + // `cmux notify` from a moved pane: spawn-time CMUX_WORKSPACE_ID is + // stale but CMUX_SURFACE_ID is the pane's stable identity — the + // notification must follow the surface, not fall back to the stale + // workspace's focused pane. + let result = TerminalController.shared.v2NotificationCreateForCaller(params: [ + "preferred_workspace_id": fixture.claimedWorkspace.id.uuidString, + "preferred_surface_id": fixture.panelId.uuidString, + "title": "Caller notify", + "body": "Body", + ]) + guard case .ok(let payload) = result, let dict = payload as? [String: Any] else { + Issue.record("Expected delivery, got \(result)") + return + } + #expect((dict["workspace_id"] as? String) == fixture.owningWorkspace.id.uuidString) + #expect((dict["surface_id"] as? String) == fixture.panelId.uuidString) + let recorded = fixture.store.notifications.filter { $0.title == "Caller notify" } + #expect(recorded.map(\.tabId) == [fixture.owningWorkspace.id]) + #expect(recorded.first?.surfaceId == fixture.panelId) + } + + @Test + func testCreateForTargetRejectsSurfaceOutsideClaimedWorkspace() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + // SECURITY boundary: `notification.create_for_target` is reachable + // through the cloud relay, whose authorization only pins workspace_id + // to the relay's owner workspace. The membership guard here is what + // confines a relay caller to that workspace — it must NOT re-home a + // surface owned by another workspace (a leaked pane UUID would allow + // cross-workspace injection). + let routing = ControlRoutingSelectors( + hasWindowIDParam: false, + windowID: nil, + groupID: nil, + workspaceID: fixture.claimedWorkspace.id, + surfaceID: nil, + paneID: nil + ) + let resolution = TerminalController.shared.controlNotificationCreateForTarget( + routing: routing, + workspaceID: fixture.claimedWorkspace.id, + surfaceID: fixture.panelId, + title: "Target notify", + subtitle: "", + body: "Body" + ) + #expect( + resolution == .surfaceNotFound(fixture.panelId), + "create_for_target must stay confined to the claimed workspace (relay authorization boundary)" + ) + #expect(fixture.store.notifications.filter { $0.title == "Target notify" }.isEmpty) + } + + @Test + func testCreateForSurfaceFollowsMovedSurface() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + // `notification.create_for_surface` is local-only (not relay- + // reachable), so a moved surface follows its live owner — including + // when the claimed routing workspace no longer lists it. + let routing = ControlRoutingSelectors( + hasWindowIDParam: false, + windowID: nil, + groupID: nil, + workspaceID: fixture.claimedWorkspace.id, + surfaceID: nil, + paneID: nil + ) + #expect(TerminalController.shared.controlNotificationCreate( + routing: routing, + explicitSurfaceID: fixture.panelId, + title: "Primary notify", + subtitle: "", + body: "Body" + ) == .delivered(workspaceID: fixture.owningWorkspace.id, surfaceID: fixture.panelId)) + let resolution = TerminalController.shared.controlNotificationCreateForSurface( + routing: routing, + surfaceID: fixture.panelId, + title: "Surface notify", + subtitle: "", + body: "Body" + ) + guard case .delivered(let workspaceID, let surfaceID, _) = resolution else { + Issue.record("A moved surface must be re-homed, not rejected; got \(resolution)") + return + } + #expect(workspaceID == fixture.owningWorkspace.id) + #expect(surfaceID == fixture.panelId) + let recorded = fixture.store.notifications.filter { $0.title == "Surface notify" } + #expect(recorded.map(\.tabId) == [fixture.owningWorkspace.id]) + } + + @Test + func testRebindKeepsNewerDestinationKeyedPendingNotification() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + // Mid-move race: the destination already owns the surface and a hook + // enqueues a valid notification under the destination key BEFORE + // rebind runs. Rebind processing must not drop it. + TerminalMutationBus.shared.enqueueNotification( + tabId: fixture.owningWorkspace.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Destination queued" + ) + fixture.store.rebindSurfaceNotifications( + fromTabId: fixture.claimedWorkspace.id, + toTabId: fixture.owningWorkspace.id, + surfaceId: fixture.panelId + ) + TerminalMutationBus.shared.drainForTesting() + + let recorded = fixture.store.notifications.filter { $0.title == "Claude Code" } + #expect( + recorded.map(\.body) == ["Destination queued"], + "Rebind must preserve a newer destination-keyed pending entry" + ) + #expect(recorded.map(\.tabId) == [fixture.owningWorkspace.id]) + } + + @Test + func pidSignalCombiningUsesExactProcessEnvironmentFallback() { + let tty = AgentDeliveryTargetCandidate(workspaceId: UUID(), surfaceId: UUID()) + let otherEnv = AgentDeliveryTargetCandidate(workspaceId: UUID(), surfaceId: UUID()) + #expect(agentDeliveryTargetCombining(ttyTarget: tty, envTarget: nil) == tty) + #expect( + agentDeliveryTargetCombining( + ttyTarget: tty, + envTarget: AgentDeliveryTargetCandidate(workspaceId: otherEnv.workspaceId, surfaceId: tty.surfaceId) + ) == tty, + "A corroborating env surface keeps the tty answer" + ) + #expect( + agentDeliveryTargetCombining(ttyTarget: tty, envTarget: otherEnv) == nil, + "Disagreement between two individually stale-able signals must fail closed" + ) + #expect( + agentDeliveryTargetCombining(ttyTarget: nil, envTarget: otherEnv) == otherEnv, + "A start-time-keyed live process environment must resolve nested-PTY sessions whose controlling TTY differs" + ) + #expect(agentDeliveryTargetCombining(ttyTarget: nil, envTarget: nil) == nil) + } + + @Test + func testTTYDeviceMatchRequiresUniqueSurface() throws { + let workspace = Workspace(), panel = try #require(workspace.focusedPanelId) + workspace.surfaceTTYNames[panel] = "/dev/null" + #expect(workspace.surfaceTTYDevices[panel] == CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: "/dev/null")) + let w1 = UUID(), s1 = UUID(), w2 = UUID(), s2 = UUID() + let bindings: [(workspaceId: UUID, surfaceId: UUID, ttyDevice: Int64)] = [ + (workspaceId: w1, surfaceId: s1, ttyDevice: 7), + (workspaceId: w2, surfaceId: s2, ttyDevice: 9), + ] + #expect( + agentDeliveryTargetMatchingTTYDevice(7, surfaceTTYDevices: bindings) + == AgentDeliveryTargetCandidate(workspaceId: w1, surfaceId: s1) + ) + #expect(agentDeliveryTargetMatchingTTYDevice(5, surfaceTTYDevices: bindings) == nil) + #expect( + agentDeliveryTargetMatchingTTYDevice( + 7, + surfaceTTYDevices: bindings + [(workspaceId: w2, surfaceId: s2, ttyDevice: 7)] + ) == nil, + "A tty device claimed by two different surfaces must refuse to guess" + ) + #expect( + agentDeliveryTargetMatchingTTYDevice( + 7, + surfaceTTYDevices: bindings + [(workspaceId: w1, surfaceId: s1, ttyDevice: 7)] + )?.surfaceId == s1, + "Consistent duplicate rows for the same surface still resolve" + ) + } + +} diff --git a/cmuxTests/AgentNotificationMoveRaceTests.swift b/cmuxTests/AgentNotificationMoveRaceTests.swift new file mode 100644 index 000000000000..69fb8a2a0fb8 --- /dev/null +++ b/cmuxTests/AgentNotificationMoveRaceTests.swift @@ -0,0 +1,496 @@ +import AppKit +import CmuxControlSocket +import Foundation +import Testing +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite("Agent notification regressions", .serialized) +@MainActor +struct AgentNotificationRegressionTests { + struct Fixture { + let store: TerminalNotificationStore + let appDelegate: AppDelegate + let manager: TabManager + let source: Workspace + let destination: Workspace + let panelId: UUID + let restore: () -> Void + } + + func makeFixture( + policyHookCommand: String? = nil, + policyHookTimeoutSeconds: TimeInterval? = nil + ) throws -> Fixture { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = TabManager() + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + var configRoot: URL? + var configStore: CmuxConfigStore? + if let policyHookCommand { + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "cmux-notification-move-race-\(UUID().uuidString)", + isDirectory: true + ) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let configURL = root.appendingPathComponent("cmux.json") + let encodedCommand = try String(data: JSONEncoder().encode(policyHookCommand), encoding: .utf8) + let timeoutJSON = policyHookTimeoutSeconds.map { ",\"timeoutSeconds\":\($0)" } ?? "" + try #"{"notifications":{"hooks":[{"id":"move-race","command":\#(encodedCommand ?? "\"cat\"")\#(timeoutJSON)}]}}"# + .write(to: configURL, atomically: true, encoding: .utf8) + let loadedStore = CmuxConfigStore( + globalConfigPath: configURL.path, + startFileWatchers: false + ) + loadedStore.loadAll() + configRoot = root + configStore = loadedStore + } + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + store.configureSuppressedNotificationFeedbackHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + + let windowId = appDelegate.registerMainWindowContextForTesting( + tabManager: manager, + cmuxConfigStore: configStore + ) + let source = manager.addWorkspace(select: true) + let destination = manager.addWorkspace(select: false) + let panelId = try #require(source.focusedPanelId) + + return Fixture( + store: store, + appDelegate: appDelegate, + manager: manager, + source: source, + destination: destination, + panelId: panelId, + restore: { + for workspace in [source, destination] where manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + appDelegate.unregisterMainWindowContextForTesting(windowId: windowId) + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + store.resetSuppressedNotificationFeedbackHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + if let configRoot { try? FileManager.default.removeItem(at: configRoot) } + } + ) + } + + func movePanel(_ fixture: Fixture) throws { + let transfer = try #require(fixture.source.detachSurface(panelId: fixture.panelId)) + let destinationPaneId = try #require(fixture.destination.bonsplitController.allPaneIds.first) + #expect( + fixture.destination.attachDetachedSurface( + transfer, + inPane: destinationPaneId, + focus: false + ) != nil + ) + } + + func waitForNotification(in store: TerminalNotificationStore) async { + // Generous for loaded CI runners; only slows the failure path. + let deadline = ContinuousClock.now + .seconds(15) + while store.notifications.isEmpty, ContinuousClock.now < deadline { + await Task.yield() + } + if store.notifications.isEmpty { + Issue.record("Timed out waiting for policy-delayed notification") + } + } + + private func waitForFile(at url: URL) async -> Bool { + // Generous for loaded CI runners; only slows the failure path. + let deadline = ContinuousClock.now + .seconds(15) + while !FileManager.default.fileExists(atPath: url.path), ContinuousClock.now < deadline { + try? await Task.sleep(for: .milliseconds(10)) + } + return FileManager.default.fileExists(atPath: url.path) + } + + @Test("Workspace clear resolves a repeated pending surface only once") + func workspaceClearMemoizesPendingSurfaceResolution() { + let bus = TerminalMutationBus.shared + bus.discardPendingNotifications() + defer { bus.discardPendingNotifications() } + let claimedTabId = UUID() + let liveTabId = UUID() + let surfaceId = UUID() + for index in 0..<128 { + bus.enqueueNotification( + tabId: claimedTabId, + surfaceId: surfaceId, + title: "Claude Code", + subtitle: "Completed", + body: "Queued \(index)", + coalesces: false + ) + } + + var resolutionCount = 0 + let sequences = bus.pendingNotificationSequencesResolvingLiveOwner( + forTabId: liveTabId, + liveOwnerResolver: { _, _ in + resolutionCount += 1 + return liveTabId + } + ) + + #expect(sequences.count == 128) + #expect(resolutionCount == 1) + } + + @Test("Source-confined synchronous delivery does not follow a moved surface") + func sourceConfinedSynchronousDeliveryDoesNotRetarget() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + try movePanel(fixture) + + TerminalController.shared.deliverNotificationSynchronously( + tabId: fixture.source.id, + surfaceId: fixture.panelId, + title: "Relay", + subtitle: "Completed", + body: "Confined to authorized source", + retargetsToLiveSurfaceOwner: false + ) + + let recorded = fixture.store.notifications.filter { $0.title == "Relay" } + #expect(recorded.map(\.tabId) == [fixture.source.id]) + #expect(!recorded.contains { $0.tabId == fixture.destination.id }) + } + + @Test("Moving a pane preserves its pending notification") + func paneMovePreservesPendingNotification() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + + TerminalMutationBus.shared.enqueueNotification( + tabId: fixture.source.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Queued before move" + ) + try movePanel(fixture) + TerminalMutationBus.shared.drainForTesting() + + let recorded = fixture.store.notifications.filter { $0.title == "Claude Code" } + #expect(recorded.map(\.tabId) == [fixture.destination.id]) + #expect(recorded.first?.surfaceId == fixture.panelId) + } + + @Test("Policy-delayed delivery resolves the pane owner again after a move") + func policyDelayedDeliveryRetargetsAtFinalApply() async throws { + let fixture = try makeFixture(policyHookCommand: "cat") + defer { fixture.restore() } + + try await confirmation("policy-delayed notification delivered") { delivered in + fixture.store.configureNotificationDeliveryHandlerForTesting { _, _ in delivered() } + let routing = ControlRoutingSelectors( + hasWindowIDParam: false, + windowID: nil, + groupID: nil, + workspaceID: fixture.source.id, + surfaceID: nil, + paneID: nil + ) + let result = TerminalController.shared.controlNotificationCreateForSurface( + routing: routing, + surfaceID: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Policy delayed" + ) + guard case .delivered = result else { + Issue.record("Expected local surface delivery, got \(result)") + return + } + + // `addNotification` has scheduled policy evaluation but cannot run + // it until this MainActor job yields, so the move deterministically + // occurs between initial routing and final apply. + try movePanel(fixture) + await waitForNotification(in: fixture.store) + } + + let recorded = fixture.store.notifications.filter { $0.title == "Claude Code" } + #expect(recorded.map(\.tabId) == [fixture.destination.id]) + #expect(recorded.first?.surfaceId == fixture.panelId) + } + + @Test("Policy-delayed relay delivery stays in its authorized workspace") + func policyDelayedRelayDeliveryDoesNotCrossWorkspaceBoundary() async throws { + let fixture = try makeFixture(policyHookCommand: "cat") + defer { fixture.restore() } + + try await confirmation("policy-delayed relay notification delivered") { delivered in + fixture.store.configureNotificationDeliveryHandlerForTesting { _, _ in delivered() } + let routing = ControlRoutingSelectors( + hasWindowIDParam: false, + windowID: nil, + groupID: nil, + workspaceID: fixture.source.id, + surfaceID: nil, + paneID: nil + ) + let result = TerminalController.shared.controlNotificationCreateForTarget( + routing: routing, + workspaceID: fixture.source.id, + surfaceID: fixture.panelId, + title: "Relay", + subtitle: "Completed", + body: "Policy delayed" + ) + guard case .delivered = result else { + Issue.record("Expected relay-target delivery, got \(result)") + return + } + + try movePanel(fixture) + await waitForNotification(in: fixture.store) + } + + let recorded = fixture.store.notifications.filter { $0.title == "Relay" } + #expect(recorded.map(\.tabId) == [fixture.source.id]) + #expect(!recorded.contains { $0.tabId == fixture.destination.id }) + + fixture.store.clearNotifications( + forTabId: fixture.source.id, + surfaceId: fixture.panelId + ) + #expect(fixture.store.notifications.isEmpty) + } + + @Test("Immediate relay delivery stays in its authorized workspace after a move") + func immediateRelayDeliveryDoesNotRebindAcrossWorkspaceBoundary() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + AppFocusState.overrideIsFocused = true + + let routing = ControlRoutingSelectors( + hasWindowIDParam: false, + windowID: nil, + groupID: nil, + workspaceID: fixture.source.id, + surfaceID: nil, + paneID: nil + ) + let result = TerminalController.shared.controlNotificationCreateForTarget( + routing: routing, + workspaceID: fixture.source.id, + surfaceID: fixture.panelId, + title: "Relay immediate", + subtitle: "Completed", + body: "Must remain source-confined" + ) + guard case .delivered = result else { + Issue.record("Expected relay-target delivery, got \(result)") + return + } + #expect(fixture.store.focusedReadIndicatorSurfaceId(forTabId: fixture.source.id) == fixture.panelId) + + try movePanel(fixture) + + let recorded = fixture.store.notifications.filter { $0.title == "Relay immediate" } + #expect(recorded.map(\.tabId) == [fixture.source.id]) + #expect(!recorded.contains { $0.tabId == fixture.destination.id }) + #expect(fixture.store.focusedReadIndicatorSurfaceId(forTabId: fixture.destination.id) == nil) + } + + @Test("Session persistence preserves source-confined notification provenance") + func sessionPersistencePreservesSourceConfinement() throws { + let notification = TerminalNotification( + id: UUID(), + tabId: UUID(), + surfaceId: UUID(), + retargetsToLiveSurfaceOwner: false, + title: "Relay persisted", + subtitle: "Completed", + body: "Must remain source-confined", + createdAt: Date(timeIntervalSince1970: 1_700_000_000), + isRead: false + ) + + let data = try JSONEncoder().encode(SessionNotificationSnapshot(notification: notification)) + let decoded = try JSONDecoder().decode(SessionNotificationSnapshot.self, from: data) + let restored = decoded.terminalNotification( + tabId: notification.tabId, + surfaceId: notification.surfaceId, + panelId: notification.panelId + ) + + #expect(!restored.retargetsToLiveSurfaceOwner) + } + + @Test("Legacy session notifications retain trusted local move behavior") + func legacySessionNotificationDefaultsToLiveRetargeting() throws { + let legacySnapshot = SessionNotificationSnapshot( + id: UUID(), + title: "Legacy local", + subtitle: "Completed", + body: "Follows its pane", + createdAt: 1_700_000_000, + isRead: false + ) + let data = try JSONEncoder().encode(legacySnapshot) + let decoded = try JSONDecoder().decode(SessionNotificationSnapshot.self, from: data) + let restored = decoded.terminalNotification( + tabId: UUID(), + surfaceId: UUID(), + panelId: nil + ) + + #expect(restored.retargetsToLiveSurfaceOwner) + } + + @Test("A destination clear preserves source-confined in-flight relay delivery") + func destinationClearPreservesInFlightRelayDelivery() async throws { + let completionURL = FileManager.default.temporaryDirectory.appendingPathComponent( + "cmux-policy-relay-clear-finished-\(UUID().uuidString)" + ) + let fixture = try makeFixture(policyHookCommand: "cat; touch '\(completionURL.path)'") + defer { fixture.restore() } + defer { try? FileManager.default.removeItem(at: completionURL) } + + let routing = ControlRoutingSelectors( + hasWindowIDParam: false, + windowID: nil, + groupID: nil, + workspaceID: fixture.source.id, + surfaceID: nil, + paneID: nil + ) + let result = TerminalController.shared.controlNotificationCreateForTarget( + routing: routing, + workspaceID: fixture.source.id, + surfaceID: fixture.panelId, + title: "Relay", + subtitle: "Completed", + body: "Must survive destination clear" + ) + guard case .delivered = result else { + Issue.record("Expected relay-target delivery, got \(result)") + return + } + + try movePanel(fixture) + fixture.store.clearNotifications(forTabId: fixture.destination.id) + + #expect(await waitForFile(at: completionURL)) + for _ in 0..<100 { await Task.yield() } + let recorded = fixture.store.notifications.filter { $0.title == "Relay" } + #expect(recorded.map(\.tabId) == [fixture.source.id]) + #expect(!recorded.contains { $0.tabId == fixture.destination.id }) + } + + @Test("A stale source surface clear preserves destination-confined in-flight relay delivery") + func staleSourceSurfaceClearPreservesDestinationConfinedInFlightRelayDelivery() async throws { + let completionURL = FileManager.default.temporaryDirectory.appendingPathComponent( + "cmux-policy-relay-source-clear-finished-\(UUID().uuidString)" + ) + let fixture = try makeFixture(policyHookCommand: "cat; touch '\(completionURL.path)'") + defer { fixture.restore() } + defer { try? FileManager.default.removeItem(at: completionURL) } + + let routing = ControlRoutingSelectors( + hasWindowIDParam: false, + windowID: nil, + groupID: nil, + workspaceID: fixture.source.id, + surfaceID: nil, + paneID: nil + ) + let result = TerminalController.shared.controlNotificationCreateForTarget( + routing: routing, + workspaceID: fixture.source.id, + surfaceID: fixture.panelId, + title: "Relay", + subtitle: "Completed", + body: "Must stay cleared at its authorized source" + ) + guard case .delivered = result else { + Issue.record("Expected relay-target delivery, got \(result)") + return + } + + try movePanel(fixture) + _ = TerminalController.shared.controlNotificationCreateForTarget( + routing: routing, workspaceID: fixture.destination.id, surfaceID: fixture.panelId, + title: "Relay live", subtitle: "Completed", body: "Must survive stale source clear" + ) + fixture.store.clearNotifications(forTabId: fixture.source.id, surfaceId: fixture.panelId) + + #expect(await waitForFile(at: completionURL)) + for _ in 0..<100 { await Task.yield() } + let recorded = fixture.store.notifications.filter { $0.title.hasPrefix("Relay") } + #expect(recorded.map(\.tabId) == [fixture.destination.id]) + #expect(recorded.map(\.body) == ["Must survive stale source clear"]) + } + + @Test("A clear invalidates policy-delayed delivery that has not applied") + func clearInvalidatesInFlightPolicyDelivery() async throws { + let fixture = try makeFixture(policyHookCommand: "cat") + defer { fixture.restore() } + + TerminalController.shared.deliverNotificationSynchronously( + tabId: fixture.source.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Must stay cleared" + ) + try movePanel(fixture) + fixture.store.clearNotifications( + forTabId: fixture.destination.id, + surfaceId: fixture.panelId + ) + + for _ in 0..<100 { await Task.yield() } + #expect(fixture.store.notifications.isEmpty) + } + + @Test("A surface clear follows a stored notification to its current workspace") + func surfaceClearRetargetsStoredNotification() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + + fixture.store.addNotification( + tabId: fixture.source.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Stored before move" + ) + try movePanel(fixture) + #expect(fixture.store.notifications.map(\.tabId) == [fixture.destination.id]) + + fixture.store.clearNotifications( + forTabId: fixture.source.id, + surfaceId: fixture.panelId + ) + + #expect(fixture.store.notifications.isEmpty) + #expect(!fixture.store.hasUnreadNotification( + forTabId: fixture.destination.id, + surfaceId: fixture.panelId + )) + } + +} diff --git a/cmuxTests/AgentNotificationMutationBoundaryTests.swift b/cmuxTests/AgentNotificationMutationBoundaryTests.swift new file mode 100644 index 000000000000..7a4d5c1f6bd5 --- /dev/null +++ b/cmuxTests/AgentNotificationMutationBoundaryTests.swift @@ -0,0 +1,382 @@ +import CmuxControlSocket +import CmuxCore +import Darwin +import Foundation +import Testing +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +extension AgentNotificationRegressionTests { + // Generous for loaded CI runners: subprocess spawn, signal propagation, + // and marker writes can take multiple seconds there. A long timeout only + // slows the failure path. + func waitForMarker(at url: URL, timeout: Duration = .seconds(15)) async -> Bool { + let deadline = ContinuousClock.now + timeout + while !FileManager.default.fileExists(atPath: url.path), ContinuousClock.now < deadline { + try? await Task.sleep(for: .milliseconds(10)) + } + return FileManager.default.fileExists(atPath: url.path) + } + + @Test("PID routing bypasses a stale negative telemetry cache after exec") + func pidResolutionBypassesStaleNegativeTelemetryCacheAfterExec() async throws { + let fixture = try makeFixture() + defer { fixture.restore() } + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "cmux-live-pid-exec-\(UUID().uuidString)", + isDirectory: true + ) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let initialScript = root.appendingPathComponent("initial.sh") + let scopedScript = root.appendingPathComponent("scoped.sh") + let readyMarker = root.appendingPathComponent("ready") + let execMarker = root.appendingPathComponent("execed") + try """ + touch '\(readyMarker.path)' + trap 'exec /bin/sh "\(scopedScript.path)"' USR1 + while :; do sleep 1; done + """.write(to: initialScript, atomically: true, encoding: .utf8) + try """ + export CMUX_SURFACE_ID='\(fixture.panelId.uuidString)' + exec /bin/sh -c 'touch "\(execMarker.path)"; exec sleep 30' + """.write(to: scopedScript, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/sh") + process.arguments = [initialScript.path] + var environment = ProcessInfo.processInfo.environment + ["CMUX_WORKSPACE_ID", "CMUX_TAB_ID", "CMUX_SURFACE_ID", "CMUX_PANEL_ID"].forEach { + environment.removeValue(forKey: $0) + } + process.environment = environment + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + try process.run() + defer { + if process.isRunning { + _ = Darwin.kill(process.processIdentifier, SIGKILL) + process.waitUntilExit() + } + try? FileManager.default.removeItem(at: root) + } + #expect(await waitForMarker(at: readyMarker)) + + let identity = try #require(agentLiveProcessIdentity(pid: process.processIdentifier)) + let cachedMiss = CmuxTopProcessSnapshot.cachedCMUXScope( + for: Int(process.processIdentifier), + cacheKey: identity.scopeCacheKey, + nowNanoseconds: DispatchTime.now().uptimeNanoseconds + ) + #expect(cachedMiss == nil) + #expect(Darwin.kill(process.processIdentifier, SIGUSR1) == 0) + #expect(await waitForMarker(at: execMarker)) + + #expect( + fixture.appDelegate.liveAgentDeliveryTarget(forAgentPID: process.processIdentifier) + == AgentDeliveryTargetCandidate( + workspaceId: fixture.source.id, + surfaceId: fixture.panelId + ) + ) + } + + @Test("Local PID routing excludes remote TTY device namespaces") + func localTTYBindingsExcludeRemoteDeviceNamespaces() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + workspace.surfaceTTYNames[panelId] = "/dev/null" + #expect(workspace.localAgentDeliveryTTYDevices.map(\.surfaceId) == [panelId]) + + workspace.remoteConfiguration = WorkspaceRemoteConfiguration( + destination: "example.invalid", + port: nil, + identityFile: nil, + sshOptions: [], + localProxyPort: nil, + relayPort: nil, + relayID: nil, + relayToken: nil, + localSocketPath: nil, + terminalStartupCommand: nil + ) + #expect(workspace.localAgentDeliveryTTYDevices.isEmpty) + } + + @Test("A stale source clear preserves a destination-confined stored notification") + func staleSourceClearPreservesDestinationConfinedStoredNotification() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + try movePanel(fixture) + + fixture.store.addNotification( + tabId: fixture.destination.id, + surfaceId: fixture.panelId, + title: "Relay", + subtitle: "Completed", + body: "Authorized only for destination", + retargetsToLiveSurfaceOwner: false + ) + + fixture.store.clearNotifications( + forTabId: fixture.source.id, + surfaceId: fixture.panelId + ) + + let recorded = fixture.store.notifications.filter { + $0.body == "Authorized only for destination" + } + #expect(recorded.map(\.tabId) == [fixture.destination.id]) + #expect(recorded.first?.surfaceId == fixture.panelId) + #expect(recorded.first?.retargetsToLiveSurfaceOwner == false) + } + + @Test("A queued workspace clear lets a moved surface notification drain first") + func queuedWorkspaceClearPreservesNotificationMovedToAnotherWorkspace() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + let bus = TerminalMutationBus.shared + bus.discardPendingNotifications() + bus.setDrainsSuspendedForTesting(true) + defer { + bus.setDrainsSuspendedForTesting(false) + bus.discardPendingNotifications() + } + + bus.enqueueNotification( + tabId: fixture.source.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Queued before move and clear" + ) + try movePanel(fixture) + bus.enqueueClearNotifications(forTabId: fixture.source.id) + + bus.setDrainsSuspendedForTesting(false) + bus.drainForTesting() + + let recorded = fixture.store.notifications.filter { + $0.body == "Queued before move and clear" + } + #expect(recorded.map(\.tabId) == [fixture.destination.id]) + #expect(recorded.first?.surfaceId == fixture.panelId) + } + + @Test("A queued clear preserves policy work registered after its barrier") + func queuedClearPreservesNewerInFlightPolicyDelivery() async throws { + let fixture = try makeFixture(policyHookCommand: "cat") + defer { fixture.restore() } + let bus = TerminalMutationBus.shared + bus.discardPendingNotifications() + bus.setDrainsSuspendedForTesting(true) + defer { + bus.setDrainsSuspendedForTesting(false) + bus.discardPendingNotifications() + } + + bus.enqueueClearNotifications( + forTabId: fixture.source.id, + surfaceId: fixture.panelId + ) + fixture.store.addNotification( + tabId: fixture.source.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Registered after clear" + ) + + bus.setDrainsSuspendedForTesting(false) + bus.drainForTesting() + await waitForNotification(in: fixture.store) + + #expect(fixture.store.notifications.map(\.body) == ["Registered after clear"]) + } + + @Test("Clearing policy work immediately releases its cooldown reservation") + func clearReleasesInFlightPolicyCooldownForReplacement() async throws { + let fixture = try makeFixture(policyHookCommand: "sleep 1; cat") + defer { fixture.restore() } + let cooldownKey = "replace-after-clear-\(UUID().uuidString)" + + fixture.store.addNotification( + tabId: fixture.source.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Discarded in flight", + cooldownKey: cooldownKey, + cooldownInterval: 60 + ) + fixture.store.clearNotifications( + forTabId: fixture.source.id, + surfaceId: fixture.panelId + ) + fixture.store.addNotification( + tabId: fixture.source.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Replacement after clear", + cooldownKey: cooldownKey, + cooldownInterval: 60 + ) + + await waitForNotification(in: fixture.store) + #expect(fixture.store.notifications.map(\.body) == ["Replacement after clear"]) + } + + @Test("Clearing policy work discards a hook result that completes afterwards") + func clearTerminatesInFlightPolicyHookProcess() async throws { + // Subprocess termination on cancellation is best-effort and is NOT + // asserted: signal delivery through the xctest harness is not + // reliable on CI runners. The guaranteed, user-visible contract is + // that a cleared in-flight request's result is discarded — the hook + // here is gated on a marker so it completes strictly AFTER the clear, + // and its late result must not record a notification or unread ring. + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "cmux-policy-cancel-\(UUID().uuidString)", + isDirectory: true + ) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let pidURL = root.appendingPathComponent("pid") + let proceedURL = root.appendingPathComponent("proceed") + let command = "printf '%s' $$ > '\(pidURL.path)'; while [ ! -e '\(proceedURL.path)' ]; do sleep 0.1; done; cat" + let fixture = try makeFixture( + policyHookCommand: command, + policyHookTimeoutSeconds: 60 + ) + defer { + fixture.restore() + if let rawPID = try? String(contentsOf: pidURL, encoding: .utf8), + let pid = pid_t(rawPID.trimmingCharacters(in: .whitespacesAndNewlines)) { + _ = Darwin.kill(-pid, SIGKILL) + _ = Darwin.kill(pid, SIGKILL) + } + try? FileManager.default.removeItem(at: root) + } + + fixture.store.addNotification( + tabId: fixture.source.id, + surfaceId: fixture.panelId, + title: "Claude Code", + subtitle: "Completed", + body: "Cancel this hook" + ) + #expect(await waitForMarker(at: pidURL)) + + fixture.store.clearNotifications( + forTabId: fixture.source.id, + surfaceId: fixture.panelId + ) + FileManager.default.createFile(atPath: proceedURL.path, contents: nil) + + // Wait for the hook subprocess to finish (it exits promptly once the + // proceed marker exists, or immediately if cancellation did + // terminate it), then give the completion path time to run. + if let rawPID = try? String(contentsOf: pidURL, encoding: .utf8), + let pid = pid_t(rawPID.trimmingCharacters(in: .whitespacesAndNewlines)) { + let deadline = ContinuousClock.now + .seconds(15) + while Darwin.kill(pid, 0) == 0, ContinuousClock.now < deadline { + try? await Task.sleep(for: .milliseconds(20)) + } + } + try? await Task.sleep(for: .milliseconds(300)) + for _ in 0..<100 { await Task.yield() } + + #expect( + fixture.store.notifications.isEmpty, + "A cleared in-flight request's late hook result must be discarded" + ) + #expect( + !fixture.store.hasUnreadNotification(forTabId: fixture.source.id, surfaceId: fixture.panelId) + ) + } + + @Test("Agent runtime mutations follow a pane that moves before queue drain") + func queuedAgentRuntimeMutationsResolveLivePanelOwner() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + let bus = TerminalMutationBus.shared + bus.discardPendingNotifications() + bus.setDrainsSuspendedForTesting(true) + defer { + bus.setDrainsSuspendedForTesting(false) + bus.discardPendingNotifications() + } + + TerminalController.shared.controlSidebarScheduleStatusUpsert( + target: .workspace(fixture.source.id), + key: "claude_code", + value: "Running", + icon: "bolt.fill", + color: "#4C8DFF", + url: nil, + priority: 0, + format: .plain, + panelID: fixture.panelId, + pid: 43_210 + ) + TerminalController.shared.controlSidebarScheduleAgentLifecycle( + target: .workspace(fixture.source.id), + key: "claude_code", + lifecycleRawValue: AgentHibernationLifecycleState.running.rawValue, + panelID: fixture.panelId + ) + + try movePanel(fixture) + bus.setDrainsSuspendedForTesting(false) + bus.drainForTesting() + + #expect(fixture.source.statusEntries["claude_code"] == nil) + #expect(fixture.destination.statusEntries["claude_code"]?.value == "Running") + #expect(fixture.destination.agentPIDs["claude_code"] == 43_210) + #expect( + fixture.destination.agentLifecycleStatesByPanelId[fixture.panelId]?["claude_code"] == .running + ) + } + + @Test("An authorized-workspace clear cancels a confined in-flight relay delivery") + func authorizedWorkspaceClearCancelsConfinedInFlightRelayDelivery() async throws { + let fixture = try makeFixture(policyHookCommand: "cat") + defer { fixture.restore() } + + let routing = ControlRoutingSelectors( + hasWindowIDParam: false, + windowID: nil, + groupID: nil, + workspaceID: fixture.source.id, + surfaceID: nil, + paneID: nil + ) + let result = TerminalController.shared.controlNotificationCreateForTarget( + routing: routing, + workspaceID: fixture.source.id, + surfaceID: fixture.panelId, + title: "Relay", + subtitle: "Completed", + body: "Must be cancelled by its authorized workspace clear" + ) + guard case .delivered = result else { + Issue.record("Expected relay-target delivery, got \(result)") + return + } + + try movePanel(fixture) + // A confined request does not follow its surface — its delivery + // identity stays the authorized workspace — so clearing that + // workspace tab-wide must cancel it even though the request carries + // a surfaceId. + fixture.store.clearNotifications(forTabId: fixture.source.id) + + for _ in 0..<200 { await Task.yield() } + let recorded = fixture.store.notifications.filter { $0.title == "Relay" } + #expect( + recorded.isEmpty, + "A confined in-flight delivery must be cancelled by clearing its authorized workspace; saw \(recorded.map(\.tabId))" + ) + } +} diff --git a/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift b/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift index d0017b4eec63..95317b10ec9d 100644 --- a/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift +++ b/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift @@ -21,8 +21,8 @@ final class CLINotifyProcessIntegrationRegressionTests: XCTestCase { XCTAssertEqual(result.status, 0, result.stderr) XCTAssertEqual(result.stdout, "OK\n") XCTAssertTrue( - context.state.commands.contains { $0 == "clear_notifications --tab=\(context.workspaceId)" }, - "Expected clear SessionStart to clear stale notifications, saw \(context.state.commands)" + context.state.commands.contains { $0 == "clear_notifications --tab=\(context.workspaceId) --panel=\(context.surfaceId)" }, + "Expected clear SessionStart to clear only the current pane, saw \(context.state.commands)" ) XCTAssertTrue( context.state.commands.contains { diff --git a/cmuxTests/ClaudeHookLifecycleCleanupTests.swift b/cmuxTests/ClaudeHookLifecycleCleanupTests.swift new file mode 100644 index 000000000000..99dbae9ea5a4 --- /dev/null +++ b/cmuxTests/ClaudeHookLifecycleCleanupTests.swift @@ -0,0 +1,442 @@ +import Foundation +import Testing + +/// Regression tests for https://github.com/manaflow-ai/cmux/issues/7939: +/// lifecycle-cleanup Claude hooks (SessionEnd, per-tool PreToolUse) must +/// mutate the pane that owns the agent NOW — resolved from live identity at +/// hook time — never a stale or polluted persisted session address. Split +/// from `ClaudeHookLiveDeliveryTargetTests.swift` for the 500-line budget. +@Suite(.serialized) +struct ClaudeHookLifecycleCleanupTests { + private typealias Harness = ClaudeHookLiveDeliveryHarness + + private static let liveWorkspaceId = "11111111-1111-1111-1111-111111111111" + private static let liveSurfaceId = "22222222-2222-2222-2222-222222222222" + private static let otherSurfaceId = "55555555-5555-5555-5555-555555555555" + private static let fallbackSurfaceId = "44444444-4444-4444-4444-444444444444" + + /// The session record was polluted to ANOTHER agent's pane (#7391) whose + /// own session is active there. SessionEnd's staleness gate must judge the + /// pane being CLEANED (the live pid target), not the polluted record + /// surface — otherwise the foreign active session makes the hook look + /// stale and the real pane keeps its ring/status after exit. + @Test func sessionEndPollutedRecordStillClearsLivePane() throws { + let context = try Harness.makeContext(name: "session-end-polluted-record") + defer { context.cleanup() } + let sessionId = "session-end-polluted-record-session" + + let now = Date().timeIntervalSince1970 + let store: [String: Any] = [ + "version": 1, + "sessions": [ + sessionId: [ + "sessionId": sessionId, + "workspaceId": Self.liveWorkspaceId, + "surfaceId": Self.otherSurfaceId, + "cwd": context.root.path, + "isRestorable": true, + "startedAt": now, + "updatedAt": now, + ], + ], + "activeSessionsBySurface": [ + Self.otherSurfaceId: [ + "sessionId": "foreign-agent-session", + "updatedAt": now, + ], + ], + ] + try JSONSerialization.data(withJSONObject: store, options: [.prettyPrinted, .sortedKeys]) + .write(to: context.storeURL) + + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [Self.liveWorkspaceId: [Self.liveSurfaceId, Self.otherSurfaceId]], + pidTarget: (workspaceId: Self.liveWorkspaceId, surfaceId: Self.liveSurfaceId) + ) + + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + environment["CMUX_CLAUDE_PID"] = "43218" + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "session-end"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"SessionEnd","cwd":"\#(context.root.path)"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + + let commands = context.state.snapshot() + #expect( + commands.contains { + $0.hasPrefix("clear_agent_pid claude_code ") + && $0.contains("--tab=\(Self.liveWorkspaceId)") + && $0.contains("--panel=\(Self.liveSurfaceId)") + }, + "SessionEnd must clear the live pane despite the polluted record surface; saw \(commands)" + ) + #expect( + !commands.contains { $0.hasPrefix("clear_agent_pid claude_code ") && $0.contains("--panel=\(Self.otherSurfaceId)") }, + "SessionEnd must not clear the foreign pane the polluted record named; saw \(commands)" + ) + #expect( + commands.contains("clear_notifications --tab=\(Self.liveWorkspaceId) --panel=\(Self.liveSurfaceId)"), + "A same-workspace live retarget must clear only the real pane; saw \(commands)" + ) + #expect( + !commands.contains("clear_notifications --tab=\(Self.liveWorkspaceId)"), + "A polluted record must not make SessionEnd clear sibling panes; saw \(commands)" + ) + } + + /// SessionEnd is the only hook after a pane move (Ctrl-C exit): its + /// cleanup must clear status and notifications on the workspace that owns + /// the pane NOW, not the consumed record's stale workspace — clearing the + /// old workspace would leave the moved pane stuck and wipe unrelated + /// panes' notifications there. + @Test func sessionEndCleanupFollowsMovedPane() throws { + let context = try Harness.makeContext(name: "session-end-moved-pane") + defer { context.cleanup() } + let sessionId = "session-end-moved-pane-session" + let newWorkspaceId = "88888888-8888-8888-8888-888888888888" + + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.liveWorkspaceId, + surfaceId: Self.liveSurfaceId, + cwd: context.root.path + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [ + Self.liveWorkspaceId: [Self.fallbackSurfaceId], + newWorkspaceId: [Self.liveSurfaceId], + ], + pidTarget: nil, + surfaceTargets: [Self.liveSurfaceId: newWorkspaceId] + ) + + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + environment["CMUX_CLAUDE_PID"] = "43215" + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "session-end"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"SessionEnd","cwd":"\#(context.root.path)"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + + let commands = context.state.snapshot() + #expect( + commands.contains { + $0.hasPrefix("clear_agent_pid claude_code ") + && $0.contains("--tab=\(newWorkspaceId)") + && $0.contains("--panel=\(Self.liveSurfaceId)") + }, + "SessionEnd must clear agent pid/status on the pane's current workspace; saw \(commands)" + ) + #expect( + commands.contains("clear_notifications --tab=\(newWorkspaceId) --panel=\(Self.liveSurfaceId)"), + "A re-homed SessionEnd clear must be scoped to the moved pane, not wipe sibling panes in the destination workspace; saw \(commands)" + ) + #expect( + !commands.contains("clear_notifications --tab=\(newWorkspaceId)"), + "A re-homed SessionEnd must not clear the whole destination workspace; saw \(commands)" + ) + #expect( + !commands.contains { $0.hasPrefix("clear_notifications --tab=\(Self.liveWorkspaceId)") }, + "SessionEnd must not wipe the stale workspace's notifications; saw \(commands)" + ) + } + + @Test func sessionEndClearStaysPaneScopedAfterRecordIsHealed() throws { + let context = try Harness.makeContext(name: "session-end-healed-target") + defer { context.cleanup() } + let sessionId = "session-end-healed-target-session" + + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.liveWorkspaceId, + surfaceId: Self.liveSurfaceId, + cwd: context.root.path + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [Self.liveWorkspaceId: [Self.liveSurfaceId, Self.otherSurfaceId]], + pidTarget: (workspaceId: Self.liveWorkspaceId, surfaceId: Self.liveSurfaceId) + ) + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + environment["CMUX_CLAUDE_PID"] = "43305" + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "session-end"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"SessionEnd","cwd":"\#(context.root.path)"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + let commands = context.state.snapshot() + #expect(commands.contains("clear_notifications --tab=\(Self.liveWorkspaceId) --panel=\(Self.liveSurfaceId)")) + #expect(!commands.contains("clear_notifications --tab=\(Self.liveWorkspaceId)")) + } + + @Test func promptSubmitClearFollowsMovedPaneWithoutClearingSiblings() throws { + let context = try Harness.makeContext(name: "prompt-submit-pane-clear") + defer { context.cleanup() } + let sessionId = "prompt-submit-pane-clear-session" + let newWorkspaceId = "77777777-7777-7777-7777-777777777777" + + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.liveWorkspaceId, + surfaceId: Self.liveSurfaceId, + cwd: context.root.path + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [newWorkspaceId: [Self.liveSurfaceId, Self.otherSurfaceId]], + pidTarget: (workspaceId: newWorkspaceId, surfaceId: Self.liveSurfaceId) + ) + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + environment["CMUX_CLAUDE_PID"] = "43306" + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "prompt-submit"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","turn_id":"turn-1","hook_event_name":"UserPromptSubmit","cwd":"\#(context.root.path)"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + let commands = context.state.snapshot() + #expect(commands.contains("clear_notifications --tab=\(newWorkspaceId) --panel=\(Self.liveSurfaceId)")) + #expect(!commands.contains("clear_notifications --tab=\(newWorkspaceId)")) + } + + /// A pane moves mid-turn: the next PreToolUse (which skips the pid/tty + /// scan for frequency) must still re-home via the cheap `{surface_id}` + /// probe instead of mutating — and re-recording via upsert — the old + /// workspace's focused pane. + @Test func preToolUseFollowsMovedPaneWithoutPidProbe() throws { + let context = try Harness.makeContext(name: "pre-tool-use-rehome") + defer { context.cleanup() } + let sessionId = "pre-tool-use-rehome-session" + let newWorkspaceId = "99999999-9999-9999-9999-999999999999" + + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.liveWorkspaceId, + surfaceId: Self.liveSurfaceId, + cwd: context.root.path + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [ + Self.liveWorkspaceId: [Self.fallbackSurfaceId], + newWorkspaceId: [Self.liveSurfaceId, Self.otherSurfaceId], + ], + pidTarget: nil, + surfaceTargets: [Self.liveSurfaceId: newWorkspaceId] + ) + + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + environment["CMUX_CLAUDE_PID"] = "43216" + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "pre-tool-use"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"PreToolUse","tool_name":"Bash","cwd":"\#(context.root.path)"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + + let commands = context.state.snapshot() + #expect( + commands.contains { + $0.hasPrefix("set_status claude_code Running ") + && $0.contains("--tab=\(newWorkspaceId)") + && $0.contains("--panel=\(Self.liveSurfaceId)") + }, + "PreToolUse status must follow the moved pane; saw \(commands)" + ) + #expect( + !commands.contains { $0.contains("--panel=\(Self.fallbackSurfaceId)") }, + "PreToolUse must not mutate the old workspace's focused pane; saw \(commands)" + ) + #expect(commands.contains("clear_notifications --tab=\(newWorkspaceId) --panel=\(Self.liveSurfaceId)")) + #expect(!commands.contains("clear_notifications --tab=\(newWorkspaceId)")) + let record = try Harness.sessionRecord(in: context.storeURL, sessionId: sessionId) + #expect(record?["workspaceId"] as? String == newWorkspaceId, "Session record must re-home, not re-pollute") + #expect(record?["surfaceId"] as? String == Self.liveSurfaceId) + } + + /// Older apps do not implement the live delivery-target resolver. A + /// high-frequency PreToolUse hook must retain the legacy validated + /// session/workspace/surface chain instead of treating the missing method + /// as an identity rejection and silently dropping the lifecycle update. + @Test func preToolUseWithoutResolverMethodKeepsLegacyRouting() throws { + let context = try Harness.makeContext(name: "pre-tool-use-legacy-fallback") + defer { context.cleanup() } + let sessionId = "pre-tool-use-legacy-fallback-session" + + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.liveWorkspaceId, + surfaceId: Self.liveSurfaceId, + cwd: context.root.path + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [Self.liveWorkspaceId: [Self.liveSurfaceId]], + pidTarget: nil, + resolverMethodAvailable: false + ) + + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + environment["CMUX_CLAUDE_PID"] = "43304" + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "pre-tool-use"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"PreToolUse","tool_name":"Bash","cwd":"\#(context.root.path)"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + + let commands = context.state.snapshot() + #expect( + commands.contains { + $0.hasPrefix("set_status claude_code Running ") + && $0.contains("--tab=\(Self.liveWorkspaceId)") + && $0.contains("--panel=\(Self.liveSurfaceId)") + }, + "PreToolUse must keep legacy routing when the resolver method is unavailable; saw \(commands)" + ) + } + + /// The persisted session surface is stale/closed but the resolver + /// recovers an authoritative live target from the spawn-time env surface: + /// the blocking needs-input branch (AskUserQuestion) must use the + /// resolved surface for its upsert, lifecycle, and notification — not + /// re-prefer the stale record surface and pin the prompt on a dead pane. + @Test func preToolUseNeedsInputUsesAuthoritativeResolvedSurface() throws { + let context = try Harness.makeContext(name: "needs-input-live-surface") + defer { context.cleanup() } + let sessionId = "needs-input-live-surface-session" + let closedSurfaceId = "66666666-6666-6666-6666-666666666666" + + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.liveWorkspaceId, + surfaceId: closedSurfaceId, + cwd: context.root.path + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [Self.liveWorkspaceId: [Self.fallbackSurfaceId]], + pidTarget: nil, + surfaceTargets: [Self.liveSurfaceId: Self.liveWorkspaceId] + ) + + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + environment["CMUX_CLAUDE_PID"] = "43217" + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "pre-tool-use"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"PreToolUse","tool_name":"AskUserQuestion","permission_mode":"bypassPermissions","cwd":"\#(context.root.path)"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + + let commands = context.state.snapshot() + #expect( + commands.contains { + $0.hasPrefix("notify_target_async \(Self.liveWorkspaceId) \(Self.liveSurfaceId) ") + }, + "Needs-input notification must target the authoritative resolved surface; saw \(commands)" + ) + #expect( + !commands.contains { $0.contains(closedSurfaceId) }, + "No mutation may target the stale/closed record surface; saw \(commands)" + ) + let record = try Harness.sessionRecord(in: context.storeURL, sessionId: sessionId) + #expect( + record?["surfaceId"] as? String == Self.liveSurfaceId, + "Upsert must heal the record to the resolved surface, not re-pollute it" + ) + } + + @Test func preToolUseRejectsPollutedLiveRecord() throws { + let context = try Harness.makeContext(name: "pre-tool-use-polluted-live-record") + defer { context.cleanup() } + let sessionId = "pre-tool-use-polluted-live-record-session" + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.liveWorkspaceId, + surfaceId: Self.otherSurfaceId, + cwd: context.root.path + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [Self.liveWorkspaceId: [Self.liveSurfaceId, Self.otherSurfaceId]], + pidTarget: nil, + surfaceTargets: [Self.liveSurfaceId: Self.liveWorkspaceId] + ) + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + environment["CMUX_CLAUDE_PID"] = "43303" + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "pre-tool-use"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"PreToolUse","tool_name":"Bash","cwd":"\#(context.root.path)"}"# + ) + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + let commands = context.state.snapshot() + #expect(!commands.contains { $0.hasPrefix("set_status ") || $0.hasPrefix("clear_notifications ") }) + } + + private func assertSuccessfulHook(_ result: ClaudeHookLiveDeliveryHarness.ProcessRunResult) { + #expect(!result.timedOut, Comment(rawValue: result.stderr)) + #expect(result.status == 0, Comment(rawValue: result.stderr)) + #expect(result.stdout == "{}\n") + } +} diff --git a/cmuxTests/ClaudeHookLiveDeliveryTargetTestSupport.swift b/cmuxTests/ClaudeHookLiveDeliveryTargetTestSupport.swift new file mode 100644 index 000000000000..6e31e05934aa --- /dev/null +++ b/cmuxTests/ClaudeHookLiveDeliveryTargetTestSupport.swift @@ -0,0 +1,349 @@ +import Darwin +import Dispatch +import Foundation + +/// Shared harness for the issue-7939 live delivery-target CLI regression +/// tests: a mock cmux control server that can answer (or refuse) the +/// `agent.resolve_delivery_target` probes, plus process/session-store +/// helpers. Kept out of the test suite file for the 500-line file budget. +enum ClaudeHookLiveDeliveryHarness { + struct Context { + let cliPath: String + let socketPath: String + let listenerFD: Int32 + let state: ServerState + let root: URL + let storeURL: URL + + func cleanup() { + Darwin.close(listenerFD) + unlink(socketPath) + try? FileManager.default.removeItem(at: root) + } + } + + final class ServerState: @unchecked Sendable { + private let lock = NSLock() + private var commands: [String] = [] + + func append(_ command: String) { + lock.lock() + commands.append(command) + lock.unlock() + } + + func snapshot() -> [String] { + lock.lock() + let value = commands + lock.unlock() + return value + } + } + + struct ProcessRunResult { + let status: Int32 + let stdout: String + let stderr: String + let timedOut: Bool + } + + static func makeContext(name: String) throws -> Context { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-\(name)-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let shortID = UUID().uuidString.replacingOccurrences(of: "-", with: "").prefix(8) + let socketPath = URL(fileURLWithPath: NSTemporaryDirectory()) + .appendingPathComponent("cli-\(name.prefix(6))-\(shortID).sock") + .path + return Context( + cliPath: try BundledCLITestSupport.bundledCLIPath(for: BundledCLILinkageTests.self), + socketPath: socketPath, + listenerFD: try bindUnixSocket(at: socketPath), + state: ServerState(), + root: root, + storeURL: root.appendingPathComponent("claude-hook-sessions.json") + ) + } + + static func hookEnvironment(context: Context) -> [String: String] { + [ + "HOME": context.root.path, + "PATH": "/usr/bin:/bin:/usr/sbin:/sbin", + "CMUX_SOCKET_PATH": context.socketPath, + "CMUX_CLAUDE_HOOK_STATE_PATH": context.storeURL.path, + "CMUX_CLI_SENTRY_DISABLED": "1", + "CMUX_CLAUDE_HOOK_SENTRY_DISABLED": "1", + ] + } + + /// Mock control server. `pidTarget` answers the `{pid}` probe; + /// `surfaceTargets` answers `{surface_id}` re-home probes; + /// `resolverMethodAvailable: false` simulates an older app. + static func startDeliveryTargetServer( + context: Context, + surfacesByWorkspace: [String: [String]], + pidTarget: (workspaceId: String, surfaceId: String)?, + surfaceTargets: [String: String] = [:], + ttyRows: [(tty: String, workspaceId: String, surfaceId: String)] = [], + resolverMethodAvailable: Bool = true + ) -> DispatchSemaphore { + startMockServer(listenerFD: context.listenerFD, state: context.state) { line in + guard let payload = jsonObject(line), + let id = payload["id"] as? String, + let method = payload["method"] as? String else { + return "OK" + } + let params = payload["params"] as? [String: Any] ?? [:] + switch method { + case "agent.resolve_delivery_target": + guard resolverMethodAvailable else { + return v2Response(id: id, ok: false, error: ["code": "unrecognized_method", "message": "unknown method"]) + } + if params["pid"] != nil { + guard let pidTarget else { + return v2Response(id: id, ok: false, error: ["code": "not_found", "message": "pid not owned by a live surface"]) + } + return v2Response(id: id, ok: true, result: [ + "workspace_id": pidTarget.workspaceId, + "surface_id": pidTarget.surfaceId, + "source": "pid", + ]) + } + if let surfaceId = params["surface_id"] as? String, + let workspaceId = surfaceTargets[surfaceId] { + return v2Response(id: id, ok: true, result: [ + "workspace_id": workspaceId, + "surface_id": surfaceId, + "source": "surface", + ]) + } + return v2Response(id: id, ok: false, error: ["code": "not_found", "message": "no live target"]) + case "surface.list": + guard let workspaceId = params["workspace_id"] as? String, + let surfaceIds = surfacesByWorkspace[workspaceId] else { + return v2Response(id: id, ok: false, error: ["code": "not_found", "message": "workspace not found"]) + } + let surfaces: [[String: Any]] = surfaceIds.enumerated().map { index, surfaceId in + ["id": surfaceId, "ref": "surface:\(index + 1)", "focused": index == 0] + } + return v2Response(id: id, ok: true, result: ["surfaces": surfaces]) + case "debug.terminals": + let terminals: [[String: Any]] = ttyRows.map { + ["tty": $0.tty, "workspace_id": $0.workspaceId, "surface_id": $0.surfaceId] + } + return v2Response(id: id, ok: true, result: ["terminals": terminals]) + case "feed.push": + return v2Response(id: id, ok: true, result: [:]) + case "surface.resume.set": + return v2Response(id: id, ok: true, result: ["resume_binding": [:]]) + default: + return v2Response(id: id, ok: false, error: ["code": "unrecognized_method", "message": "unexpected method: \(method)"]) + } + } + } + + static func resumeBindingParams(in context: Context) -> [[String: Any]] { + context.state.snapshot().compactMap { command -> [String: Any]? in + guard let payload = jsonObject(command), + payload["method"] as? String == "surface.resume.set" else { + return nil + } + return payload["params"] as? [String: Any] + } + } + + static func writeSessionStore( + to storeURL: URL, + sessionId: String, + workspaceId: String, + surfaceId: String, + cwd: String, + pid: Int? = nil + ) throws { + let now = Date().timeIntervalSince1970 + var record: [String: Any] = [ + "sessionId": sessionId, + "workspaceId": workspaceId, + "surfaceId": surfaceId, + "cwd": cwd, + "isRestorable": true, + "startedAt": now, + "updatedAt": now, + ] + if let pid { record["pid"] = pid } + let store: [String: Any] = [ + "version": 1, + "sessions": [sessionId: record], + ] + let data = try JSONSerialization.data(withJSONObject: store, options: [.prettyPrinted, .sortedKeys]) + try data.write(to: storeURL) + } + + static func sessionRecord(in storeURL: URL, sessionId: String) throws -> [String: Any]? { + let saved = try JSONSerialization.jsonObject(with: Data(contentsOf: storeURL)) as? [String: Any] + let sessions = saved?["sessions"] as? [String: Any] + return sessions?[sessionId] as? [String: Any] + } + + static func runHookProcess( + context: Context, + arguments: [String], + environment: [String: String], + standardInput: String + ) -> ProcessRunResult { + let process = Process() + let stdoutPipe = Pipe() + let stderrPipe = Pipe() + let stdinPipe = Pipe() + process.executableURL = URL(fileURLWithPath: context.cliPath) + process.arguments = arguments + process.environment = environment + process.standardInput = stdinPipe + process.standardOutput = stdoutPipe + process.standardError = stderrPipe + + do { + try process.run() + } catch { + return ProcessRunResult(status: -1, stdout: "", stderr: String(describing: error), timedOut: false) + } + stdinPipe.fileHandleForWriting.write(Data(standardInput.utf8)) + try? stdinPipe.fileHandleForWriting.close() + + let exitSignal = DispatchSemaphore(value: 0) + DispatchQueue.global(qos: .userInitiated).async { + process.waitUntilExit() + exitSignal.signal() + } + let timedOut = exitSignal.wait(timeout: .now() + 10) == .timedOut + if timedOut { + process.terminate() + if exitSignal.wait(timeout: .now() + 1) == .timedOut { + kill(process.processIdentifier, SIGKILL) + _ = exitSignal.wait(timeout: .now() + 1) + } + } + + let stdout = String(data: stdoutPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" + let stderr = String(data: stderrPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" + return ProcessRunResult( + status: process.isRunning ? SIGKILL : process.terminationStatus, + stdout: stdout, + stderr: stderr, + timedOut: timedOut + ) + } + + private static func bindUnixSocket(at path: String) throws -> Int32 { + unlink(path) + let fd = Darwin.socket(AF_UNIX, SOCK_STREAM, 0) + guard fd >= 0 else { + throw NSError(domain: "cmux.tests", code: Int(errno)) + } + + var addr = sockaddr_un() + addr.sun_family = sa_family_t(AF_UNIX) + let maxPathLength = MemoryLayout.size(ofValue: addr.sun_path) + let utf8 = Array(path.utf8) + guard utf8.count < maxPathLength else { + Darwin.close(fd) + throw NSError(domain: "cmux.tests", code: Int(ENAMETOOLONG)) + } + _ = withUnsafeMutablePointer(to: &addr.sun_path) { pointer in + pointer.withMemoryRebound(to: CChar.self, capacity: maxPathLength) { buffer in + for index in 0...size)) + } + } + guard bindResult == 0, Darwin.listen(fd, 8) == 0 else { + let code = errno + Darwin.close(fd) + throw NSError(domain: "cmux.tests", code: Int(code)) + } + return fd + } + + private static func startMockServer( + listenerFD: Int32, + state: ServerState, + handler: @escaping @Sendable (String) -> String + ) -> DispatchSemaphore { + let handled = DispatchSemaphore(value: 0) + DispatchQueue.global(qos: .userInitiated).async { + while true { + var clientAddr = sockaddr_un() + var clientAddrLen = socklen_t(MemoryLayout.size) + let clientFD = withUnsafeMutablePointer(to: &clientAddr) { ptr in + ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockaddrPtr in + Darwin.accept(listenerFD, sockaddrPtr, &clientAddrLen) + } + } + guard clientFD >= 0 else { + if errno == EINTR { continue } + return + } + + DispatchQueue.global(qos: .userInitiated).async { + defer { + Darwin.close(clientFD) + handled.signal() + } + + func writeResponse(_ response: String) { + let line = response + "\n" + _ = line.withCString { ptr in + Darwin.write(clientFD, ptr, strlen(ptr)) + } + } + + var pending = Data() + var buffer = [UInt8](repeating: 0, count: 4096) + while true { + let count = Darwin.read(clientFD, &buffer, buffer.count) + if count < 0 { + if errno == EINTR { continue } + return + } + if count == 0 { return } + pending.append(buffer, count: count) + + while let newlineRange = pending.firstRange(of: Data([0x0A])) { + let lineData = pending.subdata(in: 0.. String { + var payload: [String: Any] = ["id": id, "ok": ok] + if let result { payload["result"] = result } + if let error { payload["error"] = error } + let data = try? JSONSerialization.data(withJSONObject: payload, options: []) + return String(data: data ?? Data("{}".utf8), encoding: .utf8) ?? "{}" + } + + private static func jsonObject(_ line: String) -> [String: Any]? { + guard let data = line.data(using: .utf8) else { return nil } + return try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] + } +} diff --git a/cmuxTests/ClaudeHookLiveDeliveryTargetTests.swift b/cmuxTests/ClaudeHookLiveDeliveryTargetTests.swift new file mode 100644 index 000000000000..e935930e8d16 --- /dev/null +++ b/cmuxTests/ClaudeHookLiveDeliveryTargetTests.swift @@ -0,0 +1,302 @@ +import Foundation +import Testing + +/// Regression tests for https://github.com/manaflow-ai/cmux/issues/7939: +/// a Claude turn-complete notification must land on the pane whose agent +/// finished, resolved from LIVE identity at delivery time — never from a +/// polluted session record, a stale `debug.terminals` tty row, or spawn-time +/// `CMUX_WORKSPACE_ID`/`CMUX_SURFACE_ID` env captured before a pane move. +/// +/// The CLI asks the app for the live target via the +/// `agent.resolve_delivery_target` control method: +/// - `{pid}` probe: which live surface owns the agent process right now. +/// - `{surface_id, workspace_id}` probe: which workspace currently hosts a +/// known surface (re-homes a moved pane, issue #5781). +/// When the method is unavailable (older app) the legacy resolution chain is +/// preserved unchanged. +@Suite(.serialized) +struct ClaudeHookLiveDeliveryTargetTests { + private typealias Harness = ClaudeHookLiveDeliveryHarness + + private static let liveWorkspaceId = "11111111-1111-1111-1111-111111111111" + private static let liveSurfaceId = "22222222-2222-2222-2222-222222222222" + private static let otherWorkspaceId = "33333333-3333-3333-3333-333333333333" + private static let otherSurfaceId = "55555555-5555-5555-5555-555555555555" + private static let fallbackSurfaceId = "44444444-4444-4444-4444-444444444444" + + /// Two Claude agents in two workspaces: the session record for this agent + /// was polluted to point at the OTHER agent's pane (issue #7391 drift). + /// The live pid target must win and the record must self-heal. + @Test func stopPrefersLivePidTargetOverPollutedSessionRecord() throws { + let context = try Harness.makeContext(name: "live-pid-wins") + defer { context.cleanup() } + let sessionId = "polluted-record-session" + + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.otherWorkspaceId, + surfaceId: Self.otherSurfaceId, + cwd: context.root.path + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [ + Self.liveWorkspaceId: [Self.liveSurfaceId], + Self.otherWorkspaceId: [Self.otherSurfaceId], + ], + pidTarget: (workspaceId: Self.liveWorkspaceId, surfaceId: Self.liveSurfaceId) + ) + + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.otherWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.otherSurfaceId + environment["CMUX_CLAUDE_PID"] = "43210" + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "stop"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"Stop","cwd":"\#(context.root.path)","last_assistant_message":"All done"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + + let commands = context.state.snapshot() + #expect( + commands.contains { $0.hasPrefix("notify_target_async \(Self.liveWorkspaceId) \(Self.liveSurfaceId) ") }, + "Turn-complete notification must target the live pane resolved from the agent pid; saw \(commands)" + ) + #expect( + !commands.contains { $0.hasPrefix("notify_target_async \(Self.otherWorkspaceId)") }, + "Notification must not follow the polluted session record to another workspace; saw \(commands)" + ) + #expect( + commands.contains { + $0.hasPrefix("set_status claude_code Idle ") + && $0.contains("--tab=\(Self.liveWorkspaceId)") + && $0.contains("--panel=\(Self.liveSurfaceId)") + }, + "Status pill must follow the live pane; saw \(commands)" + ) + let record = try Harness.sessionRecord(in: context.storeURL, sessionId: sessionId) + #expect(record?["workspaceId"] as? String == Self.liveWorkspaceId, "Session record workspace must self-heal") + #expect(record?["surfaceId"] as? String == Self.liveSurfaceId, "Session record surface must self-heal") + } + + /// Pane moved to another workspace after the session record was written + /// (issue #5781). Without a pid answer, the recorded surface must be + /// re-homed to its CURRENT workspace instead of falling back to the old + /// workspace's focused surface. + @Test func stopFollowsMovedPaneToCurrentWorkspace() throws { + let context = try Harness.makeContext(name: "moved-pane") + defer { context.cleanup() } + let sessionId = "moved-pane-session" + let newWorkspaceId = "77777777-7777-7777-7777-777777777777" + + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.liveWorkspaceId, + surfaceId: Self.liveSurfaceId, + cwd: context.root.path + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [ + Self.liveWorkspaceId: [Self.fallbackSurfaceId], + newWorkspaceId: [Self.liveSurfaceId], + ], + pidTarget: nil, + surfaceTargets: [Self.liveSurfaceId: newWorkspaceId] + ) + + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + environment["CMUX_CLAUDE_PID"] = "43211" + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "stop"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"Stop","cwd":"\#(context.root.path)","last_assistant_message":"All done"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + + let commands = context.state.snapshot() + #expect( + commands.contains { $0.hasPrefix("notify_target_async \(newWorkspaceId) \(Self.liveSurfaceId) ") }, + "Notification must follow the moved pane to its current workspace; saw \(commands)" + ) + #expect( + !commands.contains { $0.contains("notify_target_async \(Self.liveWorkspaceId) \(Self.fallbackSurfaceId)") }, + "Notification must not land on the old workspace's focused surface; saw \(commands)" + ) + let record = try Harness.sessionRecord(in: context.storeURL, sessionId: sessionId) + #expect(record?["workspaceId"] as? String == newWorkspaceId, "Session record must re-home to the pane's current workspace") + #expect(record?["surfaceId"] as? String == Self.liveSurfaceId) + } + + /// The workspace listing lags the app's panel map: the recorded surface is + /// not in the resolved workspace's listing, yet the app confirms the same + /// workspace still owns it. The identity surface must win over the + /// focused-surface fallback even when the re-homed workspace is unchanged. + @Test func stopPrefersRehomedIdentitySurfaceInSameWorkspace() throws { + let context = try Harness.makeContext(name: "same-workspace-rehome") + defer { context.cleanup() } + let sessionId = "same-workspace-rehome-session" + + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.liveWorkspaceId, + surfaceId: Self.liveSurfaceId, + cwd: context.root.path + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [Self.liveWorkspaceId: [Self.fallbackSurfaceId]], + pidTarget: nil, + surfaceTargets: [Self.liveSurfaceId: Self.liveWorkspaceId] + ) + + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + environment["CMUX_CLAUDE_PID"] = "43214" + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "stop"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"Stop","cwd":"\#(context.root.path)","last_assistant_message":"All done"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + + let commands = context.state.snapshot() + #expect( + commands.contains { $0.hasPrefix("notify_target_async \(Self.liveWorkspaceId) \(Self.liveSurfaceId) ") }, + "Notification must land on the identity surface confirmed by the app, not the focused-surface fallback; saw \(commands)" + ) + #expect( + !commands.contains { $0.contains("notify_target_async \(Self.liveWorkspaceId) \(Self.fallbackSurfaceId)") }, + "Notification must not land on the focused-surface fallback when the app confirms the identity surface; saw \(commands)" + ) + } + + /// SessionStart with a stale `debug.terminals` tty row pointing at another + /// agent's pane (issue #7391 genesis): the live pid target must win so the + /// session record is born correct. + @Test func sessionStartPrefersLivePidTargetOverStaleTTYRow() throws { + let context = try Harness.makeContext(name: "stale-tty") + defer { context.cleanup() } + let sessionId = "stale-tty-session" + let ttyName = "ttys-stale-row" + + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [ + Self.liveWorkspaceId: [Self.liveSurfaceId], + Self.otherWorkspaceId: [Self.otherSurfaceId], + ], + pidTarget: (workspaceId: Self.liveWorkspaceId, surfaceId: Self.liveSurfaceId), + ttyRows: [(tty: ttyName, workspaceId: Self.otherWorkspaceId, surfaceId: Self.otherSurfaceId)] + ) + + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + environment["CMUX_CLI_TTY_NAME"] = ttyName + environment["CMUX_CLAUDE_PID"] = "43212" + environment["CMUX_AGENT_LAUNCH_KIND"] = "claude" + environment["CMUX_AGENT_LAUNCH_EXECUTABLE"] = "/usr/local/bin/claude" + environment["CMUX_AGENT_LAUNCH_CWD"] = context.root.path + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "session-start"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","source":"clear","cwd":"\#(context.root.path)","hook_event_name":"SessionStart"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + + let commands = context.state.snapshot() + let resumeBinding = try #require( + Harness.resumeBindingParams(in: context).last, + "Expected SessionStart to publish a resume binding, saw \(commands)" + ) + #expect( + resumeBinding["surface_id"] as? String == Self.liveSurfaceId, + "Resume binding must target the pane that owns the live agent pid, not the stale tty row; params=\(resumeBinding)" + ) + #expect( + commands.contains { + $0.hasPrefix("set_status claude_code Running ") + && $0.contains("--tab=\(Self.liveWorkspaceId)") + && $0.contains("--panel=\(Self.liveSurfaceId)") + }, + "Visible status must target the live pane; saw \(commands)" + ) + let record = try Harness.sessionRecord(in: context.storeURL, sessionId: sessionId) + #expect(record?["workspaceId"] as? String == Self.liveWorkspaceId) + #expect(record?["surfaceId"] as? String == Self.liveSurfaceId) + } + + + /// Older app without `agent.resolve_delivery_target`: the legacy chain + /// (session record validated against live workspaces) keeps working. + @Test func stopWithoutResolverMethodKeepsLegacyRouting() throws { + let context = try Harness.makeContext(name: "legacy-fallback") + defer { context.cleanup() } + let sessionId = "legacy-session" + + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.liveWorkspaceId, + surfaceId: Self.liveSurfaceId, + cwd: context.root.path + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [Self.liveWorkspaceId: [Self.liveSurfaceId]], + pidTarget: nil, + resolverMethodAvailable: false + ) + + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + environment["CMUX_CLAUDE_PID"] = "43213" + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "stop"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"Stop","cwd":"\#(context.root.path)","last_assistant_message":"All done"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + + let commands = context.state.snapshot() + #expect( + commands.contains { $0.hasPrefix("notify_target_async \(Self.liveWorkspaceId) \(Self.liveSurfaceId) ") }, + "Legacy routing must keep working when the resolver method is unavailable; saw \(commands)" + ) + } + + private func assertSuccessfulHook(_ result: ClaudeHookLiveDeliveryHarness.ProcessRunResult) { + #expect(!result.timedOut, Comment(rawValue: result.stderr)) + #expect(result.status == 0, Comment(rawValue: result.stderr)) + #expect(result.stdout == "{}\n") + } +} diff --git a/cmuxTests/ClaudeHookPIDAuthenticationTests.swift b/cmuxTests/ClaudeHookPIDAuthenticationTests.swift new file mode 100644 index 000000000000..b11477c6ba73 --- /dev/null +++ b/cmuxTests/ClaudeHookPIDAuthenticationTests.swift @@ -0,0 +1,168 @@ +import Foundation +import Testing + +@Suite(.serialized) +struct ClaudeHookPIDAuthenticationTests { + private typealias Harness = ClaudeHookLiveDeliveryHarness + + private static let liveWorkspaceId = "11111111-1111-1111-1111-111111111111" + private static let liveSurfaceId = "22222222-2222-2222-2222-222222222222" + private static let otherWorkspaceId = "33333333-3333-3333-3333-333333333333" + private static let otherSurfaceId = "55555555-5555-5555-5555-555555555555" + + @Test("A persisted PID is never promoted to live identity") + func persistedPIDDoesNotOverrideCurrentHookIdentity() throws { + let context = try Harness.makeContext(name: "persisted-pid-not-authoritative") + defer { context.cleanup() } + let sessionId = "persisted-pid-session" + + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.liveWorkspaceId, + surfaceId: Self.liveSurfaceId, + cwd: context.root.path, + pid: 43299 + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [ + Self.liveWorkspaceId: [Self.liveSurfaceId], + Self.otherWorkspaceId: [Self.otherSurfaceId], + ], + pidTarget: (workspaceId: Self.otherWorkspaceId, surfaceId: Self.otherSurfaceId) + ) + + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "stop"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"Stop","cwd":"\#(context.root.path)","last_assistant_message":"All done"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + let commands = context.state.snapshot() + #expect(commands.contains { $0.hasPrefix("notify_target_async \(Self.liveWorkspaceId) \(Self.liveSurfaceId) ") }) + #expect(!commands.contains { $0.hasPrefix("notify_target_async \(Self.otherWorkspaceId)") }) + } + + @Test("A current PID failure does not fall back to uncorroborated records") + func currentPIDFailureFailsClosedWithoutSurfaceCorroboration() throws { + let context = try Harness.makeContext(name: "current-pid-fails-closed") + defer { context.cleanup() } + let sessionId = "current-pid-fails-closed-session" + + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.liveWorkspaceId, + surfaceId: Self.liveSurfaceId, + cwd: context.root.path + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [ + Self.liveWorkspaceId: [Self.liveSurfaceId], + Self.otherWorkspaceId: [Self.otherSurfaceId], + ], + pidTarget: nil, + surfaceTargets: [Self.otherSurfaceId: Self.otherWorkspaceId] + ) + + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.otherWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.otherSurfaceId + environment["CMUX_CLAUDE_PID"] = "43300" + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "stop"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"Stop","cwd":"\#(context.root.path)","last_assistant_message":"All done"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + #expect(!context.state.snapshot().contains { $0.hasPrefix("notify_target_async ") }) + } + + @Test("Fresh SessionStart rejects spawn-environment identity when PID lookup has no TTY") + func freshSessionStartRejectsUnverifiedInvocationSurface() throws { + let context = try Harness.makeContext(name: "fresh-session-surface-corroboration") + defer { context.cleanup() } + let sessionId = "fresh-session-surface-corroboration-session" + + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [Self.liveWorkspaceId: [Self.liveSurfaceId]], + pidTarget: nil, + surfaceTargets: [Self.liveSurfaceId: Self.liveWorkspaceId] + ) + + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.liveWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.liveSurfaceId + environment["CMUX_CLAUDE_PID"] = "43301" + + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "session-start"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","source":"clear","cwd":"\#(context.root.path)","hook_event_name":"SessionStart"}"# + ) + + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + #expect((try? Harness.sessionRecord(in: context.storeURL, sessionId: sessionId)) == nil) + } + + @Test("SessionEnd does not mutate a record rejected by live identity") + func sessionEndSuppressesVisibleCleanupAfterIdentityRejection() throws { + let context = try Harness.makeContext(name: "session-end-identity-rejected") + defer { context.cleanup() } + let sessionId = "session-end-identity-rejected-session" + try Harness.writeSessionStore( + to: context.storeURL, + sessionId: sessionId, + workspaceId: Self.liveWorkspaceId, + surfaceId: Self.liveSurfaceId, + cwd: context.root.path + ) + let serverHandled = Harness.startDeliveryTargetServer( + context: context, + surfacesByWorkspace: [ + Self.liveWorkspaceId: [Self.liveSurfaceId], + Self.otherWorkspaceId: [Self.otherSurfaceId], + ], + pidTarget: nil, + surfaceTargets: [Self.otherSurfaceId: Self.otherWorkspaceId] + ) + var environment = Harness.hookEnvironment(context: context) + environment["CMUX_WORKSPACE_ID"] = Self.otherWorkspaceId + environment["CMUX_SURFACE_ID"] = Self.otherSurfaceId + environment["CMUX_CLAUDE_PID"] = "43302" + let result = Harness.runHookProcess( + context: context, + arguments: ["hooks", "claude", "session-end"], + environment: environment, + standardInput: #"{"session_id":"\#(sessionId)","hook_event_name":"SessionEnd","cwd":"\#(context.root.path)"}"# + ) + #expect(serverHandled.wait(timeout: .now() + 5) == .success) + assertSuccessfulHook(result) + let commands = context.state.snapshot() + #expect(!commands.contains { $0.hasPrefix("clear_agent_pid ") }) + #expect(!commands.contains { $0.hasPrefix("clear_notifications ") }) + #expect(try Harness.sessionRecord(in: context.storeURL, sessionId: sessionId) != nil) + } + + private func assertSuccessfulHook(_ result: Harness.ProcessRunResult) { + #expect(!result.timedOut, Comment(rawValue: result.stderr)) + #expect(result.status == 0, Comment(rawValue: result.stderr)) + #expect(result.stdout == "{}\n") + } +} diff --git a/cmuxTests/NativeNotificationFallbackCommandTests.swift b/cmuxTests/NativeNotificationFallbackCommandTests.swift index 39217dbd1ed1..7e68dbb03444 100644 --- a/cmuxTests/NativeNotificationFallbackCommandTests.swift +++ b/cmuxTests/NativeNotificationFallbackCommandTests.swift @@ -44,6 +44,18 @@ struct NativeNotificationFallbackCommandTests { } } + private final class BoolValuesRecorder: Sendable { + private let valuesLock = OSAllocatedUnfairLock(initialState: [Bool]()) + + var values: [Bool] { + valuesLock.withLock { $0 } + } + + func append(_ value: Bool) { + valuesLock.withLock { $0.append(value) } + } + } + @Test func deniedNativeNotificationAuthorizationDoesNotRunCustomCommandFallback() { let store = TerminalNotificationStore.shared @@ -106,6 +118,37 @@ struct NativeNotificationFallbackCommandTests { #expect(commands.invocations.isEmpty) } + @Test + func sourceConfinedNativeNotificationSerializesRetargetingProvenance() { + let store = TerminalNotificationStore.shared + let originalAppFocusOverride = AppFocusState.overrideIsFocused + resetState(originalAppFocusOverride: false) + defer { resetState(originalAppFocusOverride: originalAppFocusOverride) } + + let retargetingValues = BoolValuesRecorder() + store.configureNotificationAuthorizationHandlerForTesting { completion in + completion(true, .authorized) + } + store.configureUserNotificationSchedulerForTesting { request, completion in + if let value = request.content.userInfo["retargetsToLiveSurfaceOwner"] as? Bool { + retargetingValues.append(value) + } + completion(nil) + } + store.configureNotificationCommandRunnerForTesting { _, _, _ in } + + store.addNotification( + tabId: UUID(), + surfaceId: UUID(), + title: "Relay", + subtitle: "Completed", + body: "Must stay confined", + retargetsToLiveSurfaceOwner: false + ) + + #expect(retargetingValues.values == [false]) + } + @Test func sharedNativeUnavailableFeedbackSuppressesCommandRunner() { var effects = TerminalNotificationPolicyEffects() diff --git a/cmuxTests/PhonePushPresenceGateTests.swift b/cmuxTests/PhonePushPresenceGateTests.swift index 98cd9ad7e05e..994c63735584 100644 --- a/cmuxTests/PhonePushPresenceGateTests.swift +++ b/cmuxTests/PhonePushPresenceGateTests.swift @@ -84,6 +84,52 @@ import Testing #expect(PhonePushClient.shouldForward(mode: .always, presence: decision)) } + @Test func phonePayloadOmitsSurfaceForConfinedNotificationsOnly() { + let workspaceId = UUID() + let surfaceId = UUID() + let confined = TerminalNotification( + id: UUID(), + tabId: workspaceId, + surfaceId: surfaceId, + retargetsToLiveSurfaceOwner: false, + title: "Relay", + subtitle: "Completed", + body: "Confined to its authorized workspace", + createdAt: Self.now, + isRead: false + ) + let trusted = TerminalNotification( + id: UUID(), + tabId: workspaceId, + surfaceId: surfaceId, + title: "Claude Code", + subtitle: "Completed", + body: "May follow its live surface", + createdAt: Self.now, + isRead: false + ) + + let confinedPayload = PhonePushPayload( + notification: confined, + macDeviceId: "mac-1", + badgeCount: 1, + hideContent: false + ) + let trustedPayload = PhonePushPayload( + notification: trusted, + macDeviceId: "mac-1", + badgeCount: 2, + hideContent: false + ) + + #expect(confinedPayload.workspaceId == workspaceId.uuidString) + #expect(confinedPayload.surfaceId == surfaceId.uuidString) + #expect(!confinedPayload.retargetsToLiveSurfaceOwner) + #expect(trustedPayload.workspaceId == workspaceId.uuidString) + #expect(trustedPayload.surfaceId == surfaceId.uuidString) + #expect(trustedPayload.retargetsToLiveSurfaceOwner) + } + // MARK: - Heuristic details @Test func idleExactlyAtThresholdCountsAsActive() { diff --git a/cmuxTests/TerminalNotificationOpenPanelFallbackTests.swift b/cmuxTests/TerminalNotificationOpenPanelFallbackTests.swift index e8a24633d8cf..926acd946afc 100644 --- a/cmuxTests/TerminalNotificationOpenPanelFallbackTests.swift +++ b/cmuxTests/TerminalNotificationOpenPanelFallbackTests.swift @@ -81,4 +81,67 @@ struct TerminalNotificationOpenPanelFallbackTests { #expect(manager.focusedSurfaceId(for: targetWorkspace.id) == targetPanelId) #expect(store.notifications.first(where: { $0.id == notification.id })?.isRead == true) } + + @Test + func confinedNotificationWithMovedSurfaceOpensAuthorizedWorkspace() throws { + let store = TerminalNotificationStore.shared + let previousShared = AppDelegate.shared + let appDelegate = previousShared ?? AppDelegate() + let manager = TabManager() + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + + AppDelegate.shared = appDelegate + appDelegate.tabManager = manager + appDelegate.notificationStore = store + store.replaceNotificationsForTesting([]) + + let authorizedWorkspace = manager.addWorkspace(title: "Authorized", select: true) + let liveWorkspace = manager.addWorkspace(title: "Live owner", select: false) + let movedPanelId = try #require(authorizedWorkspace.focusedPanelId) + let windowId = appDelegate.registerMainWindowContextForTesting(tabManager: manager) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 320, height: 240), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.identifier = NSUserInterfaceItemIdentifier("cmux.main.\(windowId.uuidString)") + window.makeKeyAndOrderFront(nil) + + defer { + appDelegate.unregisterMainWindowContextForTesting(windowId: windowId) + window.close() + for workspace in manager.tabs { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppDelegate.shared = previousShared + } + + let notification = TerminalNotification( + id: UUID(), + tabId: authorizedWorkspace.id, + surfaceId: movedPanelId, + retargetsToLiveSurfaceOwner: false, + title: "Confined notification", + subtitle: "Completed", + body: "Stay in the authorized workspace", + createdAt: Date(timeIntervalSince1970: 1_778_888_889), + isRead: false + ) + store.replaceNotificationsForTesting([notification]) + + let transfer = try #require(authorizedWorkspace.detachSurface(panelId: movedPanelId)) + let destinationPaneId = try #require(liveWorkspace.bonsplitController.allPaneIds.first) + _ = try #require(liveWorkspace.attachDetachedSurface(transfer, inPane: destinationPaneId, focus: false)) + manager.selectTab(liveWorkspace) + + #expect(appDelegate.openTerminalNotification(notification)) + #expect(manager.selectedTabId == authorizedWorkspace.id) + #expect(manager.focusedSurfaceId(for: authorizedWorkspace.id) != movedPanelId) + #expect(store.notifications.first(where: { $0.id == notification.id })?.isRead == true) + } } diff --git a/ios/cmux/CmuxAppDelegate.swift b/ios/cmux/CmuxAppDelegate.swift index 95b8a3fa6e3d..7eb2d68a46a2 100644 --- a/ios/cmux/CmuxAppDelegate.swift +++ b/ios/cmux/CmuxAppDelegate.swift @@ -92,7 +92,8 @@ final class CmuxAppDelegate: NSObject, @preconcurrency UIApplicationDelegate, UN await pushCoordinator?.handleTap( workspaceId: ids.workspaceId, surfaceId: ids.surfaceId, - macDeviceId: ids.macDeviceId + macDeviceId: ids.macDeviceId, + retargetsToLiveSurfaceOwner: ids.retargetsToLiveSurfaceOwner ) await pushCoordinator?.handleDismiss( notificationId: Self.notificationID(from: request), @@ -145,12 +146,13 @@ final class CmuxAppDelegate: NSObject, @preconcurrency UIApplicationDelegate, UN private nonisolated static func cmuxIDs( from userInfo: [AnyHashable: Any] - ) -> (workspaceId: String?, surfaceId: String?, macDeviceId: String?) { - guard let cmux = userInfo["cmux"] as? [String: Any] else { return (nil, nil, nil) } + ) -> (workspaceId: String?, surfaceId: String?, macDeviceId: String?, retargetsToLiveSurfaceOwner: Bool) { + guard let cmux = userInfo["cmux"] as? [String: Any] else { return (nil, nil, nil, true) } return ( cmux["workspaceId"] as? String, cmux["surfaceId"] as? String, - cmux["macDeviceId"] as? String + cmux["macDeviceId"] as? String, + cmux["retargetsToLiveSurfaceOwner"] as? Bool ?? true ) } diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/MobilePushConfinementTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/MobilePushConfinementTests.swift new file mode 100644 index 000000000000..fb459fee3767 --- /dev/null +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/MobilePushConfinementTests.swift @@ -0,0 +1,71 @@ +import CmuxMobileRPC +@testable import CmuxMobileShell +@testable import CmuxMobileShellUI +import CmuxMobileShellModel +import Testing + +@Test @MainActor func confinedNotificationTapDoesNotFollowSurfaceToAnotherWorkspace() { + let coordinator = MobilePushCoordinator(registration: InertPushRegistration()) + let store = deeplinkTestStore() + store.replaceForegroundWorkspaceState(PreviewMobileHost.workspaces) + coordinator.bind(store: store) + + coordinator.handleTap( + workspaceId: "workspace-docs", + surfaceId: "terminal-build", + macDeviceId: nil, + retargetsToLiveSurfaceOwner: false + ) + let firstNavigationToken = store.deeplinkWorkspaceNavigationRequest?.token + coordinator.workspacesDidChange() + + #expect(store.selectedWorkspaceID == MobileWorkspacePreview.ID(rawValue: "workspace-docs")) + #expect(store.selectedTerminalID?.rawValue != "terminal-build") + #expect(store.deeplinkWorkspaceNavigationRequest?.token == firstNavigationToken) +} + +@Test @MainActor func trustedNotificationTapStillFollowsSurfaceToLiveWorkspace() { + let coordinator = MobilePushCoordinator(registration: InertPushRegistration()) + let store = deeplinkTestStore() + store.replaceForegroundWorkspaceState(PreviewMobileHost.workspaces) + coordinator.bind(store: store) + + coordinator.handleTap( + workspaceId: "workspace-docs", + surfaceId: "terminal-build", + macDeviceId: nil, + retargetsToLiveSurfaceOwner: true + ) + + #expect(store.selectedWorkspaceID == MobileWorkspacePreview.ID(rawValue: "workspace-main")) + #expect(store.selectedTerminalID == MobileTerminalPreview.ID(rawValue: "terminal-build")) +} + +@Test @MainActor func confinedNotificationTapDoesNotReplayWorkspaceWhileSurfaceIsAbsent() { + let coordinator = MobilePushCoordinator(registration: InertPushRegistration()) + let store = deeplinkTestStore() + store.replaceForegroundWorkspaceState([ + MobileWorkspacePreview(id: "workspace-docs", name: "Docs", terminals: []) + ]) + coordinator.bind(store: store) + + coordinator.handleTap( + workspaceId: "workspace-docs", + surfaceId: "terminal-notes", + macDeviceId: nil, + retargetsToLiveSurfaceOwner: false + ) + let firstNavigationToken = store.deeplinkWorkspaceNavigationRequest?.token + coordinator.workspacesDidChange() + + #expect(firstNavigationToken != nil) + #expect(store.deeplinkWorkspaceNavigationRequest?.token == firstNavigationToken) + #expect(store.consumeDeeplinkWorkspaceNavigationRequest()?.rawValue == "workspace-docs") + coordinator.workspacesDidChange() + #expect(store.deeplinkWorkspaceNavigationRequest == nil) + + store.replaceForegroundWorkspaceState(PreviewMobileHost.workspaces) + coordinator.workspacesDidChange() + #expect(store.selectedTerminalID == MobileTerminalPreview.ID(rawValue: "terminal-notes")) + #expect(store.deeplinkWorkspaceNavigationRequest == nil) +} diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift index 90aaf8886880..86a6a6398657 100644 --- a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift @@ -4137,7 +4137,7 @@ private func rpcErrorFrame(code: String? = nil, message: String) throws -> Data // MARK: - Push notification deep-link /// Inert registration stub: deep-link tests exercise tap routing only. -private struct InertPushRegistration: PushRegistering { +struct InertPushRegistration: PushRegistering { var isEnabled: Bool { get async { false } } @@ -4148,7 +4148,7 @@ private struct InertPushRegistration: PushRegistering { func unregisterFromServer(accessToken: String?, refreshToken: String?) async {} } -@MainActor private func deeplinkTestStore() -> CMUXMobileShellStore { +@MainActor func deeplinkTestStore() -> CMUXMobileShellStore { CMUXMobileShellStore( runtime: testRuntime( transportFactory: RecordingNeverConnectTransportFactory(dials: TransportDialRecorder()) diff --git a/tests/test_claude_hook_clear_running_status.py b/tests/test_claude_hook_clear_running_status.py index cc9f283b50e5..8f4e59bfb242 100644 --- a/tests/test_claude_hook_clear_running_status.py +++ b/tests/test_claude_hook_clear_running_status.py @@ -109,7 +109,21 @@ def _response_for(self, line: str) -> str: method = request.get("method") result: dict[str, object] = {} - if method == "surface.list": + if method == "agent.resolve_delivery_target": + params = request.get("params") + if isinstance(params, dict) and "pid" in params: + result = { + "source": "pid", + "workspace_id": self.workspace_id, + "surface_id": self.surface_id, + } + else: + result = { + "source": "surface", + "workspace_id": self.workspace_id, + "surface_id": self.surface_id, + } + elif method == "surface.list": result = { "surfaces": [ { @@ -254,8 +268,11 @@ def main() -> int: ) clear_commands = server.commands[clear_start:] - if not has_command(clear_commands, f"clear_notifications --tab={workspace_id}"): - print("FAIL: expected clear SessionStart to clear stale notifications") + if not has_command( + clear_commands, + f"clear_notifications --tab={workspace_id} --panel={surface_id}", + ): + print("FAIL: expected clear SessionStart to clear only the current panel") print(f"clear_commands={clear_commands!r}") return 1 if not has_command_with( diff --git a/web/services/apns/payload.ts b/web/services/apns/payload.ts index f57484151891..a3926b8975d0 100644 --- a/web/services/apns/payload.ts +++ b/web/services/apns/payload.ts @@ -25,6 +25,8 @@ export interface ApnsNotificationInput { readonly body: string; readonly workspaceId?: string | null; readonly surfaceId?: string | null; + /** Whether a tap may resolve the surface outside `workspaceId`. */ + readonly retargetsToLiveSurfaceOwner?: boolean; readonly macDeviceId?: string | null; /** * Stable Mac-side notification id. Surfaced in the payload as @@ -57,12 +59,11 @@ export interface ApnsNotificationInput { export const CMUX_APNS_CATEGORY = "cmux.terminal"; /** - * Build the APNs JSON payload. Adds `cmux.workspaceId`/`cmux.surfaceId`/ - * `cmux.macDeviceId`/`cmux.notificationId` custom keys so a tapped notification - * can deep-link to the right terminal on the right Mac and a swipe can be - * dismiss-synced, sets the dismiss-action `category`, and marks the alert - * time-sensitive (the app holds that - * entitlement). + * Build the APNs JSON payload. Adds the workspace/surface ids, live-owner + * retargeting provenance, Mac id, and notification id under `cmux` so a tap + * can deep-link without crossing a confined workspace boundary and a swipe can + * be dismiss-synced. Also sets the dismiss-action `category` and marks the + * alert time-sensitive (the app holds that entitlement). */ export function buildApnsPayload(input: ApnsNotificationInput): Record { if (input.kind === "dismiss") return buildDismissPayload(input); @@ -83,9 +84,12 @@ export function buildApnsPayload(input: ApnsNotificationInput): Record = {}; + const cmux: Record = {}; if (input.workspaceId) cmux.workspaceId = input.workspaceId; if (input.surfaceId) cmux.surfaceId = input.surfaceId; + if (typeof input.retargetsToLiveSurfaceOwner === "boolean") { + cmux.retargetsToLiveSurfaceOwner = input.retargetsToLiveSurfaceOwner; + } if (input.macDeviceId) cmux.macDeviceId = input.macDeviceId; if (input.notificationId) cmux.notificationId = input.notificationId; diff --git a/web/services/apns/routePolicy.ts b/web/services/apns/routePolicy.ts index d9b3059bd798..e326f066a037 100644 --- a/web/services/apns/routePolicy.ts +++ b/web/services/apns/routePolicy.ts @@ -31,6 +31,8 @@ export type PushPayload = { readonly body: string; readonly workspaceId: string | null; readonly surfaceId: string | null; + /** Whether iOS may resolve the surface outside the explicit workspace. */ + readonly retargetsToLiveSurfaceOwner: boolean; /** * The Mac device UUID that owns the workspace/surface ids. Needed because * workspace ids are Mac-local and can collide across paired Macs. @@ -125,6 +127,7 @@ export function parsePushPayload(body: Record): PushPayloadResu notificationId: notificationId || null, dismissedIds: kind === "dismiss" ? dismissedIds.value : [], badgeCount: parseBadgeCount(body.badgeCount), + retargetsToLiveSurfaceOwner: kind === "notify" ? body.retargetsToLiveSurfaceOwner !== false : false, hideContent: body.hideContent === true, }, }; diff --git a/web/tests/apns.test.ts b/web/tests/apns.test.ts index 5aa78108b561..c468fde89378 100644 --- a/web/tests/apns.test.ts +++ b/web/tests/apns.test.ts @@ -28,13 +28,19 @@ describe("apns payload", () => { body: "Agent finished", workspaceId: "ws-1", surfaceId: "sf-2", + retargetsToLiveSurfaceOwner: false, macDeviceId: "mac-3", - }) as { aps: Record; cmux: Record }; + }) as { aps: Record; cmux: Record }; expect(payload.aps.alert).toEqual({ title: "claude", subtitle: "issue-118", body: "Agent finished" }); expect(payload.aps["interruption-level"]).toBe("time-sensitive"); expect(payload.aps.sound).toBe("default"); - expect(payload.cmux).toEqual({ workspaceId: "ws-1", surfaceId: "sf-2", macDeviceId: "mac-3" }); + expect(payload.cmux).toEqual({ + workspaceId: "ws-1", + surfaceId: "sf-2", + retargetsToLiveSurfaceOwner: false, + macDeviceId: "mac-3", + }); }); test("omits cmux block when no ids", () => { @@ -189,6 +195,7 @@ describe("apns route policy", () => { surfaceId: " sf-1 ", macDeviceId: " mac-1 ", notificationId: " n-1 ", + retargetsToLiveSurfaceOwner: false, hideContent: true, }); @@ -205,6 +212,7 @@ describe("apns route policy", () => { notificationId: "n-1", dismissedIds: [], badgeCount: null, + retargetsToLiveSurfaceOwner: false, hideContent: true, }, }); @@ -234,6 +242,7 @@ describe("apns route policy", () => { notificationId: null, dismissedIds: [], badgeCount: null, + retargetsToLiveSurfaceOwner: true, hideContent: false, }, }); @@ -263,6 +272,7 @@ describe("apns route policy", () => { notificationId: null, dismissedIds: ["n-1", "n-2"], badgeCount: 4, + retargetsToLiveSurfaceOwner: false, hideContent: false, }, });