Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
e9bef7a
Add failing test: sidebar status/metadata dictionaries must stay bounded
austinywang Jun 10, 2026
8a12328
Cap sidebar status/metadata dictionaries to bound view-graph inputs (…
austinywang Jun 10, 2026
71e9eae
Tear down coupled agent PID state when the status cap evicts a key (#…
austinywang Jun 10, 2026
0c8a7ee
Don't record a status-coupled PID when the status self-evicts on inse…
austinywang Jun 11, 2026
f81f895
Merge remote-tracking branch 'origin/main' into issue-5845-main-threa…
austinywang Jun 11, 2026
91e1505
Key sidebar cap eviction by storage key, not entry.key (#5845 review)
austinywang Jun 11, 2026
6a713b3
Retain live agent-backed statuses ahead of stale telemetry in the cap…
austinywang Jun 11, 2026
df18b8a
Merge remote-tracking branch 'origin/main' into issue-5845-main-threa…
austinywang Jun 11, 2026
8e2f1e5
Refresh Swift file-length budget after merge with main
austinywang Jun 11, 2026
d6e0e23
Also protect lifecycle-backed agent statuses from the status cap (#58…
austinywang Jun 11, 2026
9588405
Never evict cmux-owned reserved status keys from the cap (#5845 review)
austinywang Jun 11, 2026
40f34e4
Clear lifecycle state for status keys evicted by the cap (#5845 review)
austinywang Jun 11, 2026
1b675fa
Add a just-inserted grace tier so new agent statuses survive their ow…
austinywang Jun 11, 2026
efeac54
Merge remote-tracking branch 'origin/main' into issue-5845-main-threa…
austinywang Jun 11, 2026
2a5e2e0
Refresh Swift file-length budget after merge with main
austinywang Jun 11, 2026
76a896d
Guard detached-agent adoption against orphaning capped-out PIDs (#584…
austinywang Jun 11, 2026
ce0fa83
Make #5845 regression tests reference only pre-existing symbols (#584…
austinywang Jun 11, 2026
c77521c
Merge remote-tracking branch 'origin/main' into issue-5845-main-threa…
austinywang Jun 11, 2026
8f357b5
Refresh Swift file-length budget after merge with main
austinywang Jun 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .github/swift-file-length-budget.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
# Reduce counts as files shrink. CI fails if tracked files exceed this budget.
32733 CLI/cmux.swift
22098 Sources/TerminalController.swift
19955 Sources/Workspace.swift
19251 Sources/ContentView.swift
20009 Sources/Workspace.swift
19245 Sources/ContentView.swift
18044 Sources/AppDelegate.swift
16539 Sources/GhosttyTerminalView.swift
13589 Sources/Panels/BrowserPanel.swift
Expand Down Expand Up @@ -76,10 +76,10 @@
1144 Sources/VaultAgentProcessScanner.swift
1139 cmuxTests/PiVaultAgentPersistenceTests.swift
1107 Sources/AppDelegate+CmuxSSHURL.swift
1096 Sources/GhosttyConfig.swift
1084 cmuxTests/AgentHibernationTests.swift
1068 cmuxTests/FileExplorerStoreTests.swift
1058 cmuxUITests/BonsplitTabDragUITests.swift
1096 Sources/GhosttyConfig.swift
1021 cmuxUITests/TerminalCmdClickUITests.swift
1006 cmuxTests/CmuxSSHURLRequestTests.swift
1000 cmuxTests/CmuxTopSnapshotScopeTests.swift
Expand Down Expand Up @@ -167,8 +167,8 @@
539 CLI/CodexTeamsApprovalBridge.swift
538 CLI/CMUXCLI+Themes.swift
536 cmuxTests/CmuxConfigContextMenuTests.swift
530 cmuxUITests/AutomationSocketUITests.swift
528 cmuxTests/CLINotifyProcessTestSupport.swift
528 cmuxUITests/AutomationSocketUITests.swift
527 CLI/CLISocketPathResolver.swift
523 Packages/CmuxSettingsUI/Sources/CmuxSettingsUI/Scene/SettingsWindowScene.swift
522 Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttyRuntime.swift
Expand Down
58 changes: 56 additions & 2 deletions Sources/Workspace.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10776,8 +10776,12 @@ final class Workspace: Identifiable, ObservableObject {
@Published private(set) var tmuxWorkspaceFlashReason: WorkspaceAttentionFlashReason?
@Published private(set) var tmuxWorkspaceFlashToken: UInt64 = 0
var manualUnreadMarkedAt: [UUID: Date] = [:]
@Published var statusEntries: [String: SidebarStatusEntry] = [:]
@Published var metadataBlocks: [String: SidebarMetadataBlock] = [:]
@Published var statusEntries: [String: SidebarStatusEntry] = [:] {
didSet { trimSidebarStatusEntriesIfNeeded() }
}
@Published var metadataBlocks: [String: SidebarMetadataBlock] = [:] {
didSet { trimSidebarMetadataBlocksIfNeeded() }
}
@Published private(set) var latestConversationMessage: String?
@Published private(set) var latestSubmittedMessage: String?
@Published private(set) var latestSubmittedAt: Date?
Expand Down Expand Up @@ -14455,6 +14459,56 @@ final class Workspace: Identifiable, ObservableObject {
}
}

/// Upper bound on retained sidebar status pills / metadata blocks per
/// workspace. The sidebar `status`/`metadata` socket API lets agents and CI
/// scripts insert entries under arbitrary caller-chosen keys. Without a cap,
/// a long-running or verbose integration (e.g. ~30 live agent sessions over
/// hours, https://github.com/manaflow-ai/cmux/issues/5845) grows these
/// `@Published` dictionaries without bound, which both leaks memory and makes
/// the per-tick `removeDuplicates` equality check and the
/// `sidebarStatusEntriesInDisplayOrder()` / `sidebarMetadataBlocksInDisplayOrder()`
/// sorts that feed the sidebar view graph progressively more expensive on the
/// main thread. The bound is generous enough that no realistic integration
/// (the collapsed sidebar shows at most a handful of pills) is affected;
/// it only clamps pathological growth. Mirrors the `logEntries` cap above.
static let maxSidebarStatusEntries = 200
static let maxSidebarMetadataBlocks = 200

/// Evicts the lowest-priority, then oldest, status entries once the cap is
/// exceeded so retention matches `sidebarStatusEntriesInDisplayOrder()`:
/// high-priority and recent entries (the ones actually shown) survive.
private func trimSidebarStatusEntriesIfNeeded() {
guard statusEntries.count > Self.maxSidebarStatusEntries else { return }
let keptKeys = statusEntries.values
.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.key < rhs.key
}
.prefix(Self.maxSidebarStatusEntries)
.map(\.key)
let kept = Set(keptKeys)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Reassigning re-enters didSet, but the next pass sees count <= cap and
// returns immediately, so recursion terminates at depth two.
statusEntries = statusEntries.filter { kept.contains($0.key) }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Eviction ignores the visibility filter applied by the display path

sidebarStatusEntriesInDisplayOrder() first calls sidebarStatusEntriesVisibleForDisplay() — which hides "structured agent hook status" entries whose panel is no longer active — then sorts. trimSidebarStatusEntriesIfNeeded() skips that filter and sorts all entries, including invisible structured-agent entries. An invisible entry with a high-priority or recent timestamp will claim one of the 200 slots, potentially evicting a visible non-structured entry. The PR description says "entries that are actually shown always survive," but that guarantee only holds when every entry above the cap threshold is non-structured or already visible.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Practical impact is negligible, so I left the ranking as priority/timestamp. The structured-agent-hook keys are a fixed 16-key allowlist (AgentHibernationLifecycleStatusKeys.allowedStatusKeys) — they cannot grow, so they can occupy at most ~16 of the 200 slots. The flood that actually triggers the cap is always non-structured (always-visible) keys, and the display path re-applies sidebarStatusEntriesVisibleForDisplay() to the survivors before showing the collapsed top entries, so what the user sees is unaffected. I softened the 'always survive' wording in the PR description to reflect this bound.

— Claude Code

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Double objectWillChange / publisher notification on every overflow insert

When an insert pushes statusEntries above the cap, didSet reassigns the whole dictionary via statusEntries = statusEntries.filter {…}. Because statusEntries is @Published, this second assignment fires objectWillChange a second time in the same synchronous call. Any Combine subscriber that has already received the over-cap value (e.g. sidebarObservationPublisher → .removeDuplicates()) will receive a second, distinct emission for what is logically one write. On a workload with persistent overflow, this doubles the emission rate into the chains the PR is trying to quiet. The same issue exists in trimSidebarMetadataBlocksIfNeeded(). A cheaper fix is to mutate with removeValue(forKey:) per evicted key (one notification per eviction, coalesced), or to stage the removal outside didSet entirely.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping the single whole-dictionary reassignment. The second objectWillChange fires only on the overflow path (count > cap), i.e. exactly the pathological flood the cap exists to bound — never in normal operation where the dicts stay well under 200. The suggested per-key removeValue is not cheaper for the common case (a flood evicts one entry per insert → one extra notification either way) and is strictly worse for the bulk path (restore assigns the whole dict once → N notifications vs the reassign's 1), so I left the reassign as the lower-amplitude option. The doubled emission on the already-degenerate overflow path is bounded and far below the unbounded growth it replaces.

— Claude Code

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your analysis is correct on all three counts. The reassign and per-key paths produce the same notification count on the single-entry overflow path (1 insert notification + 1 trim notification either way), the reassign is strictly fewer notifications than per-key removal on the bulk-assign path, and the overflow path itself is the bounded pathological case the cap exists to contain.

I'll retract the concern — the current approach is the right choice here.

}

/// Mirror of `trimSidebarStatusEntriesIfNeeded()` for metadata blocks,
/// matching `sidebarMetadataBlocksInDisplayOrder()` retention.
private func trimSidebarMetadataBlocksIfNeeded() {
guard metadataBlocks.count > Self.maxSidebarMetadataBlocks else { return }
let keptKeys = metadataBlocks.values
.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.key < rhs.key
}
.prefix(Self.maxSidebarMetadataBlocks)
.map(\.key)
let kept = Set(keptKeys)
metadataBlocks = metadataBlocks.filter { kept.contains($0.key) }
}

// MARK: - Panel Operations

private func seedTerminalInheritanceFontPoints(
Expand Down
73 changes: 73 additions & 0 deletions cmuxTests/WorkspaceSidebarObservationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,77 @@ final class WorkspaceSidebarObservationTests: XCTestCase {
"Expected non-visible remote heartbeat updates to avoid invalidating sidebar rows"
)
}

// The sidebar `status`/`metadata` socket API lets agents and CI scripts
// insert entries under arbitrary caller-chosen keys. With ~30 long-running
// agent sessions over hours, an integration that uses ever-distinct keys
// grows these @Published dictionaries without bound, which both leaks memory
// (footprint climbed to 6–8 GB in https://github.com/manaflow-ai/cmux/issues/5845)
// and makes the per-tick `removeDuplicates` equality check and
// `sidebarStatusEntriesInDisplayOrder()` sort that feed the sidebar view
// graph progressively more expensive on the main thread. They must stay
// bounded like `logEntries` already is.
func testStatusEntriesStayBoundedUnderUnboundedDistinctKeys() {
let workspace = Workspace()
// Mirrors `Workspace.maxSidebarStatusEntries`; kept as a literal so this
// regression test compiles and fails on the assertion (not a missing
// symbol) in the pre-fix commit.
let cap = 200

for index in 0..<(cap * 3) {
workspace.statusEntries["key_\(index)"] = SidebarStatusEntry(
key: "key_\(index)",
value: "value_\(index)",
priority: 0,
timestamp: Date(timeIntervalSince1970: TimeInterval(index))
)
}

XCTAssertLessThanOrEqual(
workspace.statusEntries.count,
cap,
"statusEntries must stay bounded so unbounded agent telemetry cannot grow the sidebar view-graph inputs without limit"
)
// Eviction keeps the most recent entries (highest timestamp) and drops
// the oldest, so the newest key survives and the oldest is gone.
XCTAssertNotNil(
workspace.statusEntries["key_\(cap * 3 - 1)"],
"The most recent status entry must be retained after trimming"
)
XCTAssertNil(
workspace.statusEntries["key_0"],
"The oldest status entry must be evicted once the cap is exceeded"
)
}

func testMetadataBlocksStayBoundedUnderUnboundedDistinctKeys() {
let workspace = Workspace()
// Mirrors `Workspace.maxSidebarMetadataBlocks`; kept as a literal so this
// regression test compiles and fails on the assertion (not a missing
// symbol) in the pre-fix commit.
let cap = 200

for index in 0..<(cap * 3) {
workspace.metadataBlocks["key_\(index)"] = SidebarMetadataBlock(
key: "key_\(index)",
markdown: "block_\(index)",
priority: 0,
timestamp: Date(timeIntervalSince1970: TimeInterval(index))
)
}

XCTAssertLessThanOrEqual(
workspace.metadataBlocks.count,
cap,
"metadataBlocks must stay bounded so unbounded agent telemetry cannot grow the sidebar view-graph inputs without limit"
)
XCTAssertNotNil(
workspace.metadataBlocks["key_\(cap * 3 - 1)"],
"The most recent metadata block must be retained after trimming"
)
XCTAssertNil(
workspace.metadataBlocks["key_0"],
"The oldest metadata block must be evicted once the cap is exceeded"
)
}
}
Loading