From 17a5e5255a214c43da443714dde33f63f1b0bac2 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 18:13:20 -0700 Subject: [PATCH 01/46] sidebar: per-agent status rows, one per agent pane Several agents in one workspace previously collapsed into a single last-write-wins status pill per agent type (statusEntries is workspace-scoped, keyed by agent type). Store a panel-scoped copy of every structured agent status report and render one sidebar row per live agent pane: panel-scoped report wins, the workspace-level entry is only trusted when a single pane owns the key, otherwise the per-panel lifecycle drives the row. Rows follow pane moves via the existing detached-runtime transfer and clear on pane close; clicking a row focuses that pane. --- Resources/Localizable.xcstrings | 51 +++++ Sources/ContentView.swift | 175 +++++++++++++++++- ...inalController+ControlSidebarContext.swift | 28 ++- Sources/Workspace+PanelLifecycle.swift | 149 ++++++++++++++- ...eSidebarAgentRuntimeObservationModel.swift | 9 + cmux.xcodeproj/project.pbxproj | 4 + cmuxTests/PerAgentSidebarStatusRowTests.swift | 149 +++++++++++++++ 7 files changed, 553 insertions(+), 12 deletions(-) create mode 100644 cmuxTests/PerAgentSidebarStatusRowTests.swift diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index aaefa95014db..c216ea8e52ee 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -193713,6 +193713,57 @@ } } }, + "sidebar.agentStatus.idle": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Idle" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "待機中" + } + } + } + }, + "sidebar.agentStatus.needsInput": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Needs input" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "入力待ち" + } + } + } + }, + "sidebar.agentStatus.running": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Running" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "実行中" + } + } + } + }, "sidebar.browserStack.closeGroup": { "extractionState": "manual", "localizations": { diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 16c4ec90a4c0..9a1cb692d523 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -13176,6 +13176,7 @@ struct SidebarWorkspaceSnapshotBuilder { let copyableSidebarSSHError: String? let latestConversationMessage: String? let metadataEntries: [SidebarStatusEntry] + let agentStatusRows: [SidebarAgentStatusRow] let metadataBlocks: [SidebarMetadataBlock] let latestLog: SidebarLogEntry? let progress: SidebarProgressState? @@ -13802,6 +13803,19 @@ struct TabItemView: View, Equatable { if detailVisibility.showsMetadata { let metadataEntries = workspaceSnapshot.metadataEntries let metadataBlocks = workspaceSnapshot.metadataBlocks + if !workspaceSnapshot.agentStatusRows.isEmpty { + SidebarAgentStatusRows( + rows: workspaceSnapshot.agentStatusRows, + isActive: usesInvertedActiveForeground, + activeForegroundColor: activeSecondaryColor(0.95), + fontScale: fontScale, + onFocusPanel: { panelId in + updateSelection() + tab.focusPanel(panelId) + } + ) + .transition(.opacity) + } if !metadataEntries.isEmpty { SidebarMetadataRows( entries: metadataEntries, @@ -14812,6 +14826,9 @@ struct TabItemView: View, Equatable { return pullRequestDisplays(orderedPanelIds: orderedPanelIds) }() + let agentStatusRows = detailVisibility.showsMetadata ? tab.sidebarAgentStatusRows() : [] + let agentRowStatusKeys = Set(agentStatusRows.map(\.statusKey)) + return SidebarWorkspaceSnapshotBuilder.Snapshot( presentationKey: workspaceSnapshotPresentationKey, title: tab.title, @@ -14825,7 +14842,10 @@ struct TabItemView: View, Equatable { && (tab.remoteConnectionState == .suspended || tab.remoteConnectionState == .disconnected), copyableSidebarSSHError: copyableSidebarSSHError, latestConversationMessage: tab.latestConversationMessage, - metadataEntries: detailVisibility.showsMetadata ? tab.sidebarStatusEntriesInDisplayOrder() : [], + metadataEntries: detailVisibility.showsMetadata + ? tab.sidebarStatusEntriesInDisplayOrder().filter { !agentRowStatusKeys.contains($0.key) } + : [], + agentStatusRows: agentStatusRows, metadataBlocks: detailVisibility.showsMetadata ? tab.sidebarMetadataBlocksInDisplayOrder() : [], latestLog: detailVisibility.showsLog ? tab.logEntries.last : nil, progress: detailVisibility.showsProgress ? tab.progress : nil, @@ -15442,6 +15462,159 @@ private struct SidebarMetadataRows: View { } } +private struct SidebarAgentStatusRows: View { + let rows: [SidebarAgentStatusRow] + let isActive: Bool + let activeForegroundColor: Color + let fontScale: CGFloat + let onFocusPanel: (UUID) -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + ForEach(rows) { row in + SidebarAgentStatusEntryRow( + row: row, + isActive: isActive, + activeForegroundColor: activeForegroundColor, + fontScale: fontScale, + onFocusPanel: onFocusPanel + ) + } + } + } +} + +private struct SidebarAgentStatusEntryRow: View { + let row: SidebarAgentStatusRow + let isActive: Bool + let activeForegroundColor: Color + let fontScale: CGFloat + let onFocusPanel: (UUID) -> Void + + var body: some View { + HStack(spacing: 4) { + if let icon = iconView { + icon + .foregroundColor(foregroundColor.opacity(0.95)) + } + Text(displayText) + .foregroundColor(foregroundColor) + .lineLimit(1) + .truncationMode(.tail) + if let paneLabel = row.paneLabel { + Text(paneLabel) + .foregroundColor(isActive ? activeForegroundColor.opacity(0.6) : .secondary.opacity(0.8)) + .lineLimit(1) + .truncationMode(.middle) + } + Spacer(minLength: 0) + } + .cmuxFont(size: 10 * fontScale) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + .onTapGesture { onFocusPanel(row.panelId) } + .safeHelp(helpText) + } + + private var displayText: String { + if let value = row.value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty { + return value + } + let name = Self.agentDisplayName(statusKey: row.statusKey) + if let lifecycleText { + return "\(name): \(lifecycleText)" + } + return name + } + + private var helpText: String { + guard let paneLabel = row.paneLabel else { return displayText } + return "\(displayText) (\(paneLabel))" + } + + private var lifecycleText: String? { + switch row.lifecycle { + case .running: + return String(localized: "sidebar.agentStatus.running", defaultValue: "Running") + case .needsInput: + return String(localized: "sidebar.agentStatus.needsInput", defaultValue: "Needs input") + case .idle: + return String(localized: "sidebar.agentStatus.idle", defaultValue: "Idle") + case .unknown, nil: + return nil + } + } + + static func agentDisplayName(statusKey: String) -> String { + statusKey + .split(separator: "_") + .map { $0.prefix(1).uppercased() + $0.dropFirst() } + .joined(separator: " ") + } + + private var effectiveIcon: String? { + if let icon = row.icon?.trimmingCharacters(in: .whitespacesAndNewlines), !icon.isEmpty { + return icon + } + switch row.lifecycle { + case .running: + return "bolt.fill" + case .needsInput: + return "exclamationmark.bubble.fill" + case .idle: + return "checkmark.circle" + case .unknown, nil: + return nil + } + } + + private var effectiveColorHex: String? { + if let color = row.color { + return color + } + switch row.lifecycle { + case .running: + return "#4C8DFF" + case .needsInput: + return "#FF9F0A" + case .idle, .unknown, nil: + return nil + } + } + + private var foregroundColor: Color { + if isActive { + return activeForegroundColor + } + if let raw = effectiveColorHex, let explicit = Color(hex: raw) { + return explicit + } + return .secondary + } + + private var iconView: AnyView? { + guard let iconRaw = effectiveIcon else { return nil } + if iconRaw.hasPrefix("emoji:") { + let value = String(iconRaw.dropFirst("emoji:".count)) + guard !value.isEmpty else { return nil } + return AnyView(Text(value).cmuxFont(size: 9 * fontScale)) + } + if iconRaw.hasPrefix("text:") { + let value = String(iconRaw.dropFirst("text:".count)) + guard !value.isEmpty else { return nil } + return AnyView(Text(value).cmuxFont(size: 8 * fontScale, weight: .semibold)) + } + let symbolName: String + if iconRaw.hasPrefix("sf:") { + symbolName = String(iconRaw.dropFirst("sf:".count)) + } else { + symbolName = iconRaw + } + guard !symbolName.isEmpty else { return nil } + return AnyView(CmuxSystemSymbolImage(magnified: symbolName, pointSize: 8 * fontScale, weight: .medium)) + } +} + private struct SidebarMetadataEntryRow: View { let entry: SidebarStatusEntry let isActive: Bool diff --git a/Sources/TerminalController+ControlSidebarContext.swift b/Sources/TerminalController+ControlSidebarContext.swift index 93dc21bb0e75..d114465e3c43 100644 --- a/Sources/TerminalController+ControlSidebarContext.swift +++ b/Sources/TerminalController+ControlSidebarContext.swift @@ -33,6 +33,22 @@ extension TerminalController: ControlSidebarContext { if let panelId = panelID, !tab.panels.keys.contains(panelId) { return } + let entry = SidebarStatusEntry( + key: key, + value: value, + icon: icon, + color: color, + url: url, + priority: priority, + format: appFormat, + timestamp: Date() + ) + // The panel-scoped copy is written unconditionally: the workspace + // slot is last-write-wins per key, so "no change" there can still + // be a change for this panel's own row. + if let panelId = panelID { + tab.recordPanelStatusEntry(entry, panelId: panelId) + } guard Self.shouldReplaceStatusEntry( current: tab.statusEntries[key], key: key, @@ -49,16 +65,7 @@ extension TerminalController: ControlSidebarContext { } return } - tab.statusEntries[key] = SidebarStatusEntry( - key: key, - value: value, - icon: icon, - color: color, - url: url, - priority: priority, - format: appFormat, - timestamp: Date() - ) + tab.statusEntries[key] = entry if let pid { tab.recordAgentPID(key: key, pid: pid, panelId: panelID) } @@ -68,6 +75,7 @@ extension TerminalController: ControlSidebarContext { nonisolated func controlSidebarScheduleStatusClear(target: ControlSidebarTabTarget, key: String) { controlSidebarScheduleMutation(target: target) { _, tab in _ = tab.statusEntries.removeValue(forKey: key) + _ = tab.clearPanelStatusEntries(statusKey: key) tab.clearAgentPID(key: key) } } diff --git a/Sources/Workspace+PanelLifecycle.swift b/Sources/Workspace+PanelLifecycle.swift index a07f55397f32..0c485a5c0b96 100644 --- a/Sources/Workspace+PanelLifecycle.swift +++ b/Sources/Workspace+PanelLifecycle.swift @@ -5,6 +5,23 @@ import Darwin import Foundation import CmuxSidebar +/// Immutable per-pane agent status row consumed by the sidebar (a value +/// snapshot only, per the sidebar list snapshot-boundary rule). +struct SidebarAgentStatusRow: Equatable, Identifiable { + let panelId: UUID + let statusKey: String + let value: String? + let icon: String? + let color: String? + let url: URL? + let lifecycle: AgentHibernationLifecycleState? + let paneLabel: String? + let priority: Int + let timestamp: Date + + var id: String { "\(panelId.uuidString)|\(statusKey)" } +} + extension Workspace { private static let structuredAgentHookStatusKeys = AgentHibernationLifecycleStatusKeys.allowedStatusKeys private static let managedSubagentEnvironmentKey = "CMUX_AGENT_MANAGED_SUBAGENT" @@ -35,6 +52,45 @@ extension Workspace { set { sidebarAgentRuntimeObservation.setAgentLifecycleStatesByPanelId(newValue) } } + var statusEntriesByPanelId: [UUID: [String: SidebarStatusEntry]] { + get { sidebarAgentRuntimeObservation.statusEntriesByPanelId } + set { sidebarAgentRuntimeObservation.setStatusEntriesByPanelId(newValue) } + } + + /// Records the panel-scoped copy of a structured agent status report, so + /// each agent pane keeps its own row even when several agents of the same + /// type share the workspace (the workspace-level `statusEntries` slot is + /// last-write-wins per agent type). + func recordPanelStatusEntry(_ entry: SidebarStatusEntry, panelId: UUID) { + guard Self.structuredAgentHookStatusKeys.contains(entry.key) else { return } + statusEntriesByPanelId[panelId, default: [:]][entry.key] = entry + } + + @discardableResult + func clearPanelStatusEntry(statusKey: String, panelId: UUID) -> Bool { + guard var entries = statusEntriesByPanelId[panelId], + entries.removeValue(forKey: statusKey) != nil else { + return false + } + if entries.isEmpty { + statusEntriesByPanelId.removeValue(forKey: panelId) + } else { + statusEntriesByPanelId[panelId] = entries + } + return true + } + + @discardableResult + func clearPanelStatusEntries(statusKey: String) -> Bool { + var didChange = false + for panelId in statusEntriesByPanelId.keys where statusEntriesByPanelId[panelId]?[statusKey] != nil { + if clearPanelStatusEntry(statusKey: statusKey, panelId: panelId) { + didChange = true + } + } + return didChange + } + func agentRuntimeState(forPanelId panelId: UUID) -> DetachedAgentRuntimeState? { let pidKeys = agentPIDKeysByPanelId[panelId] ?? [] @@ -47,10 +103,14 @@ extension Workspace { agentPIDIdentitiesForPanel[key] = agentPIDProcessIdentitiesByKey[key] } let statusKey = agentStatusKey(forAgentPIDKey: key) - if let statusEntry = statusEntries[statusKey] { + if let statusEntry = statusEntriesByPanelId[panelId]?[statusKey] ?? statusEntries[statusKey] { statusEntriesForPanel[statusKey] = statusEntry } } + for (statusKey, statusEntry) in statusEntriesByPanelId[panelId] ?? [:] + where statusEntriesForPanel[statusKey] == nil { + statusEntriesForPanel[statusKey] = statusEntry + } guard !statusEntriesForPanel.isEmpty || !agentPIDsForPanel.isEmpty || !pidKeys.isEmpty else { return nil } return DetachedAgentRuntimeState( panelId: panelId, @@ -184,6 +244,7 @@ extension Workspace { agentPIDProcessIdentitiesByKey.removeAll() agentPIDPanelIdsByKey.removeAll() agentPIDKeysByPanelId.removeAll() + statusEntriesByPanelId.removeAll() if hadAgentPIDs, refreshPorts { refreshTrackedAgentPorts() } @@ -286,6 +347,87 @@ extension Workspace { return visibleStatusKeys } + /// One sidebar row per live agent pane, so several agents in one workspace + /// never collapse into a single last-write-wins pill. A panel-scoped report + /// wins; the workspace-level entry is only trusted when a single pane owns + /// that status key; otherwise the per-panel lifecycle drives the row. + func sidebarAgentStatusRows() -> [SidebarAgentStatusRow] { + var statusKeysByPanel: [UUID: Set] = [:] + for (key, panelId) in agentPIDPanelIdsByKey where panels[panelId] != nil { + let statusKey = agentStatusKey(forAgentPIDKey: key) + guard Self.structuredAgentHookStatusKeys.contains(statusKey) else { continue } + statusKeysByPanel[panelId, default: []].insert(statusKey) + } + for (panelId, entries) in statusEntriesByPanelId where panels[panelId] != nil { + for statusKey in entries.keys where Self.structuredAgentHookStatusKeys.contains(statusKey) { + statusKeysByPanel[panelId, default: []].insert(statusKey) + } + } + + var chosenByPanel: [(panelId: UUID, statusKey: String, entry: SidebarStatusEntry?)] = [] + for (panelId, statusKeys) in statusKeysByPanel { + let candidates = statusKeys.map { ($0, statusEntriesByPanelId[panelId]?[$0]) } + let chosen = candidates.max { lhs, rhs in + switch (lhs.1, rhs.1) { + case let (lhsEntry?, rhsEntry?): + return isSidebarStatusEntryLessCurrent(lhsEntry, than: rhsEntry) + case (nil, .some): + return true + case (.some, nil): + return false + case (nil, nil): + return lhs.0 > rhs.0 + } + } + if let chosen { + chosenByPanel.append((panelId: panelId, statusKey: chosen.0, entry: chosen.1)) + } + } + + var panelCountByStatusKey: [String: Int] = [:] + for item in chosenByPanel { + panelCountByStatusKey[item.statusKey, default: 0] += 1 + } + + let includePaneLabels = chosenByPanel.count > 1 + let rows = chosenByPanel.map { item -> SidebarAgentStatusRow in + let workspaceEntry = statusEntries[item.statusKey] + let soleOwner = panelCountByStatusKey[item.statusKey] == 1 + let entry = item.entry ?? (soleOwner ? workspaceEntry : nil) + return SidebarAgentStatusRow( + panelId: item.panelId, + statusKey: item.statusKey, + value: entry?.value, + icon: entry?.icon ?? workspaceEntry?.icon, + color: entry?.color ?? workspaceEntry?.color, + url: entry?.url, + lifecycle: agentLifecycleStatesByPanelId[item.panelId]?[item.statusKey], + paneLabel: includePaneLabels ? agentStatusRowPaneLabel(panelId: item.panelId) : nil, + priority: entry?.priority ?? workspaceEntry?.priority ?? 0, + timestamp: entry?.timestamp ?? workspaceEntry?.timestamp ?? .distantPast + ) + } + return rows.sorted { lhs, rhs in + if lhs.priority != rhs.priority { return lhs.priority > rhs.priority } + if lhs.timestamp != rhs.timestamp { return lhs.timestamp > rhs.timestamp } + return lhs.id < rhs.id + } + } + + private func agentStatusRowPaneLabel(panelId: UUID) -> String? { + let candidates = [ + panelCustomTitles[panelId], + panelDirectoryDisplayLabels[panelId], + panelTitles[panelId], + ] + for candidate in candidates { + if let trimmed = candidate?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmed.isEmpty { + return trimmed + } + } + return nil + } + private func isSidebarStatusEntryLessCurrent( _ lhs: SidebarStatusEntry, than rhs: SidebarStatusEntry @@ -332,6 +474,9 @@ extension Workspace { if clearAgentLifecycle(key: lifecycleStatusKey, panelId: lifecyclePanelId) { didChange = true } + if let statusKeyToClear, clearPanelStatusEntry(statusKey: statusKeyToClear, panelId: lifecyclePanelId) { + didChange = true + } } if let statusKeyToClear, !hasAgentRuntime(forStatusKey: statusKeyToClear), @@ -370,6 +515,7 @@ extension Workspace { guard let runtimeState else { return } for (statusKey, statusEntry) in runtimeState.statusEntries { statusEntries[statusKey] = statusEntry + recordPanelStatusEntry(statusEntry, panelId: runtimeState.panelId) } var didAdoptAgentPID = false for (key, pid) in runtimeState.agentPIDs { @@ -454,6 +600,7 @@ extension Workspace { manualUnreadMarkedAt.removeValue(forKey: panelId) panelShellActivityStates.removeValue(forKey: panelId) clearAgentLifecycleStates(panelId: panelId) + statusEntriesByPanelId.removeValue(forKey: panelId) surfaceTTYNames.removeValue(forKey: panelId) discardRemotePTYSessionID(panelId: panelId) surfaceResumeBindingsByPanelId.removeValue(forKey: panelId) diff --git a/Sources/WorkspaceSidebarAgentRuntimeObservationModel.swift b/Sources/WorkspaceSidebarAgentRuntimeObservationModel.swift index 0e05409746c5..074cba8a1c53 100644 --- a/Sources/WorkspaceSidebarAgentRuntimeObservationModel.swift +++ b/Sources/WorkspaceSidebarAgentRuntimeObservationModel.swift @@ -1,3 +1,4 @@ +import CmuxSidebar import Darwin import Foundation import Observation @@ -9,6 +10,8 @@ final class WorkspaceSidebarAgentRuntimeObservationModel { @ObservationIgnored private(set) var agentPIDs: [String: pid_t] = [:] @ObservationIgnored + private(set) var statusEntriesByPanelId: [UUID: [String: SidebarStatusEntry]] = [:] + @ObservationIgnored private(set) var agentPIDProcessIdentitiesByKey: [String: AgentPIDProcessIdentity] = [:] @ObservationIgnored private(set) var agentPIDPanelIdsByKey: [String: UUID] = [:] @@ -63,6 +66,12 @@ final class WorkspaceSidebarAgentRuntimeObservationModel { notifyChanged() } + func setStatusEntriesByPanelId(_ newValue: [UUID: [String: SidebarStatusEntry]]) { + guard statusEntriesByPanelId != newValue else { return } + statusEntriesByPanelId = newValue + notifyChanged() + } + private func notifyChanged() { changeGeneration &+= 1 for continuation in changeObservers.values { diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 302ef721b838..c7cad8e1d986 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -843,6 +843,7 @@ 6313B6A0 /* PaneMemoryWarning.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6313B6A1 /* PaneMemoryWarning.swift */; }; E30760090000000000000002 /* PassthroughWindowOverlayContainerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E30760090000000000000001 /* PassthroughWindowOverlayContainerView.swift */; }; A5001425 /* PDFPreviewChromeDebugWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001424 /* PDFPreviewChromeDebugWindowController.swift */; }; + DEC515B488104031B49F68F0 /* PerAgentSidebarStatusRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF3A0288F87945DC8889FE91 /* PerAgentSidebarStatusRowTests.swift */; }; D1F0A00400000000000000D1 /* PhoneForwardingMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1F0A00400000000000000D2 /* PhoneForwardingMode.swift */; }; D1F0A00100000000000000A1 /* PhonePushClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1F0A00100000000000000A2 /* PhonePushClient.swift */; }; D1F0A00100000000000000A3 /* PhonePushPayload.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1F0A00100000000000000A4 /* PhonePushPayload.swift */; }; @@ -2283,6 +2284,7 @@ 6313B6A1 /* PaneMemoryWarning.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PaneMemoryWarning.swift; sourceTree = ""; }; E30760090000000000000001 /* PassthroughWindowOverlayContainerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PassthroughWindowOverlayContainerView.swift; sourceTree = ""; }; A5001424 /* PDFPreviewChromeDebugWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/PDFPreviewChromeDebugWindowController.swift; sourceTree = ""; }; + EF3A0288F87945DC8889FE91 /* PerAgentSidebarStatusRowTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerAgentSidebarStatusRowTests.swift; sourceTree = ""; }; D1F0A00400000000000000D2 /* PhoneForwardingMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PhoneForwardingMode.swift; sourceTree = ""; }; D1F0A00100000000000000A2 /* PhonePushClient.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PhonePushClient.swift; sourceTree = ""; }; D1F0A00100000000000000A4 /* PhonePushPayload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PhonePushPayload.swift; sourceTree = ""; }; @@ -4087,6 +4089,7 @@ A9E040000000000000000001 /* CodexAppServerSessionTests.swift */, D72260010000000000000002 /* AgentHibernationPortalVisibilityTests.swift */, D36A00020000000000000002 /* AgentHibernationTests.swift */, + EF3A0288F87945DC8889FE91 /* PerAgentSidebarStatusRowTests.swift */, D36A00050000000000000002 /* RendererRealizationPlannerTests.swift */, C58410010000000000000002 /* RenderableSystemSymbolTests.swift */, DCDC0000000000000000B002 /* DockControlDefinitionDecodingTests.swift */, @@ -6048,6 +6051,7 @@ A5E01203A1B2C3D4E5F60718 /* OpenCodeHookRegressionTests.swift in Sources */, C44550000000000000000001 /* PanelOwnedNativeViewSessionTests.swift in Sources */, 6313FACE0000000000000000 /* PaneMemoryGuardrailTests.swift in Sources */, + DEC515B488104031B49F68F0 /* PerAgentSidebarStatusRowTests.swift in Sources */, D1F0A00300000000000000C1 /* PhonePushPresenceGateTests.swift in Sources */, B3575000000000000000000A /* PiVaultAgentPersistenceTests.swift in Sources */, B1D5CEE0407545B6B57E3B0E /* PortalHitTestingPerformanceTests.swift in Sources */, diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift new file mode 100644 index 000000000000..20f62609960a --- /dev/null +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -0,0 +1,149 @@ +import CmuxSidebar +import XCTest + +@testable import cmux + +/// Per-pane agent status rows (sidebar): several agents in one workspace must +/// each keep their own row instead of collapsing into one last-write-wins +/// status pill per agent type. +final class PerAgentSidebarStatusRowTests: XCTestCase { + private func makeEntry( + key: String, + value: String, + timestamp: Date = Date() + ) -> SidebarStatusEntry { + SidebarStatusEntry( + key: key, + value: value, + icon: "bolt.fill", + color: "#4C8DFF", + timestamp: timestamp + ) + } + + @MainActor + func testTwoAgentsOfSameTypeKeepSeparateRows() throws { + let workspace = Workspace() + let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) + let paneId = try XCTUnwrap(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try XCTUnwrap(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + workspace.recordAgentPID(key: "claude_code.first", pid: 111, panelId: firstPanelId, refreshPorts: false) + workspace.recordAgentPID(key: "claude_code.second", pid: 222, panelId: secondPanelId, refreshPorts: false) + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: firstPanelId) + workspace.recordPanelStatusEntry( + makeEntry(key: "claude_code", value: "Claude is waiting for your input"), + panelId: secondPanelId + ) + // Workspace-level slot only kept the most recent write. + workspace.statusEntries["claude_code"] = makeEntry( + key: "claude_code", + value: "Claude is waiting for your input" + ) + + let rows = workspace.sidebarAgentStatusRows() + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(Set(rows.map(\.panelId)), [firstPanelId, secondPanelId]) + let valuesByPanel = Dictionary(uniqueKeysWithValues: rows.map { ($0.panelId, $0.value) }) + XCTAssertEqual(valuesByPanel[firstPanelId], "Running") + XCTAssertEqual(valuesByPanel[secondPanelId], "Claude is waiting for your input") + } + + @MainActor + func testSoleOwnerFallsBackToWorkspaceEntry() throws { + let workspace = Workspace() + let panelId = try XCTUnwrap(workspace.focusedPanelId) + + workspace.recordAgentPID(key: "claude_code.only", pid: 111, panelId: panelId, refreshPorts: false) + workspace.statusEntries["claude_code"] = makeEntry(key: "claude_code", value: "Running") + + let rows = workspace.sidebarAgentStatusRows() + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows.first?.panelId, panelId) + XCTAssertEqual(rows.first?.value, "Running") + } + + @MainActor + func testSharedKeyWithoutPanelEntriesUsesPerPanelLifecycleNotWorkspaceText() throws { + let workspace = Workspace() + let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) + let paneId = try XCTUnwrap(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try XCTUnwrap(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + workspace.recordAgentPID(key: "claude_code.first", pid: 111, panelId: firstPanelId, refreshPorts: false) + workspace.recordAgentPID(key: "claude_code.second", pid: 222, panelId: secondPanelId, refreshPorts: false) + workspace.setAgentLifecycle(key: "claude_code", panelId: firstPanelId, lifecycle: .running) + workspace.setAgentLifecycle(key: "claude_code", panelId: secondPanelId, lifecycle: .needsInput) + workspace.statusEntries["claude_code"] = makeEntry(key: "claude_code", value: "Running") + + let rows = workspace.sidebarAgentStatusRows() + XCTAssertEqual(rows.count, 2) + let byPanel = Dictionary(uniqueKeysWithValues: rows.map { ($0.panelId, $0) }) + // The ambiguous workspace-level text must not be attributed to either pane. + XCTAssertNil(byPanel[firstPanelId]?.value) + XCTAssertNil(byPanel[secondPanelId]?.value) + XCTAssertEqual(byPanel[firstPanelId]?.lifecycle, .running) + XCTAssertEqual(byPanel[secondPanelId]?.lifecycle, .needsInput) + } + + @MainActor + func testClearingAgentPIDRemovesThatPanelsRow() throws { + let workspace = Workspace() + let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) + let paneId = try XCTUnwrap(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try XCTUnwrap(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + workspace.recordAgentPID(key: "claude_code.first", pid: 111, panelId: firstPanelId, refreshPorts: false) + workspace.recordAgentPID(key: "claude_code.second", pid: 222, panelId: secondPanelId, refreshPorts: false) + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: firstPanelId) + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Idle"), panelId: secondPanelId) + + XCTAssertTrue( + workspace.clearAgentPID(key: "claude_code.first", panelId: firstPanelId, clearStatus: true, refreshPorts: false) + ) + + let rows = workspace.sidebarAgentStatusRows() + XCTAssertEqual(rows.map(\.panelId), [secondPanelId]) + XCTAssertNil(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"]) + XCTAssertEqual(workspace.statusEntriesByPanelId[secondPanelId]?["claude_code"]?.value, "Idle") + } + + @MainActor + func testDetachedRuntimeTransferCarriesPanelScopedEntry() throws { + let source = Workspace() + let panelId = try XCTUnwrap(source.focusedPanelId) + source.recordAgentPID(key: "claude_code.moved", pid: 111, panelId: panelId, refreshPorts: false) + source.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: panelId) + + let runtimeState = try XCTUnwrap(source.agentRuntimeState(forPanelId: panelId)) + XCTAssertEqual(runtimeState.statusEntries["claude_code"]?.value, "Running") + + let destination = Workspace() + destination.adoptDetachedAgentRuntimeState(runtimeState) + XCTAssertEqual(destination.statusEntriesByPanelId[panelId]?["claude_code"]?.value, "Running") + XCTAssertEqual(destination.statusEntries["claude_code"]?.value, "Running") + } + + @MainActor + func testClosingPanelDropsPanelScopedEntries() throws { + let workspace = Workspace() + let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) + let paneId = try XCTUnwrap(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try XCTUnwrap(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: secondPanelId) + + _ = workspace.discardClosedPanelLifecycleState( + panelId: secondPanelId, + paneId: nil, + panel: workspace.panels[secondPanelId], + origin: "test", + closePanel: false, + publishSurfaceClosedEvent: false, + clearSurfaceNotifications: false, + requestTransferredRemoteCleanup: false + ) + + XCTAssertNil(workspace.statusEntriesByPanelId[secondPanelId]) + XCTAssertTrue(workspace.sidebarAgentStatusRows().isEmpty) + } +} From 16534d17edc4d893f15959670b92a1cb17d46b31 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 18:19:27 -0700 Subject: [PATCH 02/46] fix remaining Snapshot construction sites for agentStatusRows --- Sources/Sidebar/SidebarWorkspaceSnapshotRefreshPolicy.swift | 1 + cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift | 1 + 2 files changed, 2 insertions(+) diff --git a/Sources/Sidebar/SidebarWorkspaceSnapshotRefreshPolicy.swift b/Sources/Sidebar/SidebarWorkspaceSnapshotRefreshPolicy.swift index fe914f58aeb3..b86d4cdd279d 100644 --- a/Sources/Sidebar/SidebarWorkspaceSnapshotRefreshPolicy.swift +++ b/Sources/Sidebar/SidebarWorkspaceSnapshotRefreshPolicy.swift @@ -34,6 +34,7 @@ extension SidebarWorkspaceSnapshotBuilder.Snapshot { copyableSidebarSSHError: copyableSidebarSSHError, latestConversationMessage: latestConversationMessage, metadataEntries: metadataEntries, + agentStatusRows: agentStatusRows, metadataBlocks: metadataBlocks, latestLog: latestLog, progress: progress, diff --git a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift index 0d3f89abeeb1..142a808bd27b 100644 --- a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift +++ b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift @@ -148,6 +148,7 @@ import Testing copyableSidebarSSHError: nil, latestConversationMessage: latestConversationMessage, metadataEntries: [], + agentStatusRows: [], metadataBlocks: [], latestLog: nil, progress: nil, From 9c95eb523213b17925f354895ab8622fca2d56f2 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 18:39:22 -0700 Subject: [PATCH 03/46] sidebar per-agent rows: review fixes + split under file length budget Review fixes: - recordPanelStatusEntry reuses TerminalController.shouldReplaceStatusEntry so identical agent heartbeats (timestamp-only changes) no longer invalidate the sidebar snapshot on every report. - Agent status rows are keyed off recorded agent PID ownership only, so a bare panel-scoped text report cannot create an unowned row or keep a stale one alive after clear_agent_pid without --clear-status. - agentRuntimeState only attributes the workspace-level last-write-wins entry to a panel when no other pane can own the status key, so a transferred pane no longer adopts a sibling agent's status text. - Shared-key rows no longer inherit the last writer's icon/color decorations. - URL-backed agent rows mirror SidebarMetadataEntryRow: underlined button that focuses the pane and opens the URL. workflow-guard-tests (Swift file length budget) fix by splitting: - Sources/Workspace+SidebarAgentStatus.swift: SidebarAgentStatusRow, panel status storage, visibility filtering, and the per-agent row projection. - Sources/SidebarStatusRowViews.swift: SidebarMetadataRows and SidebarAgentStatusRows view families moved out of ContentView.swift. Tests: identical-heartbeat dedupe, ambiguous transfer attribution, and unowned/stale row gating added to PerAgentSidebarStatusRowTests. --- Sources/ContentView.swift | 309 ---------------- Sources/SidebarStatusRowViews.swift | 336 ++++++++++++++++++ ...inalController+ControlSidebarContext.swift | 8 +- Sources/Workspace+PanelLifecycle.swift | 213 +---------- Sources/Workspace+SidebarAgentStatus.swift | 234 ++++++++++++ cmux.xcodeproj/project.pbxproj | 8 + cmuxTests/PerAgentSidebarStatusRowTests.swift | 61 ++++ 7 files changed, 654 insertions(+), 515 deletions(-) create mode 100644 Sources/SidebarStatusRowViews.swift create mode 100644 Sources/Workspace+SidebarAgentStatus.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 9a1cb692d523..3cd5650b80ea 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -15405,315 +15405,6 @@ private extension String { } } -private struct SidebarMetadataRows: View { - let entries: [SidebarStatusEntry] - let isActive: Bool - let activeForegroundColor: Color - let activeSecondaryForegroundColor: Color - let fontScale: CGFloat - let onFocus: () -> Void - - @State private var isExpanded: Bool = false - private let collapsedEntryLimit = 3 - - var body: some View { - VStack(alignment: .leading, spacing: 2) { - ForEach(visibleEntries, id: \.key) { entry in - SidebarMetadataEntryRow( - entry: entry, - isActive: isActive, - activeForegroundColor: activeForegroundColor, - fontScale: fontScale, - onFocus: onFocus - ) - } - - if shouldShowToggle { - Button(isExpanded ? String(localized: "sidebar.metadata.showLess", defaultValue: "Show less") : String(localized: "sidebar.metadata.showMore", defaultValue: "Show more")) { - onFocus() - withAnimation(.easeInOut(duration: 0.15)) { - isExpanded.toggle() - } - } - .buttonStyle(.plain) - .cmuxFont(size: 10 * fontScale, weight: .semibold) - .foregroundColor(isActive ? activeSecondaryForegroundColor : .secondary.opacity(0.9)) - .frame(maxWidth: .infinity, alignment: .leading) - } - } - .safeHelp(helpText) - } - - private var visibleEntries: [SidebarStatusEntry] { - guard !isExpanded, entries.count > collapsedEntryLimit else { return entries } - return Array(entries.prefix(collapsedEntryLimit)) - } - - private var helpText: String { - entries.map { entry in - let trimmed = entry.value.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed.isEmpty ? entry.key : trimmed - } - .joined(separator: "\n") - } - - private var shouldShowToggle: Bool { - entries.count > collapsedEntryLimit - } -} - -private struct SidebarAgentStatusRows: View { - let rows: [SidebarAgentStatusRow] - let isActive: Bool - let activeForegroundColor: Color - let fontScale: CGFloat - let onFocusPanel: (UUID) -> Void - - var body: some View { - VStack(alignment: .leading, spacing: 2) { - ForEach(rows) { row in - SidebarAgentStatusEntryRow( - row: row, - isActive: isActive, - activeForegroundColor: activeForegroundColor, - fontScale: fontScale, - onFocusPanel: onFocusPanel - ) - } - } - } -} - -private struct SidebarAgentStatusEntryRow: View { - let row: SidebarAgentStatusRow - let isActive: Bool - let activeForegroundColor: Color - let fontScale: CGFloat - let onFocusPanel: (UUID) -> Void - - var body: some View { - HStack(spacing: 4) { - if let icon = iconView { - icon - .foregroundColor(foregroundColor.opacity(0.95)) - } - Text(displayText) - .foregroundColor(foregroundColor) - .lineLimit(1) - .truncationMode(.tail) - if let paneLabel = row.paneLabel { - Text(paneLabel) - .foregroundColor(isActive ? activeForegroundColor.opacity(0.6) : .secondary.opacity(0.8)) - .lineLimit(1) - .truncationMode(.middle) - } - Spacer(minLength: 0) - } - .cmuxFont(size: 10 * fontScale) - .frame(maxWidth: .infinity, alignment: .leading) - .contentShape(Rectangle()) - .onTapGesture { onFocusPanel(row.panelId) } - .safeHelp(helpText) - } - - private var displayText: String { - if let value = row.value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty { - return value - } - let name = Self.agentDisplayName(statusKey: row.statusKey) - if let lifecycleText { - return "\(name): \(lifecycleText)" - } - return name - } - - private var helpText: String { - guard let paneLabel = row.paneLabel else { return displayText } - return "\(displayText) (\(paneLabel))" - } - - private var lifecycleText: String? { - switch row.lifecycle { - case .running: - return String(localized: "sidebar.agentStatus.running", defaultValue: "Running") - case .needsInput: - return String(localized: "sidebar.agentStatus.needsInput", defaultValue: "Needs input") - case .idle: - return String(localized: "sidebar.agentStatus.idle", defaultValue: "Idle") - case .unknown, nil: - return nil - } - } - - static func agentDisplayName(statusKey: String) -> String { - statusKey - .split(separator: "_") - .map { $0.prefix(1).uppercased() + $0.dropFirst() } - .joined(separator: " ") - } - - private var effectiveIcon: String? { - if let icon = row.icon?.trimmingCharacters(in: .whitespacesAndNewlines), !icon.isEmpty { - return icon - } - switch row.lifecycle { - case .running: - return "bolt.fill" - case .needsInput: - return "exclamationmark.bubble.fill" - case .idle: - return "checkmark.circle" - case .unknown, nil: - return nil - } - } - - private var effectiveColorHex: String? { - if let color = row.color { - return color - } - switch row.lifecycle { - case .running: - return "#4C8DFF" - case .needsInput: - return "#FF9F0A" - case .idle, .unknown, nil: - return nil - } - } - - private var foregroundColor: Color { - if isActive { - return activeForegroundColor - } - if let raw = effectiveColorHex, let explicit = Color(hex: raw) { - return explicit - } - return .secondary - } - - private var iconView: AnyView? { - guard let iconRaw = effectiveIcon else { return nil } - if iconRaw.hasPrefix("emoji:") { - let value = String(iconRaw.dropFirst("emoji:".count)) - guard !value.isEmpty else { return nil } - return AnyView(Text(value).cmuxFont(size: 9 * fontScale)) - } - if iconRaw.hasPrefix("text:") { - let value = String(iconRaw.dropFirst("text:".count)) - guard !value.isEmpty else { return nil } - return AnyView(Text(value).cmuxFont(size: 8 * fontScale, weight: .semibold)) - } - let symbolName: String - if iconRaw.hasPrefix("sf:") { - symbolName = String(iconRaw.dropFirst("sf:".count)) - } else { - symbolName = iconRaw - } - guard !symbolName.isEmpty else { return nil } - return AnyView(CmuxSystemSymbolImage(magnified: symbolName, pointSize: 8 * fontScale, weight: .medium)) - } -} - -private struct SidebarMetadataEntryRow: View { - let entry: SidebarStatusEntry - let isActive: Bool - let activeForegroundColor: Color - let fontScale: CGFloat - let onFocus: () -> Void - - var body: some View { - Group { - if let url = entry.url { - Button { - onFocus() - NSWorkspace.shared.open(url) - } label: { - rowContent(underlined: true) - } - .buttonStyle(.plain) - .safeHelp(url.absoluteString) - } else { - rowContent(underlined: false) - .contentShape(Rectangle()) - .onTapGesture { onFocus() } - } - } - } - - @ViewBuilder - private func rowContent(underlined: Bool) -> some View { - HStack(spacing: 4) { - if let icon = iconView { - icon - .foregroundColor(foregroundColor.opacity(0.95)) - } - metadataText(underlined: underlined) - .lineLimit(1) - .truncationMode(.tail) - Spacer(minLength: 0) - } - .cmuxFont(size: 10 * fontScale) - .frame(maxWidth: .infinity, alignment: .leading) - } - - private var foregroundColor: Color { - if isActive, - let raw = entry.color, - Color(hex: raw) != nil { - return activeForegroundColor - } - if let raw = entry.color, let explicit = Color(hex: raw) { - return explicit - } - return isActive ? activeForegroundColor.opacity(0.84) : .secondary - } - - private var iconView: AnyView? { - guard let iconRaw = entry.icon?.trimmingCharacters(in: .whitespacesAndNewlines), - !iconRaw.isEmpty else { - return nil - } - if iconRaw.hasPrefix("emoji:") { - let value = String(iconRaw.dropFirst("emoji:".count)) - guard !value.isEmpty else { return nil } - return AnyView(Text(value).cmuxFont(size: 9 * fontScale)) - } - if iconRaw.hasPrefix("text:") { - let value = String(iconRaw.dropFirst("text:".count)) - guard !value.isEmpty else { return nil } - return AnyView(Text(value).cmuxFont(size: 8 * fontScale, weight: .semibold)) - } - let symbolName: String - if iconRaw.hasPrefix("sf:") { - symbolName = String(iconRaw.dropFirst("sf:".count)) - } else { - symbolName = iconRaw - } - guard !symbolName.isEmpty else { return nil } - return AnyView(CmuxSystemSymbolImage(magnified: symbolName, pointSize: 8 * fontScale, weight: .medium)) - } - - @ViewBuilder - private func metadataText(underlined: Bool) -> some View { - let trimmed = entry.value.trimmingCharacters(in: .whitespacesAndNewlines) - let display = trimmed.isEmpty ? entry.key : trimmed - if entry.format == .markdown, - let attributed = try? AttributedString( - markdown: display, - options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace) - ) { - Text(attributed) - .underline(underlined) - .foregroundColor(foregroundColor) - } else { - Text(display) - .underline(underlined) - .foregroundColor(foregroundColor) - } - } -} - private struct SidebarMetadataMarkdownBlocks: View { let blocks: [SidebarMetadataBlock] let isActive: Bool diff --git a/Sources/SidebarStatusRowViews.swift b/Sources/SidebarStatusRowViews.swift new file mode 100644 index 000000000000..64726d7d519c --- /dev/null +++ b/Sources/SidebarStatusRowViews.swift @@ -0,0 +1,336 @@ +import AppKit +import CmuxFoundation +import CmuxSidebar +import SwiftUI + +/// Sidebar per-workspace status rows: keyed metadata rows reported over the +/// control socket (`SidebarMetadataRows`) and per-agent-pane status rows +/// (`SidebarAgentStatusRows`). Rows receive immutable value snapshots plus +/// closure action bundles only, per the sidebar list snapshot-boundary rule. +struct SidebarMetadataRows: View { + let entries: [SidebarStatusEntry] + let isActive: Bool + let activeForegroundColor: Color + let activeSecondaryForegroundColor: Color + let fontScale: CGFloat + let onFocus: () -> Void + + @State private var isExpanded: Bool = false + private let collapsedEntryLimit = 3 + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + ForEach(visibleEntries, id: \.key) { entry in + SidebarMetadataEntryRow( + entry: entry, + isActive: isActive, + activeForegroundColor: activeForegroundColor, + fontScale: fontScale, + onFocus: onFocus + ) + } + + if shouldShowToggle { + Button(isExpanded ? String(localized: "sidebar.metadata.showLess", defaultValue: "Show less") : String(localized: "sidebar.metadata.showMore", defaultValue: "Show more")) { + onFocus() + withAnimation(.easeInOut(duration: 0.15)) { + isExpanded.toggle() + } + } + .buttonStyle(.plain) + .cmuxFont(size: 10 * fontScale, weight: .semibold) + .foregroundColor(isActive ? activeSecondaryForegroundColor : .secondary.opacity(0.9)) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + .safeHelp(helpText) + } + + private var visibleEntries: [SidebarStatusEntry] { + guard !isExpanded, entries.count > collapsedEntryLimit else { return entries } + return Array(entries.prefix(collapsedEntryLimit)) + } + + private var helpText: String { + entries.map { entry in + let trimmed = entry.value.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? entry.key : trimmed + } + .joined(separator: "\n") + } + + private var shouldShowToggle: Bool { + entries.count > collapsedEntryLimit + } +} + +struct SidebarAgentStatusRows: View { + let rows: [SidebarAgentStatusRow] + let isActive: Bool + let activeForegroundColor: Color + let fontScale: CGFloat + let onFocusPanel: (UUID) -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + ForEach(rows) { row in + SidebarAgentStatusEntryRow( + row: row, + isActive: isActive, + activeForegroundColor: activeForegroundColor, + fontScale: fontScale, + onFocusPanel: onFocusPanel + ) + } + } + } +} + +private struct SidebarAgentStatusEntryRow: View { + let row: SidebarAgentStatusRow + let isActive: Bool + let activeForegroundColor: Color + let fontScale: CGFloat + let onFocusPanel: (UUID) -> Void + + var body: some View { + Group { + if let url = row.url { + Button { + onFocusPanel(row.panelId) + NSWorkspace.shared.open(url) + } label: { + rowContent(underlined: true) + } + .buttonStyle(.plain) + .safeHelp(url.absoluteString) + } else { + rowContent(underlined: false) + .contentShape(Rectangle()) + .onTapGesture { onFocusPanel(row.panelId) } + .safeHelp(helpText) + } + } + } + + @ViewBuilder + private func rowContent(underlined: Bool) -> some View { + HStack(spacing: 4) { + if let icon = iconView { + icon + .foregroundColor(foregroundColor.opacity(0.95)) + } + Text(displayText) + .underline(underlined) + .foregroundColor(foregroundColor) + .lineLimit(1) + .truncationMode(.tail) + if let paneLabel = row.paneLabel { + Text(paneLabel) + .foregroundColor(isActive ? activeForegroundColor.opacity(0.6) : .secondary.opacity(0.8)) + .lineLimit(1) + .truncationMode(.middle) + } + Spacer(minLength: 0) + } + .cmuxFont(size: 10 * fontScale) + .frame(maxWidth: .infinity, alignment: .leading) + } + + private var displayText: String { + if let value = row.value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty { + return value + } + let name = Self.agentDisplayName(statusKey: row.statusKey) + if let lifecycleText { + return "\(name): \(lifecycleText)" + } + return name + } + + private var helpText: String { + guard let paneLabel = row.paneLabel else { return displayText } + return "\(displayText) (\(paneLabel))" + } + + private var lifecycleText: String? { + switch row.lifecycle { + case .running: + return String(localized: "sidebar.agentStatus.running", defaultValue: "Running") + case .needsInput: + return String(localized: "sidebar.agentStatus.needsInput", defaultValue: "Needs input") + case .idle: + return String(localized: "sidebar.agentStatus.idle", defaultValue: "Idle") + case .unknown, nil: + return nil + } + } + + static func agentDisplayName(statusKey: String) -> String { + statusKey + .split(separator: "_") + .map { $0.prefix(1).uppercased() + $0.dropFirst() } + .joined(separator: " ") + } + + private var effectiveIcon: String? { + if let icon = row.icon?.trimmingCharacters(in: .whitespacesAndNewlines), !icon.isEmpty { + return icon + } + switch row.lifecycle { + case .running: + return "bolt.fill" + case .needsInput: + return "exclamationmark.bubble.fill" + case .idle: + return "checkmark.circle" + case .unknown, nil: + return nil + } + } + + private var effectiveColorHex: String? { + if let color = row.color { + return color + } + switch row.lifecycle { + case .running: + return "#4C8DFF" + case .needsInput: + return "#FF9F0A" + case .idle, .unknown, nil: + return nil + } + } + + private var foregroundColor: Color { + if isActive { + return activeForegroundColor + } + if let raw = effectiveColorHex, let explicit = Color(hex: raw) { + return explicit + } + return .secondary + } + + private var iconView: AnyView? { + guard let iconRaw = effectiveIcon else { return nil } + if iconRaw.hasPrefix("emoji:") { + let value = String(iconRaw.dropFirst("emoji:".count)) + guard !value.isEmpty else { return nil } + return AnyView(Text(value).cmuxFont(size: 9 * fontScale)) + } + if iconRaw.hasPrefix("text:") { + let value = String(iconRaw.dropFirst("text:".count)) + guard !value.isEmpty else { return nil } + return AnyView(Text(value).cmuxFont(size: 8 * fontScale, weight: .semibold)) + } + let symbolName: String + if iconRaw.hasPrefix("sf:") { + symbolName = String(iconRaw.dropFirst("sf:".count)) + } else { + symbolName = iconRaw + } + guard !symbolName.isEmpty else { return nil } + return AnyView(CmuxSystemSymbolImage(magnified: symbolName, pointSize: 8 * fontScale, weight: .medium)) + } +} + +private struct SidebarMetadataEntryRow: View { + let entry: SidebarStatusEntry + let isActive: Bool + let activeForegroundColor: Color + let fontScale: CGFloat + let onFocus: () -> Void + + var body: some View { + Group { + if let url = entry.url { + Button { + onFocus() + NSWorkspace.shared.open(url) + } label: { + rowContent(underlined: true) + } + .buttonStyle(.plain) + .safeHelp(url.absoluteString) + } else { + rowContent(underlined: false) + .contentShape(Rectangle()) + .onTapGesture { onFocus() } + } + } + } + + @ViewBuilder + private func rowContent(underlined: Bool) -> some View { + HStack(spacing: 4) { + if let icon = iconView { + icon + .foregroundColor(foregroundColor.opacity(0.95)) + } + metadataText(underlined: underlined) + .lineLimit(1) + .truncationMode(.tail) + Spacer(minLength: 0) + } + .cmuxFont(size: 10 * fontScale) + .frame(maxWidth: .infinity, alignment: .leading) + } + + private var foregroundColor: Color { + if isActive, + let raw = entry.color, + Color(hex: raw) != nil { + return activeForegroundColor + } + if let raw = entry.color, let explicit = Color(hex: raw) { + return explicit + } + return isActive ? activeForegroundColor.opacity(0.84) : .secondary + } + + private var iconView: AnyView? { + guard let iconRaw = entry.icon?.trimmingCharacters(in: .whitespacesAndNewlines), + !iconRaw.isEmpty else { + return nil + } + if iconRaw.hasPrefix("emoji:") { + let value = String(iconRaw.dropFirst("emoji:".count)) + guard !value.isEmpty else { return nil } + return AnyView(Text(value).cmuxFont(size: 9 * fontScale)) + } + if iconRaw.hasPrefix("text:") { + let value = String(iconRaw.dropFirst("text:".count)) + guard !value.isEmpty else { return nil } + return AnyView(Text(value).cmuxFont(size: 8 * fontScale, weight: .semibold)) + } + let symbolName: String + if iconRaw.hasPrefix("sf:") { + symbolName = String(iconRaw.dropFirst("sf:".count)) + } else { + symbolName = iconRaw + } + guard !symbolName.isEmpty else { return nil } + return AnyView(CmuxSystemSymbolImage(magnified: symbolName, pointSize: 8 * fontScale, weight: .medium)) + } + + @ViewBuilder + private func metadataText(underlined: Bool) -> some View { + let trimmed = entry.value.trimmingCharacters(in: .whitespacesAndNewlines) + let display = trimmed.isEmpty ? entry.key : trimmed + if entry.format == .markdown, + let attributed = try? AttributedString( + markdown: display, + options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace) + ) { + Text(attributed) + .underline(underlined) + .foregroundColor(foregroundColor) + } else { + Text(display) + .underline(underlined) + .foregroundColor(foregroundColor) + } + } +} diff --git a/Sources/TerminalController+ControlSidebarContext.swift b/Sources/TerminalController+ControlSidebarContext.swift index d114465e3c43..47c0cce2eeac 100644 --- a/Sources/TerminalController+ControlSidebarContext.swift +++ b/Sources/TerminalController+ControlSidebarContext.swift @@ -43,9 +43,11 @@ extension TerminalController: ControlSidebarContext { format: appFormat, timestamp: Date() ) - // The panel-scoped copy is written unconditionally: the workspace - // slot is last-write-wins per key, so "no change" there can still - // be a change for this panel's own row. + // The panel-scoped copy is recorded independently of the workspace + // guard below: the workspace slot is last-write-wins per key, so + // "no change" there can still be a change for this panel's own row. + // recordPanelStatusEntry drops identical repeats itself so agent + // heartbeats do not churn the sidebar snapshot. if let panelId = panelID { tab.recordPanelStatusEntry(entry, panelId: panelId) } diff --git a/Sources/Workspace+PanelLifecycle.swift b/Sources/Workspace+PanelLifecycle.swift index 0c485a5c0b96..f32d4a625083 100644 --- a/Sources/Workspace+PanelLifecycle.swift +++ b/Sources/Workspace+PanelLifecycle.swift @@ -5,25 +5,8 @@ import Darwin import Foundation import CmuxSidebar -/// Immutable per-pane agent status row consumed by the sidebar (a value -/// snapshot only, per the sidebar list snapshot-boundary rule). -struct SidebarAgentStatusRow: Equatable, Identifiable { - let panelId: UUID - let statusKey: String - let value: String? - let icon: String? - let color: String? - let url: URL? - let lifecycle: AgentHibernationLifecycleState? - let paneLabel: String? - let priority: Int - let timestamp: Date - - var id: String { "\(panelId.uuidString)|\(statusKey)" } -} - extension Workspace { - private static let structuredAgentHookStatusKeys = AgentHibernationLifecycleStatusKeys.allowedStatusKeys + static let structuredAgentHookStatusKeys = AgentHibernationLifecycleStatusKeys.allowedStatusKeys private static let managedSubagentEnvironmentKey = "CMUX_AGENT_MANAGED_SUBAGENT" private static let truthyStartupEnvironmentValues: Set = ["1", "true", "yes", "on", "enabled"] @@ -52,45 +35,6 @@ extension Workspace { set { sidebarAgentRuntimeObservation.setAgentLifecycleStatesByPanelId(newValue) } } - var statusEntriesByPanelId: [UUID: [String: SidebarStatusEntry]] { - get { sidebarAgentRuntimeObservation.statusEntriesByPanelId } - set { sidebarAgentRuntimeObservation.setStatusEntriesByPanelId(newValue) } - } - - /// Records the panel-scoped copy of a structured agent status report, so - /// each agent pane keeps its own row even when several agents of the same - /// type share the workspace (the workspace-level `statusEntries` slot is - /// last-write-wins per agent type). - func recordPanelStatusEntry(_ entry: SidebarStatusEntry, panelId: UUID) { - guard Self.structuredAgentHookStatusKeys.contains(entry.key) else { return } - statusEntriesByPanelId[panelId, default: [:]][entry.key] = entry - } - - @discardableResult - func clearPanelStatusEntry(statusKey: String, panelId: UUID) -> Bool { - guard var entries = statusEntriesByPanelId[panelId], - entries.removeValue(forKey: statusKey) != nil else { - return false - } - if entries.isEmpty { - statusEntriesByPanelId.removeValue(forKey: panelId) - } else { - statusEntriesByPanelId[panelId] = entries - } - return true - } - - @discardableResult - func clearPanelStatusEntries(statusKey: String) -> Bool { - var didChange = false - for panelId in statusEntriesByPanelId.keys where statusEntriesByPanelId[panelId]?[statusKey] != nil { - if clearPanelStatusEntry(statusKey: statusKey, panelId: panelId) { - didChange = true - } - } - return didChange - } - func agentRuntimeState(forPanelId panelId: UUID) -> DetachedAgentRuntimeState? { let pidKeys = agentPIDKeysByPanelId[panelId] ?? [] @@ -103,7 +47,14 @@ extension Workspace { agentPIDIdentitiesForPanel[key] = agentPIDProcessIdentitiesByKey[key] } let statusKey = agentStatusKey(forAgentPIDKey: key) - if let statusEntry = statusEntriesByPanelId[panelId]?[statusKey] ?? statusEntries[statusKey] { + if let statusEntry = statusEntriesByPanelId[panelId]?[statusKey] { + statusEntriesForPanel[statusKey] = statusEntry + } else if panelsOwningAgentStatusKey(statusKey).isSubset(of: [panelId]), + let statusEntry = statusEntries[statusKey] { + // The workspace-level slot is last-write-wins across panes, so + // only attribute it to this panel when no other pane can own + // the key; otherwise a transferred pane would adopt a sibling + // agent's status text as its own. statusEntriesForPanel[statusKey] = statusEntry } } @@ -121,7 +72,7 @@ extension Workspace { ) } - private func agentStatusKey(forAgentPIDKey key: String) -> String { + func agentStatusKey(forAgentPIDKey key: String) -> String { if statusEntries[key] != nil { return key } @@ -297,150 +248,6 @@ extension Workspace { return Self.truthyStartupEnvironmentValues.contains(rawValue) } - func sidebarStatusEntriesVisibleForDisplay() -> [SidebarStatusEntry] { - let visibleStructuredStatusKeys = visibleStructuredAgentStatusKeysByPanel() - return statusEntries.values.filter { entry in - shouldDisplaySidebarStatusEntry(entry, visibleStructuredStatusKeys: visibleStructuredStatusKeys) - } - } - - private func shouldDisplaySidebarStatusEntry( - _ entry: SidebarStatusEntry, - visibleStructuredStatusKeys: Set - ) -> Bool { - guard Self.structuredAgentHookStatusKeys.contains(entry.key) else { - return true - } - return visibleStructuredStatusKeys.contains(entry.key) - } - - private func visibleStructuredAgentStatusKeysByPanel() -> Set { - var statusKeysByPanelId: [UUID: Set] = [:] - for (key, panelId) in agentPIDPanelIdsByKey - where panels[panelId] != nil { - let statusKey = agentStatusKey(forAgentPIDKey: key) - guard Self.structuredAgentHookStatusKeys.contains(statusKey), - statusEntries[statusKey] != nil else { - continue - } - statusKeysByPanelId[panelId, default: []].insert(statusKey) - } - var visibleStatusKeys = Set() - for statusKeys in statusKeysByPanelId.values { - let winningEntry = statusKeys.compactMap { statusEntries[$0] }.max { - isSidebarStatusEntryLessCurrent($0, than: $1) - } - if let winningEntry { - visibleStatusKeys.insert(winningEntry.key) - } - } - - for key in agentPIDs.keys where agentPIDPanelIdsByKey[key] == nil { - let statusKey = agentStatusKey(forAgentPIDKey: key) - guard Self.structuredAgentHookStatusKeys.contains(statusKey), - statusEntries[statusKey] != nil else { - continue - } - visibleStatusKeys.insert(statusKey) - } - - return visibleStatusKeys - } - - /// One sidebar row per live agent pane, so several agents in one workspace - /// never collapse into a single last-write-wins pill. A panel-scoped report - /// wins; the workspace-level entry is only trusted when a single pane owns - /// that status key; otherwise the per-panel lifecycle drives the row. - func sidebarAgentStatusRows() -> [SidebarAgentStatusRow] { - var statusKeysByPanel: [UUID: Set] = [:] - for (key, panelId) in agentPIDPanelIdsByKey where panels[panelId] != nil { - let statusKey = agentStatusKey(forAgentPIDKey: key) - guard Self.structuredAgentHookStatusKeys.contains(statusKey) else { continue } - statusKeysByPanel[panelId, default: []].insert(statusKey) - } - for (panelId, entries) in statusEntriesByPanelId where panels[panelId] != nil { - for statusKey in entries.keys where Self.structuredAgentHookStatusKeys.contains(statusKey) { - statusKeysByPanel[panelId, default: []].insert(statusKey) - } - } - - var chosenByPanel: [(panelId: UUID, statusKey: String, entry: SidebarStatusEntry?)] = [] - for (panelId, statusKeys) in statusKeysByPanel { - let candidates = statusKeys.map { ($0, statusEntriesByPanelId[panelId]?[$0]) } - let chosen = candidates.max { lhs, rhs in - switch (lhs.1, rhs.1) { - case let (lhsEntry?, rhsEntry?): - return isSidebarStatusEntryLessCurrent(lhsEntry, than: rhsEntry) - case (nil, .some): - return true - case (.some, nil): - return false - case (nil, nil): - return lhs.0 > rhs.0 - } - } - if let chosen { - chosenByPanel.append((panelId: panelId, statusKey: chosen.0, entry: chosen.1)) - } - } - - var panelCountByStatusKey: [String: Int] = [:] - for item in chosenByPanel { - panelCountByStatusKey[item.statusKey, default: 0] += 1 - } - - let includePaneLabels = chosenByPanel.count > 1 - let rows = chosenByPanel.map { item -> SidebarAgentStatusRow in - let workspaceEntry = statusEntries[item.statusKey] - let soleOwner = panelCountByStatusKey[item.statusKey] == 1 - let entry = item.entry ?? (soleOwner ? workspaceEntry : nil) - return SidebarAgentStatusRow( - panelId: item.panelId, - statusKey: item.statusKey, - value: entry?.value, - icon: entry?.icon ?? workspaceEntry?.icon, - color: entry?.color ?? workspaceEntry?.color, - url: entry?.url, - lifecycle: agentLifecycleStatesByPanelId[item.panelId]?[item.statusKey], - paneLabel: includePaneLabels ? agentStatusRowPaneLabel(panelId: item.panelId) : nil, - priority: entry?.priority ?? workspaceEntry?.priority ?? 0, - timestamp: entry?.timestamp ?? workspaceEntry?.timestamp ?? .distantPast - ) - } - return rows.sorted { lhs, rhs in - if lhs.priority != rhs.priority { return lhs.priority > rhs.priority } - if lhs.timestamp != rhs.timestamp { return lhs.timestamp > rhs.timestamp } - return lhs.id < rhs.id - } - } - - private func agentStatusRowPaneLabel(panelId: UUID) -> String? { - let candidates = [ - panelCustomTitles[panelId], - panelDirectoryDisplayLabels[panelId], - panelTitles[panelId], - ] - for candidate in candidates { - if let trimmed = candidate?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmed.isEmpty { - return trimmed - } - } - return nil - } - - private func isSidebarStatusEntryLessCurrent( - _ lhs: SidebarStatusEntry, - than rhs: SidebarStatusEntry - ) -> Bool { - if lhs.timestamp != rhs.timestamp { - return lhs.timestamp < rhs.timestamp - } - if lhs.priority != rhs.priority { - return lhs.priority < rhs.priority - } - return lhs.key > rhs.key - } - private func isStructuredAgentHookPIDKey(_ key: String) -> Bool { Self.structuredAgentHookStatusKeys.contains(agentStatusKey(forAgentPIDKey: key)) } diff --git a/Sources/Workspace+SidebarAgentStatus.swift b/Sources/Workspace+SidebarAgentStatus.swift new file mode 100644 index 000000000000..3a04187cdc18 --- /dev/null +++ b/Sources/Workspace+SidebarAgentStatus.swift @@ -0,0 +1,234 @@ +import CmuxSidebar +import Foundation + +/// Immutable per-pane agent status row consumed by the sidebar (a value +/// snapshot only, per the sidebar list snapshot-boundary rule). +struct SidebarAgentStatusRow: Equatable, Identifiable { + let panelId: UUID + let statusKey: String + let value: String? + let icon: String? + let color: String? + let url: URL? + let lifecycle: AgentHibernationLifecycleState? + let paneLabel: String? + let priority: Int + let timestamp: Date + + var id: String { "\(panelId.uuidString)|\(statusKey)" } +} + +/// Panel-scoped structured agent status: storage, visibility filtering, and +/// the per-agent sidebar row projection. Lifecycle bookkeeping (PID ownership, +/// transfer, cleanup) stays in `Workspace+PanelLifecycle.swift`. +extension Workspace { + var statusEntriesByPanelId: [UUID: [String: SidebarStatusEntry]] { + get { sidebarAgentRuntimeObservation.statusEntriesByPanelId } + set { sidebarAgentRuntimeObservation.setStatusEntriesByPanelId(newValue) } + } + + /// Records the panel-scoped copy of a structured agent status report, so + /// each agent pane keeps its own row even when several agents of the same + /// type share the workspace (the workspace-level `statusEntries` slot is + /// last-write-wins per agent type). Identical repeated reports are dropped + /// (ignoring the timestamp) so agent heartbeats with no visible change do + /// not invalidate the sidebar snapshot. + func recordPanelStatusEntry(_ entry: SidebarStatusEntry, panelId: UUID) { + guard Self.structuredAgentHookStatusKeys.contains(entry.key) else { return } + guard TerminalController.shouldReplaceStatusEntry( + current: statusEntriesByPanelId[panelId]?[entry.key], + key: entry.key, + value: entry.value, + icon: entry.icon, + color: entry.color, + url: entry.url, + priority: entry.priority, + format: entry.format + ) else { return } + statusEntriesByPanelId[panelId, default: [:]][entry.key] = entry + } + + @discardableResult + func clearPanelStatusEntry(statusKey: String, panelId: UUID) -> Bool { + guard var entries = statusEntriesByPanelId[panelId], + entries.removeValue(forKey: statusKey) != nil else { + return false + } + if entries.isEmpty { + statusEntriesByPanelId.removeValue(forKey: panelId) + } else { + statusEntriesByPanelId[panelId] = entries + } + return true + } + + @discardableResult + func clearPanelStatusEntries(statusKey: String) -> Bool { + var didChange = false + for panelId in statusEntriesByPanelId.keys where statusEntriesByPanelId[panelId]?[statusKey] != nil { + if clearPanelStatusEntry(statusKey: statusKey, panelId: panelId) { + didChange = true + } + } + return didChange + } + + /// Every panel that plausibly owns `statusKey`: panels with a live agent + /// PID mapping to that key plus panels holding a panel-scoped entry for + /// it. Used to decide whether the ambiguous workspace-level last-write-wins + /// entry can be attributed to a single pane. + func panelsOwningAgentStatusKey(_ statusKey: String) -> Set { + var owners: Set = [] + for (key, ownerPanelId) in agentPIDPanelIdsByKey + where agentStatusKey(forAgentPIDKey: key) == statusKey { + owners.insert(ownerPanelId) + } + for (ownerPanelId, entries) in statusEntriesByPanelId where entries[statusKey] != nil { + owners.insert(ownerPanelId) + } + return owners + } + + func sidebarStatusEntriesVisibleForDisplay() -> [SidebarStatusEntry] { + let visibleStructuredStatusKeys = visibleStructuredAgentStatusKeysByPanel() + return statusEntries.values.filter { entry in + shouldDisplaySidebarStatusEntry(entry, visibleStructuredStatusKeys: visibleStructuredStatusKeys) + } + } + + private func shouldDisplaySidebarStatusEntry( + _ entry: SidebarStatusEntry, + visibleStructuredStatusKeys: Set + ) -> Bool { + guard Self.structuredAgentHookStatusKeys.contains(entry.key) else { + return true + } + return visibleStructuredStatusKeys.contains(entry.key) + } + + private func visibleStructuredAgentStatusKeysByPanel() -> Set { + var statusKeysByPanelId: [UUID: Set] = [:] + for (key, panelId) in agentPIDPanelIdsByKey + where panels[panelId] != nil { + let statusKey = agentStatusKey(forAgentPIDKey: key) + guard Self.structuredAgentHookStatusKeys.contains(statusKey), + statusEntries[statusKey] != nil else { + continue + } + statusKeysByPanelId[panelId, default: []].insert(statusKey) + } + var visibleStatusKeys = Set() + for statusKeys in statusKeysByPanelId.values { + let winningEntry = statusKeys.compactMap { statusEntries[$0] }.max { + isSidebarStatusEntryLessCurrent($0, than: $1) + } + if let winningEntry { + visibleStatusKeys.insert(winningEntry.key) + } + } + + for key in agentPIDs.keys where agentPIDPanelIdsByKey[key] == nil { + let statusKey = agentStatusKey(forAgentPIDKey: key) + guard Self.structuredAgentHookStatusKeys.contains(statusKey), + statusEntries[statusKey] != nil else { + continue + } + visibleStatusKeys.insert(statusKey) + } + + return visibleStatusKeys + } + + /// One sidebar row per live agent pane, so several agents in one workspace + /// never collapse into a single last-write-wins pill. Rows are keyed off + /// recorded agent PID ownership (the deterministic cmux-owned signal), so a + /// bare panel-scoped text report can neither create an unowned row nor keep + /// a stale one alive after the agent's PID is cleared. A panel-scoped + /// report wins; the workspace-level entry is only trusted when a single + /// pane owns that status key; otherwise the per-panel lifecycle drives the + /// row. + func sidebarAgentStatusRows() -> [SidebarAgentStatusRow] { + var statusKeysByPanel: [UUID: Set] = [:] + for (key, panelId) in agentPIDPanelIdsByKey where panels[panelId] != nil { + let statusKey = agentStatusKey(forAgentPIDKey: key) + guard Self.structuredAgentHookStatusKeys.contains(statusKey) else { continue } + statusKeysByPanel[panelId, default: []].insert(statusKey) + } + + var chosenByPanel: [(panelId: UUID, statusKey: String, entry: SidebarStatusEntry?)] = [] + for (panelId, statusKeys) in statusKeysByPanel { + let candidates = statusKeys.map { ($0, statusEntriesByPanelId[panelId]?[$0]) } + let chosen = candidates.max { lhs, rhs in + switch (lhs.1, rhs.1) { + case let (lhsEntry?, rhsEntry?): + return isSidebarStatusEntryLessCurrent(lhsEntry, than: rhsEntry) + case (nil, .some): + return true + case (.some, nil): + return false + case (nil, nil): + return lhs.0 > rhs.0 + } + } + if let chosen { + chosenByPanel.append((panelId: panelId, statusKey: chosen.0, entry: chosen.1)) + } + } + + var panelCountByStatusKey: [String: Int] = [:] + for item in chosenByPanel { + panelCountByStatusKey[item.statusKey, default: 0] += 1 + } + + let includePaneLabels = chosenByPanel.count > 1 + let rows = chosenByPanel.map { item -> SidebarAgentStatusRow in + let workspaceEntry = statusEntries[item.statusKey] + let soleOwner = panelCountByStatusKey[item.statusKey] == 1 + let entry = item.entry ?? (soleOwner ? workspaceEntry : nil) + return SidebarAgentStatusRow( + panelId: item.panelId, + statusKey: item.statusKey, + value: entry?.value, + icon: entry?.icon ?? (soleOwner ? workspaceEntry?.icon : nil), + color: entry?.color ?? (soleOwner ? workspaceEntry?.color : nil), + url: entry?.url, + lifecycle: agentLifecycleStatesByPanelId[item.panelId]?[item.statusKey], + paneLabel: includePaneLabels ? agentStatusRowPaneLabel(panelId: item.panelId) : nil, + priority: entry?.priority ?? workspaceEntry?.priority ?? 0, + timestamp: entry?.timestamp ?? workspaceEntry?.timestamp ?? .distantPast + ) + } + return rows.sorted { lhs, rhs in + if lhs.priority != rhs.priority { return lhs.priority > rhs.priority } + if lhs.timestamp != rhs.timestamp { return lhs.timestamp > rhs.timestamp } + return lhs.id < rhs.id + } + } + + private func agentStatusRowPaneLabel(panelId: UUID) -> String? { + let candidates = [ + panelCustomTitles[panelId], + panelDirectoryDisplayLabels[panelId], + panelTitles[panelId], + ] + for candidate in candidates { + if let trimmed = candidate?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmed.isEmpty { + return trimmed + } + } + return nil + } + + private func isSidebarStatusEntryLessCurrent( + _ lhs: SidebarStatusEntry, + than rhs: SidebarStatusEntry + ) -> Bool { + if lhs.timestamp != rhs.timestamp { + return lhs.timestamp < rhs.timestamp + } + if lhs.priority != rhs.priority { + return lhs.priority < rhs.priority + } + return lhs.key > rhs.key + } +} diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index c7cad8e1d986..4c0d9d43fb4a 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1080,6 +1080,7 @@ C9A57513C9A57513C9A57513 /* SidebarScrollViewConfiguratorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9A57514C9A57514C9A57514 /* SidebarScrollViewConfiguratorTests.swift */; }; E62155868BB29FEB5DAAAF25 /* SidebarSelectionState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD52285508B1D6A9875E7B3 /* SidebarSelectionState.swift */; }; F57072635F25EBCA741E125D /* SidebarState.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1614EAD3CCF70A177A51BD1 /* SidebarState.swift */; }; + 7A11AA037A11AA037A11AA03 /* SidebarStatusRowViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A11AA047A11AA047A11AA04 /* SidebarStatusRowViews.swift */; }; D7344F010000000000000001 /* SidebarTabDragPayload.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7344F010000000000000002 /* SidebarTabDragPayload.swift */; }; D73440010000000000000001 /* SidebarTabDragPayloadProviderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D73440010000000000000002 /* SidebarTabDragPayloadProviderTests.swift */; }; D7AB34300000000000000105 /* SidebarTabDropIndicatorPredicateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34300000000000000106 /* SidebarTabDropIndicatorPredicateTests.swift */; }; @@ -1361,6 +1362,7 @@ F17F00000000000000000005 /* Workspace+FullWidthTab.swift in Sources */ = {isa = PBXBuildFile; fileRef = F17F00000000000000000006 /* Workspace+FullWidthTab.swift */; }; C0DE1A050000000000000001 /* Workspace+LayoutCapture.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE1A050000000000000002 /* Workspace+LayoutCapture.swift */; }; C3744E010000000000000001 /* Workspace+PanelLifecycle.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3744E020000000000000001 /* Workspace+PanelLifecycle.swift */; }; + 7A11AA017A11AA017A11AA01 /* Workspace+SidebarAgentStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A11AA027A11AA027A11AA02 /* Workspace+SidebarAgentStatus.swift */; }; C7268002000000000000001 /* Workspace+SidebarDirectories.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7268002000000000000002 /* Workspace+SidebarDirectories.swift */; }; CA52B0170000000000000000 /* Workspace+SurfaceNavigation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA52C0170000000000000000 /* Workspace+SurfaceNavigation.swift */; }; E3B7A400000000000000020A /* Workspace+WorkspaceSurfaceTreeReading.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3B7A400000000000000020B /* Workspace+WorkspaceSurfaceTreeReading.swift */; }; @@ -2514,6 +2516,7 @@ C9A57514C9A57514C9A57514 /* SidebarScrollViewConfiguratorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarScrollViewConfiguratorTests.swift; sourceTree = ""; }; 9AD52285508B1D6A9875E7B3 /* SidebarSelectionState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarSelectionState.swift; sourceTree = ""; }; D1614EAD3CCF70A177A51BD1 /* SidebarState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarState.swift; sourceTree = ""; }; + 7A11AA047A11AA047A11AA04 /* SidebarStatusRowViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarStatusRowViews.swift; sourceTree = ""; }; D7344F010000000000000002 /* SidebarTabDragPayload.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarTabDragPayload.swift; sourceTree = ""; }; D73440010000000000000002 /* SidebarTabDragPayloadProviderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarTabDragPayloadProviderTests.swift; sourceTree = ""; }; D7AB34300000000000000106 /* SidebarTabDropIndicatorPredicateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarTabDropIndicatorPredicateTests.swift; sourceTree = ""; }; @@ -2790,6 +2793,7 @@ F17F00000000000000000006 /* Workspace+FullWidthTab.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+FullWidthTab.swift"; sourceTree = ""; }; C0DE1A050000000000000002 /* Workspace+LayoutCapture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+LayoutCapture.swift"; sourceTree = ""; }; C3744E020000000000000001 /* Workspace+PanelLifecycle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+PanelLifecycle.swift"; sourceTree = ""; }; + 7A11AA027A11AA027A11AA02 /* Workspace+SidebarAgentStatus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+SidebarAgentStatus.swift"; sourceTree = ""; }; C7268002000000000000002 /* Workspace+SidebarDirectories.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+SidebarDirectories.swift"; sourceTree = ""; }; CA52C0170000000000000000 /* Workspace+SurfaceNavigation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+SurfaceNavigation.swift"; sourceTree = ""; }; E3B7A400000000000000020B /* Workspace+WorkspaceSurfaceTreeReading.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+WorkspaceSurfaceTreeReading.swift"; sourceTree = ""; }; @@ -3389,6 +3393,8 @@ A5001416 /* Workspace.swift */, C3744E040000000000000001 /* AgentPIDProcessIdentity.swift */, 6799A0026799A0026799A002 /* WorkspaceSidebarAgentRuntimeObservationModel.swift */, + 7A11AA027A11AA027A11AA02 /* Workspace+SidebarAgentStatus.swift */, + 7A11AA047A11AA047A11AA04 /* SidebarStatusRowViews.swift */, C0A1E5CE01C0A1E5CE01A002 /* CoalesceLatestPublisher.swift */, 5659A0025659A0025659A002 /* WorkspaceSidebarObservation.swift */, 5659B0025659B0025659B002 /* WorkspaceSidebarLogEntryLimitProvider.swift */, @@ -5457,6 +5463,7 @@ C0DE35010000000000000001 /* SidebarScrim.swift in Sources */, E62155868BB29FEB5DAAAF25 /* SidebarSelectionState.swift in Sources */, F57072635F25EBCA741E125D /* SidebarState.swift in Sources */, + 7A11AA037A11AA037A11AA03 /* SidebarStatusRowViews.swift in Sources */, D7344F010000000000000001 /* SidebarTabDragPayload.swift in Sources */, C9A57605C9A57605C9A57605 /* SidebarWorkspaceDropTargetWriters.swift in Sources */, C9A57103C9A57103C9A57103 /* SidebarWorkspaceGroupConfigOpener.swift in Sources */, @@ -5662,6 +5669,7 @@ F17F00000000000000000005 /* Workspace+FullWidthTab.swift in Sources */, C0DE1A050000000000000001 /* Workspace+LayoutCapture.swift in Sources */, C3744E010000000000000001 /* Workspace+PanelLifecycle.swift in Sources */, + 7A11AA017A11AA017A11AA01 /* Workspace+SidebarAgentStatus.swift in Sources */, C7268002000000000000001 /* Workspace+SidebarDirectories.swift in Sources */, CA52B0170000000000000000 /* Workspace+SurfaceNavigation.swift in Sources */, E3B7A400000000000000020A /* Workspace+WorkspaceSurfaceTreeReading.swift in Sources */, diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 20f62609960a..6ffb23ec4020 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -21,6 +21,41 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { ) } + @MainActor + func testIdenticalPanelStatusReportDoesNotReplaceStoredEntry() throws { + let workspace = Workspace() + let panelId = try XCTUnwrap(workspace.focusedPanelId) + + let first = makeEntry(key: "claude_code", value: "Running", timestamp: Date(timeIntervalSince1970: 100)) + workspace.recordPanelStatusEntry(first, panelId: panelId) + let repeated = makeEntry(key: "claude_code", value: "Running", timestamp: Date(timeIntervalSince1970: 200)) + workspace.recordPanelStatusEntry(repeated, panelId: panelId) + // Same display content, newer timestamp: dropped so agent heartbeats + // do not invalidate the sidebar snapshot. + XCTAssertEqual(workspace.statusEntriesByPanelId[panelId]?["claude_code"], first) + + let changed = makeEntry(key: "claude_code", value: "Idle", timestamp: Date(timeIntervalSince1970: 300)) + workspace.recordPanelStatusEntry(changed, panelId: panelId) + XCTAssertEqual(workspace.statusEntriesByPanelId[panelId]?["claude_code"], changed) + } + + @MainActor + func testAmbiguousWorkspaceStatusIsNotAttributedDuringTransfer() throws { + let workspace = Workspace() + let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) + let paneId = try XCTUnwrap(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try XCTUnwrap(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + workspace.recordAgentPID(key: "claude_code.first", pid: 111, panelId: firstPanelId, refreshPorts: false) + workspace.recordAgentPID(key: "claude_code.second", pid: 222, panelId: secondPanelId, refreshPorts: false) + // Only the workspace-level last-write-wins slot has text; either pane + // could have written it, so it must not ride along with a transfer. + workspace.statusEntries["claude_code"] = makeEntry(key: "claude_code", value: "Running") + + let runtimeState = try XCTUnwrap(workspace.agentRuntimeState(forPanelId: secondPanelId)) + XCTAssertNil(runtimeState.statusEntries["claude_code"]) + } + @MainActor func testTwoAgentsOfSameTypeKeepSeparateRows() throws { let workspace = Workspace() @@ -82,10 +117,36 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { // The ambiguous workspace-level text must not be attributed to either pane. XCTAssertNil(byPanel[firstPanelId]?.value) XCTAssertNil(byPanel[secondPanelId]?.value) + // Nor its decorations: the last writer's icon/color must not bleed + // onto the other pane's row. + XCTAssertNil(byPanel[firstPanelId]?.icon) + XCTAssertNil(byPanel[secondPanelId]?.icon) + XCTAssertNil(byPanel[firstPanelId]?.color) + XCTAssertNil(byPanel[secondPanelId]?.color) XCTAssertEqual(byPanel[firstPanelId]?.lifecycle, .running) XCTAssertEqual(byPanel[secondPanelId]?.lifecycle, .needsInput) } + @MainActor + func testPanelEntryWithoutAgentPIDDoesNotCreateRow() throws { + let workspace = Workspace() + let panelId = try XCTUnwrap(workspace.focusedPanelId) + + // A bare panel-scoped text report with no recorded agent PID has no + // deterministic owner to clear it, so it must not create a row. + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: panelId) + XCTAssertTrue(workspace.sidebarAgentStatusRows().isEmpty) + + // Recording the PID makes the same entry visible; clearing the PID + // without clearing status removes the row again (no stale rows). + workspace.recordAgentPID(key: "claude_code.owner", pid: 111, panelId: panelId, refreshPorts: false) + XCTAssertEqual(workspace.sidebarAgentStatusRows().map(\.panelId), [panelId]) + XCTAssertTrue( + workspace.clearAgentPID(key: "claude_code.owner", panelId: panelId, clearStatus: false, refreshPorts: false) + ) + XCTAssertTrue(workspace.sidebarAgentStatusRows().isEmpty) + } + @MainActor func testClearingAgentPIDRemovesThatPanelsRow() throws { let workspace = Workspace() From 6e1995109c1b72f6abee6eec8737b26a03e4243a Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 18:47:30 -0700 Subject: [PATCH 04/46] sidebar per-agent rows: gate panel status clear on remaining same-key sessions A panel can hold several PID keys for one base status key (two sessions of the same agent type); clearAgentPID(clearStatus: true) now drops the panel- scoped entry only when no remaining key on that panel maps to the status key, so a stale session's cleanup cannot erase a live session's row. Mirrors the existing hasAgentRuntime gate that protects the workspace-level entry. Test: testStaleSessionCleanupKeepsLiveSameKeySessionEntry. --- Sources/Workspace+PanelLifecycle.swift | 14 ++++++++++- cmuxTests/PerAgentSidebarStatusRowTests.swift | 25 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/Sources/Workspace+PanelLifecycle.swift b/Sources/Workspace+PanelLifecycle.swift index f32d4a625083..f045688f9917 100644 --- a/Sources/Workspace+PanelLifecycle.swift +++ b/Sources/Workspace+PanelLifecycle.swift @@ -82,6 +82,12 @@ extension Workspace { return String(key[.. Bool { + (agentPIDKeysByPanelId[panelId] ?? []).contains { + agentStatusKey(forAgentPIDKey: $0) == statusKey + } + } + private func hasAgentRuntime(forStatusKey statusKey: String) -> Bool { for key in agentPIDs.keys where agentStatusKey(forAgentPIDKey: key) == statusKey { return true @@ -281,7 +287,13 @@ extension Workspace { if clearAgentLifecycle(key: lifecycleStatusKey, panelId: lifecyclePanelId) { didChange = true } - if let statusKeyToClear, clearPanelStatusEntry(statusKey: statusKeyToClear, panelId: lifecyclePanelId) { + // A panel can hold several PID keys for the same base status key + // (e.g. two sessions of one agent type); only drop the panel's + // status entry once no remaining key on the panel owns it, so a + // stale session's cleanup cannot erase a live session's row. + if let statusKeyToClear, + !panelHasAgentRuntime(forStatusKey: statusKeyToClear, panelId: lifecyclePanelId), + clearPanelStatusEntry(statusKey: statusKeyToClear, panelId: lifecyclePanelId) { didChange = true } } diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 6ffb23ec4020..17684eee02d9 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -147,6 +147,31 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { XCTAssertTrue(workspace.sidebarAgentStatusRows().isEmpty) } + @MainActor + func testStaleSessionCleanupKeepsLiveSameKeySessionEntry() throws { + let workspace = Workspace() + let panelId = try XCTUnwrap(workspace.focusedPanelId) + + // Two sessions of the same agent type can coexist on one panel. + workspace.recordAgentPID(key: "claude_code.old", pid: 111, panelId: panelId, refreshPorts: false) + workspace.recordAgentPID(key: "claude_code.new", pid: 222, panelId: panelId, refreshPorts: false) + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: panelId) + + // The stale session's cleanup must not erase the live session's entry. + XCTAssertTrue( + workspace.clearAgentPID(key: "claude_code.old", panelId: panelId, clearStatus: true, refreshPorts: false) + ) + XCTAssertEqual(workspace.statusEntriesByPanelId[panelId]?["claude_code"]?.value, "Running") + XCTAssertEqual(workspace.sidebarAgentStatusRows().map(\.panelId), [panelId]) + + // Clearing the last owner drops the entry. + XCTAssertTrue( + workspace.clearAgentPID(key: "claude_code.new", panelId: panelId, clearStatus: true, refreshPorts: false) + ) + XCTAssertNil(workspace.statusEntriesByPanelId[panelId]?["claude_code"]) + XCTAssertTrue(workspace.sidebarAgentStatusRows().isEmpty) + } + @MainActor func testClearingAgentPIDRemovesThatPanelsRow() throws { let workspace = Workspace() From 7e83b711ca26251097e620785cd367a177d43493 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 18:52:16 -0700 Subject: [PATCH 05/46] Revert "sidebar per-agent rows: gate panel status clear on remaining same-key sessions" This reverts commit 6e1995109c1b72f6abee6eec8737b26a03e4243a. --- Sources/Workspace+PanelLifecycle.swift | 14 +---------- cmuxTests/PerAgentSidebarStatusRowTests.swift | 25 ------------------- 2 files changed, 1 insertion(+), 38 deletions(-) diff --git a/Sources/Workspace+PanelLifecycle.swift b/Sources/Workspace+PanelLifecycle.swift index f045688f9917..f32d4a625083 100644 --- a/Sources/Workspace+PanelLifecycle.swift +++ b/Sources/Workspace+PanelLifecycle.swift @@ -82,12 +82,6 @@ extension Workspace { return String(key[.. Bool { - (agentPIDKeysByPanelId[panelId] ?? []).contains { - agentStatusKey(forAgentPIDKey: $0) == statusKey - } - } - private func hasAgentRuntime(forStatusKey statusKey: String) -> Bool { for key in agentPIDs.keys where agentStatusKey(forAgentPIDKey: key) == statusKey { return true @@ -287,13 +281,7 @@ extension Workspace { if clearAgentLifecycle(key: lifecycleStatusKey, panelId: lifecyclePanelId) { didChange = true } - // A panel can hold several PID keys for the same base status key - // (e.g. two sessions of one agent type); only drop the panel's - // status entry once no remaining key on the panel owns it, so a - // stale session's cleanup cannot erase a live session's row. - if let statusKeyToClear, - !panelHasAgentRuntime(forStatusKey: statusKeyToClear, panelId: lifecyclePanelId), - clearPanelStatusEntry(statusKey: statusKeyToClear, panelId: lifecyclePanelId) { + if let statusKeyToClear, clearPanelStatusEntry(statusKey: statusKeyToClear, panelId: lifecyclePanelId) { didChange = true } } diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 17684eee02d9..6ffb23ec4020 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -147,31 +147,6 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { XCTAssertTrue(workspace.sidebarAgentStatusRows().isEmpty) } - @MainActor - func testStaleSessionCleanupKeepsLiveSameKeySessionEntry() throws { - let workspace = Workspace() - let panelId = try XCTUnwrap(workspace.focusedPanelId) - - // Two sessions of the same agent type can coexist on one panel. - workspace.recordAgentPID(key: "claude_code.old", pid: 111, panelId: panelId, refreshPorts: false) - workspace.recordAgentPID(key: "claude_code.new", pid: 222, panelId: panelId, refreshPorts: false) - workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: panelId) - - // The stale session's cleanup must not erase the live session's entry. - XCTAssertTrue( - workspace.clearAgentPID(key: "claude_code.old", panelId: panelId, clearStatus: true, refreshPorts: false) - ) - XCTAssertEqual(workspace.statusEntriesByPanelId[panelId]?["claude_code"]?.value, "Running") - XCTAssertEqual(workspace.sidebarAgentStatusRows().map(\.panelId), [panelId]) - - // Clearing the last owner drops the entry. - XCTAssertTrue( - workspace.clearAgentPID(key: "claude_code.new", panelId: panelId, clearStatus: true, refreshPorts: false) - ) - XCTAssertNil(workspace.statusEntriesByPanelId[panelId]?["claude_code"]) - XCTAssertTrue(workspace.sidebarAgentStatusRows().isEmpty) - } - @MainActor func testClearingAgentPIDRemovesThatPanelsRow() throws { let workspace = Workspace() From 97acf0a1a28df487d448aea58b8299acd534fcff Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 18:59:26 -0700 Subject: [PATCH 06/46] sidebar per-agent rows: record PID ownership before the panel-scoped write recordAgentPID evicts stale structured runtimes on the panel (agent replacement in the same pane), and that cleanup clears their panel-scoped status entries. The upsert previously wrote the new panel-scoped entry first, so the eviction deleted the just-recorded row text. The upsert now updates the workspace slot (guarded), records PID ownership, then writes the panel-scoped copy last. Test: testAgentReplacementOnSamePanelKeepsFreshPanelEntry. --- ...inalController+ControlSidebarContext.swift | 32 +++++++++---------- cmuxTests/PerAgentSidebarStatusRowTests.swift | 21 ++++++++++++ 2 files changed, 37 insertions(+), 16 deletions(-) diff --git a/Sources/TerminalController+ControlSidebarContext.swift b/Sources/TerminalController+ControlSidebarContext.swift index 47c0cce2eeac..9e78a7d16c24 100644 --- a/Sources/TerminalController+ControlSidebarContext.swift +++ b/Sources/TerminalController+ControlSidebarContext.swift @@ -43,15 +43,7 @@ extension TerminalController: ControlSidebarContext { format: appFormat, timestamp: Date() ) - // The panel-scoped copy is recorded independently of the workspace - // guard below: the workspace slot is last-write-wins per key, so - // "no change" there can still be a change for this panel's own row. - // recordPanelStatusEntry drops identical repeats itself so agent - // heartbeats do not churn the sidebar snapshot. - if let panelId = panelID { - tab.recordPanelStatusEntry(entry, panelId: panelId) - } - guard Self.shouldReplaceStatusEntry( + if Self.shouldReplaceStatusEntry( current: tab.statusEntries[key], key: key, value: value, @@ -60,17 +52,25 @@ extension TerminalController: ControlSidebarContext { url: url, priority: priority, format: appFormat - ) else { - // Still update PID tracking even if the status display hasn't changed. - if let pid { - tab.recordAgentPID(key: key, pid: pid, panelId: panelID) - } - return + ) { + tab.statusEntries[key] = entry } - tab.statusEntries[key] = entry + // PID tracking updates even when the status display hasn't changed. + // It must also run BEFORE the panel-scoped write below: recording a + // new agent PID evicts stale structured runtimes on the panel and + // that cleanup clears their panel-scoped entries, so writing the + // panel copy first would let the eviction delete it. if let pid { tab.recordAgentPID(key: key, pid: pid, panelId: panelID) } + // The panel-scoped copy is recorded independently of the workspace + // guard above: the workspace slot is last-write-wins per key, so + // "no change" there can still be a change for this panel's own row. + // recordPanelStatusEntry drops identical repeats itself so agent + // heartbeats do not churn the sidebar snapshot. + if let panelId = panelID { + tab.recordPanelStatusEntry(entry, panelId: panelId) + } } } diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 6ffb23ec4020..034ed6d1d553 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -147,6 +147,27 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { XCTAssertTrue(workspace.sidebarAgentStatusRows().isEmpty) } + @MainActor + func testAgentReplacementOnSamePanelKeepsFreshPanelEntry() throws { + let workspace = Workspace() + let panelId = try XCTUnwrap(workspace.focusedPanelId) + + workspace.recordAgentPID(key: "claude_code.old", pid: 111, panelId: panelId, refreshPorts: false) + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Old session"), panelId: panelId) + + // A new session replacing the agent on the same panel: PID recording + // runs first (evicting the stale runtime, which clears its panel + // entry), then the new report's panel-scoped write. This is the upsert + // order the control-socket path uses; writing the panel copy first + // would let the eviction delete the fresh entry. + workspace.recordAgentPID(key: "claude_code.new", pid: 222, panelId: panelId, refreshPorts: false) + XCTAssertNil(workspace.statusEntriesByPanelId[panelId]?["claude_code"]) + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "New session"), panelId: panelId) + + XCTAssertEqual(workspace.statusEntriesByPanelId[panelId]?["claude_code"]?.value, "New session") + XCTAssertEqual(workspace.sidebarAgentStatusRows().first?.value, "New session") + } + @MainActor func testClearingAgentPIDRemovesThatPanelsRow() throws { let workspace = Workspace() From ba8ab517023b581e7394822f19b9e372be0c93c6 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 19:14:03 -0700 Subject: [PATCH 07/46] sidebar per-agent rows: seed rows from PID ownership OR live panel entries Claude Code hooks share ONE bare PID key per agent type across all panes of a workspace (set_agent_pid claude_code ), so bare-key ownership migrates to the last reporting pane. Seeding rows from PID ownership alone made every other pane lose its row, reintroducing the exact collapse this PR fixes (reproduced live with two panes running the real hook sequence). sidebarAgentStatusRows() now derives candidate (panel, statusKey) pairs from the union of recorded PID ownership and live panels holding a panel-scoped structured entry. Stale entries stay bounded: clear_status, clearAgentPID(clearStatus: true), and pane close all drop panel-scoped entries. Regression test: testBareSharedPIDKeyHookSequenceKeepsBothPanesRows simulates the bare-key two-pane hook sequence end-to-end at the Workspace level. --- Sources/Workspace+SidebarAgentStatus.swift | 22 ++++++---- cmuxTests/PerAgentSidebarStatusRowTests.swift | 40 +++++++++++++------ 2 files changed, 42 insertions(+), 20 deletions(-) diff --git a/Sources/Workspace+SidebarAgentStatus.swift b/Sources/Workspace+SidebarAgentStatus.swift index 3a04187cdc18..f358d99b01d9 100644 --- a/Sources/Workspace+SidebarAgentStatus.swift +++ b/Sources/Workspace+SidebarAgentStatus.swift @@ -140,13 +140,16 @@ extension Workspace { } /// One sidebar row per live agent pane, so several agents in one workspace - /// never collapse into a single last-write-wins pill. Rows are keyed off - /// recorded agent PID ownership (the deterministic cmux-owned signal), so a - /// bare panel-scoped text report can neither create an unowned row nor keep - /// a stale one alive after the agent's PID is cleared. A panel-scoped - /// report wins; the workspace-level entry is only trusted when a single - /// pane owns that status key; otherwise the per-panel lifecycle drives the - /// row. + /// never collapse into a single last-write-wins pill. Candidate + /// (panel, statusKey) pairs are the UNION of recorded agent PID ownership + /// and live panels holding a panel-scoped structured entry: Claude-style + /// hooks share one bare PID key per agent type across panes (ownership + /// migrates to the last reporter), so the panel-scoped entry must keep a + /// pane's row alive independently. Stale entries stay bounded because + /// `clear_status`, `clearAgentPID(clearStatus: true)`, and pane close all + /// drop panel-scoped entries. A panel-scoped report wins; the + /// workspace-level entry is only trusted when a single pane owns that + /// status key; otherwise the per-panel lifecycle drives the row. func sidebarAgentStatusRows() -> [SidebarAgentStatusRow] { var statusKeysByPanel: [UUID: Set] = [:] for (key, panelId) in agentPIDPanelIdsByKey where panels[panelId] != nil { @@ -154,6 +157,11 @@ extension Workspace { guard Self.structuredAgentHookStatusKeys.contains(statusKey) else { continue } statusKeysByPanel[panelId, default: []].insert(statusKey) } + for (panelId, entries) in statusEntriesByPanelId where panels[panelId] != nil { + for statusKey in entries.keys where Self.structuredAgentHookStatusKeys.contains(statusKey) { + statusKeysByPanel[panelId, default: []].insert(statusKey) + } + } var chosenByPanel: [(panelId: UUID, statusKey: String, entry: SidebarStatusEntry?)] = [] for (panelId, statusKeys) in statusKeysByPanel { diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 034ed6d1d553..48499db47f20 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -128,23 +128,37 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { } @MainActor - func testPanelEntryWithoutAgentPIDDoesNotCreateRow() throws { + func testBareSharedPIDKeyHookSequenceKeepsBothPanesRows() throws { let workspace = Workspace() - let panelId = try XCTUnwrap(workspace.focusedPanelId) + let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) + let paneId = try XCTUnwrap(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try XCTUnwrap(workspace.newTerminalSurface(inPane: paneId, focus: false)).id - // A bare panel-scoped text report with no recorded agent PID has no - // deterministic owner to clear it, so it must not create a row. - workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: panelId) - XCTAssertTrue(workspace.sidebarAgentStatusRows().isEmpty) + // Mirrors the real Claude Code hook sequence, which shares ONE bare + // PID key per agent type across all panes of a workspace + // (`set_agent_pid claude_code --panel ...` then + // `set_status claude_code ... --pid --panel ...`). Bare-key ownership + // migrates to the last reporting pane, so the panel-scoped entry must + // keep the earlier pane's row alive. + workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: firstPanelId) + workspace.setAgentLifecycle(key: "claude_code", panelId: firstPanelId, lifecycle: .running) - // Recording the PID makes the same entry visible; clearing the PID - // without clearing status removes the row again (no stale rows). - workspace.recordAgentPID(key: "claude_code.owner", pid: 111, panelId: panelId, refreshPorts: false) - XCTAssertEqual(workspace.sidebarAgentStatusRows().map(\.panelId), [panelId]) - XCTAssertTrue( - workspace.clearAgentPID(key: "claude_code.owner", panelId: panelId, clearStatus: false, refreshPorts: false) + workspace.recordAgentPID(key: "claude_code", pid: 222, panelId: secondPanelId, refreshPorts: false) + workspace.recordPanelStatusEntry( + makeEntry(key: "claude_code", value: "Claude is waiting for your input"), + panelId: secondPanelId ) - XCTAssertTrue(workspace.sidebarAgentStatusRows().isEmpty) + workspace.setAgentLifecycle(key: "claude_code", panelId: secondPanelId, lifecycle: .needsInput) + + let rows = workspace.sidebarAgentStatusRows() + XCTAssertEqual(rows.count, 2) + let valuesByPanel = Dictionary(uniqueKeysWithValues: rows.map { ($0.panelId, $0.value) }) + XCTAssertEqual(valuesByPanel[firstPanelId], "Running") + XCTAssertEqual(valuesByPanel[secondPanelId], "Claude is waiting for your input") + let lifecyclesByPanel = Dictionary(uniqueKeysWithValues: rows.map { ($0.panelId, $0.lifecycle) }) + XCTAssertEqual(lifecyclesByPanel[firstPanelId], .running) + XCTAssertEqual(lifecyclesByPanel[secondPanelId], .needsInput) } @MainActor From c3d2f4756f013a078d0f1c320e1b6ed762026a6f Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 19:16:10 -0700 Subject: [PATCH 08/46] tests: conditional cmux_DEV import for PerAgentSidebarStatusRowTests The app-host unit test lane builds the app as "cmux DEV" (module cmux_DEV), so a bare `@testable import cmux` fails module scanning there ("Unable to find module dependency: 'cmux'", all four shards red). Use the same canImport(cmux_DEV) conditional import every other wired cmuxTests file uses. --- cmuxTests/PerAgentSidebarStatusRowTests.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 48499db47f20..2b9911c2fd23 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -1,7 +1,11 @@ import CmuxSidebar import XCTest +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) @testable import cmux +#endif /// Per-pane agent status rows (sidebar): several agents in one workspace must /// each keep their own row instead of collapsing into one last-write-wins From 7092c30f1109bb8472388e0c9dc700d0f33fc8d8 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 19:25:31 -0700 Subject: [PATCH 09/46] sidebar per-agent rows: policy cleanup (one type per file, Swift Testing) - Split SidebarStatusRowViews.swift into SidebarMetadataRowViews.swift and SidebarAgentStatusRowViews.swift so each new file owns one major view type (plus its private entry row). - Convert PerAgentSidebarStatusRowTests to Swift Testing (@Test/#expect/ #require, @MainActor struct suite), matching the repo policy for new non-UI tests. Suite remains discovered by the app-host shard planner (cmux_unit_test_shard.py --validate passes, suite listed with weight 20). --- Sources/SidebarAgentStatusRowViews.swift | 179 ++++++++++ Sources/SidebarMetadataRowViews.swift | 164 +++++++++ Sources/SidebarStatusRowViews.swift | 336 ------------------ cmux.xcodeproj/project.pbxproj | 12 +- cmuxTests/PerAgentSidebarStatusRowTests.swift | 148 ++++---- 5 files changed, 426 insertions(+), 413 deletions(-) create mode 100644 Sources/SidebarAgentStatusRowViews.swift create mode 100644 Sources/SidebarMetadataRowViews.swift delete mode 100644 Sources/SidebarStatusRowViews.swift diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift new file mode 100644 index 000000000000..73a93ca5f6fc --- /dev/null +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -0,0 +1,179 @@ +import AppKit +import CmuxFoundation +import CmuxSidebar +import SwiftUI + +/// Sidebar per-agent-pane status rows: one row per live agent pane plus its +/// private entry row. Rows receive immutable value snapshots and closure +/// action bundles only, per the sidebar list snapshot-boundary rule. +struct SidebarAgentStatusRows: View { + let rows: [SidebarAgentStatusRow] + let isActive: Bool + let activeForegroundColor: Color + let fontScale: CGFloat + let onFocusPanel: (UUID) -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + ForEach(rows) { row in + SidebarAgentStatusEntryRow( + row: row, + isActive: isActive, + activeForegroundColor: activeForegroundColor, + fontScale: fontScale, + onFocusPanel: onFocusPanel + ) + } + } + } +} + +private struct SidebarAgentStatusEntryRow: View { + let row: SidebarAgentStatusRow + let isActive: Bool + let activeForegroundColor: Color + let fontScale: CGFloat + let onFocusPanel: (UUID) -> Void + + var body: some View { + Group { + if let url = row.url { + Button { + onFocusPanel(row.panelId) + NSWorkspace.shared.open(url) + } label: { + rowContent(underlined: true) + } + .buttonStyle(.plain) + .safeHelp(url.absoluteString) + } else { + rowContent(underlined: false) + .contentShape(Rectangle()) + .onTapGesture { onFocusPanel(row.panelId) } + .safeHelp(helpText) + } + } + } + + @ViewBuilder + private func rowContent(underlined: Bool) -> some View { + HStack(spacing: 4) { + if let icon = iconView { + icon + .foregroundColor(foregroundColor.opacity(0.95)) + } + Text(displayText) + .underline(underlined) + .foregroundColor(foregroundColor) + .lineLimit(1) + .truncationMode(.tail) + if let paneLabel = row.paneLabel { + Text(paneLabel) + .foregroundColor(isActive ? activeForegroundColor.opacity(0.6) : .secondary.opacity(0.8)) + .lineLimit(1) + .truncationMode(.middle) + } + Spacer(minLength: 0) + } + .cmuxFont(size: 10 * fontScale) + .frame(maxWidth: .infinity, alignment: .leading) + } + + private var displayText: String { + if let value = row.value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty { + return value + } + let name = Self.agentDisplayName(statusKey: row.statusKey) + if let lifecycleText { + return "\(name): \(lifecycleText)" + } + return name + } + + private var helpText: String { + guard let paneLabel = row.paneLabel else { return displayText } + return "\(displayText) (\(paneLabel))" + } + + private var lifecycleText: String? { + switch row.lifecycle { + case .running: + return String(localized: "sidebar.agentStatus.running", defaultValue: "Running") + case .needsInput: + return String(localized: "sidebar.agentStatus.needsInput", defaultValue: "Needs input") + case .idle: + return String(localized: "sidebar.agentStatus.idle", defaultValue: "Idle") + case .unknown, nil: + return nil + } + } + + static func agentDisplayName(statusKey: String) -> String { + statusKey + .split(separator: "_") + .map { $0.prefix(1).uppercased() + $0.dropFirst() } + .joined(separator: " ") + } + + private var effectiveIcon: String? { + if let icon = row.icon?.trimmingCharacters(in: .whitespacesAndNewlines), !icon.isEmpty { + return icon + } + switch row.lifecycle { + case .running: + return "bolt.fill" + case .needsInput: + return "exclamationmark.bubble.fill" + case .idle: + return "checkmark.circle" + case .unknown, nil: + return nil + } + } + + private var effectiveColorHex: String? { + if let color = row.color { + return color + } + switch row.lifecycle { + case .running: + return "#4C8DFF" + case .needsInput: + return "#FF9F0A" + case .idle, .unknown, nil: + return nil + } + } + + private var foregroundColor: Color { + if isActive { + return activeForegroundColor + } + if let raw = effectiveColorHex, let explicit = Color(hex: raw) { + return explicit + } + return .secondary + } + + private var iconView: AnyView? { + guard let iconRaw = effectiveIcon else { return nil } + if iconRaw.hasPrefix("emoji:") { + let value = String(iconRaw.dropFirst("emoji:".count)) + guard !value.isEmpty else { return nil } + return AnyView(Text(value).cmuxFont(size: 9 * fontScale)) + } + if iconRaw.hasPrefix("text:") { + let value = String(iconRaw.dropFirst("text:".count)) + guard !value.isEmpty else { return nil } + return AnyView(Text(value).cmuxFont(size: 8 * fontScale, weight: .semibold)) + } + let symbolName: String + if iconRaw.hasPrefix("sf:") { + symbolName = String(iconRaw.dropFirst("sf:".count)) + } else { + symbolName = iconRaw + } + guard !symbolName.isEmpty else { return nil } + return AnyView(CmuxSystemSymbolImage(magnified: symbolName, pointSize: 8 * fontScale, weight: .medium)) + } +} diff --git a/Sources/SidebarMetadataRowViews.swift b/Sources/SidebarMetadataRowViews.swift new file mode 100644 index 000000000000..9cadf97c240a --- /dev/null +++ b/Sources/SidebarMetadataRowViews.swift @@ -0,0 +1,164 @@ +import AppKit +import CmuxFoundation +import CmuxSidebar +import SwiftUI + +/// Sidebar keyed metadata rows reported over the control socket +/// (`set_status`/`report_meta`): the expandable list plus its private entry +/// row. Rows receive immutable value snapshots and closure action bundles +/// only, per the sidebar list snapshot-boundary rule. +struct SidebarMetadataRows: View { + let entries: [SidebarStatusEntry] + let isActive: Bool + let activeForegroundColor: Color + let activeSecondaryForegroundColor: Color + let fontScale: CGFloat + let onFocus: () -> Void + + @State private var isExpanded: Bool = false + private let collapsedEntryLimit = 3 + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + ForEach(visibleEntries, id: \.key) { entry in + SidebarMetadataEntryRow( + entry: entry, + isActive: isActive, + activeForegroundColor: activeForegroundColor, + fontScale: fontScale, + onFocus: onFocus + ) + } + + if shouldShowToggle { + Button(isExpanded ? String(localized: "sidebar.metadata.showLess", defaultValue: "Show less") : String(localized: "sidebar.metadata.showMore", defaultValue: "Show more")) { + onFocus() + withAnimation(.easeInOut(duration: 0.15)) { + isExpanded.toggle() + } + } + .buttonStyle(.plain) + .cmuxFont(size: 10 * fontScale, weight: .semibold) + .foregroundColor(isActive ? activeSecondaryForegroundColor : .secondary.opacity(0.9)) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + .safeHelp(helpText) + } + + private var visibleEntries: [SidebarStatusEntry] { + guard !isExpanded, entries.count > collapsedEntryLimit else { return entries } + return Array(entries.prefix(collapsedEntryLimit)) + } + + private var helpText: String { + entries.map { entry in + let trimmed = entry.value.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? entry.key : trimmed + } + .joined(separator: "\n") + } + + private var shouldShowToggle: Bool { + entries.count > collapsedEntryLimit + } +} + +private struct SidebarMetadataEntryRow: View { + let entry: SidebarStatusEntry + let isActive: Bool + let activeForegroundColor: Color + let fontScale: CGFloat + let onFocus: () -> Void + + var body: some View { + Group { + if let url = entry.url { + Button { + onFocus() + NSWorkspace.shared.open(url) + } label: { + rowContent(underlined: true) + } + .buttonStyle(.plain) + .safeHelp(url.absoluteString) + } else { + rowContent(underlined: false) + .contentShape(Rectangle()) + .onTapGesture { onFocus() } + } + } + } + + @ViewBuilder + private func rowContent(underlined: Bool) -> some View { + HStack(spacing: 4) { + if let icon = iconView { + icon + .foregroundColor(foregroundColor.opacity(0.95)) + } + metadataText(underlined: underlined) + .lineLimit(1) + .truncationMode(.tail) + Spacer(minLength: 0) + } + .cmuxFont(size: 10 * fontScale) + .frame(maxWidth: .infinity, alignment: .leading) + } + + private var foregroundColor: Color { + if isActive, + let raw = entry.color, + Color(hex: raw) != nil { + return activeForegroundColor + } + if let raw = entry.color, let explicit = Color(hex: raw) { + return explicit + } + return isActive ? activeForegroundColor.opacity(0.84) : .secondary + } + + private var iconView: AnyView? { + guard let iconRaw = entry.icon?.trimmingCharacters(in: .whitespacesAndNewlines), + !iconRaw.isEmpty else { + return nil + } + if iconRaw.hasPrefix("emoji:") { + let value = String(iconRaw.dropFirst("emoji:".count)) + guard !value.isEmpty else { return nil } + return AnyView(Text(value).cmuxFont(size: 9 * fontScale)) + } + if iconRaw.hasPrefix("text:") { + let value = String(iconRaw.dropFirst("text:".count)) + guard !value.isEmpty else { return nil } + return AnyView(Text(value).cmuxFont(size: 8 * fontScale, weight: .semibold)) + } + let symbolName: String + if iconRaw.hasPrefix("sf:") { + symbolName = String(iconRaw.dropFirst("sf:".count)) + } else { + symbolName = iconRaw + } + guard !symbolName.isEmpty else { return nil } + return AnyView(CmuxSystemSymbolImage(magnified: symbolName, pointSize: 8 * fontScale, weight: .medium)) + } + + @ViewBuilder + private func metadataText(underlined: Bool) -> some View { + let trimmed = entry.value.trimmingCharacters(in: .whitespacesAndNewlines) + let display = trimmed.isEmpty ? entry.key : trimmed + if entry.format == .markdown, + let attributed = try? AttributedString( + markdown: display, + options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace) + ) { + Text(attributed) + .underline(underlined) + .foregroundColor(foregroundColor) + } else { + Text(display) + .underline(underlined) + .foregroundColor(foregroundColor) + } + } +} diff --git a/Sources/SidebarStatusRowViews.swift b/Sources/SidebarStatusRowViews.swift deleted file mode 100644 index 64726d7d519c..000000000000 --- a/Sources/SidebarStatusRowViews.swift +++ /dev/null @@ -1,336 +0,0 @@ -import AppKit -import CmuxFoundation -import CmuxSidebar -import SwiftUI - -/// Sidebar per-workspace status rows: keyed metadata rows reported over the -/// control socket (`SidebarMetadataRows`) and per-agent-pane status rows -/// (`SidebarAgentStatusRows`). Rows receive immutable value snapshots plus -/// closure action bundles only, per the sidebar list snapshot-boundary rule. -struct SidebarMetadataRows: View { - let entries: [SidebarStatusEntry] - let isActive: Bool - let activeForegroundColor: Color - let activeSecondaryForegroundColor: Color - let fontScale: CGFloat - let onFocus: () -> Void - - @State private var isExpanded: Bool = false - private let collapsedEntryLimit = 3 - - var body: some View { - VStack(alignment: .leading, spacing: 2) { - ForEach(visibleEntries, id: \.key) { entry in - SidebarMetadataEntryRow( - entry: entry, - isActive: isActive, - activeForegroundColor: activeForegroundColor, - fontScale: fontScale, - onFocus: onFocus - ) - } - - if shouldShowToggle { - Button(isExpanded ? String(localized: "sidebar.metadata.showLess", defaultValue: "Show less") : String(localized: "sidebar.metadata.showMore", defaultValue: "Show more")) { - onFocus() - withAnimation(.easeInOut(duration: 0.15)) { - isExpanded.toggle() - } - } - .buttonStyle(.plain) - .cmuxFont(size: 10 * fontScale, weight: .semibold) - .foregroundColor(isActive ? activeSecondaryForegroundColor : .secondary.opacity(0.9)) - .frame(maxWidth: .infinity, alignment: .leading) - } - } - .safeHelp(helpText) - } - - private var visibleEntries: [SidebarStatusEntry] { - guard !isExpanded, entries.count > collapsedEntryLimit else { return entries } - return Array(entries.prefix(collapsedEntryLimit)) - } - - private var helpText: String { - entries.map { entry in - let trimmed = entry.value.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed.isEmpty ? entry.key : trimmed - } - .joined(separator: "\n") - } - - private var shouldShowToggle: Bool { - entries.count > collapsedEntryLimit - } -} - -struct SidebarAgentStatusRows: View { - let rows: [SidebarAgentStatusRow] - let isActive: Bool - let activeForegroundColor: Color - let fontScale: CGFloat - let onFocusPanel: (UUID) -> Void - - var body: some View { - VStack(alignment: .leading, spacing: 2) { - ForEach(rows) { row in - SidebarAgentStatusEntryRow( - row: row, - isActive: isActive, - activeForegroundColor: activeForegroundColor, - fontScale: fontScale, - onFocusPanel: onFocusPanel - ) - } - } - } -} - -private struct SidebarAgentStatusEntryRow: View { - let row: SidebarAgentStatusRow - let isActive: Bool - let activeForegroundColor: Color - let fontScale: CGFloat - let onFocusPanel: (UUID) -> Void - - var body: some View { - Group { - if let url = row.url { - Button { - onFocusPanel(row.panelId) - NSWorkspace.shared.open(url) - } label: { - rowContent(underlined: true) - } - .buttonStyle(.plain) - .safeHelp(url.absoluteString) - } else { - rowContent(underlined: false) - .contentShape(Rectangle()) - .onTapGesture { onFocusPanel(row.panelId) } - .safeHelp(helpText) - } - } - } - - @ViewBuilder - private func rowContent(underlined: Bool) -> some View { - HStack(spacing: 4) { - if let icon = iconView { - icon - .foregroundColor(foregroundColor.opacity(0.95)) - } - Text(displayText) - .underline(underlined) - .foregroundColor(foregroundColor) - .lineLimit(1) - .truncationMode(.tail) - if let paneLabel = row.paneLabel { - Text(paneLabel) - .foregroundColor(isActive ? activeForegroundColor.opacity(0.6) : .secondary.opacity(0.8)) - .lineLimit(1) - .truncationMode(.middle) - } - Spacer(minLength: 0) - } - .cmuxFont(size: 10 * fontScale) - .frame(maxWidth: .infinity, alignment: .leading) - } - - private var displayText: String { - if let value = row.value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty { - return value - } - let name = Self.agentDisplayName(statusKey: row.statusKey) - if let lifecycleText { - return "\(name): \(lifecycleText)" - } - return name - } - - private var helpText: String { - guard let paneLabel = row.paneLabel else { return displayText } - return "\(displayText) (\(paneLabel))" - } - - private var lifecycleText: String? { - switch row.lifecycle { - case .running: - return String(localized: "sidebar.agentStatus.running", defaultValue: "Running") - case .needsInput: - return String(localized: "sidebar.agentStatus.needsInput", defaultValue: "Needs input") - case .idle: - return String(localized: "sidebar.agentStatus.idle", defaultValue: "Idle") - case .unknown, nil: - return nil - } - } - - static func agentDisplayName(statusKey: String) -> String { - statusKey - .split(separator: "_") - .map { $0.prefix(1).uppercased() + $0.dropFirst() } - .joined(separator: " ") - } - - private var effectiveIcon: String? { - if let icon = row.icon?.trimmingCharacters(in: .whitespacesAndNewlines), !icon.isEmpty { - return icon - } - switch row.lifecycle { - case .running: - return "bolt.fill" - case .needsInput: - return "exclamationmark.bubble.fill" - case .idle: - return "checkmark.circle" - case .unknown, nil: - return nil - } - } - - private var effectiveColorHex: String? { - if let color = row.color { - return color - } - switch row.lifecycle { - case .running: - return "#4C8DFF" - case .needsInput: - return "#FF9F0A" - case .idle, .unknown, nil: - return nil - } - } - - private var foregroundColor: Color { - if isActive { - return activeForegroundColor - } - if let raw = effectiveColorHex, let explicit = Color(hex: raw) { - return explicit - } - return .secondary - } - - private var iconView: AnyView? { - guard let iconRaw = effectiveIcon else { return nil } - if iconRaw.hasPrefix("emoji:") { - let value = String(iconRaw.dropFirst("emoji:".count)) - guard !value.isEmpty else { return nil } - return AnyView(Text(value).cmuxFont(size: 9 * fontScale)) - } - if iconRaw.hasPrefix("text:") { - let value = String(iconRaw.dropFirst("text:".count)) - guard !value.isEmpty else { return nil } - return AnyView(Text(value).cmuxFont(size: 8 * fontScale, weight: .semibold)) - } - let symbolName: String - if iconRaw.hasPrefix("sf:") { - symbolName = String(iconRaw.dropFirst("sf:".count)) - } else { - symbolName = iconRaw - } - guard !symbolName.isEmpty else { return nil } - return AnyView(CmuxSystemSymbolImage(magnified: symbolName, pointSize: 8 * fontScale, weight: .medium)) - } -} - -private struct SidebarMetadataEntryRow: View { - let entry: SidebarStatusEntry - let isActive: Bool - let activeForegroundColor: Color - let fontScale: CGFloat - let onFocus: () -> Void - - var body: some View { - Group { - if let url = entry.url { - Button { - onFocus() - NSWorkspace.shared.open(url) - } label: { - rowContent(underlined: true) - } - .buttonStyle(.plain) - .safeHelp(url.absoluteString) - } else { - rowContent(underlined: false) - .contentShape(Rectangle()) - .onTapGesture { onFocus() } - } - } - } - - @ViewBuilder - private func rowContent(underlined: Bool) -> some View { - HStack(spacing: 4) { - if let icon = iconView { - icon - .foregroundColor(foregroundColor.opacity(0.95)) - } - metadataText(underlined: underlined) - .lineLimit(1) - .truncationMode(.tail) - Spacer(minLength: 0) - } - .cmuxFont(size: 10 * fontScale) - .frame(maxWidth: .infinity, alignment: .leading) - } - - private var foregroundColor: Color { - if isActive, - let raw = entry.color, - Color(hex: raw) != nil { - return activeForegroundColor - } - if let raw = entry.color, let explicit = Color(hex: raw) { - return explicit - } - return isActive ? activeForegroundColor.opacity(0.84) : .secondary - } - - private var iconView: AnyView? { - guard let iconRaw = entry.icon?.trimmingCharacters(in: .whitespacesAndNewlines), - !iconRaw.isEmpty else { - return nil - } - if iconRaw.hasPrefix("emoji:") { - let value = String(iconRaw.dropFirst("emoji:".count)) - guard !value.isEmpty else { return nil } - return AnyView(Text(value).cmuxFont(size: 9 * fontScale)) - } - if iconRaw.hasPrefix("text:") { - let value = String(iconRaw.dropFirst("text:".count)) - guard !value.isEmpty else { return nil } - return AnyView(Text(value).cmuxFont(size: 8 * fontScale, weight: .semibold)) - } - let symbolName: String - if iconRaw.hasPrefix("sf:") { - symbolName = String(iconRaw.dropFirst("sf:".count)) - } else { - symbolName = iconRaw - } - guard !symbolName.isEmpty else { return nil } - return AnyView(CmuxSystemSymbolImage(magnified: symbolName, pointSize: 8 * fontScale, weight: .medium)) - } - - @ViewBuilder - private func metadataText(underlined: Bool) -> some View { - let trimmed = entry.value.trimmingCharacters(in: .whitespacesAndNewlines) - let display = trimmed.isEmpty ? entry.key : trimmed - if entry.format == .markdown, - let attributed = try? AttributedString( - markdown: display, - options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace) - ) { - Text(attributed) - .underline(underlined) - .foregroundColor(foregroundColor) - } else { - Text(display) - .underline(underlined) - .foregroundColor(foregroundColor) - } - } -} diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 4c0d9d43fb4a..e45707d28555 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1048,6 +1048,7 @@ 5C3E0454B6C24B02A2F091A8 /* ShortcutRoutingSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = B42A82C6AA614E74873D9A5F /* ShortcutRoutingSupport.swift */; }; F6001000A1B2C3D4E5F60718 /* ShortcutUnbindingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6001001A1B2C3D4E5F60718 /* ShortcutUnbindingTests.swift */; }; C3467AB10000000000000001 /* ShortcutWhenClauseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3467AB10000000000000002 /* ShortcutWhenClauseTests.swift */; }; + 7A11AA057A11AA057A11AA05 /* SidebarAgentStatusRowViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */; }; 211A75777F433ED8BA5AE208 /* SidebarAppearanceSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 243632BA1DBBA36FD46E0610 /* SidebarAppearanceSupport.swift */; }; D7AB34310000000000000003 /* SidebarBonsplitTabDropDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34310000000000000004 /* SidebarBonsplitTabDropDelegate.swift */; }; D7AB34300000000000000003 /* SidebarBonsplitTabWorkspaceDropOverlay.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34300000000000000004 /* SidebarBonsplitTabWorkspaceDropOverlay.swift */; }; @@ -1067,6 +1068,7 @@ D41A7C01D41A7C01D41A7C01 /* SidebarLazyLayoutScaleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D41A7C02D41A7C02D41A7C02 /* SidebarLazyLayoutScaleTests.swift */; }; 385C6BA7E78DB87460E5D930 /* SidebarMarkdownRendererTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1C3F1DBF6BF5D7223C4A30C /* SidebarMarkdownRendererTests.swift */; }; C0DE5F210000000000000001 /* SidebarMetadataMarkdownRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE5F210000000000000002 /* SidebarMetadataMarkdownRenderer.swift */; }; + 7A11AA037A11AA037A11AA03 /* SidebarMetadataRowViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A11AA047A11AA047A11AA04 /* SidebarMetadataRowViews.swift */; }; CB23911D7E131E8FBC9B82B6 /* SidebarOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC39DE4B96D1931C52AF7D68 /* SidebarOrderingTests.swift */; }; EA1F00000000000000000001 /* SidebarPathFormatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA1F00000000000000000002 /* SidebarPathFormatter.swift */; }; C0DEF0A30000000000000001 /* SidebarPortDisplayText.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DEF0A30000000000000002 /* SidebarPortDisplayText.swift */; }; @@ -1080,7 +1082,6 @@ C9A57513C9A57513C9A57513 /* SidebarScrollViewConfiguratorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9A57514C9A57514C9A57514 /* SidebarScrollViewConfiguratorTests.swift */; }; E62155868BB29FEB5DAAAF25 /* SidebarSelectionState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD52285508B1D6A9875E7B3 /* SidebarSelectionState.swift */; }; F57072635F25EBCA741E125D /* SidebarState.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1614EAD3CCF70A177A51BD1 /* SidebarState.swift */; }; - 7A11AA037A11AA037A11AA03 /* SidebarStatusRowViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A11AA047A11AA047A11AA04 /* SidebarStatusRowViews.swift */; }; D7344F010000000000000001 /* SidebarTabDragPayload.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7344F010000000000000002 /* SidebarTabDragPayload.swift */; }; D73440010000000000000001 /* SidebarTabDragPayloadProviderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D73440010000000000000002 /* SidebarTabDragPayloadProviderTests.swift */; }; D7AB34300000000000000105 /* SidebarTabDropIndicatorPredicateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34300000000000000106 /* SidebarTabDropIndicatorPredicateTests.swift */; }; @@ -2484,6 +2485,7 @@ B42A82C6AA614E74873D9A5F /* ShortcutRoutingSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = App/ShortcutRoutingSupport.swift; sourceTree = ""; }; F6001001A1B2C3D4E5F60718 /* ShortcutUnbindingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShortcutUnbindingTests.swift; sourceTree = ""; }; C3467AB10000000000000002 /* ShortcutWhenClauseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShortcutWhenClauseTests.swift; sourceTree = ""; }; + 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentStatusRowViews.swift; sourceTree = ""; }; 243632BA1DBBA36FD46E0610 /* SidebarAppearanceSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarAppearanceSupport.swift; sourceTree = ""; }; D7AB34310000000000000004 /* SidebarBonsplitTabDropDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarBonsplitTabDropDelegate.swift; sourceTree = ""; }; D7AB34300000000000000004 /* SidebarBonsplitTabWorkspaceDropOverlay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarBonsplitTabWorkspaceDropOverlay.swift; sourceTree = ""; }; @@ -2503,6 +2505,7 @@ D41A7C02D41A7C02D41A7C02 /* SidebarLazyLayoutScaleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarLazyLayoutScaleTests.swift; sourceTree = ""; }; F1C3F1DBF6BF5D7223C4A30C /* SidebarMarkdownRendererTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarMarkdownRendererTests.swift; sourceTree = ""; }; C0DE5F210000000000000002 /* SidebarMetadataMarkdownRenderer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarMetadataMarkdownRenderer.swift; sourceTree = ""; }; + 7A11AA047A11AA047A11AA04 /* SidebarMetadataRowViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarMetadataRowViews.swift; sourceTree = ""; }; BC39DE4B96D1931C52AF7D68 /* SidebarOrderingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarOrderingTests.swift; sourceTree = ""; }; EA1F00000000000000000002 /* SidebarPathFormatter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarPathFormatter.swift; sourceTree = ""; }; C0DEF0A30000000000000002 /* SidebarPortDisplayText.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarPortDisplayText.swift; sourceTree = ""; }; @@ -2516,7 +2519,6 @@ C9A57514C9A57514C9A57514 /* SidebarScrollViewConfiguratorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarScrollViewConfiguratorTests.swift; sourceTree = ""; }; 9AD52285508B1D6A9875E7B3 /* SidebarSelectionState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarSelectionState.swift; sourceTree = ""; }; D1614EAD3CCF70A177A51BD1 /* SidebarState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarState.swift; sourceTree = ""; }; - 7A11AA047A11AA047A11AA04 /* SidebarStatusRowViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarStatusRowViews.swift; sourceTree = ""; }; D7344F010000000000000002 /* SidebarTabDragPayload.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarTabDragPayload.swift; sourceTree = ""; }; D73440010000000000000002 /* SidebarTabDragPayloadProviderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarTabDragPayloadProviderTests.swift; sourceTree = ""; }; D7AB34300000000000000106 /* SidebarTabDropIndicatorPredicateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarTabDropIndicatorPredicateTests.swift; sourceTree = ""; }; @@ -3394,7 +3396,8 @@ C3744E040000000000000001 /* AgentPIDProcessIdentity.swift */, 6799A0026799A0026799A002 /* WorkspaceSidebarAgentRuntimeObservationModel.swift */, 7A11AA027A11AA027A11AA02 /* Workspace+SidebarAgentStatus.swift */, - 7A11AA047A11AA047A11AA04 /* SidebarStatusRowViews.swift */, + 7A11AA047A11AA047A11AA04 /* SidebarMetadataRowViews.swift */, + 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */, C0A1E5CE01C0A1E5CE01A002 /* CoalesceLatestPublisher.swift */, 5659A0025659A0025659A002 /* WorkspaceSidebarObservation.swift */, 5659B0025659B0025659B002 /* WorkspaceSidebarLogEntryLimitProvider.swift */, @@ -5441,6 +5444,7 @@ 125BAEF2FE3B454547B964D1 /* ShortcutHintPill.swift in Sources */, 6042C0046042C0046042C004 /* ShortcutHintTitlebarPolicy.swift in Sources */, 5C3E0454B6C24B02A2F091A8 /* ShortcutRoutingSupport.swift in Sources */, + 7A11AA057A11AA057A11AA05 /* SidebarAgentStatusRowViews.swift in Sources */, 211A75777F433ED8BA5AE208 /* SidebarAppearanceSupport.swift in Sources */, D7AB34310000000000000003 /* SidebarBonsplitTabDropDelegate.swift in Sources */, D7AB34300000000000000003 /* SidebarBonsplitTabWorkspaceDropOverlay.swift in Sources */, @@ -5455,6 +5459,7 @@ 5732A0115732A0115732A011 /* SidebarLazyContractProbe.swift in Sources */, 5732A0125732A0125732A012 /* SidebarLazyContractProbeKey.swift in Sources */, C0DE5F210000000000000001 /* SidebarMetadataMarkdownRenderer.swift in Sources */, + 7A11AA037A11AA037A11AA03 /* SidebarMetadataRowViews.swift in Sources */, EA1F00000000000000000001 /* SidebarPathFormatter.swift in Sources */, C0DEF0A30000000000000001 /* SidebarPortDisplayText.swift in Sources */, C0DEA7710000000000000005 /* SidebarProBadge.swift in Sources */, @@ -5463,7 +5468,6 @@ C0DE35010000000000000001 /* SidebarScrim.swift in Sources */, E62155868BB29FEB5DAAAF25 /* SidebarSelectionState.swift in Sources */, F57072635F25EBCA741E125D /* SidebarState.swift in Sources */, - 7A11AA037A11AA037A11AA03 /* SidebarStatusRowViews.swift in Sources */, D7344F010000000000000001 /* SidebarTabDragPayload.swift in Sources */, C9A57605C9A57605C9A57605 /* SidebarWorkspaceDropTargetWriters.swift in Sources */, C9A57103C9A57103C9A57103 /* SidebarWorkspaceGroupConfigOpener.swift in Sources */, diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 2b9911c2fd23..440b30e73c2a 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -1,5 +1,6 @@ import CmuxSidebar -import XCTest +import Foundation +import Testing #if canImport(cmux_DEV) @testable import cmux_DEV @@ -10,7 +11,8 @@ import XCTest /// Per-pane agent status rows (sidebar): several agents in one workspace must /// each keep their own row instead of collapsing into one last-write-wins /// status pill per agent type. -final class PerAgentSidebarStatusRowTests: XCTestCase { +@MainActor +struct PerAgentSidebarStatusRowTests { private func makeEntry( key: String, value: String, @@ -25,10 +27,10 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { ) } - @MainActor + @Test func testIdenticalPanelStatusReportDoesNotReplaceStoredEntry() throws { let workspace = Workspace() - let panelId = try XCTUnwrap(workspace.focusedPanelId) + let panelId = try #require(workspace.focusedPanelId) let first = makeEntry(key: "claude_code", value: "Running", timestamp: Date(timeIntervalSince1970: 100)) workspace.recordPanelStatusEntry(first, panelId: panelId) @@ -36,19 +38,19 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { workspace.recordPanelStatusEntry(repeated, panelId: panelId) // Same display content, newer timestamp: dropped so agent heartbeats // do not invalidate the sidebar snapshot. - XCTAssertEqual(workspace.statusEntriesByPanelId[panelId]?["claude_code"], first) + #expect(workspace.statusEntriesByPanelId[panelId]?["claude_code"] == first) let changed = makeEntry(key: "claude_code", value: "Idle", timestamp: Date(timeIntervalSince1970: 300)) workspace.recordPanelStatusEntry(changed, panelId: panelId) - XCTAssertEqual(workspace.statusEntriesByPanelId[panelId]?["claude_code"], changed) + #expect(workspace.statusEntriesByPanelId[panelId]?["claude_code"] == changed) } - @MainActor + @Test func testAmbiguousWorkspaceStatusIsNotAttributedDuringTransfer() throws { let workspace = Workspace() - let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) - let paneId = try XCTUnwrap(workspace.paneId(forPanelId: firstPanelId)) - let secondPanelId = try XCTUnwrap(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id workspace.recordAgentPID(key: "claude_code.first", pid: 111, panelId: firstPanelId, refreshPorts: false) workspace.recordAgentPID(key: "claude_code.second", pid: 222, panelId: secondPanelId, refreshPorts: false) @@ -56,16 +58,16 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { // could have written it, so it must not ride along with a transfer. workspace.statusEntries["claude_code"] = makeEntry(key: "claude_code", value: "Running") - let runtimeState = try XCTUnwrap(workspace.agentRuntimeState(forPanelId: secondPanelId)) - XCTAssertNil(runtimeState.statusEntries["claude_code"]) + let runtimeState = try #require(workspace.agentRuntimeState(forPanelId: secondPanelId)) + #expect(runtimeState.statusEntries["claude_code"] == nil) } - @MainActor + @Test func testTwoAgentsOfSameTypeKeepSeparateRows() throws { let workspace = Workspace() - let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) - let paneId = try XCTUnwrap(workspace.paneId(forPanelId: firstPanelId)) - let secondPanelId = try XCTUnwrap(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id workspace.recordAgentPID(key: "claude_code.first", pid: 111, panelId: firstPanelId, refreshPorts: false) workspace.recordAgentPID(key: "claude_code.second", pid: 222, panelId: secondPanelId, refreshPorts: false) @@ -81,33 +83,33 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { ) let rows = workspace.sidebarAgentStatusRows() - XCTAssertEqual(rows.count, 2) - XCTAssertEqual(Set(rows.map(\.panelId)), [firstPanelId, secondPanelId]) + #expect(rows.count == 2) + #expect(Set(rows.map(\.panelId)) == [firstPanelId, secondPanelId]) let valuesByPanel = Dictionary(uniqueKeysWithValues: rows.map { ($0.panelId, $0.value) }) - XCTAssertEqual(valuesByPanel[firstPanelId], "Running") - XCTAssertEqual(valuesByPanel[secondPanelId], "Claude is waiting for your input") + #expect(valuesByPanel[firstPanelId] == "Running") + #expect(valuesByPanel[secondPanelId] == "Claude is waiting for your input") } - @MainActor + @Test func testSoleOwnerFallsBackToWorkspaceEntry() throws { let workspace = Workspace() - let panelId = try XCTUnwrap(workspace.focusedPanelId) + let panelId = try #require(workspace.focusedPanelId) workspace.recordAgentPID(key: "claude_code.only", pid: 111, panelId: panelId, refreshPorts: false) workspace.statusEntries["claude_code"] = makeEntry(key: "claude_code", value: "Running") let rows = workspace.sidebarAgentStatusRows() - XCTAssertEqual(rows.count, 1) - XCTAssertEqual(rows.first?.panelId, panelId) - XCTAssertEqual(rows.first?.value, "Running") + #expect(rows.count == 1) + #expect(rows.first?.panelId == panelId) + #expect(rows.first?.value == "Running") } - @MainActor + @Test func testSharedKeyWithoutPanelEntriesUsesPerPanelLifecycleNotWorkspaceText() throws { let workspace = Workspace() - let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) - let paneId = try XCTUnwrap(workspace.paneId(forPanelId: firstPanelId)) - let secondPanelId = try XCTUnwrap(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id workspace.recordAgentPID(key: "claude_code.first", pid: 111, panelId: firstPanelId, refreshPorts: false) workspace.recordAgentPID(key: "claude_code.second", pid: 222, panelId: secondPanelId, refreshPorts: false) @@ -116,27 +118,27 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { workspace.statusEntries["claude_code"] = makeEntry(key: "claude_code", value: "Running") let rows = workspace.sidebarAgentStatusRows() - XCTAssertEqual(rows.count, 2) + #expect(rows.count == 2) let byPanel = Dictionary(uniqueKeysWithValues: rows.map { ($0.panelId, $0) }) // The ambiguous workspace-level text must not be attributed to either pane. - XCTAssertNil(byPanel[firstPanelId]?.value) - XCTAssertNil(byPanel[secondPanelId]?.value) + #expect(byPanel[firstPanelId]?.value == nil) + #expect(byPanel[secondPanelId]?.value == nil) // Nor its decorations: the last writer's icon/color must not bleed // onto the other pane's row. - XCTAssertNil(byPanel[firstPanelId]?.icon) - XCTAssertNil(byPanel[secondPanelId]?.icon) - XCTAssertNil(byPanel[firstPanelId]?.color) - XCTAssertNil(byPanel[secondPanelId]?.color) - XCTAssertEqual(byPanel[firstPanelId]?.lifecycle, .running) - XCTAssertEqual(byPanel[secondPanelId]?.lifecycle, .needsInput) + #expect(byPanel[firstPanelId]?.icon == nil) + #expect(byPanel[secondPanelId]?.icon == nil) + #expect(byPanel[firstPanelId]?.color == nil) + #expect(byPanel[secondPanelId]?.color == nil) + #expect(byPanel[firstPanelId]?.lifecycle == .running) + #expect(byPanel[secondPanelId]?.lifecycle == .needsInput) } - @MainActor + @Test func testBareSharedPIDKeyHookSequenceKeepsBothPanesRows() throws { let workspace = Workspace() - let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) - let paneId = try XCTUnwrap(workspace.paneId(forPanelId: firstPanelId)) - let secondPanelId = try XCTUnwrap(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id // Mirrors the real Claude Code hook sequence, which shares ONE bare // PID key per agent type across all panes of a workspace @@ -156,19 +158,19 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { workspace.setAgentLifecycle(key: "claude_code", panelId: secondPanelId, lifecycle: .needsInput) let rows = workspace.sidebarAgentStatusRows() - XCTAssertEqual(rows.count, 2) + #expect(rows.count == 2) let valuesByPanel = Dictionary(uniqueKeysWithValues: rows.map { ($0.panelId, $0.value) }) - XCTAssertEqual(valuesByPanel[firstPanelId], "Running") - XCTAssertEqual(valuesByPanel[secondPanelId], "Claude is waiting for your input") - let lifecyclesByPanel = Dictionary(uniqueKeysWithValues: rows.map { ($0.panelId, $0.lifecycle) }) - XCTAssertEqual(lifecyclesByPanel[firstPanelId], .running) - XCTAssertEqual(lifecyclesByPanel[secondPanelId], .needsInput) + #expect(valuesByPanel[firstPanelId] == "Running") + #expect(valuesByPanel[secondPanelId] == "Claude is waiting for your input") + let rowsByPanel = Dictionary(uniqueKeysWithValues: rows.map { ($0.panelId, $0) }) + #expect(rowsByPanel[firstPanelId]?.lifecycle == .running) + #expect(rowsByPanel[secondPanelId]?.lifecycle == .needsInput) } - @MainActor + @Test func testAgentReplacementOnSamePanelKeepsFreshPanelEntry() throws { let workspace = Workspace() - let panelId = try XCTUnwrap(workspace.focusedPanelId) + let panelId = try #require(workspace.focusedPanelId) workspace.recordAgentPID(key: "claude_code.old", pid: 111, panelId: panelId, refreshPorts: false) workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Old session"), panelId: panelId) @@ -179,57 +181,57 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { // order the control-socket path uses; writing the panel copy first // would let the eviction delete the fresh entry. workspace.recordAgentPID(key: "claude_code.new", pid: 222, panelId: panelId, refreshPorts: false) - XCTAssertNil(workspace.statusEntriesByPanelId[panelId]?["claude_code"]) + #expect(workspace.statusEntriesByPanelId[panelId]?["claude_code"] == nil) workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "New session"), panelId: panelId) - XCTAssertEqual(workspace.statusEntriesByPanelId[panelId]?["claude_code"]?.value, "New session") - XCTAssertEqual(workspace.sidebarAgentStatusRows().first?.value, "New session") + #expect(workspace.statusEntriesByPanelId[panelId]?["claude_code"]?.value == "New session") + #expect(workspace.sidebarAgentStatusRows().first?.value == "New session") } - @MainActor + @Test func testClearingAgentPIDRemovesThatPanelsRow() throws { let workspace = Workspace() - let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) - let paneId = try XCTUnwrap(workspace.paneId(forPanelId: firstPanelId)) - let secondPanelId = try XCTUnwrap(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id workspace.recordAgentPID(key: "claude_code.first", pid: 111, panelId: firstPanelId, refreshPorts: false) workspace.recordAgentPID(key: "claude_code.second", pid: 222, panelId: secondPanelId, refreshPorts: false) workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: firstPanelId) workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Idle"), panelId: secondPanelId) - XCTAssertTrue( + #expect( workspace.clearAgentPID(key: "claude_code.first", panelId: firstPanelId, clearStatus: true, refreshPorts: false) ) let rows = workspace.sidebarAgentStatusRows() - XCTAssertEqual(rows.map(\.panelId), [secondPanelId]) - XCTAssertNil(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"]) - XCTAssertEqual(workspace.statusEntriesByPanelId[secondPanelId]?["claude_code"]?.value, "Idle") + #expect(rows.map(\.panelId) == [secondPanelId]) + #expect(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"] == nil) + #expect(workspace.statusEntriesByPanelId[secondPanelId]?["claude_code"]?.value == "Idle") } - @MainActor + @Test func testDetachedRuntimeTransferCarriesPanelScopedEntry() throws { let source = Workspace() - let panelId = try XCTUnwrap(source.focusedPanelId) + let panelId = try #require(source.focusedPanelId) source.recordAgentPID(key: "claude_code.moved", pid: 111, panelId: panelId, refreshPorts: false) source.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: panelId) - let runtimeState = try XCTUnwrap(source.agentRuntimeState(forPanelId: panelId)) - XCTAssertEqual(runtimeState.statusEntries["claude_code"]?.value, "Running") + let runtimeState = try #require(source.agentRuntimeState(forPanelId: panelId)) + #expect(runtimeState.statusEntries["claude_code"]?.value == "Running") let destination = Workspace() destination.adoptDetachedAgentRuntimeState(runtimeState) - XCTAssertEqual(destination.statusEntriesByPanelId[panelId]?["claude_code"]?.value, "Running") - XCTAssertEqual(destination.statusEntries["claude_code"]?.value, "Running") + #expect(destination.statusEntriesByPanelId[panelId]?["claude_code"]?.value == "Running") + #expect(destination.statusEntries["claude_code"]?.value == "Running") } - @MainActor + @Test func testClosingPanelDropsPanelScopedEntries() throws { let workspace = Workspace() - let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) - let paneId = try XCTUnwrap(workspace.paneId(forPanelId: firstPanelId)) - let secondPanelId = try XCTUnwrap(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: secondPanelId) _ = workspace.discardClosedPanelLifecycleState( @@ -243,7 +245,7 @@ final class PerAgentSidebarStatusRowTests: XCTestCase { requestTransferredRemoteCleanup: false ) - XCTAssertNil(workspace.statusEntriesByPanelId[secondPanelId]) - XCTAssertTrue(workspace.sidebarAgentStatusRows().isEmpty) + #expect(workspace.statusEntriesByPanelId[secondPanelId] == nil) + #expect(workspace.sidebarAgentStatusRows().isEmpty) } } From 68a8212812ae13988c5758ec3269e0dcf2e3e66e Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 19:33:58 -0700 Subject: [PATCH 10/46] sidebar per-agent rows: preserve markdown format for reported status values Structured statuses moved out of the generic metadata renderer lost their format: a set_status value with --format=markdown rendered as raw markdown syntax in the per-agent row. SidebarAgentStatusRow now carries the reported entry's format and the row view renders markdown values through the same AttributedString(markdown:) inline path SidebarMetadataEntryRow uses; lifecycle/name fallback text stays plain. Test: testRowCarriesReportedValueFormat. --- Sources/SidebarAgentStatusRowViews.swift | 35 ++++++++++++++++--- Sources/Workspace+SidebarAgentStatus.swift | 3 ++ cmuxTests/PerAgentSidebarStatusRowTests.swift | 18 ++++++++++ 3 files changed, 52 insertions(+), 4 deletions(-) diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index 73a93ca5f6fc..1924eaac8214 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -62,9 +62,7 @@ private struct SidebarAgentStatusEntryRow: View { icon .foregroundColor(foregroundColor.opacity(0.95)) } - Text(displayText) - .underline(underlined) - .foregroundColor(foregroundColor) + statusText(underlined: underlined) .lineLimit(1) .truncationMode(.tail) if let paneLabel = row.paneLabel { @@ -79,8 +77,37 @@ private struct SidebarAgentStatusEntryRow: View { .frame(maxWidth: .infinity, alignment: .leading) } + /// Mirrors `SidebarMetadataEntryRow.metadataText`: a markdown-formatted + /// reported value keeps its inline markdown rendering after moving from + /// the generic metadata renderer into the per-agent row. Lifecycle/name + /// fallback text is always plain. + @ViewBuilder + private func statusText(underlined: Bool) -> some View { + if row.format == .markdown, + reportedValueText != nil, + let attributed = try? AttributedString( + markdown: displayText, + options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace) + ) { + Text(attributed) + .underline(underlined) + .foregroundColor(foregroundColor) + } else { + Text(displayText) + .underline(underlined) + .foregroundColor(foregroundColor) + } + } + + private var reportedValueText: String? { + guard let value = row.value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else { + return nil + } + return value + } + private var displayText: String { - if let value = row.value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty { + if let value = reportedValueText { return value } let name = Self.agentDisplayName(statusKey: row.statusKey) diff --git a/Sources/Workspace+SidebarAgentStatus.swift b/Sources/Workspace+SidebarAgentStatus.swift index f358d99b01d9..7a7c2a18675d 100644 --- a/Sources/Workspace+SidebarAgentStatus.swift +++ b/Sources/Workspace+SidebarAgentStatus.swift @@ -10,6 +10,8 @@ struct SidebarAgentStatusRow: Equatable, Identifiable { let icon: String? let color: String? let url: URL? + /// How `value` renders (markdown vs plain); tied to `value`'s source entry. + let format: SidebarMetadataFormat let lifecycle: AgentHibernationLifecycleState? let paneLabel: String? let priority: Int @@ -200,6 +202,7 @@ extension Workspace { icon: entry?.icon ?? (soleOwner ? workspaceEntry?.icon : nil), color: entry?.color ?? (soleOwner ? workspaceEntry?.color : nil), url: entry?.url, + format: entry?.format ?? .plain, lifecycle: agentLifecycleStatesByPanelId[item.panelId]?[item.statusKey], paneLabel: includePaneLabels ? agentStatusRowPaneLabel(panelId: item.panelId) : nil, priority: entry?.priority ?? workspaceEntry?.priority ?? 0, diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 440b30e73c2a..e7a5a308b5f0 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -133,6 +133,24 @@ struct PerAgentSidebarStatusRowTests { #expect(byPanel[secondPanelId]?.lifecycle == .needsInput) } + @Test + func testRowCarriesReportedValueFormat() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + + workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: panelId, refreshPorts: false) + workspace.recordPanelStatusEntry( + SidebarStatusEntry(key: "claude_code", value: "**bold** status", format: .markdown), + panelId: panelId + ) + + // The row must carry the reported value's format so markdown statuses + // keep their inline rendering after moving out of the metadata rows. + let row = try #require(workspace.sidebarAgentStatusRows().first) + #expect(row.value == "**bold** status") + #expect(row.format == .markdown) + } + @Test func testBareSharedPIDKeyHookSequenceKeepsBothPanesRows() throws { let workspace = Workspace() From e02e286653528f11ecd7d95cccd180426943d9f3 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 19:43:54 -0700 Subject: [PATCH 11/46] sidebar: accordion for per-agent rows inside the workspace area With more than one agent pane, the agent-rows block gets a disclosure header showing an aggregate summary (agent count, needs-input count, worst-state accent dot when collapsed). Clicking the header folds or unfolds the per-agent rows. Single-agent workspaces render the row directly with no accordion chrome. --- Resources/Localizable.xcstrings | 68 ++++++++++ Sources/ContentView.swift | 1 + Sources/SidebarAgentStatusRowViews.swift | 118 ++++++++++++++++-- cmuxTests/PerAgentSidebarStatusRowTests.swift | 33 +++++ 4 files changed, 211 insertions(+), 9 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index c216ea8e52ee..1cc5fbbabc55 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -193764,6 +193764,74 @@ } } }, + "sidebar.agentStatus.summary.agentCount": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%lld agents" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "エージェント %lld件" + } + } + } + }, + "sidebar.agentStatus.summary.needsInputCount": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%lld need input" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%lld件が入力待ち" + } + } + } + }, + "sidebar.agentStatus.summary.oneAgent": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "1 agent" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "エージェント 1件" + } + } + } + }, + "sidebar.agentStatus.summary.oneNeedsInput": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "1 needs input" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "1件が入力待ち" + } + } + } + }, "sidebar.browserStack.closeGroup": { "extractionState": "manual", "localizations": { diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 3cd5650b80ea..74d9d70df672 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -13809,6 +13809,7 @@ struct TabItemView: View, Equatable { isActive: usesInvertedActiveForeground, activeForegroundColor: activeSecondaryColor(0.95), fontScale: fontScale, + onFocus: { updateSelection() }, onFocusPanel: { panelId in updateSelection() tab.focusPanel(panelId) diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index 1924eaac8214..0a3bf81bcbe9 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -3,28 +3,128 @@ import CmuxFoundation import CmuxSidebar import SwiftUI +/// Aggregate over the agent rows of one workspace, shown in the accordion +/// header (and standing in for the rows while collapsed). +struct SidebarAgentStatusRowsSummary: Equatable { + let agentCount: Int + let needsInputCount: Int + let runningCount: Int + + init(rows: [SidebarAgentStatusRow]) { + agentCount = rows.count + needsInputCount = rows.filter { $0.lifecycle == .needsInput }.count + runningCount = rows.filter { $0.lifecycle == .running }.count + } + + var text: String { + var parts: [String] = [] + if agentCount == 1 { + parts.append(String(localized: "sidebar.agentStatus.summary.oneAgent", defaultValue: "1 agent")) + } else { + parts.append(String( + format: String(localized: "sidebar.agentStatus.summary.agentCount", defaultValue: "%lld agents"), + agentCount + )) + } + if needsInputCount == 1 { + parts.append(String(localized: "sidebar.agentStatus.summary.oneNeedsInput", defaultValue: "1 needs input")) + } else if needsInputCount > 1 { + parts.append(String( + format: String(localized: "sidebar.agentStatus.summary.needsInputCount", defaultValue: "%lld need input"), + needsInputCount + )) + } + return parts.joined(separator: " · ") + } + + /// Worst-state accent: needs-input beats running beats idle. + var accentColorHex: String? { + if needsInputCount > 0 { return "#FF9F0A" } + if runningCount > 0 { return "#4C8DFF" } + return nil + } +} + /// Sidebar per-agent-pane status rows: one row per live agent pane plus its -/// private entry row. Rows receive immutable value snapshots and closure -/// action bundles only, per the sidebar list snapshot-boundary rule. +/// private entry row. With more than one agent the block becomes an accordion: +/// a summary header ("2 agents · 1 needs input") that folds the rows. Rows +/// receive immutable value snapshots and closure action bundles only, per the +/// sidebar list snapshot-boundary rule. struct SidebarAgentStatusRows: View { let rows: [SidebarAgentStatusRow] let isActive: Bool let activeForegroundColor: Color let fontScale: CGFloat + let onFocus: () -> Void let onFocusPanel: (UUID) -> Void + @State private var isCollapsed = false + var body: some View { VStack(alignment: .leading, spacing: 2) { - ForEach(rows) { row in - SidebarAgentStatusEntryRow( - row: row, - isActive: isActive, - activeForegroundColor: activeForegroundColor, - fontScale: fontScale, - onFocusPanel: onFocusPanel + if rows.count > 1 { + accordionHeader + if !isCollapsed { + rowList + } + } else { + rowList + } + } + } + + private var rowList: some View { + ForEach(rows) { row in + SidebarAgentStatusEntryRow( + row: row, + isActive: isActive, + activeForegroundColor: activeForegroundColor, + fontScale: fontScale, + onFocusPanel: onFocusPanel + ) + } + } + + private var accordionHeader: some View { + let summary = SidebarAgentStatusRowsSummary(rows: rows) + return Button { + onFocus() + withAnimation(.easeInOut(duration: 0.15)) { + isCollapsed.toggle() + } + } label: { + HStack(spacing: 4) { + CmuxSystemSymbolImage( + magnified: isCollapsed ? "chevron.right" : "chevron.down", + pointSize: 7 * fontScale, + weight: .semibold ) + .foregroundColor(headerSecondaryColor) + if isCollapsed, let accent = summary.accentColorHex, let color = Color(hex: accent), !isActive { + Circle() + .fill(color) + .frame(width: 5 * fontScale, height: 5 * fontScale) + } + Text(summary.text) + .foregroundColor(headerForegroundColor) + .lineLimit(1) + .truncationMode(.tail) + Spacer(minLength: 0) } + .cmuxFont(size: 10 * fontScale, weight: .semibold) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) } + .buttonStyle(.plain) + .safeHelp(summary.text) + } + + private var headerForegroundColor: Color { + isActive ? activeForegroundColor : .secondary + } + + private var headerSecondaryColor: Color { + isActive ? activeForegroundColor.opacity(0.65) : .secondary.opacity(0.8) } } diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index e7a5a308b5f0..df8bface7ca2 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -266,4 +266,37 @@ struct PerAgentSidebarStatusRowTests { #expect(workspace.statusEntriesByPanelId[secondPanelId] == nil) #expect(workspace.sidebarAgentStatusRows().isEmpty) } + + @Test + func testAccordionSummaryCounts() { + func row(lifecycle: AgentHibernationLifecycleState?) -> SidebarAgentStatusRow { + SidebarAgentStatusRow( + panelId: UUID(), + statusKey: "claude_code", + value: nil, + icon: nil, + color: nil, + url: nil, + format: .plain, + lifecycle: lifecycle, + paneLabel: nil, + priority: 0, + timestamp: Date(timeIntervalSince1970: 0) + ) + } + + let summary = SidebarAgentStatusRowsSummary(rows: [ + row(lifecycle: .running), + row(lifecycle: .needsInput), + row(lifecycle: .idle), + ]) + #expect(summary.agentCount == 3) + #expect(summary.needsInputCount == 1) + #expect(summary.runningCount == 1) + #expect(summary.accentColorHex == "#FF9F0A") + + let runningOnly = SidebarAgentStatusRowsSummary(rows: [row(lifecycle: .running)]) + #expect(runningOnly.accentColorHex == "#4C8DFF") + #expect(SidebarAgentStatusRowsSummary(rows: [row(lifecycle: .idle)]).accentColorHex == nil) + } } From b76ad3d609c19e74db49688946b2bb94eddc6c44 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 20:33:34 -0700 Subject: [PATCH 12/46] sidebar per-agent rows: review round fixes - Pane close now clears the workspace-level status slot when the closed pane was the key's last plausible owner (a panel-scoped status recorded without a PID previously left stale workspace text that a future same-type agent pane would adopt via the sole-owner fallback). - Ambiguous shared-key rows no longer inherit the workspace entry's priority/timestamp for sorting; only a sole owner trusts the workspace-level slot, matching the row-content rule. - Document the clear_status workspace-wide contract at the clear path (agent hooks clean up via panel-scoped clear_agent_pid, so a bare clear_status cannot be an agent-exit path). - Tests: panel-close workspace-slot cleanup (sole owner vs shared), ambiguous-row sort freshness, and agentStatusRows retention through the context-menu immediate-fields refresh. --- ...inalController+ControlSidebarContext.swift | 6 ++ Sources/Workspace+PanelLifecycle.swift | 11 +++ Sources/Workspace+SidebarAgentStatus.swift | 7 +- cmuxTests/PerAgentSidebarStatusRowTests.swift | 91 +++++++++++++++++++ ...rWorkspaceSnapshotRefreshPolicyTests.swift | 25 ++++- 5 files changed, 137 insertions(+), 3 deletions(-) diff --git a/Sources/TerminalController+ControlSidebarContext.swift b/Sources/TerminalController+ControlSidebarContext.swift index 9e78a7d16c24..3cf601e29d5c 100644 --- a/Sources/TerminalController+ControlSidebarContext.swift +++ b/Sources/TerminalController+ControlSidebarContext.swift @@ -74,6 +74,12 @@ extension TerminalController: ControlSidebarContext { } } + /// `clear_status ` is the workspace-scoped user command: it removes + /// the key from the whole workspace, including every pane's panel-scoped + /// copy, by contract. Agent lifecycle hooks never send it; they clean up + /// via `clear_agent_pid --panel= --clear-status`, which + /// routes through the panel-scoped `clearAgentPID` and cannot touch + /// sibling panes' rows. nonisolated func controlSidebarScheduleStatusClear(target: ControlSidebarTabTarget, key: String) { controlSidebarScheduleMutation(target: target) { _, tab in _ = tab.statusEntries.removeValue(forKey: key) diff --git a/Sources/Workspace+PanelLifecycle.swift b/Sources/Workspace+PanelLifecycle.swift index f32d4a625083..b16efc7d5b3a 100644 --- a/Sources/Workspace+PanelLifecycle.swift +++ b/Sources/Workspace+PanelLifecycle.swift @@ -407,6 +407,7 @@ extension Workspace { manualUnreadMarkedAt.removeValue(forKey: panelId) panelShellActivityStates.removeValue(forKey: panelId) clearAgentLifecycleStates(panelId: panelId) + let closedPanelStatusKeys = Set((statusEntriesByPanelId[panelId] ?? [:]).keys) statusEntriesByPanelId.removeValue(forKey: panelId) surfaceTTYNames.removeValue(forKey: panelId) discardRemotePTYSessionID(panelId: panelId) @@ -418,6 +419,16 @@ extension Workspace { debugSessionSnapshotSyntheticScrollbackByPanelId.removeValue(forKey: panelId) #endif discardAgentRuntimeState(closedAgentRuntimeState) + // A pane can hold a panel-scoped structured status with no recorded + // PID (`set_status --panel` without `--pid`); discardAgentRuntimeState + // only sweeps PID-owned keys. Clear the workspace-level slot for keys + // whose last plausible owner was this pane, or a future same-type + // agent pane would adopt the dead pane's text via the sole-owner + // fallback in sidebarAgentStatusRows(). + for statusKey in closedPanelStatusKeys + where panelsOwningAgentStatusKey(statusKey).isEmpty && !hasAgentRuntime(forStatusKey: statusKey) { + statusEntries.removeValue(forKey: statusKey) + } restoredAgentSnapshotsByPanelId.removeValue(forKey: panelId) restoredAgentResumeStatesByPanelId.removeValue(forKey: panelId) restoredResumeSessionWorkingDirectoriesByPanelId.removeValue(forKey: panelId) diff --git a/Sources/Workspace+SidebarAgentStatus.swift b/Sources/Workspace+SidebarAgentStatus.swift index 7a7c2a18675d..5b9c4f2a28d7 100644 --- a/Sources/Workspace+SidebarAgentStatus.swift +++ b/Sources/Workspace+SidebarAgentStatus.swift @@ -205,8 +205,11 @@ extension Workspace { format: entry?.format ?? .plain, lifecycle: agentLifecycleStatesByPanelId[item.panelId]?[item.statusKey], paneLabel: includePaneLabels ? agentStatusRowPaneLabel(panelId: item.panelId) : nil, - priority: entry?.priority ?? workspaceEntry?.priority ?? 0, - timestamp: entry?.timestamp ?? workspaceEntry?.timestamp ?? .distantPast + // No workspace fallback here: when the pane is not the sole + // owner, the last-write-wins workspace entry's freshness must + // not influence this row's sort position either. + priority: entry?.priority ?? 0, + timestamp: entry?.timestamp ?? .distantPast ) } return rows.sorted { lhs, rhs in diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index df8bface7ca2..03c2bdf0d286 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -267,6 +267,97 @@ struct PerAgentSidebarStatusRowTests { #expect(workspace.sidebarAgentStatusRows().isEmpty) } + @Test + func testClosingPanelWithoutPIDClearsSoleOwnerWorkspaceStatus() throws { + let workspace = Workspace() + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + // `set_status --panel` without `--pid`: the workspace slot and the + // panel copy are both written, but there is no PID ownership for the + // runtime cleanup to sweep. + let entry = makeEntry(key: "claude_code", value: "Running") + workspace.recordPanelStatusEntry(entry, panelId: secondPanelId) + workspace.statusEntries["claude_code"] = entry + + _ = workspace.discardClosedPanelLifecycleState( + panelId: secondPanelId, + paneId: nil, + panel: workspace.panels[secondPanelId], + origin: "test", + closePanel: false, + publishSurfaceClosedEvent: false, + clearSurfaceNotifications: false, + requestTransferredRemoteCleanup: false + ) + + // The closed pane was the key's only plausible owner, so the stale + // workspace-level slot must not survive to be adopted by a future + // same-type agent pane through the sole-owner fallback. + #expect(workspace.statusEntries["claude_code"] == nil) + } + + @Test + func testClosingPanelKeepsWorkspaceStatusWhenAnotherPaneOwnsKey() throws { + let workspace = Workspace() + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + let entry = makeEntry(key: "claude_code", value: "Running") + workspace.recordPanelStatusEntry(entry, panelId: firstPanelId) + workspace.recordPanelStatusEntry(entry, panelId: secondPanelId) + workspace.statusEntries["claude_code"] = entry + + _ = workspace.discardClosedPanelLifecycleState( + panelId: secondPanelId, + paneId: nil, + panel: workspace.panels[secondPanelId], + origin: "test", + closePanel: false, + publishSurfaceClosedEvent: false, + clearSurfaceNotifications: false, + requestTransferredRemoteCleanup: false + ) + + // The first pane still owns the key, so the workspace-level slot + // stays for its sole-owner fallback. + #expect(workspace.statusEntries["claude_code"]?.value == "Running") + #expect(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"]?.value == "Running") + } + + @Test + func testAmbiguousSharedKeyRowDoesNotInheritWorkspaceSortFreshness() throws { + let workspace = Workspace() + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + workspace.recordAgentPID(key: "claude_code.first", pid: 111, panelId: firstPanelId, refreshPorts: false) + workspace.recordAgentPID(key: "claude_code.second", pid: 222, panelId: secondPanelId, refreshPorts: false) + // Only the second pane has a panel-scoped entry; the workspace slot + // is newer and high-priority but ambiguous between the two panes. + workspace.recordPanelStatusEntry( + makeEntry(key: "claude_code", value: "Idle", timestamp: Date(timeIntervalSince1970: 100)), + panelId: secondPanelId + ) + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Running", + priority: 500, + timestamp: Date(timeIntervalSince1970: 9_999) + ) + + let rows = workspace.sidebarAgentStatusRows() + let rowsByPanel = Dictionary(uniqueKeysWithValues: rows.map { ($0.panelId, $0) }) + // The pane without its own entry must not borrow the ambiguous + // workspace entry's freshness for sorting. + #expect(rowsByPanel[firstPanelId]?.priority == 0) + #expect(rowsByPanel[firstPanelId]?.timestamp == .distantPast) + #expect(rows.first?.panelId == secondPanelId) + } + @Test func testAccordionSummaryCounts() { func row(lifecycle: AgentHibernationLifecycleState?) -> SidebarAgentStatusRow { diff --git a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift index 142a808bd27b..24a968acc9a7 100644 --- a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift +++ b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift @@ -12,12 +12,14 @@ import Testing @Suite struct SidebarWorkspaceSnapshotRefreshPolicyTests { @Test func contextMenuPinChangeUpdatesDisplayedFieldsAndDefersNoisyFields() { + let currentAgentRows = [Self.agentStatusRow(value: "Running")] let current = Self.snapshot( title: "lmao", isPinned: false, customColorHex: nil, remoteConnectionStatusText: "Connected", latestConversationMessage: "old message", + agentStatusRows: currentAgentRows, listeningPorts: [3000], finderDirectoryPath: "/old" ) @@ -27,6 +29,7 @@ import Testing customColorHex: nil, remoteConnectionStatusText: "Disconnected", latestConversationMessage: "new message", + agentStatusRows: [], listeningPorts: [3000, 4000], finderDirectoryPath: nil ) @@ -45,6 +48,9 @@ import Testing #expect(decision.workspaceSnapshotStorage?.remoteConnectionStatusText == "Connected") #expect(decision.workspaceSnapshotStorage?.latestConversationMessage == "old message") #expect(decision.workspaceSnapshotStorage?.listeningPorts == [3000]) + // Agent rows are noisy telemetry: they must survive the immediate + // context-menu refresh unchanged, like metadataEntries/listeningPorts. + #expect(decision.workspaceSnapshotStorage?.agentStatusRows == currentAgentRows) #expect(decision.workspaceSnapshotStorage?.finderDirectoryPath == nil) #expect(decision.pendingWorkspaceSnapshot == next) #expect(decision.hasDeferredWorkspaceObservationInvalidation) @@ -131,6 +137,7 @@ import Testing customColorHex: String? = nil, remoteConnectionStatusText: String = "Disconnected", latestConversationMessage: String? = nil, + agentStatusRows: [SidebarAgentStatusRow] = [], listeningPorts: [Int] = [], finderDirectoryPath: String? = nil, mediaActivity: BrowserMediaActivity = BrowserMediaActivity() @@ -148,7 +155,7 @@ import Testing copyableSidebarSSHError: nil, latestConversationMessage: latestConversationMessage, metadataEntries: [], - agentStatusRows: [], + agentStatusRows: agentStatusRows, metadataBlocks: [], latestLog: nil, progress: nil, @@ -164,6 +171,22 @@ import Testing ) } + private static func agentStatusRow(value: String) -> SidebarAgentStatusRow { + SidebarAgentStatusRow( + panelId: UUID(), + statusKey: "claude_code", + value: value, + icon: nil, + color: nil, + url: nil, + format: .plain, + lifecycle: nil, + paneLabel: nil, + priority: 0, + timestamp: Date(timeIntervalSince1970: 0) + ) + } + private static func presentationKey( showsWorkspaceDescription: Bool = true, usesVerticalBranchLayout: Bool = true, From 1042a53f61c6ab0a0ec099e7f5dcc15c320c4e85 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 20:46:28 -0700 Subject: [PATCH 13/46] sidebar per-agent rows: non-owner pane exit hook clears its own row state clearAgentPID returned early on the ownership mismatch, so after bare shared-key ownership migrated to a newer pane, the older pane's exit hook (clear_agent_pid --panel=A --clear-status) no-oped and A's panel-scoped row and lifecycle stayed stale until the pane closed. The mismatch branch now drops the requesting pane's own panel-scoped entry and lifecycle while leaving the current owner's runtime untouched. Also refresh the swift file length budget for the test growth (SidebarWorkspaceSnapshotRefreshPolicyTests.swift crossed 500 lines in the previous commit, which failed workflow-guard-tests). --- .github/swift-file-length-budget.tsv | 3 +- Sources/Workspace+PanelLifecycle.swift | 15 ++++++++- cmuxTests/PerAgentSidebarStatusRowTests.swift | 31 +++++++++++++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 8142a23c7f2d..92283643cca6 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -3,7 +3,7 @@ # Reduce counts as files shrink. CI fails if tracked files exceed this budget. 35600 CLI/cmux.swift 18229 Sources/AppDelegate.swift -16443 Sources/ContentView.swift +16303 Sources/ContentView.swift 15163 Sources/TerminalController.swift 13232 Sources/Workspace.swift 12511 Sources/GhosttyTerminalView.swift @@ -239,6 +239,7 @@ 524 CLI/CMUXCLI+AutoNaming.swift 520 CLI/CMUXCLI+AmpExtension.swift 520 cmuxTests/MainWindowVisibilityControllerTests.swift +520 cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift 519 Packages/macOS/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-two-column-cockpit-sidebar.swift 518 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift 518 Packages/macOS/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-git-review-queue-command-deck.swift diff --git a/Sources/Workspace+PanelLifecycle.swift b/Sources/Workspace+PanelLifecycle.swift index b16efc7d5b3a..9248b7c0656c 100644 --- a/Sources/Workspace+PanelLifecycle.swift +++ b/Sources/Workspace+PanelLifecycle.swift @@ -261,7 +261,20 @@ extension Workspace { ) -> Bool { let ownedPanelId = agentPIDPanelIdsByKey[key] if let panelId, let ownedPanelId, ownedPanelId != panelId { - return false + // Bare shared keys migrate ownership to the last reporting pane, + // so an earlier pane's exit hook arrives with a panel that no + // longer owns the PID key. Never touch the current owner's + // runtime, but still drop the exiting pane's own panel-scoped row + // state or its sidebar row would stay stale until the pane closes. + var didChange = false + let statusKey = agentStatusKey(forAgentPIDKey: key) + if clearAgentLifecycle(key: statusKey, panelId: panelId) { + didChange = true + } + if clearStatus, clearPanelStatusEntry(statusKey: statusKey, panelId: panelId) { + didChange = true + } + return didChange } let statusKeyToClear = clearStatus ? agentStatusKey(forAgentPIDKey: key) : nil diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 03c2bdf0d286..25df21a49999 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -267,6 +267,37 @@ struct PerAgentSidebarStatusRowTests { #expect(workspace.sidebarAgentStatusRows().isEmpty) } + @Test + func testBareKeyExitHookFromNonOwnerPaneClearsOnlyThatPanesRow() throws { + let workspace = Workspace() + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + // Real bare-key hook sequence: both panes report the shared + // `claude_code` key, ownership migrates to the last reporter. + workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: firstPanelId) + workspace.setAgentLifecycle(key: "claude_code", panelId: firstPanelId, lifecycle: .running) + + workspace.recordAgentPID(key: "claude_code", pid: 222, panelId: secondPanelId, refreshPorts: false) + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Waiting"), panelId: secondPanelId) + workspace.setAgentLifecycle(key: "claude_code", panelId: secondPanelId, lifecycle: .needsInput) + + // Pane A exits: its hook sends `clear_agent_pid claude_code --panel=A + // --clear-status` although pane B now owns the key. The clear must + // drop A's own row state without touching B's runtime. + #expect(workspace.clearAgentPID(key: "claude_code", panelId: firstPanelId, clearStatus: true, refreshPorts: false)) + + let rows = workspace.sidebarAgentStatusRows() + #expect(rows.map(\.panelId) == [secondPanelId]) + #expect(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"] == nil) + #expect(workspace.agentLifecycleStatesByPanelId[firstPanelId]?["claude_code"] == nil) + #expect(workspace.agentPIDs["claude_code"] == 222) + #expect(workspace.agentPIDPanelIdsByKey["claude_code"] == secondPanelId) + #expect(workspace.statusEntriesByPanelId[secondPanelId]?["claude_code"]?.value == "Waiting") + } + @Test func testClosingPanelWithoutPIDClearsSoleOwnerWorkspaceStatus() throws { let workspace = Workspace() From 099573f6a40ea383476e43053bc39253d12e3eb8 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 21:04:27 -0700 Subject: [PATCH 14/46] sidebar per-agent rows: guard repair (merge main, split oversized files) workflow-guard-tests on main rejects newly tracked >=500-line files outright, so a budget entry cannot legalize the test growth: split the three unrelated suites in SidebarWorkspaceSnapshotRefreshPolicyTests into their own files (SidebarSelectedWorkspaceScrollPolicyTests, SidebarWorkspaceRowInteractionStateTests) and revert the budget edit. Merge origin/main so the guard's merge base includes the VMClient.swift growth from https://github.com/manaflow-ai/cmux/pull/7547 (the stale base misattributed that hard-cap hit to this PR). Also move SidebarAgentStatusRowsSummary into its own file per the one-major-type-per-file policy this PR already applied in 7092c30f11. --- .github/swift-file-length-budget.tsv | 3 +- Sources/SidebarAgentStatusRowViews.swift | 42 --- Sources/SidebarAgentStatusRowsSummary.swift | 44 +++ cmux.xcodeproj/project.pbxproj | 12 + ...arSelectedWorkspaceScrollPolicyTests.swift | 97 ++++++ ...barWorkspaceRowInteractionStateTests.swift | 233 +++++++++++++ ...rWorkspaceSnapshotRefreshPolicyTests.swift | 308 ------------------ 7 files changed, 387 insertions(+), 352 deletions(-) create mode 100644 Sources/SidebarAgentStatusRowsSummary.swift create mode 100644 cmuxTests/SidebarSelectedWorkspaceScrollPolicyTests.swift create mode 100644 cmuxTests/SidebarWorkspaceRowInteractionStateTests.swift diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 8a59081469f7..6a0835822f88 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -3,7 +3,7 @@ # Reduce counts as files shrink. CI fails if tracked files exceed this budget. 35600 CLI/cmux.swift 18229 Sources/AppDelegate.swift -16303 Sources/ContentView.swift +16443 Sources/ContentView.swift 15163 Sources/TerminalController.swift 13232 Sources/Workspace.swift 12511 Sources/GhosttyTerminalView.swift @@ -239,7 +239,6 @@ 524 CLI/CMUXCLI+AutoNaming.swift 520 CLI/CMUXCLI+AmpExtension.swift 520 cmuxTests/MainWindowVisibilityControllerTests.swift -520 cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift 519 Packages/macOS/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-two-column-cockpit-sidebar.swift 518 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift 518 Packages/macOS/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-git-review-queue-command-deck.swift diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index 0a3bf81bcbe9..7674bff23d59 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -3,48 +3,6 @@ import CmuxFoundation import CmuxSidebar import SwiftUI -/// Aggregate over the agent rows of one workspace, shown in the accordion -/// header (and standing in for the rows while collapsed). -struct SidebarAgentStatusRowsSummary: Equatable { - let agentCount: Int - let needsInputCount: Int - let runningCount: Int - - init(rows: [SidebarAgentStatusRow]) { - agentCount = rows.count - needsInputCount = rows.filter { $0.lifecycle == .needsInput }.count - runningCount = rows.filter { $0.lifecycle == .running }.count - } - - var text: String { - var parts: [String] = [] - if agentCount == 1 { - parts.append(String(localized: "sidebar.agentStatus.summary.oneAgent", defaultValue: "1 agent")) - } else { - parts.append(String( - format: String(localized: "sidebar.agentStatus.summary.agentCount", defaultValue: "%lld agents"), - agentCount - )) - } - if needsInputCount == 1 { - parts.append(String(localized: "sidebar.agentStatus.summary.oneNeedsInput", defaultValue: "1 needs input")) - } else if needsInputCount > 1 { - parts.append(String( - format: String(localized: "sidebar.agentStatus.summary.needsInputCount", defaultValue: "%lld need input"), - needsInputCount - )) - } - return parts.joined(separator: " · ") - } - - /// Worst-state accent: needs-input beats running beats idle. - var accentColorHex: String? { - if needsInputCount > 0 { return "#FF9F0A" } - if runningCount > 0 { return "#4C8DFF" } - return nil - } -} - /// Sidebar per-agent-pane status rows: one row per live agent pane plus its /// private entry row. With more than one agent the block becomes an accordion: /// a summary header ("2 agents · 1 needs input") that folds the rows. Rows diff --git a/Sources/SidebarAgentStatusRowsSummary.swift b/Sources/SidebarAgentStatusRowsSummary.swift new file mode 100644 index 000000000000..c15f136e29d1 --- /dev/null +++ b/Sources/SidebarAgentStatusRowsSummary.swift @@ -0,0 +1,44 @@ +import Foundation + +/// Aggregate over the agent rows of one workspace, shown in the accordion +/// header of `SidebarAgentStatusRows` (and standing in for the rows while +/// collapsed). +struct SidebarAgentStatusRowsSummary: Equatable { + let agentCount: Int + let needsInputCount: Int + let runningCount: Int + + init(rows: [SidebarAgentStatusRow]) { + agentCount = rows.count + needsInputCount = rows.filter { $0.lifecycle == .needsInput }.count + runningCount = rows.filter { $0.lifecycle == .running }.count + } + + var text: String { + var parts: [String] = [] + if agentCount == 1 { + parts.append(String(localized: "sidebar.agentStatus.summary.oneAgent", defaultValue: "1 agent")) + } else { + parts.append(String( + format: String(localized: "sidebar.agentStatus.summary.agentCount", defaultValue: "%lld agents"), + agentCount + )) + } + if needsInputCount == 1 { + parts.append(String(localized: "sidebar.agentStatus.summary.oneNeedsInput", defaultValue: "1 needs input")) + } else if needsInputCount > 1 { + parts.append(String( + format: String(localized: "sidebar.agentStatus.summary.needsInputCount", defaultValue: "%lld need input"), + needsInputCount + )) + } + return parts.joined(separator: " · ") + } + + /// Worst-state accent: needs-input beats running beats idle. + var accentColorHex: String? { + if needsInputCount > 0 { return "#FF9F0A" } + if runningCount > 0 { return "#4C8DFF" } + return nil + } +} diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 85d118c2ffd4..a26a347dd497 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1061,6 +1061,7 @@ 5C3E0454B6C24B02A2F091A8 /* ShortcutRoutingSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = B42A82C6AA614E74873D9A5F /* ShortcutRoutingSupport.swift */; }; F6001000A1B2C3D4E5F60718 /* ShortcutUnbindingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6001001A1B2C3D4E5F60718 /* ShortcutUnbindingTests.swift */; }; C3467AB10000000000000001 /* ShortcutWhenClauseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3467AB10000000000000002 /* ShortcutWhenClauseTests.swift */; }; + 2FB188449942360CAB895143 /* SidebarAgentStatusRowsSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D2990638B9E75D4B02AF14F /* SidebarAgentStatusRowsSummary.swift */; }; 7A11AA057A11AA057A11AA05 /* SidebarAgentStatusRowViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */; }; 211A75777F433ED8BA5AE208 /* SidebarAppearanceSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 243632BA1DBBA36FD46E0610 /* SidebarAppearanceSupport.swift */; }; D7AB34310000000000000003 /* SidebarBonsplitTabDropDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34310000000000000004 /* SidebarBonsplitTabDropDelegate.swift */; }; @@ -1094,6 +1095,7 @@ AABBCC00000000000000020A /* SidebarRowDragGate.swift in Sources */ = {isa = PBXBuildFile; fileRef = AABBCC000000000000000209 /* SidebarRowDragGate.swift */; }; C0DE35010000000000000001 /* SidebarScrim.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE35010000000000000002 /* SidebarScrim.swift */; }; C9A57513C9A57513C9A57513 /* SidebarScrollViewConfiguratorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9A57514C9A57514C9A57514 /* SidebarScrollViewConfiguratorTests.swift */; }; + 8217C253F7094AEF327D3C2C /* SidebarSelectedWorkspaceScrollPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75165CBC3A62A756E504EDAA /* SidebarSelectedWorkspaceScrollPolicyTests.swift */; }; E62155868BB29FEB5DAAAF25 /* SidebarSelectionState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD52285508B1D6A9875E7B3 /* SidebarSelectionState.swift */; }; F57072635F25EBCA741E125D /* SidebarState.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1614EAD3CCF70A177A51BD1 /* SidebarState.swift */; }; D7344F010000000000000001 /* SidebarTabDragPayload.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7344F010000000000000002 /* SidebarTabDragPayload.swift */; }; @@ -1121,6 +1123,7 @@ D35450070000000000000007 /* SidebarWorkspaceRowHoverReconciler.swift in Sources */ = {isa = PBXBuildFile; fileRef = D35450070000000000000008 /* SidebarWorkspaceRowHoverReconciler.swift */; }; D35450070000000000000009 /* SidebarWorkspaceRowHoverReconcilerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3545007000000000000000A /* SidebarWorkspaceRowHoverReconcilerView.swift */; }; D3545007000000000000000B /* SidebarWorkspaceRowHoverTrackingModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3545007000000000000000C /* SidebarWorkspaceRowHoverTrackingModifier.swift */; }; + 44576F2FBCF43FF925F8838C /* SidebarWorkspaceRowInteractionStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0963502F3A0F42A3DA1B6124 /* SidebarWorkspaceRowInteractionStateTests.swift */; }; D35450030000000000000003 /* SidebarWorkspaceRowMenuTrackingReconciler.swift in Sources */ = {isa = PBXBuildFile; fileRef = D35450030000000000000004 /* SidebarWorkspaceRowMenuTrackingReconciler.swift */; }; D35450030000000000000005 /* SidebarWorkspaceRowMenuTrackingReconcilerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D35450030000000000000006 /* SidebarWorkspaceRowMenuTrackingReconcilerView.swift */; }; C9A57505C9A57505C9A57505 /* SidebarWorkspaceScrollLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9A57506C9A57506C9A57506 /* SidebarWorkspaceScrollLayoutTests.swift */; }; @@ -2520,6 +2523,7 @@ B42A82C6AA614E74873D9A5F /* ShortcutRoutingSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = App/ShortcutRoutingSupport.swift; sourceTree = ""; }; F6001001A1B2C3D4E5F60718 /* ShortcutUnbindingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShortcutUnbindingTests.swift; sourceTree = ""; }; C3467AB10000000000000002 /* ShortcutWhenClauseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShortcutWhenClauseTests.swift; sourceTree = ""; }; + 1D2990638B9E75D4B02AF14F /* SidebarAgentStatusRowsSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentStatusRowsSummary.swift; sourceTree = ""; }; 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentStatusRowViews.swift; sourceTree = ""; }; 243632BA1DBBA36FD46E0610 /* SidebarAppearanceSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarAppearanceSupport.swift; sourceTree = ""; }; D7AB34310000000000000004 /* SidebarBonsplitTabDropDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarBonsplitTabDropDelegate.swift; sourceTree = ""; }; @@ -2553,6 +2557,7 @@ AABBCC000000000000000209 /* SidebarRowDragGate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarRowDragGate.swift; sourceTree = ""; }; C0DE35010000000000000002 /* SidebarScrim.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarScrim.swift; sourceTree = ""; }; C9A57514C9A57514C9A57514 /* SidebarScrollViewConfiguratorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarScrollViewConfiguratorTests.swift; sourceTree = ""; }; + 75165CBC3A62A756E504EDAA /* SidebarSelectedWorkspaceScrollPolicyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarSelectedWorkspaceScrollPolicyTests.swift; sourceTree = ""; }; 9AD52285508B1D6A9875E7B3 /* SidebarSelectionState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarSelectionState.swift; sourceTree = ""; }; D1614EAD3CCF70A177A51BD1 /* SidebarState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarState.swift; sourceTree = ""; }; D7344F010000000000000002 /* SidebarTabDragPayload.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarTabDragPayload.swift; sourceTree = ""; }; @@ -2580,6 +2585,7 @@ D35450070000000000000008 /* SidebarWorkspaceRowHoverReconciler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarWorkspaceRowHoverReconciler.swift; sourceTree = ""; }; D3545007000000000000000A /* SidebarWorkspaceRowHoverReconcilerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarWorkspaceRowHoverReconcilerView.swift; sourceTree = ""; }; D3545007000000000000000C /* SidebarWorkspaceRowHoverTrackingModifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarWorkspaceRowHoverTrackingModifier.swift; sourceTree = ""; }; + 0963502F3A0F42A3DA1B6124 /* SidebarWorkspaceRowInteractionStateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarWorkspaceRowInteractionStateTests.swift; sourceTree = ""; }; D35450030000000000000004 /* SidebarWorkspaceRowMenuTrackingReconciler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarWorkspaceRowMenuTrackingReconciler.swift; sourceTree = ""; }; D35450030000000000000006 /* SidebarWorkspaceRowMenuTrackingReconcilerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarWorkspaceRowMenuTrackingReconcilerView.swift; sourceTree = ""; }; C9A57506C9A57506C9A57506 /* SidebarWorkspaceScrollLayoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarWorkspaceScrollLayoutTests.swift; sourceTree = ""; }; @@ -3448,6 +3454,7 @@ 7A11AA027A11AA027A11AA02 /* Workspace+SidebarAgentStatus.swift */, 7A11AA047A11AA047A11AA04 /* SidebarMetadataRowViews.swift */, 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */, + 1D2990638B9E75D4B02AF14F /* SidebarAgentStatusRowsSummary.swift */, C0A1E5CE01C0A1E5CE01A002 /* CoalesceLatestPublisher.swift */, 5659A0025659A0025659A002 /* WorkspaceSidebarObservation.swift */, 5659B0025659B0025659B002 /* WorkspaceSidebarLogEntryLimitProvider.swift */, @@ -4283,6 +4290,8 @@ 46792DAA478444ED87B17B31 /* AutoNamingHookPayloadAdapterTests.swift */, CE7000000000000000000002 /* ClaudeWrapperResumeEnvironmentTests.swift */, F016B5C09357B3226FA2E014 /* SidebarWorkspaceSnapshotRefreshPolicyTests.swift */, + 75165CBC3A62A756E504EDAA /* SidebarSelectedWorkspaceScrollPolicyTests.swift */, + 0963502F3A0F42A3DA1B6124 /* SidebarWorkspaceRowInteractionStateTests.swift */, C9A57514C9A57514C9A57514 /* SidebarScrollViewConfiguratorTests.swift */, C9A57506C9A57506C9A57506 /* SidebarWorkspaceScrollLayoutTests.swift */, D41A7C02D41A7C02D41A7C02 /* SidebarLazyLayoutScaleTests.swift */, @@ -5521,6 +5530,7 @@ 125BAEF2FE3B454547B964D1 /* ShortcutHintPill.swift in Sources */, 6042C0046042C0046042C004 /* ShortcutHintTitlebarPolicy.swift in Sources */, 5C3E0454B6C24B02A2F091A8 /* ShortcutRoutingSupport.swift in Sources */, + 2FB188449942360CAB895143 /* SidebarAgentStatusRowsSummary.swift in Sources */, 7A11AA057A11AA057A11AA05 /* SidebarAgentStatusRowViews.swift in Sources */, 211A75777F433ED8BA5AE208 /* SidebarAppearanceSupport.swift in Sources */, D7AB34310000000000000003 /* SidebarBonsplitTabDropDelegate.swift in Sources */, @@ -6222,6 +6232,7 @@ CB23911D7E131E8FBC9B82B6 /* SidebarOrderingTests.swift in Sources */, C0DE48000000000000000001 /* SidebarProviderMenuRegressionTests.swift in Sources */, C9A57513C9A57513C9A57513 /* SidebarScrollViewConfiguratorTests.swift in Sources */, + 8217C253F7094AEF327D3C2C /* SidebarSelectedWorkspaceScrollPolicyTests.swift in Sources */, D73440010000000000000001 /* SidebarTabDragPayloadProviderTests.swift in Sources */, D7AB34300000000000000105 /* SidebarTabDropIndicatorPredicateTests.swift in Sources */, CA39C0304FE351A21C372429 /* SidebarWidthPolicyTests.swift in Sources */, @@ -6229,6 +6240,7 @@ C135190000000000000000B1 /* SidebarWorkspaceGroupConfigOpenerTests.swift in Sources */, C9A57303C9A57303C9A57303 /* SidebarWorkspaceGroupHeaderMetricsTests.swift in Sources */, C9A57305C9A57305C9A57305 /* SidebarWorkspaceReorderDropOverlayHitTestingTests.swift in Sources */, + 44576F2FBCF43FF925F8838C /* SidebarWorkspaceRowInteractionStateTests.swift in Sources */, C9A57505C9A57505C9A57505 /* SidebarWorkspaceScrollLayoutTests.swift in Sources */, C0DE56010000000000000001 /* SidebarWorkspaceSelectionAnchorPolicyTests.swift in Sources */, 62270F3DCECB4787D789CCE3 /* SidebarWorkspaceSnapshotRefreshPolicyTests.swift in Sources */, diff --git a/cmuxTests/SidebarSelectedWorkspaceScrollPolicyTests.swift b/cmuxTests/SidebarSelectedWorkspaceScrollPolicyTests.swift new file mode 100644 index 000000000000..367be574f370 --- /dev/null +++ b/cmuxTests/SidebarSelectedWorkspaceScrollPolicyTests.swift @@ -0,0 +1,97 @@ +import AppKit +import CmuxSidebar +import CmuxWorkspaces +import SwiftUI +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite struct SidebarSelectedWorkspaceScrollPolicyTests { + @Test func skipsScrollWhenSelectedWorkspaceIdIsNil() { + #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( + selectedWorkspaceId: nil as String?, + oldWorkspaceIds: ["a"], + newWorkspaceIds: ["a"] + )) + } + + @Test func requestsScrollWhenSelectedWorkspaceFirstAppears() { + #expect(SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( + selectedWorkspaceId: "b", + oldWorkspaceIds: ["a"], + newWorkspaceIds: ["a", "b"] + )) + } + + @Test func requestsScrollWhenSelectedWorkspaceMovesToTop() { + #expect(SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( + selectedWorkspaceId: "c", + oldWorkspaceIds: ["a", "b", "c"], + newWorkspaceIds: ["c", "a", "b"] + )) + } + + @Test func requestsScrollWhenAnotherReorderShiftsSelectedWorkspaceIndex() { + #expect(SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( + selectedWorkspaceId: "b", + oldWorkspaceIds: ["a", "b", "c"], + newWorkspaceIds: ["c", "a", "b"] + )) + } + + @Test func skipsScrollWhenReorderLeavesSelectedWorkspaceIndexUnchanged() { + #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( + selectedWorkspaceId: "a", + oldWorkspaceIds: ["a", "b", "c"], + newWorkspaceIds: ["a", "c", "b"] + )) + } + + @Test func skipsScrollWhenSelectedWorkspaceIsMissing() { + #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( + selectedWorkspaceId: "b", + oldWorkspaceIds: ["a", "b"], + newWorkspaceIds: ["a", "c"] + )) + } + + @Test func scrollTargetIsSelfWithoutGroup() { + let workspaceId = UUID() + #expect(SidebarSelectedWorkspaceScrollPolicy.scrollTargetWorkspaceId( + selectedWorkspaceId: workspaceId, + group: nil + ) == workspaceId) + } + + @Test func scrollTargetIsSelfInExpandedGroup() { + let workspaceId = UUID() + #expect(SidebarSelectedWorkspaceScrollPolicy.scrollTargetWorkspaceId( + selectedWorkspaceId: workspaceId, + group: makeGroup(isCollapsed: false, anchorWorkspaceId: UUID()) + ) == workspaceId) + } + + @Test func scrollTargetIsGroupAnchorWhenGroupIsCollapsed() { + let anchorId = UUID() + #expect(SidebarSelectedWorkspaceScrollPolicy.scrollTargetWorkspaceId( + selectedWorkspaceId: UUID(), + group: makeGroup(isCollapsed: true, anchorWorkspaceId: anchorId) + ) == anchorId) + } + + private func makeGroup(isCollapsed: Bool, anchorWorkspaceId: UUID) -> WorkspaceGroup { + WorkspaceGroup( + id: UUID(), + name: "group", + isCollapsed: isCollapsed, + isPinned: false, + anchorWorkspaceId: anchorWorkspaceId, + customColor: nil, + iconSymbol: nil + ) + } +} diff --git a/cmuxTests/SidebarWorkspaceRowInteractionStateTests.swift b/cmuxTests/SidebarWorkspaceRowInteractionStateTests.swift new file mode 100644 index 000000000000..5d747e1e02a6 --- /dev/null +++ b/cmuxTests/SidebarWorkspaceRowInteractionStateTests.swift @@ -0,0 +1,233 @@ +import AppKit +import CmuxSidebar +import CmuxWorkspaces +import SwiftUI +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite struct SidebarWorkspaceRowInteractionStateTests { + @Test func appKitMenuTrackingEndClearsStaleContextMenuVisibility() { + var state = SidebarWorkspaceRowInteractionState() + + state.contextMenuDidAppear() + #expect(state.contextMenuVisible) + + let didEndTracking = state.contextMenuTrackingDidEnd(pointerInsideRow: true) + #expect(didEndTracking) + state.setPointerHovering(true) + + #expect( + state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "AppKit menu tracking ending must clear stale SwiftUI context-menu visibility so later hover can reveal row affordances." + ) + } + + @Test func appKitMenuTrackingEndUsesReconciledPointerExit() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + state.contextMenuDidAppear() + + let didEndTracking = state.contextMenuTrackingDidEnd(pointerInsideRow: false) + #expect(didEndTracking) + + #expect( + !state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "If the pointer leaves through the context menu, AppKit menu tracking reconciliation must keep the row affordance hidden." + ) + } + + @Test @MainActor func menuTrackingReconcilerIgnoresSubmenuEndNotifications() { + let rootMenu = NSMenu() + let submenu = NSMenu() + let item = NSMenuItem(title: "submenu", action: nil, keyEquivalent: "") + rootMenu.addItem(item) + rootMenu.setSubmenu(submenu, for: item) + + #expect(SidebarWorkspaceRowMenuTrackingReconcilerView.shouldReconcileMenuEnd(object: rootMenu)) + #expect(!SidebarWorkspaceRowMenuTrackingReconcilerView.shouldReconcileMenuEnd(object: submenu)) + #expect(!SidebarWorkspaceRowMenuTrackingReconcilerView.shouldReconcileMenuEnd(object: nil)) + } + + @Test func hoverDuringContextMenuStaysHiddenUntilDismissal() { + var state = SidebarWorkspaceRowInteractionState() + + state.contextMenuDidAppear() + state.setPointerHovering(true) + + #expect( + !state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "Pointer hover updates observed during the context-menu lifecycle must not reveal the close affordance under the menu." + ) + + state.contextMenuDidDisappear() + + #expect( + state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "Once the context menu dismisses, the last observed pointer position may reveal the close affordance." + ) + } + + @Test func contextMenuDismissalRestoresHoverWithoutPointerMovement() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + state.contextMenuDidAppear() + state.contextMenuDidDisappear() + + #expect( + state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "Closing a context menu without moving the pointer must restore the row hover affordance." + ) + } + + @Test func pointerExitWhileContextMenuIsVisibleStaysHiddenAfterDismissal() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + state.contextMenuDidAppear() + state.contextMenuTrackingObserverDidInstall() + state.setPointerHovering(false) + state.contextMenuDidDisappear() + + #expect( + !state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "Pointer exit remains authoritative even when it is observed during the context-menu lifecycle." + ) + } + + @Test func swiftUIOnlyFastContextMenuDismissalKeepsInitialHoverFallback() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + state.contextMenuDidAppear() + state.setPointerHovering(false) + state.contextMenuDidDisappear() + + #expect( + state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "A SwiftUI hover-exit caused by the menu taking focus must not erase the initial hover fallback before the AppKit reconciler mounts." + ) + } + + @Test func noHoverDoesNotRevealCloseButtonWhileContextMenuIsVisible() { + var state = SidebarWorkspaceRowInteractionState() + + state.contextMenuDidAppear() + state.setPointerHovering(false) + + #expect( + !state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "A visible context menu must not make the close affordance visible when the pointer is not hovering." + ) + } + + @Test @MainActor func hoverReconcilerRestoresCloseButtonAfterLifecycleHoverReset() { + var state = SidebarWorkspaceRowInteractionState() + + let view = SidebarWorkspaceRowHoverReconcilerView() + view.frame = NSRect(x: 0, y: 0, width: 120, height: 28) + view.onPointerHoverChanged = { state.setPointerHovering($0) } + + view.reconcilePointerLocation(pointInView: NSPoint(x: 60, y: 14)) + #expect(state.shouldShowCloseButton(canCloseWorkspace: true, shortcutHintModeActive: false)) + + state.setPointerHovering(false) + #expect(!state.shouldShowCloseButton(canCloseWorkspace: true, shortcutHintModeActive: false)) + + view.reconcilePointerLocation(pointInView: NSPoint(x: 60, y: 14)) + + #expect( + state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "When sidebar updates or row reuse clear SwiftUI hover state while the pointer is still inside the row, the AppKit hover reconciler must restore the close affordance without waiting for another mouse move." + ) + } + + @Test func contextMenuAppearanceHidesExistingCloseButtonUntilPointerIsReconciled() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + #expect(state.shouldShowCloseButton(canCloseWorkspace: true, shortcutHintModeActive: false)) + + state.contextMenuDidAppear() + + #expect( + !state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "Opening a context menu must clear the row close affordance until tracking reports the pointer is still inside." + ) + } + + @Test func contextMenuDismissalCanRevealAfterPointerReconciliation() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + state.contextMenuDidAppear() + state.contextMenuDidDisappear() + state.setPointerHovering(true) + + #expect( + state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "Closing the context menu may reveal the close affordance again only after pointer tracking reconciles inside the row." + ) + } + + @Test func closeButtonHiddenWhenWorkspaceCannotBeClosed() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + + #expect(!state.shouldShowCloseButton( + canCloseWorkspace: false, + shortcutHintModeActive: false + )) + } + + @Test func closeButtonHiddenDuringShortcutHintMode() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + + #expect(!state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: true + )) + } +} diff --git a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift index 24a968acc9a7..411a0bc232f1 100644 --- a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift +++ b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift @@ -210,311 +210,3 @@ import Testing ) } } - -@Suite struct SidebarSelectedWorkspaceScrollPolicyTests { - @Test func skipsScrollWhenSelectedWorkspaceIdIsNil() { - #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( - selectedWorkspaceId: nil as String?, - oldWorkspaceIds: ["a"], - newWorkspaceIds: ["a"] - )) - } - - @Test func requestsScrollWhenSelectedWorkspaceFirstAppears() { - #expect(SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( - selectedWorkspaceId: "b", - oldWorkspaceIds: ["a"], - newWorkspaceIds: ["a", "b"] - )) - } - - @Test func requestsScrollWhenSelectedWorkspaceMovesToTop() { - #expect(SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( - selectedWorkspaceId: "c", - oldWorkspaceIds: ["a", "b", "c"], - newWorkspaceIds: ["c", "a", "b"] - )) - } - - @Test func requestsScrollWhenAnotherReorderShiftsSelectedWorkspaceIndex() { - #expect(SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( - selectedWorkspaceId: "b", - oldWorkspaceIds: ["a", "b", "c"], - newWorkspaceIds: ["c", "a", "b"] - )) - } - - @Test func skipsScrollWhenReorderLeavesSelectedWorkspaceIndexUnchanged() { - #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( - selectedWorkspaceId: "a", - oldWorkspaceIds: ["a", "b", "c"], - newWorkspaceIds: ["a", "c", "b"] - )) - } - - @Test func skipsScrollWhenSelectedWorkspaceIsMissing() { - #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( - selectedWorkspaceId: "b", - oldWorkspaceIds: ["a", "b"], - newWorkspaceIds: ["a", "c"] - )) - } - - @Test func scrollTargetIsSelfWithoutGroup() { - let workspaceId = UUID() - #expect(SidebarSelectedWorkspaceScrollPolicy.scrollTargetWorkspaceId( - selectedWorkspaceId: workspaceId, - group: nil - ) == workspaceId) - } - - @Test func scrollTargetIsSelfInExpandedGroup() { - let workspaceId = UUID() - #expect(SidebarSelectedWorkspaceScrollPolicy.scrollTargetWorkspaceId( - selectedWorkspaceId: workspaceId, - group: makeGroup(isCollapsed: false, anchorWorkspaceId: UUID()) - ) == workspaceId) - } - - @Test func scrollTargetIsGroupAnchorWhenGroupIsCollapsed() { - let anchorId = UUID() - #expect(SidebarSelectedWorkspaceScrollPolicy.scrollTargetWorkspaceId( - selectedWorkspaceId: UUID(), - group: makeGroup(isCollapsed: true, anchorWorkspaceId: anchorId) - ) == anchorId) - } - - private func makeGroup(isCollapsed: Bool, anchorWorkspaceId: UUID) -> WorkspaceGroup { - WorkspaceGroup( - id: UUID(), - name: "group", - isCollapsed: isCollapsed, - isPinned: false, - anchorWorkspaceId: anchorWorkspaceId, - customColor: nil, - iconSymbol: nil - ) - } -} - -@Suite struct SidebarWorkspaceRowInteractionStateTests { - @Test func appKitMenuTrackingEndClearsStaleContextMenuVisibility() { - var state = SidebarWorkspaceRowInteractionState() - - state.contextMenuDidAppear() - #expect(state.contextMenuVisible) - - let didEndTracking = state.contextMenuTrackingDidEnd(pointerInsideRow: true) - #expect(didEndTracking) - state.setPointerHovering(true) - - #expect( - state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "AppKit menu tracking ending must clear stale SwiftUI context-menu visibility so later hover can reveal row affordances." - ) - } - - @Test func appKitMenuTrackingEndUsesReconciledPointerExit() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - state.contextMenuDidAppear() - - let didEndTracking = state.contextMenuTrackingDidEnd(pointerInsideRow: false) - #expect(didEndTracking) - - #expect( - !state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "If the pointer leaves through the context menu, AppKit menu tracking reconciliation must keep the row affordance hidden." - ) - } - - @Test @MainActor func menuTrackingReconcilerIgnoresSubmenuEndNotifications() { - let rootMenu = NSMenu() - let submenu = NSMenu() - let item = NSMenuItem(title: "submenu", action: nil, keyEquivalent: "") - rootMenu.addItem(item) - rootMenu.setSubmenu(submenu, for: item) - - #expect(SidebarWorkspaceRowMenuTrackingReconcilerView.shouldReconcileMenuEnd(object: rootMenu)) - #expect(!SidebarWorkspaceRowMenuTrackingReconcilerView.shouldReconcileMenuEnd(object: submenu)) - #expect(!SidebarWorkspaceRowMenuTrackingReconcilerView.shouldReconcileMenuEnd(object: nil)) - } - - @Test func hoverDuringContextMenuStaysHiddenUntilDismissal() { - var state = SidebarWorkspaceRowInteractionState() - - state.contextMenuDidAppear() - state.setPointerHovering(true) - - #expect( - !state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "Pointer hover updates observed during the context-menu lifecycle must not reveal the close affordance under the menu." - ) - - state.contextMenuDidDisappear() - - #expect( - state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "Once the context menu dismisses, the last observed pointer position may reveal the close affordance." - ) - } - - @Test func contextMenuDismissalRestoresHoverWithoutPointerMovement() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - state.contextMenuDidAppear() - state.contextMenuDidDisappear() - - #expect( - state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "Closing a context menu without moving the pointer must restore the row hover affordance." - ) - } - - @Test func pointerExitWhileContextMenuIsVisibleStaysHiddenAfterDismissal() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - state.contextMenuDidAppear() - state.contextMenuTrackingObserverDidInstall() - state.setPointerHovering(false) - state.contextMenuDidDisappear() - - #expect( - !state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "Pointer exit remains authoritative even when it is observed during the context-menu lifecycle." - ) - } - - @Test func swiftUIOnlyFastContextMenuDismissalKeepsInitialHoverFallback() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - state.contextMenuDidAppear() - state.setPointerHovering(false) - state.contextMenuDidDisappear() - - #expect( - state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "A SwiftUI hover-exit caused by the menu taking focus must not erase the initial hover fallback before the AppKit reconciler mounts." - ) - } - - @Test func noHoverDoesNotRevealCloseButtonWhileContextMenuIsVisible() { - var state = SidebarWorkspaceRowInteractionState() - - state.contextMenuDidAppear() - state.setPointerHovering(false) - - #expect( - !state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "A visible context menu must not make the close affordance visible when the pointer is not hovering." - ) - } - - @Test @MainActor func hoverReconcilerRestoresCloseButtonAfterLifecycleHoverReset() { - var state = SidebarWorkspaceRowInteractionState() - - let view = SidebarWorkspaceRowHoverReconcilerView() - view.frame = NSRect(x: 0, y: 0, width: 120, height: 28) - view.onPointerHoverChanged = { state.setPointerHovering($0) } - - view.reconcilePointerLocation(pointInView: NSPoint(x: 60, y: 14)) - #expect(state.shouldShowCloseButton(canCloseWorkspace: true, shortcutHintModeActive: false)) - - state.setPointerHovering(false) - #expect(!state.shouldShowCloseButton(canCloseWorkspace: true, shortcutHintModeActive: false)) - - view.reconcilePointerLocation(pointInView: NSPoint(x: 60, y: 14)) - - #expect( - state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "When sidebar updates or row reuse clear SwiftUI hover state while the pointer is still inside the row, the AppKit hover reconciler must restore the close affordance without waiting for another mouse move." - ) - } - - @Test func contextMenuAppearanceHidesExistingCloseButtonUntilPointerIsReconciled() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - #expect(state.shouldShowCloseButton(canCloseWorkspace: true, shortcutHintModeActive: false)) - - state.contextMenuDidAppear() - - #expect( - !state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "Opening a context menu must clear the row close affordance until tracking reports the pointer is still inside." - ) - } - - @Test func contextMenuDismissalCanRevealAfterPointerReconciliation() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - state.contextMenuDidAppear() - state.contextMenuDidDisappear() - state.setPointerHovering(true) - - #expect( - state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "Closing the context menu may reveal the close affordance again only after pointer tracking reconciles inside the row." - ) - } - - @Test func closeButtonHiddenWhenWorkspaceCannotBeClosed() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - - #expect(!state.shouldShowCloseButton( - canCloseWorkspace: false, - shortcutHintModeActive: false - )) - } - - @Test func closeButtonHiddenDuringShortcutHintMode() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - - #expect(!state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: true - )) - } -} From 801912500e56616184123fc0b1444e7cdd67f8f9 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 21:16:25 -0700 Subject: [PATCH 15/46] sidebar: agent brand icons, restore-surviving per-agent rows - Rows show the agent's brand mark (AgentIcons asset) with a colored state dot; keys without an asset keep the SF-symbol fallback. - Panel-scoped status entries and lifecycles persist in the session snapshot per terminal panel and re-seed on restore keyed to the restored pane, so rows survive relaunch with a live pane binding (click-to-navigate keeps working). Captured running lifecycle demotes to unknown on restore since the resumed agent sits at its prompt. --- Sources/SessionPersistence.swift | 11 +++- Sources/SidebarAgentStatusRowViews.swift | 37 ++++++++++++- Sources/Workspace+SidebarAgentStatus.swift | 55 +++++++++++++++++++ Sources/Workspace.swift | 5 +- cmuxTests/PerAgentSidebarStatusRowTests.swift | 34 ++++++++++++ 5 files changed, 139 insertions(+), 3 deletions(-) diff --git a/Sources/SessionPersistence.swift b/Sources/SessionPersistence.swift index 759abe72d0c7..7ecb80d37954 100644 --- a/Sources/SessionPersistence.swift +++ b/Sources/SessionPersistence.swift @@ -1398,6 +1398,11 @@ struct SessionTerminalPanelSnapshot: Codable, Sendable { /// Whether the agent process was actively running when this snapshot was captured. /// Nil means unknown (legacy snapshots); treated as true for backwards compatibility. var wasAgentRunning: Bool? + /// Panel-scoped structured agent status reports (one per status key), so + /// per-agent sidebar rows keep their pane binding across restart. + var agentStatusEntries: [SessionStatusEntrySnapshot]? + /// Last known agent lifecycle raw value per structured status key. + var agentLifecyclesByStatusKey: [String: String]? init( workingDirectory: String? = nil, @@ -1409,7 +1414,9 @@ struct SessionTerminalPanelSnapshot: Codable, Sendable { textBoxDraft: SessionTextBoxInputDraftSnapshot? = nil, isRemoteTerminal: Bool? = nil, remotePTYSessionID: String? = nil, - wasAgentRunning: Bool? = nil + wasAgentRunning: Bool? = nil, + agentStatusEntries: [SessionStatusEntrySnapshot]? = nil, + agentLifecyclesByStatusKey: [String: String]? = nil ) { self.workingDirectory = workingDirectory self.scrollback = scrollback @@ -1421,6 +1428,8 @@ struct SessionTerminalPanelSnapshot: Codable, Sendable { self.isRemoteTerminal = isRemoteTerminal self.remotePTYSessionID = remotePTYSessionID self.wasAgentRunning = wasAgentRunning + self.agentStatusEntries = agentStatusEntries + self.agentLifecyclesByStatusKey = agentLifecyclesByStatusKey } } diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index 7674bff23d59..c67e4f2910be 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -116,7 +116,17 @@ private struct SidebarAgentStatusEntryRow: View { @ViewBuilder private func rowContent(underlined: Bool) -> some View { HStack(spacing: 4) { - if let icon = iconView { + if let brandAssetName { + Image(brandAssetName) + .resizable() + .scaledToFit() + .frame(width: 11 * fontScale, height: 11 * fontScale) + if let stateColor { + Circle() + .fill(stateColor) + .frame(width: 5 * fontScale, height: 5 * fontScale) + } + } else if let icon = iconView { icon .foregroundColor(foregroundColor.opacity(0.95)) } @@ -200,6 +210,31 @@ private struct SidebarAgentStatusEntryRow: View { .joined(separator: " ") } + /// Brand marks for the structured agent status keys that have assets in + /// `Assets.xcassets/AgentIcons`; keys without a mark keep the reported or + /// lifecycle-derived SF symbol. + static let brandAssetsByStatusKey: [String: String] = [ + "antigravity": "AgentIcons/Antigravity", + "claude_code": "AgentIcons/Claude", + "codex": "AgentIcons/Codex", + "grok": "AgentIcons/Grok", + "hermes-agent": "AgentIcons/HermesAgent", + "opencode": "AgentIcons/OpenCode", + "pi": "AgentIcons/Pi", + "rovodev": "AgentIcons/RovoDev", + ] + + private var brandAssetName: String? { + Self.brandAssetsByStatusKey[row.statusKey] + } + + /// Lifecycle/report state shown as a dot next to the brand mark, which + /// replaces the state-colored SF symbol when a brand asset exists. + private var stateColor: Color? { + guard let raw = effectiveColorHex else { return nil } + return Color(hex: raw) + } + private var effectiveIcon: String? { if let icon = row.icon?.trimmingCharacters(in: .whitespacesAndNewlines), !icon.isEmpty { return icon diff --git a/Sources/Workspace+SidebarAgentStatus.swift b/Sources/Workspace+SidebarAgentStatus.swift index 5b9c4f2a28d7..959eb1e54f7d 100644 --- a/Sources/Workspace+SidebarAgentStatus.swift +++ b/Sources/Workspace+SidebarAgentStatus.swift @@ -245,4 +245,59 @@ extension Workspace { } return lhs.key > rhs.key } + + // MARK: - Session persistence + + /// Panel-scoped structured status reports for the session snapshot, so a + /// restored pane keeps its own sidebar row (and stays click-navigable) + /// instead of degrading to the ambiguous workspace-level slot. + func panelScopedAgentStatusSnapshots(panelId: UUID) -> [SessionStatusEntrySnapshot]? { + let entries = (statusEntriesByPanelId[panelId] ?? [:]).values + .filter { Self.structuredAgentHookStatusKeys.contains($0.key) } + .sorted { $0.key < $1.key } + .map { + SessionStatusEntrySnapshot( + key: $0.key, + value: $0.value, + icon: $0.icon, + color: $0.color, + timestamp: $0.timestamp.timeIntervalSince1970 + ) + } + return entries.isEmpty ? nil : entries + } + + func panelScopedAgentLifecycleSnapshots(panelId: UUID) -> [String: String]? { + let lifecycles = (agentLifecycleStatesByPanelId[panelId] ?? [:]) + .filter { Self.structuredAgentHookStatusKeys.contains($0.key) } + .mapValues { $0.rawValue } + return lifecycles.isEmpty ? nil : lifecycles + } + + /// Seeds the restored pane's panel-scoped agent status from its session + /// snapshot. A captured `.running` lifecycle is demoted to `.unknown`: the + /// resumed agent sits at its prompt until the user acts, so restoring + /// "Running" would be a lie that sticks until the next hook fires. + func restorePanelScopedAgentStatus(terminal: SessionTerminalPanelSnapshot?, panelId: UUID) { + guard let terminal else { return } + for snapshot in terminal.agentStatusEntries ?? [] { + guard Self.structuredAgentHookStatusKeys.contains(snapshot.key) else { continue } + recordPanelStatusEntry( + SidebarStatusEntry( + key: snapshot.key, + value: snapshot.value, + icon: snapshot.icon, + color: snapshot.color, + timestamp: Date(timeIntervalSince1970: snapshot.timestamp) + ), + panelId: panelId + ) + } + for (key, rawValue) in terminal.agentLifecyclesByStatusKey ?? [:] { + guard Self.structuredAgentHookStatusKeys.contains(key), + let captured = AgentHibernationLifecycleState(rawValue: rawValue) else { continue } + let lifecycle: AgentHibernationLifecycleState = captured == .running ? .unknown : captured + setAgentLifecycle(key: key, panelId: panelId, lifecycle: lifecycle) + } + } } diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index f7ca2063e724..00c6cd5b132f 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -557,7 +557,9 @@ extension Workspace { textBoxDraft: terminalPanel.sessionTextBoxDraftSnapshot(), isRemoteTerminal: activeRemoteTerminalSurfaceIds.contains(panelId), remotePTYSessionID: remotePTYSessionIDForSnapshot(panelId: panelId), - wasAgentRunning: agentWasRunning + wasAgentRunning: agentWasRunning, + agentStatusEntries: panelScopedAgentStatusSnapshots(panelId: panelId), + agentLifecyclesByStatusKey: panelScopedAgentLifecycleSnapshots(panelId: panelId) ) browserSnapshot = nil markdownSnapshot = nil @@ -1496,6 +1498,7 @@ extension Workspace { } else { surfaceResumeBindingsByPanelId.removeValue(forKey: terminalPanel.id) } + restorePanelScopedAgentStatus(terminal: snapshot.terminal, panelId: terminalPanel.id) // A terminal whose startup command cds itself (agent resume, tmux // attach, agent-hook) is spawned without a working directory, so its // shell starts in the default directory and shell integration reports diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 25df21a49999..d915a06380d2 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -421,4 +421,38 @@ struct PerAgentSidebarStatusRowTests { #expect(runningOnly.accentColorHex == "#4C8DFF") #expect(SidebarAgentStatusRowsSummary(rows: [row(lifecycle: .idle)]).accentColorHex == nil) } + + @Test + func testRestoredPanelSnapshotSeedsRowWithPaneBinding() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + + let terminal = SessionTerminalPanelSnapshot( + agentStatusEntries: [ + SessionStatusEntrySnapshot( + key: "claude_code", + value: "Claude is waiting for your input", + icon: "exclamationmark.bubble.fill", + color: "#FF9F0A", + timestamp: 1_000 + ) + ], + agentLifecyclesByStatusKey: ["claude_code": "running"] + ) + workspace.restorePanelScopedAgentStatus(terminal: terminal, panelId: panelId) + + let row = try #require(workspace.sidebarAgentStatusRows().first) + // The restored row is bound to the live pane, so clicking it can + // focus that pane immediately after relaunch. + #expect(row.panelId == panelId) + #expect(row.value == "Claude is waiting for your input") + // Captured "running" must not survive restore: the resumed agent sits + // at its prompt, so a restored Running pill would stick until the + // next hook fires. + #expect(row.lifecycle == .unknown) + + // The seeded state round-trips back out into the next snapshot. + #expect(workspace.panelScopedAgentStatusSnapshots(panelId: panelId)?.first?.key == "claude_code") + #expect(workspace.panelScopedAgentLifecycleSnapshots(panelId: panelId)?["claude_code"] == "unknown") + } } From 5d963a47b6ce8c3cdfcb316a09ffe5c19576f11a Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 21:33:05 -0700 Subject: [PATCH 16/46] sidebar: seed restored per-agent rows after the ephemeral-state clears restoreSessionSnapshot wipes statusEntries/agent PIDs/lifecycles AFTER restorePane, so seeding inside createPanel was destroyed before the sidebar ever saw it. Seed from the panel snapshots after the clears, keyed through oldToNewPanelIds so collision-remapped panes stay bound. --- Sources/Workspace.swift | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 00c6cd5b132f..1d27066efa6a 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -230,6 +230,15 @@ extension Workspace { clearAllAgentPIDs(refreshPorts: false) clearAllAgentLifecycleStates() agentListeningPorts.removeAll() + // Panel-scoped agent status is restorable UI state, unlike PIDs: the + // rows re-bind to the restored panes so the sidebar stays informative + // and click-navigable across relaunch. Seed AFTER the ephemeral-state + // clears above, which would otherwise wipe the seeds (restorePane runs + // earlier). + for (oldPanelId, newPanelId) in oldToNewPanelIds { + guard let terminal = panelSnapshotsById[oldPanelId]?.terminal else { continue } + restorePanelScopedAgentStatus(terminal: terminal, panelId: newPanelId) + } logEntries = snapshot.logEntries.map { entry in SidebarLogEntry( message: entry.message, @@ -1498,7 +1507,6 @@ extension Workspace { } else { surfaceResumeBindingsByPanelId.removeValue(forKey: terminalPanel.id) } - restorePanelScopedAgentStatus(terminal: snapshot.terminal, panelId: terminalPanel.id) // A terminal whose startup command cds itself (agent resume, tmux // attach, agent-hook) is spawned without a working directory, so its // shell starts in the default directory and shell integration reports From 01ce4bbe41d07b930be8d488575a64d65fadfdad Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 22:03:47 -0700 Subject: [PATCH 17/46] sidebar: guard repair, restore-ordering regression test, localized row templates workflow-guard-tests hard-caps any net growth to files over 900 lines. Pay the growth back where it landed: - Workspace.swift: the ephemeral-clears + panel-scoped seed block moves into Workspace+SidebarAgentStatus.resetAgentRuntimeStateForSessionRestore, which also puts the seed-after-clears ordering invariant behind one owner (net -1 vs merge base). - SessionPersistence.swift: SessionTerminalPanelSnapshot's hand-written memberwise init is replaced by the synthesized one (every property now defaults to nil), identical parameter list and call sites (net -16). - Refresh only this PR's two budget entries; unrelated drift untouched. Add the end-to-end regression test for the restore ordering bug that shipped in 801912500e: restoreSessionSnapshot clears statusEntries/agent PIDs/lifecycles AFTER restorePane, so seeding during panel creation was wiped before the sidebar ever saw it. The test snapshots a workspace with a panel-scoped row, restores it into a fresh workspace, and requires the row to survive with the remapped pane binding. Also localize the lifecycle fallback and tooltip templates in SidebarAgentStatusRowViews (review finding: bare "\(name): \(lifecycle)" interpolation), with en/ja entries in Localizable.xcstrings. --- .github/swift-file-length-budget.tsv | 4 +- Resources/Localizable.xcstrings | 34 ++++++++++++ Sources/SessionPersistence.swift | 55 +++++-------------- Sources/SidebarAgentStatusRowViews.swift | 10 +++- Sources/Workspace+SidebarAgentStatus.swift | 22 ++++++++ Sources/Workspace.swift | 20 ++----- cmuxTests/PerAgentSidebarStatusRowTests.swift | 26 +++++++++ 7 files changed, 111 insertions(+), 60 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 6a0835822f88..781f1190e9d5 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -5,7 +5,7 @@ 18229 Sources/AppDelegate.swift 16443 Sources/ContentView.swift 15163 Sources/TerminalController.swift -13232 Sources/Workspace.swift +13231 Sources/Workspace.swift 12511 Sources/GhosttyTerminalView.swift 12348 cmuxTests/AppDelegateShortcutRoutingTests.swift 11669 Sources/Panels/BrowserPanel.swift @@ -46,7 +46,7 @@ 2225 Sources/RestorableAgentSession.swift 2133 cmuxTests/ShortcutAndCommandPaletteTests.swift 2126 cmuxTests/CmuxConfigTests.swift -2079 Sources/SessionPersistence.swift +2003 Sources/SessionPersistence.swift 2011 Sources/KeyboardShortcutSettingsFileStore.swift 1900 cmuxTests/NotificationAndMenuBarTests.swift 1866 Sources/Panels/BrowserWebAuthnSupport.swift diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index c92e0e1c54b8..a08991c5d0bf 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -193764,6 +193764,23 @@ } } }, + "sidebar.agentStatus.nameWithLifecycle": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%1$@: %2$@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%1$@: %2$@" + } + } + } + }, "sidebar.agentStatus.needsInput": { "extractionState": "manual", "localizations": { @@ -193866,6 +193883,23 @@ } } }, + "sidebar.agentStatus.valueWithPaneLabel": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%1$@ (%2$@)" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%1$@ (%2$@)" + } + } + } + }, "sidebar.browserStack.closeGroup": { "extractionState": "manual", "localizations": { diff --git a/Sources/SessionPersistence.swift b/Sources/SessionPersistence.swift index 7ecb80d37954..54c300b24b95 100644 --- a/Sources/SessionPersistence.swift +++ b/Sources/SessionPersistence.swift @@ -1385,52 +1385,27 @@ enum SurfaceResumeBindingScriptStore { } } +/// The synthesized memberwise initializer (every property defaults to nil) +/// replaces the hand-written one; keep new properties `var ... = nil` so the +/// synthesized parameter list stays fully defaulted. struct SessionTerminalPanelSnapshot: Codable, Sendable { - var workingDirectory: String? - var scrollback: String? - var agent: SessionRestorableAgentSnapshot? - var tmuxStartCommand: String? - var hibernation: SessionAgentHibernationSnapshot? - var resumeBinding: SurfaceResumeBindingSnapshot? - var textBoxDraft: SessionTextBoxInputDraftSnapshot? - var isRemoteTerminal: Bool? - var remotePTYSessionID: String? + var workingDirectory: String? = nil + var scrollback: String? = nil + var agent: SessionRestorableAgentSnapshot? = nil + var tmuxStartCommand: String? = nil + var hibernation: SessionAgentHibernationSnapshot? = nil + var resumeBinding: SurfaceResumeBindingSnapshot? = nil + var textBoxDraft: SessionTextBoxInputDraftSnapshot? = nil + var isRemoteTerminal: Bool? = nil + var remotePTYSessionID: String? = nil /// Whether the agent process was actively running when this snapshot was captured. /// Nil means unknown (legacy snapshots); treated as true for backwards compatibility. - var wasAgentRunning: Bool? + var wasAgentRunning: Bool? = nil /// Panel-scoped structured agent status reports (one per status key), so /// per-agent sidebar rows keep their pane binding across restart. - var agentStatusEntries: [SessionStatusEntrySnapshot]? + var agentStatusEntries: [SessionStatusEntrySnapshot]? = nil /// Last known agent lifecycle raw value per structured status key. - var agentLifecyclesByStatusKey: [String: String]? - - init( - workingDirectory: String? = nil, - scrollback: String? = nil, - agent: SessionRestorableAgentSnapshot? = nil, - tmuxStartCommand: String? = nil, - hibernation: SessionAgentHibernationSnapshot? = nil, - resumeBinding: SurfaceResumeBindingSnapshot? = nil, - textBoxDraft: SessionTextBoxInputDraftSnapshot? = nil, - isRemoteTerminal: Bool? = nil, - remotePTYSessionID: String? = nil, - wasAgentRunning: Bool? = nil, - agentStatusEntries: [SessionStatusEntrySnapshot]? = nil, - agentLifecyclesByStatusKey: [String: String]? = nil - ) { - self.workingDirectory = workingDirectory - self.scrollback = scrollback - self.agent = agent - self.tmuxStartCommand = tmuxStartCommand - self.hibernation = hibernation - self.resumeBinding = resumeBinding - self.textBoxDraft = textBoxDraft - self.isRemoteTerminal = isRemoteTerminal - self.remotePTYSessionID = remotePTYSessionID - self.wasAgentRunning = wasAgentRunning - self.agentStatusEntries = agentStatusEntries - self.agentLifecyclesByStatusKey = agentLifecyclesByStatusKey - } + var agentLifecyclesByStatusKey: [String: String]? = nil } extension SessionTerminalPanelSnapshot: WorkspaceSessionRemoteRestoreTerminalSnapshot {} diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index c67e4f2910be..2afa2edabf62 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -180,14 +180,20 @@ private struct SidebarAgentStatusEntryRow: View { } let name = Self.agentDisplayName(statusKey: row.statusKey) if let lifecycleText { - return "\(name): \(lifecycleText)" + return String( + localized: "sidebar.agentStatus.nameWithLifecycle", + defaultValue: "\(name): \(lifecycleText)" + ) } return name } private var helpText: String { guard let paneLabel = row.paneLabel else { return displayText } - return "\(displayText) (\(paneLabel))" + return String( + localized: "sidebar.agentStatus.valueWithPaneLabel", + defaultValue: "\(displayText) (\(paneLabel))" + ) } private var lifecycleText: String? { diff --git a/Sources/Workspace+SidebarAgentStatus.swift b/Sources/Workspace+SidebarAgentStatus.swift index 959eb1e54f7d..8e1e98fd179e 100644 --- a/Sources/Workspace+SidebarAgentStatus.swift +++ b/Sources/Workspace+SidebarAgentStatus.swift @@ -248,6 +248,28 @@ extension Workspace { // MARK: - Session persistence + /// Runs the session-restore reset for agent runtime state: status entries + /// and agent PIDs are ephemeral state tied to running processes (e.g. + /// claude_code "Running"), so they never survive a restart. Panel-scoped + /// agent status is restorable UI state, unlike PIDs: the rows re-bind to + /// the restored panes so the sidebar stays informative and click-navigable + /// across relaunch. Seeding MUST run after the clears: restorePane runs + /// earlier in restoreSessionSnapshot, so seeding during panel creation is + /// wiped before the sidebar ever sees it (this bug shipped). + func resetAgentRuntimeStateForSessionRestore( + panelSnapshotsById: [UUID: SessionPanelSnapshot], + oldToNewPanelIds: [UUID: UUID] + ) { + statusEntries.removeAll() + clearAllAgentPIDs(refreshPorts: false) + clearAllAgentLifecycleStates() + agentListeningPorts.removeAll() + for (oldPanelId, newPanelId) in oldToNewPanelIds { + guard let terminal = panelSnapshotsById[oldPanelId]?.terminal else { continue } + restorePanelScopedAgentStatus(terminal: terminal, panelId: newPanelId) + } + } + /// Panel-scoped structured status reports for the session snapshot, so a /// restored pane keeps its own sidebar row (and stays click-navigable) /// instead of degrading to the ambiguous workspace-level slot. diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 1d27066efa6a..74b8537442c3 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -223,22 +223,10 @@ extension Workspace { isPinned = snapshot.isPinned groupId = snapshot.groupId - // Status entries and agent PIDs are ephemeral runtime state tied to running - // processes (e.g. claude_code "Running"). Don't restore them across app - // restarts because the processes that set them are gone. - statusEntries.removeAll() - clearAllAgentPIDs(refreshPorts: false) - clearAllAgentLifecycleStates() - agentListeningPorts.removeAll() - // Panel-scoped agent status is restorable UI state, unlike PIDs: the - // rows re-bind to the restored panes so the sidebar stays informative - // and click-navigable across relaunch. Seed AFTER the ephemeral-state - // clears above, which would otherwise wipe the seeds (restorePane runs - // earlier). - for (oldPanelId, newPanelId) in oldToNewPanelIds { - guard let terminal = panelSnapshotsById[oldPanelId]?.terminal else { continue } - restorePanelScopedAgentStatus(terminal: terminal, panelId: newPanelId) - } + resetAgentRuntimeStateForSessionRestore( + panelSnapshotsById: panelSnapshotsById, + oldToNewPanelIds: oldToNewPanelIds + ) logEntries = snapshot.logEntries.map { entry in SidebarLogEntry( message: entry.message, diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index d915a06380d2..9582a11b27d1 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -455,4 +455,30 @@ struct PerAgentSidebarStatusRowTests { #expect(workspace.panelScopedAgentStatusSnapshots(panelId: panelId)?.first?.key == "claude_code") #expect(workspace.panelScopedAgentLifecycleSnapshots(panelId: panelId)?["claude_code"] == "unknown") } + + @Test + func testRestoreSessionSnapshotSeedsPanelScopedRowsAfterEphemeralClears() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + workspace.recordPanelStatusEntry( + makeEntry(key: "codex", value: "Reviewing PR", timestamp: Date(timeIntervalSince1970: 500)), + panelId: panelId + ) + workspace.setAgentLifecycle(key: "codex", panelId: panelId, lifecycle: .needsInput) + let snapshot = workspace.sessionSnapshot(includeScrollback: false) + + let restored = Workspace() + let oldToNewPanelIds = restored.restoreSessionSnapshot(snapshot) + let restoredPanelId = try #require(oldToNewPanelIds[panelId]) + + // restoreSessionSnapshot clears statusEntries/agent PIDs/lifecycles + // AFTER restorePane, so the seed must run after those clears. Seeding + // during panel creation shipped exactly this bug: the clears wiped + // the rows before the sidebar ever saw them. + let row = try #require(restored.sidebarAgentStatusRows().first) + #expect(row.panelId == restoredPanelId) + #expect(row.statusKey == "codex") + #expect(row.value == "Reviewing PR") + #expect(row.lifecycle == .needsInput) + } } From ff0adc906f520a524411acb3ffd7bfed954bb237 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 22:04:14 -0700 Subject: [PATCH 18/46] Add failing regression test: panel-scoped status change must dirty the session autosave TabManager.sessionAutosaveFingerprint hashes workspace.statusEntries.count but nothing panel-scoped: a value-only change to a panel-scoped entry (or any lifecycle change) keeps the count identical, so the autosave timer skips the write and the persisted per-agent row text goes stale until an unrelated change happens to land. Red before the fix, by design. --- cmuxTests/PerAgentSidebarStatusRowTests.swift | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 9582a11b27d1..8b89e9eea6b0 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -481,4 +481,30 @@ struct PerAgentSidebarStatusRowTests { #expect(row.value == "Reviewing PR") #expect(row.lifecycle == .needsInput) } + + @Test + func testPanelScopedStatusValueChangeDirtiesAutosaveFingerprint() throws { + let manager = TabManager() + let workspace = try #require(manager.selectedWorkspace) + let panelId = try #require(workspace.focusedPanelId) + + workspace.recordPanelStatusEntry( + makeEntry(key: "claude_code", value: "Running", timestamp: Date(timeIntervalSince1970: 100)), + panelId: panelId + ) + let runningFingerprint = manager.sessionAutosaveFingerprint() + + // Value-only change: the entry count is unchanged, so a count-based + // fingerprint never goes dirty and the autosave keeps persisting the + // stale row text until an unrelated change happens to land. + workspace.recordPanelStatusEntry( + makeEntry(key: "claude_code", value: "Waiting for input", timestamp: Date(timeIntervalSince1970: 200)), + panelId: panelId + ) + #expect(manager.sessionAutosaveFingerprint() != runningFingerprint) + + let beforeLifecycleChange = manager.sessionAutosaveFingerprint() + workspace.setAgentLifecycle(key: "claude_code", panelId: panelId, lifecycle: .needsInput) + #expect(manager.sessionAutosaveFingerprint() != beforeLifecycleChange) + } } From e4d3b1d2058e4b768e35b479a645801dc3974075 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 22:04:48 -0700 Subject: [PATCH 19/46] Hash panel-scoped agent status into the session autosave fingerprint Workspace.hashPanelScopedAgentStatus feeds each panel-scoped entry's key, value, icon, and color plus the whole lifecycle map into the fingerprint, so a value-only or lifecycle-only change (same entry count) dirties the autosave and the persisted per-agent rows stay current. Timestamps are excluded: identical repeated reports are dropped before storage, so content is the real change signal and heartbeats cannot churn the autosave. TabManager.swift stays at net-zero lines for the length guard by dropping the redundant hasher.combine(panelIds.count) (workspace.panels.count is already combined a few lines above and panelIds is panels.keys sorted). --- Sources/TabManager.swift | 2 +- Sources/Workspace+SidebarAgentStatus.swift | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index db62fc10fb32..ed89d3196626 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -5577,6 +5577,7 @@ extension TabManager { hasher.combine(workspace.isPinned) hasher.combine(workspace.panels.count) hasher.combine(workspace.statusEntries.count) + workspace.hashPanelScopedAgentStatus(into: &hasher) hasher.combine(workspace.metadataBlocks.count) hasher.combine(workspace.logEntries.count) hasher.combine(workspace.panelDirectories.count) @@ -5591,7 +5592,6 @@ extension TabManager { into: &hasher ) let panelIds = workspace.panels.keys.sorted { $0.uuidString < $1.uuidString } - hasher.combine(panelIds.count) for panelId in panelIds { hasher.combine(panelId) hasher.combine(workspace.panelDirectories[panelId] ?? "") diff --git a/Sources/Workspace+SidebarAgentStatus.swift b/Sources/Workspace+SidebarAgentStatus.swift index 8e1e98fd179e..093f325070f9 100644 --- a/Sources/Workspace+SidebarAgentStatus.swift +++ b/Sources/Workspace+SidebarAgentStatus.swift @@ -270,6 +270,25 @@ extension Workspace { } } + /// Feeds the panel-scoped agent status content into the session autosave + /// fingerprint. Counts are not enough: a value-only change to a + /// panel-scoped entry (same entry count) must dirty the autosave, or the + /// persisted per-agent row text goes stale until an unrelated change + /// happens to land. Timestamps are excluded on purpose: identical repeated + /// reports are dropped before storage, so content is the real signal. + func hashPanelScopedAgentStatus(into hasher: inout Hasher) { + for (panelId, entries) in statusEntriesByPanelId.sorted(by: { $0.key.uuidString < $1.key.uuidString }) { + hasher.combine(panelId) + for (key, entry) in entries.sorted(by: { $0.key < $1.key }) { + hasher.combine(key) + hasher.combine(entry.value) + hasher.combine(entry.icon) + hasher.combine(entry.color) + } + } + hasher.combine(agentLifecycleStatesByPanelId) + } + /// Panel-scoped structured status reports for the session snapshot, so a /// restored pane keeps its own sidebar row (and stays click-navigable) /// instead of degrading to the ambiguous workspace-level slot. From 0d512d5ec46c71c154a0b750609d3c5ff2b6b483 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 22:08:00 -0700 Subject: [PATCH 20/46] guard: split per-agent persistence tests into their own suite The three new persistence tests pushed PerAgentSidebarStatusRowTests.swift to 510 lines, and workflow-guard-tests rejects newly tracked >=500-line files outright. Move the persistence-scoped suites (restored snapshot seeding, restore-after-clears ordering, autosave fingerprint) into PerAgentSidebarStatusPersistenceTests.swift (wired into cmuxTests), which also matches the row-vs-persistence concern split. --- cmux.xcodeproj/project.pbxproj | 4 + ...erAgentSidebarStatusPersistenceTests.swift | 115 ++++++++++++++++++ cmuxTests/PerAgentSidebarStatusRowTests.swift | 86 ------------- 3 files changed, 119 insertions(+), 86 deletions(-) create mode 100644 cmuxTests/PerAgentSidebarStatusPersistenceTests.swift diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index a26a347dd497..0a5981f707a5 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -854,6 +854,7 @@ 6313B6A0 /* PaneMemoryWarning.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6313B6A1 /* PaneMemoryWarning.swift */; }; E30760090000000000000002 /* PassthroughWindowOverlayContainerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E30760090000000000000001 /* PassthroughWindowOverlayContainerView.swift */; }; A5001425 /* PDFPreviewChromeDebugWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001424 /* PDFPreviewChromeDebugWindowController.swift */; }; + 2255A23ACD5B366E35B6ED0F /* PerAgentSidebarStatusPersistenceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EDCC62AF23B380D1227E261 /* PerAgentSidebarStatusPersistenceTests.swift */; }; DEC515B488104031B49F68F0 /* PerAgentSidebarStatusRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF3A0288F87945DC8889FE91 /* PerAgentSidebarStatusRowTests.swift */; }; D1F0A00400000000000000D1 /* PhoneForwardingMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1F0A00400000000000000D2 /* PhoneForwardingMode.swift */; }; D1F0A00100000000000000A1 /* PhonePushClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1F0A00100000000000000A2 /* PhonePushClient.swift */; }; @@ -2323,6 +2324,7 @@ 6313B6A1 /* PaneMemoryWarning.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PaneMemoryWarning.swift; sourceTree = ""; }; E30760090000000000000001 /* PassthroughWindowOverlayContainerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PassthroughWindowOverlayContainerView.swift; sourceTree = ""; }; A5001424 /* PDFPreviewChromeDebugWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/PDFPreviewChromeDebugWindowController.swift; sourceTree = ""; }; + 3EDCC62AF23B380D1227E261 /* PerAgentSidebarStatusPersistenceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerAgentSidebarStatusPersistenceTests.swift; sourceTree = ""; }; EF3A0288F87945DC8889FE91 /* PerAgentSidebarStatusRowTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerAgentSidebarStatusRowTests.swift; sourceTree = ""; }; D1F0A00400000000000000D2 /* PhoneForwardingMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PhoneForwardingMode.swift; sourceTree = ""; }; D1F0A00100000000000000A2 /* PhonePushClient.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PhonePushClient.swift; sourceTree = ""; }; @@ -4168,6 +4170,7 @@ A9E040000000000000000001 /* CodexAppServerSessionTests.swift */, D72260010000000000000002 /* AgentHibernationPortalVisibilityTests.swift */, D36A00020000000000000002 /* AgentHibernationTests.swift */, + 3EDCC62AF23B380D1227E261 /* PerAgentSidebarStatusPersistenceTests.swift */, EF3A0288F87945DC8889FE91 /* PerAgentSidebarStatusRowTests.swift */, D36A00050000000000000002 /* RendererRealizationPlannerTests.swift */, C58410010000000000000002 /* RenderableSystemSymbolTests.swift */, @@ -6160,6 +6163,7 @@ A5E01203A1B2C3D4E5F60718 /* OpenCodeHookRegressionTests.swift in Sources */, C44550000000000000000001 /* PanelOwnedNativeViewSessionTests.swift in Sources */, 6313FACE0000000000000000 /* PaneMemoryGuardrailTests.swift in Sources */, + 2255A23ACD5B366E35B6ED0F /* PerAgentSidebarStatusPersistenceTests.swift in Sources */, DEC515B488104031B49F68F0 /* PerAgentSidebarStatusRowTests.swift in Sources */, D1F0A00300000000000000C1 /* PhonePushPresenceGateTests.swift in Sources */, B3575000000000000000000A /* PiVaultAgentPersistenceTests.swift in Sources */, diff --git a/cmuxTests/PerAgentSidebarStatusPersistenceTests.swift b/cmuxTests/PerAgentSidebarStatusPersistenceTests.swift new file mode 100644 index 000000000000..63b1d57438fd --- /dev/null +++ b/cmuxTests/PerAgentSidebarStatusPersistenceTests.swift @@ -0,0 +1,115 @@ +import CmuxSidebar +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +/// Session persistence for per-pane agent status rows: panel-scoped entries +/// and lifecycles must survive relaunch bound to the restored pane, and any +/// panel-scoped change must dirty the session autosave fingerprint. +@MainActor +struct PerAgentSidebarStatusPersistenceTests { + private func makeEntry( + key: String, + value: String, + timestamp: Date = Date() + ) -> SidebarStatusEntry { + SidebarStatusEntry( + key: key, + value: value, + icon: "bolt.fill", + color: "#4C8DFF", + timestamp: timestamp + ) + } + + @Test + func testRestoredPanelSnapshotSeedsRowWithPaneBinding() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + + let terminal = SessionTerminalPanelSnapshot( + agentStatusEntries: [ + SessionStatusEntrySnapshot( + key: "claude_code", + value: "Claude is waiting for your input", + icon: "exclamationmark.bubble.fill", + color: "#FF9F0A", + timestamp: 1_000 + ) + ], + agentLifecyclesByStatusKey: ["claude_code": "running"] + ) + workspace.restorePanelScopedAgentStatus(terminal: terminal, panelId: panelId) + + let row = try #require(workspace.sidebarAgentStatusRows().first) + // The restored row is bound to the live pane, so clicking it can + // focus that pane immediately after relaunch. + #expect(row.panelId == panelId) + #expect(row.value == "Claude is waiting for your input") + // Captured "running" must not survive restore: the resumed agent sits + // at its prompt, so a restored Running pill would stick until the + // next hook fires. + #expect(row.lifecycle == .unknown) + + // The seeded state round-trips back out into the next snapshot. + #expect(workspace.panelScopedAgentStatusSnapshots(panelId: panelId)?.first?.key == "claude_code") + #expect(workspace.panelScopedAgentLifecycleSnapshots(panelId: panelId)?["claude_code"] == "unknown") + } + + @Test + func testRestoreSessionSnapshotSeedsPanelScopedRowsAfterEphemeralClears() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + workspace.recordPanelStatusEntry( + makeEntry(key: "codex", value: "Reviewing PR", timestamp: Date(timeIntervalSince1970: 500)), + panelId: panelId + ) + workspace.setAgentLifecycle(key: "codex", panelId: panelId, lifecycle: .needsInput) + let snapshot = workspace.sessionSnapshot(includeScrollback: false) + + let restored = Workspace() + let oldToNewPanelIds = restored.restoreSessionSnapshot(snapshot) + let restoredPanelId = try #require(oldToNewPanelIds[panelId]) + + // restoreSessionSnapshot clears statusEntries/agent PIDs/lifecycles + // AFTER restorePane, so the seed must run after those clears. Seeding + // during panel creation shipped exactly this bug: the clears wiped + // the rows before the sidebar ever saw them. + let row = try #require(restored.sidebarAgentStatusRows().first) + #expect(row.panelId == restoredPanelId) + #expect(row.statusKey == "codex") + #expect(row.value == "Reviewing PR") + #expect(row.lifecycle == .needsInput) + } + + @Test + func testPanelScopedStatusValueChangeDirtiesAutosaveFingerprint() throws { + let manager = TabManager() + let workspace = try #require(manager.selectedWorkspace) + let panelId = try #require(workspace.focusedPanelId) + + workspace.recordPanelStatusEntry( + makeEntry(key: "claude_code", value: "Running", timestamp: Date(timeIntervalSince1970: 100)), + panelId: panelId + ) + let runningFingerprint = manager.sessionAutosaveFingerprint() + + // Value-only change: the entry count is unchanged, so a count-based + // fingerprint never goes dirty and the autosave keeps persisting the + // stale row text until an unrelated change happens to land. + workspace.recordPanelStatusEntry( + makeEntry(key: "claude_code", value: "Waiting for input", timestamp: Date(timeIntervalSince1970: 200)), + panelId: panelId + ) + #expect(manager.sessionAutosaveFingerprint() != runningFingerprint) + + let beforeLifecycleChange = manager.sessionAutosaveFingerprint() + workspace.setAgentLifecycle(key: "claude_code", panelId: panelId, lifecycle: .needsInput) + #expect(manager.sessionAutosaveFingerprint() != beforeLifecycleChange) + } +} diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 8b89e9eea6b0..25df21a49999 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -421,90 +421,4 @@ struct PerAgentSidebarStatusRowTests { #expect(runningOnly.accentColorHex == "#4C8DFF") #expect(SidebarAgentStatusRowsSummary(rows: [row(lifecycle: .idle)]).accentColorHex == nil) } - - @Test - func testRestoredPanelSnapshotSeedsRowWithPaneBinding() throws { - let workspace = Workspace() - let panelId = try #require(workspace.focusedPanelId) - - let terminal = SessionTerminalPanelSnapshot( - agentStatusEntries: [ - SessionStatusEntrySnapshot( - key: "claude_code", - value: "Claude is waiting for your input", - icon: "exclamationmark.bubble.fill", - color: "#FF9F0A", - timestamp: 1_000 - ) - ], - agentLifecyclesByStatusKey: ["claude_code": "running"] - ) - workspace.restorePanelScopedAgentStatus(terminal: terminal, panelId: panelId) - - let row = try #require(workspace.sidebarAgentStatusRows().first) - // The restored row is bound to the live pane, so clicking it can - // focus that pane immediately after relaunch. - #expect(row.panelId == panelId) - #expect(row.value == "Claude is waiting for your input") - // Captured "running" must not survive restore: the resumed agent sits - // at its prompt, so a restored Running pill would stick until the - // next hook fires. - #expect(row.lifecycle == .unknown) - - // The seeded state round-trips back out into the next snapshot. - #expect(workspace.panelScopedAgentStatusSnapshots(panelId: panelId)?.first?.key == "claude_code") - #expect(workspace.panelScopedAgentLifecycleSnapshots(panelId: panelId)?["claude_code"] == "unknown") - } - - @Test - func testRestoreSessionSnapshotSeedsPanelScopedRowsAfterEphemeralClears() throws { - let workspace = Workspace() - let panelId = try #require(workspace.focusedPanelId) - workspace.recordPanelStatusEntry( - makeEntry(key: "codex", value: "Reviewing PR", timestamp: Date(timeIntervalSince1970: 500)), - panelId: panelId - ) - workspace.setAgentLifecycle(key: "codex", panelId: panelId, lifecycle: .needsInput) - let snapshot = workspace.sessionSnapshot(includeScrollback: false) - - let restored = Workspace() - let oldToNewPanelIds = restored.restoreSessionSnapshot(snapshot) - let restoredPanelId = try #require(oldToNewPanelIds[panelId]) - - // restoreSessionSnapshot clears statusEntries/agent PIDs/lifecycles - // AFTER restorePane, so the seed must run after those clears. Seeding - // during panel creation shipped exactly this bug: the clears wiped - // the rows before the sidebar ever saw them. - let row = try #require(restored.sidebarAgentStatusRows().first) - #expect(row.panelId == restoredPanelId) - #expect(row.statusKey == "codex") - #expect(row.value == "Reviewing PR") - #expect(row.lifecycle == .needsInput) - } - - @Test - func testPanelScopedStatusValueChangeDirtiesAutosaveFingerprint() throws { - let manager = TabManager() - let workspace = try #require(manager.selectedWorkspace) - let panelId = try #require(workspace.focusedPanelId) - - workspace.recordPanelStatusEntry( - makeEntry(key: "claude_code", value: "Running", timestamp: Date(timeIntervalSince1970: 100)), - panelId: panelId - ) - let runningFingerprint = manager.sessionAutosaveFingerprint() - - // Value-only change: the entry count is unchanged, so a count-based - // fingerprint never goes dirty and the autosave keeps persisting the - // stale row text until an unrelated change happens to land. - workspace.recordPanelStatusEntry( - makeEntry(key: "claude_code", value: "Waiting for input", timestamp: Date(timeIntervalSince1970: 200)), - panelId: panelId - ) - #expect(manager.sessionAutosaveFingerprint() != runningFingerprint) - - let beforeLifecycleChange = manager.sessionAutosaveFingerprint() - workspace.setAgentLifecycle(key: "claude_code", panelId: panelId, lifecycle: .needsInput) - #expect(manager.sessionAutosaveFingerprint() != beforeLifecycleChange) - } } From 4a017c6f55e015dfeabaeb4f7cb2bd6f2b9fa7bb Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 22:24:07 -0700 Subject: [PATCH 21/46] Extend restore regression test: row behavior fields must survive relaunch Panel-scoped rows carry set_status --url/--priority/--format=markdown and the row renderer uses them live, so the round-trip test now pins them. Red before the fix: the snapshot drops all three, restoring rows as plain/unclickable/default-sorted. --- ...erAgentSidebarStatusPersistenceTests.swift | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/cmuxTests/PerAgentSidebarStatusPersistenceTests.swift b/cmuxTests/PerAgentSidebarStatusPersistenceTests.swift index 63b1d57438fd..0d2d504535ec 100644 --- a/cmuxTests/PerAgentSidebarStatusPersistenceTests.swift +++ b/cmuxTests/PerAgentSidebarStatusPersistenceTests.swift @@ -66,7 +66,16 @@ struct PerAgentSidebarStatusPersistenceTests { let workspace = Workspace() let panelId = try #require(workspace.focusedPanelId) workspace.recordPanelStatusEntry( - makeEntry(key: "codex", value: "Reviewing PR", timestamp: Date(timeIntervalSince1970: 500)), + SidebarStatusEntry( + key: "codex", + value: "**Reviewing** PR", + icon: "bolt.fill", + color: "#4C8DFF", + url: URL(string: "https://github.com/manaflow-ai/cmux/pull/7559"), + priority: 7, + format: .markdown, + timestamp: Date(timeIntervalSince1970: 500) + ), panelId: panelId ) workspace.setAgentLifecycle(key: "codex", panelId: panelId, lifecycle: .needsInput) @@ -83,8 +92,14 @@ struct PerAgentSidebarStatusPersistenceTests { let row = try #require(restored.sidebarAgentStatusRows().first) #expect(row.panelId == restoredPanelId) #expect(row.statusKey == "codex") - #expect(row.value == "Reviewing PR") + #expect(row.value == "**Reviewing** PR") #expect(row.lifecycle == .needsInput) + // Behavior fields survive the round-trip: a markdown/clickable/ + // high-priority row must not degrade to plain/unclickable/default + // sort order after relaunch. + #expect(row.url == URL(string: "https://github.com/manaflow-ai/cmux/pull/7559")) + #expect(row.priority == 7) + #expect(row.format == .markdown) } @Test From 1ea08d8e6e9ba5a5ea99cc847e173c5c3eb2d670 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 22:24:07 -0700 Subject: [PATCH 22/46] Persist and hash the full panel-scoped status entry Structured review (Codex P2): panelScopedAgentStatusSnapshots wrote only key/value/icon/color/timestamp, so restore rebuilt entries with url: nil, priority: 0, format: .plain, silently degrading markdown/clickable/ high-priority rows after relaunch; hashPanelScopedAgentStatus had the same blind spot, so changes to those fields never dirtied the autosave. SessionStatusEntrySnapshot gains optional url/priority/format (nil in legacy snapshots, decoded as nil, so old session files stay compatible); capture writes them, restore parses them back (unknown format falls back to .plain), and the autosave fingerprint hashes them. --- .github/swift-file-length-budget.tsv | 2 +- Sources/SessionPersistence.swift | 6 ++++++ Sources/Workspace+SidebarAgentStatus.swift | 11 ++++++++++- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 781f1190e9d5..d62c90234bae 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -46,7 +46,7 @@ 2225 Sources/RestorableAgentSession.swift 2133 cmuxTests/ShortcutAndCommandPaletteTests.swift 2126 cmuxTests/CmuxConfigTests.swift -2003 Sources/SessionPersistence.swift +2009 Sources/SessionPersistence.swift 2011 Sources/KeyboardShortcutSettingsFileStore.swift 1900 cmuxTests/NotificationAndMenuBarTests.swift 1866 Sources/Panels/BrowserWebAuthnSupport.swift diff --git a/Sources/SessionPersistence.swift b/Sources/SessionPersistence.swift index 54c300b24b95..8bc90951862f 100644 --- a/Sources/SessionPersistence.swift +++ b/Sources/SessionPersistence.swift @@ -240,6 +240,12 @@ struct SessionStatusEntrySnapshot: Codable, Sendable { var icon: String? var color: String? var timestamp: TimeInterval + /// Row behavior fields (click-to-open URL, sort priority, markdown + /// rendering). Nil in legacy snapshots; panel-scoped restores must keep + /// them or a markdown/clickable/high-priority row degrades on relaunch. + var url: String? = nil + var priority: Int? = nil + var format: String? = nil } struct SessionLogEntrySnapshot: Codable, Sendable { diff --git a/Sources/Workspace+SidebarAgentStatus.swift b/Sources/Workspace+SidebarAgentStatus.swift index 093f325070f9..ce227c91a4cb 100644 --- a/Sources/Workspace+SidebarAgentStatus.swift +++ b/Sources/Workspace+SidebarAgentStatus.swift @@ -284,6 +284,9 @@ extension Workspace { hasher.combine(entry.value) hasher.combine(entry.icon) hasher.combine(entry.color) + hasher.combine(entry.url) + hasher.combine(entry.priority) + hasher.combine(entry.format.rawValue) } } hasher.combine(agentLifecycleStatesByPanelId) @@ -302,7 +305,10 @@ extension Workspace { value: $0.value, icon: $0.icon, color: $0.color, - timestamp: $0.timestamp.timeIntervalSince1970 + timestamp: $0.timestamp.timeIntervalSince1970, + url: $0.url?.absoluteString, + priority: $0.priority, + format: $0.format.rawValue ) } return entries.isEmpty ? nil : entries @@ -329,6 +335,9 @@ extension Workspace { value: snapshot.value, icon: snapshot.icon, color: snapshot.color, + url: snapshot.url.flatMap(URL.init(string:)), + priority: snapshot.priority ?? 0, + format: snapshot.format.flatMap(SidebarMetadataFormat.init(rawValue:)) ?? .plain, timestamp: Date(timeIntervalSince1970: snapshot.timestamp) ), panelId: panelId From 369adc9512f5101ad5e7aa56510716dd16ad1c8d Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 7 Jul 2026 22:27:27 -0700 Subject: [PATCH 23/46] sidebar: agent rows move below the workspace card as independent click targets The card's whole-row tap gesture selects the workspace, so rows embedded in the card could not be clicked reliably. Each agent row is now its own hover-highlighted button in a section under the card (indented, outside the card background and gestures), always rendered with plain sidebar colors instead of the card's inverted active foreground. --- Sources/ContentView.swift | 36 ++++++++++++---------- Sources/SidebarAgentStatusRowViews.swift | 38 +++++++++++++----------- 2 files changed, 42 insertions(+), 32 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index dab51f5f29b8..82ce88a89cf7 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -13801,20 +13801,6 @@ struct TabItemView: View, Equatable { if detailVisibility.showsMetadata { let metadataEntries = workspaceSnapshot.metadataEntries let metadataBlocks = workspaceSnapshot.metadataBlocks - if !workspaceSnapshot.agentStatusRows.isEmpty { - SidebarAgentStatusRows( - rows: workspaceSnapshot.agentStatusRows, - isActive: usesInvertedActiveForeground, - activeForegroundColor: activeSecondaryColor(0.95), - fontScale: fontScale, - onFocus: { updateSelection() }, - onFocusPanel: { panelId in - updateSelection() - tab.focusPanel(panelId) - } - ) - .transition(.opacity) - } if !metadataEntries.isEmpty { SidebarMetadataRows( entries: metadataEntries, @@ -14198,7 +14184,27 @@ struct TabItemView: View, Equatable { } } let _ = SidebarProfilingSignposts.end(signpost) - rowView + // Agent rows live BELOW the workspace card, not inside it: the card's + // whole-row tap gesture selects the workspace, so embedded rows could + // not be clicked independently. Out here each agent is its own + // full-width click target. + VStack(alignment: .leading, spacing: 2) { + rowView + if detailVisibility.showsMetadata, !workspaceSnapshot.agentStatusRows.isEmpty { + SidebarAgentStatusRows( + rows: workspaceSnapshot.agentStatusRows, + fontScale: fontScale, + onFocus: { updateSelection() }, + onFocusPanel: { panelId in + updateSelection() + tab.focusPanel(panelId) + } + ) + .padding(.leading, 14) + .padding(.trailing, 6) + .transition(.opacity) + } + } } private func beginInlineRename() { updateSelection() diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index 2afa2edabf62..689cc3773c21 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -10,8 +10,6 @@ import SwiftUI /// sidebar list snapshot-boundary rule. struct SidebarAgentStatusRows: View { let rows: [SidebarAgentStatusRow] - let isActive: Bool - let activeForegroundColor: Color let fontScale: CGFloat let onFocus: () -> Void let onFocusPanel: (UUID) -> Void @@ -35,8 +33,6 @@ struct SidebarAgentStatusRows: View { ForEach(rows) { row in SidebarAgentStatusEntryRow( row: row, - isActive: isActive, - activeForegroundColor: activeForegroundColor, fontScale: fontScale, onFocusPanel: onFocusPanel ) @@ -58,7 +54,7 @@ struct SidebarAgentStatusRows: View { weight: .semibold ) .foregroundColor(headerSecondaryColor) - if isCollapsed, let accent = summary.accentColorHex, let color = Color(hex: accent), !isActive { + if isCollapsed, let accent = summary.accentColorHex, let color = Color(hex: accent) { Circle() .fill(color) .frame(width: 5 * fontScale, height: 5 * fontScale) @@ -78,21 +74,21 @@ struct SidebarAgentStatusRows: View { } private var headerForegroundColor: Color { - isActive ? activeForegroundColor : .secondary + .secondary } private var headerSecondaryColor: Color { - isActive ? activeForegroundColor.opacity(0.65) : .secondary.opacity(0.8) + .secondary.opacity(0.8) } } private struct SidebarAgentStatusEntryRow: View { let row: SidebarAgentStatusRow - let isActive: Bool - let activeForegroundColor: Color let fontScale: CGFloat let onFocusPanel: (UUID) -> Void + @State private var isHovering = false + var body: some View { Group { if let url = row.url { @@ -105,12 +101,20 @@ private struct SidebarAgentStatusEntryRow: View { .buttonStyle(.plain) .safeHelp(url.absoluteString) } else { - rowContent(underlined: false) - .contentShape(Rectangle()) - .onTapGesture { onFocusPanel(row.panelId) } - .safeHelp(helpText) + Button { + onFocusPanel(row.panelId) + } label: { + rowContent(underlined: false) + } + .buttonStyle(.plain) + .safeHelp(helpText) } } + .background( + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(Color.primary.opacity(isHovering ? 0.07 : 0)) + ) + .onHover { isHovering = $0 } } @ViewBuilder @@ -135,14 +139,17 @@ private struct SidebarAgentStatusEntryRow: View { .truncationMode(.tail) if let paneLabel = row.paneLabel { Text(paneLabel) - .foregroundColor(isActive ? activeForegroundColor.opacity(0.6) : .secondary.opacity(0.8)) + .foregroundColor(.secondary.opacity(0.8)) .lineLimit(1) .truncationMode(.middle) } Spacer(minLength: 0) } .cmuxFont(size: 10 * fontScale) + .padding(.vertical, 3) + .padding(.horizontal, 6) .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) } /// Mirrors `SidebarMetadataEntryRow.metadataText`: a markdown-formatted @@ -272,9 +279,6 @@ private struct SidebarAgentStatusEntryRow: View { } private var foregroundColor: Color { - if isActive { - return activeForegroundColor - } if let raw = effectiveColorHex, let explicit = Color(hex: raw) { return explicit } From 3c2add97b7e5f8d43051de8f1c6d9265b025bea0 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 00:15:11 -0700 Subject: [PATCH 24/46] sidebar: displaced bare-key panes keep their rows; name-first labels; 7-variant debug lab MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Bare shared PID keys (claude-style hooks) no longer erase a sibling pane's presence: displacement re-keys the previous owner's runtime to a synthesized panel-scoped key (pid + identity move with it, liveness sweep and exit hooks reap it), so two claudes always mean two rows. - Row labels are name-first: pane rename wins, then the live surface title (agents set it to the session name), then the directory label; status text rides second. - Debug > Agent Rows Style… opens a floating lab with seven live presentation variants (below-card accordion/flat/tree/chips, in-card rows/compact, global bottom Agents section), persisted in defaults. --- Resources/Localizable.xcstrings | 306 +++++++++++ Sources/ContentView.swift | 36 +- Sources/SidebarAgentRowsVariantLab.swift | 196 +++++++ Sources/SidebarAgentStatusRowViews.swift | 518 +++++++++++------- Sources/Workspace+PanelLifecycle.swift | 48 +- Sources/Workspace+SidebarAgentStatus.swift | 11 +- Sources/cmuxApp.swift | 4 + cmux.xcodeproj/project.pbxproj | 4 + cmuxTests/PerAgentSidebarStatusRowTests.swift | 32 ++ 9 files changed, 956 insertions(+), 199 deletions(-) create mode 100644 Sources/SidebarAgentRowsVariantLab.swift diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index a08991c5d0bf..3322eeb7aba9 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -69520,6 +69520,295 @@ } } }, + "debug.agentRows.variant.belowAccordion": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Below card · accordion" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "カード下・アコーディオン" + } + } + } + }, + "debug.agentRows.variant.belowAccordion.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Summary header folds the rows; each row is its own button." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "サマリーヘッダーで行を折りたたみ。各行は独立したボタン。" + } + } + } + }, + "debug.agentRows.variant.belowChips": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Below card · chips" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "カード下・チップ" + } + } + } + }, + "debug.agentRows.variant.belowChips.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Wrapping icon chips, one per agent." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "エージェントごとに折り返すアイコンチップ。" + } + } + } + }, + "debug.agentRows.variant.belowFlat": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Below card · flat rows" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "カード下・フラット行" + } + } + } + }, + "debug.agentRows.variant.belowFlat.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Always-expanded rows, no header." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "常に展開された行。ヘッダーなし。" + } + } + } + }, + "debug.agentRows.variant.belowTree": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Below card · tree guide" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "カード下・ツリーガイド" + } + } + } + }, + "debug.agentRows.variant.belowTree.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Rows hang off a tree guide line under the workspace." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ワークスペース下のツリーガイド線に行をぶら下げる。" + } + } + } + }, + "debug.agentRows.variant.globalSection": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Global Agents section (sidebar bottom)" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "グローバルなエージェント欄(サイドバー下部)" + } + } + } + }, + "debug.agentRows.variant.globalSection.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No per-workspace rows; one Agents list at the sidebar bottom, grouped by workspace." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ワークスペースごとの行はなし。サイドバー下部にワークスペース別のエージェント一覧。" + } + } + } + }, + "debug.agentRows.variant.inCardCompact": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "In card · compact line" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "カード内・コンパクト行" + } + } + } + }, + "debug.agentRows.variant.inCardCompact.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "One dense line of brand icons and state dots in the card." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "カード内にアイコンと状態ドットを1行で凝縮。" + } + } + } + }, + "debug.agentRows.variant.inCardRows": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "In card · rows" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "カード内・行" + } + } + } + }, + "debug.agentRows.variant.inCardRows.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Rows embedded inside the workspace card." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ワークスペースカード内に行を埋め込み。" + } + } + } + }, + "debug.agentRows.window.caption": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Switches the per-agent sidebar rows live. The choice persists across relaunch." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "エージェント行の表示をライブで切り替えます。選択は再起動後も保持されます。" + } + } + } + }, + "debug.agentRows.window.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Agent Rows Style" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "エージェント行スタイル" + } + } + } + }, + "debug.menu.agentRowsStyle": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Agent Rows Style…" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "エージェント行スタイル…" + } + } + } + }, "debug.aboutTitlebarDebug.resetAbout": { "extractionState": "manual", "localizations": { @@ -193747,6 +194036,23 @@ } } }, + "sidebar.agentStatus.globalSection.header": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Agents" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "エージェント" + } + } + } + }, "sidebar.agentStatus.idle": { "extractionState": "manual", "localizations": { diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 82ce88a89cf7..30fcffc53ae4 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -12627,16 +12627,29 @@ private struct SidebarFooter: View { var updateViewModel: UpdateStateModel @ObservedObject var fileExplorerState: FileExplorerState let onSendFeedback: () -> Void + @EnvironmentObject private var tabManager: TabManager var body: some View { + VStack(alignment: .leading, spacing: 0) { + // Renders only while the globalSection debug variant is selected. + SidebarGlobalAgentsSection( + tabManager: tabManager, + fontScale: 1, + onFocus: { workspaceId, panelId in + guard let tab = tabManager.tabs.first(where: { $0.id == workspaceId }) else { return } + tabManager.selectedTabId = workspaceId + tab.focusPanel(panelId) + } + ) #if DEBUG - SidebarDevFooter(updateViewModel: updateViewModel, fileExplorerState: fileExplorerState, onSendFeedback: onSendFeedback) + SidebarDevFooter(updateViewModel: updateViewModel, fileExplorerState: fileExplorerState, onSendFeedback: onSendFeedback) #else - SidebarFooterButtons(updateViewModel: updateViewModel, fileExplorerState: fileExplorerState, onSendFeedback: onSendFeedback) - .padding(.leading, 6) - .padding(.trailing, 10) - .padding(.bottom, 6) + SidebarFooterButtons(updateViewModel: updateViewModel, fileExplorerState: fileExplorerState, onSendFeedback: onSendFeedback) + .padding(.leading, 6) + .padding(.trailing, 10) + .padding(.bottom, 6) #endif + } } } @@ -13801,6 +13814,19 @@ struct TabItemView: View, Equatable { if detailVisibility.showsMetadata { let metadataEntries = workspaceSnapshot.metadataEntries let metadataBlocks = workspaceSnapshot.metadataBlocks + if !workspaceSnapshot.agentStatusRows.isEmpty { + // Renders only while an in-card debug variant is selected. + SidebarAgentStatusInCardRows( + rows: workspaceSnapshot.agentStatusRows, + isActive: usesInvertedActiveForeground, + activeForegroundColor: activeSecondaryColor(0.95), + fontScale: fontScale, + onFocusPanel: { panelId in + updateSelection() + tab.focusPanel(panelId) + } + ) + } if !metadataEntries.isEmpty { SidebarMetadataRows( entries: metadataEntries, diff --git a/Sources/SidebarAgentRowsVariantLab.swift b/Sources/SidebarAgentRowsVariantLab.swift new file mode 100644 index 000000000000..63ca53594133 --- /dev/null +++ b/Sources/SidebarAgentRowsVariantLab.swift @@ -0,0 +1,196 @@ +import AppKit +import SwiftUI + +/// Debug explorer for the per-agent sidebar row presentation: seven variants +/// switchable live from Debug > "Agent Rows Style…", persisted in +/// UserDefaults. This is a dogfood decision aid; once a winner is picked the +/// losing variants get deleted and the store collapses to a constant. +enum SidebarAgentRowsVariant: String, CaseIterable, Identifiable { + case belowAccordion + case belowFlat + case belowTree + case belowChips + case inCardRows + case inCardCompact + case globalSection + + static let userDefaultsKey = "sidebarAgentRowsVariantDebug" + + var id: String { rawValue } + + var isInCard: Bool { self == .inCardRows || self == .inCardCompact } + + var displayName: String { + switch self { + case .belowAccordion: + return String(localized: "debug.agentRows.variant.belowAccordion", defaultValue: "Below card · accordion") + case .belowFlat: + return String(localized: "debug.agentRows.variant.belowFlat", defaultValue: "Below card · flat rows") + case .belowTree: + return String(localized: "debug.agentRows.variant.belowTree", defaultValue: "Below card · tree guide") + case .belowChips: + return String(localized: "debug.agentRows.variant.belowChips", defaultValue: "Below card · chips") + case .inCardRows: + return String(localized: "debug.agentRows.variant.inCardRows", defaultValue: "In card · rows") + case .inCardCompact: + return String(localized: "debug.agentRows.variant.inCardCompact", defaultValue: "In card · compact line") + case .globalSection: + return String(localized: "debug.agentRows.variant.globalSection", defaultValue: "Global Agents section (sidebar bottom)") + } + } + + var detail: String { + switch self { + case .belowAccordion: + return String(localized: "debug.agentRows.variant.belowAccordion.detail", defaultValue: "Summary header folds the rows; each row is its own button.") + case .belowFlat: + return String(localized: "debug.agentRows.variant.belowFlat.detail", defaultValue: "Always-expanded rows, no header.") + case .belowTree: + return String(localized: "debug.agentRows.variant.belowTree.detail", defaultValue: "Rows hang off a tree guide line under the workspace.") + case .belowChips: + return String(localized: "debug.agentRows.variant.belowChips.detail", defaultValue: "Wrapping icon chips, one per agent.") + case .inCardRows: + return String(localized: "debug.agentRows.variant.inCardRows.detail", defaultValue: "Rows embedded inside the workspace card.") + case .inCardCompact: + return String(localized: "debug.agentRows.variant.inCardCompact.detail", defaultValue: "One dense line of brand icons and state dots in the card.") + case .globalSection: + return String(localized: "debug.agentRows.variant.globalSection.detail", defaultValue: "No per-workspace rows; one Agents list at the sidebar bottom, grouped by workspace.") + } + } +} + +/// Singleton the row containers observe. It only mutates when the user picks +/// a variant in the lab window, so the extra invalidation is bounded; this is +/// a deliberate, temporary exception to the sidebar snapshot-boundary rule +/// while the presentation is being chosen. +@MainActor +final class SidebarAgentRowsVariantStore: ObservableObject { + static let shared = SidebarAgentRowsVariantStore() + + @Published var variant: SidebarAgentRowsVariant { + didSet { + UserDefaults.standard.set(variant.rawValue, forKey: SidebarAgentRowsVariant.userDefaultsKey) + } + } + + private init() { + let raw = UserDefaults.standard.string(forKey: SidebarAgentRowsVariant.userDefaultsKey) + variant = raw.flatMap(SidebarAgentRowsVariant.init(rawValue:)) ?? .belowAccordion + } +} + +@MainActor +final class AgentRowsVariantLabWindowController: ReleasingWindowController { + static let shared = AgentRowsVariantLabWindowController() + + override func makeWindow() -> NSWindow { + let window = NSPanel( + contentRect: NSRect(x: 0, y: 0, width: 380, height: 430), + styleMask: [.titled, .closable, .utilityWindow], + backing: .buffered, + defer: false + ) + window.title = String(localized: "debug.agentRows.window.title", defaultValue: "Agent Rows Style") + window.titleVisibility = .visible + window.isMovableByWindowBackground = true + window.level = .floating + window.identifier = NSUserInterfaceItemIdentifier("cmux.agentRowsVariantLab") + window.center() + window.contentView = NSHostingView(rootView: AgentRowsVariantLabView()) + AppDelegate.shared?.applyWindowDecorations(to: window) + return window + } + + func show() { + showManagedWindow() + } +} + +private struct AgentRowsVariantLabView: View { + @ObservedObject private var store = SidebarAgentRowsVariantStore.shared + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + Text(String( + localized: "debug.agentRows.window.caption", + defaultValue: "Switches the per-agent sidebar rows live. The choice persists across relaunch." + )) + .font(.system(size: 11)) + .foregroundColor(.secondary) + + ForEach(SidebarAgentRowsVariant.allCases) { variant in + Button { + store.variant = variant + } label: { + HStack(alignment: .top, spacing: 8) { + Image(systemName: store.variant == variant ? "largecircle.fill.circle" : "circle") + .foregroundColor(store.variant == variant ? Color.accentColor : .secondary) + .padding(.top, 1) + VStack(alignment: .leading, spacing: 1) { + Text(variant.displayName) + .font(.system(size: 12, weight: .medium)) + Text(variant.detail) + .font(.system(size: 10.5)) + .foregroundColor(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + Spacer(minLength: 0) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + Spacer(minLength: 0) + } + .padding(14) + .frame(width: 380, alignment: .topLeading) + } +} + +/// The `globalSection` variant: one Agents list at the bottom of the sidebar, +/// grouped by workspace. Reads live workspace state directly; acceptable only +/// because it renders exclusively while this debug variant is selected. +struct SidebarGlobalAgentsSection: View { + let tabManager: TabManager + let fontScale: CGFloat + let onFocus: (UUID, UUID) -> Void + + @ObservedObject private var store = SidebarAgentRowsVariantStore.shared + + var body: some View { + if store.variant == .globalSection { + let groups = tabManager.tabs.compactMap { tab -> (workspaceId: UUID, title: String, rows: [SidebarAgentStatusRow])? in + let rows = tab.sidebarAgentStatusRows() + guard !rows.isEmpty else { return nil } + return (tab.id, tab.title, rows) + } + if !groups.isEmpty { + VStack(alignment: .leading, spacing: 3) { + Text(String(localized: "sidebar.agentStatus.globalSection.header", defaultValue: "Agents")) + .cmuxFont(size: 10 * fontScale, weight: .semibold) + .foregroundColor(.secondary) + .padding(.horizontal, 10) + .padding(.top, 8) + ForEach(groups, id: \.workspaceId) { group in + Text(group.title) + .cmuxFont(size: 9 * fontScale, weight: .medium) + .foregroundColor(.secondary.opacity(0.7)) + .lineLimit(1) + .padding(.horizontal, 10) + .padding(.top, 2) + ForEach(group.rows) { row in + SidebarAgentStatusEntryRowView( + row: row, + fontScale: fontScale, + layout: .nameFirst, + onFocusPanel: { panelId in onFocus(group.workspaceId, panelId) } + ) + .padding(.horizontal, 8) + } + } + } + .padding(.bottom, 6) + } + } + } +} diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index 689cc3773c21..82867f5333f1 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -3,37 +3,98 @@ import CmuxFoundation import CmuxSidebar import SwiftUI -/// Sidebar per-agent-pane status rows: one row per live agent pane plus its -/// private entry row. With more than one agent the block becomes an accordion: -/// a summary header ("2 agents · 1 needs input") that folds the rows. Rows -/// receive immutable value snapshots and closure action bundles only, per the -/// sidebar list snapshot-boundary rule. +/// Aggregate over the agent rows of one workspace, shown in the accordion +/// header (and standing in for the rows while collapsed). +struct SidebarAgentStatusRowsSummary: Equatable { + let agentCount: Int + let needsInputCount: Int + let runningCount: Int + + init(rows: [SidebarAgentStatusRow]) { + agentCount = rows.count + needsInputCount = rows.filter { $0.lifecycle == .needsInput }.count + runningCount = rows.filter { $0.lifecycle == .running }.count + } + + var text: String { + var parts: [String] = [] + if agentCount == 1 { + parts.append(String(localized: "sidebar.agentStatus.summary.oneAgent", defaultValue: "1 agent")) + } else { + parts.append(String( + format: String(localized: "sidebar.agentStatus.summary.agentCount", defaultValue: "%lld agents"), + agentCount + )) + } + if needsInputCount == 1 { + parts.append(String(localized: "sidebar.agentStatus.summary.oneNeedsInput", defaultValue: "1 needs input")) + } else if needsInputCount > 1 { + parts.append(String( + format: String(localized: "sidebar.agentStatus.summary.needsInputCount", defaultValue: "%lld need input"), + needsInputCount + )) + } + return parts.joined(separator: " · ") + } + + /// Worst-state accent: needs-input beats running beats idle. + var accentColorHex: String? { + if needsInputCount > 0 { return "#FF9F0A" } + if runningCount > 0 { return "#4C8DFF" } + return nil + } +} + +/// Below-card presentation of the per-agent rows. Owns the variant switch for +/// every below-card style; renders nothing when an in-card or global variant +/// is active. Rows receive immutable value snapshots and closure action +/// bundles only, per the sidebar list snapshot-boundary rule (the variant +/// store is a deliberate, temporary debug-lab exception; it changes only on +/// explicit user picks). struct SidebarAgentStatusRows: View { let rows: [SidebarAgentStatusRow] let fontScale: CGFloat let onFocus: () -> Void let onFocusPanel: (UUID) -> Void + @ObservedObject private var variantStore = SidebarAgentRowsVariantStore.shared @State private var isCollapsed = false var body: some View { - VStack(alignment: .leading, spacing: 2) { - if rows.count > 1 { - accordionHeader - if !isCollapsed { - rowList + switch variantStore.variant { + case .belowAccordion: + VStack(alignment: .leading, spacing: 2) { + if rows.count > 1 { + accordionHeader + if !isCollapsed { + rowList(layout: .nameFirst) + } + } else { + rowList(layout: .nameFirst) } - } else { - rowList } + case .belowFlat: + VStack(alignment: .leading, spacing: 2) { + rowList(layout: .nameFirst) + } + case .belowTree: + VStack(alignment: .leading, spacing: 0) { + rowList(layout: .tree) + } + case .belowChips: + SidebarAgentChipsFlow(rows: rows, fontScale: fontScale, onFocusPanel: onFocusPanel) + case .inCardRows, .inCardCompact, .globalSection: + EmptyView() } } - private var rowList: some View { + @ViewBuilder + private func rowList(layout: SidebarAgentRowLayout) -> some View { ForEach(rows) { row in - SidebarAgentStatusEntryRow( + SidebarAgentStatusEntryRowView( row: row, fontScale: fontScale, + layout: layout, onFocusPanel: onFocusPanel ) } @@ -53,14 +114,14 @@ struct SidebarAgentStatusRows: View { pointSize: 7 * fontScale, weight: .semibold ) - .foregroundColor(headerSecondaryColor) + .foregroundColor(.secondary.opacity(0.8)) if isCollapsed, let accent = summary.accentColorHex, let color = Color(hex: accent) { Circle() .fill(color) .frame(width: 5 * fontScale, height: 5 * fontScale) } Text(summary.text) - .foregroundColor(headerForegroundColor) + .foregroundColor(.secondary) .lineLimit(1) .truncationMode(.tail) Spacer(minLength: 0) @@ -72,138 +133,165 @@ struct SidebarAgentStatusRows: View { .buttonStyle(.plain) .safeHelp(summary.text) } - - private var headerForegroundColor: Color { - .secondary - } - - private var headerSecondaryColor: Color { - .secondary.opacity(0.8) - } } -private struct SidebarAgentStatusEntryRow: View { - let row: SidebarAgentStatusRow +/// In-card presentation (variants `inCardRows` / `inCardCompact`), mounted +/// inside the workspace card so it inherits the selection background. Renders +/// nothing for the below-card and global variants. +struct SidebarAgentStatusInCardRows: View { + let rows: [SidebarAgentStatusRow] + let isActive: Bool + let activeForegroundColor: Color let fontScale: CGFloat let onFocusPanel: (UUID) -> Void - @State private var isHovering = false + @ObservedObject private var variantStore = SidebarAgentRowsVariantStore.shared var body: some View { - Group { - if let url = row.url { - Button { - onFocusPanel(row.panelId) - NSWorkspace.shared.open(url) - } label: { - rowContent(underlined: true) + switch variantStore.variant { + case .inCardRows: + VStack(alignment: .leading, spacing: 2) { + ForEach(rows) { row in + SidebarAgentStatusEntryRowView( + row: row, + fontScale: fontScale, + layout: .inCard(isActive: isActive, activeForeground: activeForegroundColor), + onFocusPanel: onFocusPanel + ) } - .buttonStyle(.plain) - .safeHelp(url.absoluteString) - } else { + } + case .inCardCompact: + compactLine + case .belowAccordion, .belowFlat, .belowTree, .belowChips, .globalSection: + EmptyView() + } + } + + private var compactLine: some View { + let summary = SidebarAgentStatusRowsSummary(rows: rows) + return HStack(spacing: 5) { + ForEach(rows) { row in Button { onFocusPanel(row.panelId) } label: { - rowContent(underlined: false) + HStack(spacing: 2) { + SidebarAgentBrandIcon(row: row, fontScale: fontScale) + if let color = SidebarAgentRowStateStyle.stateColor(for: row) { + Circle() + .fill(color) + .frame(width: 4.5 * fontScale, height: 4.5 * fontScale) + } + } + .contentShape(Rectangle()) } .buttonStyle(.plain) - .safeHelp(helpText) + .safeHelp(rowTooltip(row)) } + Text(summary.text) + .cmuxFont(size: 9 * fontScale) + .foregroundColor(isActive ? activeForegroundColor.opacity(0.7) : .secondary.opacity(0.9)) + .lineLimit(1) + Spacer(minLength: 0) } - .background( - RoundedRectangle(cornerRadius: 5, style: .continuous) - .fill(Color.primary.opacity(isHovering ? 0.07 : 0)) - ) - .onHover { isHovering = $0 } } - @ViewBuilder - private func rowContent(underlined: Bool) -> some View { - HStack(spacing: 4) { - if let brandAssetName { - Image(brandAssetName) - .resizable() - .scaledToFit() - .frame(width: 11 * fontScale, height: 11 * fontScale) - if let stateColor { - Circle() - .fill(stateColor) - .frame(width: 5 * fontScale, height: 5 * fontScale) + private func rowTooltip(_ row: SidebarAgentStatusRow) -> String { + [row.paneLabel, row.value].compactMap { $0 }.joined(separator: " · ") + } +} + +/// Wrapping chips variant: one capsule per agent, border tinted by state. +struct SidebarAgentChipsFlow: View { + let rows: [SidebarAgentStatusRow] + let fontScale: CGFloat + let onFocusPanel: (UUID) -> Void + + var body: some View { + // Simple two-column-ish flow: chips wrap by rendering in an adaptive grid. + LazyVGrid( + columns: [GridItem(.adaptive(minimum: 96 * fontScale), spacing: 4, alignment: .leading)], + alignment: .leading, + spacing: 4 + ) { + ForEach(rows) { row in + Button { + onFocusPanel(row.panelId) + } label: { + HStack(spacing: 3) { + SidebarAgentBrandIcon(row: row, fontScale: fontScale) + Text(row.paneLabel ?? SidebarAgentRowStateStyle.agentDisplayName(statusKey: row.statusKey)) + .cmuxFont(size: 9.5 * fontScale, weight: .medium) + .foregroundColor(.primary.opacity(0.85)) + .lineLimit(1) + .truncationMode(.middle) + } + .padding(.vertical, 2.5) + .padding(.horizontal, 6) + .background( + Capsule() + .strokeBorder( + SidebarAgentRowStateStyle.stateColor(for: row) ?? Color.secondary.opacity(0.35), + lineWidth: 1 + ) + ) + .contentShape(Capsule()) } - } else if let icon = iconView { - icon - .foregroundColor(foregroundColor.opacity(0.95)) - } - statusText(underlined: underlined) - .lineLimit(1) - .truncationMode(.tail) - if let paneLabel = row.paneLabel { - Text(paneLabel) - .foregroundColor(.secondary.opacity(0.8)) - .lineLimit(1) - .truncationMode(.middle) + .buttonStyle(.plain) + .safeHelp([row.paneLabel, row.value].compactMap { $0 }.joined(separator: " · ")) } - Spacer(minLength: 0) } - .cmuxFont(size: 10 * fontScale) - .padding(.vertical, 3) - .padding(.horizontal, 6) - .frame(maxWidth: .infinity, alignment: .leading) - .contentShape(Rectangle()) } +} - /// Mirrors `SidebarMetadataEntryRow.metadataText`: a markdown-formatted - /// reported value keeps its inline markdown rendering after moving from - /// the generic metadata renderer into the per-agent row. Lifecycle/name - /// fallback text is always plain. - @ViewBuilder - private func statusText(underlined: Bool) -> some View { - if row.format == .markdown, - reportedValueText != nil, - let attributed = try? AttributedString( - markdown: displayText, - options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace) - ) { - Text(attributed) - .underline(underlined) - .foregroundColor(foregroundColor) - } else { - Text(displayText) - .underline(underlined) - .foregroundColor(foregroundColor) - } - } +enum SidebarAgentRowLayout: Equatable { + case nameFirst + case tree + case inCard(isActive: Bool, activeForeground: Color) +} - private var reportedValueText: String? { - guard let value = row.value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else { - return nil - } - return value +/// Shared state-styling helpers used by every variant. +enum SidebarAgentRowStateStyle { + /// Brand marks for the structured agent status keys that have assets in + /// `Assets.xcassets/AgentIcons`; keys without a mark fall back to the + /// reported or lifecycle-derived SF symbol. + static let brandAssetsByStatusKey: [String: String] = [ + "antigravity": "AgentIcons/Antigravity", + "claude_code": "AgentIcons/Claude", + "codex": "AgentIcons/Codex", + "grok": "AgentIcons/Grok", + "hermes-agent": "AgentIcons/HermesAgent", + "opencode": "AgentIcons/OpenCode", + "pi": "AgentIcons/Pi", + "rovodev": "AgentIcons/RovoDev", + ] + + static func agentDisplayName(statusKey: String) -> String { + statusKey + .split(separator: "_") + .map { $0.prefix(1).uppercased() + $0.dropFirst() } + .joined(separator: " ") } - private var displayText: String { - if let value = reportedValueText { - return value + static func effectiveColorHex(for row: SidebarAgentStatusRow) -> String? { + if let color = row.color { + return color } - let name = Self.agentDisplayName(statusKey: row.statusKey) - if let lifecycleText { - return String( - localized: "sidebar.agentStatus.nameWithLifecycle", - defaultValue: "\(name): \(lifecycleText)" - ) + switch row.lifecycle { + case .running: + return "#4C8DFF" + case .needsInput: + return "#FF9F0A" + case .idle, .unknown, nil: + return nil } - return name } - private var helpText: String { - guard let paneLabel = row.paneLabel else { return displayText } - return String( - localized: "sidebar.agentStatus.valueWithPaneLabel", - defaultValue: "\(displayText) (\(paneLabel))" - ) + static func stateColor(for row: SidebarAgentStatusRow) -> Color? { + guard let raw = effectiveColorHex(for: row) else { return nil } + return Color(hex: raw) } - private var lifecycleText: String? { + static func lifecycleText(for row: SidebarAgentStatusRow) -> String? { switch row.lifecycle { case .running: return String(localized: "sidebar.agentStatus.running", defaultValue: "Running") @@ -216,94 +304,154 @@ private struct SidebarAgentStatusEntryRow: View { } } - static func agentDisplayName(statusKey: String) -> String { - statusKey - .split(separator: "_") - .map { $0.prefix(1).uppercased() + $0.dropFirst() } - .joined(separator: " ") + /// The row's status line: the reported value, else the lifecycle text. + static func statusText(for row: SidebarAgentStatusRow) -> String? { + if let value = row.value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty { + return value + } + return lifecycleText(for: row) } +} - /// Brand marks for the structured agent status keys that have assets in - /// `Assets.xcassets/AgentIcons`; keys without a mark keep the reported or - /// lifecycle-derived SF symbol. - static let brandAssetsByStatusKey: [String: String] = [ - "antigravity": "AgentIcons/Antigravity", - "claude_code": "AgentIcons/Claude", - "codex": "AgentIcons/Codex", - "grok": "AgentIcons/Grok", - "hermes-agent": "AgentIcons/HermesAgent", - "opencode": "AgentIcons/OpenCode", - "pi": "AgentIcons/Pi", - "rovodev": "AgentIcons/RovoDev", - ] - - private var brandAssetName: String? { - Self.brandAssetsByStatusKey[row.statusKey] - } +/// The agent's brand mark, or the reported/lifecycle SF symbol fallback. +struct SidebarAgentBrandIcon: View { + let row: SidebarAgentStatusRow + let fontScale: CGFloat - /// Lifecycle/report state shown as a dot next to the brand mark, which - /// replaces the state-colored SF symbol when a brand asset exists. - private var stateColor: Color? { - guard let raw = effectiveColorHex else { return nil } - return Color(hex: raw) + var body: some View { + if let asset = SidebarAgentRowStateStyle.brandAssetsByStatusKey[row.statusKey] { + Image(asset) + .resizable() + .scaledToFit() + .frame(width: 11 * fontScale, height: 11 * fontScale) + } else if let symbol = fallbackSymbol { + CmuxSystemSymbolImage(magnified: symbol, pointSize: 8 * fontScale, weight: .medium) + .foregroundColor((SidebarAgentRowStateStyle.stateColor(for: row) ?? .secondary).opacity(0.95)) + } } - private var effectiveIcon: String? { + private var fallbackSymbol: String? { if let icon = row.icon?.trimmingCharacters(in: .whitespacesAndNewlines), !icon.isEmpty { + if icon.hasPrefix("sf:") { return String(icon.dropFirst(3)) } + if icon.hasPrefix("emoji:") || icon.hasPrefix("text:") { return nil } return icon } switch row.lifecycle { - case .running: - return "bolt.fill" - case .needsInput: - return "exclamationmark.bubble.fill" - case .idle: - return "checkmark.circle" - case .unknown, nil: - return nil + case .running: return "bolt.fill" + case .needsInput: return "exclamationmark.bubble.fill" + case .idle: return "checkmark.circle" + case .unknown, nil: return "person.crop.square" } } +} - private var effectiveColorHex: String? { - if let color = row.color { - return color - } - switch row.lifecycle { - case .running: - return "#4C8DFF" - case .needsInput: - return "#FF9F0A" - case .idle, .unknown, nil: - return nil +/// One agent row. Primary text is the session/tab name (rename wins, then the +/// live surface title); the status rides second. Each row is its own +/// hover-highlighted button so clicks never fight workspace selection. +struct SidebarAgentStatusEntryRowView: View { + let row: SidebarAgentStatusRow + let fontScale: CGFloat + let layout: SidebarAgentRowLayout + let onFocusPanel: (UUID) -> Void + + @State private var isHovering = false + + var body: some View { + Button { + onFocusPanel(row.panelId) + if let url = row.url { + NSWorkspace.shared.open(url) + } + } label: { + content } + .buttonStyle(.plain) + .background( + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(Color.primary.opacity(isHovering && !isInCard ? 0.07 : 0)) + ) + .onHover { isHovering = $0 } + .safeHelp(helpText) + } + + private var isInCard: Bool { + if case .inCard = layout { return true } + return false } - private var foregroundColor: Color { - if let raw = effectiveColorHex, let explicit = Color(hex: raw) { - return explicit + @ViewBuilder + private var content: some View { + HStack(spacing: 4) { + if case .tree = layout { + Text(verbatim: "└") + .cmuxFont(size: 9 * fontScale) + .foregroundColor(.secondary.opacity(0.5)) + } + SidebarAgentBrandIcon(row: row, fontScale: fontScale) + if let stateColor = SidebarAgentRowStateStyle.stateColor(for: row) { + Circle() + .fill(stateColor) + .frame(width: 5 * fontScale, height: 5 * fontScale) + } + Text(primaryText) + .cmuxFont(size: 10 * fontScale, weight: .medium) + .foregroundColor(primaryColor) + .lineLimit(1) + .truncationMode(.middle) + if let status = statusLineText { + statusTextView(status) + .lineLimit(1) + .truncationMode(.tail) + } + Spacer(minLength: 0) } - return .secondary + .padding(.vertical, isInCard ? 1 : 3) + .padding(.horizontal, isInCard ? 0 : 6) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + + /// Session/tab name first; agent-type name when the pane has no title yet. + private var primaryText: String { + row.paneLabel ?? SidebarAgentRowStateStyle.agentDisplayName(statusKey: row.statusKey) + } + + private var statusLineText: String? { + SidebarAgentRowStateStyle.statusText(for: row) } - private var iconView: AnyView? { - guard let iconRaw = effectiveIcon else { return nil } - if iconRaw.hasPrefix("emoji:") { - let value = String(iconRaw.dropFirst("emoji:".count)) - guard !value.isEmpty else { return nil } - return AnyView(Text(value).cmuxFont(size: 9 * fontScale)) + @ViewBuilder + private func statusTextView(_ status: String) -> some View { + if row.format == .markdown, + let attributed = try? AttributedString( + markdown: status, + options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace) + ) { + Text(attributed) + .cmuxFont(size: 9.5 * fontScale) + .foregroundColor(secondaryColor) + } else { + Text(status) + .cmuxFont(size: 9.5 * fontScale) + .foregroundColor(secondaryColor) } - if iconRaw.hasPrefix("text:") { - let value = String(iconRaw.dropFirst("text:".count)) - guard !value.isEmpty else { return nil } - return AnyView(Text(value).cmuxFont(size: 8 * fontScale, weight: .semibold)) + } + + private var primaryColor: Color { + if case let .inCard(isActive, activeForeground) = layout, isActive { + return activeForeground } - let symbolName: String - if iconRaw.hasPrefix("sf:") { - symbolName = String(iconRaw.dropFirst("sf:".count)) - } else { - symbolName = iconRaw + return .primary.opacity(0.85) + } + + private var secondaryColor: Color { + if case let .inCard(isActive, activeForeground) = layout, isActive { + return activeForeground.opacity(0.65) } - guard !symbolName.isEmpty else { return nil } - return AnyView(CmuxSystemSymbolImage(magnified: symbolName, pointSize: 8 * fontScale, weight: .medium)) + return .secondary.opacity(0.9) + } + + private var helpText: String { + [primaryText, statusLineText].compactMap { $0 }.joined(separator: " · ") } } diff --git a/Sources/Workspace+PanelLifecycle.swift b/Sources/Workspace+PanelLifecycle.swift index 9248b7c0656c..b3e3903c1c74 100644 --- a/Sources/Workspace+PanelLifecycle.swift +++ b/Sources/Workspace+PanelLifecycle.swift @@ -104,30 +104,59 @@ extension Workspace { private func recordAgentPIDOwnership(key: String, panelId: UUID) { if let previousPanelId = agentPIDPanelIdsByKey[key], previousPanelId != panelId { + preserveDisplacedBareKeyRuntime(key: key, displacedPanelId: previousPanelId) removeAgentPIDOwnership(key: key) } if isStructuredAgentHookPIDKey(key) { let statusKey = agentStatusKey(forAgentPIDKey: key) let stalePanelKeys = agentPIDKeysByPanelId[panelId]?.filter { - $0 != key && - isStructuredAgentHookPIDKey($0) && - agentStatusKey(forAgentPIDKey: $0) != statusKey + $0 != key && isStructuredAgentHookPIDKey($0) } ?? [] for staleKey in stalePanelKeys { - _ = clearAgentPID(key: staleKey, panelId: panelId, clearStatus: true, refreshPorts: false) + // A stale key for the SAME agent type is a key-shape change + // (bare key returning to a pane that holds a synthesized + // displacement key): keep the pane's status entry. A different + // agent type is a real replacement: clear its status too. + let sameAgent = agentStatusKey(forAgentPIDKey: staleKey) == statusKey + _ = clearAgentPID(key: staleKey, panelId: panelId, clearStatus: !sameAgent, refreshPorts: false) } } agentPIDPanelIdsByKey[key] = panelId agentPIDKeysByPanelId[panelId, default: []].insert(key) } + /// Claude-style dedicated hooks share ONE bare PID key per agent type + /// across every pane of a workspace, so a report from pane B displaces + /// pane A's ownership even though A still hosts its own live agent. + /// Re-key A's record to a synthesized panel-scoped key instead of dropping + /// its presence: the pid and start-time identity move with it, so the + /// liveness sweep still owns cleanup, and A keeps its sidebar row. + private func preserveDisplacedBareKeyRuntime(key: String, displacedPanelId: UUID) { + guard isStructuredAgentHookPIDKey(key), !key.contains(".") else { return } + guard panels[displacedPanelId] != nil, let pid = agentPIDs[key] else { return } + let synthesizedKey = Self.synthesizedDisplacedPIDKey(statusKey: key, panelId: displacedPanelId) + agentPIDs[synthesizedKey] = pid + agentPIDProcessIdentitiesByKey[synthesizedKey] = agentPIDProcessIdentitiesByKey[key] + agentPIDPanelIdsByKey[synthesizedKey] = displacedPanelId + agentPIDKeysByPanelId[displacedPanelId, default: []].insert(synthesizedKey) + } + + static func synthesizedDisplacedPIDKey(statusKey: String, panelId: UUID) -> String { + "\(statusKey).pane-\(panelId.uuidString)" + } + @discardableResult private func clearOtherStructuredAgentRuntimes(onPanel panelId: UUID, keeping retainedKey: String) -> Bool { guard isStructuredAgentHookPIDKey(retainedKey) else { return false } let staleKeys = agentPIDKeysByPanelId[panelId] ?? [] var didChange = false for staleKey in staleKeys where staleKey != retainedKey && isStructuredAgentHookPIDKey(staleKey) { - if clearAgentPID(key: staleKey, panelId: panelId, clearStatus: true, refreshPorts: false) { + // A stale key for the SAME agent type is a key-shape change (bare + // key returning to a pane holding a synthesized displacement key): + // keep the pane's status entry. A different agent type is a real + // replacement: clear its status too. + let sameAgent = agentStatusKey(forAgentPIDKey: staleKey) == agentStatusKey(forAgentPIDKey: retainedKey) + if clearAgentPID(key: staleKey, panelId: panelId, clearStatus: !sameAgent, refreshPorts: false) { didChange = true } } @@ -274,6 +303,15 @@ extension Workspace { if clearStatus, clearPanelStatusEntry(statusKey: statusKey, panelId: panelId) { didChange = true } + // The exiting pane's runtime may live under a synthesized + // displacement key (bare-key ownership moved to another pane + // after this agent's last report); reap it with the exit hook + // instead of waiting for the liveness sweep. + let synthesizedKey = Self.synthesizedDisplacedPIDKey(statusKey: statusKey, panelId: panelId) + if agentPIDPanelIdsByKey[synthesizedKey] == panelId, + clearAgentPID(key: synthesizedKey, panelId: panelId, clearStatus: clearStatus, refreshPorts: false) { + didChange = true + } return didChange } let statusKeyToClear = clearStatus ? agentStatusKey(forAgentPIDKey: key) : nil diff --git a/Sources/Workspace+SidebarAgentStatus.swift b/Sources/Workspace+SidebarAgentStatus.swift index ce227c91a4cb..4b4af844d11a 100644 --- a/Sources/Workspace+SidebarAgentStatus.swift +++ b/Sources/Workspace+SidebarAgentStatus.swift @@ -190,7 +190,6 @@ extension Workspace { panelCountByStatusKey[item.statusKey, default: 0] += 1 } - let includePaneLabels = chosenByPanel.count > 1 let rows = chosenByPanel.map { item -> SidebarAgentStatusRow in let workspaceEntry = statusEntries[item.statusKey] let soleOwner = panelCountByStatusKey[item.statusKey] == 1 @@ -204,7 +203,7 @@ extension Workspace { url: entry?.url, format: entry?.format ?? .plain, lifecycle: agentLifecycleStatesByPanelId[item.panelId]?[item.statusKey], - paneLabel: includePaneLabels ? agentStatusRowPaneLabel(panelId: item.panelId) : nil, + paneLabel: agentStatusRowPaneLabel(panelId: item.panelId), // No workspace fallback here: when the pane is not the sole // owner, the last-write-wins workspace entry's freshness must // not influence this row's sort position either. @@ -219,11 +218,15 @@ extension Workspace { } } - private func agentStatusRowPaneLabel(panelId: UUID) -> String? { + /// The row's identity label: an explicit rename wins, then the live + /// surface title (agents set it to their session name/topic), then the + /// directory label. This is what makes a row say the session's name + /// instead of a generic "Claude Code". + func agentStatusRowPaneLabel(panelId: UUID) -> String? { let candidates = [ panelCustomTitles[panelId], - panelDirectoryDisplayLabels[panelId], panelTitles[panelId], + panelDirectoryDisplayLabels[panelId], ] for candidate in candidates { if let trimmed = candidate?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmed.isEmpty { diff --git a/Sources/cmuxApp.swift b/Sources/cmuxApp.swift index 670390fee49e..9ec576e2e099 100644 --- a/Sources/cmuxApp.swift +++ b/Sources/cmuxApp.swift @@ -515,6 +515,10 @@ struct cmuxApp: App { #if DEBUG CommandMenu("Debug") { + Button(String(localized: "debug.menu.agentRowsStyle", defaultValue: "Agent Rows Style…")) { + AgentRowsVariantLabWindowController.shared.show() + } + Button("New Tab With Lorem Search Text") { appDelegate.openDebugLoremTab(nil) } diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 0a5981f707a5..0e2f98f8a4c5 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1062,6 +1062,7 @@ 5C3E0454B6C24B02A2F091A8 /* ShortcutRoutingSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = B42A82C6AA614E74873D9A5F /* ShortcutRoutingSupport.swift */; }; F6001000A1B2C3D4E5F60718 /* ShortcutUnbindingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6001001A1B2C3D4E5F60718 /* ShortcutUnbindingTests.swift */; }; C3467AB10000000000000001 /* ShortcutWhenClauseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3467AB10000000000000002 /* ShortcutWhenClauseTests.swift */; }; + 14FE4CD3BCAD423796E56EE5 /* SidebarAgentRowsVariantLab.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4722F35D10C94D12ADC4D017 /* SidebarAgentRowsVariantLab.swift */; }; 2FB188449942360CAB895143 /* SidebarAgentStatusRowsSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D2990638B9E75D4B02AF14F /* SidebarAgentStatusRowsSummary.swift */; }; 7A11AA057A11AA057A11AA05 /* SidebarAgentStatusRowViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */; }; 211A75777F433ED8BA5AE208 /* SidebarAppearanceSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 243632BA1DBBA36FD46E0610 /* SidebarAppearanceSupport.swift */; }; @@ -2525,6 +2526,7 @@ B42A82C6AA614E74873D9A5F /* ShortcutRoutingSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = App/ShortcutRoutingSupport.swift; sourceTree = ""; }; F6001001A1B2C3D4E5F60718 /* ShortcutUnbindingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShortcutUnbindingTests.swift; sourceTree = ""; }; C3467AB10000000000000002 /* ShortcutWhenClauseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShortcutWhenClauseTests.swift; sourceTree = ""; }; + 4722F35D10C94D12ADC4D017 /* SidebarAgentRowsVariantLab.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentRowsVariantLab.swift; sourceTree = ""; }; 1D2990638B9E75D4B02AF14F /* SidebarAgentStatusRowsSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentStatusRowsSummary.swift; sourceTree = ""; }; 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentStatusRowViews.swift; sourceTree = ""; }; 243632BA1DBBA36FD46E0610 /* SidebarAppearanceSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarAppearanceSupport.swift; sourceTree = ""; }; @@ -3456,6 +3458,7 @@ 7A11AA027A11AA027A11AA02 /* Workspace+SidebarAgentStatus.swift */, 7A11AA047A11AA047A11AA04 /* SidebarMetadataRowViews.swift */, 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */, + 4722F35D10C94D12ADC4D017 /* SidebarAgentRowsVariantLab.swift */, 1D2990638B9E75D4B02AF14F /* SidebarAgentStatusRowsSummary.swift */, C0A1E5CE01C0A1E5CE01A002 /* CoalesceLatestPublisher.swift */, 5659A0025659A0025659A002 /* WorkspaceSidebarObservation.swift */, @@ -5533,6 +5536,7 @@ 125BAEF2FE3B454547B964D1 /* ShortcutHintPill.swift in Sources */, 6042C0046042C0046042C004 /* ShortcutHintTitlebarPolicy.swift in Sources */, 5C3E0454B6C24B02A2F091A8 /* ShortcutRoutingSupport.swift in Sources */, + 14FE4CD3BCAD423796E56EE5 /* SidebarAgentRowsVariantLab.swift in Sources */, 2FB188449942360CAB895143 /* SidebarAgentStatusRowsSummary.swift in Sources */, 7A11AA057A11AA057A11AA05 /* SidebarAgentStatusRowViews.swift in Sources */, 211A75777F433ED8BA5AE208 /* SidebarAppearanceSupport.swift in Sources */, diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 25df21a49999..2ee613f5e968 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -421,4 +421,36 @@ struct PerAgentSidebarStatusRowTests { #expect(runningOnly.accentColorHex == "#4C8DFF") #expect(SidebarAgentStatusRowsSummary(rows: [row(lifecycle: .idle)]).accentColorHex == nil) } + + @Test + func testDisplacedBareKeyPaneKeepsRowWithItsOwnPid() throws { + let workspace = Workspace() + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + // Pane A reports first with the bare shared key (real claude hook shape). + workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) + workspace.setAgentLifecycle(key: "claude_code", panelId: firstPanelId, lifecycle: .running) + // Pane B's report displaces A's bare-key ownership. + workspace.recordAgentPID(key: "claude_code", pid: 222, panelId: secondPanelId, refreshPorts: false) + + let rows = workspace.sidebarAgentStatusRows() + #expect(rows.count == 2) + #expect(Set(rows.map(\.panelId)) == [firstPanelId, secondPanelId]) + // A's runtime moved to a synthesized key with its own pid intact, so + // the liveness sweep still owns its cleanup. + let synthesizedKey = Workspace.synthesizedDisplacedPIDKey(statusKey: "claude_code", panelId: firstPanelId) + #expect(workspace.agentPIDs[synthesizedKey] == 111) + #expect(workspace.agentPIDs["claude_code"] == 222) + #expect(workspace.agentLifecycleStatesByPanelId[firstPanelId]?["claude_code"] == .running) + + // A reports again: the bare key returns to A, the synthesized key is + // reaped, and A's panel-scoped entry survives the key-shape change. + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: firstPanelId) + workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) + #expect(workspace.agentPIDs[synthesizedKey] == nil) + #expect(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"]?.value == "Running") + #expect(workspace.sidebarAgentStatusRows().count == 2) + } } From 525a3ae6aeba76e073888ea5ec666f4c1bad98d3 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 00:19:18 -0700 Subject: [PATCH 25/46] fix duplicate SidebarAgentStatusRowsSummary declaration --- Sources/SidebarAgentStatusRowViews.swift | 42 ------------------------ 1 file changed, 42 deletions(-) diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index 82867f5333f1..ce98890783f6 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -3,48 +3,6 @@ import CmuxFoundation import CmuxSidebar import SwiftUI -/// Aggregate over the agent rows of one workspace, shown in the accordion -/// header (and standing in for the rows while collapsed). -struct SidebarAgentStatusRowsSummary: Equatable { - let agentCount: Int - let needsInputCount: Int - let runningCount: Int - - init(rows: [SidebarAgentStatusRow]) { - agentCount = rows.count - needsInputCount = rows.filter { $0.lifecycle == .needsInput }.count - runningCount = rows.filter { $0.lifecycle == .running }.count - } - - var text: String { - var parts: [String] = [] - if agentCount == 1 { - parts.append(String(localized: "sidebar.agentStatus.summary.oneAgent", defaultValue: "1 agent")) - } else { - parts.append(String( - format: String(localized: "sidebar.agentStatus.summary.agentCount", defaultValue: "%lld agents"), - agentCount - )) - } - if needsInputCount == 1 { - parts.append(String(localized: "sidebar.agentStatus.summary.oneNeedsInput", defaultValue: "1 needs input")) - } else if needsInputCount > 1 { - parts.append(String( - format: String(localized: "sidebar.agentStatus.summary.needsInputCount", defaultValue: "%lld need input"), - needsInputCount - )) - } - return parts.joined(separator: " · ") - } - - /// Worst-state accent: needs-input beats running beats idle. - var accentColorHex: String? { - if needsInputCount > 0 { return "#FF9F0A" } - if runningCount > 0 { return "#4C8DFF" } - return nil - } -} - /// Below-card presentation of the per-agent rows. Owns the variant switch for /// every below-card style; renders nothing when an in-card or global variant /// is active. Rows receive immutable value snapshots and closure action From 813ad677b6aad9b0697f0d43e7d8957d2c065172 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 01:00:18 -0700 Subject: [PATCH 26/46] fix: displaced bare-key runtime must capture the displaced pane's pid recordAgentPID overwrote agentPIDs[key]/identity with the NEW reporter's pid before recordAgentPIDOwnership ran, so preserveDisplacedBareKeyRuntime synthesized the displaced pane's key with the WRONG process (the sibling's). The displaced row then tracked the sibling's liveness: ghost row if its own agent died, vanishing row if the sibling's did. Ownership displacement now runs before the pid write. Also moves the ownership/displacement cluster to Workspace+AgentPIDOwnership.swift (file length budget) and scopes the sidebar footer's TabManager observation inside SidebarGlobalAgentsSection so the footer no longer re-renders on TabManager changes; extracts the Debug Windows submenu from cmuxApp.swift and ratchets its budget 4759->4627. --- .github/swift-file-length-budget.tsv | 2 +- Sources/ContentView.swift | 13 +- Sources/DebugWindowsMenu.swift | 146 ++++++++++++++++++++ Sources/SidebarAgentRowsVariantLab.swift | 16 ++- Sources/Workspace+AgentPIDOwnership.swift | 80 +++++++++++ Sources/Workspace+PanelLifecycle.swift | 83 +----------- Sources/cmuxApp.swift | 158 ++-------------------- cmux.xcodeproj/project.pbxproj | 8 ++ 8 files changed, 268 insertions(+), 238 deletions(-) create mode 100644 Sources/DebugWindowsMenu.swift create mode 100644 Sources/Workspace+AgentPIDOwnership.swift diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 598ffcbbb0f6..44ff482b6564 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -21,7 +21,7 @@ 5915 cmuxTests/TerminalAndGhosttyTests.swift 5809 Sources/TextBoxInput.swift 5573 cmuxTests/BrowserConfigTests.swift -4759 Sources/cmuxApp.swift +4627 Sources/cmuxApp.swift 4482 Sources/Panels/FilePreviewPanel.swift 4367 cmuxTests/BrowserPanelTests.swift 4036 Sources/BrowserWindowPortal.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 0934c147c3e9..e5ee2e3f15e3 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -12626,20 +12626,13 @@ private struct SidebarFooter: View { var updateViewModel: UpdateStateModel @ObservedObject var fileExplorerState: FileExplorerState let onSendFeedback: () -> Void - @EnvironmentObject private var tabManager: TabManager var body: some View { VStack(alignment: .leading, spacing: 0) { // Renders only while the globalSection debug variant is selected. - SidebarGlobalAgentsSection( - tabManager: tabManager, - fontScale: 1, - onFocus: { workspaceId, panelId in - guard let tab = tabManager.tabs.first(where: { $0.id == workspaceId }) else { return } - tabManager.selectedTabId = workspaceId - tab.focusPanel(panelId) - } - ) + // Owns its TabManager observation internally so the footer (and + // the dev footer) never re-render on TabManager changes. + SidebarGlobalAgentsSection(fontScale: 1) #if DEBUG SidebarDevFooter(updateViewModel: updateViewModel, fileExplorerState: fileExplorerState, onSendFeedback: onSendFeedback) #else diff --git a/Sources/DebugWindowsMenu.swift b/Sources/DebugWindowsMenu.swift new file mode 100644 index 000000000000..e1195187560c --- /dev/null +++ b/Sources/DebugWindowsMenu.swift @@ -0,0 +1,146 @@ +import SwiftUI + +#if DEBUG +/// The Debug > "Debug Windows" submenu, extracted from `cmuxApp.swift` +/// (see `AgentSessionDebugMenuButtons` / `CanvasDebugMenuButtons` for the +/// same pattern). Every item opens a singleton debug window controller. +struct DebugWindowsMenu: View { + var body: some View { + Menu("Debug Windows") { + Button("Background Debug…") { + BackgroundDebugWindowController.shared.show() + } + Button("Pro Badge Style…") { + ProBadgeDebugWindowController.shared.show() + } + Button( + String( + localized: "debug.menu.bonsplitTabBarDebug", + defaultValue: "Bonsplit Tab Bar Debug…" + ) + ) { + BonsplitTabBarDebugWindowController.shared.show() + } + Button("Browser Import Hint Debug…") { + BrowserImportHintDebugWindowController.shared.show() + } + Button( + String( + localized: "debug.menu.browserProfilePopoverDebug", + defaultValue: "Browser Profile Popover Debug…" + ) + ) { + BrowserProfilePopoverDebugWindowController.shared.show() + } + Button("Debug Window Controls…") { + DebugWindowControlsWindowController.shared.show() + } + Button( + String( + localized: "debug.menu.devWindowDisplay", + defaultValue: "Dev Window Display…" + ) + ) { + DevWindowDisplayDebugWindowController.shared.show() + } + Button("Feed Preview…") { + FeedPreviewWindowController.shared.show() + } + Button( + String( + localized: "debug.menu.feedTextEditorDebug", + defaultValue: "Feed Text Editor Lab…" + ) + ) { + FeedTextEditorDebugWindowController.shared.show() + } + Button( + String( + localized: "debug.menu.feedButtonStyleDebug", + defaultValue: "Feed Button Style Debug…" + ) + ) { + FeedButtonStyleDebugWindowController.shared.show() + } + Button( + String( + localized: "debug.menu.startupAppearanceDebug", + defaultValue: "Startup Appearance Debug…" + ) + ) { + StartupAppearanceDebugWindowController.shared.show() + } + Button("Menu Bar Extra Debug…") { + MenuBarExtraDebugWindowController.shared.show() + } + Button( + String( + localized: "debug.menu.aboutTitlebarDebug", + defaultValue: "About Titlebar Debug…" + ) + ) { + AppDelegate.shared?.debugWindowsCoordinator.showAboutTitlebarDebugWindow() + } + Button( + String( + localized: "debug.menu.titlebarLayoutDebug", + defaultValue: "Titlebar Layout Debug..." + ) + ) { + TitlebarLayoutDebugWindowController.shared.show() + } + Button("Sidebar Debug…") { + SidebarDebugWindowController.shared.show() + } + Button( + String( + localized: "debug.menu.splitButtonLayoutDebug", + defaultValue: "Split Button Layout Debug…" + ) + ) { + SplitButtonLayoutDebugWindowController.shared.show() + } + Button( + String( + localized: "debug.menu.tabBarBackdropLab", + defaultValue: "Tab Bar Backdrop Lab…" + ) + ) { + TabBarBackdropLabWindowController.shared.show() + } + Button("File Explorer Style Debug…") { + FileExplorerStyleDebugWindowController.shared.show() + } + Button( + String( + localized: "debug.menu.pdfPreviewChromeDebug", + defaultValue: "PDF Preview Chrome Debug…" + ) + ) { + PDFPreviewChromeDebugWindowController.shared.show() + } + Button("Open All Debug Windows") { + Self.openAllDebugWindows() + } + } + } + + private static func openAllDebugWindows() { + DebugWindowControlsWindowController.shared.show() + BrowserImportHintDebugWindowController.shared.show() + BrowserProfilePopoverDebugWindowController.shared.show() + AppDelegate.shared?.debugWindowsCoordinator.showAboutTitlebarDebugWindow() + TitlebarLayoutDebugWindowController.shared.show() + SidebarDebugWindowController.shared.show() + BackgroundDebugWindowController.shared.show() + StartupAppearanceDebugWindowController.shared.show() + MenuBarExtraDebugWindowController.shared.show() + PDFPreviewChromeDebugWindowController.shared.show() + FeedPreviewWindowController.shared.show() + FeedTextEditorDebugWindowController.shared.show() + FeedButtonStyleDebugWindowController.shared.show() + BonsplitTabBarDebugWindowController.shared.show() + SplitButtonLayoutDebugWindowController.shared.show() + } +} +#endif diff --git a/Sources/SidebarAgentRowsVariantLab.swift b/Sources/SidebarAgentRowsVariantLab.swift index 63ca53594133..28162d4d72e7 100644 --- a/Sources/SidebarAgentRowsVariantLab.swift +++ b/Sources/SidebarAgentRowsVariantLab.swift @@ -149,14 +149,22 @@ private struct AgentRowsVariantLabView: View { /// The `globalSection` variant: one Agents list at the bottom of the sidebar, /// grouped by workspace. Reads live workspace state directly; acceptable only -/// because it renders exclusively while this debug variant is selected. +/// because it renders exclusively while this debug variant is selected. Owns +/// its TabManager observation so the host (the sidebar footer) does not +/// re-render on TabManager changes; when another variant is selected the +/// re-evaluated body is a single enum comparison. struct SidebarGlobalAgentsSection: View { - let tabManager: TabManager let fontScale: CGFloat - let onFocus: (UUID, UUID) -> Void + @EnvironmentObject private var tabManager: TabManager @ObservedObject private var store = SidebarAgentRowsVariantStore.shared + private func focus(workspaceId: UUID, panelId: UUID) { + guard let tab = tabManager.tabs.first(where: { $0.id == workspaceId }) else { return } + tabManager.selectedTabId = workspaceId + tab.focusPanel(panelId) + } + var body: some View { if store.variant == .globalSection { let groups = tabManager.tabs.compactMap { tab -> (workspaceId: UUID, title: String, rows: [SidebarAgentStatusRow])? in @@ -183,7 +191,7 @@ struct SidebarGlobalAgentsSection: View { row: row, fontScale: fontScale, layout: .nameFirst, - onFocusPanel: { panelId in onFocus(group.workspaceId, panelId) } + onFocusPanel: { panelId in focus(workspaceId: group.workspaceId, panelId: panelId) } ) .padding(.horizontal, 8) } diff --git a/Sources/Workspace+AgentPIDOwnership.swift b/Sources/Workspace+AgentPIDOwnership.swift new file mode 100644 index 000000000000..311bd984486f --- /dev/null +++ b/Sources/Workspace+AgentPIDOwnership.swift @@ -0,0 +1,80 @@ +import Foundation + +// Panel ownership of agent PID keys: which pane owns each reported key, and +// how a bare shared key (claude-style hooks report one key per agent type for +// the whole workspace) moves between panes without erasing a sibling pane's +// live agent row. Cleanup of the maps written here stays with the callers in +// `Workspace+PanelLifecycle.swift` (`clearAgentPID`, the liveness sweeps, and +// `discardClosedPanelLifecycleState`). +extension Workspace { + func removeAgentPIDOwnership(key: String) { + if let previousPanelId = agentPIDPanelIdsByKey[key] { + agentPIDKeysByPanelId[previousPanelId]?.remove(key) + if agentPIDKeysByPanelId[previousPanelId]?.isEmpty == true { + agentPIDKeysByPanelId.removeValue(forKey: previousPanelId) + } + agentPIDPanelIdsByKey.removeValue(forKey: key) + } + } + + func recordAgentPIDOwnership(key: String, panelId: UUID) { + if let previousPanelId = agentPIDPanelIdsByKey[key], previousPanelId != panelId { + preserveDisplacedBareKeyRuntime(key: key, displacedPanelId: previousPanelId) + removeAgentPIDOwnership(key: key) + } + if isStructuredAgentHookPIDKey(key) { + let statusKey = agentStatusKey(forAgentPIDKey: key) + let stalePanelKeys = agentPIDKeysByPanelId[panelId]?.filter { + $0 != key && isStructuredAgentHookPIDKey($0) + } ?? [] + for staleKey in stalePanelKeys { + // A stale key for the SAME agent type is a key-shape change + // (bare key returning to a pane that holds a synthesized + // displacement key): keep the pane's status entry. A different + // agent type is a real replacement: clear its status too. + let sameAgent = agentStatusKey(forAgentPIDKey: staleKey) == statusKey + _ = clearAgentPID(key: staleKey, panelId: panelId, clearStatus: !sameAgent, refreshPorts: false) + } + } + agentPIDPanelIdsByKey[key] = panelId + agentPIDKeysByPanelId[panelId, default: []].insert(key) + } + + /// Claude-style dedicated hooks share ONE bare PID key per agent type + /// across every pane of a workspace, so a report from pane B displaces + /// pane A's ownership even though A still hosts its own live agent. + /// Re-key A's record to a synthesized panel-scoped key instead of dropping + /// its presence: the pid and start-time identity move with it, so the + /// liveness sweep still owns cleanup, and A keeps its sidebar row. + private func preserveDisplacedBareKeyRuntime(key: String, displacedPanelId: UUID) { + guard isStructuredAgentHookPIDKey(key), !key.contains(".") else { return } + guard panels[displacedPanelId] != nil, let pid = agentPIDs[key] else { return } + let synthesizedKey = Self.synthesizedDisplacedPIDKey(statusKey: key, panelId: displacedPanelId) + agentPIDs[synthesizedKey] = pid + agentPIDProcessIdentitiesByKey[synthesizedKey] = agentPIDProcessIdentitiesByKey[key] + agentPIDPanelIdsByKey[synthesizedKey] = displacedPanelId + agentPIDKeysByPanelId[displacedPanelId, default: []].insert(synthesizedKey) + } + + static func synthesizedDisplacedPIDKey(statusKey: String, panelId: UUID) -> String { + "\(statusKey).pane-\(panelId.uuidString)" + } + + @discardableResult + func clearOtherStructuredAgentRuntimes(onPanel panelId: UUID, keeping retainedKey: String) -> Bool { + guard isStructuredAgentHookPIDKey(retainedKey) else { return false } + let staleKeys = agentPIDKeysByPanelId[panelId] ?? [] + var didChange = false + for staleKey in staleKeys where staleKey != retainedKey && isStructuredAgentHookPIDKey(staleKey) { + // A stale key for the SAME agent type is a key-shape change (bare + // key returning to a pane holding a synthesized displacement key): + // keep the pane's status entry. A different agent type is a real + // replacement: clear its status too. + let sameAgent = agentStatusKey(forAgentPIDKey: staleKey) == agentStatusKey(forAgentPIDKey: retainedKey) + if clearAgentPID(key: staleKey, panelId: panelId, clearStatus: !sameAgent, refreshPorts: false) { + didChange = true + } + } + return didChange + } +} diff --git a/Sources/Workspace+PanelLifecycle.swift b/Sources/Workspace+PanelLifecycle.swift index b3e3903c1c74..bb062e09852e 100644 --- a/Sources/Workspace+PanelLifecycle.swift +++ b/Sources/Workspace+PanelLifecycle.swift @@ -92,90 +92,21 @@ extension Workspace { return false } - private func removeAgentPIDOwnership(key: String) { - if let previousPanelId = agentPIDPanelIdsByKey[key] { - agentPIDKeysByPanelId[previousPanelId]?.remove(key) - if agentPIDKeysByPanelId[previousPanelId]?.isEmpty == true { - agentPIDKeysByPanelId.removeValue(forKey: previousPanelId) - } - agentPIDPanelIdsByKey.removeValue(forKey: key) - } - } - - private func recordAgentPIDOwnership(key: String, panelId: UUID) { - if let previousPanelId = agentPIDPanelIdsByKey[key], previousPanelId != panelId { - preserveDisplacedBareKeyRuntime(key: key, displacedPanelId: previousPanelId) - removeAgentPIDOwnership(key: key) - } - if isStructuredAgentHookPIDKey(key) { - let statusKey = agentStatusKey(forAgentPIDKey: key) - let stalePanelKeys = agentPIDKeysByPanelId[panelId]?.filter { - $0 != key && isStructuredAgentHookPIDKey($0) - } ?? [] - for staleKey in stalePanelKeys { - // A stale key for the SAME agent type is a key-shape change - // (bare key returning to a pane that holds a synthesized - // displacement key): keep the pane's status entry. A different - // agent type is a real replacement: clear its status too. - let sameAgent = agentStatusKey(forAgentPIDKey: staleKey) == statusKey - _ = clearAgentPID(key: staleKey, panelId: panelId, clearStatus: !sameAgent, refreshPorts: false) - } - } - agentPIDPanelIdsByKey[key] = panelId - agentPIDKeysByPanelId[panelId, default: []].insert(key) - } - - /// Claude-style dedicated hooks share ONE bare PID key per agent type - /// across every pane of a workspace, so a report from pane B displaces - /// pane A's ownership even though A still hosts its own live agent. - /// Re-key A's record to a synthesized panel-scoped key instead of dropping - /// its presence: the pid and start-time identity move with it, so the - /// liveness sweep still owns cleanup, and A keeps its sidebar row. - private func preserveDisplacedBareKeyRuntime(key: String, displacedPanelId: UUID) { - guard isStructuredAgentHookPIDKey(key), !key.contains(".") else { return } - guard panels[displacedPanelId] != nil, let pid = agentPIDs[key] else { return } - let synthesizedKey = Self.synthesizedDisplacedPIDKey(statusKey: key, panelId: displacedPanelId) - agentPIDs[synthesizedKey] = pid - agentPIDProcessIdentitiesByKey[synthesizedKey] = agentPIDProcessIdentitiesByKey[key] - agentPIDPanelIdsByKey[synthesizedKey] = displacedPanelId - agentPIDKeysByPanelId[displacedPanelId, default: []].insert(synthesizedKey) - } - - static func synthesizedDisplacedPIDKey(statusKey: String, panelId: UUID) -> String { - "\(statusKey).pane-\(panelId.uuidString)" - } - - @discardableResult - private func clearOtherStructuredAgentRuntimes(onPanel panelId: UUID, keeping retainedKey: String) -> Bool { - guard isStructuredAgentHookPIDKey(retainedKey) else { return false } - let staleKeys = agentPIDKeysByPanelId[panelId] ?? [] - var didChange = false - for staleKey in staleKeys where staleKey != retainedKey && isStructuredAgentHookPIDKey(staleKey) { - // A stale key for the SAME agent type is a key-shape change (bare - // key returning to a pane holding a synthesized displacement key): - // keep the pane's status entry. A different agent type is a real - // replacement: clear its status too. - let sameAgent = agentStatusKey(forAgentPIDKey: staleKey) == agentStatusKey(forAgentPIDKey: retainedKey) - if clearAgentPID(key: staleKey, panelId: panelId, clearStatus: !sameAgent, refreshPorts: false) { - didChange = true - } - } - return didChange - } - @discardableResult func recordAgentPID(key: String, pid: pid_t, panelId: UUID?, refreshPorts: Bool = true) -> Bool { var didClearOtherStructuredAgentRuntime = false + // Ownership displacement must run BEFORE the bare key's pid/identity + // are overwritten: preserveDisplacedBareKeyRuntime re-keys the + // previous owner's runtime and must capture the DISPLACED pane's pid, + // not the new reporter's. if let panelId { didClearOtherStructuredAgentRuntime = clearOtherStructuredAgentRuntimes(onPanel: panelId, keeping: key) - } - agentPIDs[key] = pid - agentPIDProcessIdentitiesByKey[key] = Self.agentPIDProcessIdentity(pid: pid) - if let panelId { recordAgentPIDOwnership(key: key, panelId: panelId) } else { removeAgentPIDOwnership(key: key) } + agentPIDs[key] = pid + agentPIDProcessIdentitiesByKey[key] = Self.agentPIDProcessIdentity(pid: pid) if refreshPorts { refreshTrackedAgentPorts() } @@ -277,7 +208,7 @@ extension Workspace { return Self.truthyStartupEnvironmentValues.contains(rawValue) } - private func isStructuredAgentHookPIDKey(_ key: String) -> Bool { + func isStructuredAgentHookPIDKey(_ key: String) -> Bool { Self.structuredAgentHookStatusKeys.contains(agentStatusKey(forAgentPIDKey: key)) } diff --git a/Sources/cmuxApp.swift b/Sources/cmuxApp.swift index 9ec576e2e099..72591149831b 100644 --- a/Sources/cmuxApp.swift +++ b/Sources/cmuxApp.swift @@ -544,123 +544,7 @@ struct cmuxApp: App { ) Divider() - Menu("Debug Windows") { - Button("Background Debug…") { - BackgroundDebugWindowController.shared.show() - } - Button("Pro Badge Style…") { - ProBadgeDebugWindowController.shared.show() - } - Button( - String( - localized: "debug.menu.bonsplitTabBarDebug", - defaultValue: "Bonsplit Tab Bar Debug…" - ) - ) { - BonsplitTabBarDebugWindowController.shared.show() - } - Button("Browser Import Hint Debug…") { - BrowserImportHintDebugWindowController.shared.show() - } - Button( - String( - localized: "debug.menu.browserProfilePopoverDebug", - defaultValue: "Browser Profile Popover Debug…" - ) - ) { - BrowserProfilePopoverDebugWindowController.shared.show() - } - Button("Debug Window Controls…") { - DebugWindowControlsWindowController.shared.show() - } - Button( - String( - localized: "debug.menu.devWindowDisplay", - defaultValue: "Dev Window Display…" - ) - ) { - DevWindowDisplayDebugWindowController.shared.show() - } - Button("Feed Preview…") { - FeedPreviewWindowController.shared.show() - } - Button( - String( - localized: "debug.menu.feedTextEditorDebug", - defaultValue: "Feed Text Editor Lab…" - ) - ) { - FeedTextEditorDebugWindowController.shared.show() - } - Button( - String( - localized: "debug.menu.feedButtonStyleDebug", - defaultValue: "Feed Button Style Debug…" - ) - ) { - FeedButtonStyleDebugWindowController.shared.show() - } - Button( - String( - localized: "debug.menu.startupAppearanceDebug", - defaultValue: "Startup Appearance Debug…" - ) - ) { - StartupAppearanceDebugWindowController.shared.show() - } - Button("Menu Bar Extra Debug…") { - MenuBarExtraDebugWindowController.shared.show() - } - Button( - String( - localized: "debug.menu.aboutTitlebarDebug", - defaultValue: "About Titlebar Debug…" - ) - ) { - AppDelegate.shared?.debugWindowsCoordinator.showAboutTitlebarDebugWindow() - } - Button( - String( - localized: "debug.menu.titlebarLayoutDebug", - defaultValue: "Titlebar Layout Debug..." - ) - ) { - TitlebarLayoutDebugWindowController.shared.show() - } - Button("Sidebar Debug…") { - SidebarDebugWindowController.shared.show() - } - Button( - String( - localized: "debug.menu.splitButtonLayoutDebug", - defaultValue: "Split Button Layout Debug…" - ) - ) { - SplitButtonLayoutDebugWindowController.shared.show() - } - Button( - String( - localized: "debug.menu.tabBarBackdropLab", - defaultValue: "Tab Bar Backdrop Lab…" - ) - ) { - TabBarBackdropLabWindowController.shared.show() - } - Button("File Explorer Style Debug…") { - FileExplorerStyleDebugWindowController.shared.show() - } - Button( - String( - localized: "debug.menu.pdfPreviewChromeDebug", - defaultValue: "PDF Preview Chrome Debug…" - ) - ) { - PDFPreviewChromeDebugWindowController.shared.show() - } - Button("Open All Debug Windows") { - openAllDebugWindows() - } - } + DebugWindowsMenu() Menu( String( @@ -1427,26 +1311,6 @@ struct cmuxApp: App { private func showNotificationsPopover() { AppDelegate.shared?.toggleNotificationsPopover(animated: false) } - -#if DEBUG - private func openAllDebugWindows() { - DebugWindowControlsWindowController.shared.show() - BrowserImportHintDebugWindowController.shared.show() - BrowserProfilePopoverDebugWindowController.shared.show() - AppDelegate.shared?.debugWindowsCoordinator.showAboutTitlebarDebugWindow() - TitlebarLayoutDebugWindowController.shared.show() - SidebarDebugWindowController.shared.show() - BackgroundDebugWindowController.shared.show() - StartupAppearanceDebugWindowController.shared.show() - MenuBarExtraDebugWindowController.shared.show() - PDFPreviewChromeDebugWindowController.shared.show() - FeedPreviewWindowController.shared.show() - FeedTextEditorDebugWindowController.shared.show() - FeedButtonStyleDebugWindowController.shared.show() - BonsplitTabBarDebugWindowController.shared.show() - SplitButtonLayoutDebugWindowController.shared.show() - } -#endif } private struct MainWindowBootstrapView: View { @@ -1584,7 +1448,7 @@ private enum DebugWindowConfigSnapshot { } #if DEBUG -private final class DebugWindowControlsWindowController: ReleasingWindowController { +final class DebugWindowControlsWindowController: ReleasingWindowController { static let shared = DebugWindowControlsWindowController() override func makeWindow() -> NSWindow { @@ -1846,7 +1710,7 @@ private struct DebugWindowControlsView: View { } #endif -private final class BrowserImportHintDebugWindowController: ReleasingWindowController { +final class BrowserImportHintDebugWindowController: ReleasingWindowController { static let shared = BrowserImportHintDebugWindowController() override func makeWindow() -> NSWindow { @@ -1872,7 +1736,7 @@ private final class BrowserImportHintDebugWindowController: ReleasingWindowContr } } -private final class BrowserProfilePopoverDebugWindowController: ReleasingWindowController { +final class BrowserProfilePopoverDebugWindowController: ReleasingWindowController { static let shared = BrowserProfilePopoverDebugWindowController() override func makeWindow() -> NSWindow { @@ -2388,7 +2252,7 @@ extension Notification.Name { static let fileExplorerStyleDidChange = Notification.Name("fileExplorerStyleDidChange") } -private final class FileExplorerStyleDebugWindowController: ReleasingWindowController { +final class FileExplorerStyleDebugWindowController: ReleasingWindowController { static let shared = FileExplorerStyleDebugWindowController() private override init() { @@ -2423,7 +2287,7 @@ private final class FileExplorerStyleDebugWindowController: ReleasingWindowContr } } -private final class SidebarDebugWindowController: ReleasingWindowController { +final class SidebarDebugWindowController: ReleasingWindowController { static let shared = SidebarDebugWindowController() private override init() { @@ -2789,7 +2653,7 @@ private struct SidebarDebugView: View { // MARK: - Menu Bar Extra Debug Window -private final class MenuBarExtraDebugWindowController: ReleasingWindowController { +final class MenuBarExtraDebugWindowController: ReleasingWindowController { static let shared = MenuBarExtraDebugWindowController() private override init() { @@ -2961,7 +2825,7 @@ private struct MenuBarExtraDebugView: View { #if DEBUG // MARK: - Split Button Layout Debug Window -private final class SplitButtonLayoutDebugWindowController: ReleasingWindowController { +final class SplitButtonLayoutDebugWindowController: ReleasingWindowController { static let shared = SplitButtonLayoutDebugWindowController() override func makeWindow() -> NSWindow { @@ -3285,7 +3149,7 @@ private struct SplitButtonLayoutDebugView: View { // MARK: - Tab Bar Backdrop Lab Window -private final class TabBarBackdropLabWindowController: ReleasingWindowController { +final class TabBarBackdropLabWindowController: ReleasingWindowController { static let shared = TabBarBackdropLabWindowController() override func makeWindow() -> NSWindow { @@ -3918,7 +3782,7 @@ private struct TabBarBackdropLabTerminalPane: View { // MARK: - Background Debug Window -private final class BackgroundDebugWindowController: ReleasingWindowController { +final class BackgroundDebugWindowController: ReleasingWindowController { static let shared = BackgroundDebugWindowController() private override init() { @@ -4067,7 +3931,7 @@ private struct BackgroundDebugView: View { } } -private final class StartupAppearanceDebugWindowController: ReleasingWindowController { +final class StartupAppearanceDebugWindowController: ReleasingWindowController { static let shared = StartupAppearanceDebugWindowController() private override init() { diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index ba1b3007a4c7..56d7f4cac934 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -534,6 +534,7 @@ DEBDADADADADADADAD000001 /* DebugDogfoodCredentialResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEBDADADADADADADAD000002 /* DebugDogfoodCredentialResolver.swift */; }; DEBDADADADADADADAD000003 /* DebugDogfoodCredentialResolverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEBDADADADADADADAD000004 /* DebugDogfoodCredentialResolverTests.swift */; }; A500D010A1B2C3D4E5F60718 /* DebugLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = A500D011A1B2C3D4E5F60718 /* DebugLogging.swift */; }; + 6D3C42A16D3C42A16D3C42A1 /* DebugWindowsMenu.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D3C42A26D3C42A26D3C42A2 /* DebugWindowsMenu.swift */; }; A5001F000000000000000001 /* DetachedFolderDragIcon.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001F000000000000000002 /* DetachedFolderDragIcon.swift */; }; B05553C10000000000000001 /* DetachedFolderPathLookupCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = B05553C10000000000000002 /* DetachedFolderPathLookupCache.swift */; }; B0555303B0555303B0555303 /* DetachedFolderPathLookupCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0555304B0555304B0555304 /* DetachedFolderPathLookupCacheTests.swift */; }; @@ -1401,6 +1402,7 @@ 604500100000000000000003 /* WindowTitleTemplateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 604500100000000000000004 /* WindowTitleTemplateTests.swift */; }; E30760080000000000000002 /* WindowTmuxWorkspacePaneOverlayController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E30760080000000000000001 /* WindowTmuxWorkspacePaneOverlayController.swift */; }; A5001209 /* WindowToolbarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001219 /* WindowToolbarController.swift */; }; + 9A0B71D19A0B71D19A0B71D1 /* Workspace+AgentPIDOwnership.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A0B71D29A0B71D29A0B71D2 /* Workspace+AgentPIDOwnership.swift */; }; CA52B0150000000000000000 /* Workspace+CanvasLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA52C0150000000000000000 /* Workspace+CanvasLayout.swift */; }; C54860020000000000000001 /* Workspace+CmuxNavigationDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = C54860020000000000000002 /* Workspace+CmuxNavigationDescriptor.swift */; }; A5FB120D /* Workspace+CustomLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5FB120E /* Workspace+CustomLayout.swift */; }; @@ -2035,6 +2037,7 @@ DEBDADADADADADADAD000002 /* DebugDogfoodCredentialResolver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DebugDogfoodCredentialResolver.swift; sourceTree = ""; }; DEBDADADADADADADAD000004 /* DebugDogfoodCredentialResolverTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DebugDogfoodCredentialResolverTests.swift; sourceTree = ""; }; A500D011A1B2C3D4E5F60718 /* DebugLogging.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = App/DebugLogging.swift; sourceTree = ""; }; + 6D3C42A26D3C42A26D3C42A2 /* DebugWindowsMenu.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DebugWindowsMenu.swift; sourceTree = ""; }; A5001F000000000000000002 /* DetachedFolderDragIcon.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DetachedFolderDragIcon.swift; sourceTree = ""; }; B05553C10000000000000002 /* DetachedFolderPathLookupCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DetachedFolderPathLookupCache.swift; sourceTree = ""; }; B0555304B0555304B0555304 /* DetachedFolderPathLookupCacheTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DetachedFolderPathLookupCacheTests.swift; sourceTree = ""; }; @@ -2886,6 +2889,7 @@ 604500100000000000000004 /* WindowTitleTemplateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WindowTitleTemplateTests.swift; sourceTree = ""; }; E30760080000000000000001 /* WindowTmuxWorkspacePaneOverlayController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WindowTmuxWorkspacePaneOverlayController.swift; sourceTree = ""; }; A5001219 /* WindowToolbarController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WindowToolbarController.swift; sourceTree = ""; }; + 9A0B71D29A0B71D29A0B71D2 /* Workspace+AgentPIDOwnership.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+AgentPIDOwnership.swift"; sourceTree = ""; }; CA52C0150000000000000000 /* Workspace+CanvasLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+CanvasLayout.swift"; sourceTree = ""; }; C54860020000000000000002 /* Workspace+CmuxNavigationDescriptor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+CmuxNavigationDescriptor.swift"; sourceTree = ""; }; A5FB120E /* Workspace+CustomLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+CustomLayout.swift"; sourceTree = ""; }; @@ -3520,6 +3524,8 @@ F0ACC0DE000000000000000A /* Workspace+ForkAgentConversationAvailability.swift */, F0ACC0DE000000000000000C /* WorkspaceForkAgentConversationAvailability.swift */, F0ACC0DE0000000000000004 /* Workspace+ForkConversationContextMenu.swift */, + 6D3C42A26D3C42A26D3C42A2 /* DebugWindowsMenu.swift */, + 9A0B71D29A0B71D29A0B71D2 /* Workspace+AgentPIDOwnership.swift */, C3744E020000000000000001 /* Workspace+PanelLifecycle.swift */, 42C2726A34F27E7A43B77368 /* Workspace+CustomSidebarPullRequests.swift */, C7268001000000000000002 /* Workspace+CustomSidebarSnapshot.swift */, @@ -5271,6 +5277,7 @@ C57B00090000000000000001 /* CustomSidebarPanelView.swift in Sources */, DEBDADADADADADADAD000001 /* DebugDogfoodCredentialResolver.swift in Sources */, A500D010A1B2C3D4E5F60718 /* DebugLogging.swift in Sources */, + 6D3C42A16D3C42A16D3C42A1 /* DebugWindowsMenu.swift in Sources */, A5001F000000000000000001 /* DetachedFolderDragIcon.swift in Sources */, B05553C10000000000000001 /* DetachedFolderPathLookupCache.swift in Sources */, DE71CE000000000000000004 /* DeviceRegistryClient.swift in Sources */, @@ -5859,6 +5866,7 @@ 604500200000000000000001 /* WindowTitleTemplateContext.swift in Sources */, E30760080000000000000002 /* WindowTmuxWorkspacePaneOverlayController.swift in Sources */, A5001209 /* WindowToolbarController.swift in Sources */, + 9A0B71D19A0B71D19A0B71D1 /* Workspace+AgentPIDOwnership.swift in Sources */, CA52B0150000000000000000 /* Workspace+CanvasLayout.swift in Sources */, C54860020000000000000001 /* Workspace+CmuxNavigationDescriptor.swift in Sources */, A5FB120D /* Workspace+CustomLayout.swift in Sources */, From 302abddd9689ef31fb8de9e713a2e7b7a6bcf899 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 01:19:33 -0700 Subject: [PATCH 27/46] review fixes: workspace-scoped clear reaps displaced runtimes; port refresh on displaced exit; lab window Cmd+W lint - clear_status now routes through clearAgentRuntimes(forStatusKey:), reaping the bare key, every synthesized displacement key, and every pane's lifecycle for the key, honoring the whole-workspace contract (regression test testWorkspaceScopedStatusClearReapsDisplacedRuntimes). - clearAgentPID's non-owner exit-hook branch forwards refreshPorts when reaping the synthesized key, so PortScanner stops advertising a dead displaced agent's ports immediately. - register cmux.agentRowsVariantLab in cmuxAuxiliaryWindowIdentifiers (auxiliary window close-shortcut lint). --- .github/swift-file-length-budget.tsv | 2 +- ...inalController+ControlSidebarContext.swift | 5 +++- Sources/Workspace+AgentPIDOwnership.swift | 28 +++++++++++++++++ Sources/Workspace+PanelLifecycle.swift | 2 +- Sources/cmuxApp.swift | 1 + cmuxTests/PerAgentSidebarStatusRowTests.swift | 30 +++++++++++++++++++ 6 files changed, 65 insertions(+), 3 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 44ff482b6564..cbc265daa76f 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -21,7 +21,7 @@ 5915 cmuxTests/TerminalAndGhosttyTests.swift 5809 Sources/TextBoxInput.swift 5573 cmuxTests/BrowserConfigTests.swift -4627 Sources/cmuxApp.swift +4628 Sources/cmuxApp.swift 4482 Sources/Panels/FilePreviewPanel.swift 4367 cmuxTests/BrowserPanelTests.swift 4036 Sources/BrowserWindowPortal.swift diff --git a/Sources/TerminalController+ControlSidebarContext.swift b/Sources/TerminalController+ControlSidebarContext.swift index 3cf601e29d5c..009f747a5668 100644 --- a/Sources/TerminalController+ControlSidebarContext.swift +++ b/Sources/TerminalController+ControlSidebarContext.swift @@ -84,7 +84,10 @@ extension TerminalController: ControlSidebarContext { controlSidebarScheduleMutation(target: target) { _, tab in _ = tab.statusEntries.removeValue(forKey: key) _ = tab.clearPanelStatusEntries(statusKey: key) - tab.clearAgentPID(key: key) + // Bare shared keys can have been displaced onto synthesized + // panel-scoped keys; the workspace-scoped clear must reap those + // runtimes and lifecycles too, not just the exact bare key. + tab.clearAgentRuntimes(forStatusKey: key) } } diff --git a/Sources/Workspace+AgentPIDOwnership.swift b/Sources/Workspace+AgentPIDOwnership.swift index 311bd984486f..e9a816082a8b 100644 --- a/Sources/Workspace+AgentPIDOwnership.swift +++ b/Sources/Workspace+AgentPIDOwnership.swift @@ -60,6 +60,34 @@ extension Workspace { "\(statusKey).pane-\(panelId.uuidString)" } + /// Workspace-scoped removal of every runtime tracked for a status key: + /// the bare shared key, every synthesized displacement key, and every + /// pane's lifecycle for the key. This backs the `clear_status ` + /// contract ("removes the key from the whole workspace"). The liveness + /// sweep must NOT use this: it judges each pid key's process separately, + /// and a dead bare-key owner does not imply displaced siblings are dead. + func clearAgentRuntimes(forStatusKey statusKey: String, refreshPorts: Bool = true) { + var keysToClear = Set() + for key in agentPIDs.keys where agentStatusKey(forAgentPIDKey: key) == statusKey { + keysToClear.insert(key) + } + for key in agentPIDPanelIdsByKey.keys where agentStatusKey(forAgentPIDKey: key) == statusKey { + keysToClear.insert(key) + } + var didChange = false + for key in keysToClear { + if clearAgentPID(key: key, clearStatus: false, refreshPorts: false) { + didChange = true + } + } + if clearAgentLifecycle(key: statusKey) { + didChange = true + } + if didChange, refreshPorts { + refreshTrackedAgentPorts() + } + } + @discardableResult func clearOtherStructuredAgentRuntimes(onPanel panelId: UUID, keeping retainedKey: String) -> Bool { guard isStructuredAgentHookPIDKey(retainedKey) else { return false } diff --git a/Sources/Workspace+PanelLifecycle.swift b/Sources/Workspace+PanelLifecycle.swift index bb062e09852e..58a942b61ea4 100644 --- a/Sources/Workspace+PanelLifecycle.swift +++ b/Sources/Workspace+PanelLifecycle.swift @@ -240,7 +240,7 @@ extension Workspace { // instead of waiting for the liveness sweep. let synthesizedKey = Self.synthesizedDisplacedPIDKey(statusKey: statusKey, panelId: panelId) if agentPIDPanelIdsByKey[synthesizedKey] == panelId, - clearAgentPID(key: synthesizedKey, panelId: panelId, clearStatus: clearStatus, refreshPorts: false) { + clearAgentPID(key: synthesizedKey, panelId: panelId, clearStatus: clearStatus, refreshPorts: refreshPorts) { didChange = true } return didChange diff --git a/Sources/cmuxApp.swift b/Sources/cmuxApp.swift index 72591149831b..11dfef0ba4b0 100644 --- a/Sources/cmuxApp.swift +++ b/Sources/cmuxApp.swift @@ -1333,6 +1333,7 @@ private struct MainWindowBootstrapView: View { private let cmuxAuxiliaryWindowIdentifiers: Set = [ "cmux.settings", "cmux.about", + "cmux.agentRowsVariantLab", "cmux.licenses", "cmux.browser-popup", "cmux.browserProfilePopoverDebug", diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 2ee613f5e968..ebaf78df0501 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -453,4 +453,34 @@ struct PerAgentSidebarStatusRowTests { #expect(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"]?.value == "Running") #expect(workspace.sidebarAgentStatusRows().count == 2) } + + @Test + func testWorkspaceScopedStatusClearReapsDisplacedRuntimes() throws { + let workspace = Workspace() + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) + workspace.setAgentLifecycle(key: "claude_code", panelId: firstPanelId, lifecycle: .running) + workspace.recordAgentPID(key: "claude_code", pid: 222, panelId: secondPanelId, refreshPorts: false) + workspace.setAgentLifecycle(key: "claude_code", panelId: secondPanelId, lifecycle: .running) + #expect(workspace.sidebarAgentStatusRows().count == 2) + + // The `clear_status ` contract: remove the key from the WHOLE + // workspace. The displaced pane's synthesized runtime and both panes' + // lifecycles must go too, or its row reappears with lifecycle text. + _ = workspace.statusEntries.removeValue(forKey: "claude_code") + _ = workspace.clearPanelStatusEntries(statusKey: "claude_code") + workspace.clearAgentRuntimes(forStatusKey: "claude_code", refreshPorts: false) + + #expect(workspace.sidebarAgentStatusRows().isEmpty) + let synthesizedKey = Workspace.synthesizedDisplacedPIDKey(statusKey: "claude_code", panelId: firstPanelId) + #expect(workspace.agentPIDs[synthesizedKey] == nil) + #expect(workspace.agentPIDs["claude_code"] == nil) + #expect(workspace.agentPIDPanelIdsByKey.isEmpty) + #expect(workspace.agentPIDKeysByPanelId.isEmpty) + #expect(workspace.agentLifecycleStatesByPanelId[firstPanelId]?["claude_code"] == nil) + #expect(workspace.agentLifecycleStatesByPanelId[secondPanelId]?["claude_code"] == nil) + } } From 2cde0e4b7c584dbdd2422a34dea94b86e9db73d9 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 01:36:54 -0700 Subject: [PATCH 28/46] fix: different agent replacing a no-pid panel-scoped status drops the stale entry clearOtherStructuredAgentRuntimes only swept pid-owned keys, so a pane whose previous agent reported via set_status --panel without --pid kept that dead agent's row text after a different structured agent started on the pane (a nil-entry candidate loses to any entry in the row chooser). Replacement now also drops other structured panel-scoped entries and lifecycles on the pane, and the orphaned workspace-level slot when this pane was its last owner, mirroring pane close. Displacement/replacement tests move to their own PerAgentSidebarStatusDisplacementTests suite (file length budget). --- Sources/Workspace+AgentPIDOwnership.swift | 24 +++- Sources/Workspace+PanelLifecycle.swift | 2 +- cmux.xcodeproj/project.pbxproj | 4 + ...rAgentSidebarStatusDisplacementTests.swift | 117 ++++++++++++++++++ cmuxTests/PerAgentSidebarStatusRowTests.swift | 62 ---------- 5 files changed, 145 insertions(+), 64 deletions(-) create mode 100644 cmuxTests/PerAgentSidebarStatusDisplacementTests.swift diff --git a/Sources/Workspace+AgentPIDOwnership.swift b/Sources/Workspace+AgentPIDOwnership.swift index e9a816082a8b..8ec4b322ca58 100644 --- a/Sources/Workspace+AgentPIDOwnership.swift +++ b/Sources/Workspace+AgentPIDOwnership.swift @@ -91,6 +91,7 @@ extension Workspace { @discardableResult func clearOtherStructuredAgentRuntimes(onPanel panelId: UUID, keeping retainedKey: String) -> Bool { guard isStructuredAgentHookPIDKey(retainedKey) else { return false } + let retainedStatusKey = agentStatusKey(forAgentPIDKey: retainedKey) let staleKeys = agentPIDKeysByPanelId[panelId] ?? [] var didChange = false for staleKey in staleKeys where staleKey != retainedKey && isStructuredAgentHookPIDKey(staleKey) { @@ -98,11 +99,32 @@ extension Workspace { // key returning to a pane holding a synthesized displacement key): // keep the pane's status entry. A different agent type is a real // replacement: clear its status too. - let sameAgent = agentStatusKey(forAgentPIDKey: staleKey) == agentStatusKey(forAgentPIDKey: retainedKey) + let sameAgent = agentStatusKey(forAgentPIDKey: staleKey) == retainedStatusKey if clearAgentPID(key: staleKey, panelId: panelId, clearStatus: !sameAgent, refreshPorts: false) { didChange = true } } + // A pane can hold a panel-scoped structured status with NO recorded + // pid (`set_status --panel` without `--pid`), which the loop above + // never sees. A different structured agent replacing it on this pane + // must drop that entry and its lifecycle, or the row keeps showing + // the dead agent's text (nil-entry candidates lose to any entry in + // sidebarAgentStatusRows' comparator). Mirror pane close for the + // workspace-level slot: drop it when this pane was its last owner. + for statusKey in Set((statusEntriesByPanelId[panelId] ?? [:]).keys) + where statusKey != retainedStatusKey && Self.structuredAgentHookStatusKeys.contains(statusKey) { + if clearPanelStatusEntry(statusKey: statusKey, panelId: panelId) { + didChange = true + } + if clearAgentLifecycle(key: statusKey, panelId: panelId) { + didChange = true + } + if panelsOwningAgentStatusKey(statusKey).isEmpty, + !hasAgentRuntime(forStatusKey: statusKey), + statusEntries.removeValue(forKey: statusKey) != nil { + didChange = true + } + } return didChange } } diff --git a/Sources/Workspace+PanelLifecycle.swift b/Sources/Workspace+PanelLifecycle.swift index 58a942b61ea4..bf79831a020b 100644 --- a/Sources/Workspace+PanelLifecycle.swift +++ b/Sources/Workspace+PanelLifecycle.swift @@ -82,7 +82,7 @@ extension Workspace { return String(key[.. Bool { + func hasAgentRuntime(forStatusKey statusKey: String) -> Bool { for key in agentPIDs.keys where agentStatusKey(forAgentPIDKey: key) == statusKey { return true } diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 56d7f4cac934..e6c423dff879 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -873,6 +873,7 @@ 6313B6A0 /* PaneMemoryWarning.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6313B6A1 /* PaneMemoryWarning.swift */; }; E30760090000000000000002 /* PassthroughWindowOverlayContainerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E30760090000000000000001 /* PassthroughWindowOverlayContainerView.swift */; }; A5001425 /* PDFPreviewChromeDebugWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001424 /* PDFPreviewChromeDebugWindowController.swift */; }; + 5B21C4E15B21C4E15B21C4E1 /* PerAgentSidebarStatusDisplacementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B21C4E25B21C4E25B21C4E2 /* PerAgentSidebarStatusDisplacementTests.swift */; }; 2255A23ACD5B366E35B6ED0F /* PerAgentSidebarStatusPersistenceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EDCC62AF23B380D1227E261 /* PerAgentSidebarStatusPersistenceTests.swift */; }; DEC515B488104031B49F68F0 /* PerAgentSidebarStatusRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF3A0288F87945DC8889FE91 /* PerAgentSidebarStatusRowTests.swift */; }; D1F0A00400000000000000D1 /* PhoneForwardingMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1F0A00400000000000000D2 /* PhoneForwardingMode.swift */; }; @@ -2372,6 +2373,7 @@ 6313B6A1 /* PaneMemoryWarning.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PaneMemoryWarning.swift; sourceTree = ""; }; E30760090000000000000001 /* PassthroughWindowOverlayContainerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PassthroughWindowOverlayContainerView.swift; sourceTree = ""; }; A5001424 /* PDFPreviewChromeDebugWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/PDFPreviewChromeDebugWindowController.swift; sourceTree = ""; }; + 5B21C4E25B21C4E25B21C4E2 /* PerAgentSidebarStatusDisplacementTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerAgentSidebarStatusDisplacementTests.swift; sourceTree = ""; }; 3EDCC62AF23B380D1227E261 /* PerAgentSidebarStatusPersistenceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerAgentSidebarStatusPersistenceTests.swift; sourceTree = ""; }; EF3A0288F87945DC8889FE91 /* PerAgentSidebarStatusRowTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerAgentSidebarStatusRowTests.swift; sourceTree = ""; }; D1F0A00400000000000000D2 /* PhoneForwardingMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PhoneForwardingMode.swift; sourceTree = ""; }; @@ -4254,6 +4256,7 @@ A9E040000000000000000001 /* CodexAppServerSessionTests.swift */, D72260010000000000000002 /* AgentHibernationPortalVisibilityTests.swift */, D36A00020000000000000002 /* AgentHibernationTests.swift */, + 5B21C4E25B21C4E25B21C4E2 /* PerAgentSidebarStatusDisplacementTests.swift */, 3EDCC62AF23B380D1227E261 /* PerAgentSidebarStatusPersistenceTests.swift */, EF3A0288F87945DC8889FE91 /* PerAgentSidebarStatusRowTests.swift */, D36A00050000000000000002 /* RendererRealizationPlannerTests.swift */, @@ -6279,6 +6282,7 @@ A5E01203A1B2C3D4E5F60718 /* OpenCodeHookRegressionTests.swift in Sources */, C44550000000000000000001 /* PanelOwnedNativeViewSessionTests.swift in Sources */, 6313FACE0000000000000000 /* PaneMemoryGuardrailTests.swift in Sources */, + 5B21C4E15B21C4E15B21C4E1 /* PerAgentSidebarStatusDisplacementTests.swift in Sources */, 2255A23ACD5B366E35B6ED0F /* PerAgentSidebarStatusPersistenceTests.swift in Sources */, DEC515B488104031B49F68F0 /* PerAgentSidebarStatusRowTests.swift in Sources */, D1F0A00300000000000000C1 /* PhonePushPresenceGateTests.swift in Sources */, diff --git a/cmuxTests/PerAgentSidebarStatusDisplacementTests.swift b/cmuxTests/PerAgentSidebarStatusDisplacementTests.swift new file mode 100644 index 000000000000..edcc8e6d8639 --- /dev/null +++ b/cmuxTests/PerAgentSidebarStatusDisplacementTests.swift @@ -0,0 +1,117 @@ +import CmuxSidebar +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +/// Bare shared PID key displacement and same-pane agent replacement: a +/// claude-style hook reports ONE bare key per agent type per workspace, so +/// ownership moves between panes; displaced panes must keep their own rows, +/// workspace-scoped clears must reap synthesized displacement keys, and a +/// different agent replacing a no-pid panel-scoped status must drop it. +@MainActor +struct PerAgentSidebarStatusDisplacementTests { + private func makeEntry( + key: String, + value: String, + timestamp: Date = Date() + ) -> SidebarStatusEntry { + SidebarStatusEntry( + key: key, + value: value, + icon: "bolt.fill", + color: "#4C8DFF", + timestamp: timestamp + ) + } + + @Test + func testDisplacedBareKeyPaneKeepsRowWithItsOwnPid() throws { + let workspace = Workspace() + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + // Pane A reports first with the bare shared key (real claude hook shape). + workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) + workspace.setAgentLifecycle(key: "claude_code", panelId: firstPanelId, lifecycle: .running) + // Pane B's report displaces A's bare-key ownership. + workspace.recordAgentPID(key: "claude_code", pid: 222, panelId: secondPanelId, refreshPorts: false) + + let rows = workspace.sidebarAgentStatusRows() + #expect(rows.count == 2) + #expect(Set(rows.map(\.panelId)) == [firstPanelId, secondPanelId]) + // A's runtime moved to a synthesized key with its own pid intact, so + // the liveness sweep still owns its cleanup. + let synthesizedKey = Workspace.synthesizedDisplacedPIDKey(statusKey: "claude_code", panelId: firstPanelId) + #expect(workspace.agentPIDs[synthesizedKey] == 111) + #expect(workspace.agentPIDs["claude_code"] == 222) + #expect(workspace.agentLifecycleStatesByPanelId[firstPanelId]?["claude_code"] == .running) + + // A reports again: the bare key returns to A, the synthesized key is + // reaped, and A's panel-scoped entry survives the key-shape change. + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: firstPanelId) + workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) + #expect(workspace.agentPIDs[synthesizedKey] == nil) + #expect(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"]?.value == "Running") + #expect(workspace.sidebarAgentStatusRows().count == 2) + } + + @Test + func testWorkspaceScopedStatusClearReapsDisplacedRuntimes() throws { + let workspace = Workspace() + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) + workspace.setAgentLifecycle(key: "claude_code", panelId: firstPanelId, lifecycle: .running) + workspace.recordAgentPID(key: "claude_code", pid: 222, panelId: secondPanelId, refreshPorts: false) + workspace.setAgentLifecycle(key: "claude_code", panelId: secondPanelId, lifecycle: .running) + #expect(workspace.sidebarAgentStatusRows().count == 2) + + // The `clear_status ` contract: remove the key from the WHOLE + // workspace. The displaced pane's synthesized runtime and both panes' + // lifecycles must go too, or its row reappears with lifecycle text. + _ = workspace.statusEntries.removeValue(forKey: "claude_code") + _ = workspace.clearPanelStatusEntries(statusKey: "claude_code") + workspace.clearAgentRuntimes(forStatusKey: "claude_code", refreshPorts: false) + + #expect(workspace.sidebarAgentStatusRows().isEmpty) + let synthesizedKey = Workspace.synthesizedDisplacedPIDKey(statusKey: "claude_code", panelId: firstPanelId) + #expect(workspace.agentPIDs[synthesizedKey] == nil) + #expect(workspace.agentPIDs["claude_code"] == nil) + #expect(workspace.agentPIDPanelIdsByKey.isEmpty) + #expect(workspace.agentPIDKeysByPanelId.isEmpty) + #expect(workspace.agentLifecycleStatesByPanelId[firstPanelId]?["claude_code"] == nil) + #expect(workspace.agentLifecycleStatesByPanelId[secondPanelId]?["claude_code"] == nil) + } + + @Test + func testDifferentAgentReplacesNoPIDPanelScopedStatus() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + + // codex reported only a panel-scoped status (set_status --panel with + // no --pid) plus a lifecycle; it never recorded a pid on the pane. + workspace.statusEntries["codex"] = makeEntry(key: "codex", value: "Old codex text") + workspace.recordPanelStatusEntry(makeEntry(key: "codex", value: "Old codex text"), panelId: panelId) + workspace.setAgentLifecycle(key: "codex", panelId: panelId, lifecycle: .idle) + + // claude replaces it on the same pane: the stale codex entry, + // lifecycle, and orphaned workspace-level slot must all go, or the + // pane's row keeps showing the dead agent's text (a nil claude entry + // loses to any codex entry in the row chooser). + workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: panelId, refreshPorts: false) + + let rows = workspace.sidebarAgentStatusRows() + #expect(rows.map(\.statusKey) == ["claude_code"]) + #expect(workspace.statusEntriesByPanelId[panelId]?["codex"] == nil) + #expect(workspace.agentLifecycleStatesByPanelId[panelId]?["codex"] == nil) + #expect(workspace.statusEntries["codex"] == nil) + } +} diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index ebaf78df0501..25df21a49999 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -421,66 +421,4 @@ struct PerAgentSidebarStatusRowTests { #expect(runningOnly.accentColorHex == "#4C8DFF") #expect(SidebarAgentStatusRowsSummary(rows: [row(lifecycle: .idle)]).accentColorHex == nil) } - - @Test - func testDisplacedBareKeyPaneKeepsRowWithItsOwnPid() throws { - let workspace = Workspace() - let firstPanelId = try #require(workspace.focusedPanelId) - let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) - let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id - - // Pane A reports first with the bare shared key (real claude hook shape). - workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) - workspace.setAgentLifecycle(key: "claude_code", panelId: firstPanelId, lifecycle: .running) - // Pane B's report displaces A's bare-key ownership. - workspace.recordAgentPID(key: "claude_code", pid: 222, panelId: secondPanelId, refreshPorts: false) - - let rows = workspace.sidebarAgentStatusRows() - #expect(rows.count == 2) - #expect(Set(rows.map(\.panelId)) == [firstPanelId, secondPanelId]) - // A's runtime moved to a synthesized key with its own pid intact, so - // the liveness sweep still owns its cleanup. - let synthesizedKey = Workspace.synthesizedDisplacedPIDKey(statusKey: "claude_code", panelId: firstPanelId) - #expect(workspace.agentPIDs[synthesizedKey] == 111) - #expect(workspace.agentPIDs["claude_code"] == 222) - #expect(workspace.agentLifecycleStatesByPanelId[firstPanelId]?["claude_code"] == .running) - - // A reports again: the bare key returns to A, the synthesized key is - // reaped, and A's panel-scoped entry survives the key-shape change. - workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: firstPanelId) - workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) - #expect(workspace.agentPIDs[synthesizedKey] == nil) - #expect(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"]?.value == "Running") - #expect(workspace.sidebarAgentStatusRows().count == 2) - } - - @Test - func testWorkspaceScopedStatusClearReapsDisplacedRuntimes() throws { - let workspace = Workspace() - let firstPanelId = try #require(workspace.focusedPanelId) - let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) - let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id - - workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) - workspace.setAgentLifecycle(key: "claude_code", panelId: firstPanelId, lifecycle: .running) - workspace.recordAgentPID(key: "claude_code", pid: 222, panelId: secondPanelId, refreshPorts: false) - workspace.setAgentLifecycle(key: "claude_code", panelId: secondPanelId, lifecycle: .running) - #expect(workspace.sidebarAgentStatusRows().count == 2) - - // The `clear_status ` contract: remove the key from the WHOLE - // workspace. The displaced pane's synthesized runtime and both panes' - // lifecycles must go too, or its row reappears with lifecycle text. - _ = workspace.statusEntries.removeValue(forKey: "claude_code") - _ = workspace.clearPanelStatusEntries(statusKey: "claude_code") - workspace.clearAgentRuntimes(forStatusKey: "claude_code", refreshPorts: false) - - #expect(workspace.sidebarAgentStatusRows().isEmpty) - let synthesizedKey = Workspace.synthesizedDisplacedPIDKey(statusKey: "claude_code", panelId: firstPanelId) - #expect(workspace.agentPIDs[synthesizedKey] == nil) - #expect(workspace.agentPIDs["claude_code"] == nil) - #expect(workspace.agentPIDPanelIdsByKey.isEmpty) - #expect(workspace.agentPIDKeysByPanelId.isEmpty) - #expect(workspace.agentLifecycleStatesByPanelId[firstPanelId]?["claude_code"] == nil) - #expect(workspace.agentLifecycleStatesByPanelId[secondPanelId]?["claude_code"] == nil) - } } From 11434ca59a2ca97c89844a97e2925c3ab2e2bb69 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 02:04:56 -0700 Subject: [PATCH 29/46] fix: only the synthesized displacement key keeps a pane's status entry across same-agent key changes The blanket same-agent keep from the displacement commit regressed testAgentReplacementOnSamePanelKeepsFreshPanelEntry (masked by a green shard, https://github.com/manaflow-ai/cmux/issues/7471): a NEW session of the same agent type under a different suffixed key must clear the pane's old panel-scoped entry, like before. Keep the entry only when the stale key is this pane's own synthesized displacement key (bare key returning after displacement), in both recordAgentPIDOwnership and clearOtherStructuredAgentRuntimes. --- Sources/Workspace+AgentPIDOwnership.swift | 26 +++++++++++++---------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/Sources/Workspace+AgentPIDOwnership.swift b/Sources/Workspace+AgentPIDOwnership.swift index 8ec4b322ca58..24440147a17d 100644 --- a/Sources/Workspace+AgentPIDOwnership.swift +++ b/Sources/Workspace+AgentPIDOwnership.swift @@ -24,16 +24,18 @@ extension Workspace { } if isStructuredAgentHookPIDKey(key) { let statusKey = agentStatusKey(forAgentPIDKey: key) + let synthesizedKey = Self.synthesizedDisplacedPIDKey(statusKey: statusKey, panelId: panelId) let stalePanelKeys = agentPIDKeysByPanelId[panelId]?.filter { $0 != key && isStructuredAgentHookPIDKey($0) } ?? [] for staleKey in stalePanelKeys { - // A stale key for the SAME agent type is a key-shape change - // (bare key returning to a pane that holds a synthesized - // displacement key): keep the pane's status entry. A different - // agent type is a real replacement: clear its status too. - let sameAgent = agentStatusKey(forAgentPIDKey: staleKey) == statusKey - _ = clearAgentPID(key: staleKey, panelId: panelId, clearStatus: !sameAgent, refreshPorts: false) + // Keep the pane's status entry ONLY for the key-shape change + // (the bare key returning to a pane holding this pane's own + // synthesized displacement key). Anything else, including a + // NEW session of the same agent type under a different + // suffixed key, is a real replacement: clear its status too. + let keepEntry = staleKey == synthesizedKey + _ = clearAgentPID(key: staleKey, panelId: panelId, clearStatus: !keepEntry, refreshPorts: false) } } agentPIDPanelIdsByKey[key] = panelId @@ -92,15 +94,17 @@ extension Workspace { func clearOtherStructuredAgentRuntimes(onPanel panelId: UUID, keeping retainedKey: String) -> Bool { guard isStructuredAgentHookPIDKey(retainedKey) else { return false } let retainedStatusKey = agentStatusKey(forAgentPIDKey: retainedKey) + let synthesizedKey = Self.synthesizedDisplacedPIDKey(statusKey: retainedStatusKey, panelId: panelId) let staleKeys = agentPIDKeysByPanelId[panelId] ?? [] var didChange = false for staleKey in staleKeys where staleKey != retainedKey && isStructuredAgentHookPIDKey(staleKey) { - // A stale key for the SAME agent type is a key-shape change (bare - // key returning to a pane holding a synthesized displacement key): - // keep the pane's status entry. A different agent type is a real + // Keep the pane's status entry ONLY for the key-shape change (the + // bare key returning to a pane holding this pane's own synthesized + // displacement key). Anything else, including a NEW session of the + // same agent type under a different suffixed key, is a real // replacement: clear its status too. - let sameAgent = agentStatusKey(forAgentPIDKey: staleKey) == retainedStatusKey - if clearAgentPID(key: staleKey, panelId: panelId, clearStatus: !sameAgent, refreshPorts: false) { + let keepEntry = staleKey == synthesizedKey + if clearAgentPID(key: staleKey, panelId: panelId, clearStatus: !keepEntry, refreshPorts: false) { didChange = true } } From bce1be207b5f9eb63ea0ce5b0029067455131d84 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 02:19:09 -0700 Subject: [PATCH 30/46] fix: same-runtime key-shape change preserves the pane's lifecycle Routing the synthesized-to-bare rekey through clearAgentPID cleared the pane's lifecycle even with clearStatus: false, blanking the state dot and summary counts until the next lifecycle hook. The keep path now reaps only the synthesized key's pid bookkeeping (pids, identities, ownership); entry and lifecycle survive. Displacement test extended to lock this in. --- Sources/Workspace+AgentPIDOwnership.swift | 55 ++++++++++++++----- ...rAgentSidebarStatusDisplacementTests.swift | 4 ++ 2 files changed, 45 insertions(+), 14 deletions(-) diff --git a/Sources/Workspace+AgentPIDOwnership.swift b/Sources/Workspace+AgentPIDOwnership.swift index 24440147a17d..0286ba87046c 100644 --- a/Sources/Workspace+AgentPIDOwnership.swift +++ b/Sources/Workspace+AgentPIDOwnership.swift @@ -29,13 +29,17 @@ extension Workspace { $0 != key && isStructuredAgentHookPIDKey($0) } ?? [] for staleKey in stalePanelKeys { - // Keep the pane's status entry ONLY for the key-shape change - // (the bare key returning to a pane holding this pane's own - // synthesized displacement key). Anything else, including a - // NEW session of the same agent type under a different - // suffixed key, is a real replacement: clear its status too. - let keepEntry = staleKey == synthesizedKey - _ = clearAgentPID(key: staleKey, panelId: panelId, clearStatus: !keepEntry, refreshPorts: false) + // The key-shape change (bare key returning to a pane holding + // this pane's own synthesized displacement key) reaps only the + // pid bookkeeping: the same runtime keeps reporting, so its + // status entry AND lifecycle survive. Anything else, including + // a NEW session of the same agent type under a different + // suffixed key, is a real replacement: clear everything. + if staleKey == synthesizedKey { + _ = reapSynthesizedDisplacementKeyPreservingRow(staleKey) + } else { + _ = clearAgentPID(key: staleKey, panelId: panelId, clearStatus: true, refreshPorts: false) + } } } agentPIDPanelIdsByKey[key] = panelId @@ -62,6 +66,25 @@ extension Workspace { "\(statusKey).pane-\(panelId.uuidString)" } + /// Removes ONLY the pid bookkeeping for a pane's synthesized displacement + /// key. The pane's status entry and lifecycle survive: the same runtime is + /// re-keying back to the bare key, not exiting. + @discardableResult + private func reapSynthesizedDisplacementKeyPreservingRow(_ synthesizedKey: String) -> Bool { + var didChange = false + if agentPIDs.removeValue(forKey: synthesizedKey) != nil { + didChange = true + } + if agentPIDProcessIdentitiesByKey.removeValue(forKey: synthesizedKey) != nil { + didChange = true + } + if agentPIDPanelIdsByKey[synthesizedKey] != nil { + removeAgentPIDOwnership(key: synthesizedKey) + didChange = true + } + return didChange + } + /// Workspace-scoped removal of every runtime tracked for a status key: /// the bare shared key, every synthesized displacement key, and every /// pane's lifecycle for the key. This backs the `clear_status ` @@ -98,13 +121,17 @@ extension Workspace { let staleKeys = agentPIDKeysByPanelId[panelId] ?? [] var didChange = false for staleKey in staleKeys where staleKey != retainedKey && isStructuredAgentHookPIDKey(staleKey) { - // Keep the pane's status entry ONLY for the key-shape change (the - // bare key returning to a pane holding this pane's own synthesized - // displacement key). Anything else, including a NEW session of the - // same agent type under a different suffixed key, is a real - // replacement: clear its status too. - let keepEntry = staleKey == synthesizedKey - if clearAgentPID(key: staleKey, panelId: panelId, clearStatus: !keepEntry, refreshPorts: false) { + // The key-shape change (bare key returning to a pane holding this + // pane's own synthesized displacement key) reaps only the pid + // bookkeeping: the same runtime keeps reporting, so its status + // entry AND lifecycle survive. Anything else, including a NEW + // session of the same agent type under a different suffixed key, + // is a real replacement: clear everything. + if staleKey == synthesizedKey { + if reapSynthesizedDisplacementKeyPreservingRow(staleKey) { + didChange = true + } + } else if clearAgentPID(key: staleKey, panelId: panelId, clearStatus: true, refreshPorts: false) { didChange = true } } diff --git a/cmuxTests/PerAgentSidebarStatusDisplacementTests.swift b/cmuxTests/PerAgentSidebarStatusDisplacementTests.swift index edcc8e6d8639..651b3ed01846 100644 --- a/cmuxTests/PerAgentSidebarStatusDisplacementTests.swift +++ b/cmuxTests/PerAgentSidebarStatusDisplacementTests.swift @@ -58,6 +58,10 @@ struct PerAgentSidebarStatusDisplacementTests { workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) #expect(workspace.agentPIDs[synthesizedKey] == nil) #expect(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"]?.value == "Running") + // The key-shape change is the SAME runtime re-keying, not an exit: + // the pane's lifecycle must survive too, or the state dot and summary + // counts go blank until the next lifecycle hook. + #expect(workspace.agentLifecycleStatesByPanelId[firstPanelId]?["claude_code"] == .running) #expect(workspace.sidebarAgentStatusRows().count == 2) } From 5e4065178c69e8843c4a5faa2aa817353f922b95 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 12:54:03 -0700 Subject: [PATCH 31/46] sidebar: graphite prototype (picked design G) Graphite elevated selection card (neutral, auto-contrast foreground) in place of the accent-colored selection, in-card agents accordion under the workspace title, and a periwinkle accent bar + tint on the ACTIVE agent row (the workspace's focused pane), keeping blue/orange dots as the only status colors. Lives behind the debug variant lab as the new 'graphite' case. --- Resources/Localizable.xcstrings | 85 ++++++++++ Sources/ContentView.swift | 25 ++- Sources/SidebarAgentRowsVariantLab.swift | 5 + Sources/SidebarAgentStatusRowViews.swift | 189 ++++++++++++++++++++++- 4 files changed, 302 insertions(+), 2 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index f02fff452f9e..bb3a1f44b431 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -69656,6 +69656,40 @@ } } }, + "debug.agentRows.variant.graphite": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Graphite prototype (picked)" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "グラファイト試作(採用案)" + } + } + } + }, + "debug.agentRows.variant.graphite.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Graphite selection card, in-card accordion, accent bar on the active (focused) agent." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "グラファイトの選択カード、カード内アコーディオン、アクティブなエージェントにアクセントバー。" + } + } + } + }, "debug.agentRows.variant.globalSection": { "extractionState": "manual", "localizations": { @@ -194206,6 +194240,57 @@ } } }, + "sidebar.agentStatus.word.idle": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "idle" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "待機" + } + } + } + }, + "sidebar.agentStatus.word.waiting": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "waiting" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "入力待ち" + } + } + } + }, + "sidebar.agentStatus.word.working": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "working" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "作業中" + } + } + } + }, "sidebar.browserStack.closeGroup": { "extractionState": "manual", "localizations": { diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index e5ee2e3f15e3..5aa441441954 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -13357,6 +13357,12 @@ struct TabItemView: View, Equatable { settings.activeTabIndicatorStyle } + // Debug lab observation: bounded (it mutates only on explicit picks in + // the Agent Rows Style window) and removed with the lab once a final + // design ships. Needed here because the graphite prototype restyles the + // workspace card's own selection background and border. + @ObservedObject private var agentRowsVariantStore = SidebarAgentRowsVariantStore.shared + private var isActive: Bool { observedIsActive ?? (tabManager.selectedTabId == tab.id) } @@ -13370,7 +13376,16 @@ struct TabItemView: View, Equatable { } private var selectedWorkspaceBackgroundNSColor: NSColor { - sidebarSelectedWorkspaceBackgroundNSColor( + // Debug lab "graphite" prototype: neutral elevated selection instead + // of the accent color, so agent state dots stay the only hues on the + // card. The foreground helper below auto-contrasts on it. Dies with + // the variant lab once a final design ships. + if agentRowsVariantStore.variant == .graphite { + return colorScheme == .dark + ? NSColor(calibratedWhite: 0.24, alpha: 1.0) + : NSColor(calibratedWhite: 0.82, alpha: 1.0) + } + return sidebarSelectedWorkspaceBackgroundNSColor( for: colorScheme, sidebarSelectionColorHex: sidebarSelectionColorHex ) @@ -13432,6 +13447,9 @@ struct TabItemView: View, Equatable { } private var activeBorderLineWidth: CGFloat { + if agentRowsVariantStore.variant == .graphite { + return isActive ? 1 : 0 + } switch activeTabIndicatorStyle { case .leftRail: return 0 @@ -13442,6 +13460,9 @@ struct TabItemView: View, Equatable { private var activeBorderColor: Color { guard isActive else { return .clear } + if agentRowsVariantStore.variant == .graphite { + return Color.primary.opacity(0.18) + } switch activeTabIndicatorStyle { case .leftRail: return .clear @@ -13810,9 +13831,11 @@ struct TabItemView: View, Equatable { // Renders only while an in-card debug variant is selected. SidebarAgentStatusInCardRows( rows: workspaceSnapshot.agentStatusRows, + activePanelId: tab.focusedPanelId, isActive: usesInvertedActiveForeground, activeForegroundColor: activeSecondaryColor(0.95), fontScale: fontScale, + onFocus: { updateSelection() }, onFocusPanel: { panelId in updateSelection() tab.focusPanel(panelId) diff --git a/Sources/SidebarAgentRowsVariantLab.swift b/Sources/SidebarAgentRowsVariantLab.swift index 28162d4d72e7..fd85fe1c00e1 100644 --- a/Sources/SidebarAgentRowsVariantLab.swift +++ b/Sources/SidebarAgentRowsVariantLab.swift @@ -6,6 +6,7 @@ import SwiftUI /// UserDefaults. This is a dogfood decision aid; once a winner is picked the /// losing variants get deleted and the store collapses to a constant. enum SidebarAgentRowsVariant: String, CaseIterable, Identifiable { + case graphite case belowAccordion case belowFlat case belowTree @@ -22,6 +23,8 @@ enum SidebarAgentRowsVariant: String, CaseIterable, Identifiable { var displayName: String { switch self { + case .graphite: + return String(localized: "debug.agentRows.variant.graphite", defaultValue: "Graphite prototype (picked)") case .belowAccordion: return String(localized: "debug.agentRows.variant.belowAccordion", defaultValue: "Below card · accordion") case .belowFlat: @@ -41,6 +44,8 @@ enum SidebarAgentRowsVariant: String, CaseIterable, Identifiable { var detail: String { switch self { + case .graphite: + return String(localized: "debug.agentRows.variant.graphite.detail", defaultValue: "Graphite selection card, in-card accordion, accent bar on the active (focused) agent.") case .belowAccordion: return String(localized: "debug.agentRows.variant.belowAccordion.detail", defaultValue: "Summary header folds the rows; each row is its own button.") case .belowFlat: diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index ce98890783f6..5a760353d204 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -41,7 +41,7 @@ struct SidebarAgentStatusRows: View { } case .belowChips: SidebarAgentChipsFlow(rows: rows, fontScale: fontScale, onFocusPanel: onFocusPanel) - case .inCardRows, .inCardCompact, .globalSection: + case .graphite, .inCardRows, .inCardCompact, .globalSection: EmptyView() } } @@ -98,15 +98,27 @@ struct SidebarAgentStatusRows: View { /// nothing for the below-card and global variants. struct SidebarAgentStatusInCardRows: View { let rows: [SidebarAgentStatusRow] + let activePanelId: UUID? let isActive: Bool let activeForegroundColor: Color let fontScale: CGFloat + let onFocus: () -> Void let onFocusPanel: (UUID) -> Void @ObservedObject private var variantStore = SidebarAgentRowsVariantStore.shared var body: some View { switch variantStore.variant { + case .graphite: + SidebarAgentStatusGraphiteRows( + rows: rows, + activePanelId: activePanelId, + isActive: isActive, + activeForegroundColor: activeForegroundColor, + fontScale: fontScale, + onFocus: onFocus, + onFocusPanel: onFocusPanel + ) case .inCardRows: VStack(alignment: .leading, spacing: 2) { ForEach(rows) { row in @@ -249,6 +261,20 @@ enum SidebarAgentRowStateStyle { return Color(hex: raw) } + /// Short right-aligned state word for dense layouts. + static func stateWord(for row: SidebarAgentStatusRow) -> String? { + switch row.lifecycle { + case .running: + return String(localized: "sidebar.agentStatus.word.working", defaultValue: "working") + case .needsInput: + return String(localized: "sidebar.agentStatus.word.waiting", defaultValue: "waiting") + case .idle: + return String(localized: "sidebar.agentStatus.word.idle", defaultValue: "idle") + case .unknown, nil: + return nil + } + } + static func lifecycleText(for row: SidebarAgentStatusRow) -> String? { switch row.lifecycle { case .running: @@ -413,3 +439,164 @@ struct SidebarAgentStatusEntryRowView: View { [primaryText, statusLineText].compactMap { $0 }.joined(separator: " · ") } } + + +/// The picked design (round-2 mock "G"): in-card accordion under the +/// workspace title, one row per agent with a right-aligned state word, and a +/// periwinkle accent bar + tint marking the ACTIVE agent (the workspace's +/// focused pane). Selection styling of the card itself is handled by +/// `TabItemView` (graphite instead of the blue selection) while this variant +/// is active. +struct SidebarAgentStatusGraphiteRows: View { + static let accent = Color(red: 124 / 255, green: 140 / 255, blue: 248 / 255) + + let rows: [SidebarAgentStatusRow] + let activePanelId: UUID? + let isActive: Bool + let activeForegroundColor: Color + let fontScale: CGFloat + let onFocus: () -> Void + let onFocusPanel: (UUID) -> Void + + @State private var isCollapsed = false + + var body: some View { + VStack(alignment: .leading, spacing: 1) { + header + if !isCollapsed { + ForEach(rows) { row in + SidebarAgentGraphiteRow( + row: row, + isActiveAgent: row.panelId == activePanelId, + isActive: isActive, + activeForegroundColor: activeForegroundColor, + fontScale: fontScale, + onFocusPanel: onFocusPanel + ) + } + } + } + .padding(.top, 3) + } + + private var header: some View { + let summary = SidebarAgentStatusRowsSummary(rows: rows) + return Button { + onFocus() + withAnimation(.easeInOut(duration: 0.15)) { + isCollapsed.toggle() + } + } label: { + HStack(spacing: 4) { + CmuxSystemSymbolImage( + magnified: isCollapsed ? "chevron.right" : "chevron.down", + pointSize: 6.5 * fontScale, + weight: .semibold + ) + .foregroundColor(secondaryColor.opacity(0.8)) + if isCollapsed, let accent = summary.accentColorHex, let color = Color(hex: accent) { + Circle() + .fill(color) + .frame(width: 5 * fontScale, height: 5 * fontScale) + } + Text(summary.text) + .cmuxFont(size: 9.5 * fontScale, weight: .semibold) + .foregroundColor(secondaryColor) + .lineLimit(1) + Spacer(minLength: 0) + } + .padding(.vertical, 1) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .safeHelp(summary.text) + } + + private var secondaryColor: Color { + isActive ? activeForegroundColor.opacity(0.7) : .secondary + } +} + +private struct SidebarAgentGraphiteRow: View { + let row: SidebarAgentStatusRow + let isActiveAgent: Bool + let isActive: Bool + let activeForegroundColor: Color + let fontScale: CGFloat + let onFocusPanel: (UUID) -> Void + + @State private var isHovering = false + + var body: some View { + Button { + onFocusPanel(row.panelId) + } label: { + HStack(spacing: 6) { + SidebarAgentBrandIcon(row: row, fontScale: fontScale) + Text(row.paneLabel ?? SidebarAgentRowStateStyle.agentDisplayName(statusKey: row.statusKey)) + .cmuxFont(size: 10.5 * fontScale, weight: .medium) + .foregroundColor(nameColor) + .lineLimit(1) + .truncationMode(.middle) + Spacer(minLength: 4) + if let stateColor = SidebarAgentRowStateStyle.stateColor(for: row) { + Circle() + .fill(stateColor) + .frame(width: 5 * fontScale, height: 5 * fontScale) + } + if let word = SidebarAgentRowStateStyle.stateWord(for: row) { + Text(word) + .cmuxFont(size: 9.5 * fontScale) + .foregroundColor(stateWordColor) + .lineLimit(1) + } + } + .padding(.vertical, 3) + .padding(.horizontal, 7) + .frame(maxWidth: .infinity, alignment: .leading) + .background(rowBackground) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .onHover { isHovering = $0 } + .safeHelp(tooltip) + } + + @ViewBuilder + private var rowBackground: some View { + if isActiveAgent { + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(SidebarAgentStatusGraphiteRows.accent.opacity(0.16)) + .overlay(alignment: .leading) { + RoundedRectangle(cornerRadius: 1.5) + .fill(SidebarAgentStatusGraphiteRows.accent) + .frame(width: 2.5) + .padding(.vertical, 2) + } + } else { + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(Color.primary.opacity(isHovering ? 0.07 : 0)) + } + } + + private var nameColor: Color { + if isActiveAgent { + return isActive ? activeForegroundColor : Color(red: 205 / 255, green: 212 / 255, blue: 1) + } + return isActive ? activeForegroundColor.opacity(0.92) : .primary.opacity(0.85) + } + + private var stateWordColor: Color { + if row.lifecycle == .needsInput { + return Color(hex: "#FF9F0A") ?? .orange + } + return isActive ? activeForegroundColor.opacity(0.6) : .secondary.opacity(0.8) + } + + private var tooltip: String { + [ + row.paneLabel ?? SidebarAgentRowStateStyle.agentDisplayName(statusKey: row.statusKey), + SidebarAgentRowStateStyle.statusText(for: row), + ].compactMap { $0 }.joined(separator: " · ") + } +} From e08a88a5f35332e23e301842b91815be57d78bff Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 13:04:11 -0700 Subject: [PATCH 32/46] graphite prototype: fill the card at the real background source, active bar only in the selected workspace --- Sources/ContentView.swift | 8 ++++++++ Sources/SidebarAgentStatusRowViews.swift | 5 ++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 5aa441441954..52136b6bbf9d 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -14575,6 +14575,14 @@ struct TabItemView: View, Equatable { } private var backgroundColor: Color { + // Debug lab "graphite" prototype: the selected card fills with a + // neutral elevated graphite instead of the accent color. Dies with + // the variant lab once a final design ships. + if agentRowsVariantStore.variant == .graphite, isActive { + return Color(nsColor: colorScheme == .dark + ? NSColor(calibratedWhite: 0.24, alpha: 1.0) + : NSColor(calibratedWhite: 0.82, alpha: 1.0)) + } let style = sidebarWorkspaceRowBackgroundStyle( activeTabIndicatorStyle: activeTabIndicatorStyle, isActive: isActive, diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index 5a760353d204..7d84b874766c 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -467,7 +467,10 @@ struct SidebarAgentStatusGraphiteRows: View { ForEach(rows) { row in SidebarAgentGraphiteRow( row: row, - isActiveAgent: row.panelId == activePanelId, + // Only the selected workspace hosts the globally + // focused pane; unselected workspaces remember a + // focus but the "camera" is not on them. + isActiveAgent: isActive && row.panelId == activePanelId, isActive: isActive, activeForegroundColor: activeForegroundColor, fontScale: fontScale, From caf3660ddb1674513b026503d65199f6d5229486 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 14:27:16 -0700 Subject: [PATCH 33/46] graphite prototype: judge-note cleanups (doc count, unreachable color branch) --- Sources/SidebarAgentRowsVariantLab.swift | 2 +- Sources/SidebarAgentStatusRowViews.swift | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Sources/SidebarAgentRowsVariantLab.swift b/Sources/SidebarAgentRowsVariantLab.swift index fd85fe1c00e1..403b838b0acd 100644 --- a/Sources/SidebarAgentRowsVariantLab.swift +++ b/Sources/SidebarAgentRowsVariantLab.swift @@ -1,7 +1,7 @@ import AppKit import SwiftUI -/// Debug explorer for the per-agent sidebar row presentation: seven variants +/// Debug explorer for the per-agent sidebar row presentation: eight variants /// switchable live from Debug > "Agent Rows Style…", persisted in /// UserDefaults. This is a dogfood decision aid; once a winner is picked the /// losing variants get deleted and the store collapses to a constant. diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index 7d84b874766c..e114f50b7d05 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -583,8 +583,9 @@ private struct SidebarAgentGraphiteRow: View { } private var nameColor: Color { + // isActiveAgent implies isActive (gated at the call site). if isActiveAgent { - return isActive ? activeForegroundColor : Color(red: 205 / 255, green: 212 / 255, blue: 1) + return activeForegroundColor } return isActive ? activeForegroundColor.opacity(0.92) : .primary.opacity(0.85) } From 001a41828464149f123a11852869f15f62790064 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 14:47:09 -0700 Subject: [PATCH 34/46] graphite v2: borderless state-tinted selection, custom colors respected, active agent darker same hue Selected card fill = the workspace's own color (custom color when set, else the selection color) pulled far toward the sidebar base; no border. The active agent row fills with an even darker shade of that same hue, replacing the periwinkle bar. --- Sources/ContentView.swift | 58 ++++++++++++++++++------ Sources/SidebarAgentStatusRowViews.swift | 17 ++++--- 2 files changed, 51 insertions(+), 24 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 52136b6bbf9d..858daa950710 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -13376,14 +13376,13 @@ struct TabItemView: View, Equatable { } private var selectedWorkspaceBackgroundNSColor: NSColor { - // Debug lab "graphite" prototype: neutral elevated selection instead - // of the accent color, so agent state dots stay the only hues on the - // card. The foreground helper below auto-contrasts on it. Dies with - // the variant lab once a final design ships. + // Debug lab "graphite" prototype v2: the selection is a dark tint of + // the workspace's own color (custom color when set, else the user's + // selection color), borderless. The foreground helper below + // auto-contrasts on it. Dies with the variant lab once a final design + // ships. if agentRowsVariantStore.variant == .graphite { - return colorScheme == .dark - ? NSColor(calibratedWhite: 0.24, alpha: 1.0) - : NSColor(calibratedWhite: 0.82, alpha: 1.0) + return graphiteSelectionFillNSColor } return sidebarSelectedWorkspaceBackgroundNSColor( for: colorScheme, @@ -13391,6 +13390,37 @@ struct TabItemView: View, Equatable { ) } + /// Graphite prototype: selected-card fill = the workspace's color pulled + /// far toward the sidebar base, so custom colors survive as a tint + /// instead of a saturated slab. + private var graphiteSelectionFillNSColor: NSColor { + let base: NSColor = workspaceSnapshot.customColorHex.flatMap { + WorkspaceTabColorSettings.displayNSColor( + hex: $0, + colorScheme: colorScheme, + forceBright: false + ) + } ?? sidebarSelectedWorkspaceBackgroundNSColor( + for: colorScheme, + sidebarSelectionColorHex: sidebarSelectionColorHex + ) + let srgbBase = base.usingColorSpace(.sRGB) ?? base + let dimBase = colorScheme == .dark + ? NSColor(calibratedWhite: 0.14, alpha: 1.0) + : NSColor(calibratedWhite: 0.92, alpha: 1.0) + return srgbBase.blended(withFraction: colorScheme == .dark ? 0.66 : 0.45, of: dimBase) ?? srgbBase + } + + /// Graphite prototype: the ACTIVE agent row is an even darker shade of + /// the same selection hue. + private var graphiteActiveAgentRowNSColor: NSColor { + let fill = graphiteSelectionFillNSColor + let deep = colorScheme == .dark + ? NSColor.black + : NSColor(calibratedWhite: 0.5, alpha: 1.0) + return fill.blended(withFraction: 0.38, of: deep) ?? fill + } + private func selectedWorkspaceForegroundNSColor(opacity: CGFloat) -> NSColor { sidebarSelectedWorkspaceForegroundNSColor( on: selectedWorkspaceBackgroundNSColor, @@ -13448,7 +13478,7 @@ struct TabItemView: View, Equatable { private var activeBorderLineWidth: CGFloat { if agentRowsVariantStore.variant == .graphite { - return isActive ? 1 : 0 + return 0 } switch activeTabIndicatorStyle { case .leftRail: @@ -13461,7 +13491,7 @@ struct TabItemView: View, Equatable { private var activeBorderColor: Color { guard isActive else { return .clear } if agentRowsVariantStore.variant == .graphite { - return Color.primary.opacity(0.18) + return .clear } switch activeTabIndicatorStyle { case .leftRail: @@ -13834,6 +13864,7 @@ struct TabItemView: View, Equatable { activePanelId: tab.focusedPanelId, isActive: usesInvertedActiveForeground, activeForegroundColor: activeSecondaryColor(0.95), + activeAgentRowColor: Color(nsColor: graphiteActiveAgentRowNSColor), fontScale: fontScale, onFocus: { updateSelection() }, onFocusPanel: { panelId in @@ -14575,13 +14606,10 @@ struct TabItemView: View, Equatable { } private var backgroundColor: Color { - // Debug lab "graphite" prototype: the selected card fills with a - // neutral elevated graphite instead of the accent color. Dies with - // the variant lab once a final design ships. + // Debug lab "graphite" prototype v2: dark tint of the workspace's + // own color. Dies with the variant lab once a final design ships. if agentRowsVariantStore.variant == .graphite, isActive { - return Color(nsColor: colorScheme == .dark - ? NSColor(calibratedWhite: 0.24, alpha: 1.0) - : NSColor(calibratedWhite: 0.82, alpha: 1.0)) + return Color(nsColor: graphiteSelectionFillNSColor) } let style = sidebarWorkspaceRowBackgroundStyle( activeTabIndicatorStyle: activeTabIndicatorStyle, diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index e114f50b7d05..cfa8f3a7f14f 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -101,6 +101,7 @@ struct SidebarAgentStatusInCardRows: View { let activePanelId: UUID? let isActive: Bool let activeForegroundColor: Color + let activeAgentRowColor: Color let fontScale: CGFloat let onFocus: () -> Void let onFocusPanel: (UUID) -> Void @@ -115,6 +116,7 @@ struct SidebarAgentStatusInCardRows: View { activePanelId: activePanelId, isActive: isActive, activeForegroundColor: activeForegroundColor, + activeAgentRowColor: activeAgentRowColor, fontScale: fontScale, onFocus: onFocus, onFocusPanel: onFocusPanel @@ -448,12 +450,11 @@ struct SidebarAgentStatusEntryRowView: View { /// `TabItemView` (graphite instead of the blue selection) while this variant /// is active. struct SidebarAgentStatusGraphiteRows: View { - static let accent = Color(red: 124 / 255, green: 140 / 255, blue: 248 / 255) - let rows: [SidebarAgentStatusRow] let activePanelId: UUID? let isActive: Bool let activeForegroundColor: Color + let activeAgentRowColor: Color let fontScale: CGFloat let onFocus: () -> Void let onFocusPanel: (UUID) -> Void @@ -473,6 +474,7 @@ struct SidebarAgentStatusGraphiteRows: View { isActiveAgent: isActive && row.panelId == activePanelId, isActive: isActive, activeForegroundColor: activeForegroundColor, + activeAgentRowColor: activeAgentRowColor, fontScale: fontScale, onFocusPanel: onFocusPanel ) @@ -525,6 +527,7 @@ private struct SidebarAgentGraphiteRow: View { let isActiveAgent: Bool let isActive: Bool let activeForegroundColor: Color + let activeAgentRowColor: Color let fontScale: CGFloat let onFocusPanel: (UUID) -> Void @@ -568,14 +571,10 @@ private struct SidebarAgentGraphiteRow: View { @ViewBuilder private var rowBackground: some View { if isActiveAgent { + // "Even darker of the same color": the active agent sits in a + // deeper shade of the card's own selection tint. RoundedRectangle(cornerRadius: 5, style: .continuous) - .fill(SidebarAgentStatusGraphiteRows.accent.opacity(0.16)) - .overlay(alignment: .leading) { - RoundedRectangle(cornerRadius: 1.5) - .fill(SidebarAgentStatusGraphiteRows.accent) - .frame(width: 2.5) - .padding(.vertical, 2) - } + .fill(activeAgentRowColor) } else { RoundedRectangle(cornerRadius: 5, style: .continuous) .fill(Color.primary.opacity(isHovering ? 0.07 : 0)) From a43bf286aafb41b3513b08b5b26fb23bb6a477bb Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 15:58:02 -0700 Subject: [PATCH 35/46] sidebar: third-party agents drive per-agent rows via registry-validated dynamic keys + CLI verbs Any agent registered in the vault agent registry becomes row-capable: panel-scoped set_status/set_agent_lifecycle for a registered key (validated off-main exactly like the lifecycle path) registers a runtime-only dynamic row key; reporter-supplied icon (sf:/emoji:/text:) and description render in the row; unvalidated keys stay metadata pills, including across pane transfers (eligibility rides DetachedAgentRuntimeState). New CLI verbs: set-status --panel/--pid, set-agent-lifecycle, clear-agent-pid. Coder: GPT 5.5 via codex exec (fable loop), judge-approved over two rounds; transfer-eligibility test added by the orchestrator. --- CLI/CMUXCLI+CommandSuggestions.swift | 2 + CLI/cmux.swift | 195 +++++++++++++++++- ...CommandCoordinator+SidebarMetadataV1.swift | 24 ++- .../Sidebar/ControlSidebarContext.swift | 3 +- ...mmandContextTestStubs+SidebarBrowser.swift | 3 +- ...inalController+ControlSidebarContext.swift | 9 +- Sources/Workspace+AgentPIDOwnership.swift | 4 +- .../Workspace+DetachedSurfaceTransfer.swift | 1 + Sources/Workspace+PanelLifecycle.swift | 18 +- Sources/Workspace+SidebarAgentStatus.swift | 62 +++++- Sources/Workspace.swift | 12 +- ...eSidebarAgentRuntimeObservationModel.swift | 8 + .../AgentSessionAutoResumeSwiftTests.swift | 3 +- cmuxTests/DockTerminalReattachTests.swift | 9 +- cmuxTests/PerAgentSidebarStatusRowTests.swift | 98 +++++++++ 15 files changed, 424 insertions(+), 27 deletions(-) diff --git a/CLI/CMUXCLI+CommandSuggestions.swift b/CLI/CMUXCLI+CommandSuggestions.swift index 74099d433247..df0caa7352c2 100644 --- a/CLI/CMUXCLI+CommandSuggestions.swift +++ b/CLI/CMUXCLI+CommandSuggestions.swift @@ -68,6 +68,7 @@ extension CMUXCLI { "capture-pane", "claude-hook", "claude-teams", + "clear-agent-pid", "clear-history", "clear-log", "clear-notifications", @@ -169,6 +170,7 @@ extension CMUXCLI { "send-key", "send-key-panel", "send-panel", + "set-agent-lifecycle", "set-app-focus", "set-buffer", "set-hook", diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 0eb725ccfa31..e77cdc995b32 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -5144,6 +5144,24 @@ struct CMUXCLI { case "set-status": let response = try forwardSidebarMetadataCommand( "set_status", + commandArgs: commandArgs, + client: client, + windowOverride: windowId, + resolvePanelOption: true, + validatePIDOption: true + ) + print(response) + + case "set-agent-lifecycle": + let response = try forwardSetAgentLifecycleCommand( + commandArgs: commandArgs, + client: client, + windowOverride: windowId + ) + print(response) + + case "clear-agent-pid": + let response = try forwardClearAgentPIDCommand( commandArgs: commandArgs, client: client, windowOverride: windowId @@ -16810,21 +16828,52 @@ struct CMUXCLI { return String(localized: "cli.help.setStatus", defaultValue: """ Usage: cmux set-status [flags] - Set a sidebar status entry for a workspace. Status entries appear as - pills in the sidebar tab row. Use a unique key so different tools - (e.g. "claude_code", "build") can manage their own entries. + Set a sidebar status entry. Workspace entries appear as pills; a + pane-scoped registered agent key appears as that pane's agent row. Flags: --icon Icon name (e.g. "sparkle", "hammer") --color <#hex> Pill color (e.g. "#ff9500") --priority Sort priority; higher appears first (default: 0) + --panel Scope this status to a pane/surface + --pid Associate a live agent PID with this key --workspace Target workspace (default: $CMUX_WORKSPACE_ID) --window Window context for workspace refs and indexes Example: cmux set-status build "compiling" --icon hammer --color "#ff9500" --priority 80 + cmux set-status my-agent "Running checks" --panel surface:1 --pid 12345 cmux set-status deploy "v1.2.3" --workspace workspace:2 """) + case "set-agent-lifecycle": + return """ + Usage: cmux set-agent-lifecycle [flags] + + Set a pane-scoped agent lifecycle state. + + Flags: + --panel Target pane/surface (default: focused surface) + --workspace Target workspace (default: $CMUX_WORKSPACE_ID) + --window Window context for workspace refs and indexes + + Example: + cmux set-agent-lifecycle my-agent running --panel surface:1 + """ + case "clear-agent-pid": + return """ + Usage: cmux clear-agent-pid [flags] + + Clear a tracked agent PID and optionally its status row state. + + Flags: + --panel Target pane/surface + --clear-status Also clear the associated status entry + --workspace Target workspace (default: $CMUX_WORKSPACE_ID) + --window Window context for workspace refs and indexes + + Example: + cmux clear-agent-pid my-agent --panel surface:1 --clear-status + """ case "clear-status": return """ Usage: cmux clear-status [flags] @@ -17298,7 +17347,9 @@ struct CMUXCLI { _ socketCommand: String, commandArgs: [String], client: SocketClient, - windowOverride: String? + windowOverride: String?, + resolvePanelOption: Bool = false, + validatePIDOption: Bool = false ) throws -> String { func insertArgumentBeforeSeparator(_ value: String, into args: inout [String]) { if let separatorIndex = args.firstIndex(of: "--") { @@ -17308,13 +17359,79 @@ struct CMUXCLI { } } + func hasOption(_ name: String, in args: [String]) -> Bool { + for arg in args { + if arg == "--" { return false } + if arg == name || arg.hasPrefix("\(name)=") { + return true + } + } + return false + } + + func validatePIDOptions(_ args: [String]) throws { + var index = 0 + while index < args.count { + let arg = args[index] + if arg == "--" { return } + let rawPID: String? + if arg == "--pid" { + guard index + 1 < args.count else { + throw CLIError(message: "set-status: --pid requires a positive integer") + } + rawPID = args[index + 1] + index += 2 + } else if arg.hasPrefix("--pid=") { + rawPID = String(arg.dropFirst("--pid=".count)) + index += 1 + } else { + index += 1 + continue + } + guard let rawPID, + let pid = Int32(rawPID), + pid > 0 else { + throw CLIError(message: "set-status: --pid requires a positive integer") + } + } + } + + func resolvePanelOptionValues(in args: inout [String], workspaceId: String) throws { + var index = 0 + while index < args.count { + let arg = args[index] + if arg == "--" { return } + if arg == "--panel" { + guard index + 1 < args.count else { + throw CLIError(message: "\(socketCommand.replacingOccurrences(of: "_", with: "-")): --panel requires a value") + } + args[index + 1] = try resolveSurfaceId(args[index + 1], workspaceId: workspaceId, client: client) + index += 2 + continue + } + if arg.hasPrefix("--panel=") { + let rawPanel = String(arg.dropFirst("--panel=".count)) + let panelId = try resolveSurfaceId(rawPanel, workspaceId: workspaceId, client: client) + args[index] = "--panel=\(panelId)" + index += 1 + continue + } + index += 1 + } + } + var forwardedArgs: [String] = [] var resolvedExplicitWorkspace = false + var targetWorkspaceId: String? var index = 0 var parsingOptions = true let rawWindow = windowFromArgsOrOverride(commandArgs, windowOverride: windowOverride) let windowHandle = try normalizeWindowHandle(rawWindow, client: client) + if validatePIDOption { + try validatePIDOptions(commandArgs) + } + while index < commandArgs.count { let arg = commandArgs[index] if parsingOptions, arg == "--" { @@ -17327,6 +17444,7 @@ struct CMUXCLI { let workspaceId = try resolveWorkspaceId(commandArgs[index + 1], client: client, windowHandle: windowHandle) forwardedArgs.append("--tab=\(workspaceId)") resolvedExplicitWorkspace = true + targetWorkspaceId = workspaceId index += 2 continue } @@ -17335,6 +17453,7 @@ struct CMUXCLI { let workspaceId = try resolveWorkspaceId(rawWorkspace, client: client, windowHandle: windowHandle) forwardedArgs.append("--tab=\(workspaceId)") resolvedExplicitWorkspace = true + targetWorkspaceId = workspaceId index += 1 continue } @@ -17354,6 +17473,7 @@ struct CMUXCLI { let workspaceArg = workspaceFromArgsOrEnv(commandArgs, windowOverride: windowOverride) { let workspaceId = try resolveWorkspaceId(workspaceArg, client: client, windowHandle: windowHandle) insertArgumentBeforeSeparator("--tab=\(workspaceId)", into: &forwardedArgs) + targetWorkspaceId = workspaceId } else if !resolvedExplicitWorkspace, let windowHandle { let workspaceId = try requireCurrentWorkspaceId( @@ -17362,6 +17482,18 @@ struct CMUXCLI { command: socketCommand ) insertArgumentBeforeSeparator("--tab=\(workspaceId)", into: &forwardedArgs) + targetWorkspaceId = workspaceId + } else if resolvePanelOption, + hasOption("--panel", in: commandArgs) { + let workspaceId = try resolveWorkspaceId(nil, client: client, windowHandle: windowHandle) + insertArgumentBeforeSeparator("--tab=\(workspaceId)", into: &forwardedArgs) + targetWorkspaceId = workspaceId + } + + if resolvePanelOption, + let targetWorkspaceId, + hasOption("--panel", in: forwardedArgs) { + try resolvePanelOptionValues(in: &forwardedArgs, workspaceId: targetWorkspaceId) } let command = ([socketCommand] + forwardedArgs) @@ -17370,6 +17502,57 @@ struct CMUXCLI { return try sendV1Command(command, client: client) } + private func forwardSetAgentLifecycleCommand( + commandArgs: [String], + client: SocketClient, + windowOverride: String? + ) throws -> String { + let (_, rem0) = parseOption(commandArgs, name: "--workspace") + let (_, rem1) = parseOption(rem0, name: "--window") + let (_, rem2) = parseOption(rem1, name: "--panel") + guard rem2.count == 2 else { + throw CLIError(message: "Usage: cmux set-agent-lifecycle [--workspace ] [--panel ]") + } + let lifecycle = rem2[1] + let allowed = ["running", "idle", "needsInput", "unknown"] + guard allowed.contains(lifecycle) else { + throw CLIError(message: "set-agent-lifecycle: invalid lifecycle '\(lifecycle)' (expected running, idle, needsInput, or unknown)") + } + return try forwardSidebarMetadataCommand( + "set_agent_lifecycle", + commandArgs: commandArgs, + client: client, + windowOverride: windowOverride, + resolvePanelOption: true + ) + } + + private func forwardClearAgentPIDCommand( + commandArgs: [String], + client: SocketClient, + windowOverride: String? + ) throws -> String { + let clearStatus = hasFlag(commandArgs, name: "--clear-status") + let argsWithoutClearStatus = commandArgs.filter { $0 != "--clear-status" } + let (_, rem0) = parseOption(argsWithoutClearStatus, name: "--workspace") + let (_, rem1) = parseOption(rem0, name: "--window") + let (_, rem2) = parseOption(rem1, name: "--panel") + guard rem2.count == 1 else { + throw CLIError(message: "Usage: cmux clear-agent-pid [--workspace ] [--panel ] [--clear-status]") + } + var forwardedArgs = argsWithoutClearStatus + if clearStatus { + forwardedArgs.append("--clear-status") + } + return try forwardSidebarMetadataCommand( + "clear_agent_pid", + commandArgs: forwardedArgs, + client: client, + windowOverride: windowOverride, + resolvePanelOption: true + ) + } + private struct RightSidebarCLIArguments { let positional: [String] let workspace: String? @@ -35480,7 +35663,9 @@ export default CMUXSessionRestore; clear-notifications [--workspace ] [--window ] right-sidebar [--workspace ] [--window ] [--no-focus] sidebar [name] - set-status [--workspace ] [--window ] [--icon ] [--color <#hex>] [--priority ] + set-status [--workspace ] [--window ] [--panel ] [--pid ] [--icon ] [--color <#hex>] [--priority ] + set-agent-lifecycle [--workspace ] [--panel ] [--window ] + clear-agent-pid [--workspace ] [--panel ] [--clear-status] [--window ] clear-status [--workspace ] [--window ] list-status [--workspace ] [--window ] set-progress <0.0-1.0> [--label ] [--workspace ] [--window ] diff --git a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Sidebar/ControlCommandCoordinator+SidebarMetadataV1.swift b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Sidebar/ControlCommandCoordinator+SidebarMetadataV1.swift index e9a0fc42d72c..ff8125cd4a25 100644 --- a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Sidebar/ControlCommandCoordinator+SidebarMetadataV1.swift +++ b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Sidebar/ControlCommandCoordinator+SidebarMetadataV1.swift @@ -18,11 +18,14 @@ extension ControlCommandCoordinator { // MARK: - Status / metadata entries /// The shared `set_status`/`report_meta` upsert body: parse + validate on - /// the calling thread, then a bus enqueue; the `OK` reply is parse-only - /// (zero main hops, exactly the legacy deferred-mutation semantics). + /// the calling thread, then a bus enqueue. `set_status --panel` may run + /// the app-owned vault-agent allowlist check to decide whether a custom + /// key is row-eligible; otherwise the `OK` reply is parse-only (zero main + /// hops, exactly the legacy deferred-mutation semantics). nonisolated func sidebarUpsertMetadata( _ args: String, missingError: String, + allowsDynamicAgentRows: Bool, context: (any ControlCommandContext)? ) -> String { let parsed = sidebarParseOptionsNoStop(args) @@ -66,7 +69,7 @@ extension ControlCommandCoordinator { } let panelResolution = sidebarParseOptionalPanelIdOption( options: parsed.options, - usage: "set_status [--icon=X] [--color=#hex] [--url=X] [--priority=N] [--format=plain|markdown] [--tab=X] [--panel=ID]" + usage: "set_status [--icon=X] [--color=#hex] [--url=X] [--priority=N] [--format=plain|markdown] [--tab=X] [--panel=ID] [--pid=N]" ) if let error = panelResolution.error { return error @@ -80,6 +83,14 @@ extension ControlCommandCoordinator { return nil }() + let dynamicAgentRowKey = allowsDynamicAgentRows + && panelResolution.panelId != nil + && (context?.controlSidebarIsAllowedAgentLifecycleKey( + key, + target: target, + panelID: panelResolution.panelId + ) ?? false) + context?.controlSidebarScheduleStatusUpsert( target: target, key: key, @@ -90,7 +101,8 @@ extension ControlCommandCoordinator { priority: priority, format: format, panelID: panelResolution.panelId, - pid: pidValue + pid: pidValue, + dynamicAgentRowKey: dynamicAgentRowKey ) return "OK" } @@ -120,7 +132,8 @@ extension ControlCommandCoordinator { nonisolated func sidebarSetStatus(_ args: String, context: (any ControlCommandContext)?) -> String { sidebarUpsertMetadata( args, - missingError: "ERROR: Missing status key or value — usage: set_status [--icon=X] [--color=#hex] [--url=X] [--priority=N] [--format=plain|markdown] [--tab=X]", + missingError: "ERROR: Missing status key or value — usage: set_status [--icon=X] [--color=#hex] [--url=X] [--priority=N] [--format=plain|markdown] [--tab=X] [--panel=ID] [--pid=N]", + allowsDynamicAgentRows: true, context: context ) } @@ -130,6 +143,7 @@ extension ControlCommandCoordinator { sidebarUpsertMetadata( args, missingError: "ERROR: Missing metadata key or value — usage: report_meta [--icon=X] [--color=#hex] [--url=X] [--priority=N] [--format=plain|markdown] [--tab=X]", + allowsDynamicAgentRows: false, context: context ) } diff --git a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Sidebar/ControlSidebarContext.swift b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Sidebar/ControlSidebarContext.swift index a9be16cb5e13..06497bc23d4d 100644 --- a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Sidebar/ControlSidebarContext.swift +++ b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Sidebar/ControlSidebarContext.swift @@ -59,7 +59,8 @@ public protocol ControlSidebarContext: AnyObject { priority: Int, format: ControlSidebarMetadataFormat, panelID: UUID?, - pid: Int32? + pid: Int32?, + dynamicAgentRowKey: Bool ) /// Enqueues the `clear_status`/`clear_meta` removal mutation. diff --git a/Packages/macOS/CmuxControlSocket/Tests/CmuxControlSocketTests/ControlCommandContextTestStubs+SidebarBrowser.swift b/Packages/macOS/CmuxControlSocket/Tests/CmuxControlSocketTests/ControlCommandContextTestStubs+SidebarBrowser.swift index 5c54e9e532aa..49f3987abcdf 100644 --- a/Packages/macOS/CmuxControlSocket/Tests/CmuxControlSocketTests/ControlCommandContextTestStubs+SidebarBrowser.swift +++ b/Packages/macOS/CmuxControlSocket/Tests/CmuxControlSocketTests/ControlCommandContextTestStubs+SidebarBrowser.swift @@ -58,7 +58,8 @@ extension ControlSidebarContext { priority: Int, format: ControlSidebarMetadataFormat, panelID: UUID?, - pid: Int32? + pid: Int32?, + dynamicAgentRowKey: Bool ) {} nonisolated func controlSidebarScheduleStatusClear(target: ControlSidebarTabTarget, key: String) {} diff --git a/Sources/TerminalController+ControlSidebarContext.swift b/Sources/TerminalController+ControlSidebarContext.swift index 009f747a5668..ffa35e4b2e5d 100644 --- a/Sources/TerminalController+ControlSidebarContext.swift +++ b/Sources/TerminalController+ControlSidebarContext.swift @@ -26,7 +26,8 @@ extension TerminalController: ControlSidebarContext { priority: Int, format: ControlSidebarMetadataFormat, panelID: UUID?, - pid: Int32? + pid: Int32?, + dynamicAgentRowKey: Bool ) { let appFormat = SidebarMetadataFormat(rawValue: format.rawValue) ?? .plain controlSidebarScheduleMutation(target: target) { _, tab in @@ -43,6 +44,9 @@ extension TerminalController: ControlSidebarContext { format: appFormat, timestamp: Date() ) + if dynamicAgentRowKey { + tab.registerDynamicAgentRowKey(key) + } if Self.shouldReplaceStatusEntry( current: tab.statusEntries[key], key: key, @@ -183,6 +187,9 @@ extension TerminalController: ControlSidebarContext { if let panelId = panelID, !tab.panels.keys.contains(panelId) { return } + if panelID != nil { + tab.registerDynamicAgentRowKey(key) + } tab.setAgentLifecycle(key: key, panelId: panelID, lifecycle: lifecycle) } } diff --git a/Sources/Workspace+AgentPIDOwnership.swift b/Sources/Workspace+AgentPIDOwnership.swift index 0286ba87046c..2a990e3d283e 100644 --- a/Sources/Workspace+AgentPIDOwnership.swift +++ b/Sources/Workspace+AgentPIDOwnership.swift @@ -108,6 +108,7 @@ extension Workspace { if clearAgentLifecycle(key: statusKey) { didChange = true } + pruneDynamicAgentRowKeyIfUnused(statusKey) if didChange, refreshPorts { refreshTrackedAgentPorts() } @@ -143,7 +144,7 @@ extension Workspace { // sidebarAgentStatusRows' comparator). Mirror pane close for the // workspace-level slot: drop it when this pane was its last owner. for statusKey in Set((statusEntriesByPanelId[panelId] ?? [:]).keys) - where statusKey != retainedStatusKey && Self.structuredAgentHookStatusKeys.contains(statusKey) { + where statusKey != retainedStatusKey && isAgentRowKey(statusKey) { if clearPanelStatusEntry(statusKey: statusKey, panelId: panelId) { didChange = true } @@ -155,6 +156,7 @@ extension Workspace { statusEntries.removeValue(forKey: statusKey) != nil { didChange = true } + pruneDynamicAgentRowKeyIfUnused(statusKey) } return didChange } diff --git a/Sources/Workspace+DetachedSurfaceTransfer.swift b/Sources/Workspace+DetachedSurfaceTransfer.swift index fb0a03894275..def97559529c 100644 --- a/Sources/Workspace+DetachedSurfaceTransfer.swift +++ b/Sources/Workspace+DetachedSurfaceTransfer.swift @@ -14,6 +14,7 @@ extension Workspace { /// an unrelated process" (same contract as `isRecordedAgentPIDLive`). let agentPIDProcessIdentities: [String: AgentPIDProcessIdentity] let agentPIDKeys: Set + let dynamicAgentRowKeys: Set } struct DetachedSurfaceTransfer { diff --git a/Sources/Workspace+PanelLifecycle.swift b/Sources/Workspace+PanelLifecycle.swift index bf79831a020b..dd73a56dfe8b 100644 --- a/Sources/Workspace+PanelLifecycle.swift +++ b/Sources/Workspace+PanelLifecycle.swift @@ -68,7 +68,8 @@ extension Workspace { statusEntries: statusEntriesForPanel, agentPIDs: agentPIDsForPanel, agentPIDProcessIdentities: agentPIDIdentitiesForPanel, - agentPIDKeys: pidKeys + agentPIDKeys: pidKeys, + dynamicAgentRowKeys: dynamicAgentRowKeys.intersection(statusEntriesForPanel.keys) ) } @@ -156,6 +157,7 @@ extension Workspace { agentPIDPanelIdsByKey.removeAll() agentPIDKeysByPanelId.removeAll() statusEntriesByPanelId.removeAll() + pruneDynamicAgentRowKeys() if hadAgentPIDs, refreshPorts { refreshTrackedAgentPorts() } @@ -209,7 +211,7 @@ extension Workspace { } func isStructuredAgentHookPIDKey(_ key: String) -> Bool { - Self.structuredAgentHookStatusKeys.contains(agentStatusKey(forAgentPIDKey: key)) + isAgentRowKey(agentStatusKey(forAgentPIDKey: key)) } @discardableResult @@ -243,6 +245,7 @@ extension Workspace { clearAgentPID(key: synthesizedKey, panelId: panelId, clearStatus: clearStatus, refreshPorts: refreshPorts) { didChange = true } + pruneDynamicAgentRowKeyIfUnused(statusKey) return didChange } let statusKeyToClear = clearStatus ? agentStatusKey(forAgentPIDKey: key) : nil @@ -272,6 +275,11 @@ extension Workspace { statusEntries.removeValue(forKey: statusKeyToClear) != nil { didChange = true } + if let statusKeyToClear { + pruneDynamicAgentRowKeyIfUnused(statusKeyToClear) + } else { + pruneDynamicAgentRowKeyIfUnused(agentStatusKey(forAgentPIDKey: key)) + } if didChange, refreshPorts { refreshTrackedAgentPorts() } @@ -303,6 +311,9 @@ extension Workspace { func adoptDetachedAgentRuntimeState(_ runtimeState: DetachedAgentRuntimeState?) { guard let runtimeState else { return } for (statusKey, statusEntry) in runtimeState.statusEntries { + if runtimeState.dynamicAgentRowKeys.contains(statusKey) { + registerDynamicAgentRowKey(statusKey) + } statusEntries[statusKey] = statusEntry recordPanelStatusEntry(statusEntry, panelId: runtimeState.panelId) } @@ -411,6 +422,9 @@ extension Workspace { where panelsOwningAgentStatusKey(statusKey).isEmpty && !hasAgentRuntime(forStatusKey: statusKey) { statusEntries.removeValue(forKey: statusKey) } + for statusKey in closedPanelStatusKeys { + pruneDynamicAgentRowKeyIfUnused(statusKey) + } restoredAgentSnapshotsByPanelId.removeValue(forKey: panelId) restoredAgentResumeStatesByPanelId.removeValue(forKey: panelId) restoredResumeSessionWorkingDirectoriesByPanelId.removeValue(forKey: panelId) diff --git a/Sources/Workspace+SidebarAgentStatus.swift b/Sources/Workspace+SidebarAgentStatus.swift index 4b4af844d11a..17ce9aba3b12 100644 --- a/Sources/Workspace+SidebarAgentStatus.swift +++ b/Sources/Workspace+SidebarAgentStatus.swift @@ -29,6 +29,55 @@ extension Workspace { set { sidebarAgentRuntimeObservation.setStatusEntriesByPanelId(newValue) } } + var dynamicAgentRowKeys: Set { + get { sidebarAgentRuntimeObservation.dynamicAgentRowKeys } + set { sidebarAgentRuntimeObservation.setDynamicAgentRowKeys(newValue) } + } + + func isAgentRowKey(_ key: String) -> Bool { + Self.structuredAgentHookStatusKeys.contains(key) || dynamicAgentRowKeys.contains(key) + } + + func registerDynamicAgentRowKey(_ key: String) { + guard !Self.structuredAgentHookStatusKeys.contains(key), + !dynamicAgentRowKeys.contains(key) else { + return + } + dynamicAgentRowKeys.insert(key) + } + + @discardableResult + func pruneDynamicAgentRowKeyIfUnused(_ key: String) -> Bool { + guard dynamicAgentRowKeys.contains(key), + !hasRuntimeStateForDynamicAgentRowKey(key) else { + return false + } + dynamicAgentRowKeys.remove(key) + return true + } + + func pruneDynamicAgentRowKeys() { + for key in Array(dynamicAgentRowKeys) { + _ = pruneDynamicAgentRowKeyIfUnused(key) + } + } + + private func hasRuntimeStateForDynamicAgentRowKey(_ statusKey: String) -> Bool { + if statusEntries[statusKey] != nil { + return true + } + if hasAgentRuntime(forStatusKey: statusKey) { + return true + } + if statusEntriesByPanelId.values.contains(where: { $0[statusKey] != nil }) { + return true + } + if agentLifecycleStatesByPanelId.values.contains(where: { $0[statusKey] != nil }) { + return true + } + return false + } + /// Records the panel-scoped copy of a structured agent status report, so /// each agent pane keeps its own row even when several agents of the same /// type share the workspace (the workspace-level `statusEntries` slot is @@ -36,7 +85,7 @@ extension Workspace { /// (ignoring the timestamp) so agent heartbeats with no visible change do /// not invalidate the sidebar snapshot. func recordPanelStatusEntry(_ entry: SidebarStatusEntry, panelId: UUID) { - guard Self.structuredAgentHookStatusKeys.contains(entry.key) else { return } + guard isAgentRowKey(entry.key) else { return } guard TerminalController.shouldReplaceStatusEntry( current: statusEntriesByPanelId[panelId]?[entry.key], key: entry.key, @@ -61,6 +110,7 @@ extension Workspace { } else { statusEntriesByPanelId[panelId] = entries } + pruneDynamicAgentRowKeyIfUnused(statusKey) return true } @@ -102,7 +152,7 @@ extension Workspace { _ entry: SidebarStatusEntry, visibleStructuredStatusKeys: Set ) -> Bool { - guard Self.structuredAgentHookStatusKeys.contains(entry.key) else { + guard isAgentRowKey(entry.key) else { return true } return visibleStructuredStatusKeys.contains(entry.key) @@ -113,7 +163,7 @@ extension Workspace { for (key, panelId) in agentPIDPanelIdsByKey where panels[panelId] != nil { let statusKey = agentStatusKey(forAgentPIDKey: key) - guard Self.structuredAgentHookStatusKeys.contains(statusKey), + guard isAgentRowKey(statusKey), statusEntries[statusKey] != nil else { continue } @@ -131,7 +181,7 @@ extension Workspace { for key in agentPIDs.keys where agentPIDPanelIdsByKey[key] == nil { let statusKey = agentStatusKey(forAgentPIDKey: key) - guard Self.structuredAgentHookStatusKeys.contains(statusKey), + guard isAgentRowKey(statusKey), statusEntries[statusKey] != nil else { continue } @@ -156,11 +206,11 @@ extension Workspace { var statusKeysByPanel: [UUID: Set] = [:] for (key, panelId) in agentPIDPanelIdsByKey where panels[panelId] != nil { let statusKey = agentStatusKey(forAgentPIDKey: key) - guard Self.structuredAgentHookStatusKeys.contains(statusKey) else { continue } + guard isAgentRowKey(statusKey) else { continue } statusKeysByPanel[panelId, default: []].insert(statusKey) } for (panelId, entries) in statusEntriesByPanelId where panels[panelId] != nil { - for statusKey in entries.keys where Self.structuredAgentHookStatusKeys.contains(statusKey) { + for statusKey in entries.keys where isAgentRowKey(statusKey) { statusKeysByPanel[panelId, default: []].insert(statusKey) } } diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 8e77ecb3d9ab..9c20da79dcea 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -4619,18 +4619,28 @@ final class Workspace: Identifiable, ObservableObject { didClear = true recordAgentLifecycleChange(panelId: panelId) } + if didClear { + pruneDynamicAgentRowKeyIfUnused(key) + } return didClear } func clearAgentLifecycleStates(panelId: UUID) { - guard agentLifecycleStatesByPanelId.removeValue(forKey: panelId) != nil else { return } + guard let removedStates = agentLifecycleStatesByPanelId.removeValue(forKey: panelId) else { return } + for key in removedStates.keys { + pruneDynamicAgentRowKeyIfUnused(key) + } recordAgentLifecycleChange(panelId: panelId) } func clearAllAgentLifecycleStates() { let panelIds = Array(agentLifecycleStatesByPanelId.keys) guard !panelIds.isEmpty else { return } + let removedKeys = Set(agentLifecycleStatesByPanelId.values.flatMap(\.keys)) agentLifecycleStatesByPanelId.removeAll() + for key in removedKeys { + pruneDynamicAgentRowKeyIfUnused(key) + } for panelId in panelIds { recordAgentLifecycleChange(panelId: panelId) } diff --git a/Sources/WorkspaceSidebarAgentRuntimeObservationModel.swift b/Sources/WorkspaceSidebarAgentRuntimeObservationModel.swift index 074cba8a1c53..daa964aa3cc0 100644 --- a/Sources/WorkspaceSidebarAgentRuntimeObservationModel.swift +++ b/Sources/WorkspaceSidebarAgentRuntimeObservationModel.swift @@ -20,6 +20,8 @@ final class WorkspaceSidebarAgentRuntimeObservationModel { @ObservationIgnored private(set) var agentLifecycleStatesByPanelId: [UUID: [String: AgentHibernationLifecycleState]] = [:] @ObservationIgnored + private(set) var dynamicAgentRowKeys: Set = [] + @ObservationIgnored private(set) var changeGeneration: UInt64 = 0 @ObservationIgnored @@ -72,6 +74,12 @@ final class WorkspaceSidebarAgentRuntimeObservationModel { notifyChanged() } + func setDynamicAgentRowKeys(_ newValue: Set) { + guard dynamicAgentRowKeys != newValue else { return } + dynamicAgentRowKeys = newValue + notifyChanged() + } + private func notifyChanged() { changeGeneration &+= 1 for continuation in changeObservers.values { diff --git a/cmuxTests/AgentSessionAutoResumeSwiftTests.swift b/cmuxTests/AgentSessionAutoResumeSwiftTests.swift index 640945188540..e51b2c340484 100644 --- a/cmuxTests/AgentSessionAutoResumeSwiftTests.swift +++ b/cmuxTests/AgentSessionAutoResumeSwiftTests.swift @@ -57,7 +57,8 @@ struct AgentSessionAutoResumeSwiftTests { statusEntries: [:], agentPIDs: [pidKey: livePid], agentPIDProcessIdentities: [pidKey: savedIdentity], - agentPIDKeys: [pidKey] + agentPIDKeys: [pidKey], + dynamicAgentRowKeys: [] ) ) diff --git a/cmuxTests/DockTerminalReattachTests.swift b/cmuxTests/DockTerminalReattachTests.swift index 36af7be52a8e..cc37c33d3596 100644 --- a/cmuxTests/DockTerminalReattachTests.swift +++ b/cmuxTests/DockTerminalReattachTests.swift @@ -339,7 +339,8 @@ extension DockSocketLifecycleTests { statusEntries: [:], agentPIDs: ["claude": deadPid], agentPIDProcessIdentities: [:], - agentPIDKeys: ["claude"] + agentPIDKeys: ["claude"], + dynamicAgentRowKeys: [] ) ) @@ -396,7 +397,8 @@ extension DockSocketLifecycleTests { statusEntries: [:], agentPIDs: ["claude": livePid], agentPIDProcessIdentities: ["claude": mismatchedIdentity], - agentPIDKeys: ["claude"] + agentPIDKeys: ["claude"], + dynamicAgentRowKeys: [] ) ) @@ -441,7 +443,8 @@ extension DockSocketLifecycleTests { statusEntries: [:], agentPIDs: ["claude": livePid], agentPIDProcessIdentities: ["claude": currentIdentity], - agentPIDKeys: ["claude"] + agentPIDKeys: ["claude"], + dynamicAgentRowKeys: [] ) ) diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 25df21a49999..28499361e19a 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -151,6 +151,104 @@ struct PerAgentSidebarStatusRowTests { #expect(row.format == .markdown) } + @Test + func testRegisteredDynamicAgentKeyProducesRowWithReporterContentAndClearsRuntime() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + let key = "third-party-agent" + let entry = SidebarStatusEntry( + key: key, + value: "Running checks", + icon: "text:TP", + color: "#34C759", + timestamp: Date(timeIntervalSince1970: 100) + ) + + workspace.registerDynamicAgentRowKey(key) + workspace.statusEntries[key] = entry + workspace.recordAgentPID(key: key, pid: 111, panelId: panelId, refreshPorts: false) + workspace.recordPanelStatusEntry(entry, panelId: panelId) + workspace.setAgentLifecycle(key: key, panelId: panelId, lifecycle: .running) + + let row = try #require(workspace.sidebarAgentStatusRows().first) + #expect(row.statusKey == key) + #expect(row.panelId == panelId) + #expect(row.value == "Running checks") + #expect(row.icon == "text:TP") + #expect(row.color == "#34C759") + #expect(row.lifecycle == .running) + #expect(workspace.dynamicAgentRowKeys.contains(key)) + + #expect(workspace.clearAgentPID(key: key, panelId: panelId, clearStatus: true, refreshPorts: false)) + #expect(workspace.sidebarAgentStatusRows().isEmpty) + #expect(!workspace.dynamicAgentRowKeys.contains(key)) + #expect(workspace.statusEntries[key] == nil) + #expect(workspace.statusEntriesByPanelId[panelId]?[key] == nil) + #expect(workspace.agentLifecycleStatesByPanelId[panelId]?[key] == nil) + } + + @Test + func testUnregisteredCustomKeyRemainsMetadataPill() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + let key = "unregistered-agent" + let entry = SidebarStatusEntry( + key: key, + value: "metadata only", + icon: "text:UA", + color: "#8E8E93", + timestamp: Date(timeIntervalSince1970: 100) + ) + + workspace.statusEntries[key] = entry + workspace.recordPanelStatusEntry(entry, panelId: panelId) + + #expect(workspace.sidebarAgentStatusRows().isEmpty) + #expect(workspace.statusEntriesByPanelId[panelId]?[key] == nil) + #expect(workspace.sidebarStatusEntriesVisibleForDisplay().contains(entry)) + } + + @Test + func testDynamicKeyRowEligibilityTransfersOnlyWhenRegistered() throws { + let source = Workspace() + let panelId = try #require(source.focusedPanelId) + let key = "third-party-agent" + let entry = SidebarStatusEntry( + key: key, + value: "Running checks", + icon: "emoji:🤖", + timestamp: Date(timeIntervalSince1970: 100) + ) + source.registerDynamicAgentRowKey(key) + source.statusEntries[key] = entry + source.recordAgentPID(key: key, pid: 111, panelId: panelId, refreshPorts: false) + source.recordPanelStatusEntry(entry, panelId: panelId) + + // A registered dynamic key carries its row eligibility across a pane + // transfer. + let runtimeState = try #require(source.agentRuntimeState(forPanelId: panelId)) + #expect(runtimeState.dynamicAgentRowKeys.contains(key)) + let destination = Workspace() + destination.adoptDetachedAgentRuntimeState(runtimeState) + #expect(destination.dynamicAgentRowKeys.contains(key)) + #expect(destination.sidebarAgentStatusRows().first?.statusKey == key) + + // An adopted runtime whose keys were never validated must stay a + // metadata pill in the destination, exactly as at the source. + let unvalidated = DetachedAgentRuntimeState( + panelId: panelId, + statusEntries: [key: entry], + agentPIDs: [key: 111], + agentPIDProcessIdentities: [:], + agentPIDKeys: [key], + dynamicAgentRowKeys: [] + ) + let strictDestination = Workspace() + strictDestination.adoptDetachedAgentRuntimeState(unvalidated) + #expect(!strictDestination.dynamicAgentRowKeys.contains(key)) + #expect(strictDestination.sidebarAgentStatusRows().isEmpty) + } + @Test func testBareSharedPIDKeyHookSequenceKeepsBothPanesRows() throws { let workspace = Workspace() From f6d26c5bf29d6b07cad4c788fd29b0bc877808ec Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 15:58:02 -0700 Subject: [PATCH 36/46] graphite: grey default selection (custom/selection colors still tint); agents accordion below the branch line by default, placement switchable in the lab --- Resources/Localizable.xcstrings | 51 ++++++++++++++++++++ Sources/ContentView.swift | 60 +++++++++++++++--------- Sources/SidebarAgentRowsVariantLab.swift | 50 +++++++++++++++++++- 3 files changed, 139 insertions(+), 22 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index bb3a1f44b431..42733182d438 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -69520,6 +69520,57 @@ } } }, + "debug.agentRows.placement.belowBranch": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Below the branch line" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ブランチ行の下" + } + } + } + }, + "debug.agentRows.placement.header": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Accordion position (in-card variants)" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アコーディオンの位置(カード内バリアント)" + } + } + } + }, + "debug.agentRows.placement.top": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Top of card (under the title)" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "カード上部(タイトルの下)" + } + } + } + }, "debug.agentRows.variant.belowAccordion": { "extractionState": "manual", "localizations": { diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 858daa950710..a47f1ac6a294 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -13392,18 +13392,22 @@ struct TabItemView: View, Equatable { /// Graphite prototype: selected-card fill = the workspace's color pulled /// far toward the sidebar base, so custom colors survive as a tint - /// instead of a saturated slab. + /// instead of a saturated slab. With no custom color (and no explicitly + /// customized selection color) the default is a neutral grey, not the + /// accent blue. private var graphiteSelectionFillNSColor: NSColor { - let base: NSColor = workspaceSnapshot.customColorHex.flatMap { + let explicitBase: NSColor? = workspaceSnapshot.customColorHex.flatMap { WorkspaceTabColorSettings.displayNSColor( hex: $0, colorScheme: colorScheme, forceBright: false ) - } ?? sidebarSelectedWorkspaceBackgroundNSColor( - for: colorScheme, - sidebarSelectionColorHex: sidebarSelectionColorHex - ) + } ?? sidebarSelectionColorHex.flatMap { NSColor(hex: $0) } + guard let base = explicitBase else { + return colorScheme == .dark + ? NSColor(calibratedWhite: 0.24, alpha: 1.0) + : NSColor(calibratedWhite: 0.82, alpha: 1.0) + } let srgbBase = base.usingColorSpace(.sRGB) ?? base let dimBase = colorScheme == .dark ? NSColor(calibratedWhite: 0.14, alpha: 1.0) @@ -13421,6 +13425,27 @@ struct TabItemView: View, Equatable { return fill.blended(withFraction: 0.38, of: deep) ?? fill } + /// Shared mount for the in-card agents accordion; used at both placements + /// (top of card / below the branch line). + @ViewBuilder + private var inCardAgentRowsMount: some View { + if !workspaceSnapshot.agentStatusRows.isEmpty { + SidebarAgentStatusInCardRows( + rows: workspaceSnapshot.agentStatusRows, + activePanelId: tab.focusedPanelId, + isActive: usesInvertedActiveForeground, + activeForegroundColor: activeSecondaryColor(0.95), + activeAgentRowColor: Color(nsColor: graphiteActiveAgentRowNSColor), + fontScale: fontScale, + onFocus: { updateSelection() }, + onFocusPanel: { panelId in + updateSelection() + tab.focusPanel(panelId) + } + ) + } + } + private func selectedWorkspaceForegroundNSColor(opacity: CGFloat) -> NSColor { sidebarSelectedWorkspaceForegroundNSColor( on: selectedWorkspaceBackgroundNSColor, @@ -13857,21 +13882,8 @@ struct TabItemView: View, Equatable { if detailVisibility.showsMetadata { let metadataEntries = workspaceSnapshot.metadataEntries let metadataBlocks = workspaceSnapshot.metadataBlocks - if !workspaceSnapshot.agentStatusRows.isEmpty { - // Renders only while an in-card debug variant is selected. - SidebarAgentStatusInCardRows( - rows: workspaceSnapshot.agentStatusRows, - activePanelId: tab.focusedPanelId, - isActive: usesInvertedActiveForeground, - activeForegroundColor: activeSecondaryColor(0.95), - activeAgentRowColor: Color(nsColor: graphiteActiveAgentRowNSColor), - fontScale: fontScale, - onFocus: { updateSelection() }, - onFocusPanel: { panelId in - updateSelection() - tab.focusPanel(panelId) - } - ) + if agentRowsVariantStore.inCardPlacement == .top { + inCardAgentRowsMount } if !metadataEntries.isEmpty { SidebarMetadataRows( @@ -14026,6 +14038,12 @@ struct TabItemView: View, Equatable { } } + // Agents accordion below the branch/directory line (default + // placement; switchable to top-of-card in the debug lab). + if detailVisibility.showsMetadata, agentRowsVariantStore.inCardPlacement == .belowBranch { + inCardAgentRowsMount + } + // Pull request rows if detailVisibility.showsPullRequests, !workspaceSnapshot.pullRequestRows.isEmpty { VStack(alignment: .leading, spacing: 1) { diff --git a/Sources/SidebarAgentRowsVariantLab.swift b/Sources/SidebarAgentRowsVariantLab.swift index 403b838b0acd..ee299e916039 100644 --- a/Sources/SidebarAgentRowsVariantLab.swift +++ b/Sources/SidebarAgentRowsVariantLab.swift @@ -64,6 +64,25 @@ enum SidebarAgentRowsVariant: String, CaseIterable, Identifiable { } } +/// Where the in-card agents accordion sits inside the workspace card. +enum SidebarAgentRowsPlacement: String, CaseIterable, Identifiable { + case top + case belowBranch + + static let userDefaultsKey = "sidebarAgentRowsPlacementDebug" + + var id: String { rawValue } + + var displayName: String { + switch self { + case .top: + return String(localized: "debug.agentRows.placement.top", defaultValue: "Top of card (under the title)") + case .belowBranch: + return String(localized: "debug.agentRows.placement.belowBranch", defaultValue: "Below the branch line") + } + } +} + /// Singleton the row containers observe. It only mutates when the user picks /// a variant in the lab window, so the extra invalidation is bounded; this is /// a deliberate, temporary exception to the sidebar snapshot-boundary rule @@ -78,9 +97,17 @@ final class SidebarAgentRowsVariantStore: ObservableObject { } } + @Published var inCardPlacement: SidebarAgentRowsPlacement { + didSet { + UserDefaults.standard.set(inCardPlacement.rawValue, forKey: SidebarAgentRowsPlacement.userDefaultsKey) + } + } + private init() { let raw = UserDefaults.standard.string(forKey: SidebarAgentRowsVariant.userDefaultsKey) variant = raw.flatMap(SidebarAgentRowsVariant.init(rawValue:)) ?? .belowAccordion + let placementRaw = UserDefaults.standard.string(forKey: SidebarAgentRowsPlacement.userDefaultsKey) + inCardPlacement = placementRaw.flatMap(SidebarAgentRowsPlacement.init(rawValue:)) ?? .belowBranch } } @@ -90,7 +117,7 @@ final class AgentRowsVariantLabWindowController: ReleasingWindowController { override func makeWindow() -> NSWindow { let window = NSPanel( - contentRect: NSRect(x: 0, y: 0, width: 380, height: 430), + contentRect: NSRect(x: 0, y: 0, width: 380, height: 560), styleMask: [.titled, .closable, .utilityWindow], backing: .buffered, defer: false @@ -145,6 +172,27 @@ private struct AgentRowsVariantLabView: View { } .buttonStyle(.plain) } + + Divider() + + Text(String(localized: "debug.agentRows.placement.header", defaultValue: "Accordion position (in-card variants)")) + .font(.system(size: 11, weight: .semibold)) + .foregroundColor(.secondary) + ForEach(SidebarAgentRowsPlacement.allCases) { placement in + Button { + store.inCardPlacement = placement + } label: { + HStack(spacing: 8) { + Image(systemName: store.inCardPlacement == placement ? "largecircle.fill.circle" : "circle") + .foregroundColor(store.inCardPlacement == placement ? Color.accentColor : .secondary) + Text(placement.displayName) + .font(.system(size: 12)) + Spacer(minLength: 0) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } Spacer(minLength: 0) } .padding(14) From a2544ae87af32dd3463d6fbc196d754e30f457ed Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 16:11:55 -0700 Subject: [PATCH 37/46] cli: sidebar metadata verbs resolve --workspace into both --tab and panel scope set-status/set-agent-lifecycle/clear-agent-pid previously resolved the workspace from the caller context, ignoring --workspace, so --tab pointed at the selected workspace while --panel belonged to the addressed one and the moved-panel guard silently dropped the mutation. --- CLI/cmux.swift | 57 +++++++++++++++++++++----------------------------- 1 file changed, 24 insertions(+), 33 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index e77cdc995b32..df24cf01337a 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -17420,18 +17420,35 @@ struct CMUXCLI { } } - var forwardedArgs: [String] = [] - var resolvedExplicitWorkspace = false - var targetWorkspaceId: String? - var index = 0 - var parsingOptions = true let rawWindow = windowFromArgsOrOverride(commandArgs, windowOverride: windowOverride) let windowHandle = try normalizeWindowHandle(rawWindow, client: client) + let explicitWorkspaceArg = optionValue(commandArgs, name: "--workspace") if validatePIDOption { try validatePIDOptions(commandArgs) } + let targetWorkspaceId: String? + if let explicitWorkspaceArg { + targetWorkspaceId = try resolveWorkspaceId(explicitWorkspaceArg, client: client, windowHandle: windowHandle) + } else if let workspaceArg = workspaceFromArgsOrEnv(commandArgs, windowOverride: windowOverride) { + targetWorkspaceId = try resolveWorkspaceId(workspaceArg, client: client, windowHandle: windowHandle) + } else if let windowHandle { + targetWorkspaceId = try requireCurrentWorkspaceId( + windowHandle: windowHandle, + client: client, + command: socketCommand + ) + } else if resolvePanelOption, + hasOption("--panel", in: commandArgs) { + targetWorkspaceId = try resolveWorkspaceId(nil, client: client, windowHandle: windowHandle) + } else { + targetWorkspaceId = nil + } + + var forwardedArgs: [String] = [] + var index = 0 + var parsingOptions = true while index < commandArgs.count { let arg = commandArgs[index] if parsingOptions, arg == "--" { @@ -17441,19 +17458,10 @@ struct CMUXCLI { continue } if parsingOptions, arg == "--workspace", index + 1 < commandArgs.count { - let workspaceId = try resolveWorkspaceId(commandArgs[index + 1], client: client, windowHandle: windowHandle) - forwardedArgs.append("--tab=\(workspaceId)") - resolvedExplicitWorkspace = true - targetWorkspaceId = workspaceId index += 2 continue } if parsingOptions, arg.hasPrefix("--workspace=") { - let rawWorkspace = String(arg.dropFirst("--workspace=".count)) - let workspaceId = try resolveWorkspaceId(rawWorkspace, client: client, windowHandle: windowHandle) - forwardedArgs.append("--tab=\(workspaceId)") - resolvedExplicitWorkspace = true - targetWorkspaceId = workspaceId index += 1 continue } @@ -17469,25 +17477,8 @@ struct CMUXCLI { index += 1 } - if !resolvedExplicitWorkspace, - let workspaceArg = workspaceFromArgsOrEnv(commandArgs, windowOverride: windowOverride) { - let workspaceId = try resolveWorkspaceId(workspaceArg, client: client, windowHandle: windowHandle) - insertArgumentBeforeSeparator("--tab=\(workspaceId)", into: &forwardedArgs) - targetWorkspaceId = workspaceId - } else if !resolvedExplicitWorkspace, - let windowHandle { - let workspaceId = try requireCurrentWorkspaceId( - windowHandle: windowHandle, - client: client, - command: socketCommand - ) - insertArgumentBeforeSeparator("--tab=\(workspaceId)", into: &forwardedArgs) - targetWorkspaceId = workspaceId - } else if resolvePanelOption, - hasOption("--panel", in: commandArgs) { - let workspaceId = try resolveWorkspaceId(nil, client: client, windowHandle: windowHandle) - insertArgumentBeforeSeparator("--tab=\(workspaceId)", into: &forwardedArgs) - targetWorkspaceId = workspaceId + if let targetWorkspaceId { + insertArgumentBeforeSeparator("--tab=\(targetWorkspaceId)", into: &forwardedArgs) } if resolvePanelOption, From 868d0570951377bb7dbfef36cf15f5991f182f9a Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 8 Jul 2026 20:58:20 -0700 Subject: [PATCH 38/46] sidebar rows: spinner for running, nothing for idle; pane renames reach row labels - Running agents show a small native spinner instead of a state word; idle renders nothing; waiting keeps the orange dot + word. Rows whose agent reported only a status (no lifecycle) keep their reported color dot. - panelTitles/panelCustomTitles join the sidebar observation pipeline and its Equatable state, so renaming a pane invalidates the snapshot and the row label updates immediately. --- Sources/SidebarAgentStatusRowViews.swift | 60 ++++++++++++++++++----- Sources/WorkspaceSidebarObservation.swift | 10 +++- 2 files changed, 57 insertions(+), 13 deletions(-) diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index cfa8f3a7f14f..fb7cb9de7c64 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -291,10 +291,14 @@ enum SidebarAgentRowStateStyle { } /// The row's status line: the reported value, else the lifecycle text. + /// Idle intentionally renders nothing: absence of activity needs no label. static func statusText(for row: SidebarAgentStatusRow) -> String? { if let value = row.value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty { return value } + if row.lifecycle == .idle { + return nil + } return lifecycleText(for: row) } } @@ -545,17 +549,7 @@ private struct SidebarAgentGraphiteRow: View { .lineLimit(1) .truncationMode(.middle) Spacer(minLength: 4) - if let stateColor = SidebarAgentRowStateStyle.stateColor(for: row) { - Circle() - .fill(stateColor) - .frame(width: 5 * fontScale, height: 5 * fontScale) - } - if let word = SidebarAgentRowStateStyle.stateWord(for: row) { - Text(word) - .cmuxFont(size: 9.5 * fontScale) - .foregroundColor(stateWordColor) - .lineLimit(1) - } + trailingState } .padding(.vertical, 3) .padding(.horizontal, 7) @@ -568,6 +562,37 @@ private struct SidebarAgentGraphiteRow: View { .safeHelp(tooltip) } + /// Running shows a spinner (no state word); waiting keeps the orange + /// dot + word; idle shows nothing. Lifecycle-less rows (BYO agents that + /// only reported a status) keep their reported color as a small dot. + @ViewBuilder + private var trailingState: some View { + switch row.lifecycle { + case .running: + SidebarAgentRowSpinner(fontScale: fontScale) + case .needsInput: + if let stateColor = SidebarAgentRowStateStyle.stateColor(for: row) { + Circle() + .fill(stateColor) + .frame(width: 5 * fontScale, height: 5 * fontScale) + } + if let word = SidebarAgentRowStateStyle.stateWord(for: row) { + Text(word) + .cmuxFont(size: 9.5 * fontScale) + .foregroundColor(stateWordColor) + .lineLimit(1) + } + case .idle, .unknown: + EmptyView() + case nil: + if let raw = row.color, let reported = Color(hex: raw) { + Circle() + .fill(reported) + .frame(width: 5 * fontScale, height: 5 * fontScale) + } + } + } + @ViewBuilder private var rowBackground: some View { if isActiveAgent { @@ -603,3 +628,16 @@ private struct SidebarAgentGraphiteRow: View { ].compactMap { $0 }.joined(separator: " · ") } } + + +/// Small native activity spinner sized for a sidebar agent row. +struct SidebarAgentRowSpinner: View { + let fontScale: CGFloat + + var body: some View { + ProgressView() + .controlSize(.small) + .scaleEffect(0.55 * fontScale) + .frame(width: 10 * fontScale, height: 10 * fontScale) + } +} diff --git a/Sources/WorkspaceSidebarObservation.swift b/Sources/WorkspaceSidebarObservation.swift index 3c86232e2b22..832f02eef6fb 100644 --- a/Sources/WorkspaceSidebarObservation.swift +++ b/Sources/WorkspaceSidebarObservation.swift @@ -43,6 +43,10 @@ private struct SidebarObservationState: Equatable { let panels: SidebarPanelObservationState let panelDirectories: [UUID: String] let panelDirectoryDisplayLabels: [UUID: String] + // Agent row labels resolve pane rename > surface title, so both must + // invalidate the sidebar snapshot or a rename never reaches the row. + let panelTitles: [UUID: String] + let panelCustomTitles: [UUID: String] let directoryChangeRevision: UInt64 let statusEntries: [String: SidebarStatusEntry] let metadataBlocks: [String: SidebarMetadataBlock] @@ -158,8 +162,8 @@ extension Workspace { remoteFields ) .combineLatest($listeningPorts, sidebarMetadata.panelDirectoryDisplayLabelsPublisher) - .combineLatest(directoryChangeRevision) - .compactMap { [weak self] values, directoryChangeRevision -> SidebarObservationState? in + .combineLatest(directoryChangeRevision, Publishers.CombineLatest($panelTitles, $panelCustomTitles)) + .compactMap { [weak self] values, directoryChangeRevision, panelTitleFields -> SidebarObservationState? in guard let self else { return nil } let (groupedFields, listeningPorts, panelDirectoryDisplayLabels) = values let workspaceFields = groupedFields.0 @@ -172,6 +176,8 @@ extension Workspace { panels: workspaceFields.2, panelDirectories: workspaceFields.3, panelDirectoryDisplayLabels: panelDirectoryDisplayLabels, + panelTitles: panelTitleFields.0, + panelCustomTitles: panelTitleFields.1, directoryChangeRevision: directoryChangeRevision, statusEntries: metadataFields.0, metadataBlocks: metadataFields.1, From fcf43ddba3f2856822b2a7eff83ab9dbb8fd8c5b Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 9 Jul 2026 16:58:06 -0700 Subject: [PATCH 39/46] sidebar agent rows: feature flag + canonical cross-workspace row focus - New PostHog flag sidebar-agent-rows-enabled-release (DEBUG default on, release default off) gates the rows, the graphite card styling, and the lab variants; off restores the pre-feature status pills exactly. - Row clicks route through notificationNavigation.open, the same primitive notification jumps use, so clicking an agent in an unfocused workspace focuses THAT pane instead of losing to the workspace's own focus restoration. --- Resources/Localizable.xcstrings | 34 ++++++++++++++++++++++ Sources/ContentView.swift | 36 +++++++++++++++++++----- Sources/FeatureFlags.swift | 28 ++++++++++++++++++ Sources/SidebarAgentRowsVariantLab.swift | 9 +++++- 4 files changed, 99 insertions(+), 8 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 42733182d438..3621846285bb 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -99150,6 +99150,40 @@ } } }, + "featureFlags.sidebarAgentRows.description": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Shows one row per agent pane in the sidebar with live state, replacing the single status pill." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "サイドバーにエージェントのペインごとの行をライブ状態付きで表示し、単一のステータスピルを置き換えます。" + } + } + } + }, + "featureFlags.sidebarAgentRows.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Per-agent sidebar rows" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "エージェントごとのサイドバー行" + } + } + } + }, "featureFlags.proUpgrade.description": { "extractionState": "manual", "localizations": { diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index a47f1ac6a294..5b656495d43b 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -13363,6 +13363,16 @@ struct TabItemView: View, Equatable { // workspace card's own selection background and border. @ObservedObject private var agentRowsVariantStore = SidebarAgentRowsVariantStore.shared + /// Feature-flag gate for the whole per-agent rows surface (rows, graphite + /// card styling, lab variants). Off = the pre-feature status pills. + private var agentRowsFeatureEnabled: Bool { + CmuxFeatureFlags.shared.isSidebarAgentRowsEnabled + } + + private var usesGraphiteVariant: Bool { + agentRowsFeatureEnabled && agentRowsVariantStore.variant == .graphite + } + private var isActive: Bool { observedIsActive ?? (tabManager.selectedTabId == tab.id) } @@ -13381,7 +13391,7 @@ struct TabItemView: View, Equatable { // selection color), borderless. The foreground helper below // auto-contrasts on it. Dies with the variant lab once a final design // ships. - if agentRowsVariantStore.variant == .graphite { + if usesGraphiteVariant { return graphiteSelectionFillNSColor } return sidebarSelectedWorkspaceBackgroundNSColor( @@ -13439,8 +13449,18 @@ struct TabItemView: View, Equatable { fontScale: fontScale, onFocus: { updateSelection() }, onFocusPanel: { panelId in - updateSelection() - tab.focusPanel(panelId) + // The notification-jump path owns cross-workspace focus: + // plain updateSelection + focusPanel loses to the + // workspace's own focus restoration when the workspace + // was not already selected. + if AppDelegate.shared?.notificationNavigation.open( + tabId: tab.id, + surfaceId: panelId, + notificationId: nil + ) != true { + updateSelection() + tab.focusPanel(panelId) + } } ) } @@ -13502,7 +13522,7 @@ struct TabItemView: View, Equatable { } private var activeBorderLineWidth: CGFloat { - if agentRowsVariantStore.variant == .graphite { + if usesGraphiteVariant { return 0 } switch activeTabIndicatorStyle { @@ -13515,7 +13535,7 @@ struct TabItemView: View, Equatable { private var activeBorderColor: Color { guard isActive else { return .clear } - if agentRowsVariantStore.variant == .graphite { + if usesGraphiteVariant { return .clear } switch activeTabIndicatorStyle { @@ -14626,7 +14646,7 @@ struct TabItemView: View, Equatable { private var backgroundColor: Color { // Debug lab "graphite" prototype v2: dark tint of the workspace's // own color. Dies with the variant lab once a final design ships. - if agentRowsVariantStore.variant == .graphite, isActive { + if usesGraphiteVariant, isActive { return Color(nsColor: graphiteSelectionFillNSColor) } let style = sidebarWorkspaceRowBackgroundStyle( @@ -14928,7 +14948,9 @@ struct TabItemView: View, Equatable { return pullRequestDisplays(orderedPanelIds: orderedPanelIds) }() - let agentStatusRows = detailVisibility.showsMetadata ? tab.sidebarAgentStatusRows() : [] + let agentStatusRows = detailVisibility.showsMetadata && CmuxFeatureFlags.shared.isSidebarAgentRowsEnabled + ? tab.sidebarAgentStatusRows() + : [] let agentRowStatusKeys = Set(agentStatusRows.map(\.statusKey)) return SidebarWorkspaceSnapshotBuilder.Snapshot( diff --git a/Sources/FeatureFlags.swift b/Sources/FeatureFlags.swift index ff6c7842daee..384cb151d2f3 100644 --- a/Sources/FeatureFlags.swift +++ b/Sources/FeatureFlags.swift @@ -38,6 +38,13 @@ final class CmuxFeatureFlags { #endif private static let mobileConnectButtonDefault = true + + #if DEBUG + private static let sidebarAgentRowsDefault = true + #else + private static let sidebarAgentRowsDefault = false + #endif + private static let overrideKeyPrefix = "cmux.flags.override." // Order is load-bearing for the typed accessors below. A keyed lookup would @@ -74,6 +81,23 @@ final class CmuxFeatureFlags { ), defaultWhenUnavailable: Self.mobileConnectButtonDefault ), + + // FLAG(key: sidebar-agent-rows-enabled-release, owner: lawrencecchen, + // reviewBy: 2026-10-01, defaultWhenUnavailable: false) + // Per-agent sidebar rows: one row per agent pane inside the + // workspace card (graphite prototype), spinner/waiting states, + // click-to-focus, and the BYO-agent dynamic row keys. Release + // builds keep the pre-feature status pills until the PostHog flag + // is enabled; DEBUG keeps the rows on for dogfood. + CmuxFeatureFlagDefinition( + key: "sidebar-agent-rows-enabled-release", + title: String(localized: "featureFlags.sidebarAgentRows.title", defaultValue: "Per-agent sidebar rows"), + flagDescription: String( + localized: "featureFlags.sidebarAgentRows.description", + defaultValue: "Shows one row per agent pane in the sidebar with live state, replacing the single status pill." + ), + defaultWhenUnavailable: Self.sidebarAgentRowsDefault + ), ] } @@ -85,6 +109,10 @@ final class CmuxFeatureFlags { effectiveValue(for: Self.allFlags[1]) } + var isSidebarAgentRowsEnabled: Bool { + effectiveValue(for: Self.allFlags[2]) + } + @ObservationIgnored private let defaults: UserDefaults @ObservationIgnored diff --git a/Sources/SidebarAgentRowsVariantLab.swift b/Sources/SidebarAgentRowsVariantLab.swift index ee299e916039..3032c0b3ad6a 100644 --- a/Sources/SidebarAgentRowsVariantLab.swift +++ b/Sources/SidebarAgentRowsVariantLab.swift @@ -213,13 +213,20 @@ struct SidebarGlobalAgentsSection: View { @ObservedObject private var store = SidebarAgentRowsVariantStore.shared private func focus(workspaceId: UUID, panelId: UUID) { + if AppDelegate.shared?.notificationNavigation.open( + tabId: workspaceId, + surfaceId: panelId, + notificationId: nil + ) == true { + return + } guard let tab = tabManager.tabs.first(where: { $0.id == workspaceId }) else { return } tabManager.selectedTabId = workspaceId tab.focusPanel(panelId) } var body: some View { - if store.variant == .globalSection { + if CmuxFeatureFlags.shared.isSidebarAgentRowsEnabled, store.variant == .globalSection { let groups = tabManager.tabs.compactMap { tab -> (workspaceId: UUID, title: String, rows: [SidebarAgentStatusRow])? in let rows = tab.sidebarAgentStatusRows() guard !rows.isEmpty else { return nil } From c25854497b653b683b37d6a7af0753ebcdd48a04 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 9 Jul 2026 19:10:16 -0700 Subject: [PATCH 40/46] Split new >=500-line files to satisfy the file-length budget guard workflow-guard-tests rejects files that enter the tracked budget at >=500 lines. Pure moves, no behavior change: - SidebarAgentStatusRowViews.swift -> graphite row views split into SidebarAgentGraphiteRowViews.swift - PerAgentSidebarStatusRowTests.swift -> clearing/replacement/summary tests split into PerAgentSidebarStatusRowClearingTests.swift - SidebarWorkspaceSnapshotRefreshPolicyTests.swift -> scroll-policy and row-interaction suites split into their own test files (matching the pre-revert extraction shape) --- .github/swift-file-length-budget.tsv | 3 - Sources/SidebarAgentGraphiteRowViews.swift | 197 +++++++++++ Sources/SidebarAgentStatusRowViews.swift | 188 ----------- cmux.xcodeproj/project.pbxproj | 16 + ...erAgentSidebarStatusRowClearingTests.swift | 184 +++++++++++ cmuxTests/PerAgentSidebarStatusRowTests.swift | 155 --------- ...arSelectedWorkspaceScrollPolicyTests.swift | 100 ++++++ ...barWorkspaceRowInteractionStateTests.swift | 232 +++++++++++++ ...rWorkspaceSnapshotRefreshPolicyTests.swift | 311 ------------------ 9 files changed, 729 insertions(+), 657 deletions(-) create mode 100644 Sources/SidebarAgentGraphiteRowViews.swift create mode 100644 cmuxTests/PerAgentSidebarStatusRowClearingTests.swift create mode 100644 cmuxTests/SidebarSelectedWorkspaceScrollPolicyTests.swift create mode 100644 cmuxTests/SidebarWorkspaceRowInteractionStateTests.swift diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 6b9ebb910e9b..e4a1fce041c9 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -173,7 +173,6 @@ 650 Sources/Panels/MarkdownRemoteImageLoader.swift 648 cmuxTests/TerminalNotificationQueueTests.swift 644 Packages/macOS/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentLaunchSanitizerTests.swift -643 Sources/SidebarAgentStatusRowViews.swift 641 cmuxTests/CommandPaletteNucleoFFITests.swift 638 cmuxTests/RemoteTmuxControlParserTests.swift 637 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift @@ -234,9 +233,7 @@ 526 Packages/macOS/CMUXAgentLaunch/Sources/CMUXAgentLaunch/Workstream/WorkstreamStore.swift 525 Packages/macOS/CmuxSettings/Sources/CmuxSettings/SocketControl/SocketControlSettings.swift 524 CLI/CMUXCLI+AutoNaming.swift -523 cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift 522 Sources/TerminalPaneDropTargetView.swift -522 cmuxTests/PerAgentSidebarStatusRowTests.swift 520 CLI/CMUXCLI+AmpExtension.swift 520 cmuxTests/MainWindowVisibilityControllerTests.swift 519 Packages/macOS/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-two-column-cockpit-sidebar.swift diff --git a/Sources/SidebarAgentGraphiteRowViews.swift b/Sources/SidebarAgentGraphiteRowViews.swift new file mode 100644 index 000000000000..48fb213586c2 --- /dev/null +++ b/Sources/SidebarAgentGraphiteRowViews.swift @@ -0,0 +1,197 @@ +import AppKit +import CmuxFoundation +import CmuxSidebar +import SwiftUI + +/// Graphite (in-card) presentation of the per-agent rows, split from +/// `SidebarAgentStatusRowViews.swift` to satisfy the new-file length budget. +/// Rows receive immutable value snapshots and closure action bundles only, +/// per the sidebar list snapshot-boundary rule. +struct SidebarAgentStatusGraphiteRows: View { + let rows: [SidebarAgentStatusRow] + let activePanelId: UUID? + let isActive: Bool + let activeForegroundColor: Color + let activeAgentRowColor: Color + let fontScale: CGFloat + let onFocus: () -> Void + let onFocusPanel: (UUID) -> Void + + @State private var isCollapsed = false + + var body: some View { + VStack(alignment: .leading, spacing: 1) { + header + if !isCollapsed { + ForEach(rows) { row in + SidebarAgentGraphiteRow( + row: row, + // Only the selected workspace hosts the globally + // focused pane; unselected workspaces remember a + // focus but the "camera" is not on them. + isActiveAgent: isActive && row.panelId == activePanelId, + isActive: isActive, + activeForegroundColor: activeForegroundColor, + activeAgentRowColor: activeAgentRowColor, + fontScale: fontScale, + onFocusPanel: onFocusPanel + ) + } + } + } + .padding(.top, 3) + } + + private var header: some View { + let summary = SidebarAgentStatusRowsSummary(rows: rows) + return Button { + onFocus() + withAnimation(.easeInOut(duration: 0.15)) { + isCollapsed.toggle() + } + } label: { + HStack(spacing: 4) { + CmuxSystemSymbolImage( + magnified: isCollapsed ? "chevron.right" : "chevron.down", + pointSize: 6.5 * fontScale, + weight: .semibold + ) + .foregroundColor(secondaryColor.opacity(0.8)) + if isCollapsed, let accent = summary.accentColorHex, let color = Color(hex: accent) { + Circle() + .fill(color) + .frame(width: 5 * fontScale, height: 5 * fontScale) + } + Text(summary.text) + .cmuxFont(size: 9.5 * fontScale, weight: .semibold) + .foregroundColor(secondaryColor) + .lineLimit(1) + Spacer(minLength: 0) + } + .padding(.vertical, 1) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .safeHelp(summary.text) + } + + private var secondaryColor: Color { + isActive ? activeForegroundColor.opacity(0.7) : .secondary + } +} + +private struct SidebarAgentGraphiteRow: View { + let row: SidebarAgentStatusRow + let isActiveAgent: Bool + let isActive: Bool + let activeForegroundColor: Color + let activeAgentRowColor: Color + let fontScale: CGFloat + let onFocusPanel: (UUID) -> Void + + @State private var isHovering = false + + var body: some View { + Button { + onFocusPanel(row.panelId) + } label: { + HStack(spacing: 6) { + SidebarAgentBrandIcon(row: row, fontScale: fontScale) + Text(row.paneLabel ?? SidebarAgentRowStateStyle.agentDisplayName(statusKey: row.statusKey)) + .cmuxFont(size: 10.5 * fontScale, weight: .medium) + .foregroundColor(nameColor) + .lineLimit(1) + .truncationMode(.middle) + Spacer(minLength: 4) + trailingState + } + .padding(.vertical, 3) + .padding(.horizontal, 7) + .frame(maxWidth: .infinity, alignment: .leading) + .background(rowBackground) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .onHover { isHovering = $0 } + .safeHelp(tooltip) + } + + /// Running shows a spinner (no state word); waiting keeps the orange + /// dot + word; idle shows nothing. Lifecycle-less rows (BYO agents that + /// only reported a status) keep their reported color as a small dot. + @ViewBuilder + private var trailingState: some View { + switch row.lifecycle { + case .running: + SidebarAgentRowSpinner(fontScale: fontScale) + case .needsInput: + if let stateColor = SidebarAgentRowStateStyle.stateColor(for: row) { + Circle() + .fill(stateColor) + .frame(width: 5 * fontScale, height: 5 * fontScale) + } + if let word = SidebarAgentRowStateStyle.stateWord(for: row) { + Text(word) + .cmuxFont(size: 9.5 * fontScale) + .foregroundColor(stateWordColor) + .lineLimit(1) + } + case .idle, .unknown: + EmptyView() + case nil: + if let raw = row.color, let reported = Color(hex: raw) { + Circle() + .fill(reported) + .frame(width: 5 * fontScale, height: 5 * fontScale) + } + } + } + + @ViewBuilder + private var rowBackground: some View { + if isActiveAgent { + // "Even darker of the same color": the active agent sits in a + // deeper shade of the card's own selection tint. + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(activeAgentRowColor) + } else { + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(Color.primary.opacity(isHovering ? 0.07 : 0)) + } + } + + private var nameColor: Color { + // isActiveAgent implies isActive (gated at the call site). + if isActiveAgent { + return activeForegroundColor + } + return isActive ? activeForegroundColor.opacity(0.92) : .primary.opacity(0.85) + } + + private var stateWordColor: Color { + if row.lifecycle == .needsInput { + return Color(hex: "#FF9F0A") ?? .orange + } + return isActive ? activeForegroundColor.opacity(0.6) : .secondary.opacity(0.8) + } + + private var tooltip: String { + [ + row.paneLabel ?? SidebarAgentRowStateStyle.agentDisplayName(statusKey: row.statusKey), + SidebarAgentRowStateStyle.statusText(for: row), + ].compactMap { $0 }.joined(separator: " · ") + } +} + + +/// Small native activity spinner sized for a sidebar agent row. +struct SidebarAgentRowSpinner: View { + let fontScale: CGFloat + + var body: some View { + ProgressView() + .controlSize(.small) + .scaleEffect(0.55 * fontScale) + .frame(width: 10 * fontScale, height: 10 * fontScale) + } +} diff --git a/Sources/SidebarAgentStatusRowViews.swift b/Sources/SidebarAgentStatusRowViews.swift index fb7cb9de7c64..103ee8d17539 100644 --- a/Sources/SidebarAgentStatusRowViews.swift +++ b/Sources/SidebarAgentStatusRowViews.swift @@ -453,191 +453,3 @@ struct SidebarAgentStatusEntryRowView: View { /// focused pane). Selection styling of the card itself is handled by /// `TabItemView` (graphite instead of the blue selection) while this variant /// is active. -struct SidebarAgentStatusGraphiteRows: View { - let rows: [SidebarAgentStatusRow] - let activePanelId: UUID? - let isActive: Bool - let activeForegroundColor: Color - let activeAgentRowColor: Color - let fontScale: CGFloat - let onFocus: () -> Void - let onFocusPanel: (UUID) -> Void - - @State private var isCollapsed = false - - var body: some View { - VStack(alignment: .leading, spacing: 1) { - header - if !isCollapsed { - ForEach(rows) { row in - SidebarAgentGraphiteRow( - row: row, - // Only the selected workspace hosts the globally - // focused pane; unselected workspaces remember a - // focus but the "camera" is not on them. - isActiveAgent: isActive && row.panelId == activePanelId, - isActive: isActive, - activeForegroundColor: activeForegroundColor, - activeAgentRowColor: activeAgentRowColor, - fontScale: fontScale, - onFocusPanel: onFocusPanel - ) - } - } - } - .padding(.top, 3) - } - - private var header: some View { - let summary = SidebarAgentStatusRowsSummary(rows: rows) - return Button { - onFocus() - withAnimation(.easeInOut(duration: 0.15)) { - isCollapsed.toggle() - } - } label: { - HStack(spacing: 4) { - CmuxSystemSymbolImage( - magnified: isCollapsed ? "chevron.right" : "chevron.down", - pointSize: 6.5 * fontScale, - weight: .semibold - ) - .foregroundColor(secondaryColor.opacity(0.8)) - if isCollapsed, let accent = summary.accentColorHex, let color = Color(hex: accent) { - Circle() - .fill(color) - .frame(width: 5 * fontScale, height: 5 * fontScale) - } - Text(summary.text) - .cmuxFont(size: 9.5 * fontScale, weight: .semibold) - .foregroundColor(secondaryColor) - .lineLimit(1) - Spacer(minLength: 0) - } - .padding(.vertical, 1) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .safeHelp(summary.text) - } - - private var secondaryColor: Color { - isActive ? activeForegroundColor.opacity(0.7) : .secondary - } -} - -private struct SidebarAgentGraphiteRow: View { - let row: SidebarAgentStatusRow - let isActiveAgent: Bool - let isActive: Bool - let activeForegroundColor: Color - let activeAgentRowColor: Color - let fontScale: CGFloat - let onFocusPanel: (UUID) -> Void - - @State private var isHovering = false - - var body: some View { - Button { - onFocusPanel(row.panelId) - } label: { - HStack(spacing: 6) { - SidebarAgentBrandIcon(row: row, fontScale: fontScale) - Text(row.paneLabel ?? SidebarAgentRowStateStyle.agentDisplayName(statusKey: row.statusKey)) - .cmuxFont(size: 10.5 * fontScale, weight: .medium) - .foregroundColor(nameColor) - .lineLimit(1) - .truncationMode(.middle) - Spacer(minLength: 4) - trailingState - } - .padding(.vertical, 3) - .padding(.horizontal, 7) - .frame(maxWidth: .infinity, alignment: .leading) - .background(rowBackground) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .onHover { isHovering = $0 } - .safeHelp(tooltip) - } - - /// Running shows a spinner (no state word); waiting keeps the orange - /// dot + word; idle shows nothing. Lifecycle-less rows (BYO agents that - /// only reported a status) keep their reported color as a small dot. - @ViewBuilder - private var trailingState: some View { - switch row.lifecycle { - case .running: - SidebarAgentRowSpinner(fontScale: fontScale) - case .needsInput: - if let stateColor = SidebarAgentRowStateStyle.stateColor(for: row) { - Circle() - .fill(stateColor) - .frame(width: 5 * fontScale, height: 5 * fontScale) - } - if let word = SidebarAgentRowStateStyle.stateWord(for: row) { - Text(word) - .cmuxFont(size: 9.5 * fontScale) - .foregroundColor(stateWordColor) - .lineLimit(1) - } - case .idle, .unknown: - EmptyView() - case nil: - if let raw = row.color, let reported = Color(hex: raw) { - Circle() - .fill(reported) - .frame(width: 5 * fontScale, height: 5 * fontScale) - } - } - } - - @ViewBuilder - private var rowBackground: some View { - if isActiveAgent { - // "Even darker of the same color": the active agent sits in a - // deeper shade of the card's own selection tint. - RoundedRectangle(cornerRadius: 5, style: .continuous) - .fill(activeAgentRowColor) - } else { - RoundedRectangle(cornerRadius: 5, style: .continuous) - .fill(Color.primary.opacity(isHovering ? 0.07 : 0)) - } - } - - private var nameColor: Color { - // isActiveAgent implies isActive (gated at the call site). - if isActiveAgent { - return activeForegroundColor - } - return isActive ? activeForegroundColor.opacity(0.92) : .primary.opacity(0.85) - } - - private var stateWordColor: Color { - if row.lifecycle == .needsInput { - return Color(hex: "#FF9F0A") ?? .orange - } - return isActive ? activeForegroundColor.opacity(0.6) : .secondary.opacity(0.8) - } - - private var tooltip: String { - [ - row.paneLabel ?? SidebarAgentRowStateStyle.agentDisplayName(statusKey: row.statusKey), - SidebarAgentRowStateStyle.statusText(for: row), - ].compactMap { $0 }.joined(separator: " · ") - } -} - - -/// Small native activity spinner sized for a sidebar agent row. -struct SidebarAgentRowSpinner: View { - let fontScale: CGFloat - - var body: some View { - ProgressView() - .controlSize(.small) - .scaleEffect(0.55 * fontScale) - .frame(width: 10 * fontScale, height: 10 * fontScale) - } -} diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 67b7b4007a8d..4e5ddb2fe752 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -934,6 +934,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources A5001425 /* PDFPreviewChromeDebugWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001424 /* PDFPreviewChromeDebugWindowController.swift */; }; 5B21C4E15B21C4E15B21C4E1 /* PerAgentSidebarStatusDisplacementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B21C4E25B21C4E25B21C4E2 /* PerAgentSidebarStatusDisplacementTests.swift */; }; 2255A23ACD5B366E35B6ED0F /* PerAgentSidebarStatusPersistenceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EDCC62AF23B380D1227E261 /* PerAgentSidebarStatusPersistenceTests.swift */; }; + 263D65B017D9E9AC6F525C27 /* PerAgentSidebarStatusRowClearingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C414665C5461092EFE64FE11 /* PerAgentSidebarStatusRowClearingTests.swift */; }; DEC515B488104031B49F68F0 /* PerAgentSidebarStatusRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF3A0288F87945DC8889FE91 /* PerAgentSidebarStatusRowTests.swift */; }; D1F0A00400000000000000D1 /* PhoneForwardingMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1F0A00400000000000000D2 /* PhoneForwardingMode.swift */; }; D1F0A00100000000000000A1 /* PhonePushClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1F0A00100000000000000A2 /* PhonePushClient.swift */; }; @@ -1176,6 +1177,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources C3467AB10000000000000001 /* ShortcutWhenClauseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3467AB10000000000000002 /* ShortcutWhenClauseTests.swift */; }; A6AC71020000000000000001 /* SidebarAgentActivityIndicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6AC71030000000000000001 /* SidebarAgentActivityIndicator.swift */; }; A6AC71040000000000000001 /* SidebarAgentActivitySummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6AC71050000000000000001 /* SidebarAgentActivitySummary.swift */; }; + 492FBAC7FCA33879352B4204 /* SidebarAgentGraphiteRowViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E409BA6FC74C8E2681694F1 /* SidebarAgentGraphiteRowViews.swift */; }; 14FE4CD3BCAD423796E56EE5 /* SidebarAgentRowsVariantLab.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4722F35D10C94D12ADC4D017 /* SidebarAgentRowsVariantLab.swift */; }; 2FB188449942360CAB895143 /* SidebarAgentStatusRowsSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D2990638B9E75D4B02AF14F /* SidebarAgentStatusRowsSummary.swift */; }; 7A11AA057A11AA057A11AA05 /* SidebarAgentStatusRowViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */; }; @@ -1211,6 +1213,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources AABBCC00000000000000020A /* SidebarRowDragGate.swift in Sources */ = {isa = PBXBuildFile; fileRef = AABBCC000000000000000209 /* SidebarRowDragGate.swift */; }; C0DE35010000000000000001 /* SidebarScrim.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE35010000000000000002 /* SidebarScrim.swift */; }; C9A57513C9A57513C9A57513 /* SidebarScrollViewConfiguratorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9A57514C9A57514C9A57514 /* SidebarScrollViewConfiguratorTests.swift */; }; + 51CA9864B90D2721F384B327 /* SidebarSelectedWorkspaceScrollPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 221E4C0E77F96E7A38811AEE /* SidebarSelectedWorkspaceScrollPolicyTests.swift */; }; E62155868BB29FEB5DAAAF25 /* SidebarSelectionState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD52285508B1D6A9875E7B3 /* SidebarSelectionState.swift */; }; F57072635F25EBCA741E125D /* SidebarState.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1614EAD3CCF70A177A51BD1 /* SidebarState.swift */; }; D7344F010000000000000001 /* SidebarTabDragPayload.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7344F010000000000000002 /* SidebarTabDragPayload.swift */; }; @@ -1240,6 +1243,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources D35450070000000000000007 /* SidebarWorkspaceRowHoverReconciler.swift in Sources */ = {isa = PBXBuildFile; fileRef = D35450070000000000000008 /* SidebarWorkspaceRowHoverReconciler.swift */; }; D35450070000000000000009 /* SidebarWorkspaceRowHoverReconcilerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3545007000000000000000A /* SidebarWorkspaceRowHoverReconcilerView.swift */; }; D3545007000000000000000B /* SidebarWorkspaceRowHoverTrackingModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3545007000000000000000C /* SidebarWorkspaceRowHoverTrackingModifier.swift */; }; + 2E58C01936DF355241CC6911 /* SidebarWorkspaceRowInteractionStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B96BD18955B1A751A8493637 /* SidebarWorkspaceRowInteractionStateTests.swift */; }; D35450030000000000000003 /* SidebarWorkspaceRowMenuTrackingReconciler.swift in Sources */ = {isa = PBXBuildFile; fileRef = D35450030000000000000004 /* SidebarWorkspaceRowMenuTrackingReconciler.swift */; }; D35450030000000000000005 /* SidebarWorkspaceRowMenuTrackingReconcilerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D35450030000000000000006 /* SidebarWorkspaceRowMenuTrackingReconcilerView.swift */; }; C9A57505C9A57505C9A57505 /* SidebarWorkspaceScrollLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9A57506C9A57506C9A57506 /* SidebarWorkspaceScrollLayoutTests.swift */; }; @@ -2553,6 +2557,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5001424 /* PDFPreviewChromeDebugWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/PDFPreviewChromeDebugWindowController.swift; sourceTree = ""; }; 5B21C4E25B21C4E25B21C4E2 /* PerAgentSidebarStatusDisplacementTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerAgentSidebarStatusDisplacementTests.swift; sourceTree = ""; }; 3EDCC62AF23B380D1227E261 /* PerAgentSidebarStatusPersistenceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerAgentSidebarStatusPersistenceTests.swift; sourceTree = ""; }; + C414665C5461092EFE64FE11 /* PerAgentSidebarStatusRowClearingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerAgentSidebarStatusRowClearingTests.swift; sourceTree = ""; }; EF3A0288F87945DC8889FE91 /* PerAgentSidebarStatusRowTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerAgentSidebarStatusRowTests.swift; sourceTree = ""; }; D1F0A00400000000000000D2 /* PhoneForwardingMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PhoneForwardingMode.swift; sourceTree = ""; }; D1F0A00100000000000000A2 /* PhonePushClient.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PhonePushClient.swift; sourceTree = ""; }; @@ -2788,6 +2793,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C3467AB10000000000000002 /* ShortcutWhenClauseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShortcutWhenClauseTests.swift; sourceTree = ""; }; A6AC71030000000000000001 /* SidebarAgentActivityIndicator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarAgentActivityIndicator.swift; sourceTree = ""; }; A6AC71050000000000000001 /* SidebarAgentActivitySummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentActivitySummary.swift; sourceTree = ""; }; + 5E409BA6FC74C8E2681694F1 /* SidebarAgentGraphiteRowViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentGraphiteRowViews.swift; sourceTree = ""; }; 4722F35D10C94D12ADC4D017 /* SidebarAgentRowsVariantLab.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentRowsVariantLab.swift; sourceTree = ""; }; 1D2990638B9E75D4B02AF14F /* SidebarAgentStatusRowsSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentStatusRowsSummary.swift; sourceTree = ""; }; 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentStatusRowViews.swift; sourceTree = ""; }; @@ -2823,6 +2829,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = AABBCC000000000000000209 /* SidebarRowDragGate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarRowDragGate.swift; sourceTree = ""; }; C0DE35010000000000000002 /* SidebarScrim.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarScrim.swift; sourceTree = ""; }; C9A57514C9A57514C9A57514 /* SidebarScrollViewConfiguratorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarScrollViewConfiguratorTests.swift; sourceTree = ""; }; + 221E4C0E77F96E7A38811AEE /* SidebarSelectedWorkspaceScrollPolicyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarSelectedWorkspaceScrollPolicyTests.swift; sourceTree = ""; }; 9AD52285508B1D6A9875E7B3 /* SidebarSelectionState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarSelectionState.swift; sourceTree = ""; }; D1614EAD3CCF70A177A51BD1 /* SidebarState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarState.swift; sourceTree = ""; }; D7344F010000000000000002 /* SidebarTabDragPayload.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarTabDragPayload.swift; sourceTree = ""; }; @@ -2852,6 +2859,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = D35450070000000000000008 /* SidebarWorkspaceRowHoverReconciler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarWorkspaceRowHoverReconciler.swift; sourceTree = ""; }; D3545007000000000000000A /* SidebarWorkspaceRowHoverReconcilerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarWorkspaceRowHoverReconcilerView.swift; sourceTree = ""; }; D3545007000000000000000C /* SidebarWorkspaceRowHoverTrackingModifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarWorkspaceRowHoverTrackingModifier.swift; sourceTree = ""; }; + B96BD18955B1A751A8493637 /* SidebarWorkspaceRowInteractionStateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarWorkspaceRowInteractionStateTests.swift; sourceTree = ""; }; D35450030000000000000004 /* SidebarWorkspaceRowMenuTrackingReconciler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarWorkspaceRowMenuTrackingReconciler.swift; sourceTree = ""; }; D35450030000000000000006 /* SidebarWorkspaceRowMenuTrackingReconcilerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarWorkspaceRowMenuTrackingReconcilerView.swift; sourceTree = ""; }; C9A57506C9A57506C9A57506 /* SidebarWorkspaceScrollLayoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarWorkspaceScrollLayoutTests.swift; sourceTree = ""; }; @@ -3777,6 +3785,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 7A11AA027A11AA027A11AA02 /* Workspace+SidebarAgentStatus.swift */, 7A11AA047A11AA047A11AA04 /* SidebarMetadataRowViews.swift */, 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */, + 5E409BA6FC74C8E2681694F1 /* SidebarAgentGraphiteRowViews.swift */, 4722F35D10C94D12ADC4D017 /* SidebarAgentRowsVariantLab.swift */, 1D2990638B9E75D4B02AF14F /* SidebarAgentStatusRowsSummary.swift */, A91C0D0E0000000000000001 /* TerminalTabAgentIcon.swift */, @@ -4723,6 +4732,9 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 46792DAA478444ED87B17B31 /* AutoNamingHookPayloadAdapterTests.swift */, CE7000000000000000000002 /* ClaudeWrapperResumeEnvironmentTests.swift */, F016B5C09357B3226FA2E014 /* SidebarWorkspaceSnapshotRefreshPolicyTests.swift */, + B96BD18955B1A751A8493637 /* SidebarWorkspaceRowInteractionStateTests.swift */, + 221E4C0E77F96E7A38811AEE /* SidebarSelectedWorkspaceScrollPolicyTests.swift */, + C414665C5461092EFE64FE11 /* PerAgentSidebarStatusRowClearingTests.swift */, A6AC73040000000000000002 /* SidebarWorkspaceSnapshotAgentActivityTests.swift */, C9A57514C9A57514C9A57514 /* SidebarScrollViewConfiguratorTests.swift */, C9A57506C9A57506C9A57506 /* SidebarWorkspaceScrollLayoutTests.swift */, @@ -6052,6 +6064,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 5C3E0454B6C24B02A2F091A8 /* ShortcutRoutingSupport.swift in Sources */, A6AC71020000000000000001 /* SidebarAgentActivityIndicator.swift in Sources */, A6AC71040000000000000001 /* SidebarAgentActivitySummary.swift in Sources */, + 492FBAC7FCA33879352B4204 /* SidebarAgentGraphiteRowViews.swift in Sources */, 14FE4CD3BCAD423796E56EE5 /* SidebarAgentRowsVariantLab.swift in Sources */, 2FB188449942360CAB895143 /* SidebarAgentStatusRowsSummary.swift in Sources */, 7A11AA057A11AA057A11AA05 /* SidebarAgentStatusRowViews.swift in Sources */, @@ -6751,6 +6764,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 6313FACE0000000000000000 /* PaneMemoryGuardrailTests.swift in Sources */, 5B21C4E15B21C4E15B21C4E1 /* PerAgentSidebarStatusDisplacementTests.swift in Sources */, 2255A23ACD5B366E35B6ED0F /* PerAgentSidebarStatusPersistenceTests.swift in Sources */, + 263D65B017D9E9AC6F525C27 /* PerAgentSidebarStatusRowClearingTests.swift in Sources */, DEC515B488104031B49F68F0 /* PerAgentSidebarStatusRowTests.swift in Sources */, D1F0A00300000000000000C1 /* PhonePushPresenceGateTests.swift in Sources */, B3575000000000000000000A /* PiVaultAgentPersistenceTests.swift in Sources */, @@ -6828,6 +6842,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = CB23911D7E131E8FBC9B82B6 /* SidebarOrderingTests.swift in Sources */, C0DE48000000000000000001 /* SidebarProviderMenuRegressionTests.swift in Sources */, C9A57513C9A57513C9A57513 /* SidebarScrollViewConfiguratorTests.swift in Sources */, + 51CA9864B90D2721F384B327 /* SidebarSelectedWorkspaceScrollPolicyTests.swift in Sources */, D73440010000000000000001 /* SidebarTabDragPayloadProviderTests.swift in Sources */, D7AB34300000000000000105 /* SidebarTabDropIndicatorPredicateTests.swift in Sources */, CA39C0304FE351A21C372429 /* SidebarWidthPolicyTests.swift in Sources */, @@ -6835,6 +6850,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C135190000000000000000B1 /* SidebarWorkspaceGroupConfigOpenerTests.swift in Sources */, C9A57303C9A57303C9A57303 /* SidebarWorkspaceGroupHeaderMetricsTests.swift in Sources */, C9A57305C9A57305C9A57305 /* SidebarWorkspaceReorderDropOverlayHitTestingTests.swift in Sources */, + 2E58C01936DF355241CC6911 /* SidebarWorkspaceRowInteractionStateTests.swift in Sources */, C9A57505C9A57505C9A57505 /* SidebarWorkspaceScrollLayoutTests.swift in Sources */, C0DE56010000000000000001 /* SidebarWorkspaceSelectionAnchorPolicyTests.swift in Sources */, A6AC73040000000000000001 /* SidebarWorkspaceSnapshotAgentActivityTests.swift in Sources */, diff --git a/cmuxTests/PerAgentSidebarStatusRowClearingTests.swift b/cmuxTests/PerAgentSidebarStatusRowClearingTests.swift new file mode 100644 index 000000000000..09108d79b23c --- /dev/null +++ b/cmuxTests/PerAgentSidebarStatusRowClearingTests.swift @@ -0,0 +1,184 @@ +import CmuxSidebar +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +/// Continuation of `PerAgentSidebarStatusRowTests`, split to satisfy the +/// new-file length budget: bare-key exit-hook clears, dead-agent replacement, +/// and the rows summary accent. +@MainActor +struct PerAgentSidebarStatusRowClearingTests { + private func makeEntry( + key: String, + value: String, + timestamp: Date = Date() + ) -> SidebarStatusEntry { + SidebarStatusEntry( + key: key, + value: value, + icon: "bolt.fill", + color: "#4C8DFF", + timestamp: timestamp + ) + } + + @Test + func testBareKeyExitHookFromNonOwnerPaneClearsOnlyThatPanesRow() throws { + let workspace = Workspace() + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + // Real bare-key hook sequence: both panes report the shared + // `claude_code` key, ownership migrates to the last reporter. + workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: firstPanelId) + workspace.setAgentLifecycle(key: "claude_code", panelId: firstPanelId, lifecycle: .running) + + workspace.recordAgentPID(key: "claude_code", pid: 222, panelId: secondPanelId, refreshPorts: false) + workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Waiting"), panelId: secondPanelId) + workspace.setAgentLifecycle(key: "claude_code", panelId: secondPanelId, lifecycle: .needsInput) + + // Pane A exits: its hook sends `clear_agent_pid claude_code --panel=A + // --clear-status` although pane B now owns the key. The clear must + // drop A's own row state without touching B's runtime. + #expect(workspace.clearAgentPID(key: "claude_code", panelId: firstPanelId, clearStatus: true, refreshPorts: false)) + + let rows = workspace.sidebarAgentStatusRows() + #expect(rows.map(\.panelId) == [secondPanelId]) + #expect(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"] == nil) + #expect(workspace.agentLifecycleStatesByPanelId[firstPanelId]?["claude_code"] == nil) + #expect(workspace.agentPIDs["claude_code"] == 222) + #expect(workspace.agentPIDPanelIdsByKey["claude_code"] == secondPanelId) + #expect(workspace.statusEntriesByPanelId[secondPanelId]?["claude_code"]?.value == "Waiting") + } + + @Test + func testClosingPanelWithoutPIDClearsSoleOwnerWorkspaceStatus() throws { + let workspace = Workspace() + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + // `set_status --panel` without `--pid`: the workspace slot and the + // panel copy are both written, but there is no PID ownership for the + // runtime cleanup to sweep. + let entry = makeEntry(key: "claude_code", value: "Running") + workspace.recordPanelStatusEntry(entry, panelId: secondPanelId) + workspace.statusEntries["claude_code"] = entry + + _ = workspace.discardClosedPanelLifecycleState( + panelId: secondPanelId, + paneId: nil, + panel: workspace.panels[secondPanelId], + origin: "test", + closePanel: false, + publishSurfaceClosedEvent: false, + clearSurfaceNotifications: false, + requestTransferredRemoteCleanup: false + ) + + // The closed pane was the key's only plausible owner, so the stale + // workspace-level slot must not survive to be adopted by a future + // same-type agent pane through the sole-owner fallback. + #expect(workspace.statusEntries["claude_code"] == nil) + } + + @Test + func testClosingPanelKeepsWorkspaceStatusWhenAnotherPaneOwnsKey() throws { + let workspace = Workspace() + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + let entry = makeEntry(key: "claude_code", value: "Running") + workspace.recordPanelStatusEntry(entry, panelId: firstPanelId) + workspace.recordPanelStatusEntry(entry, panelId: secondPanelId) + workspace.statusEntries["claude_code"] = entry + + _ = workspace.discardClosedPanelLifecycleState( + panelId: secondPanelId, + paneId: nil, + panel: workspace.panels[secondPanelId], + origin: "test", + closePanel: false, + publishSurfaceClosedEvent: false, + clearSurfaceNotifications: false, + requestTransferredRemoteCleanup: false + ) + + // The first pane still owns the key, so the workspace-level slot + // stays for its sole-owner fallback. + #expect(workspace.statusEntries["claude_code"]?.value == "Running") + #expect(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"]?.value == "Running") + } + + @Test + func testAmbiguousSharedKeyRowDoesNotInheritWorkspaceSortFreshness() throws { + let workspace = Workspace() + let firstPanelId = try #require(workspace.focusedPanelId) + let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) + let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id + + workspace.recordAgentPID(key: "claude_code.first", pid: 111, panelId: firstPanelId, refreshPorts: false) + workspace.recordAgentPID(key: "claude_code.second", pid: 222, panelId: secondPanelId, refreshPorts: false) + // Only the second pane has a panel-scoped entry; the workspace slot + // is newer and high-priority but ambiguous between the two panes. + workspace.recordPanelStatusEntry( + makeEntry(key: "claude_code", value: "Idle", timestamp: Date(timeIntervalSince1970: 100)), + panelId: secondPanelId + ) + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Running", + priority: 500, + timestamp: Date(timeIntervalSince1970: 9_999) + ) + + let rows = workspace.sidebarAgentStatusRows() + let rowsByPanel = Dictionary(uniqueKeysWithValues: rows.map { ($0.panelId, $0) }) + // The pane without its own entry must not borrow the ambiguous + // workspace entry's freshness for sorting. + #expect(rowsByPanel[firstPanelId]?.priority == 0) + #expect(rowsByPanel[firstPanelId]?.timestamp == .distantPast) + #expect(rows.first?.panelId == secondPanelId) + } + + @Test + func testAccordionSummaryCounts() { + func row(lifecycle: AgentHibernationLifecycleState?) -> SidebarAgentStatusRow { + SidebarAgentStatusRow( + panelId: UUID(), + statusKey: "claude_code", + value: nil, + icon: nil, + color: nil, + url: nil, + format: .plain, + lifecycle: lifecycle, + paneLabel: nil, + priority: 0, + timestamp: Date(timeIntervalSince1970: 0) + ) + } + + let summary = SidebarAgentStatusRowsSummary(rows: [ + row(lifecycle: .running), + row(lifecycle: .needsInput), + row(lifecycle: .idle), + ]) + #expect(summary.agentCount == 3) + #expect(summary.needsInputCount == 1) + #expect(summary.runningCount == 1) + #expect(summary.accentColorHex == "#FF9F0A") + + let runningOnly = SidebarAgentStatusRowsSummary(rows: [row(lifecycle: .running)]) + #expect(runningOnly.accentColorHex == "#4C8DFF") + #expect(SidebarAgentStatusRowsSummary(rows: [row(lifecycle: .idle)]).accentColorHex == nil) + } +} diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 28499361e19a..6b0e4b7b4912 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -364,159 +364,4 @@ struct PerAgentSidebarStatusRowTests { #expect(workspace.statusEntriesByPanelId[secondPanelId] == nil) #expect(workspace.sidebarAgentStatusRows().isEmpty) } - - @Test - func testBareKeyExitHookFromNonOwnerPaneClearsOnlyThatPanesRow() throws { - let workspace = Workspace() - let firstPanelId = try #require(workspace.focusedPanelId) - let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) - let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id - - // Real bare-key hook sequence: both panes report the shared - // `claude_code` key, ownership migrates to the last reporter. - workspace.recordAgentPID(key: "claude_code", pid: 111, panelId: firstPanelId, refreshPorts: false) - workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Running"), panelId: firstPanelId) - workspace.setAgentLifecycle(key: "claude_code", panelId: firstPanelId, lifecycle: .running) - - workspace.recordAgentPID(key: "claude_code", pid: 222, panelId: secondPanelId, refreshPorts: false) - workspace.recordPanelStatusEntry(makeEntry(key: "claude_code", value: "Waiting"), panelId: secondPanelId) - workspace.setAgentLifecycle(key: "claude_code", panelId: secondPanelId, lifecycle: .needsInput) - - // Pane A exits: its hook sends `clear_agent_pid claude_code --panel=A - // --clear-status` although pane B now owns the key. The clear must - // drop A's own row state without touching B's runtime. - #expect(workspace.clearAgentPID(key: "claude_code", panelId: firstPanelId, clearStatus: true, refreshPorts: false)) - - let rows = workspace.sidebarAgentStatusRows() - #expect(rows.map(\.panelId) == [secondPanelId]) - #expect(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"] == nil) - #expect(workspace.agentLifecycleStatesByPanelId[firstPanelId]?["claude_code"] == nil) - #expect(workspace.agentPIDs["claude_code"] == 222) - #expect(workspace.agentPIDPanelIdsByKey["claude_code"] == secondPanelId) - #expect(workspace.statusEntriesByPanelId[secondPanelId]?["claude_code"]?.value == "Waiting") - } - - @Test - func testClosingPanelWithoutPIDClearsSoleOwnerWorkspaceStatus() throws { - let workspace = Workspace() - let firstPanelId = try #require(workspace.focusedPanelId) - let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) - let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id - - // `set_status --panel` without `--pid`: the workspace slot and the - // panel copy are both written, but there is no PID ownership for the - // runtime cleanup to sweep. - let entry = makeEntry(key: "claude_code", value: "Running") - workspace.recordPanelStatusEntry(entry, panelId: secondPanelId) - workspace.statusEntries["claude_code"] = entry - - _ = workspace.discardClosedPanelLifecycleState( - panelId: secondPanelId, - paneId: nil, - panel: workspace.panels[secondPanelId], - origin: "test", - closePanel: false, - publishSurfaceClosedEvent: false, - clearSurfaceNotifications: false, - requestTransferredRemoteCleanup: false - ) - - // The closed pane was the key's only plausible owner, so the stale - // workspace-level slot must not survive to be adopted by a future - // same-type agent pane through the sole-owner fallback. - #expect(workspace.statusEntries["claude_code"] == nil) - } - - @Test - func testClosingPanelKeepsWorkspaceStatusWhenAnotherPaneOwnsKey() throws { - let workspace = Workspace() - let firstPanelId = try #require(workspace.focusedPanelId) - let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) - let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id - - let entry = makeEntry(key: "claude_code", value: "Running") - workspace.recordPanelStatusEntry(entry, panelId: firstPanelId) - workspace.recordPanelStatusEntry(entry, panelId: secondPanelId) - workspace.statusEntries["claude_code"] = entry - - _ = workspace.discardClosedPanelLifecycleState( - panelId: secondPanelId, - paneId: nil, - panel: workspace.panels[secondPanelId], - origin: "test", - closePanel: false, - publishSurfaceClosedEvent: false, - clearSurfaceNotifications: false, - requestTransferredRemoteCleanup: false - ) - - // The first pane still owns the key, so the workspace-level slot - // stays for its sole-owner fallback. - #expect(workspace.statusEntries["claude_code"]?.value == "Running") - #expect(workspace.statusEntriesByPanelId[firstPanelId]?["claude_code"]?.value == "Running") - } - - @Test - func testAmbiguousSharedKeyRowDoesNotInheritWorkspaceSortFreshness() throws { - let workspace = Workspace() - let firstPanelId = try #require(workspace.focusedPanelId) - let paneId = try #require(workspace.paneId(forPanelId: firstPanelId)) - let secondPanelId = try #require(workspace.newTerminalSurface(inPane: paneId, focus: false)).id - - workspace.recordAgentPID(key: "claude_code.first", pid: 111, panelId: firstPanelId, refreshPorts: false) - workspace.recordAgentPID(key: "claude_code.second", pid: 222, panelId: secondPanelId, refreshPorts: false) - // Only the second pane has a panel-scoped entry; the workspace slot - // is newer and high-priority but ambiguous between the two panes. - workspace.recordPanelStatusEntry( - makeEntry(key: "claude_code", value: "Idle", timestamp: Date(timeIntervalSince1970: 100)), - panelId: secondPanelId - ) - workspace.statusEntries["claude_code"] = SidebarStatusEntry( - key: "claude_code", - value: "Running", - priority: 500, - timestamp: Date(timeIntervalSince1970: 9_999) - ) - - let rows = workspace.sidebarAgentStatusRows() - let rowsByPanel = Dictionary(uniqueKeysWithValues: rows.map { ($0.panelId, $0) }) - // The pane without its own entry must not borrow the ambiguous - // workspace entry's freshness for sorting. - #expect(rowsByPanel[firstPanelId]?.priority == 0) - #expect(rowsByPanel[firstPanelId]?.timestamp == .distantPast) - #expect(rows.first?.panelId == secondPanelId) - } - - @Test - func testAccordionSummaryCounts() { - func row(lifecycle: AgentHibernationLifecycleState?) -> SidebarAgentStatusRow { - SidebarAgentStatusRow( - panelId: UUID(), - statusKey: "claude_code", - value: nil, - icon: nil, - color: nil, - url: nil, - format: .plain, - lifecycle: lifecycle, - paneLabel: nil, - priority: 0, - timestamp: Date(timeIntervalSince1970: 0) - ) - } - - let summary = SidebarAgentStatusRowsSummary(rows: [ - row(lifecycle: .running), - row(lifecycle: .needsInput), - row(lifecycle: .idle), - ]) - #expect(summary.agentCount == 3) - #expect(summary.needsInputCount == 1) - #expect(summary.runningCount == 1) - #expect(summary.accentColorHex == "#FF9F0A") - - let runningOnly = SidebarAgentStatusRowsSummary(rows: [row(lifecycle: .running)]) - #expect(runningOnly.accentColorHex == "#4C8DFF") - #expect(SidebarAgentStatusRowsSummary(rows: [row(lifecycle: .idle)]).accentColorHex == nil) - } } diff --git a/cmuxTests/SidebarSelectedWorkspaceScrollPolicyTests.swift b/cmuxTests/SidebarSelectedWorkspaceScrollPolicyTests.swift new file mode 100644 index 000000000000..9de3601befd4 --- /dev/null +++ b/cmuxTests/SidebarSelectedWorkspaceScrollPolicyTests.swift @@ -0,0 +1,100 @@ +import CmuxWorkspaces +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +/// Sidebar selected-workspace scroll policy tests, split from the snapshot +/// refresh policy test file to satisfy the file-length budget. +@Suite struct SidebarSelectedWorkspaceScrollPolicyTests { + @Test func skipsScrollWhenSelectedWorkspaceIdIsNil() { + #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( + selectedWorkspaceId: nil as String?, + oldWorkspaceIds: ["a"], + newWorkspaceIds: ["a"] + )) + } + + @Test func requestsScrollWhenSelectedWorkspaceFirstAppears() { + #expect(SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( + selectedWorkspaceId: "b", + oldWorkspaceIds: ["a"], + newWorkspaceIds: ["a", "b"] + )) + } + + @Test func requestsScrollWhenSelectedWorkspaceMovesToTop() { + #expect(SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( + selectedWorkspaceId: "c", + oldWorkspaceIds: ["a", "b", "c"], + newWorkspaceIds: ["c", "a", "b"] + )) + } + + @Test func requestsScrollWhenAnotherReorderShiftsSelectedWorkspaceIndex() { + #expect(SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( + selectedWorkspaceId: "b", + oldWorkspaceIds: ["a", "b", "c"], + newWorkspaceIds: ["c", "a", "b"] + )) + } + + @Test func skipsScrollWhenWorkspaceBeforeSelectedWorkspaceCloses() { + #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace(selectedWorkspaceId: "d", oldWorkspaceIds: ["a", "b", "c", "d"], newWorkspaceIds: ["a", "c", "d"])) + } + @Test func skipsScrollWhenReorderLeavesSelectedWorkspaceIndexUnchanged() { + #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( + selectedWorkspaceId: "a", + oldWorkspaceIds: ["a", "b", "c"], + newWorkspaceIds: ["a", "c", "b"] + )) + } + + @Test func skipsScrollWhenSelectedWorkspaceIsMissing() { + #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( + selectedWorkspaceId: "b", + oldWorkspaceIds: ["a", "b"], + newWorkspaceIds: ["a", "c"] + )) + } + + @Test func scrollTargetIsSelfWithoutGroup() { + let workspaceId = UUID() + #expect(SidebarSelectedWorkspaceScrollPolicy.scrollTargetWorkspaceId( + selectedWorkspaceId: workspaceId, + group: nil + ) == workspaceId) + } + + @Test func scrollTargetIsSelfInExpandedGroup() { + let workspaceId = UUID() + #expect(SidebarSelectedWorkspaceScrollPolicy.scrollTargetWorkspaceId( + selectedWorkspaceId: workspaceId, + group: makeGroup(isCollapsed: false, anchorWorkspaceId: UUID()) + ) == workspaceId) + } + + @Test func scrollTargetIsGroupAnchorWhenGroupIsCollapsed() { + let anchorId = UUID() + #expect(SidebarSelectedWorkspaceScrollPolicy.scrollTargetWorkspaceId( + selectedWorkspaceId: UUID(), + group: makeGroup(isCollapsed: true, anchorWorkspaceId: anchorId) + ) == anchorId) + } + + private func makeGroup(isCollapsed: Bool, anchorWorkspaceId: UUID) -> WorkspaceGroup { + WorkspaceGroup( + id: UUID(), + name: "group", + isCollapsed: isCollapsed, + isPinned: false, + anchorWorkspaceId: anchorWorkspaceId, + customColor: nil, + iconSymbol: nil + ) + } +} diff --git a/cmuxTests/SidebarWorkspaceRowInteractionStateTests.swift b/cmuxTests/SidebarWorkspaceRowInteractionStateTests.swift new file mode 100644 index 000000000000..708a76b916b8 --- /dev/null +++ b/cmuxTests/SidebarWorkspaceRowInteractionStateTests.swift @@ -0,0 +1,232 @@ +import AppKit +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +/// Sidebar row interaction tests, split from the snapshot refresh policy test +/// file to satisfy the file-length budget. +@Suite struct SidebarWorkspaceRowInteractionStateTests { + @Test func appKitMenuTrackingEndClearsStaleContextMenuVisibility() { + var state = SidebarWorkspaceRowInteractionState() + + state.contextMenuDidAppear() + #expect(state.contextMenuVisible) + + let didEndTracking = state.contextMenuTrackingDidEnd(pointerInsideRow: true) + #expect(didEndTracking) + state.setPointerHovering(true) + + #expect( + state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "AppKit menu tracking ending must clear stale SwiftUI context-menu visibility so later hover can reveal row affordances." + ) + } + + @Test func appKitMenuTrackingEndUsesReconciledPointerExit() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + state.contextMenuDidAppear() + + let didEndTracking = state.contextMenuTrackingDidEnd(pointerInsideRow: false) + #expect(didEndTracking) + + #expect( + !state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "If the pointer leaves through the context menu, AppKit menu tracking reconciliation must keep the row affordance hidden." + ) + } + + @Test @MainActor func menuTrackingReconcilerIgnoresSubmenuEndNotifications() { + let rootMenu = NSMenu() + let submenu = NSMenu() + let item = NSMenuItem(title: "submenu", action: nil, keyEquivalent: "") + rootMenu.addItem(item) + rootMenu.setSubmenu(submenu, for: item) + + #expect(SidebarWorkspaceRowMenuTrackingReconcilerView.shouldReconcileMenuEnd(object: rootMenu)) + #expect(!SidebarWorkspaceRowMenuTrackingReconcilerView.shouldReconcileMenuEnd(object: submenu)) + #expect(!SidebarWorkspaceRowMenuTrackingReconcilerView.shouldReconcileMenuEnd(object: nil)) + } + + @Test func hoverDuringContextMenuStaysHiddenUntilDismissal() { + var state = SidebarWorkspaceRowInteractionState() + + state.contextMenuDidAppear() + state.setPointerHovering(true) + + #expect( + !state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "Pointer hover updates observed during the context-menu lifecycle must not reveal the close affordance under the menu." + ) + + state.contextMenuDidDisappear() + + #expect( + state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "Once the context menu dismisses, the last observed pointer position may reveal the close affordance." + ) + } + + @Test func contextMenuDismissalRestoresHoverWithoutPointerMovement() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + state.contextMenuDidAppear() + state.contextMenuDidDisappear() + + #expect( + state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "Closing a context menu without moving the pointer must restore the row hover affordance." + ) + } + + @Test func pointerExitWhileContextMenuIsVisibleStaysHiddenAfterDismissal() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + state.contextMenuDidAppear() + state.contextMenuTrackingObserverDidInstall() + state.setPointerHovering(false) + state.contextMenuDidDisappear() + + #expect( + !state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "Pointer exit remains authoritative even when it is observed during the context-menu lifecycle." + ) + } + + @Test func swiftUIOnlyFastContextMenuDismissalKeepsInitialHoverFallback() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + state.contextMenuDidAppear() + state.setPointerHovering(false) + state.contextMenuDidDisappear() + + #expect( + state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "A SwiftUI hover-exit caused by the menu taking focus must not erase the initial hover fallback before the AppKit reconciler mounts." + ) + } + + @Test func noHoverDoesNotRevealCloseButtonWhileContextMenuIsVisible() { + var state = SidebarWorkspaceRowInteractionState() + + state.contextMenuDidAppear() + state.setPointerHovering(false) + + #expect( + !state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "A visible context menu must not make the close affordance visible when the pointer is not hovering." + ) + } + + @Test @MainActor func hoverReconcilerRestoresCloseButtonAfterLifecycleHoverReset() { + var state = SidebarWorkspaceRowInteractionState() + + let view = SidebarWorkspaceRowHoverReconcilerView() + view.frame = NSRect(x: 0, y: 0, width: 120, height: 28) + view.onPointerHoverChanged = { state.setPointerHovering($0) } + + view.reconcilePointerLocation(pointInView: NSPoint(x: 60, y: 14)) + #expect(state.shouldShowCloseButton(canCloseWorkspace: true, shortcutHintModeActive: false)) + + state.setPointerHovering(false) + #expect(!state.shouldShowCloseButton(canCloseWorkspace: true, shortcutHintModeActive: false)) + + view.reconcilePointerLocation(pointInView: NSPoint(x: 60, y: 14)) + + #expect( + state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "When sidebar updates or row reuse clear SwiftUI hover state while the pointer is still inside the row, the AppKit hover reconciler must restore the close affordance without waiting for another mouse move." + ) + } + + @Test func contextMenuAppearanceHidesExistingCloseButtonUntilPointerIsReconciled() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + #expect(state.shouldShowCloseButton(canCloseWorkspace: true, shortcutHintModeActive: false)) + + state.contextMenuDidAppear() + + #expect( + !state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "Opening a context menu must clear the row close affordance until tracking reports the pointer is still inside." + ) + } + + @Test func contextMenuDismissalCanRevealAfterPointerReconciliation() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + state.contextMenuDidAppear() + state.contextMenuDidDisappear() + state.setPointerHovering(true) + + #expect( + state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: false + ), + "Closing the context menu may reveal the close affordance again only after pointer tracking reconciles inside the row." + ) + } + + @Test func closeButtonHiddenWhenWorkspaceCannotBeClosed() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + + #expect(!state.shouldShowCloseButton( + canCloseWorkspace: false, + shortcutHintModeActive: false + )) + } + + @Test func closeButtonHiddenDuringShortcutHintMode() { + var state = SidebarWorkspaceRowInteractionState() + + state.setPointerHovering(true) + + #expect(!state.shouldShowCloseButton( + canCloseWorkspace: true, + shortcutHintModeActive: true + )) + } +} diff --git a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift index a6e0726d5c69..4175f987fad1 100644 --- a/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift +++ b/cmuxTests/SidebarWorkspaceSnapshotRefreshPolicyTests.swift @@ -210,314 +210,3 @@ import Testing ) } } - -@Suite struct SidebarSelectedWorkspaceScrollPolicyTests { - @Test func skipsScrollWhenSelectedWorkspaceIdIsNil() { - #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( - selectedWorkspaceId: nil as String?, - oldWorkspaceIds: ["a"], - newWorkspaceIds: ["a"] - )) - } - - @Test func requestsScrollWhenSelectedWorkspaceFirstAppears() { - #expect(SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( - selectedWorkspaceId: "b", - oldWorkspaceIds: ["a"], - newWorkspaceIds: ["a", "b"] - )) - } - - @Test func requestsScrollWhenSelectedWorkspaceMovesToTop() { - #expect(SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( - selectedWorkspaceId: "c", - oldWorkspaceIds: ["a", "b", "c"], - newWorkspaceIds: ["c", "a", "b"] - )) - } - - @Test func requestsScrollWhenAnotherReorderShiftsSelectedWorkspaceIndex() { - #expect(SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( - selectedWorkspaceId: "b", - oldWorkspaceIds: ["a", "b", "c"], - newWorkspaceIds: ["c", "a", "b"] - )) - } - - @Test func skipsScrollWhenWorkspaceBeforeSelectedWorkspaceCloses() { - #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace(selectedWorkspaceId: "d", oldWorkspaceIds: ["a", "b", "c", "d"], newWorkspaceIds: ["a", "c", "d"])) - } - @Test func skipsScrollWhenReorderLeavesSelectedWorkspaceIndexUnchanged() { - #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( - selectedWorkspaceId: "a", - oldWorkspaceIds: ["a", "b", "c"], - newWorkspaceIds: ["a", "c", "b"] - )) - } - - @Test func skipsScrollWhenSelectedWorkspaceIsMissing() { - #expect(!SidebarSelectedWorkspaceScrollPolicy.shouldScrollSelectedWorkspace( - selectedWorkspaceId: "b", - oldWorkspaceIds: ["a", "b"], - newWorkspaceIds: ["a", "c"] - )) - } - - @Test func scrollTargetIsSelfWithoutGroup() { - let workspaceId = UUID() - #expect(SidebarSelectedWorkspaceScrollPolicy.scrollTargetWorkspaceId( - selectedWorkspaceId: workspaceId, - group: nil - ) == workspaceId) - } - - @Test func scrollTargetIsSelfInExpandedGroup() { - let workspaceId = UUID() - #expect(SidebarSelectedWorkspaceScrollPolicy.scrollTargetWorkspaceId( - selectedWorkspaceId: workspaceId, - group: makeGroup(isCollapsed: false, anchorWorkspaceId: UUID()) - ) == workspaceId) - } - - @Test func scrollTargetIsGroupAnchorWhenGroupIsCollapsed() { - let anchorId = UUID() - #expect(SidebarSelectedWorkspaceScrollPolicy.scrollTargetWorkspaceId( - selectedWorkspaceId: UUID(), - group: makeGroup(isCollapsed: true, anchorWorkspaceId: anchorId) - ) == anchorId) - } - - private func makeGroup(isCollapsed: Bool, anchorWorkspaceId: UUID) -> WorkspaceGroup { - WorkspaceGroup( - id: UUID(), - name: "group", - isCollapsed: isCollapsed, - isPinned: false, - anchorWorkspaceId: anchorWorkspaceId, - customColor: nil, - iconSymbol: nil - ) - } -} - -@Suite struct SidebarWorkspaceRowInteractionStateTests { - @Test func appKitMenuTrackingEndClearsStaleContextMenuVisibility() { - var state = SidebarWorkspaceRowInteractionState() - - state.contextMenuDidAppear() - #expect(state.contextMenuVisible) - - let didEndTracking = state.contextMenuTrackingDidEnd(pointerInsideRow: true) - #expect(didEndTracking) - state.setPointerHovering(true) - - #expect( - state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "AppKit menu tracking ending must clear stale SwiftUI context-menu visibility so later hover can reveal row affordances." - ) - } - - @Test func appKitMenuTrackingEndUsesReconciledPointerExit() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - state.contextMenuDidAppear() - - let didEndTracking = state.contextMenuTrackingDidEnd(pointerInsideRow: false) - #expect(didEndTracking) - - #expect( - !state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "If the pointer leaves through the context menu, AppKit menu tracking reconciliation must keep the row affordance hidden." - ) - } - - @Test @MainActor func menuTrackingReconcilerIgnoresSubmenuEndNotifications() { - let rootMenu = NSMenu() - let submenu = NSMenu() - let item = NSMenuItem(title: "submenu", action: nil, keyEquivalent: "") - rootMenu.addItem(item) - rootMenu.setSubmenu(submenu, for: item) - - #expect(SidebarWorkspaceRowMenuTrackingReconcilerView.shouldReconcileMenuEnd(object: rootMenu)) - #expect(!SidebarWorkspaceRowMenuTrackingReconcilerView.shouldReconcileMenuEnd(object: submenu)) - #expect(!SidebarWorkspaceRowMenuTrackingReconcilerView.shouldReconcileMenuEnd(object: nil)) - } - - @Test func hoverDuringContextMenuStaysHiddenUntilDismissal() { - var state = SidebarWorkspaceRowInteractionState() - - state.contextMenuDidAppear() - state.setPointerHovering(true) - - #expect( - !state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "Pointer hover updates observed during the context-menu lifecycle must not reveal the close affordance under the menu." - ) - - state.contextMenuDidDisappear() - - #expect( - state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "Once the context menu dismisses, the last observed pointer position may reveal the close affordance." - ) - } - - @Test func contextMenuDismissalRestoresHoverWithoutPointerMovement() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - state.contextMenuDidAppear() - state.contextMenuDidDisappear() - - #expect( - state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "Closing a context menu without moving the pointer must restore the row hover affordance." - ) - } - - @Test func pointerExitWhileContextMenuIsVisibleStaysHiddenAfterDismissal() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - state.contextMenuDidAppear() - state.contextMenuTrackingObserverDidInstall() - state.setPointerHovering(false) - state.contextMenuDidDisappear() - - #expect( - !state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "Pointer exit remains authoritative even when it is observed during the context-menu lifecycle." - ) - } - - @Test func swiftUIOnlyFastContextMenuDismissalKeepsInitialHoverFallback() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - state.contextMenuDidAppear() - state.setPointerHovering(false) - state.contextMenuDidDisappear() - - #expect( - state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "A SwiftUI hover-exit caused by the menu taking focus must not erase the initial hover fallback before the AppKit reconciler mounts." - ) - } - - @Test func noHoverDoesNotRevealCloseButtonWhileContextMenuIsVisible() { - var state = SidebarWorkspaceRowInteractionState() - - state.contextMenuDidAppear() - state.setPointerHovering(false) - - #expect( - !state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "A visible context menu must not make the close affordance visible when the pointer is not hovering." - ) - } - - @Test @MainActor func hoverReconcilerRestoresCloseButtonAfterLifecycleHoverReset() { - var state = SidebarWorkspaceRowInteractionState() - - let view = SidebarWorkspaceRowHoverReconcilerView() - view.frame = NSRect(x: 0, y: 0, width: 120, height: 28) - view.onPointerHoverChanged = { state.setPointerHovering($0) } - - view.reconcilePointerLocation(pointInView: NSPoint(x: 60, y: 14)) - #expect(state.shouldShowCloseButton(canCloseWorkspace: true, shortcutHintModeActive: false)) - - state.setPointerHovering(false) - #expect(!state.shouldShowCloseButton(canCloseWorkspace: true, shortcutHintModeActive: false)) - - view.reconcilePointerLocation(pointInView: NSPoint(x: 60, y: 14)) - - #expect( - state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "When sidebar updates or row reuse clear SwiftUI hover state while the pointer is still inside the row, the AppKit hover reconciler must restore the close affordance without waiting for another mouse move." - ) - } - - @Test func contextMenuAppearanceHidesExistingCloseButtonUntilPointerIsReconciled() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - #expect(state.shouldShowCloseButton(canCloseWorkspace: true, shortcutHintModeActive: false)) - - state.contextMenuDidAppear() - - #expect( - !state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "Opening a context menu must clear the row close affordance until tracking reports the pointer is still inside." - ) - } - - @Test func contextMenuDismissalCanRevealAfterPointerReconciliation() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - state.contextMenuDidAppear() - state.contextMenuDidDisappear() - state.setPointerHovering(true) - - #expect( - state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: false - ), - "Closing the context menu may reveal the close affordance again only after pointer tracking reconciles inside the row." - ) - } - - @Test func closeButtonHiddenWhenWorkspaceCannotBeClosed() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - - #expect(!state.shouldShowCloseButton( - canCloseWorkspace: false, - shortcutHintModeActive: false - )) - } - - @Test func closeButtonHiddenDuringShortcutHintMode() { - var state = SidebarWorkspaceRowInteractionState() - - state.setPointerHovering(true) - - #expect(!state.shouldShowCloseButton( - canCloseWorkspace: true, - shortcutHintModeActive: true - )) - } -} From 0b57efb72814c2b654625fa833f46c91b69bd0f3 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 9 Jul 2026 20:12:42 -0700 Subject: [PATCH 41/46] Retrigger CI (no pull_request run was created for c25854497b) From 3d7fbd7b419dbecee6fe76701ea0025955c171b8 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 9 Jul 2026 21:34:25 -0700 Subject: [PATCH 42/46] Qualify Workspace.DetachedAgentRuntimeState in transfer test Main nested the struct inside Workspace (Workspace+DetachedSurfaceTransfer.swift); the bare reference broke the test-target build on every app-host shard. --- cmuxTests/PerAgentSidebarStatusRowTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmuxTests/PerAgentSidebarStatusRowTests.swift b/cmuxTests/PerAgentSidebarStatusRowTests.swift index 6b0e4b7b4912..65ce82de15f1 100644 --- a/cmuxTests/PerAgentSidebarStatusRowTests.swift +++ b/cmuxTests/PerAgentSidebarStatusRowTests.swift @@ -235,7 +235,7 @@ struct PerAgentSidebarStatusRowTests { // An adopted runtime whose keys were never validated must stay a // metadata pill in the destination, exactly as at the source. - let unvalidated = DetachedAgentRuntimeState( + let unvalidated = Workspace.DetachedAgentRuntimeState( panelId: panelId, statusEntries: [key: entry], agentPIDs: [key: 111], From 32fae4cd993d6ba2fe28bc21343519caa872123a Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 9 Jul 2026 21:52:58 -0700 Subject: [PATCH 43/46] Fix covariant Self in allFlags stored-property initializer Merge left the new flag entry referencing Self.sidebarAgentRowsDefault inside the allFlags closure initializer; spell the class name like the sibling entries. --- Sources/FeatureFlags.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/FeatureFlags.swift b/Sources/FeatureFlags.swift index 08fdb34fa937..cdcd7ce37eeb 100644 --- a/Sources/FeatureFlags.swift +++ b/Sources/FeatureFlags.swift @@ -153,7 +153,7 @@ final class CmuxFeatureFlags { localized: "featureFlags.sidebarAgentRows.description", defaultValue: "Shows one row per agent pane in the sidebar with live state, replacing the single status pill." ), - defaultWhenUnavailable: Self.sidebarAgentRowsDefault + defaultWhenUnavailable: CmuxFeatureFlags.sidebarAgentRowsDefault ), ] }() From 8b0f2f18af7aa5882592adbe2eaf3559ddf8b95e Mon Sep 17 00:00:00 2001 From: Austin Wang Date: Mon, 3 Aug 2026 18:35:42 -0700 Subject: [PATCH 44/46] Show surface names in agent rows (#9491) * test: cover agent row surface names * Show surface names in agent rows --- Sources/Workspace+SidebarAgentStatus.swift | 28 +++++-- cmux.xcodeproj/project.pbxproj | 4 + cmuxTests/SidebarAgentSurfaceNameTests.swift | 88 ++++++++++++++++++++ 3 files changed, 111 insertions(+), 9 deletions(-) create mode 100644 cmuxTests/SidebarAgentSurfaceNameTests.swift diff --git a/Sources/Workspace+SidebarAgentStatus.swift b/Sources/Workspace+SidebarAgentStatus.swift index 17ce9aba3b12..d009edbf3b7b 100644 --- a/Sources/Workspace+SidebarAgentStatus.swift +++ b/Sources/Workspace+SidebarAgentStatus.swift @@ -268,22 +268,32 @@ extension Workspace { } } - /// The row's identity label: an explicit rename wins, then the live - /// surface title (agents set it to their session name/topic), then the - /// directory label. This is what makes a row say the session's name - /// instead of a generic "Claude Code". + /// The row's identity label combines the live surface title with a + /// user-authored rename so sibling agents in the same tab stay distinct. + /// Auto-generated titles remain replacements rather than extra identity. func agentStatusRowPaneLabel(panelId: UUID) -> String? { - let candidates = [ - panelCustomTitles[panelId], + let baseCandidates = [ panelTitles[panelId], panelDirectoryDisplayLabels[panelId], ] - for candidate in candidates { + var baseLabel: String? + for candidate in baseCandidates { if let trimmed = candidate?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmed.isEmpty { - return trimmed + baseLabel = trimmed + break } } - return nil + + guard let customLabel = panelCustomTitles[panelId]?.trimmingCharacters(in: .whitespacesAndNewlines), + !customLabel.isEmpty else { + return baseLabel + } + guard (panelCustomTitleSources[panelId] ?? .user) == .user, + let baseLabel, + baseLabel != customLabel else { + return customLabel + } + return "\(baseLabel) · \(customLabel)" } private func isSidebarStatusEntryLessCurrent( diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 7d1de70f1dfb..2fab48c1e900 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1207,6 +1207,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources 14FE4CD3BCAD423796E56EE5 /* SidebarAgentRowsVariantLab.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4722F35D10C94D12ADC4D017 /* SidebarAgentRowsVariantLab.swift */; }; 2FB188449942360CAB895143 /* SidebarAgentStatusRowsSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D2990638B9E75D4B02AF14F /* SidebarAgentStatusRowsSummary.swift */; }; 7A11AA057A11AA057A11AA05 /* SidebarAgentStatusRowViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */; }; + 9322B0019322B0019322B001 /* SidebarAgentSurfaceNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9322B0029322B0029322B002 /* SidebarAgentSurfaceNameTests.swift */; }; 211A75777F433ED8BA5AE208 /* SidebarAppearanceSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 243632BA1DBBA36FD46E0610 /* SidebarAppearanceSupport.swift */; }; D7AB34310000000000000003 /* SidebarBonsplitTabDropDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34310000000000000004 /* SidebarBonsplitTabDropDelegate.swift */; }; D7AB34300000000000000003 /* SidebarBonsplitTabWorkspaceDropOverlay.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34300000000000000004 /* SidebarBonsplitTabWorkspaceDropOverlay.swift */; }; @@ -2859,6 +2860,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 4722F35D10C94D12ADC4D017 /* SidebarAgentRowsVariantLab.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentRowsVariantLab.swift; sourceTree = ""; }; 1D2990638B9E75D4B02AF14F /* SidebarAgentStatusRowsSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentStatusRowsSummary.swift; sourceTree = ""; }; 7A11AA067A11AA067A11AA06 /* SidebarAgentStatusRowViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentStatusRowViews.swift; sourceTree = ""; }; + 9322B0029322B0029322B002 /* SidebarAgentSurfaceNameTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarAgentSurfaceNameTests.swift; sourceTree = ""; }; 243632BA1DBBA36FD46E0610 /* SidebarAppearanceSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarAppearanceSupport.swift; sourceTree = ""; }; D7AB34310000000000000004 /* SidebarBonsplitTabDropDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarBonsplitTabDropDelegate.swift; sourceTree = ""; }; D7AB34300000000000000004 /* SidebarBonsplitTabWorkspaceDropOverlay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarBonsplitTabWorkspaceDropOverlay.swift; sourceTree = ""; }; @@ -4695,6 +4697,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 5B21C4E25B21C4E25B21C4E2 /* PerAgentSidebarStatusDisplacementTests.swift */, 3EDCC62AF23B380D1227E261 /* PerAgentSidebarStatusPersistenceTests.swift */, EF3A0288F87945DC8889FE91 /* PerAgentSidebarStatusRowTests.swift */, + 9322B0029322B0029322B002 /* SidebarAgentSurfaceNameTests.swift */, D36A00050000000000000002 /* RendererRealizationPlannerTests.swift */, C58410010000000000000002 /* RenderableSystemSymbolTests.swift */, DCDC0000000000000000B002 /* DockControlDefinitionDecodingTests.swift */, @@ -6981,6 +6984,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 6042A0016042A0016042A001 /* ShortcutHintModifierPolicyTests.swift in Sources */, F6001000A1B2C3D4E5F60718 /* ShortcutUnbindingTests.swift in Sources */, C3467AB10000000000000001 /* ShortcutWhenClauseTests.swift in Sources */, + 9322B0019322B0019322B001 /* SidebarAgentSurfaceNameTests.swift in Sources */, 51D800000000000000000001 /* SidebarIdentifierFormattingTests.swift in Sources */, AABBCC000000000000000206 /* SidebarInlineRenameKeyResolverTests.swift in Sources */, D41A7C01D41A7C01D41A7C01 /* SidebarLazyLayoutScaleTests.swift in Sources */, diff --git a/cmuxTests/SidebarAgentSurfaceNameTests.swift b/cmuxTests/SidebarAgentSurfaceNameTests.swift new file mode 100644 index 000000000000..ee690e4612f0 --- /dev/null +++ b/cmuxTests/SidebarAgentSurfaceNameTests.swift @@ -0,0 +1,88 @@ +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@MainActor +struct SidebarAgentSurfaceNameTests { + @Test + func userSetSurfaceNameIsAppendedWithoutChangingUnnamedRowText() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + workspace.recordAgentPID( + key: "claude_code.only", + pid: 111, + panelId: panelId, + refreshPorts: false + ) + workspace.panelTitles[panelId] = "workers" + + #expect(try #require(workspace.sidebarAgentStatusRows().first).paneLabel == "workers") + + #expect(workspace.setPanelCustomTitle(panelId: panelId, title: " fix-pr93 ")) + #expect( + try #require(workspace.sidebarAgentStatusRows().first).paneLabel + == "workers · fix-pr93" + ) + + #expect(workspace.setPanelCustomTitle(panelId: panelId, title: nil)) + #expect(try #require(workspace.sidebarAgentStatusRows().first).paneLabel == "workers") + } + + @Test + func autoGeneratedTitleRemainsTheBaseUntilUserClaimsIt() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + workspace.recordAgentPID( + key: "claude_code.only", + pid: 111, + panelId: panelId, + refreshPorts: false + ) + workspace.panelTitles[panelId] = "workers" + + #expect( + workspace.setPanelCustomTitle( + panelId: panelId, + title: "Generated topic", + source: .auto + ) + ) + #expect( + try #require(workspace.sidebarAgentStatusRows().first).paneLabel + == "Generated topic" + ) + + #expect( + workspace.setPanelCustomTitle( + panelId: panelId, + title: "Generated topic", + source: .user + ) + ) + #expect( + try #require(workspace.sidebarAgentStatusRows().first).paneLabel + == "workers · Generated topic" + ) + } + + @Test + func duplicateSurfaceNameIsNotRenderedTwice() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + workspace.recordAgentPID( + key: "claude_code.only", + pid: 111, + panelId: panelId, + refreshPorts: false + ) + workspace.panelTitles[panelId] = "fix-pr93" + + #expect(workspace.setPanelCustomTitle(panelId: panelId, title: "fix-pr93")) + #expect(try #require(workspace.sidebarAgentStatusRows().first).paneLabel == "fix-pr93") + } +} From 23df38fc0a6ca929c2effd963788dd42d58fb4b1 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 24 Aug 2026 20:53:10 -0700 Subject: [PATCH 45/46] test: cover sidebar refresh for title provenance claims Add a regression test proving that claiming an unchanged auto-generated surface name emits the sidebar observation update and renders the combined row label. --- .../WorkspaceSidebarObservationTests.swift | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/cmuxTests/WorkspaceSidebarObservationTests.swift b/cmuxTests/WorkspaceSidebarObservationTests.swift index e0eb1f70fd9b..2febced2d604 100644 --- a/cmuxTests/WorkspaceSidebarObservationTests.swift +++ b/cmuxTests/WorkspaceSidebarObservationTests.swift @@ -367,6 +367,41 @@ struct WorkspaceSidebarObservationTests { ) == 2 ) } + + @Test func sidebarObservationPublisherEmitsForSameTextCustomTitleProvenanceChange() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + workspace.panelTitles[panelId] = "workers" + #expect( + workspace.setPanelCustomTitle( + panelId: panelId, + title: "Generated topic", + source: .auto + ) + ) + + var publishCount = 0 + let cancellable = workspace.sidebarObservationPublisher.sink { + publishCount += 1 + } + defer { cancellable.cancel() } + publishCount = 0 + + #expect( + workspace.setPanelCustomTitle( + panelId: panelId, + title: "Generated topic", + source: .user + ) + ) + #expect( + publishCount == 1, + "A same-text auto-to-user title claim must invalidate the sidebar snapshot." + ) + #expect( + workspace.sidebarAgentStatusRows().first?.paneLabel == "workers · Generated topic" + ) + } } // Mutable flag captured by Observation's Sendable onChange closure in this test. From 403717e4f9eb45af67bccfe05f84c871dec7b175 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 24 Aug 2026 20:54:46 -0700 Subject: [PATCH 46/46] fix: publish sidebar title provenance changes Include custom-title provenance in the sidebar observation snapshot so a same-text auto-to-user claim refreshes the visible agent row immediately. --- Sources/Workspace.swift | 2 +- Sources/WorkspaceSidebarObservation.swift | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index f177ad217900..391704567b6f 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -2197,7 +2197,7 @@ final class Workspace: Identifiable, ObservableObject { /// Provenance of entries in `panelCustomTitles` (see ``CustomTitleSource``). /// An entry may be absent for a title carried across panel moves or /// restored from older snapshots; absent provenance is treated as `.user`. - var panelCustomTitleSources: [UUID: CustomTitleSource] = [:] + @Published var panelCustomTitleSources: [UUID: CustomTitleSource] = [:] @Published var pinnedPanelIds: Set = [] var pinMutationTokensByPanelId: [UUID: UUID] = [:] @Published var manualUnreadPanelIds: Set = [] { diff --git a/Sources/WorkspaceSidebarObservation.swift b/Sources/WorkspaceSidebarObservation.swift index 832f02eef6fb..a631ad95950b 100644 --- a/Sources/WorkspaceSidebarObservation.swift +++ b/Sources/WorkspaceSidebarObservation.swift @@ -43,10 +43,11 @@ private struct SidebarObservationState: Equatable { let panels: SidebarPanelObservationState let panelDirectories: [UUID: String] let panelDirectoryDisplayLabels: [UUID: String] - // Agent row labels resolve pane rename > surface title, so both must - // invalidate the sidebar snapshot or a rename never reaches the row. + // Agent row labels resolve pane rename > surface title, and provenance + // determines whether a same-text rename changes the rendered label. let panelTitles: [UUID: String] let panelCustomTitles: [UUID: String] + let panelCustomTitleSources: [UUID: Workspace.CustomTitleSource] let directoryChangeRevision: UInt64 let statusEntries: [String: SidebarStatusEntry] let metadataBlocks: [String: SidebarMetadataBlock] @@ -162,7 +163,10 @@ extension Workspace { remoteFields ) .combineLatest($listeningPorts, sidebarMetadata.panelDirectoryDisplayLabelsPublisher) - .combineLatest(directoryChangeRevision, Publishers.CombineLatest($panelTitles, $panelCustomTitles)) + .combineLatest( + directoryChangeRevision, + Publishers.CombineLatest3($panelTitles, $panelCustomTitles, $panelCustomTitleSources) + ) .compactMap { [weak self] values, directoryChangeRevision, panelTitleFields -> SidebarObservationState? in guard let self else { return nil } let (groupedFields, listeningPorts, panelDirectoryDisplayLabels) = values @@ -178,6 +182,7 @@ extension Workspace { panelDirectoryDisplayLabels: panelDirectoryDisplayLabels, panelTitles: panelTitleFields.0, panelCustomTitles: panelTitleFields.1, + panelCustomTitleSources: panelTitleFields.2, directoryChangeRevision: directoryChangeRevision, statusEntries: metadataFields.0, metadataBlocks: metadataFields.1,