diff --git a/CLI/CMUXCLI+PiExtension.swift b/CLI/CMUXCLI+PiExtension.swift index 9ea3d8d04b6e..c52cc9abfaec 100644 --- a/CLI/CMUXCLI+PiExtension.swift +++ b/CLI/CMUXCLI+PiExtension.swift @@ -1,4 +1,5 @@ import Foundation +import Darwin extension CMUXCLI { private static let piExtensionMarker = "cmux-pi-session-extension-marker" @@ -26,6 +27,89 @@ extension CMUXCLI { } } + @discardableResult + private func withPiExtensionMutationLock( + at extensionURL: URL, + createParentDirectory: Bool, + acquireNonBlocking: Bool = false, + fileManager: FileManager = .default, + _ operation: () throws -> T + ) throws -> T? { + let directoryURL = extensionURL.deletingLastPathComponent() + if createParentDirectory { + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true) + } + let lockURL = directoryURL.appendingPathComponent(".cmux-session.lock", isDirectory: false) + let descriptor = Darwin.open( + lockURL.path, + O_CREAT | O_RDWR | O_CLOEXEC | O_NOFOLLOW, + mode_t(S_IRUSR | S_IWUSR) + ) + guard descriptor >= 0 else { + throw piExtensionReadError(at: extensionURL) + } + defer { Darwin.close(descriptor) } + var metadata = stat() + guard Darwin.fstat(descriptor, &metadata) == 0, + metadata.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG) else { + throw piExtensionReadError(at: extensionURL) + } + let lockOperation = LOCK_EX | (acquireNonBlocking ? LOCK_NB : 0) + guard flock(descriptor, lockOperation) == 0 else { + if acquireNonBlocking, errno == EWOULDBLOCK || errno == EAGAIN { + return nil + } + throw piExtensionReadError(at: extensionURL) + } + defer { flock(descriptor, LOCK_UN) } + return try operation() + } + + private func piExtensionReadError(at url: URL) -> CLIError { + CLIError(message: String.localizedStringWithFormat( + String( + localized: "cli.hooks.pi.error.readFailed", + defaultValue: "Failed to read %@" + ), + url.path + )) + } + + func refreshManagedPiExtensionIfNeeded(_ def: AgentHookDef) { + let extensionURL = piExtensionURL(for: def) + let fileManager = FileManager.default + guard fileManager.fileExists(atPath: extensionURL.path) else { return } + do { + try withPiExtensionMutationLock( + at: extensionURL, + createParentDirectory: false, + acquireNonBlocking: true, + fileManager: fileManager + ) { + guard fileManager.fileExists(atPath: extensionURL.path) else { return } + let existing = try existingPiExtensionContents(at: extensionURL, fileManager: fileManager) + if existing.isEmpty { + try Self.piExtensionSource.write(to: extensionURL, atomically: true, encoding: .utf8) + return + } + guard existing.contains(Self.piExtensionMarker), + existing != Self.piExtensionSource + else { + return + } + // Revalidate immediately before replacement. All cmux install, refresh, + // and uninstall mutations share this lock, so an in-flight refresh + // cannot recreate an extension that another cmux process removed. + guard try existingPiExtensionContents(at: extensionURL, fileManager: fileManager) == existing else { + return + } + try Self.piExtensionSource.write(to: extensionURL, atomically: true, encoding: .utf8) + } + } catch { + // Hook delivery must continue when a managed extension cannot be refreshed. + } + } + func installPiExtensionHooks(_ def: AgentHookDef) throws { let extensionURL = piExtensionURL(for: def) let fileManager = FileManager.default @@ -64,11 +148,25 @@ extension CMUXCLI { return } } - try fileManager.createDirectory( - at: extensionURL.deletingLastPathComponent(), - withIntermediateDirectories: true - ) - try Self.piExtensionSource.write(to: extensionURL, atomically: true, encoding: .utf8) + try withPiExtensionMutationLock( + at: extensionURL, + createParentDirectory: true, + fileManager: fileManager + ) { + let current = try existingPiExtensionContents(at: extensionURL, fileManager: fileManager) + if !current.isEmpty, !current.contains(Self.piExtensionMarker) { + throw CLIError(message: String.localizedStringWithFormat( + String( + localized: "cli.hooks.pi.error.notCmuxExtension", + defaultValue: "%@ exists and is not a cmux extension; leaving it alone" + ), + extensionURL.path + )) + } + if current != Self.piExtensionSource { + try Self.piExtensionSource.write(to: extensionURL, atomically: true, encoding: .utf8) + } + } print(String.localizedStringWithFormat( String( localized: "cli.hooks.pi.installed", @@ -91,8 +189,23 @@ extension CMUXCLI { )) return } - let existing = try existingPiExtensionContents(at: extensionURL, fileManager: fm) - guard existing.contains(Self.piExtensionMarker) else { + var removed = false + var refused = false + try withPiExtensionMutationLock( + at: extensionURL, + createParentDirectory: false, + fileManager: fm + ) { + let existing = try existingPiExtensionContents(at: extensionURL, fileManager: fm) + guard !existing.isEmpty else { return } + guard existing.contains(Self.piExtensionMarker) else { + refused = true + return + } + try fm.removeItem(at: extensionURL) + removed = true + } + if refused { print(String.localizedStringWithFormat( String( localized: "cli.hooks.pi.refuseRemoveMissingMarker", @@ -102,7 +215,16 @@ extension CMUXCLI { )) return } - try fm.removeItem(at: extensionURL) + guard removed else { + print(String.localizedStringWithFormat( + String( + localized: "cli.hooks.pi.noneFound", + defaultValue: "No Pi cmux extension found at %@" + ), + extensionURL.path + )) + return + } print(String.localizedStringWithFormat( String( localized: "cli.hooks.pi.removed", diff --git a/CLI/CMUXCLI+PiExtensionSourceDispatch.swift b/CLI/CMUXCLI+PiExtensionSourceDispatch.swift index 7937248d56b8..4605324fc10b 100644 --- a/CLI/CMUXCLI+PiExtensionSourceDispatch.swift +++ b/CLI/CMUXCLI+PiExtensionSourceDispatch.swift @@ -31,7 +31,7 @@ class PiCmuxCommandDispatcher { // CLI owns a four-second end-to-end deadline. Observe that outcome before the // extension classifies a terminal delivery as failed. private static readonly feedDrainDeadlineMs = 4500; - private controlQueue: Promise = Promise.resolve(); + private controlQueues = new Map>(); private pendingFeedCommands = new Map(); private pendingFeedKeysBySession = new Map(); private priorityFeedCommands = new Map(); @@ -56,8 +56,16 @@ class PiCmuxCommandDispatcher { input: string | undefined, context: PiExtensionContextSnapshot, ): Promise { - const scheduled = this.controlQueue.then(() => this.execute(args, cwd, input, context)); - this.controlQueue = scheduled.then(() => undefined, () => undefined); + const sessionId = context.sessionId; + const previous = this.controlQueues.get(sessionId) || Promise.resolve(); + const scheduled = previous.then(() => this.execute(args, cwd, input, context)); + let tail: Promise; + tail = scheduled + .then(() => undefined, () => undefined) + .finally(() => { + if (this.controlQueues.get(sessionId) === tail) this.controlQueues.delete(sessionId); + }); + this.controlQueues.set(sessionId, tail); return scheduled; } enqueueFeed(key: string, command: PiFeedCommand): void { diff --git a/CLI/CMUXCLI+PiExtensionSourcePart1.swift b/CLI/CMUXCLI+PiExtensionSourcePart1.swift index 68bbce698c8b..5babceaac3e1 100644 --- a/CLI/CMUXCLI+PiExtensionSourcePart1.swift +++ b/CLI/CMUXCLI+PiExtensionSourcePart1.swift @@ -466,16 +466,26 @@ function settleTurn(sessionStates: Map, sessionId: string) return completion; } -function warn(ctx: PiExtensionContextSnapshot | null, message: string, details: Record = {}): void { +function warn( + ctx: PiExtensionContextSnapshot | null, + message: string, + details: Record = {}, + notifyUser = false, +): void { const payload = { source: "cmux-pi-extension", level: "warning", message, ...details }; try { console.warn(JSON.stringify(payload)); } catch (_) { console.warn(`[cmux-pi-extension] ${message}`); } - try { - ctx?.notifyWarning?.(); - } catch (_) {} + // Hook transport is best-effort telemetry. Keep routine command failures in + // the terminal instead of interrupting Pi with a generic toast; reserve the + // UI warning for an unexpected extension-task exception. + if (notifyUser) { + try { + ctx?.notifyWarning?.(); + } catch (_) {} + } } function cmuxExecutable(): string { diff --git a/CLI/CMUXCLI+PiExtensionSourcePart2.swift b/CLI/CMUXCLI+PiExtensionSourcePart2.swift index 8cc92922fe38..2ecf8134f815 100644 --- a/CLI/CMUXCLI+PiExtensionSourcePart2.swift +++ b/CLI/CMUXCLI+PiExtensionSourcePart2.swift @@ -283,21 +283,19 @@ function isTerminalFeedEvent(eventName: PiFeedEventName): boolean { return eventName === "PostToolUse" || eventName === "SubagentStop"; } -function sendFeed( +function prepareFeedDispatch( dispatcher: PiCmuxCommandDispatcher, sessionStates: Map, eventName: PiFeedEventName, context: PiExtensionContextSnapshot, event: unknown, -): void { - if (process.env.CMUX_PI_HOOKS_DISABLED === "1") return; +): (() => void) | undefined { + if (process.env.CMUX_PI_HOOKS_DISABLED === "1") return undefined; const sessionId = context.sessionId; - if (!sessionId) return; - if (!dispatcher.canDispatch(sessionId)) return; - const target = surfaceTargetArgs(dispatcher, sessionId); - if (!target) return; + if (!sessionId) return undefined; + if (!dispatcher.canDispatch(sessionId)) return undefined; const state = stateFor(sessionStates, sessionId); - if (state.stopped) return; + if (state.stopped) return undefined; const cwd = context.cwd; const toolCallId = firstString(objectValue(event, ["toolCallId", "tool_call_id", "id"])); const toolName = firstString(objectValue(event, ["toolName", "tool_name", "name"])); @@ -323,14 +321,18 @@ function sendFeed( const isError = objectValue(event, ["isError", "is_error"]); if (isError !== undefined) payload.is_error = projectPiFeedValue(isError, projectionState); } - dispatcher.enqueueFeed(`${sessionId}:${toolCallId || toolName || "unknown"}`, { - args: ["hooks", "feed", "--source", "pi", "--event", eventName, ...target], - cwd, - payload, - context, - terminal: isTerminalFeedEvent(eventName), - onFailure: () => { state.feedDeliveryFailed = true; }, - }); + return () => { + const target = surfaceTargetArgs(dispatcher, sessionId); + if (!target) return; + dispatcher.enqueueFeed(`${sessionId}:${toolCallId || toolName || "unknown"}`, { + args: ["hooks", "feed", "--source", "pi", "--event", eventName, ...target], + cwd, + payload, + context, + terminal: isTerminalFeedEvent(eventName), + onFailure: () => { state.feedDeliveryFailed = true; }, + }); + }; } async function publishPendingCompletion( @@ -338,9 +340,8 @@ async function publishPendingCompletion( sessionStates: Map, context: PiExtensionContextSnapshot, sessionId: string, + completion: PendingCompletion, ): Promise { - const completion = settleTurn(sessionStates, sessionId); - if (!completion) return; await dispatcher.finishFeedForSession(sessionId); const state = stateFor(sessionStates, sessionId); const feedDelivered = !state.feedDeliveryFailed; @@ -366,8 +367,33 @@ async function publishPendingCompletion( export default function cmuxPiSessionExtension(pi: ExtensionAPI) { const dispatcher = new PiCmuxCommandDispatcher(); const sessionStates = new Map(); + const lifecycleTails = new Map>(); + + const enqueueLifecycleTask = ( + sessionId: string, + context: PiExtensionContextSnapshot, + operation: () => Promise | unknown, + ): Promise => { + const previous = lifecycleTails.get(sessionId) || Promise.resolve(); + let tracked: Promise; + tracked = previous + .then(operation) + .then(() => undefined) + .catch((error) => { + const errorMessage = error instanceof Error ? error.message : undefined; + warn(context, "cmux lifecycle task failed", { + error_available: error !== undefined, + error_message: utf8Prefix(errorMessage, 512), + }, true); + }) + .finally(() => { + if (lifecycleTails.get(sessionId) === tracked) lifecycleTails.delete(sessionId); + }); + lifecycleTails.set(sessionId, tracked); + return tracked; + }; - pi.on("session_start", async (_event, ctx) => { + pi.on("session_start", (_event, ctx) => { const context = snapshotContext(ctx); const sessionId = context.sessionId; if (sessionId) { @@ -376,40 +402,53 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { state.feedDeliveryFailed = false; state.stopped = false; } - const ok = await sendHook(dispatcher, "session-start", context); - if (ok && sessionId) await ensureResumeBinding(dispatcher, context, sessionId); + if (!sessionId) return; + enqueueLifecycleTask(sessionId, context, async () => { + const ok = await sendHook(dispatcher, "session-start", context); + if (ok) await ensureResumeBinding(dispatcher, context, sessionId); + }); }); - pi.on("before_agent_start", async (event, ctx) => { + pi.on("before_agent_start", (event, ctx) => { const context = snapshotContext(ctx); const sessionId = context.sessionId; - const turnId = sessionId ? beginTurn(sessionStates, sessionId, event) : undefined; - await sendHook(dispatcher, "prompt-submit", context, { prompt: event.prompt, turn_id: turnId }); + if (!sessionId) return; + const turnId = beginTurn(sessionStates, sessionId, event); + enqueueLifecycleTask(sessionId, context, () => ( + sendHook(dispatcher, "prompt-submit", context, { prompt: event.prompt, turn_id: turnId }) + )); }); - pi.on("tool_execution_start", async (event, ctx) => { + const enqueueFeed = ( + eventName: PiFeedEventName, + event: unknown, + ctx: ExtensionContext, + ): void => { const context = snapshotContext(ctx); - const eventName = isSubagentTool(event) ? "SubagentStart" : "PreToolUse"; - sendFeed(dispatcher, sessionStates, eventName, context, event); + const sessionId = context.sessionId; + if (!sessionId) return; + const dispatch = prepareFeedDispatch(dispatcher, sessionStates, eventName, context, event); + if (!dispatch) return; + enqueueLifecycleTask(sessionId, context, dispatch); + }; + + pi.on("tool_execution_start", (event, ctx) => { + enqueueFeed(isSubagentTool(event) ? "SubagentStart" : "PreToolUse", event, ctx); }); - pi.on("tool_execution_end", async (event, ctx) => { - const context = snapshotContext(ctx); - const eventName = isSubagentTool(event) ? "SubagentStop" : "PostToolUse"; - sendFeed(dispatcher, sessionStates, eventName, context, event); + pi.on("tool_execution_end", (event, ctx) => { + enqueueFeed(isSubagentTool(event) ? "SubagentStop" : "PostToolUse", event, ctx); }); - pi.on("session_before_compact", async (event, ctx) => { - const context = snapshotContext(ctx); - sendFeed(dispatcher, sessionStates, "PreCompact", context, event); + pi.on("session_before_compact", (event, ctx) => { + enqueueFeed("PreCompact", event, ctx); }); - pi.on("session_compact", async (event, ctx) => { - const context = snapshotContext(ctx); - sendFeed(dispatcher, sessionStates, "PostCompact", context, event); + pi.on("session_compact", (event, ctx) => { + enqueueFeed("PostCompact", event, ctx); }); - pi.on("agent_end", async (event, ctx) => { + pi.on("agent_end", (event, ctx) => { const context = snapshotContext(ctx); const sessionId = context.sessionId; if (!sessionId) return; @@ -423,17 +462,27 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { }; // Older Pi versions do not emit agent_settled, so retain their established completion behavior. if (!supportsAgentSettled()) { - await publishPendingCompletion(dispatcher, sessionStates, context, sessionId); + const completion = settleTurn(sessionStates, sessionId); + if (completion) { + enqueueLifecycleTask(sessionId, context, () => ( + publishPendingCompletion(dispatcher, sessionStates, context, sessionId, completion) + )); + } } }); - pi.on("agent_settled", async (_event, ctx) => { + pi.on("agent_settled", (_event, ctx) => { const context = snapshotContext(ctx); const isIdle = ctx.isIdle(); const sessionId = context.sessionId; if (!sessionId || !isIdle) return; // Consume pending completion before subprocess calls so duplicate settlement cannot notify twice. - await publishPendingCompletion(dispatcher, sessionStates, context, sessionId); + const completion = settleTurn(sessionStates, sessionId); + if (completion) { + enqueueLifecycleTask(sessionId, context, () => ( + publishPendingCompletion(dispatcher, sessionStates, context, sessionId, completion) + )); + } }); pi.on("session_shutdown", async (event, ctx) => { @@ -449,16 +498,18 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { terminationReason: firstString(objectValue(event, ["reason"])) || "session_shutdown", }; } - await dispatcher.finishFeedForSession(sessionId); - const feedDelivered = !state.feedDeliveryFailed; - state.feedDeliveryFailed = false; - if (!feedDelivered) warn(context, "cmux hook command failed", { session_id: sessionId }); - if (stopPayload) await sendHook(dispatcher, "stop", context, stopPayload); - try { - await clearResumeBinding(dispatcher, context, sessionId); - } finally { - releaseSessionRuntime(dispatcher, sessionStates, sessionId); - } + await enqueueLifecycleTask(sessionId, context, async () => { + await dispatcher.finishFeedForSession(sessionId); + const feedDelivered = !state.feedDeliveryFailed; + state.feedDeliveryFailed = false; + if (!feedDelivered) warn(context, "cmux hook command failed", { session_id: sessionId }); + if (stopPayload) await sendHook(dispatcher, "stop", context, stopPayload); + try { + await clearResumeBinding(dispatcher, context, sessionId); + } finally { + releaseSessionRuntime(dispatcher, sessionStates, sessionId); + } + }); }); } """# diff --git a/CLI/cmux.swift b/CLI/cmux.swift index b61e0a56ba2f..329a9404f802 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -35274,6 +35274,9 @@ export default CMUXSessionRestore; print(subcommandUsage("hooks") ?? "Usage: cmux hooks ") return true } + if def.name == "pi", action == "session-start" { + refreshManagedPiExtensionIfNeeded(def) + } let actionArgs = Array(rest.dropFirst()) switch action { case "inject-args" where def.name == "codex": diff --git a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift new file mode 100644 index 000000000000..9fd421ca8975 --- /dev/null +++ b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/SidebarUnreadSnapshot.swift @@ -0,0 +1,280 @@ +public import Foundation +import Observation + +/// The unread values rendered for one workspace row. +public struct SidebarWorkspaceUnreadSummary: Equatable, Sendable { + /// The workspace's displayed unread count. + public var unreadCount: Int + /// The trimmed body or title of the latest notification, when present. + public var latestNotificationText: String? + /// Whether the workspace has a latest notification that can be cleared. + public var hasLatestNotification: Bool + + /// Creates one workspace unread summary. + public init( + unreadCount: Int, + latestNotificationText: String?, + hasLatestNotification: Bool = false + ) { + self.unreadCount = unreadCount + self.latestNotificationText = latestNotificationText + self.hasLatestNotification = hasLatestNotification + } +} + +/// A workspace and optional surface pair in the unread set. +public struct SidebarSurfaceUnreadKey: Hashable, Sendable { + /// The owning workspace identifier. + public var workspaceId: UUID + /// The surface identifier, or `nil` for a workspace-wide notification. + public var surfaceId: UUID? + + /// Creates one workspace or surface unread key. + public init(workspaceId: UUID, surfaceId: UUID?) { + self.workspaceId = workspaceId + self.surfaceId = surfaceId + } +} + +/// One atomic unread-state publication shared by all presentation surfaces. +public struct SidebarUnreadSnapshot: Equatable, Sendable { + /// Total unread count rendered by global badges. + public let totalUnreadCount: Int + /// Per-workspace row summaries, omitting default empty summaries. + public let summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] + /// Workspace and surface pairs with unread notifications. + public let unreadSurfaceKeys: Set + /// Focused surfaces whose read indicator remains visible. + public let focusedReadIndicatorByWorkspaceId: [UUID: UUID] + /// Workspaces explicitly marked unread by the user. + public let manualUnreadWorkspaceIds: Set + + /// Creates one complete unread snapshot. + public init( + totalUnreadCount: Int = 0, + summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] = [:], + unreadSurfaceKeys: Set = [], + focusedReadIndicatorByWorkspaceId: [UUID: UUID] = [:], + manualUnreadWorkspaceIds: Set = [] + ) { + self.totalUnreadCount = totalUnreadCount + self.summaryByWorkspaceId = summaryByWorkspaceId + self.unreadSurfaceKeys = unreadSurfaceKeys + self.focusedReadIndicatorByWorkspaceId = focusedReadIndicatorByWorkspaceId + self.manualUnreadWorkspaceIds = manualUnreadWorkspaceIds + } + + /// Returns the workspace summary, or an empty summary when absent. + public func summary(forWorkspaceId id: UUID) -> SidebarWorkspaceUnreadSummary { + summaryByWorkspaceId[id] ?? SidebarWorkspaceUnreadSummary( + unreadCount: 0, + latestNotificationText: nil + ) + } + + /// Returns the workspace's displayed unread count. + public func unreadCount(forWorkspaceId id: UUID) -> Int { + summary(forWorkspaceId: id).unreadCount + } + + /// Returns the workspace's latest notification text. + public func latestNotificationText(forWorkspaceId id: UUID) -> String? { + summary(forWorkspaceId: id).latestNotificationText + } + + /// Returns whether the workspace has any displayed unread state. + public func workspaceIsUnread(forWorkspaceId id: UUID) -> Bool { + unreadCount(forWorkspaceId: id) > 0 || hasManualUnread(forWorkspaceId: id) + } + + /// Returns whether the workspace was explicitly marked unread. + public func hasManualUnread(forWorkspaceId id: UUID) -> Bool { + manualUnreadWorkspaceIds.contains(id) + } + + /// Returns whether the workspace or surface has an unread notification. + public func hasUnreadNotification(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { + unreadSurfaceKeys.contains(SidebarSurfaceUnreadKey(workspaceId: id, surfaceId: surfaceId)) + } + + /// Returns whether the surface should render its notification indicator. + public func hasVisibleNotificationIndicator(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { + hasUnreadNotification(forWorkspaceId: id, surfaceId: surfaceId) || + (focusedReadIndicatorByWorkspaceId[id].map { $0 == surfaceId } ?? false) + } + + /// Returns whether any supplied workspace can be marked read. + public func canMarkWorkspaceRead(forWorkspaceIds ids: [UUID]) -> Bool { + ids.contains { workspaceIsUnread(forWorkspaceId: $0) } + } + + /// Returns whether any supplied workspace can be marked unread. + public func canMarkWorkspaceUnread(forWorkspaceIds ids: [UUID]) -> Bool { + ids.contains { !workspaceIsUnread(forWorkspaceId: $0) } + } +} + +/// Cancels one imperative unread-snapshot observation. +@MainActor +public final class SidebarUnreadObservation { + nonisolated(unsafe) private weak var model: SidebarUnreadModel? + nonisolated private let id: UUID + + fileprivate init(model: SidebarUnreadModel, id: UUID) { + self.model = model + self.id = id + } + + /// Stops delivering snapshot changes. + public func cancel() { + model?.removeSnapshotObserver(id) + model = nil + } + + deinit { + let model = model + let id = id + Task { @MainActor in + model?.removeSnapshotObserver(id) + } + } +} + +/// Main-actor unread source of truth for leaf UI projections. +/// +/// Mutations publish one equality-guarded snapshot. SwiftUI tracks ``snapshot`` +/// through Observation, while imperative consumers register weak-owner callbacks. +@MainActor +@Observable +public final class SidebarUnreadModel { + /// The latest complete unread state. + public private(set) var snapshot = SidebarUnreadSnapshot() + + /// Total unread count rendered by global badges. + public var totalUnreadCount: Int { snapshot.totalUnreadCount } + /// Current per-workspace unread summaries. + public var summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] { + snapshot.summaryByWorkspaceId + } + /// Current workspace and surface unread keys. + public var unreadSurfaceKeys: Set { snapshot.unreadSurfaceKeys } + /// Current focused read-indicator surfaces. + public var focusedReadIndicatorByWorkspaceId: [UUID: UUID] { + snapshot.focusedReadIndicatorByWorkspaceId + } + /// Workspaces explicitly marked unread. + public var manualUnreadWorkspaceIds: Set { snapshot.manualUnreadWorkspaceIds } + + @ObservationIgnored + private var snapshotObservers: [UUID: (SidebarUnreadSnapshot) -> Bool] = [:] + @ObservationIgnored + private var pendingSnapshots: [SidebarUnreadSnapshot] = [] + @ObservationIgnored + private var isPublishingSnapshot = false + + /// Creates an empty unread model. + public init() {} + + /// Observes changed snapshots synchronously after publication. + /// + /// The model retains neither `owner` nor the returned cancellation token. + public func observeChanges( + owner: Owner, + _ receive: @escaping @MainActor (Owner, SidebarUnreadSnapshot) -> Void + ) -> SidebarUnreadObservation { + let id = UUID() + snapshotObservers[id] = { [weak owner] snapshot in + guard let owner else { return false } + receive(owner, snapshot) + return true + } + return SidebarUnreadObservation(model: self, id: id) + } + + /// Atomically applies one complete unread state and publishes only changes. + public func apply( + totalUnreadCount: Int, + summaries: [UUID: SidebarWorkspaceUnreadSummary], + unreadSurfaceKeys: Set, + focusedReadIndicatorByWorkspaceId: [UUID: UUID], + manualUnreadWorkspaceIds: Set + ) { + let next = SidebarUnreadSnapshot( + totalUnreadCount: totalUnreadCount, + summaryByWorkspaceId: summaries, + unreadSurfaceKeys: unreadSurfaceKeys, + focusedReadIndicatorByWorkspaceId: focusedReadIndicatorByWorkspaceId, + manualUnreadWorkspaceIds: manualUnreadWorkspaceIds + ) + guard (pendingSnapshots.last ?? snapshot) != next else { return } + pendingSnapshots.append(next) + guard !isPublishingSnapshot else { return } + + isPublishingSnapshot = true + defer { + pendingSnapshots.removeAll(keepingCapacity: true) + isPublishingSnapshot = false + } + var publicationIndex = 0 + while publicationIndex < pendingSnapshots.count { + let publication = pendingSnapshots[publicationIndex] + publicationIndex += 1 + snapshot = publication + for id in Array(snapshotObservers.keys) { + guard let observer = snapshotObservers[id] else { continue } + if !observer(publication) { + snapshotObservers[id] = nil + } + } + } + } + + fileprivate func removeSnapshotObserver(_ id: UUID) { + snapshotObservers[id] = nil + } + + /// Returns the summary for one workspace. + public func summary(forWorkspaceId id: UUID) -> SidebarWorkspaceUnreadSummary { + snapshot.summary(forWorkspaceId: id) + } + + /// Returns the unread count for one workspace. + public func unreadCount(forWorkspaceId id: UUID) -> Int { + snapshot.unreadCount(forWorkspaceId: id) + } + + /// Returns the latest notification text for one workspace. + public func latestNotificationText(forWorkspaceId id: UUID) -> String? { + snapshot.latestNotificationText(forWorkspaceId: id) + } + + /// Returns whether one workspace is unread. + public func workspaceIsUnread(forWorkspaceId id: UUID) -> Bool { + snapshot.workspaceIsUnread(forWorkspaceId: id) + } + + /// Returns whether one workspace was manually marked unread. + public func hasManualUnread(forWorkspaceId id: UUID) -> Bool { + snapshot.hasManualUnread(forWorkspaceId: id) + } + + /// Returns whether a workspace or surface has an unread notification. + public func hasUnreadNotification(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { + snapshot.hasUnreadNotification(forWorkspaceId: id, surfaceId: surfaceId) + } + + /// Returns whether a surface should show its notification indicator. + public func hasVisibleNotificationIndicator(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { + snapshot.hasVisibleNotificationIndicator(forWorkspaceId: id, surfaceId: surfaceId) + } + + /// Returns whether any supplied workspace can be marked read. + public func canMarkWorkspaceRead(forWorkspaceIds ids: [UUID]) -> Bool { + snapshot.canMarkWorkspaceRead(forWorkspaceIds: ids) + } + + /// Returns whether any supplied workspace can be marked unread. + public func canMarkWorkspaceUnread(forWorkspaceIds ids: [UUID]) -> Bool { + snapshot.canMarkWorkspaceUnread(forWorkspaceIds: ids) + } +} diff --git a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift index 4e39da05e22b..f2b2bb423759 100644 --- a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift +++ b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift @@ -251,7 +251,7 @@ struct NotificationDismissalModelTests { #expect(host.log.contains("notificationFlash")) } - @Test func focusedWorkspaceDismissalUsesProjectedSurfaceIdentity() { + @Test func focusedWorkspaceDismissalStartsWithProjectedSurfaceIdentity() { let workspaceId = UUID(uuidString: "11111111-1111-1111-1111-111111111111")! let containerId = UUID(uuidString: "22222222-2222-2222-2222-222222222222")! let projectedSurfaceId = UUID(uuidString: "33333333-3333-3333-3333-333333333333")! @@ -269,8 +269,11 @@ struct NotificationDismissalModelTests { context: .explicitWorkspaceResume ) - #expect(host.log.contains("markRead:3333")) - #expect(!host.log.contains("markRead:2222")) + #expect(host.log == [ + "markRead:3333", "markRead:2222", + "clearFocusedRead:3333", "clearFocusedRead:2222", + "notificationFlash", + ]) } @Test func pendingSelectionContextTakeClearsIt() { diff --git a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift new file mode 100644 index 000000000000..3614e58c0163 --- /dev/null +++ b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/SidebarUnreadSnapshotTests.swift @@ -0,0 +1,167 @@ +import Foundation +import Observation +import os +import Testing +@testable import CmuxNotifications + +@Suite("Sidebar unread snapshot") +struct SidebarUnreadSnapshotTests { + @Test + func queriesResolveMissingAndSurfaceState() { + let workspaceID = UUID() + let surfaceID = UUID() + let snapshot = SidebarUnreadSnapshot( + totalUnreadCount: 2, + summaryByWorkspaceId: [ + workspaceID: SidebarWorkspaceUnreadSummary( + unreadCount: 2, + latestNotificationText: "Pi finished", + hasLatestNotification: true + ), + ], + unreadSurfaceKeys: [ + SidebarSurfaceUnreadKey(workspaceId: workspaceID, surfaceId: surfaceID), + ], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [workspaceID] + ) + + #expect(snapshot.totalUnreadCount == 2) + #expect(snapshot.unreadCount(forWorkspaceId: workspaceID) == 2) + #expect(snapshot.latestNotificationText(forWorkspaceId: workspaceID) == "Pi finished") + #expect(snapshot.hasManualUnread(forWorkspaceId: workspaceID)) + #expect(snapshot.hasVisibleNotificationIndicator( + forWorkspaceId: workspaceID, + surfaceId: surfaceID + )) + #expect(snapshot.summary(forWorkspaceId: UUID()).unreadCount == 0) + } + + @Test + func manualUnreadStateControlsWorkspaceActionsWithoutANotificationCount() { + let workspaceID = UUID() + let snapshot = SidebarUnreadSnapshot(manualUnreadWorkspaceIds: [workspaceID]) + + #expect(snapshot.workspaceIsUnread(forWorkspaceId: workspaceID)) + #expect(snapshot.canMarkWorkspaceRead(forWorkspaceIds: [workspaceID])) + #expect(!snapshot.canMarkWorkspaceUnread(forWorkspaceIds: [workspaceID])) + } + + @Test + @MainActor + func modelPublishesOnlyChangedAtomicSnapshots() { + let workspaceID = UUID() + let model = SidebarUnreadModel() + final class Recorder { + var snapshots: [SidebarUnreadSnapshot] = [] + } + let recorder = Recorder() + let observation = model.observeChanges(owner: recorder) { recorder, snapshot in + recorder.snapshots.append(snapshot) + } + + model.apply( + totalUnreadCount: 1, + summaries: [ + workspaceID: SidebarWorkspaceUnreadSummary( + unreadCount: 1, + latestNotificationText: "Pi finished" + ), + ], + unreadSurfaceKeys: [], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + #expect(recorder.snapshots == [model.snapshot]) + + let publicationCount = OSAllocatedUnfairLock(initialState: 0) + withObservationTracking { + _ = model.snapshot + } onChange: { + publicationCount.withLock { $0 += 1 } + } + model.apply( + totalUnreadCount: 1, + summaries: [ + workspaceID: SidebarWorkspaceUnreadSummary( + unreadCount: 1, + latestNotificationText: "Pi finished" + ), + ], + unreadSurfaceKeys: [], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + #expect( + publicationCount.withLock { $0 } == 0, + "An equivalent snapshot must not publish." + ) + + model.apply( + totalUnreadCount: 0, + summaries: [:], + unreadSurfaceKeys: [], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + #expect(recorder.snapshots.count == 2) + #expect(recorder.snapshots.last?.totalUnreadCount == 0) + #expect(recorder.snapshots.last?.summaryByWorkspaceId.isEmpty == true) + + observation.cancel() + model.apply( + totalUnreadCount: 1, + summaries: [:], + unreadSurfaceKeys: [], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + #expect(recorder.snapshots.count == 2) + } + + @Test + @MainActor + func reentrantPublicationsRemainOrderedForEveryObserver() { + final class Recorder { + var totals: [Int] = [] + } + final class ReentrancyState { + var didPublishNestedSnapshot = false + } + + let model = SidebarUnreadModel() + let first = Recorder() + let second = Recorder() + let reentrancy = ReentrancyState() + let receive: @MainActor (Recorder, SidebarUnreadSnapshot) -> Void = { recorder, snapshot in + recorder.totals.append(snapshot.totalUnreadCount) + guard !reentrancy.didPublishNestedSnapshot else { return } + reentrancy.didPublishNestedSnapshot = true + model.apply( + totalUnreadCount: 2, + summaries: [:], + unreadSurfaceKeys: [], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + } + let firstObservation = model.observeChanges(owner: first, receive) + let secondObservation = model.observeChanges(owner: second, receive) + defer { + firstObservation.cancel() + secondObservation.cancel() + } + + model.apply( + totalUnreadCount: 1, + summaries: [:], + unreadSurfaceKeys: [], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + + #expect(first.totals == [1, 2]) + #expect(second.totals == [1, 2]) + #expect(model.snapshot.totalUnreadCount == 2) + } +} diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index be9ebbbee0d2..9e80eb5655a1 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -862,7 +862,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent var debugFocusedTerminalKeyRepairObserverForTesting: ((NSWindow, NSEvent, NSResponder?) -> Void)? #endif private lazy var updateController = UpdateController(log: updateLog) - private lazy var titlebarAccessoryController = UpdateTitlebarAccessoryController(updateLog: updateLog, settingsRuntime: settingsRuntime) + private let titlebarControlsLayoutModel = TitlebarControlsLayoutModel() + private lazy var titlebarAccessoryController = UpdateTitlebarAccessoryController( + updateLog: updateLog, + settingsRuntime: settingsRuntime, + layoutModel: titlebarControlsLayoutModel + ) private let windowDecorationsController = WindowDecorationsController() private var menuBarExtraController: MenuBarExtraController? private var transientGlobalSearchMenuBarExtraController: MenuBarExtraController? @@ -8984,10 +8989,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent } #endif - let root = ContentView(updateViewModel: updateViewModel, windowId: windowId) + let root = ContentView( + updateViewModel: updateViewModel, + windowId: windowId, + titlebarControlsLayoutModel: titlebarControlsLayoutModel + ) .environmentObject(tabManager) .environmentObject(notificationStore) - .environmentObject(notificationStore.sidebarUnread) .environmentObject(sidebarState) .environmentObject(sidebarSelectionState) .environmentObject(fileExplorerState) diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index b61ca8e1d121..fd1f6ee840a7 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -1,4 +1,5 @@ import CmuxFoundation +import CmuxNotifications @_spi(CmuxHostTransport) import CmuxSidebar @_spi(CmuxHostTransport) import CmuxExtensionKit import AppKit @@ -132,12 +133,91 @@ private struct CMUXSidebarExtensionLimitedChoiceStore { } } +@MainActor +final class CMUXSidebarSnapshotCache { + private struct CachedUnreadState: Equatable { + let unreadCount: Int + let latestNotification: String? + + init(workspace: CmuxSidebarWorkspace) { + unreadCount = workspace.unreadCount + latestNotification = workspace.latestNotification + } + + init(summary: SidebarWorkspaceUnreadSummary) { + unreadCount = summary.unreadCount + latestNotification = summary.latestNotificationText + } + + var isEmpty: Bool { + unreadCount == 0 && latestNotification == nil + } + } + + private(set) var snapshot: CmuxSidebarSnapshot? + private var workspaceIndexByID: [UUID: Int] = [:] + private var unreadStateByWorkspaceID: [UUID: CachedUnreadState] = [:] + + func replace(with next: CmuxSidebarSnapshot) -> CmuxSidebarSnapshot { + guard let current = snapshot else { + store(next) + return next + } + guard current != next else { return current } + var contentComparableNext = next + contentComparableNext.sequence = current.sequence + guard current != contentComparableNext else { return current } + var updated = next + updated.sequence = max(next.sequence, current.sequence &+ 1) + store(updated) + return updated + } + + func applyUnread(_ unread: SidebarUnreadSnapshot) -> CmuxSidebarSnapshot? { + guard var next = snapshot else { return nil } + var candidateWorkspaceIDs = Set(unreadStateByWorkspaceID.keys) + candidateWorkspaceIDs.formUnion(unread.summaryByWorkspaceId.keys) + var changed = false + for workspaceID in candidateWorkspaceIDs { + guard let index = workspaceIndexByID[workspaceID] else { continue } + let state = CachedUnreadState(summary: unread.summary(forWorkspaceId: workspaceID)) + guard unreadStateByWorkspaceID[workspaceID] != state else { continue } + next.workspaces[index].unreadCount = state.unreadCount + next.workspaces[index].latestNotification = state.latestNotification + if state.isEmpty { + unreadStateByWorkspaceID[workspaceID] = nil + } else { + unreadStateByWorkspaceID[workspaceID] = state + } + changed = true + } + guard changed else { return nil } + next.sequence &+= 1 + snapshot = next + return next + } + + private func store(_ next: CmuxSidebarSnapshot) { + snapshot = next + workspaceIndexByID = Dictionary( + uniqueKeysWithValues: next.workspaces.enumerated().map { ($1.id, $0) } + ) + unreadStateByWorkspaceID = Dictionary( + uniqueKeysWithValues: next.workspaces.compactMap { workspace in + let state = CachedUnreadState(workspace: workspace) + return state.isEmpty ? nil : (workspace.id, state) + } + ) + } +} + struct CMUXInstalledExtensionSidebarHostView: View { private static let selectedExtensionBundleIDDefaultsKey = "cmuxExtensionSidebar.selectedExtensionBundleId" private static let selectedExtensionNameDefaultsKey = "cmuxExtensionSidebar.selectedExtensionName" var snapshotProvider: @MainActor () -> CmuxSidebarSnapshot var snapshotUpdateToken: UInt64 = 0 + let unreadSource: SidebarUnreadModel var actionHandler: @MainActor (CmuxSidebarAction) -> CmuxSidebarActionResult var onUseDefaultSidebar: @MainActor () -> Void = {} @@ -158,6 +238,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { @State private var isShowingAccessReview = false @State private var keptLimitedManifestKeys = CMUXSidebarExtensionLimitedChoiceStore().choices() @State private var hostReloadToken: UInt64 = 0 + @State private var snapshotCache = CMUXSidebarSnapshotCache() var body: some View { Group { @@ -173,7 +254,9 @@ struct CMUXInstalledExtensionSidebarHostView: View { xpcHost.attach( connection: connection, bundleIdentifier: identity.bundleIdentifier, - snapshotProvider: snapshotProvider, + snapshotProvider: { + snapshotCache.replace(with: snapshotProvider()) + }, actionHandler: actionHandler, onGrantChanged: { grant in effectiveGrant = grant @@ -253,14 +336,24 @@ struct CMUXInstalledExtensionSidebarHostView: View { } } .task { - xpcHost.update(snapshotProvider: snapshotProvider, actionHandler: actionHandler) + _ = snapshotCache.replace(with: snapshotProvider()) + xpcHost.update( + snapshotProvider: { snapshotCache.replace(with: snapshotProvider()) }, + actionHandler: actionHandler + ) await observeExtensionAvailability() } - .onChange(of: snapshotProvider().sequence) { _, _ in - xpcHost.sendSnapshotDidChange() + .background { + SidebarUnreadSnapshotObserver(source: unreadSource) { unreadSnapshot in + guard let snapshot = snapshotCache.applyUnread(unreadSnapshot) else { + return + } + xpcHost.sendSnapshotDidChange(snapshot) + } } .onChange(of: snapshotUpdateToken) { _, _ in - xpcHost.sendSnapshotDidChange() + let snapshot = snapshotCache.replace(with: snapshotProvider()) + xpcHost.sendSnapshotDidChange(snapshot) } .onDisappear { xpcHost.invalidate() @@ -1121,9 +1214,18 @@ private final class CMUXSidebarExtensionHostXPC { } func sendSnapshotDidChange() { - guard let extensionProxy, let snapshotProvider else { return } + guard let snapshotProvider else { return } + sendSnapshotDidChange(snapshotProvider()) + } + + func sendSnapshotDidChange(_ snapshot: CmuxSidebarSnapshot) { + guard let extensionProxy else { return } do { - extensionProxy.sidebarSnapshotDidChange(try CmuxSidebarXPCCodec.encodeSnapshot(filteredSnapshot(from: snapshotProvider))) + extensionProxy.sidebarSnapshotDidChange( + try CmuxSidebarXPCCodec.encodeSnapshot( + snapshot.filtered(for: allowedScopes, actionScopes: allowedActionScopes) + ) + ) } catch { #if DEBUG cmuxDebugLog("extension.sidebar.xpc.snapshot.encode.failed error=\(error.localizedDescription)") diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 15054416ee58..f3cb458856c4 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -4,6 +4,7 @@ import CmuxCommandPalette import CmuxCore import CmuxFeedback import CmuxFoundation +import CmuxNotifications import CmuxPanes import CmuxSettings import CmuxWorkspaces @@ -803,30 +804,67 @@ private final class SelectedWorkspaceDirectoryObserver: ObservableObject { } } +/// Restricts unread Observation invalidation to the subtree that reads the +/// snapshot instead of making `ContentView` or `VerticalTabsSidebar` observers. +private struct SidebarUnreadSnapshotReader: View { + let source: SidebarUnreadModel + let content: (SidebarUnreadSnapshot) -> Content + + init( + source: SidebarUnreadModel, + @ViewBuilder content: @escaping (SidebarUnreadSnapshot) -> Content + ) { + self.source = source + self.content = content + } + + var body: some View { + content(source.snapshot) + } +} + +/// Runs an imperative unread side effect from an isolated Observation leaf. +struct SidebarUnreadSnapshotObserver: View { + let source: SidebarUnreadModel + let action: @MainActor (SidebarUnreadSnapshot) -> Void + + var body: some View { + Color.clear + .frame(width: 0, height: 0) + .accessibilityHidden(true) + .onChange(of: source.snapshot) { _, snapshot in + action(snapshot) + } + } +} + struct ContentView: View { var updateViewModel: UpdateStateModel let windowId: UUID let featureFlags: CmuxFeatureFlags + let sidebarUnread: SidebarUnreadModel + let titlebarControlsLayoutModel: TitlebarControlsLayoutModel @MainActor init( updateViewModel: UpdateStateModel, windowId: UUID, - featureFlags: CmuxFeatureFlags? = nil + featureFlags: CmuxFeatureFlags? = nil, + sidebarUnread: SidebarUnreadModel? = nil, + titlebarControlsLayoutModel: TitlebarControlsLayoutModel? = nil ) { self.updateViewModel = updateViewModel self.windowId = windowId self.featureFlags = featureFlags ?? .shared + self.sidebarUnread = sidebarUnread ?? TerminalNotificationStore.shared.sidebarUnread + self.titlebarControlsLayoutModel = titlebarControlsLayoutModel + ?? TitlebarControlsLayoutModel() } @EnvironmentObject var tabManager: TabManager - // ContentView observes the coalesced unread projection, NOT the notification - // store. Reading `notificationStore` directly here would re-render the entire - // content view + sidebar on every notification publish (terminal/agent - // activity), which reconstructs every workspace row and starves the main - // thread (issue #2586 class; surfaced as scroll lag). `notificationStore` - // stays available as an unobserved singleton for actions and pass-down. - @EnvironmentObject var sidebarUnread: SidebarUnreadModel + // Unread state is read imperatively by actions and passed to leaf observers. + // ContentView itself must not observe it: one agent notification would + // otherwise rebuild the terminal, sidebar, and window chrome together. var notificationStore: TerminalNotificationStore { .shared } @EnvironmentObject var sidebarState: SidebarState @EnvironmentObject var sidebarSelectionState: SidebarSelectionState @@ -1013,8 +1051,12 @@ struct ContentView: View { return exactFitsWithinPane ? exactRect : paneRect } - private func tmuxWorkspacePaneWindowOverlayState(for window: NSWindow) -> TmuxWorkspacePaneOverlayRenderState? { + private func tmuxWorkspacePaneWindowOverlayState( + for window: NSWindow, + unreadSnapshot explicitUnreadSnapshot: SidebarUnreadSnapshot? = nil + ) -> TmuxWorkspacePaneOverlayRenderState? { guard let workspace = tabManager.selectedWorkspace else { return nil } + let unreadSnapshot = explicitUnreadSnapshot ?? sidebarUnread.snapshot let usesWorkspacePaneOverlay = TmuxOverlayExperimentSettings.target().usesWorkspacePaneOverlay let resolvedActivePaneBorderColorHex = WorkspaceTabColorSettings.normalizedHex(activePaneBorderColorHex) let shouldShowActivePaneBorder = shouldShowActivePaneBorder(for: workspace, colorHex: resolvedActivePaneBorderColorHex) @@ -1028,7 +1070,7 @@ struct ContentView: View { let unreadRects: [CGRect] if usesWorkspacePaneOverlay { - let isWorkspaceManuallyUnread = sidebarUnread.hasManualUnread(forWorkspaceId: workspace.id) + let isWorkspaceManuallyUnread = unreadSnapshot.hasManualUnread(forWorkspaceId: workspace.id) let workspaceManualUnreadPanelId = workspace.representativePanelIdForWorkspaceManualUnread() if let layoutSnapshot, let contentView { unreadRects = layoutSnapshot.panes.compactMap { pane in @@ -1040,7 +1082,7 @@ struct ContentView: View { } let shouldShowUnread = Workspace.shouldShowUnreadIndicator( - hasUnreadNotification: sidebarUnread.hasVisibleNotificationIndicator( + hasUnreadNotification: unreadSnapshot.hasVisibleNotificationIndicator( forWorkspaceId: workspace.id, surfaceId: panelId ), @@ -1137,9 +1179,15 @@ struct ContentView: View { ) } - private func refreshTmuxWorkspacePaneWindowOverlay(in window: NSWindow?) { + private func refreshTmuxWorkspacePaneWindowOverlay( + in window: NSWindow?, + unreadSnapshot: SidebarUnreadSnapshot? = nil + ) { guard let window else { return } - let tmuxOverlayState = tmuxWorkspacePaneWindowOverlayState(for: window) + let tmuxOverlayState = tmuxWorkspacePaneWindowOverlayState( + for: window, + unreadSnapshot: unreadSnapshot + ) WindowTmuxWorkspacePaneOverlayController.controller( for: window, createIfNeeded: tmuxOverlayState != nil @@ -1686,6 +1734,8 @@ struct ContentView: View { fileExplorerState: fileExplorerState, featureFlags: featureFlags, isPresented: sidebarState.isVisible, + sidebarUnread: sidebarUnread, + titlebarControlsLayoutModel: titlebarControlsLayoutModel, windowId: windowId, onSendFeedback: presentFeedbackComposer, onToggleSidebar: { sidebarState.toggle() }, @@ -2028,7 +2078,8 @@ struct ContentView: View { } private var fullscreenControls: some View { TitlebarControlsView( - notificationStore: TerminalNotificationStore.shared, + unreadModel: sidebarUnread, + layoutModel: titlebarControlsLayoutModel, viewModel: fullscreenControlsViewModel, onToggleSidebar: { sidebarState.toggle() }, onToggleNotifications: { [fullscreenControlsViewModel] in @@ -2062,8 +2113,7 @@ struct ContentView: View { /// Used to reserve space in the title row so the title flows to the right of /// the controls, which are themselves mounted once in the band overlay. private var fullscreenControlsWidth: CGFloat { - let style = TitlebarControlsStyle.stored(rawValue: titlebarControlsStyleRawValue) - return TitlebarControlsLayoutMetrics.contentSize(config: style.config).width + titlebarControlsLayoutModel.snapshot.contentSize.width } private var titlebarDebugChromeSnapshot: MinimalModeTitlebarDebugSnapshot { @@ -2838,6 +2888,17 @@ struct ContentView: View { scheduleTitlebarTextRefresh() }) + view = AnyView(view.background { + // Update the AppKit-owned pane overlay from a dedicated Observation + // leaf, without making ContentView itself an unread observer. + SidebarUnreadSnapshotObserver(source: sidebarUnread) { snapshot in + refreshTmuxWorkspacePaneWindowOverlay( + in: observedWindow, + unreadSnapshot: snapshot + ) + } + }) + view = AnyView(view.onReceive(NotificationCenter.default.publisher(for: .workspacePaneGeometryDidChange)) { notification in guard let tabId = notification.userInfo?[GhosttyNotificationKey.tabId] as? UUID, tabId == tabManager.selectedTabId else { return } @@ -10454,6 +10515,8 @@ struct VerticalTabsSidebar: View, Equatable { && lhs.updateViewModel === rhs.updateViewModel && lhs.fileExplorerState === rhs.fileExplorerState && lhs.featureFlags === rhs.featureFlags + && lhs.sidebarUnread === rhs.sidebarUnread + && lhs.titlebarControlsLayoutModel === rhs.titlebarControlsLayoutModel && lhs.isPresented == rhs.isPresented } @@ -10461,6 +10524,8 @@ struct VerticalTabsSidebar: View, Equatable { @ObservedObject var fileExplorerState: FileExplorerState var featureFlags: CmuxFeatureFlags = .shared var isPresented: Bool = true + let sidebarUnread: SidebarUnreadModel + let titlebarControlsLayoutModel: TitlebarControlsLayoutModel let windowId: UUID let onSendFeedback: () -> Void let onToggleSidebar: () -> Void @@ -10468,11 +10533,8 @@ struct VerticalTabsSidebar: View, Equatable { let observedWindowReference: WeakWindowReference var observedWindow: NSWindow? { observedWindowReference.window } @EnvironmentObject var tabManager: TabManager - // Observe the coalesced unread projection instead of the notification store - // so notification churn (terminal/agent activity) no longer reconstructs - // every workspace row. The store stays available as an unobserved singleton - // for context-menu actions and pass-down. See SidebarUnreadModel / #2586. - @EnvironmentObject var sidebarUnread: SidebarUnreadModel + // Plain reference by design. Native row and titlebar subscribers own the + // unread invalidation boundary, so this O(workspaces) root stays inert. var notificationStore: TerminalNotificationStore { .shared } @EnvironmentObject var cmuxConfigStore: CmuxConfigStore @Binding var selection: SidebarSelection @@ -10602,13 +10664,16 @@ struct VerticalTabsSidebar: View, Equatable { /// `ForEach(workspaces) { w in Text(w.title) }`) and re-render when it /// changes. A value snapshot built fresh each render, never the store /// itself, so it respects the sidebar snapshot-boundary rule. - private func customSidebarDataContext(now: Date) -> [String: SwiftValue] { + private func customSidebarDataContext( + now: Date, + unreadSnapshot: SidebarUnreadSnapshot + ) -> [String: SwiftValue] { let selectedId = tabManager.selectedTabId let workspaces = tabManager.tabs.enumerated().map { index, workspace in workspace.customSidebarWorkspaceSnapshot( index: index, selectedId: selectedId, - unreadCount: sidebarUnread.unreadCount(forWorkspaceId: workspace.id) + unreadCount: unreadSnapshot.unreadCount(forWorkspaceId: workspace.id) ) } let selectedWorkspace = tabManager.tabs.first { $0.id == selectedId } @@ -10616,7 +10681,7 @@ struct VerticalTabsSidebar: View, Equatable { workspaces: workspaces, selectedWorkspaceId: selectedId, selectedWorkspaceTitle: selectedWorkspace?.customTitle ?? selectedWorkspace?.title ?? "", - totalUnreadCount: sidebarUnread.totalUnreadCount, + totalUnreadCount: unreadSnapshot.totalUnreadCount, now: now ) return CustomSidebarDataContextBuilder().dataContext(for: snapshot) @@ -10762,7 +10827,8 @@ struct VerticalTabsSidebar: View, Equatable { private func minimalModeSidebarTitlebarControlsOverlay() -> some View { MinimalModeSidebarTitlebarControlsOverlay( - notificationStore: notificationStore, + unreadModel: sidebarUnread, + layoutModel: titlebarControlsLayoutModel, leadingInset: CGFloat(titlebarDebugChromeSnapshot.leftControlsLeadingInset), topPadding: minimalModeSidebarTitlebarControlsTopPadding, onToggleSidebar: onToggleSidebar, @@ -11090,8 +11156,13 @@ struct VerticalTabsSidebar: View, Equatable { ) } else { AnyView( - legacyWorkspaceScrollArea(renderContext: renderContext) - .onAppear { WindowTerminalPortal.usesCoalescedAnchorFailsafe = false } + SidebarUnreadSnapshotReader(source: sidebarUnread) { unreadSnapshot in + legacyWorkspaceScrollArea( + renderContext: renderContext, + unreadSnapshot: unreadSnapshot + ) + } + .onAppear { WindowTerminalPortal.usesCoalescedAnchorFailsafe = false } ) } } @@ -11155,7 +11226,10 @@ struct VerticalTabsSidebar: View, Equatable { } } - private func legacyWorkspaceScrollArea(renderContext: WorkspaceListRenderContext) -> some View { + private func legacyWorkspaceScrollArea( + renderContext: WorkspaceListRenderContext, + unreadSnapshot: SidebarUnreadSnapshot + ) -> some View { let scrollInsets = SidebarWorkspaceScrollInsets.workspaceList return GeometryReader { viewport in // Keep viewport geometry as a downward-only layout input. Writing @@ -11168,7 +11242,11 @@ struct VerticalTabsSidebar: View, Equatable { ) ScrollViewReader { scrollProxy in ScrollView(.vertical) { - workspaceScrollContent(renderContext: renderContext, minHeight: contentMinHeight) + workspaceScrollContent( + renderContext: renderContext, + minHeight: contentMinHeight, + unreadSnapshot: unreadSnapshot + ) } .coordinateSpace(name: SidebarPointerInteractionMonitor.coordinateSpaceName) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) @@ -11376,7 +11454,8 @@ struct VerticalTabsSidebar: View, Equatable { workspaceIds: isPresented ? renderContext.workspaceIds : tabManager.tabs.map(\.id), selectedWorkspaceId: selectedWorkspaceId, selectedScrollTargetWorkspaceId: selectedScrollTargetWorkspaceId, - isPresented: isPresented + isPresented: isPresented, + unreadSource: sidebarUnread ) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .mask( @@ -11472,7 +11551,10 @@ struct VerticalTabsSidebar: View, Equatable { // whether a change class re-renders the sidebar subtree or skips it. cmuxDebugLog("sidebar.table.rowsBuild items=\(renderContext.workspaceRenderItems.count)") #endif - let unreadSummariesByWorkspaceId = sidebarUnread.summaryByWorkspaceId + // AppKit applies the live unread snapshot inside its controller. Keep + // root row construction independent from notification publications. + let unreadSnapshot = SidebarUnreadSnapshot() + let unreadSummariesByWorkspaceId = unreadSnapshot.summaryByWorkspaceId let notificationIndex = SidebarWorkspaceNotificationIndex( notifications: notificationStore.notifications ) @@ -11493,7 +11575,7 @@ struct VerticalTabsSidebar: View, Equatable { group: group, memberWorkspaceIds: renderContext.memberWorkspaceIdsByGroupId[group.id] ?? [], renderContext: renderContext, - unreadSummariesByWorkspaceId: unreadSummariesByWorkspaceId, + unreadSnapshot: unreadSnapshot, notificationIndex: notificationIndex, shouldCollectWorkspaceDropTargets: false ) @@ -11851,7 +11933,18 @@ struct VerticalTabsSidebar: View, Equatable { actions: rowActions, groupId: input.groupId, isPinned: input.workspace.isPinned, - environment: environment + environment: environment, + unreadRebuild: { + [model, workspaceId = tab.id, + showsNotificationMessage = input.settings.showsNotificationMessage] snapshot in + let summary = snapshot.summary(forWorkspaceId: workspaceId) + var fresh = model + fresh.unreadCount = summary.unreadCount + fresh.latestNotificationText = showsNotificationMessage + ? summary.latestNotificationText + : nil + return fresh + } ) } @@ -11884,6 +11977,7 @@ struct VerticalTabsSidebar: View, Equatable { CMUXInstalledExtensionSidebarHostView( snapshotProvider: { cmuxSidebarSnapshotForCurrentTabs() }, snapshotUpdateToken: extensionSidebarUpdateToken, + unreadSource: sidebarUnread, actionHandler: { handleCMUXSidebarExtensionAction($0) }, onUseDefaultSidebar: { CmuxExtensionSidebarSelection.setProviderId(CmuxSidebarProviderDescriptor.defaultWorkspacesID) @@ -11919,18 +12013,23 @@ struct VerticalTabsSidebar: View, Equatable { // can mount the other renderer for one tick before flipping; // harmless (the host shuts the short-lived client down on // unmount). - TimelineView(.periodic(from: .now, by: 1)) { timeline in - CustomSidebarSurface( - fileURL: customSidebarURL, - dataContext: customSidebarDataContext(now: timeline.date), - dispatch: makeCmuxSidebarActionDispatch(), - contentInsets: CustomSidebarContentInsets( - top: SidebarWorkspaceScrollInsets.workspaceList.top, - bottom: SidebarWorkspaceScrollInsets.workspaceList.bottom - ), - rendersInProcess: customSidebarRenderer == .inProcess, - client: $sidebarRenderWorkerClient - ) + SidebarUnreadSnapshotReader(source: sidebarUnread) { unreadSnapshot in + TimelineView(.periodic(from: .now, by: 1)) { timeline in + CustomSidebarSurface( + fileURL: customSidebarURL, + dataContext: customSidebarDataContext( + now: timeline.date, + unreadSnapshot: unreadSnapshot + ), + dispatch: makeCmuxSidebarActionDispatch(), + contentInsets: CustomSidebarContentInsets( + top: SidebarWorkspaceScrollInsets.workspaceList.top, + bottom: SidebarWorkspaceScrollInsets.workspaceList.bottom + ), + rendersInProcess: customSidebarRenderer == .inProcess, + client: $sidebarRenderWorkerClient + ) + } } .mask( SidebarWorkspaceScrollEdgeFadeMask( @@ -11939,9 +12038,19 @@ struct VerticalTabsSidebar: View, Equatable { ) ) } else { - TimelineView(.periodic(from: .now, by: 30)) { timeline in - let model = extensionSidebarRenderModel(renderContext: renderContext, now: timeline.date) - extensionSidebarTimelineContent(renderContext: renderContext, model: model, now: timeline.date) + SidebarUnreadSnapshotReader(source: sidebarUnread) { unreadSnapshot in + TimelineView(.periodic(from: .now, by: 30)) { timeline in + let model = extensionSidebarRenderModel( + renderContext: renderContext, + unreadSnapshot: unreadSnapshot, + now: timeline.date + ) + extensionSidebarTimelineContent( + renderContext: renderContext, + model: model, + now: timeline.date + ) + } } } } @@ -12153,10 +12262,14 @@ struct VerticalTabsSidebar: View, Equatable { private func extensionSidebarRenderModel( renderContext: WorkspaceListRenderContext, + unreadSnapshot: SidebarUnreadSnapshot, now: Date ) -> CmuxSidebarProviderRenderModel { let _ = extensionSidebarUpdateToken - let snapshot = extensionSidebarSnapshot(renderContext: renderContext) + let snapshot = extensionSidebarSnapshot( + renderContext: renderContext, + unreadSnapshot: unreadSnapshot + ) return extensionSidebarRenderModel(snapshot: snapshot, now: now) } @@ -12184,13 +12297,20 @@ struct VerticalTabsSidebar: View, Equatable { } private func extensionSidebarSnapshot( - renderContext: WorkspaceListRenderContext + renderContext: WorkspaceListRenderContext, + unreadSnapshot: SidebarUnreadSnapshot ) -> CmuxSidebarProviderSnapshot { - extensionSidebarSnapshot(workspaces: renderContext.tabs) + extensionSidebarSnapshot( + workspaces: renderContext.tabs, + unreadSnapshot: unreadSnapshot + ) } private func extensionSidebarSnapshotForCurrentTabs() -> CmuxSidebarProviderSnapshot { - extensionSidebarSnapshot(workspaces: tabManager.tabs) + extensionSidebarSnapshot( + workspaces: tabManager.tabs, + unreadSnapshot: sidebarUnread.snapshot + ) } private func cmuxSidebarSnapshotForCurrentTabs() -> CmuxSidebarSnapshot { @@ -12409,16 +12529,24 @@ struct VerticalTabsSidebar: View, Equatable { } } - private func extensionSidebarSnapshot(workspaces: [Workspace]) -> CmuxSidebarProviderSnapshot { + private func extensionSidebarSnapshot( + workspaces: [Workspace], + unreadSnapshot: SidebarUnreadSnapshot + ) -> CmuxSidebarProviderSnapshot { CmuxSidebarProviderSnapshot( sequence: UInt64(max(0, CmuxEventBus.shared.latestSequence)), selectedWorkspaceId: tabManager.selectedTabId, - workspaces: workspaces.map(extensionWorkspaceSnapshot(for:)), + workspaces: workspaces.map { + extensionWorkspaceSnapshot(for: $0, unreadSnapshot: unreadSnapshot) + }, windowId: windowId ) } - private func extensionWorkspaceSnapshot(for workspace: Workspace) -> CmuxSidebarProviderWorkspace { + private func extensionWorkspaceSnapshot( + for workspace: Workspace, + unreadSnapshot: SidebarUnreadSnapshot + ) -> CmuxSidebarProviderWorkspace { let rootPath = extensionSidebarRootPath(for: workspace) return CmuxSidebarProviderWorkspace( id: workspace.id, @@ -12430,8 +12558,8 @@ struct VerticalTabsSidebar: View, Equatable { branchSummary: workspace.sidebarGitBranchesInDisplayOrder().first?.branch, remoteDisplayTarget: workspace.remoteDisplayTarget, remoteConnectionState: workspace.remoteConnectionState.rawValue, - unreadCount: sidebarUnread.unreadCount(forWorkspaceId: workspace.id), - latestNotificationText: sidebarUnread.latestNotificationText(forWorkspaceId: workspace.id), + unreadCount: unreadSnapshot.unreadCount(forWorkspaceId: workspace.id), + latestNotificationText: unreadSnapshot.latestNotificationText(forWorkspaceId: workspace.id), latestSubmittedMessage: workspace.latestSubmittedMessage, latestSubmittedAt: workspace.latestSubmittedAt, listeningPorts: workspace.listeningPorts, @@ -12953,7 +13081,13 @@ struct VerticalTabsSidebar: View, Equatable { } private func extensionWorkspaceSnapshot(for workspaceId: UUID) -> CmuxSidebarProviderWorkspace? { - tabManager.tabs.first { $0.id == workspaceId }.map(extensionWorkspaceSnapshot(for:)) + guard let workspace = tabManager.tabs.first(where: { $0.id == workspaceId }) else { + return nil + } + return extensionWorkspaceSnapshot( + for: workspace, + unreadSnapshot: sidebarUnread.snapshot + ) } private func extensionSidebarTreeSectionTitle(_ section: CmuxSidebarProviderTreeSection) -> String { @@ -13003,7 +13137,8 @@ struct VerticalTabsSidebar: View, Equatable { private func workspaceScrollContent( renderContext: WorkspaceListRenderContext, - minHeight: CGFloat + minHeight: CGFloat, + unreadSnapshot: SidebarUnreadSnapshot ) -> some View { let signpost = SidebarProfilingSignposts.begin("sidebar-scroll-content", "workspaces=\(renderContext.workspaceCount) renderItems=\(renderContext.workspaceRenderItems.count) minHeight=\(minHeight)"); defer { SidebarProfilingSignposts.end(signpost) } let shouldCollectWorkspaceDropTargets = SidebarDropPlanner().shouldCollectWorkspaceDropTargets( @@ -13018,7 +13153,8 @@ struct VerticalTabsSidebar: View, Equatable { // #5845; regressed by #6033). Drop/tap = background; indicator on rows. let content = workspaceRows( renderContext: renderContext, - shouldCollectWorkspaceDropTargets: shouldCollectWorkspaceDropTargets + shouldCollectWorkspaceDropTargets: shouldCollectWorkspaceDropTargets, + unreadSnapshot: unreadSnapshot ) .overlay(alignment: .bottom) { if emptyAreaTopDropIndicatorVisible() { @@ -13079,14 +13215,15 @@ struct VerticalTabsSidebar: View, Equatable { @ViewBuilder private func workspaceRows( renderContext: WorkspaceListRenderContext, - shouldCollectWorkspaceDropTargets: Bool + shouldCollectWorkspaceDropTargets: Bool, + unreadSnapshot: SidebarUnreadSnapshot ) -> some View { let signpost = SidebarProfilingSignposts.begin("sidebar-workspace-rows", "renderItems=\(renderContext.workspaceRenderItems.count) collectDropTargets=\(shouldCollectWorkspaceDropTargets)") let renderItems = renderContext.workspaceRenderItems // Reduce live models to cheap immutable values above the LazyVStack. // Shared notification/selection projections are built once here; full // row trees and row-specific closure binding remain lazy. - let unreadSummariesByWorkspaceId = sidebarUnread.summaryByWorkspaceId + let unreadSummariesByWorkspaceId = unreadSnapshot.summaryByWorkspaceId let notificationIndex = SidebarWorkspaceNotificationIndex( notifications: notificationStore.notifications ) @@ -13108,7 +13245,7 @@ struct VerticalTabsSidebar: View, Equatable { group: group, memberWorkspaceIds: renderContext.memberWorkspaceIdsByGroupId[group.id] ?? [], renderContext: renderContext, - unreadSummariesByWorkspaceId: unreadSummariesByWorkspaceId, + unreadSnapshot: unreadSnapshot, notificationIndex: notificationIndex, shouldCollectWorkspaceDropTargets: shouldCollectWorkspaceDropTargets ) diff --git a/Sources/DockPanelView.swift b/Sources/DockPanelView.swift index 7d616f9cc813..113cd4f70b16 100644 --- a/Sources/DockPanelView.swift +++ b/Sources/DockPanelView.swift @@ -1,6 +1,7 @@ import AppKit import Bonsplit import CmuxAppKitSupportUI +import CmuxNotifications import CmuxTerminal import SwiftUI diff --git a/Sources/DockUnreadPanelProjection.swift b/Sources/DockUnreadPanelProjection.swift index 1e4b5d5b9679..4ee1ace99d75 100644 --- a/Sources/DockUnreadPanelProjection.swift +++ b/Sources/DockUnreadPanelProjection.swift @@ -1,4 +1,4 @@ -import Combine +import CmuxNotifications import Foundation import Observation @@ -14,7 +14,7 @@ final class DockUnreadPanelProjection { @ObservationIgnored private var isActive = false @ObservationIgnored private var unreadSurfaceKeys: Set @ObservationIgnored private var focusedReadIndicatorByWorkspaceID: [UUID: UUID] - @ObservationIgnored private var unreadSubscription: AnyCancellable? + @ObservationIgnored private var unreadObservation: SidebarUnreadObservation? init( source: SidebarUnreadModel, @@ -25,20 +25,15 @@ final class DockUnreadPanelProjection { self.workspaceID = workspaceID self.panelIDs = panelIDs self.isActive = isActive - unreadSurfaceKeys = source.unreadSurfaceKeys - focusedReadIndicatorByWorkspaceID = source.focusedReadIndicatorByWorkspaceId + let initialSnapshot = source.snapshot + unreadSurfaceKeys = initialSnapshot.unreadSurfaceKeys + focusedReadIndicatorByWorkspaceID = initialSnapshot.focusedReadIndicatorByWorkspaceId refresh() - unreadSubscription = source.$unreadSurfaceKeys.combineLatest( - source.$focusedReadIndicatorByWorkspaceId - ).sink { [weak self] unreadSurfaceKeys, focusedReadIndicatorByWorkspaceID in - // Both publishers are main-actor-owned and publish synchronously - // from SidebarUnreadModel.apply(). - MainActor.assumeIsolated { - self?.receive( - unreadSurfaceKeys: unreadSurfaceKeys, - focusedReadIndicatorByWorkspaceID: focusedReadIndicatorByWorkspaceID - ) - } + unreadObservation = source.observeChanges(owner: self) { projection, snapshot in + projection.receive( + unreadSurfaceKeys: snapshot.unreadSurfaceKeys, + focusedReadIndicatorByWorkspaceID: snapshot.focusedReadIndicatorByWorkspaceId + ) } } diff --git a/Sources/MinimalModeSidebarTitlebarControlsOverlay.swift b/Sources/MinimalModeSidebarTitlebarControlsOverlay.swift index 830cdb348947..4e3f2412a2a9 100644 --- a/Sources/MinimalModeSidebarTitlebarControlsOverlay.swift +++ b/Sources/MinimalModeSidebarTitlebarControlsOverlay.swift @@ -1,8 +1,10 @@ import AppKit +import CmuxNotifications import SwiftUI struct MinimalModeSidebarTitlebarControlsOverlay: View { - let notificationStore: TerminalNotificationStore + let unreadModel: SidebarUnreadModel + let layoutModel: TitlebarControlsLayoutModel let leadingInset: CGFloat let topPadding: CGFloat let onToggleSidebar: () -> Void @@ -21,7 +23,8 @@ struct MinimalModeSidebarTitlebarControlsOverlay: View { var body: some View { if isMinimalMode { HiddenTitlebarSidebarControlsView( - notificationStore: notificationStore, + unreadModel: unreadModel, + layoutModel: layoutModel, onToggleSidebar: onToggleSidebar, onToggleNotifications: onToggleNotifications, onNewTab: onNewTab, diff --git a/Sources/Mobile/MobileHostIdentity.swift b/Sources/Mobile/MobileHostIdentity.swift index 22acbcc6c11f..8a8620547065 100644 --- a/Sources/Mobile/MobileHostIdentity.swift +++ b/Sources/Mobile/MobileHostIdentity.swift @@ -28,7 +28,7 @@ enum MobileHostIdentity { bundleIdentifier: String? = Bundle.main.bundleIdentifier ) -> String { if let id = readSharedDeviceID(from: sharedIDURL) { - defaults.set(id, forKey: deviceIDKey) + persistDeviceIDIfNeeded(id, defaults: defaults) return id } @@ -83,10 +83,16 @@ enum MobileHostIdentity { return normalizedID(existing) } + private static func persistDeviceIDIfNeeded(_ id: String, defaults: UserDefaults) { + let stored = normalizedID(defaults.string(forKey: deviceIDKey)) + guard stored != id else { return } + defaults.set(id, forKey: deviceIDKey) + } + private static func settleSharedDeviceID(_ candidate: String, defaults: UserDefaults, sharedIDURL: URL?) -> String { let candidate = cmxCanonicalDeviceID(candidate) guard let sharedIDURL else { - defaults.set(candidate, forKey: deviceIDKey) + persistDeviceIDIfNeeded(candidate, defaults: defaults) return candidate } try? FileManager.default.createDirectory( @@ -96,13 +102,13 @@ enum MobileHostIdentity { let data = Data(candidate.utf8) if !FileManager.default.createFile(atPath: sharedIDURL.path, contents: data) { if let winner = readSharedDeviceID(from: sharedIDURL) { - defaults.set(winner, forKey: deviceIDKey) + persistDeviceIDIfNeeded(winner, defaults: defaults) return winner } try? data.write(to: sharedIDURL, options: .atomic) } let settled = readSharedDeviceID(from: sharedIDURL) ?? candidate - defaults.set(settled, forKey: deviceIDKey) + persistDeviceIDIfNeeded(settled, defaults: defaults) return settled } diff --git a/Sources/Panels/CustomSidebarPaneDataContextCache.swift b/Sources/Panels/CustomSidebarPaneDataContextCache.swift index cc5f712e2759..39b35069abce 100644 --- a/Sources/Panels/CustomSidebarPaneDataContextCache.swift +++ b/Sources/Panels/CustomSidebarPaneDataContextCache.swift @@ -1,4 +1,5 @@ import CmuxSidebar +import CmuxNotifications import CmuxSwiftRender import Foundation diff --git a/Sources/Panels/CustomSidebarPanelView.swift b/Sources/Panels/CustomSidebarPanelView.swift index 5fe8535d7609..e20c23d82e2d 100644 --- a/Sources/Panels/CustomSidebarPanelView.swift +++ b/Sources/Panels/CustomSidebarPanelView.swift @@ -1,4 +1,5 @@ import CmuxAppKitSupportUI +import CmuxNotifications import CmuxSettings import CmuxSettingsUI import CmuxSidebar diff --git a/Sources/Panels/PanelContentView.swift b/Sources/Panels/PanelContentView.swift index 8e868a7193a6..ca69eabbbd02 100644 --- a/Sources/Panels/PanelContentView.swift +++ b/Sources/Panels/PanelContentView.swift @@ -1,4 +1,5 @@ import CmuxFoundation +import CmuxNotifications import SwiftUI import Foundation import Bonsplit diff --git a/Sources/Sidebar/AppKitList/Cells/SidebarGroupHeaderRowModel.swift b/Sources/Sidebar/AppKitList/Cells/SidebarGroupHeaderRowModel.swift index a1afc9bf8249..916e5d403ebf 100644 --- a/Sources/Sidebar/AppKitList/Cells/SidebarGroupHeaderRowModel.swift +++ b/Sources/Sidebar/AppKitList/Cells/SidebarGroupHeaderRowModel.swift @@ -2,7 +2,7 @@ import AppKit import CoreGraphics import Foundation -/// Immutable render input for one pure-AppKit sidebar group header row. +/// Value-snapshot render input for one pure-AppKit sidebar group header row. /// /// Value fields only: action closures live in ``SidebarGroupHeaderRowActions`` /// and are excluded from equality so recycled cells can reconfigure cheaply @@ -19,12 +19,12 @@ struct SidebarGroupHeaderRowModel: Equatable, Hashable { let isMultiSelected: Bool let multiSelectionBackgroundStyle: SidebarWorkspaceRowBackgroundStyle let memberCount: Int - let anchorUnreadCount: Int - let canMarkRead: Bool - let canMarkUnread: Bool - let hasLatestNotifications: Bool - let canMarkAllRead: Bool - let canMarkAllUnread: Bool + var anchorUnreadCount: Int + var canMarkRead: Bool + var canMarkUnread: Bool + var hasLatestNotifications: Bool + var canMarkAllRead: Bool + var canMarkAllUnread: Bool /// Resolved modifier-hold hint (for example "⌘3"); nil hides the pill. let shortcutHintText: String? let shortcutHintXOffset: Double diff --git a/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowModel.swift b/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowModel.swift index 718f22245070..7c538108c73d 100644 --- a/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowModel.swift +++ b/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowModel.swift @@ -21,8 +21,8 @@ struct SidebarWorkspaceRowModel: Equatable { var isMultiSelected: Bool let canCloseWorkspace: Bool let accessibilityWorkspaceCount: Int - let unreadCount: Int - let latestNotificationText: String? + var unreadCount: Int + var latestNotificationText: String? let showsAgentActivity: Bool let rowSpacing: CGFloat let isBeingDragged: Bool diff --git a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift index c1f608b1eaf5..ce8f67a8cdd6 100644 --- a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift +++ b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableController.swift @@ -2,6 +2,7 @@ import AppKit import Bonsplit import CmuxAppKitSupportUI import CmuxFoundation +import CmuxNotifications import SwiftUI /// Main-actor owner of the default sidebar table lifecycle and its AppKit interactions. @@ -31,6 +32,9 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS private var appKitDropIndicator: SidebarDropIndicator? private var appKitDropIndicatorScope: SidebarWorkspaceReorderDropIndicatorScope = .raw private var appKitDropIndicatorIncludesRowTargets = false + private weak var unreadSource: SidebarUnreadModel? + private var unreadSnapshot = SidebarUnreadSnapshot() + private var unreadObservation: SidebarUnreadObservation? private var clipBoundsObserver: NSObjectProtocol? private var resizeDidEndObserver: NSObjectProtocol? private lazy var mutationScheduler = SidebarWorkspaceTableMutationScheduler( @@ -156,6 +160,10 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS let postUpdateActions = detachLoadedCells() workspaceDragSessionDidEnd() actions = nil + unreadObservation?.cancel() + unreadObservation = nil + unreadSource = nil + unreadSnapshot = SidebarUnreadSnapshot() rows.removeAll(keepingCapacity: false) workspaceIds.removeAll(keepingCapacity: false) selectedScrollTargetWorkspaceId = nil @@ -172,6 +180,58 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS mutationScheduler.stagePostUpdateActions(postUpdateActions) } + /// Installs one unread subscription for the native table. Snapshot changes + /// are projected directly into affected visible cells, bypassing SwiftUI's + /// `VerticalTabsSidebar.body` and its O(workspaces) row construction. + func setUnreadSource(_ source: SidebarUnreadModel) { + guard unreadSource !== source else { return } + unreadObservation?.cancel() + unreadSource = source + applyUnreadSnapshot(source.snapshot) + unreadObservation = source.observeChanges(owner: self) { controller, snapshot in + controller.applyUnreadSnapshot(snapshot) + } + } + + private func applyUnreadSnapshot(_ nextSnapshot: SidebarUnreadSnapshot) { + let previousSnapshot = unreadSnapshot + unreadSnapshot = nextSnapshot + guard isPresentationActive, let table = containerView?.tableView else { return } + + let candidateIds = Set(previousSnapshot.summaryByWorkspaceId.keys) + .union(nextSnapshot.summaryByWorkspaceId.keys) + let changedWorkspaceIds = Set(candidateIds.filter { + previousSnapshot.summary(forWorkspaceId: $0) + != nextSnapshot.summary(forWorkspaceId: $0) + }) + guard !changedWorkspaceIds.isEmpty else { return } + + var changedRows = IndexSet() + for row in rows.indices { + let configuration = rows[row] + guard !configuration.appKitUnreadDependencyWorkspaceIds.isDisjoint( + with: changedWorkspaceIds + ) else { + continue + } + let updated = configuration.applyingUnreadSnapshot(nextSnapshot) + guard !configuration.hasEquivalentContent(to: updated) else { continue } + rows[row] = updated + changedRows.insert(row) + } + guard !changedRows.isEmpty else { return } + + let heightChanges = rowHeightCache.prepareRows( + at: changedRows, + in: rows, + columnWidth: currentColumnWidth() + ) + reconfigureVisibleRows(changedRows) + if !heightChanges.isEmpty { + noteHeightOfRowsWithoutAnimation(table, heightChanges) + } + } + func setPresentationActive(_ isActive: Bool, workspaceIds liveWorkspaceIds: [UUID]) { guard isPresentationActive != isActive else { if !isActive { @@ -277,7 +337,7 @@ final class SidebarWorkspaceTableController: NSObject, NSTableViewDataSource, NS private func flushApply(_ input: SidebarWorkspaceTableApplyInput) { guard isPresentationActive, let containerView else { return } - let nextRows = input.rows + let nextRows = input.rows.map { $0.applyingUnreadSnapshot(unreadSnapshot) } let actions = input.actions let nextWorkspaceIds = input.workspaceIds let selectedWorkspaceId = input.selectedWorkspaceId diff --git a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableRowConfiguration.swift b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableRowConfiguration.swift index 8a21ea699fc4..8790b4c03690 100644 --- a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableRowConfiguration.swift +++ b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableRowConfiguration.swift @@ -1,3 +1,4 @@ +import CmuxNotifications import SwiftUI struct SidebarWorkspaceTableContextMenuActions { @@ -39,6 +40,12 @@ struct SidebarWorkspaceTableRowConfiguration { /// pump (metadata/branch/PR updates repaint one cell, no container render). let appKitWorkspaceRowWorkspace: Workspace? let appKitWorkspaceRowRebuild: (@MainActor () -> SidebarWorkspaceRowModel)? + /// Workspace ids whose unread summaries affect this row, plus factories + /// that repaint only the matching AppKit cell from the latest atomic + /// unread snapshot. They are intentionally excluded from row equality. + let appKitUnreadDependencyWorkspaceIds: Set + let appKitWorkspaceUnreadRebuild: (@MainActor (SidebarUnreadSnapshot) -> SidebarWorkspaceRowModel)? + let appKitGroupHeaderUnreadRebuild: (@MainActor (SidebarUnreadSnapshot) -> SidebarGroupHeaderRowModel)? private let environment: SidebarWorkspaceTableEnvironmentSnapshot private let equivalenceValue: Any @@ -69,6 +76,9 @@ struct SidebarWorkspaceTableRowConfiguration { self.appKitWorkspaceRowActions = nil self.appKitWorkspaceRowWorkspace = nil self.appKitWorkspaceRowRebuild = nil + self.appKitUnreadDependencyWorkspaceIds = [] + self.appKitWorkspaceUnreadRebuild = nil + self.appKitGroupHeaderUnreadRebuild = nil self.environment = environment self.equivalenceValue = equivalenceValue self.isEquivalentValue = isEquivalentValue @@ -97,6 +107,9 @@ struct SidebarWorkspaceTableRowConfiguration { self.appKitWorkspaceRowActions = nil self.appKitWorkspaceRowWorkspace = nil self.appKitWorkspaceRowRebuild = nil + self.appKitUnreadDependencyWorkspaceIds = [] + self.appKitWorkspaceUnreadRebuild = nil + self.appKitGroupHeaderUnreadRebuild = nil self.equivalenceValue = equivalenceValue self.isEquivalentValue = { value in guard let value = value as? Content else { return false } @@ -107,7 +120,9 @@ struct SidebarWorkspaceTableRowConfiguration { init( groupHeaderModel: SidebarGroupHeaderRowModel, actions: SidebarGroupHeaderRowActions, - environment: SidebarWorkspaceTableEnvironmentSnapshot + environment: SidebarWorkspaceTableEnvironmentSnapshot, + unreadDependencyWorkspaceIds: Set = [], + unreadRebuild: (@MainActor (SidebarUnreadSnapshot) -> SidebarGroupHeaderRowModel)? = nil ) { self.id = .group(groupHeaderModel.groupId) self.workspaceId = groupHeaderModel.anchorWorkspaceId @@ -122,6 +137,9 @@ struct SidebarWorkspaceTableRowConfiguration { self.appKitWorkspaceRowActions = nil self.appKitWorkspaceRowWorkspace = nil self.appKitWorkspaceRowRebuild = nil + self.appKitUnreadDependencyWorkspaceIds = unreadDependencyWorkspaceIds + self.appKitWorkspaceUnreadRebuild = nil + self.appKitGroupHeaderUnreadRebuild = unreadRebuild self.equivalenceValue = groupHeaderModel self.isEquivalentValue = { value in guard let value = value as? SidebarGroupHeaderRowModel else { return false } @@ -136,7 +154,8 @@ struct SidebarWorkspaceTableRowConfiguration { isPinned: Bool, environment: SidebarWorkspaceTableEnvironmentSnapshot, workspace: Workspace? = nil, - rebuild: (@MainActor () -> SidebarWorkspaceRowModel)? = nil + rebuild: (@MainActor () -> SidebarWorkspaceRowModel)? = nil, + unreadRebuild: (@MainActor (SidebarUnreadSnapshot) -> SidebarWorkspaceRowModel)? = nil ) { self.id = .workspace(workspaceRowModel.workspaceId) self.workspaceId = workspaceRowModel.workspaceId @@ -151,6 +170,9 @@ struct SidebarWorkspaceTableRowConfiguration { self.appKitWorkspaceRowActions = actions self.appKitWorkspaceRowWorkspace = workspace self.appKitWorkspaceRowRebuild = rebuild + self.appKitUnreadDependencyWorkspaceIds = [workspaceRowModel.workspaceId] + self.appKitWorkspaceUnreadRebuild = unreadRebuild + self.appKitGroupHeaderUnreadRebuild = nil self.equivalenceValue = workspaceRowModel self.isEquivalentValue = { value in guard let value = value as? SidebarWorkspaceRowModel else { return false } @@ -163,6 +185,37 @@ struct SidebarWorkspaceTableRowConfiguration { && isEquivalentValue(other.equivalenceValue) } + func applyingUnreadSnapshot(_ snapshot: SidebarUnreadSnapshot) -> Self { + if let rebuild = appKitWorkspaceUnreadRebuild, + let actions = appKitWorkspaceRowActions { + let model = rebuild(snapshot) + guard model != appKitWorkspaceRowModel else { return self } + return Self( + workspaceRowModel: model, + actions: actions, + groupId: groupId, + isPinned: isPinned, + environment: environment, + workspace: appKitWorkspaceRowWorkspace, + rebuild: appKitWorkspaceRowRebuild, + unreadRebuild: rebuild + ) + } + if let rebuild = appKitGroupHeaderUnreadRebuild, + let actions = appKitGroupHeaderActions { + let model = rebuild(snapshot) + guard model != appKitGroupHeaderModel else { return self } + return Self( + groupHeaderModel: model, + actions: actions, + environment: environment, + unreadDependencyWorkspaceIds: appKitUnreadDependencyWorkspaceIds, + unreadRebuild: rebuild + ) + } + return self + } + /// Keeps the immutable paint model while dropping every live action, /// workspace, and hosted-content capture during retained hidden display. func presentationSnapshot() -> Self { diff --git a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableView.swift b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableView.swift index 4dd14b652d31..821c1a3e153b 100644 --- a/Sources/Sidebar/AppKitList/SidebarWorkspaceTableView.swift +++ b/Sources/Sidebar/AppKitList/SidebarWorkspaceTableView.swift @@ -1,3 +1,4 @@ +import CmuxNotifications import SwiftUI /// Container-level bridge mounting the AppKit-owned default workspace list once. @@ -8,6 +9,7 @@ struct SidebarWorkspaceTableView: NSViewRepresentable { let selectedWorkspaceId: UUID? let selectedScrollTargetWorkspaceId: UUID? let isPresented: Bool + let unreadSource: SidebarUnreadModel #if DEBUG @Environment(\.sidebarLazyContractProbe) private var sidebarLazyContractProbe @@ -25,6 +27,7 @@ struct SidebarWorkspaceTableView: NSViewRepresentable { #if DEBUG context.coordinator.reconfigurationProbe = sidebarLazyContractProbe.tableRootViewReconfigure #endif + context.coordinator.setUnreadSource(unreadSource) context.coordinator.setPresentationActive(isPresented, workspaceIds: workspaceIds) guard isPresented else { return } context.coordinator.apply( diff --git a/Sources/TerminalNotificationStore.swift b/Sources/TerminalNotificationStore.swift index 1c8858e9ffaa..9de79c65c61d 100644 --- a/Sources/TerminalNotificationStore.swift +++ b/Sources/TerminalNotificationStore.swift @@ -1,5 +1,7 @@ import CmuxFoundation +import CmuxNotifications import AppKit +import Combine import Foundation import os import UserNotifications @@ -548,15 +550,17 @@ final class TerminalNotificationStore: ObservableObject { result.reserveCapacity(ids.count) for id in ids { let count = unreadCount(forTabId: id) - let latestText: String? = indexes.latestByTabId[id].flatMap { notification in + let latestNotification = indexes.latestByTabId[id] + let latestText: String? = latestNotification.flatMap { notification in let text = notification.body.isEmpty ? notification.title : notification.body let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) return trimmed.isEmpty ? nil : trimmed } - if count == 0, latestText == nil { continue } + if count == 0, latestNotification == nil { continue } result[id] = SidebarWorkspaceUnreadSummary( unreadCount: count, - latestNotificationText: latestText + latestNotificationText: latestText, + hasLatestNotification: latestNotification != nil ) } return result @@ -2307,99 +2311,3 @@ final class TerminalNotificationStore: ObservableObject { NSApp?.dockTile.badgeLabel = label } } - -/// Immutable per-workspace unread projection rendered by the sidebar. Equatable -/// so the coalesced model only republishes when a workspace's badge or -/// latest-message text actually changes. `latestNotificationText` is the -/// trimmed body-or-title of the latest notification (read or unread) and is NOT -/// gated by the `showsSidebarNotificationMessage` setting; the sidebar applies -/// that gate at its read site. -struct SidebarWorkspaceUnreadSummary: Equatable { - var unreadCount: Int - var latestNotificationText: String? -} - -/// Workspace + surface pair used to mirror the store's per-surface unread set. -struct SidebarSurfaceUnreadKey: Hashable { - var workspaceId: UUID - var surfaceId: UUID? -} - -/// Lightweight observable that the workspace sidebar and `ContentView` observe -/// instead of `TerminalNotificationStore`. `TerminalNotificationStore` drives it -/// from its single `refreshUnreadPresentation()` coalescing hub with equality -/// guards, so notification activity that does not change any workspace's badge, -/// latest-text, per-surface unread, or read-indicator never fires -/// `objectWillChange` here. That is what stops high-frequency notification churn -/// from re-rendering the workspace list (issue #2586 class of sidebar re-render -/// spins). The query methods mirror the equivalent `TerminalNotificationStore` -/// reads exactly so callers can switch source without behavior change. -@MainActor -final class SidebarUnreadModel: ObservableObject { - @Published private(set) var totalUnreadCount: Int = 0 - @Published private(set) var summaryByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary] = [:] - @Published private(set) var unreadSurfaceKeys: Set = [] - @Published private(set) var focusedReadIndicatorByWorkspaceId: [UUID: UUID] = [:] - @Published private(set) var manualUnreadWorkspaceIds: Set = [] - - func apply( - totalUnreadCount: Int, - summaries: [UUID: SidebarWorkspaceUnreadSummary], - unreadSurfaceKeys: Set, - focusedReadIndicatorByWorkspaceId: [UUID: UUID], - manualUnreadWorkspaceIds: Set - ) { - if self.totalUnreadCount != totalUnreadCount { - self.totalUnreadCount = totalUnreadCount - } - if summaryByWorkspaceId != summaries { - summaryByWorkspaceId = summaries - } - if self.unreadSurfaceKeys != unreadSurfaceKeys { - self.unreadSurfaceKeys = unreadSurfaceKeys - } - if self.focusedReadIndicatorByWorkspaceId != focusedReadIndicatorByWorkspaceId { - self.focusedReadIndicatorByWorkspaceId = focusedReadIndicatorByWorkspaceId - } - if self.manualUnreadWorkspaceIds != manualUnreadWorkspaceIds { - self.manualUnreadWorkspaceIds = manualUnreadWorkspaceIds - } - } - - func summary(forWorkspaceId id: UUID) -> SidebarWorkspaceUnreadSummary { - summaryByWorkspaceId[id] ?? SidebarWorkspaceUnreadSummary(unreadCount: 0, latestNotificationText: nil) - } - - func unreadCount(forWorkspaceId id: UUID) -> Int { - summary(forWorkspaceId: id).unreadCount - } - - func latestNotificationText(forWorkspaceId id: UUID) -> String? { - summary(forWorkspaceId: id).latestNotificationText - } - - func workspaceIsUnread(forWorkspaceId id: UUID) -> Bool { - unreadCount(forWorkspaceId: id) > 0 - } - - func hasManualUnread(forWorkspaceId id: UUID) -> Bool { - manualUnreadWorkspaceIds.contains(id) - } - - func hasUnreadNotification(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { - unreadSurfaceKeys.contains(SidebarSurfaceUnreadKey(workspaceId: id, surfaceId: surfaceId)) - } - - func hasVisibleNotificationIndicator(forWorkspaceId id: UUID, surfaceId: UUID?) -> Bool { - hasUnreadNotification(forWorkspaceId: id, surfaceId: surfaceId) || - (focusedReadIndicatorByWorkspaceId[id].map { $0 == surfaceId } ?? false) - } - - func canMarkWorkspaceRead(forWorkspaceIds ids: [UUID]) -> Bool { - ids.contains { workspaceIsUnread(forWorkspaceId: $0) } - } - - func canMarkWorkspaceUnread(forWorkspaceIds ids: [UUID]) -> Bool { - ids.contains { !workspaceIsUnread(forWorkspaceId: $0) } - } -} diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index 719a4ce67b85..66df7d5750a2 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -2,9 +2,11 @@ import AppKit import Bonsplit import Combine import CmuxFoundation +import CmuxNotifications import CmuxSettings import CmuxSettingsUI import CmuxTestSupport +import Observation import SwiftUI enum TitlebarControlsStyle: Int, CaseIterable, Identifiable { @@ -139,6 +141,116 @@ struct TitlebarControlsStyleConfig { let hoverBackground: Bool } +struct TitlebarControlsLayoutModelSnapshot: Equatable { + let style: TitlebarControlsStyle + let contentSize: NSSize +} + +/// Owns the expensive shortcut/font-derived titlebar size once for every +/// titlebar surface. Unrelated defaults and notification activity must not +/// invalidate titlebar geometry. +@MainActor +@Observable +final class TitlebarControlsLayoutModel { + typealias ContentSizeProvider = (TitlebarControlsStyleConfig) -> NSSize + + private(set) var snapshot: TitlebarControlsLayoutModelSnapshot + + private let defaults: UserDefaults + @ObservationIgnored + private let notificationCenter: NotificationCenter + private let contentSizeProvider: ContentSizeProvider + @ObservationIgnored + private nonisolated(unsafe) var observers: [NSObjectProtocol] = [] + + init( + defaults: UserDefaults = .standard, + notificationCenter: NotificationCenter = .default, + contentSizeProvider: @escaping ContentSizeProvider = { + TitlebarControlsLayoutMetrics.contentSize(config: $0) + } + ) { + self.defaults = defaults + self.notificationCenter = notificationCenter + self.contentSizeProvider = contentSizeProvider + let style = TitlebarControlsStyle.stored(in: defaults) + snapshot = TitlebarControlsLayoutModelSnapshot( + style: style, + contentSize: contentSizeProvider(style.config) + ) + + observers.append( + notificationCenter.addObserver( + forName: UserDefaults.didChangeNotification, + object: nil, + queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + self?.refreshStyleIfNeeded() + } + } + ) + observers.append( + notificationCenter.addObserver( + forName: KeyboardShortcutSettings.didChangeNotification, + object: nil, + queue: .main + ) { [weak self] notification in + MainActor.assumeIsolated { + guard let self, self.shortcutChangeAffectsLayout(notification) else { return } + self.recompute() + } + } + ) + observers.append( + notificationCenter.addObserver( + forName: GlobalFontMagnification.didChangeNotification, + object: nil, + queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + self?.recompute() + } + } + ) + } + + deinit { + removeObservers() + } + + private nonisolated func removeObservers() { + for observer in observers { + notificationCenter.removeObserver(observer) + } + observers.removeAll() + } + + private func refreshStyleIfNeeded() { + let style = TitlebarControlsStyle.stored(in: defaults) + guard style != snapshot.style else { return } + recompute(style: style) + } + + private func shortcutChangeAffectsLayout(_ notification: Notification) -> Bool { + guard let rawAction = notification.userInfo?[KeyboardShortcutSettings.actionUserInfoKey] + as? String, + let action = KeyboardShortcutSettings.Action(rawValue: rawAction) else { + // Bulk and settings-file reloads intentionally omit one action. + return true + } + return TitlebarShortcutHintActionSlot.allCases.contains { $0.action == action } + } + + private func recompute(style: TitlebarControlsStyle? = nil) { + let style = style ?? snapshot.style + snapshot = TitlebarControlsLayoutModelSnapshot( + style: style, + contentSize: contentSizeProvider(style.config) + ) + } +} + enum TitlebarControlsVisualMetrics { static let verticalLift: CGFloat = 0 @@ -869,8 +981,31 @@ private final class TitlebarControlRightClickNSView: NSView { } } +private struct TitlebarNotificationBadge: View { + let unreadModel: SidebarUnreadModel + let config: TitlebarControlsStyleConfig + @Environment(\.cmuxGlobalFontMagnificationPercent) private var globalFontPercent + + var body: some View { + let unreadCount = unreadModel.totalUnreadCount + if unreadCount > 0 { + Text("\(min(unreadCount, 99))") + .cmuxFont( + size: titlebarNotificationBadgeFontSize(for: config) + / max(1, GlobalFontMagnification.scale(for: globalFontPercent)), + weight: .semibold + ) + .foregroundColor(.white) + .frame(width: config.badgeSize, height: config.badgeSize) + .background(Circle().fill(cmuxAccentColor())) + .offset(x: config.badgeOffset.width, y: config.badgeOffset.height) + } + } +} + struct TitlebarControlsView: View { - @ObservedObject var notificationStore: TerminalNotificationStore + let unreadModel: SidebarUnreadModel + let layoutModel: TitlebarControlsLayoutModel @ObservedObject var viewModel: TitlebarControlsViewModel let onToggleSidebar: () -> Void let onToggleNotifications: () -> Void @@ -879,9 +1014,6 @@ struct TitlebarControlsView: View { let onFocusHistoryForward: () -> Void let visibilityMode: TitlebarControlsVisibilityMode @ObservedObject private var popoverVisibilityState = NotificationsPopoverVisibilityState.shared - @AppStorage(TitlebarControlsStyle.storageKey) private var styleRawValue = TitlebarControlsStyle.defaultRawValue - @Environment(\.cmuxGlobalFontMagnificationPercent) private var globalFontPercent - @State private var shortcutRefreshTick = 0 @State private var appearanceRefreshTick = 0 @State private var isHoveringControls = false @State private var hostWindowNumber: Int? @@ -927,17 +1059,11 @@ struct TitlebarControlsView: View { } var body: some View { - // Force the `.safeHelp(...)` tooltips to re-evaluate when shortcuts are changed in settings. - // (The titlebar controls don't otherwise re-render on UserDefaults changes.) - let _ = shortcutRefreshTick let _ = appearanceRefreshTick - let _ = globalFontPercent - let style = TitlebarControlsStyle.stored(rawValue: styleRawValue) + let layoutSnapshot = layoutModel.snapshot + let style = layoutSnapshot.style let config = style.config - let contentSize = TitlebarControlsLayoutMetrics.contentSize( - config: config, - titlebarShortcutHintXOffset: titlebarShortcutHintXOffset - ) + let contentSize = layoutSnapshot.contentSize let foregroundColor = Color(nsColor: titlebarControlForegroundNSColor(opacity: 1.0)) controlsGroup(config: config, foregroundColor: foregroundColor) .padding(.leading, TitlebarControlsLayoutMetrics.hintLeadingPadding) @@ -966,9 +1092,6 @@ struct TitlebarControlsView: View { .onHover { hovering in isHoveringControls = hovering } - .onReceive(NotificationCenter.default.publisher(for: KeyboardShortcutSettings.didChangeNotification)) { _ in - shortcutRefreshTick &+= 1 - } .onReceive(NotificationCenter.default.publisher(for: .tabManagerFocusHistoryRevisionDidChange)) { _ in focusHistoryAvailabilityRevision &+= 1 } @@ -1007,7 +1130,6 @@ struct TitlebarControlsView: View { private func controlsGroup(config: TitlebarControlsStyleConfig, foregroundColor: Color) -> some View { let hintLayoutItems = titlebarHintLayoutItems(config: config) let focusHistoryAvailability = focusHistoryNavigationAvailabilitySnapshot - let badgeBaseFontSize = titlebarNotificationBadgeFontSize(for: config) / max(1, GlobalFontMagnification.scale(for: globalFontPercent)) let content = HStack(spacing: config.spacing) { TitlebarControlButton( config: config, @@ -1045,15 +1167,7 @@ struct TitlebarControlsView: View { iconGeometryKeyPrefix: "titlebarControl_showNotificationsIcon" ) - if notificationStore.unreadCount > 0 { - Text("\(min(notificationStore.unreadCount, 99))") - // Fixed-size badge; cap effective glyph size. - .cmuxFont(size: badgeBaseFontSize, weight: .semibold) - .foregroundColor(.white) - .frame(width: config.badgeSize, height: config.badgeSize) - .background(Circle().fill(cmuxAccentColor())) - .offset(x: config.badgeOffset.width, y: config.badgeOffset.height) - } + TitlebarNotificationBadge(unreadModel: unreadModel, config: config) } .frame(width: config.buttonSize, height: config.buttonSize) } @@ -1385,7 +1499,8 @@ private struct MinimalModeTitlebarButtonHitRegionView: NSViewRepresentable { } struct HiddenTitlebarSidebarControlsView: View { - @ObservedObject var notificationStore: TerminalNotificationStore + let unreadModel: SidebarUnreadModel + let layoutModel: TitlebarControlsLayoutModel let onToggleSidebar: () -> Void let onToggleNotifications: (NSView?) -> Void let onNewTab: () -> Void @@ -1396,14 +1511,12 @@ struct HiddenTitlebarSidebarControlsView: View { @State private var isHoveringHost = false @State private var isHoveringWindowChrome = false @State private var hostWindowNumber: Int? - @AppStorage(TitlebarControlsStyle.storageKey) private var styleRawValue = TitlebarControlsStyle.defaultRawValue - private var shouldPinControls: Bool { isHoveringHost || isHoveringWindowChrome || popoverVisibilityState.isShown(in: hostWindowNumber) } var body: some View { - let style = TitlebarControlsStyle.stored(rawValue: styleRawValue) + let style = layoutModel.snapshot.style ZStack(alignment: .leading) { WindowAccessor { window in @@ -1436,7 +1549,8 @@ struct HiddenTitlebarSidebarControlsView: View { .allowsHitTesting(false) TitlebarControlsView( - notificationStore: notificationStore, + unreadModel: unreadModel, + layoutModel: layoutModel, viewModel: viewModel, onToggleSidebar: onToggleSidebar, onToggleNotifications: { [viewModel] in @@ -1790,6 +1904,7 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont private let hostingView: NonDraggableHostingView private let containerView: NSView private let notificationStore: TerminalNotificationStore + private let layoutModel: TitlebarControlsLayoutModel private lazy var notificationsPopover: NSPopover = makeNotificationsPopover() private var pendingSizeUpdate = false private var intrinsicSizeNeedsRefresh = true @@ -1800,13 +1915,20 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont private var windowGeometryObservers: [NSObjectProtocol] = [] private let viewModel = TitlebarControlsViewModel() private var userDefaultsObserver: NSObjectProtocol? + private var lastShowsWorkspaceTitlebar = !WorkspacePresentationModeSettings.isMinimal() + private var lastTitlebarDebugSnapshot = MinimalModeTitlebarDebugSettings.snapshot() var popoverIsShownForTesting: Bool { notificationsPopover.isShown } private var showsWorkspaceTitlebar: Bool { !WorkspacePresentationModeSettings.isMinimal() } - init(notificationStore: TerminalNotificationStore, settingsRuntime: SettingsRuntime?) { + init( + notificationStore: TerminalNotificationStore, + settingsRuntime: SettingsRuntime?, + layoutModel: TitlebarControlsLayoutModel + ) { let containerView = TitlebarAccessoryContainerView() self.containerView = containerView self.notificationStore = notificationStore + self.layoutModel = layoutModel let prepareOriginatingAction: () -> AppDelegate.MainWindowContext? = { [weak containerView] in guard let appDelegate = AppDelegate.shared, let window = containerView?.window else { @@ -1836,7 +1958,8 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont _ = prepareOriginatingAction()?.tabManager.navigateForward() } let rootView = TitlebarControlsView( - notificationStore: notificationStore, + unreadModel: notificationStore.sidebarUnread, + layoutModel: layoutModel, viewModel: viewModel, onToggleSidebar: toggleSidebar, onToggleNotifications: toggleNotifications, @@ -1877,12 +2000,24 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont object: nil, queue: .main ) { [weak self] _ in - self?.applyWorkspaceTitlebarVisibility() - if self?.showsWorkspaceTitlebar == true { - self?.restoreSizeAfterMinimalMode() - self?.scheduleSizeUpdate() + guard let self else { return } + let shouldShow = self.showsWorkspaceTitlebar + let debugSnapshot = MinimalModeTitlebarDebugSettings.snapshot() + let visibilityChanged = shouldShow != self.lastShowsWorkspaceTitlebar + let debugLayoutChanged = debugSnapshot != self.lastTitlebarDebugSnapshot + guard visibilityChanged || debugLayoutChanged else { return } + self.lastTitlebarDebugSnapshot = debugSnapshot + if visibilityChanged { + self.applyWorkspaceTitlebarVisibility() + if shouldShow { + self.restoreSizeAfterMinimalMode() + } + } + if debugLayoutChanged, shouldShow { + self.scheduleSizeUpdate(invalidateLayout: true) } } + observeLayoutModel() applyWorkspaceTitlebarVisibility() scheduleSizeUpdate(invalidateIntrinsicSize: true) @@ -1905,6 +2040,21 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont scheduleSizeUpdate(invalidateIntrinsicSize: true) } + private func observeLayoutModel() { + withObservationTracking { + _ = layoutModel.snapshot + } onChange: { [weak self] in + Task { @MainActor [weak self] in + guard let self else { return } + self.scheduleSizeUpdate( + invalidateIntrinsicSize: true, + invalidateLayout: true + ) + self.observeLayoutModel() + } + } + } + override func viewDidLayout() { super.viewDidLayout() let observedWindowChanged = updateObservedWindowIfNeeded() @@ -1966,8 +2116,7 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont updateObservedWindowIfNeeded() applyWorkspaceTitlebarVisibility() guard showsWorkspaceTitlebar else { return } - let style = TitlebarControlsStyle.stored() - let contentSize = TitlebarControlsLayoutMetrics.contentSize(config: style.config) + let contentSize = layoutModel.snapshot.contentSize if intrinsicSizeNeedsRefresh { hostingView.invalidateIntrinsicContentSize() intrinsicSizeNeedsRefresh = false @@ -2024,6 +2173,7 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont private func applyWorkspaceTitlebarVisibility() { let shouldShow = showsWorkspaceTitlebar + lastShowsWorkspaceTitlebar = shouldShow self.isHidden = !shouldShow view.isHidden = !shouldShow view.alphaValue = shouldShow ? 1 : 0 @@ -2501,6 +2651,7 @@ private struct NotificationsPopoverView: View { final class UpdateTitlebarAccessoryController { private let updateLog: UpdateLogStore private let settingsRuntime: SettingsRuntime? + private let layoutModel: TitlebarControlsLayoutModel private var didStart = false private let attachedWindows = NSHashTable.weakObjects() private var observers: [NSObjectProtocol] = [] @@ -2512,9 +2663,14 @@ final class UpdateTitlebarAccessoryController { private var detachedNotificationsPopover: NSPopover? private var detachedNotificationsPopoverDelegate: DetachedNotificationsPopoverDelegate? - init(updateLog: UpdateLogStore, settingsRuntime: SettingsRuntime?) { + init( + updateLog: UpdateLogStore, + settingsRuntime: SettingsRuntime?, + layoutModel: TitlebarControlsLayoutModel + ) { self.updateLog = updateLog self.settingsRuntime = settingsRuntime + self.layoutModel = layoutModel } deinit { @@ -2660,7 +2816,8 @@ final class UpdateTitlebarAccessoryController { if !window.titlebarAccessoryViewControllers.contains(where: { $0.view.identifier == controlsIdentifier }) { let controls = TitlebarControlsAccessoryViewController( notificationStore: TerminalNotificationStore.shared, - settingsRuntime: settingsRuntime + settingsRuntime: settingsRuntime, + layoutModel: layoutModel ) controls.layoutAttribute = .left controls.view.identifier = controlsIdentifier diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index 2b336dfb82a5..ed3c2d22e84b 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -1,5 +1,6 @@ import AppKit import CmuxFoundation +import CmuxNotifications import SwiftUI import CmuxSettings import CmuxWorkspaces @@ -31,24 +32,33 @@ extension VerticalTabsSidebar { ) let cwdContextMenuItems = resolvedConfig?.contextMenuItems ?? [] let newWorkspacePlacement = resolvedConfig?.newWorkspacePlacement + // The AppKit controller applies the current unread snapshot after row + // construction, keeping this root projection outside Observation. + let unreadSnapshot = SidebarUnreadSnapshot() let anchorUnreadCount: Int = { if group.isCollapsed { return memberWorkspaceIds.reduce(0) { partial, workspaceId in - partial + notificationStore.unreadCount(forTabId: workspaceId) + partial + unreadSnapshot.unreadCount(forWorkspaceId: workspaceId) } } - return notificationStore.unreadCount(forTabId: group.anchorWorkspaceId) + return unreadSnapshot.unreadCount(forWorkspaceId: group.anchorWorkspaceId) }() let anchorIds = [group.anchorWorkspaceId] - let canMarkAnchorRead = notificationStore.canMarkWorkspaceRead(forTabIds: anchorIds) - let canMarkAnchorUnread = notificationStore.canMarkWorkspaceUnread(forTabIds: anchorIds) - let anchorHasLatestNotification = notificationStore.latestNotification(forTabId: group.anchorWorkspaceId) != nil + let canMarkAnchorRead = unreadSnapshot.canMarkWorkspaceRead(forWorkspaceIds: anchorIds) + let canMarkAnchorUnread = unreadSnapshot.canMarkWorkspaceUnread(forWorkspaceIds: anchorIds) + let anchorHasLatestNotification = unreadSnapshot + .summary(forWorkspaceId: group.anchorWorkspaceId) + .hasLatestNotification // "Mark all workspaces in group" targets the contained workspaces only, // never the anchor: the anchor is the group's own row, whose read status // is owned by the separate "Mark Group as Read/Unread" actions. let nonAnchorMemberIds = memberWorkspaceIds.filter { $0 != group.anchorWorkspaceId } - let canMarkAllRead = notificationStore.canMarkWorkspaceRead(forTabIds: nonAnchorMemberIds) - let canMarkAllUnread = notificationStore.canMarkWorkspaceUnread(forTabIds: nonAnchorMemberIds) + let canMarkAllRead = unreadSnapshot.canMarkWorkspaceRead( + forWorkspaceIds: nonAnchorMemberIds + ) + let canMarkAllUnread = unreadSnapshot.canMarkWorkspaceUnread( + forWorkspaceIds: nonAnchorMemberIds + ) let topDropIndicatorVisible = SidebarTabDropIndicatorPredicate().topVisible( forTabId: group.anchorWorkspaceId, draggedTabId: dragState.draggedTabId, @@ -203,7 +213,39 @@ extension VerticalTabsSidebar { return SidebarWorkspaceTableRowConfiguration( groupHeaderModel: model, actions: actions, - environment: renderContext.environment + environment: renderContext.environment, + unreadDependencyWorkspaceIds: Set(memberWorkspaceIds) + .union([group.anchorWorkspaceId]), + unreadRebuild: { + [model, anchorWorkspaceId = group.anchorWorkspaceId, + isCollapsed = group.isCollapsed, memberWorkspaceIds, + nonAnchorMemberIds] snapshot in + // Membership and collapse are structural row inputs, so their + // changes rebuild this configuration. Reuse the render context's + // indexed members instead of rescanning every tab per unread row. + var fresh = model + fresh.anchorUnreadCount = isCollapsed + ? memberWorkspaceIds.reduce(0) { + $0 + snapshot.unreadCount(forWorkspaceId: $1) + } + : snapshot.unreadCount(forWorkspaceId: anchorWorkspaceId) + fresh.canMarkRead = snapshot.canMarkWorkspaceRead( + forWorkspaceIds: [anchorWorkspaceId] + ) + fresh.canMarkUnread = snapshot.canMarkWorkspaceUnread( + forWorkspaceIds: [anchorWorkspaceId] + ) + fresh.hasLatestNotifications = snapshot + .summary(forWorkspaceId: anchorWorkspaceId) + .hasLatestNotification + fresh.canMarkAllRead = snapshot.canMarkWorkspaceRead( + forWorkspaceIds: nonAnchorMemberIds + ) + fresh.canMarkAllUnread = snapshot.canMarkWorkspaceUnread( + forWorkspaceIds: nonAnchorMemberIds + ) + return fresh + } ) } @@ -211,10 +253,11 @@ extension VerticalTabsSidebar { group: WorkspaceGroup, memberWorkspaceIds: [UUID], renderContext: WorkspaceListRenderContext, - unreadSummariesByWorkspaceId: [UUID: SidebarWorkspaceUnreadSummary], + unreadSnapshot: SidebarUnreadSnapshot, notificationIndex: SidebarWorkspaceNotificationIndex, shouldCollectWorkspaceDropTargets: Bool ) -> SidebarWorkspaceGroupRowSnapshot { + let unreadSummariesByWorkspaceId = unreadSnapshot.summaryByWorkspaceId let settings = renderContext.tabItemSettings let isAnchorActive = tabManager.selectedTabId == group.anchorWorkspaceId let isMultiSelected = selectedTabIds.contains(group.anchorWorkspaceId) @@ -244,13 +287,12 @@ extension VerticalTabsSidebar { } return unreadSummariesByWorkspaceId[group.anchorWorkspaceId]?.unreadCount ?? 0 }() - let anchorIds = [group.anchorWorkspaceId] - let canMarkAnchorRead = anchorIds.contains { - (unreadSummariesByWorkspaceId[$0]?.unreadCount ?? 0) > 0 - } - let canMarkAnchorUnread = anchorIds.contains { - (unreadSummariesByWorkspaceId[$0]?.unreadCount ?? 0) == 0 - } + let canMarkAnchorRead = unreadSnapshot.canMarkWorkspaceRead( + forWorkspaceIds: [group.anchorWorkspaceId] + ) + let canMarkAnchorUnread = unreadSnapshot.canMarkWorkspaceUnread( + forWorkspaceIds: [group.anchorWorkspaceId] + ) let anchorHasLatestNotification = notificationIndex.hasNotification( workspaceId: group.anchorWorkspaceId ) @@ -258,12 +300,12 @@ extension VerticalTabsSidebar { // never the anchor: the anchor is the group's own row, whose read status // is owned by the separate "Mark Group as Read/Unread" actions. let nonAnchorMemberIds = memberWorkspaceIds.filter { $0 != group.anchorWorkspaceId } - let canMarkAllRead = nonAnchorMemberIds.contains { - (unreadSummariesByWorkspaceId[$0]?.unreadCount ?? 0) > 0 - } - let canMarkAllUnread = nonAnchorMemberIds.contains { - (unreadSummariesByWorkspaceId[$0]?.unreadCount ?? 0) == 0 - } + let canMarkAllRead = unreadSnapshot.canMarkWorkspaceRead( + forWorkspaceIds: nonAnchorMemberIds + ) + let canMarkAllUnread = unreadSnapshot.canMarkWorkspaceUnread( + forWorkspaceIds: nonAnchorMemberIds + ) let rowId = SidebarWorkspaceRenderItemID.group(group.id) let isPointerHovering = pointerInteractionMonitor.hoveredRowId == rowId let topDropIndicatorVisible = SidebarTabDropIndicatorPredicate().topVisible( diff --git a/cmuxTests/DockRuntimeParityTests.swift b/cmuxTests/DockRuntimeParityTests.swift index ed10f8397347..118a80fca9a0 100644 --- a/cmuxTests/DockRuntimeParityTests.swift +++ b/cmuxTests/DockRuntimeParityTests.swift @@ -2,6 +2,7 @@ import AppKit import Bonsplit import Combine import CmuxControlSocket +import CmuxNotifications import CmuxTerminal import Foundation import Testing diff --git a/cmuxTests/FileDropOverlayViewTests.swift b/cmuxTests/FileDropOverlayViewTests.swift index 0eac941fb581..29424bc54db3 100644 --- a/cmuxTests/FileDropOverlayViewTests.swift +++ b/cmuxTests/FileDropOverlayViewTests.swift @@ -20,12 +20,6 @@ struct FileDropOverlayViewTests { let root = ContentView(updateViewModel: UpdateStateModel(), windowId: windowId) .environmentObject(TabManager()) .environmentObject(TerminalNotificationStore.shared) - // ContentView reads SidebarUnreadModel from the environment. A missing - // @EnvironmentObject is a SwiftUI fatalError rather than a nil, so leaving it out does - // not fail this test, it kills the app host and discards every verdict still pending in - // it. The model belongs to the notification store, so hand over that store's instance - // rather than a detached one. - .environmentObject(TerminalNotificationStore.shared.sidebarUnread) .environmentObject(SidebarState()) .environmentObject(SidebarSelectionState()) .environmentObject(FileExplorerState()) diff --git a/cmuxTests/MobileHostIdentityTests.swift b/cmuxTests/MobileHostIdentityTests.swift index c566135507a7..11ec3c1e8c48 100644 --- a/cmuxTests/MobileHostIdentityTests.swift +++ b/cmuxTests/MobileHostIdentityTests.swift @@ -176,6 +176,28 @@ struct MobileHostIdentityTests { #expect(defaults.string(forKey: "mobileHost.deviceID") == sharedID.lowercased()) } + @Test func canonicalEquivalentSharedDeviceIDDoesNotRewriteDefaults() throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let sharedIDURL = directory.appendingPathComponent("mobile-host-device-id") + let sharedID = "3D56C547-271C-47D8-84F6-5C79C9394A37".lowercased() + try sharedID.write(to: sharedIDURL, atomically: true, encoding: .utf8) + + let suiteName = "mobile-host-identity-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + let legacyStoredID = " \(sharedID.uppercased())\n" + defaults.set(legacyStoredID, forKey: "mobileHost.deviceID") + + #expect(MobileHostIdentity.deviceID( + defaults: defaults, + sharedIDURL: sharedIDURL + ) == sharedID) + #expect(defaults.string(forKey: "mobileHost.deviceID") == legacyStoredID) + } + @Test func migratesExistingBundleIDToSharedFile() throws { let directory = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString, isDirectory: true) diff --git a/cmuxTests/SidebarHiddenPresentationTests.swift b/cmuxTests/SidebarHiddenPresentationTests.swift index 239641602941..ac26b7d65693 100644 --- a/cmuxTests/SidebarHiddenPresentationTests.swift +++ b/cmuxTests/SidebarHiddenPresentationTests.swift @@ -215,7 +215,6 @@ struct SidebarHiddenPresentationTests { ) .environmentObject(tabManager) .environmentObject(notificationStore) - .environmentObject(notificationStore.sidebarUnread) .environmentObject(sidebarState) .environmentObject(SidebarSelectionState()) .environmentObject(FileExplorerState()) diff --git a/cmuxTests/SidebarLazyLayoutScaleTests.swift b/cmuxTests/SidebarLazyLayoutScaleTests.swift index 5afec960c582..4b7700314c88 100644 --- a/cmuxTests/SidebarLazyLayoutScaleTests.swift +++ b/cmuxTests/SidebarLazyLayoutScaleTests.swift @@ -1,6 +1,7 @@ import Testing import AppKit import CmuxSidebar +import CmuxNotifications import CmuxUpdater import SwiftUI @@ -146,6 +147,8 @@ final class SidebarLazyLayoutScaleTests { let root = VerticalTabsSidebar( updateViewModel: UpdateStateModel(), fileExplorerState: FileExplorerState(), + sidebarUnread: unread, + titlebarControlsLayoutModel: TitlebarControlsLayoutModel(), windowId: UUID(), onSendFeedback: {}, onToggleSidebar: {}, @@ -158,7 +161,6 @@ final class SidebarLazyLayoutScaleTests { ) .frame(width: 280) .environmentObject(tabManager) - .environmentObject(unread) .environmentObject(CmuxConfigStore()) .environmentObject(TerminalNotificationStore.shared) .environmentObject(SidebarState()) @@ -318,21 +320,33 @@ final class SidebarLazyLayoutScaleTests { await Self.drainMainRunLoop(for: harness.window) - // The default sidebar intentionally accepts the initial value from - // both workspace publisher families. Wait for those known initial - // projections before isolating the operation count for this burst. - // Initial mount builds fallback + owner snapshots, then each of the - // two keyed publisher families delivers its accepted initial value. - let initialObservationBuildFloor = Self.workspaceCount * 4 + // Wait for initial workspace publishers to quiesce before isolating + // the operation count for this burst. The exact number of accepted + // initial projections is an implementation detail; the invariant is + // that every workspace is projected and the owner reaches a stable + // snapshot before the counter resets. let initialDeadline = ProcessInfo.processInfo.systemUptime + 3 - while harness.counter.workspaceSnapshotBuilds < initialObservationBuildFloor, + var previousInitialBuildCount = -1 + var stableInitialPasses = 0 + while stableInitialPasses < 4, ProcessInfo.processInfo.systemUptime < initialDeadline { Self.turnMainRunLoopOnce(layingOut: harness.window) await Task.yield() + let currentBuildCount = harness.counter.workspaceSnapshotBuilds + if currentBuildCount == previousInitialBuildCount { + stableInitialPasses += 1 + } else { + previousInitialBuildCount = currentBuildCount + stableInitialPasses = 0 + } } #expect( - harness.counter.workspaceSnapshotBuilds >= initialObservationBuildFloor, - "Initial keyed workspace publisher values did not reach the snapshot owner." + harness.counter.workspaceSnapshotBuilds >= Self.workspaceCount, + "Initial workspace values did not reach the snapshot owner." + ) + #expect( + stableInitialPasses == 4, + "Initial workspace publishers did not quiesce before the batch measurement." ) harness.counter.reset() diff --git a/cmuxTests/SidebarPointerInteractionScaleTests.swift b/cmuxTests/SidebarPointerInteractionScaleTests.swift index fbf46752ff8d..9289485830ad 100644 --- a/cmuxTests/SidebarPointerInteractionScaleTests.swift +++ b/cmuxTests/SidebarPointerInteractionScaleTests.swift @@ -1,5 +1,6 @@ import AppKit import CmuxSidebar +import CmuxNotifications import CoreGraphics import OSLog import Testing diff --git a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift index e4bec409fd53..80d1b667b328 100644 --- a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift +++ b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift @@ -1,6 +1,8 @@ import AppKit +import CmuxNotifications import CmuxSidebar import CmuxWorkspaces +@_spi(CmuxHostTransport) import CmuxExtensionKit import SwiftUI import Testing #if canImport(cmux_DEV) @@ -10,6 +12,62 @@ import Testing #endif @Suite struct SidebarWorkspaceSnapshotRefreshPolicyTests { + @Test @MainActor + func extensionSnapshotCacheDoesNotInflateSequenceForIdenticalProviderContent() throws { + let workspaceID = UUID() + let initial = CmuxSidebarSnapshot( + sequence: 10, + selectedWorkspaceID: workspaceID, + workspaces: [CmuxSidebarWorkspace(id: workspaceID, title: "Pi")] + ) + let cache = CMUXSidebarSnapshotCache() + _ = cache.replace(with: initial) + let unread = SidebarUnreadSnapshot( + totalUnreadCount: 1, + summaryByWorkspaceId: [ + workspaceID: SidebarWorkspaceUnreadSummary( + unreadCount: 1, + latestNotificationText: "Done" + ), + ] + ) + let patched = try #require(cache.applyUnread(unread)) + let matchingProvider = CmuxSidebarSnapshot( + sequence: 10, + selectedWorkspaceID: workspaceID, + workspaces: [ + CmuxSidebarWorkspace( + id: workspaceID, + title: "Pi", + unreadCount: 1, + latestNotification: "Done" + ), + ] + ) + + let firstPoll = cache.replace(with: matchingProvider) + let secondPoll = cache.replace(with: matchingProvider) + + #expect(firstPoll.sequence == patched.sequence) + #expect(secondPoll.sequence == patched.sequence) + + let changedProvider = CmuxSidebarSnapshot( + sequence: 10, + selectedWorkspaceID: workspaceID, + workspaces: [ + CmuxSidebarWorkspace( + id: workspaceID, + title: "Pi renamed", + unreadCount: 1, + latestNotification: "Done" + ), + ] + ) + let changedPoll = cache.replace(with: changedProvider) + #expect(changedPoll.sequence == patched.sequence + 1) + #expect(changedPoll.workspaces.first?.title == "Pi renamed") + } + @Test func contextMenuPinChangeUpdatesDisplayedFieldsAndDefersNoisyFields() { let current = Self.snapshot( title: "lmao", diff --git a/cmuxTests/TitlebarInteractiveControlTests.swift b/cmuxTests/TitlebarInteractiveControlTests.swift index 23aac6b6419f..97a2d5d3325a 100644 --- a/cmuxTests/TitlebarInteractiveControlTests.swift +++ b/cmuxTests/TitlebarInteractiveControlTests.swift @@ -151,7 +151,11 @@ struct TitlebarInteractiveControlTests { defer { window.orderOut(nil) } window.isMovable = false - let controller = TitlebarControlsAccessoryViewController(notificationStore: TerminalNotificationStore.shared, settingsRuntime: nil) + let controller = TitlebarControlsAccessoryViewController( + notificationStore: TerminalNotificationStore.shared, + settingsRuntime: nil, + layoutModel: TitlebarControlsLayoutModel() + ) let container = controller.view container.frame = NSRect(x: 0, y: 0, width: 180, height: 44) window.contentView = container @@ -185,7 +189,11 @@ struct TitlebarInteractiveControlTests { @Test func accessoryControlsRemainNonDraggable() { _ = NSApplication.shared - let controller = TitlebarControlsAccessoryViewController(notificationStore: TerminalNotificationStore.shared, settingsRuntime: nil) + let controller = TitlebarControlsAccessoryViewController( + notificationStore: TerminalNotificationStore.shared, + settingsRuntime: nil, + layoutModel: TitlebarControlsLayoutModel() + ) let container = controller.view container.frame = NSRect(x: 0, y: 0, width: 180, height: 44) diff --git a/cmuxTests/UpdatePillReleaseVisibilityTests.swift b/cmuxTests/UpdatePillReleaseVisibilityTests.swift index d875686420a2..ee5ac5175a41 100644 --- a/cmuxTests/UpdatePillReleaseVisibilityTests.swift +++ b/cmuxTests/UpdatePillReleaseVisibilityTests.swift @@ -1,5 +1,6 @@ import Foundation import AppKit +import CmuxFoundation import Testing #if canImport(cmux_DEV) @@ -247,6 +248,76 @@ struct TitlebarControlsSizingPolicyTests { checkTrue(titlebarControlsShouldApplyLayout(previous: baseline, next: offsetChanged)) } + @Test + @MainActor + func testLayoutModelOnlyRecomputesForTitlebarInputs() async { + let suiteName = "TitlebarControlsLayoutModel-\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suiteName)! + defer { defaults.removePersistentDomain(forName: suiteName) } + let notificationCenter = NotificationCenter() + var computationCount = 0 + let model = TitlebarControlsLayoutModel( + defaults: defaults, + notificationCenter: notificationCenter + ) { config in + computationCount += 1 + return NSSize(width: config.buttonSize, height: config.buttonSize) + } + + checkEqual(computationCount, 1) + checkEqual(model.snapshot.style, .classic) + + defaults.set(true, forKey: "unrelatedTitlebarTestSetting") + notificationCenter.post(name: UserDefaults.didChangeNotification, object: defaults) + await drainMainQueue() + checkEqual(computationCount, 1) + + defaults.set(TitlebarControlsStyle.compact.rawValue, forKey: TitlebarControlsStyle.storageKey) + notificationCenter.post(name: UserDefaults.didChangeNotification, object: defaults) + await drainMainQueue() + checkEqual(computationCount, 2) + checkEqual(model.snapshot.style, .compact) + + notificationCenter.post( + name: KeyboardShortcutSettings.didChangeNotification, + object: nil, + userInfo: [ + KeyboardShortcutSettings.actionUserInfoKey: + KeyboardShortcutSettings.Action.closeWindow.rawValue, + ] + ) + await drainMainQueue() + checkEqual(computationCount, 2) + + notificationCenter.post( + name: KeyboardShortcutSettings.didChangeNotification, + object: nil, + userInfo: [ + KeyboardShortcutSettings.actionUserInfoKey: + KeyboardShortcutSettings.Action.toggleSidebar.rawValue, + ] + ) + await drainMainQueue() + checkEqual(computationCount, 3) + + notificationCenter.post(name: KeyboardShortcutSettings.didChangeNotification, object: nil) + await drainMainQueue() + checkEqual(computationCount, 4) + + notificationCenter.post(name: GlobalFontMagnification.didChangeNotification, object: nil) + await drainMainQueue() + checkEqual(computationCount, 5) + } + + @MainActor + private func drainMainQueue() async { + await withCheckedContinuation { continuation in + DispatchQueue.main.async { + continuation.resume() + } + } + } + @Test func testTitlebarControlsListenForWindowGeometryChanges() { checkTrue(TitlebarWindowGeometryNotifications.names.contains(NSWindow.didResizeNotification)) diff --git a/cmuxTests/WorkspaceContentViewVisibilityTests.swift b/cmuxTests/WorkspaceContentViewVisibilityTests.swift index 8ccdec40a225..7c07f631d138 100644 --- a/cmuxTests/WorkspaceContentViewVisibilityTests.swift +++ b/cmuxTests/WorkspaceContentViewVisibilityTests.swift @@ -1,7 +1,9 @@ import Testing import AppKit +import CmuxNotifications import CmuxUpdater import CoreGraphics +import Observation import SwiftUI import Bonsplit @@ -204,7 +206,6 @@ final class WorkspaceContentViewVisibilityTests { let root = ContentView(updateViewModel: UpdateStateModel(), windowId: UUID()) .environmentObject(tabManager) .environmentObject(notificationStore) - .environmentObject(notificationStore.sidebarUnread) .environmentObject(SidebarState()) .environmentObject(SidebarSelectionState()) .environmentObject(FileExplorerState()) @@ -257,6 +258,181 @@ final class WorkspaceContentViewVisibilityTests { ) } + @Test + @MainActor + func testUnreadChangeUpdatesOnlyAffectedSidebarRow() async throws { + _ = NSApplication.shared + + let suiteName = "WorkspaceContentViewUnreadTests.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defaults.removePersistentDomain(forName: suiteName) + defer { + defaults.removePersistentDomain(forName: suiteName) + } + defaults.set( + CmuxExtensionSidebarSelection.defaultProviderId, + forKey: CmuxExtensionSidebarSelection.defaultsKey + ) + + let tabManager = TabManager() + let workspaceId = try #require(tabManager.selectedTabId) + let unaffectedWorkspace = tabManager.addWorkspace( + select: false, + autoWelcomeIfNeeded: false + ) + let unread = SidebarUnreadModel() + let counts = MinimalModeBodyProbeCounts() + let root = ContentView( + updateViewModel: UpdateStateModel(), + windowId: UUID(), + sidebarUnread: unread + ) + .environmentObject(tabManager) + .environmentObject(TerminalNotificationStore.shared) + .environmentObject(SidebarState()) + .environmentObject(SidebarSelectionState()) + .environmentObject(FileExplorerState()) + .environmentObject(CmuxConfigStore()) + .environment( + \.minimalModeInvalidationProbe, + MinimalModeInvalidationProbe( + contentViewBody: { counts.contentViewBody += 1 }, + workspaceContentBody: { counts.workspaceContentBody += 1 }, + verticalTabsSidebarBody: { counts.verticalTabsSidebarBody += 1 } + ) + ) + .defaultAppStorage(defaults) + + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 900, height: 640), + styleMask: [.titled, .closable, .resizable], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + window.contentView = MainWindowHostingView(rootView: root) + defer { + window.contentView = nil + window.close() + } + + await Self.drainMainRunLoop(for: window) + let workspaceCell = try #require( + window.contentView.flatMap { root in + Self.descendants(of: root) + .compactMap { $0 as? SidebarWorkspaceRowTableCellView } + .first { $0.currentModelForMeasurement?.workspaceId == workspaceId } + } + ) + let unaffectedWorkspaceCell = try #require( + window.contentView.flatMap { root in + Self.descendants(of: root) + .compactMap { $0 as? SidebarWorkspaceRowTableCellView } + .first { + $0.currentModelForMeasurement?.workspaceId == unaffectedWorkspace.id + } + } + ) + var appliedUnreadCount: Int? + var unaffectedApplyCount = 0 + workspaceCell.applyModelProbeForTesting = { model in + appliedUnreadCount = model.unreadCount + } + unaffectedWorkspaceCell.applyModelProbeForTesting = { _ in + unaffectedApplyCount += 1 + } + counts.reset() + + unread.apply( + totalUnreadCount: 1, + summaries: [ + workspaceId: SidebarWorkspaceUnreadSummary( + unreadCount: 1, + latestNotificationText: "Pi finished" + ), + ], + unreadSurfaceKeys: [ + SidebarSurfaceUnreadKey(workspaceId: workspaceId, surfaceId: nil), + ], + focusedReadIndicatorByWorkspaceId: [:], + manualUnreadWorkspaceIds: [] + ) + await Self.drainMainRunLoop(for: window) + + #expect( + counts.contentViewBody == 0, + "Unread changes must update their leaf consumers without rebuilding ContentView." + ) + #expect( + counts.workspaceContentBody == 0, + "Unread changes must not rebuild terminal or browser content." + ) + #expect( + counts.verticalTabsSidebarBody == 0, + "Unread changes must not rebuild every row through VerticalTabsSidebar." + ) + #expect( + appliedUnreadCount == 1, + "The affected visible AppKit row must still receive the unread badge." + ) + #expect( + unaffectedApplyCount == 0, + "An unread change must not reconfigure an unaffected AppKit row." + ) + #expect( + unaffectedWorkspaceCell.currentModelForMeasurement?.unreadCount == 0, + "An unread change must not copy its badge into a neighboring workspace row." + ) + } + + @Test + @MainActor + func testUnreadApplyPublishesOneAtomicSnapshot() { + let workspaceId = UUID() + let surfaceId = UUID() + let unread = SidebarUnreadModel() + var publicationCount = 0 + withObservationTracking { + _ = unread.snapshot + } onChange: { + publicationCount += 1 + } + let summaries = [ + workspaceId: SidebarWorkspaceUnreadSummary( + unreadCount: 1, + latestNotificationText: "Pi finished" + ), + ] + let surfaceKeys: Set = [ + SidebarSurfaceUnreadKey(workspaceId: workspaceId, surfaceId: surfaceId), + ] + let focusedIndicators = [workspaceId: surfaceId] + let manualUnreadWorkspaceIds: Set = [workspaceId] + + unread.apply( + totalUnreadCount: 1, + summaries: summaries, + unreadSurfaceKeys: surfaceKeys, + focusedReadIndicatorByWorkspaceId: focusedIndicators, + manualUnreadWorkspaceIds: manualUnreadWorkspaceIds + ) + #expect(publicationCount == 1) + + withObservationTracking { + _ = unread.snapshot + } onChange: { + publicationCount += 1 + } + unread.apply( + totalUnreadCount: 1, + summaries: summaries, + unreadSurfaceKeys: surfaceKeys, + focusedReadIndicatorByWorkspaceId: focusedIndicators, + manualUnreadWorkspaceIds: manualUnreadWorkspaceIds + ) + #expect(publicationCount == 1, "Applying an equivalent snapshot must stay silent.") + } + @Test func minimalModeSidebarFooterKeepsOnlyUpgradeControl() { let minimalControls = SidebarFooterControl.allCases.filter { @@ -329,6 +505,10 @@ final class WorkspaceContentViewVisibilityTests { } } + private static func descendants(of view: NSView) -> [NSView] { + view.subviews + view.subviews.flatMap { descendants(of: $0) } + } + @Test func testNonSelectedNonRetiringWorkspaceIsFullyHidden() { #expect( diff --git a/docs/cli-contract.md b/docs/cli-contract.md index 3b299bf588d8..f7fae9f6032f 100644 --- a/docs/cli-contract.md +++ b/docs/cli-contract.md @@ -560,7 +560,7 @@ the expected text without connecting to a cmux socket. - `cmux enable-browser --help` -> `Usage: cmux enable-browser [--json]` - `cmux browser-status --help` -> `Usage: cmux browser-status [--json]` - `cmux agent-hibernation --help` -> `Usage: cmux agent-hibernation [--json]` -- `cmux restore --help` -> `Usage: cmux restore `; `--surface [id|ref]` uses the caller when omitted. +- `cmux restore --help` -> `Usage: cmux restore ` - `cmux restore-session --help` -> `Usage: cmux restore-session` - `cmux open --help` -> `Usage: cmux open ...` - `cmux feedback --help` -> `Usage: cmux feedback` diff --git a/tests/test_pi_extension_dispatch.py b/tests/test_pi_extension_dispatch.py index 0760424e84d7..a1610fd84508 100644 --- a/tests/test_pi_extension_dispatch.py +++ b/tests/test_pi_extension_dispatch.py @@ -161,6 +161,289 @@ def check_responsiveness(bun: str, root: Path, extension_path: Path) -> int: return 0 +def check_ui_lifecycle_handlers_return_immediately( + bun: str, + root: Path, + extension_path: Path, +) -> int: + lifecycle_log = root / "ui-lifecycle-latency.log" + lifecycle_release = root / "ui-lifecycle-release" + lifecycle_cmux = root / "ui-lifecycle-latency-cmux" + make_executable( + lifecycle_cmux, + """#!/usr/bin/env bash +set -euo pipefail +payload="$(cat)" +printf 'start %s|%s\n' "$*" "$payload" >> "$CMUX_TEST_PI_UI_LATENCY_LOG" +for _ in {1..250}; do + if [ -f "$CMUX_TEST_PI_UI_RELEASE" ]; then break; fi + sleep 0.02 +done +if [ ! -f "$CMUX_TEST_PI_UI_RELEASE" ]; then + printf 'blocked %s\n' "$*" >> "$CMUX_TEST_PI_UI_LATENCY_LOG" + exit 88 +fi +printf 'end %s\n' "$*" >> "$CMUX_TEST_PI_UI_LATENCY_LOG" +printf '{"workspace_id":"00000000-0000-0000-0000-000000008673","surface_id":"00000000-0000-0000-0000-000000008672","resume_binding":{"kind":"pi","checkpoint_id":"pi-ui-latency-session"}}\n' +""", + ) + lifecycle_source = """ +import { writeFileSync } from "node:fs"; +const extensionPath = process.env.CMUX_TEST_PI_EXTENSION_PATH; +const mod = await import(extensionPath); +const handlers = new Map(); +mod.default({ on(name, handler) { handlers.set(name, handler); } }); +const ctx = { + cwd: "/tmp/pi-ui-latency-project", + isIdle() { return true; }, + sessionManager: { getSessionId() { return "pi-ui-latency-session"; } } +}; +await Promise.resolve(handlers.get("session_start")({}, ctx)); +await Promise.resolve(handlers.get("before_agent_start")({ prompt: "hello" }, ctx)); +await Promise.resolve(handlers.get("tool_execution_end")({ + toolCallId: "ui-lifecycle-tool", + toolName: "bash", + result: { content: [{ type: "text", text: "done" }] }, + isError: false +}, ctx)); +await Promise.resolve(handlers.get("agent_end")({ + messages: [{ role: "assistant", content: "done" }], + stopReason: "completed" +}, ctx)); +console.log("lifecycle_handlers_returned"); +writeFileSync(process.env.CMUX_TEST_PI_UI_RELEASE, "ready"); + +const logPath = process.env.CMUX_TEST_PI_UI_LATENCY_LOG; +const deadline = performance.now() + 5000; +while (performance.now() < deadline) { + let text = ""; + try { + text = await Bun.file(logPath).text(); + } catch (_) {} + const completed = text.split("\\n").filter((line) => line.startsWith("end ")).length; + if (completed >= 7) break; + await new Promise((resolve) => setTimeout(resolve, 10)); +} +""" + result = run_extension( + bun=bun, + root=root, + extension_path=extension_path, + fake_cmux=lifecycle_cmux, + source=lifecycle_source, + extra_env={ + "CMUX_TEST_PI_UI_LATENCY_LOG": str(lifecycle_log), + "CMUX_TEST_PI_UI_RELEASE": str(lifecycle_release), + }, + ) + if result.returncode != 0: + print("FAIL: Pi UI lifecycle handler awaited cmux subprocess work") + print(f"exit={result.returncode}") + print(f"stdout={result.stdout.strip()}") + print(f"stderr={result.stderr.strip()}") + return 1 + + if "lifecycle_handlers_returned" not in result.stdout: + print(f"FAIL: Pi UI lifecycle handlers did not return before release: {result.stdout!r}") + return 1 + + calls = lifecycle_log.read_text(encoding="utf-8").splitlines() + completed = [line for line in calls if line.startswith("end ")] + expected = ( + "hooks pi session-start", + "--json surface resume set", + "--json surface resume get", + "hooks pi prompt-submit", + "hooks feed --source pi --event PostToolUse", + "hooks pi notification", + "hooks pi stop", + ) + indexes = { + command: [index for index, line in enumerate(completed) if command in line] + for command in expected + } + orderedIndexes = [indexes[command][0] for command in expected if indexes[command]] + commandPhases = [line.split(" ", 1)[0] for line in calls if line.startswith(("start ", "end "))] + if ( + len(completed) != len(expected) + or any(len(found) != 1 for found in indexes.values()) + or orderedIndexes != sorted(orderedIndexes) + or commandPhases != [phase for _ in expected for phase in ("start", "end")] + ): + print(f"FAIL: detached Pi lifecycle work lost command ordering: {calls!r}") + return 1 + return 0 + + +def check_completion_precedes_next_prompt(bun: str, root: Path, extension_path: Path) -> int: + transition_log = root / "turn-transition.log" + transition_cmux = root / "turn-transition-cmux" + make_executable( + transition_cmux, + """#!/usr/bin/env bash +set -euo pipefail +payload="$(cat)" +printf '%s|%s\n' "$*" "$payload" >> "$CMUX_TEST_PI_TRANSITION_LOG" +printf '{}\n' +""", + ) + transition_source = """ +const extensionPath = process.env.CMUX_TEST_PI_EXTENSION_PATH; +const mod = await import(extensionPath); +const handlers = new Map(); +mod.default({ on(name, handler) { handlers.set(name, handler); } }); +const ctx = { + cwd: "/tmp/pi-turn-transition", + sessionManager: { getSessionId() { return "pi-turn-transition-session"; } } +}; +handlers.get("before_agent_start")({ prompt: "first" }, ctx); +handlers.get("agent_end")({ + messages: [{ role: "assistant", content: "first done" }], + stopReason: "completed" +}, ctx); +handlers.get("before_agent_start")({ prompt: "second" }, ctx); +await handlers.get("session_shutdown")({ reason: "test complete" }, ctx); +""" + result = run_extension( + bun=bun, + root=root, + extension_path=extension_path, + fake_cmux=transition_cmux, + source=transition_source, + extra_env={"CMUX_TEST_PI_TRANSITION_LOG": str(transition_log)}, + ) + if result.returncode != 0: + print(f"FAIL: Pi turn-transition harness failed: {result.stderr!r}") + return 1 + calls = transition_log.read_text(encoding="utf-8").splitlines() + first_stop = next( + ( + index + for index, line in enumerate(calls) + if "hooks pi stop" in line + and '"turn_id":"pi-turn-transition-session:turn-1"' in line + ), + None, + ) + second_prompt = next( + ( + index + for index, line in enumerate(calls) + if "hooks pi prompt-submit" in line + and '"turn_id":"pi-turn-transition-session:turn-2"' in line + ), + None, + ) + if first_stop is None or second_prompt is None or first_stop > second_prompt: + print(f"FAIL: previous Pi completion raced the next prompt: {calls!r}") + return 1 + return 0 + + +def check_cross_session_lifecycle_isolation( + bun: str, + root: Path, + extension_path: Path, +) -> int: + lifecycle_log = root / "cross-session-lifecycle.log" + lifecycle_release = root / "cross-session-lifecycle-release" + lifecycle_cmux = root / "cross-session-lifecycle-cmux" + make_executable( + lifecycle_cmux, + """#!/usr/bin/env bash +set -euo pipefail +payload="$(cat)" +printf 'start %s|%s\n' "$*" "$payload" >> "$CMUX_TEST_PI_CROSS_LIFECYCLE_LOG" +if [[ "$payload" == *'"session_id":"pi-slow-session"'* ]] && [[ "$*" == *"prompt-submit"* ]]; then + for _ in {1..250}; do + if [ -f "$CMUX_TEST_PI_CROSS_LIFECYCLE_RELEASE" ]; then break; fi + sleep 0.02 + done + if [ ! -f "$CMUX_TEST_PI_CROSS_LIFECYCLE_RELEASE" ]; then + printf 'blocked %s|%s\n' "$*" "$payload" >> "$CMUX_TEST_PI_CROSS_LIFECYCLE_LOG" + exit 88 + fi +fi +printf 'end %s|%s\n' "$*" "$payload" >> "$CMUX_TEST_PI_CROSS_LIFECYCLE_LOG" +printf '{}\n' +""", + ) + lifecycle_source = """ +import { writeFileSync } from "node:fs"; +const extensionPath = process.env.CMUX_TEST_PI_EXTENSION_PATH; +const mod = await import(extensionPath); +const handlers = new Map(); +mod.default({ on(name, handler) { handlers.set(name, handler); } }); +const context = (sessionId) => ({ + cwd: "/tmp/pi-cross-session-lifecycle", + sessionManager: { getSessionId() { return sessionId; } } +}); +const slow = context("pi-slow-session"); +const healthy = context("pi-healthy-session"); +handlers.get("before_agent_start")({ prompt: "block session A" }, slow); +const logPath = process.env.CMUX_TEST_PI_CROSS_LIFECYCLE_LOG; +const slowStartDeadline = performance.now() + 5000; +let sawSlowStart = false; +while (performance.now() < slowStartDeadline) { + try { + if ((await Bun.file(logPath).text()).includes("pi-slow-session")) { + sawSlowStart = true; + break; + } + } catch (_) {} + await new Promise((resolve) => setTimeout(resolve, 10)); +} +if (!sawSlowStart) throw new Error("slow session never entered cmux dispatch"); +await handlers.get("session_shutdown")({ reason: "session B complete" }, healthy); +writeFileSync(process.env.CMUX_TEST_PI_CROSS_LIFECYCLE_RELEASE, "ready"); +await handlers.get("session_shutdown")({ reason: "session A complete" }, slow); +""" + result = run_extension( + bun=bun, + root=root, + extension_path=extension_path, + fake_cmux=lifecycle_cmux, + source=lifecycle_source, + extra_env={ + "CMUX_TEST_PI_CROSS_LIFECYCLE_LOG": str(lifecycle_log), + "CMUX_TEST_PI_CROSS_LIFECYCLE_RELEASE": str(lifecycle_release), + }, + ) + if result.returncode != 0: + print(f"FAIL: cross-session lifecycle harness failed: {result.stderr!r}") + return 1 + calls = lifecycle_log.read_text(encoding="utf-8").splitlines() + slow_prompt_end = next( + ( + index + for index, line in enumerate(calls) + if line.startswith("end ") + and "prompt-submit" in line + and '"session_id":"pi-slow-session"' in line + ), + None, + ) + healthy_stop = next( + ( + index + for index, line in enumerate(calls) + if line.startswith("end ") + and "hooks pi stop" in line + and '"session_id":"pi-healthy-session"' in line + ), + None, + ) + if ( + any(line.startswith("blocked ") for line in calls) + or healthy_stop is None + or slow_prompt_end is None + or healthy_stop > slow_prompt_end + ): + print(f"FAIL: slow Pi session delayed another session's shutdown: {calls!r}") + return 1 + return 0 + + def check_panel_only_target_fails_closed(bun: str, root: Path, extension_path: Path) -> int: marker = root / "panel-only-cmux-called" fake_cmux = root / "panel-only-cmux" @@ -1114,7 +1397,14 @@ def check_completion_order(bun: str, root: Path, extension_path: Path) -> int: }, ctx); } const logPath = process.env.CMUX_TEST_PI_CANCELLATION_LOG; -while (!(await Bun.file(logPath).text()).includes("hooks feed")) { +async function readLog() { + try { + return await Bun.file(logPath).text(); + } catch (_) { + return ""; + } +} +while (!(await readLog()).includes("hooks feed")) { await new Promise((resolve) => setTimeout(resolve, 10)); } for (const index of [3, 1, 2, 0]) { @@ -1134,7 +1424,11 @@ def check_completion_order(bun: str, root: Path, extension_path: Path) -> int: toolName: "bash", result: { content: [{ type: "text", text: "late" }] } }, ctx); -await new Promise((resolve) => setTimeout(resolve, 250)); +const completionDeadline = performance.now() + 5000; +while (performance.now() < completionDeadline) { + if ((await readLog()).includes("hooks pi stop")) break; + await new Promise((resolve) => setTimeout(resolve, 10)); +} """ completion = run_extension( bun=bun, @@ -1402,6 +1696,11 @@ def check_completion_drain_deadline(bun: str, root: Path, extension_path: Path) messages: [{ role: "assistant", content: "done" }], stopReason: "completed" }, ctx); +const completionDeadline = performance.now() + 5000; +while (performance.now() < completionDeadline) { + if ((await Bun.file(logPath).text()).includes("hooks pi stop")) break; + await new Promise((resolve) => setTimeout(resolve, 10)); +} console.log(`ordered_completion_ms=${performance.now() - startedAt}`); """ ordered = run_extension( @@ -1508,6 +1807,11 @@ def handle_term(_signum, _frame): messages: [{ role: "assistant", content: "done" }], stopReason: "completed" }, ctx); +const completionDeadline = performance.now() + 6000; +while (performance.now() < completionDeadline) { + if ((await Bun.file(logPath).text()).includes("hooks pi stop")) break; + await new Promise((resolve) => setTimeout(resolve, 10)); +} console.log(`completion_ms=${performance.now() - startedAt}`); """ deadline = run_extension( @@ -1650,12 +1954,25 @@ def check_error_classification(bun: str, root: Path, extension_path: Path) -> in const mod = await import(extensionPath); const handlers = new Map(); mod.default({ on(name, handler) { handlers.set(name, handler); } }); +let notificationCount = 0; const ctx = { cwd: "/tmp/pi-ambiguous-error-project", + ui: { notify() { notificationCount += 1; } }, sessionManager: { getSessionId() { return "pi-ambiguous-error-session"; } } }; await handlers.get("before_agent_start")({ prompt: "first" }, ctx); await handlers.get("before_agent_start")({ prompt: "second" }, ctx); +const logPath = process.env.CMUX_TEST_PI_AMBIGUOUS_LOG; +const deadline = performance.now() + 5000; +while (performance.now() < deadline) { + try { + if ((await Bun.file(logPath).text()).trim().split("\\n").length >= 2) break; + } catch (_) {} + await new Promise((resolve) => setTimeout(resolve, 10)); +} +if (notificationCount !== 0) { + throw new Error(`routine cmux failure showed ${notificationCount} Pi warning toast(s)`); +} """ ambiguous = run_extension( bun=bun, @@ -1961,6 +2278,16 @@ def check_runtime_isolation(bun: str, root: Path, extension_path: Path) -> int: { prompt: "healthy runtime" }, context("pi-runtime-healthy") ); +await Promise.all([ + staleHandlers.get("session_shutdown")( + { reason: "runtime isolation test" }, + context("pi-runtime-stale"), + ), + healthyHandlers.get("session_shutdown")( + { reason: "runtime isolation test" }, + context("pi-runtime-healthy"), + ), +]); """ runtime = run_extension( bun=bun, @@ -1974,7 +2301,13 @@ def check_runtime_isolation(bun: str, root: Path, extension_path: Path) -> int: print(f"FAIL: runtime-isolation harness failed: {runtime.stderr!r}") return 1 runtime_calls = runtime_log.read_text(encoding="utf-8").splitlines() - if len(runtime_calls) != 2 or "pi-runtime-healthy" not in runtime_calls[-1]: + prompt_calls = [line for line in runtime_calls if "hooks pi prompt-submit" in line] + prompt_sessions = { + session_id + for session_id in ("pi-runtime-stale", "pi-runtime-healthy") + if any(session_id in line for line in prompt_calls) + } + if len(prompt_calls) != 2 or prompt_sessions != {"pi-runtime-stale", "pi-runtime-healthy"}: print(f"FAIL: stale surface leaked across Pi extension runtimes: {runtime_calls!r}") return 1 @@ -2006,18 +2339,22 @@ def check_session_isolation_within_runtime(bun: str, root: Path, extension_path: cwd: "/tmp/pi-session-isolation-project", sessionManager: { getSessionId() { return sessionId; } }, }); +const staleContext = context("pi-session-stale"); +const healthyContext = context("pi-session-healthy"); await handlers.get("before_agent_start")( { prompt: "stale session" }, - context("pi-session-stale"), + staleContext, ); await handlers.get("before_agent_start")( { prompt: "stale session retry" }, - context("pi-session-stale"), + staleContext, ); await handlers.get("before_agent_start")( { prompt: "healthy session" }, - context("pi-session-healthy"), + healthyContext, ); +await handlers.get("session_shutdown")({ reason: "session isolation test" }, staleContext); +await handlers.get("session_shutdown")({ reason: "session isolation test" }, healthyContext); """ result = run_extension( bun=bun, @@ -2031,7 +2368,12 @@ def check_session_isolation_within_runtime(bun: str, root: Path, extension_path: print(f"FAIL: same-runtime session isolation harness failed: {result.stderr!r}") return 1 calls = session_log.read_text(encoding="utf-8").splitlines() - if len(calls) != 2 or "pi-session-healthy" not in calls[-1]: + prompt_calls = [line for line in calls if "hooks pi prompt-submit" in line] + if ( + len(prompt_calls) != 2 + or sum("pi-session-stale" in line for line in prompt_calls) != 1 + or sum("pi-session-healthy" in line for line in prompt_calls) != 1 + ): print(f"FAIL: stale surface disabled another Pi session in the same runtime: {calls!r}") return 1 return 0 @@ -2103,6 +2445,9 @@ def check_stale_surface(bun: str, root: Path, extension_path: Path) -> int: def run_checks(bun: str, root: Path, extension_path: Path) -> int: checks = ( check_responsiveness, + check_ui_lifecycle_handlers_return_immediately, + check_completion_precedes_next_prompt, + check_cross_session_lifecycle_isolation, check_panel_only_target_fails_closed, check_feed_backlog, check_terminal_feed_compaction, diff --git a/tests/test_pi_extension_install.py b/tests/test_pi_extension_install.py index e12160f9e855..e41614897ca1 100644 --- a/tests/test_pi_extension_install.py +++ b/tests/test_pi_extension_install.py @@ -6,15 +6,24 @@ from __future__ import annotations import base64 +import fcntl import json import os +import signal import shutil import subprocess import tempfile import time from pathlib import Path -from claude_teams_test_utils import install_pi_extension, resolve_cmux_cli +from claude_teams_test_utils import ( + FOCUSED_SURFACE_ID, + FOCUSED_WORKSPACE_ID, + install_pi_extension, + resolve_cmux_cli, +) + +NONBLOCKING_LOCK_TIMEOUT_SECONDS = 5.0 def make_executable(path: Path, content: str) -> None: @@ -22,6 +31,39 @@ def make_executable(path: Path, content: str) -> None: path.chmod(0o755) +def communicate_or_terminate( + process: subprocess.Popen[str], + *, + input_text: str | None = None, + timeout: float = 20, +) -> tuple[str, str]: + try: + return process.communicate(input=input_text, timeout=timeout) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + pass + try: + process.communicate(timeout=2) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + try: + process.communicate(timeout=2) + except subprocess.TimeoutExpired: + for pipe in (process.stdin, process.stdout, process.stderr): + if pipe is not None: + pipe.close() + try: + process.wait(timeout=2) + except subprocess.TimeoutExpired: + pass + raise + + def wait_for_text( path: Path, expected_count: int, @@ -41,9 +83,9 @@ def wait_for_text( def payloads_from_log(text: str) -> list[dict[str, object]]: payloads: list[dict[str, object]] = [] - for raw in text.split("\n---\n"): + for raw in text.splitlines(): raw = raw.strip() - if not raw: + if not raw or raw == "---": continue try: payload = json.loads(raw) @@ -86,6 +128,191 @@ def main() -> int: print("FAIL: generated Pi extension does not import the current Pi package") return 1 + extension_path.write_text( + "// cmux-pi-session-extension-marker v2\n" + "// stale managed fixture using synchronous hook dispatch\n" + 'import { spawnSync } from "node:child_process";\n', + encoding="utf-8", + ) + refresh_env = os.environ.copy() + isolated_home = root / "home" + isolated_home.mkdir() + refresh_env["HOME"] = str(isolated_home) + refresh_env["CFFIXED_USER_HOME"] = str(isolated_home) + refresh_env["PI_CODING_AGENT_DIR"] = str(config_dir) + refresh_env["CMUX_WORKSPACE_ID"] = FOCUSED_WORKSPACE_ID + refresh_env["CMUX_SURFACE_ID"] = FOCUSED_SURFACE_ID + refresh_command = [ + cli_path, + "--socket", + str(root / "missing-pi-refresh.sock"), + "hooks", + "pi", + "session-start", + "--workspace", + FOCUSED_WORKSPACE_ID, + "--surface", + FOCUSED_SURFACE_ID, + ] + refresh_payload = json.dumps( + { + "session_id": "pi-managed-extension-refresh", + "cwd": str(root), + "hook_event_name": "SessionStart", + "event": "SessionStart", + } + ) + refresh_result = subprocess.run( + refresh_command, + input=refresh_payload, + capture_output=True, + text=True, + check=False, + env=refresh_env, + timeout=20, + ) + if refresh_result.returncode == 0: + print("FAIL: Pi refresh fixture unexpectedly connected to its missing socket") + return 1 + if extension_path.read_text(encoding="utf-8") != extension_text: + print("FAIL: Pi session-start did not refresh the stale cmux-managed extension") + return 1 + + extension_path.write_text("", encoding="utf-8") + empty_refresh_result = subprocess.run( + refresh_command, + input=refresh_payload, + capture_output=True, + text=True, + check=False, + env=refresh_env, + timeout=20, + ) + if empty_refresh_result.returncode == 0: + print("FAIL: empty Pi refresh fixture unexpectedly connected to its missing socket") + return 1 + if extension_path.read_text(encoding="utf-8") != extension_text: + print("FAIL: Pi session-start did not repair an empty managed extension") + return 1 + + extension_path.write_text( + "// cmux-pi-session-extension-marker v2\n// stale managed race fixture\n", + encoding="utf-8", + ) + lock_path = extension_path.parent / ".cmux-session.lock" + replacement = "// user replacement without the cmux ownership marker\n" + with lock_path.open("a", encoding="utf-8") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + blocked_refresh = subprocess.Popen( + refresh_command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=refresh_env, + start_new_session=True, + ) + extension_path.write_text(replacement, encoding="utf-8") + try: + communicate_or_terminate( + blocked_refresh, + input_text=refresh_payload, + timeout=NONBLOCKING_LOCK_TIMEOUT_SECONDS, + ) + except subprocess.TimeoutExpired: + print("FAIL: Pi session-start refresh blocked on its advisory lock") + return 1 + fcntl.flock(lock, fcntl.LOCK_UN) + if extension_path.read_text(encoding="utf-8") != replacement: + print("FAIL: in-flight Pi refresh overwrote a replacement extension") + return 1 + + extension_path.unlink() + extension_path = install_pi_extension(config_dir, cli_path) + extension_text = extension_path.read_text(encoding="utf-8") + extension_path.write_text( + "// cmux-pi-session-extension-marker v2\n// stale uninstall race fixture\n", + encoding="utf-8", + ) + with lock_path.open("a", encoding="utf-8") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + blocked_refresh = subprocess.Popen( + refresh_command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=refresh_env, + start_new_session=True, + ) + blocked_uninstall = subprocess.Popen( + [cli_path, "hooks", "pi", "uninstall"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=refresh_env, + start_new_session=True, + ) + refresh_timed_out = False + try: + communicate_or_terminate( + blocked_refresh, + input_text=refresh_payload, + timeout=NONBLOCKING_LOCK_TIMEOUT_SECONDS, + ) + except subprocess.TimeoutExpired: + refresh_timed_out = True + fcntl.flock(lock, fcntl.LOCK_UN) + try: + uninstall_stdout, uninstall_stderr = communicate_or_terminate(blocked_uninstall) + except subprocess.TimeoutExpired: + print("FAIL: concurrent Pi uninstall timed out") + return 1 + if refresh_timed_out: + print("FAIL: concurrent Pi refresh blocked behind uninstall") + return 1 + if blocked_uninstall.returncode != 0: + print( + "FAIL: concurrent Pi uninstall failed: " + f"stdout={uninstall_stdout!r} stderr={uninstall_stderr!r}" + ) + return 1 + if extension_path.exists(): + print("FAIL: in-flight Pi refresh recreated an uninstalled extension") + return 1 + extension_path = install_pi_extension(config_dir, cli_path) + extension_text = extension_path.read_text(encoding="utf-8") + + stale_symlink_fixture = ( + "// cmux-pi-session-extension-marker v2\n" + "// stale lock symlink fixture\n" + ) + extension_path.write_text(stale_symlink_fixture, encoding="utf-8") + lock_path.unlink(missing_ok=True) + lock_target = root / "redirected-lock-target" + lock_target.write_text("sentinel\n", encoding="utf-8") + lock_path.symlink_to(lock_target) + symlink_result = subprocess.run( + [cli_path, "hooks", "pi", "install", "--yes"], + capture_output=True, + text=True, + check=False, + env=refresh_env, + timeout=20, + ) + if symlink_result.returncode == 0: + print("FAIL: Pi install followed a symlinked mutation lock") + return 1 + if extension_path.read_text(encoding="utf-8") != stale_symlink_fixture: + print("FAIL: Pi install mutated the extension through a symlinked lock") + return 1 + if lock_target.read_text(encoding="utf-8") != "sentinel\n": + print("FAIL: Pi install mutated the symlinked lock target") + return 1 + lock_path.unlink() + extension_path = install_pi_extension(config_dir, cli_path) + extension_text = extension_path.read_text(encoding="utf-8") + bin_dir = root / "bin" bin_dir.mkdir() fake_pi = bin_dir / "pi" @@ -131,8 +358,7 @@ def main() -> int: set -euo pipefail printf '%s\n' "$*" >> "$CMUX_TEST_PI_ARGS_LOG" payload="$(cat)" -printf '%s' "$payload" >> "$CMUX_TEST_PI_STDIN_LOG" -printf '\n---\n' >> "$CMUX_TEST_PI_STDIN_LOG" +printf '%s\n' "$payload" >> "$CMUX_TEST_PI_STDIN_LOG" { printf 'kind=%s\n' "${CMUX_AGENT_LAUNCH_KIND-}" printf 'cwd=%s\n' "${CMUX_AGENT_LAUNCH_CWD-}" @@ -270,6 +496,14 @@ def main() -> int: const lines = (await Bun.file(path).text()).split("\\n"); return lines.filter((line) => line.includes("hooks pi notification") || line.includes("hooks pi stop")).length; } +async function waitForCompletionHookCount(expectedCount) { + const deadline = Date.now() + 5000; + while (Date.now() < deadline) { + if (await completionHookCount() === expectedCount) return; + await Bun.sleep(10); + } + throw new Error(`timed out waiting for ${expectedCount} completion hooks`); +} async function waitForFeedEvent(eventName, expectedCount) { const path = process.env.CMUX_TEST_PI_ARGS_LOG; const deadline = Date.now() + 5000; @@ -372,7 +606,7 @@ def main() -> int: agentIdle = true; await handlers.get("agent_settled")({}, ctx); completionCount += 2; -if (await completionHookCount() !== completionCount) throw new Error("agent_settled did not emit notification and stop"); +await waitForCompletionHookCount(completionCount); await handlers.get("agent_settled")({}, ctx); if (await completionHookCount() !== completionCount) throw new Error("duplicate agent_settled emitted completion twice"); await handlers.get("session_shutdown")({ reason: "quit" }, ctx); @@ -430,7 +664,7 @@ def main() -> int: if (await completionHookCount() !== completionCount) throw new Error("failed notification was attempted before settlement"); await handlers.get("agent_settled")({}, notificationFailureCtx); completionCount += 2; -if (await completionHookCount() !== completionCount) throw new Error("settlement did not attempt failed notification and stop"); +await waitForCompletionHookCount(completionCount); await handlers.get("agent_settled")({}, notificationFailureCtx); if (await completionHookCount() !== completionCount) throw new Error("failed notification was retried after duplicate settlement"); process.argv.splice( @@ -454,7 +688,7 @@ def main() -> int: stopReason: "completed" }, legacyCtx); completionCount += 2; -if (await completionHookCount() !== completionCount) throw new Error("legacy Pi agent_end did not emit completion fallback"); +await waitForCompletionHookCount(completionCount); process.argv.splice( 0, process.argv.length, @@ -476,7 +710,7 @@ def main() -> int: stopReason: "completed" }, unknownCtx); completionCount += 2; -if (await completionHookCount() !== completionCount) throw new Error("unknown Pi agent_end did not emit completion fallback"); +await waitForCompletionHookCount(completionCount); process.argv.splice( 0, process.argv.length, @@ -498,7 +732,7 @@ def main() -> int: stopReason: "completed" }, malformedCtx); completionCount += 2; -if (await completionHookCount() !== completionCount) throw new Error("malformed Pi agent_end did not emit completion fallback"); +await waitForCompletionHookCount(completionCount); """ check = subprocess.run( [bun, "--eval", check_source], @@ -524,7 +758,7 @@ def main() -> int: ) stdin_log = wait_for_text( fake_stdin_log, - 62, + 38, timeout=20.0, expected_substrings=('"hook_event_name":"PostToolUse"',), )