Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
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
12 changes: 6 additions & 6 deletions .github/swift-file-length-budget.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
# Format: max_lines<TAB>relative path
# Reduce counts as files shrink. CI fails if tracked files exceed this budget.
34336 CLI/cmux.swift
17717 Sources/AppDelegate.swift
17720 Sources/AppDelegate.swift
16112 Sources/ContentView.swift
13950 Sources/TerminalController.swift
13958 Sources/TerminalController.swift
12758 Sources/Workspace.swift
12144 cmuxTests/AppDelegateShortcutRoutingTests.swift
11924 Sources/Panels/BrowserPanel.swift
Expand All @@ -20,7 +20,7 @@
6084 Sources/TextBoxInput.swift
5915 cmuxTests/TerminalAndGhosttyTests.swift
5573 cmuxTests/BrowserConfigTests.swift
5566 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift
5507 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift
4487 Sources/Panels/FilePreviewPanel.swift
4478 Sources/cmuxApp.swift
4401 cmuxTests/BrowserPanelTests.swift
Expand Down Expand Up @@ -123,9 +123,9 @@
754 Sources/TerminalController+ControlWorkspaceContext.swift
752 cmuxUITests/CloseWorkspaceCmdDUITests.swift
738 Packages/macOS/CMUXProjectModel/Sources/CMUXProjectModel/XcodeProjectAdapter.swift
736 Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift
726 cmuxTests/CLICodexHookTimeoutRegressionTests.swift
722 Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Store/ChatConversationStore.swift
718 Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift
716 Sources/TaskManagerSnapshot.swift
715 Sources/AppleScriptSupport.swift
710 Sources/TerminalSSHSessionDetector.swift
Expand Down Expand Up @@ -155,11 +155,11 @@
636 Sources/TerminalController+ControlPaneContext.swift
630 Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/ShortcutWhenClause.swift
629 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/KeyboardShortcutsSection.swift
629 Sources/PortScanner.swift
621 cmuxUITests/RightSidebarChromeHeightUITests.swift
620 cmuxTests/FinderFileDropRegressionTests.swift
620 cmuxTests/TerminalNotificationQueueTests.swift
615 cmuxTests/RemoteTmuxControlParserTests.swift
614 Sources/PortScanner.swift
612 cmuxUITests/FeedSidebarUITests.swift
608 Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Coordinators/WorkspaceGroupCoordinator.swift
606 Sources/SettingsNavigation.swift
Expand Down Expand Up @@ -205,12 +205,12 @@
526 Packages/macOS/CmuxSettings/Sources/CmuxSettings/SocketControl/SocketControlSettings.swift
524 CLI/CMUXCLI+AutoNaming.swift
523 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/AutomationSection.swift
521 Sources/PaneMemoryGuardrail.swift
520 CLI/CMUXCLI+AmpExtension.swift
520 cmuxTests/MainWindowVisibilityControllerTests.swift
519 Packages/macOS/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-two-column-cockpit-sidebar.swift
519 Sources/CmuxConfigExecutor.swift
518 Packages/macOS/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-git-review-queue-command-deck.swift
517 Sources/PaneMemoryGuardrail.swift
516 Sources/TerminalImageTransfer.swift
514 Packages/macOS/CmuxSwiftRender/Sources/CmuxSwiftRender/ExpressionEvaluator.swift
514 cmuxUITests/UpdatePillUITests.swift
Expand Down
3 changes: 3 additions & 0 deletions Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2070,6 +2070,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
/// leaking pane can OOM-suspend the whole app (issue #6313).
private func startPaneMemoryGuardrailIfNeeded(notificationStore: TerminalNotificationStore) {
let guardrail = PaneMemoryGuardrail.shared
guardrail.shouldPoll = {
NSApplication.shared.isActive
}
guardrail.paneProvider = { [weak self] in
self?.paneMemoryGuardrailDescriptors() ?? []
}
Expand Down
4 changes: 4 additions & 0 deletions Sources/PaneMemoryGuardrail.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ final class PaneMemoryGuardrail {
/// Supplies the live pane set each tick (main-actor; reads ghostty/tty).
@ObservationIgnored
var paneProvider: (@MainActor () -> [PaneMemoryDescriptor])?
/// Returns whether the periodic poll should run on this tick.
@ObservationIgnored
var shouldPoll: (@MainActor () -> Bool)?
/// Pushes the set of workspaces that should show a warning badge.
@ObservationIgnored
var onWarnedWorkspacesChanged: (@MainActor (Set<UUID>) -> Void)?
Expand Down Expand Up @@ -87,6 +90,7 @@ final class PaneMemoryGuardrail {
// MARK: Tick

private func tick() {
guard shouldPoll?() ?? true else { return }
guard isEnabled else {
clearAll()
return
Expand Down
23 changes: 19 additions & 4 deletions Sources/PortScanner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ final class PortScanner: @unchecked Sendable {
var onAgentPortsUpdated: (@MainActor (_ workspaceId: UUID, _ ports: [Int]) -> Void)?
/// Provider returns tracked agent root PIDs for the given workspaces.
var agentPIDsProvider: (@MainActor (_ workspaceIds: Set<UUID>) -> [UUID: Set<Int>])?
/// Filters workspaces eligible for periodic tracked-agent rescans.
var trackedAgentScanWorkspaceFilter: (@MainActor (_ workspaceIds: Set<UUID>) -> Set<UUID>)?

// MARK: - State (all guarded by `queue`)

Expand All @@ -36,6 +38,9 @@ final class PortScanner: @unchecked Sendable {
/// Workspaces with active agent PID tracking that need background rescans.
private var trackedAgentWorkspaces: Set<UUID> = []

/// Last delivered agent-owned listening ports per workspace.
private var lastAgentPortsByWorkspace: [UUID: [Int]] = [:]

Comment thread
austinywang marked this conversation as resolved.
Resolved
/// Panels that requested a scan since the last coalesce snapshot.
private var pendingKicks: Set<PanelKey> = []

Expand Down Expand Up @@ -299,15 +304,21 @@ final class PortScanner: @unchecked Sendable {
)
return
}
let workspaceFilter = trackedAgentScanWorkspaceFilter

Task { [weak self] in
guard let self else { return }
let agentPIDsByWorkspace = await MainActor.run {
agentPIDsProvider(workspaceIds)
let (eligibleWorkspaceIds, agentPIDsByWorkspace) = await MainActor.run {
let eligibleWorkspaceIds = workspaceFilter?(workspaceIds) ?? workspaceIds
guard !eligibleWorkspaceIds.isEmpty else {
return (Set<UUID>(), [UUID: Set<Int>]())
}
return (eligibleWorkspaceIds, agentPIDsProvider(eligibleWorkspaceIds))
}
guard !eligibleWorkspaceIds.isEmpty else { return }
self.queue.async { [weak self] in
self?.finishTrackedAgentScan(
workspaceIds: workspaceIds,
workspaceIds: eligibleWorkspaceIds,
agentPIDsByWorkspace: agentPIDsByWorkspace,
agentRevisions: agentRevisions
)
Expand Down Expand Up @@ -415,7 +426,7 @@ final class PortScanner: @unchecked Sendable {
}
}

private func validatedAgentResults(
func validatedAgentResults(
Comment thread
austinywang marked this conversation as resolved.
Resolved
workspaceIds: Set<UUID>,
agentPortsByWorkspace: [UUID: Set<Int>],
agentRevisions: [UUID: UInt64]
Expand All @@ -428,6 +439,10 @@ final class PortScanner: @unchecked Sendable {
let expectedRevision = agentRevisions[workspaceId, default: 0]
guard currentRevision == expectedRevision else { continue }
let ports = Array(agentPortsByWorkspace[workspaceId] ?? []).sorted()
let previousPorts = lastAgentPortsByWorkspace[workspaceId]
guard previousPorts != ports else { continue }
guard previousPorts != nil || !ports.isEmpty else { continue }
lastAgentPortsByWorkspace[workspaceId] = ports
results.append((workspaceId, ports))
}
continuation.resume(returning: results)
Expand Down
8 changes: 8 additions & 0 deletions Sources/TerminalController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -787,6 +787,14 @@ class TerminalController {
}
return pidsByWorkspace
}
PortScanner.shared.trackedAgentScanWorkspaceFilter = { [weak self] workspaceIds in
guard NSApplication.shared.isActive,
let selectedWorkspaceId = self?.tabManager?.selectedTabId,
workspaceIds.contains(selectedWorkspaceId) else {
return []
}
return [selectedWorkspaceId]
}
}

nonisolated func socketListenerHealth(expectedSocketPath: String) -> SocketListenerHealth {
Expand Down
22 changes: 22 additions & 0 deletions cmuxTests/PaneMemoryGuardrailTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,28 @@ struct PaneMemoryGuardrailTests {
#expect(workspaceIds.contains(secondWindowWorkspace.id))
}

@MainActor
@Test
func appDelegateGuardrailDescriptorsKeepBackgroundWorkspacesLive() throws {
let app = AppDelegate()
let manager = TabManager()
let windowId = app.registerMainWindowContextForTesting(tabManager: manager)
defer { app.unregisterMainWindowContextForTesting(windowId: windowId) }

let firstWorkspace = try #require(manager.selectedWorkspace)
let backgroundWorkspace = manager.addWorkspace(title: "Background", select: false)

let initialWorkspaceIds = Set(app.paneMemoryGuardrailDescriptors().map(\.workspaceId))
#expect(initialWorkspaceIds.contains(firstWorkspace.id))
#expect(initialWorkspaceIds.contains(backgroundWorkspace.id))

manager.selectWorkspace(backgroundWorkspace)

let selectedWorkspaceIds = Set(app.paneMemoryGuardrailDescriptors().map(\.workspaceId))
#expect(selectedWorkspaceIds.contains(firstWorkspace.id))
#expect(selectedWorkspaceIds.contains(backgroundWorkspace.id))
}

@MainActor
@Test
func appDelegateGuardrailCloseRoutesThroughOwningWindowManager() throws {
Expand Down
94 changes: 71 additions & 23 deletions cmuxTests/PortScannerTests.swift
Original file line number Diff line number Diff line change
@@ -1,68 +1,116 @@
import XCTest
import Foundation
import Testing

#if canImport(cmux_DEV)
@testable import cmux_DEV
#elseif canImport(cmux)
@testable import cmux
#endif

final class PortScannerProcessCaptureTests: XCTestCase {
@Suite
struct PortScannerProcessCaptureTests {
private func openFDCount() -> Int? {
try? FileManager.default.contentsOfDirectory(atPath: "/dev/fd").count
}

func testCaptureStandardOutputDoesNotLeakPipeFDs() throws {
guard let baseline = openFDCount() else {
throw XCTSkip("Unable to inspect /dev/fd on this runner")
}
@Test
func captureStandardOutputDoesNotLeakPipeFDs() throws {
let baseline = try #require(openFDCount(), "Unable to inspect /dev/fd on this runner")

var maxCount = baseline
for _ in 0..<200 {
let output = PortScanner.captureStandardOutput(
executablePath: "/usr/bin/printf",
arguments: ["cmux"]
)
XCTAssertEqual(output, "cmux")
#expect(output == "cmux")
if let current = openFDCount() {
maxCount = max(maxCount, current)
}
}

guard let finalCount = openFDCount() else {
throw XCTSkip("Unable to inspect final /dev/fd count on this runner")
}
let finalCount = try #require(openFDCount(), "Unable to inspect final /dev/fd count on this runner")

XCTAssertLessThanOrEqual(maxCount - baseline, 8)
XCTAssertLessThanOrEqual(finalCount - baseline, 8)
#expect(maxCount - baseline <= 8)
#expect(finalCount - baseline <= 8)
}

@Test
func unchangedAgentPortResultsAreSuppressed() async {
let scanner = PortScanner()
let workspaceId = UUID()
let revisions = [workspaceId: UInt64(0)]

let initialEmpty = await scanner.validatedAgentResults(
workspaceIds: [workspaceId],
agentPortsByWorkspace: [:],
agentRevisions: revisions
)
#expect(initialEmpty.isEmpty)

let firstPorts = await scanner.validatedAgentResults(
workspaceIds: [workspaceId],
agentPortsByWorkspace: [workspaceId: [3000, 8787]],
agentRevisions: revisions
)
#expect(firstPorts.count == 1)
#expect(firstPorts.first?.0 == workspaceId)
#expect(firstPorts.first?.1 == [3000, 8787])

let unchangedPorts = await scanner.validatedAgentResults(
workspaceIds: [workspaceId],
agentPortsByWorkspace: [workspaceId: [8787, 3000]],
agentRevisions: revisions
)
#expect(unchangedPorts.isEmpty)

let clearedPorts = await scanner.validatedAgentResults(
workspaceIds: [workspaceId],
agentPortsByWorkspace: [:],
agentRevisions: revisions
)
#expect(clearedPorts.count == 1)
#expect(clearedPorts.first?.0 == workspaceId)
#expect(clearedPorts.first?.1 == [])

let unchangedEmpty = await scanner.validatedAgentResults(
workspaceIds: [workspaceId],
agentPortsByWorkspace: [:],
agentRevisions: revisions
)
#expect(unchangedEmpty.isEmpty)
}
}

final class ProcessTerminationGateTests: XCTestCase {
func testPrelaunchTerminationRequestIsDeferredUntilLaunch() {
@Suite
struct ProcessTerminationGateTests {
@Test
func prelaunchTerminationRequestIsDeferredUntilLaunch() {
let gate = ProcessTerminationGate()

XCTAssertFalse(
gate.requestTermination(),
#expect(
!gate.requestTermination(),
"A cancellation that arrives before Process.run() succeeds must not touch the Process."
)
XCTAssertTrue(
#expect(
gate.markLaunched(),
"Once launch succeeds, the deferred termination request should be applied to the running Process."
)
gate.markFinished()
XCTAssertFalse(
gate.requestTermination(),
#expect(
!gate.requestTermination(),
"Late cancellation after completion must not touch Process termination state."
)
}

func testFinishedPrelaunchProcessIgnoresDeferredTermination() {
@Test
func finishedPrelaunchProcessIgnoresDeferredTermination() {
let gate = ProcessTerminationGate()

XCTAssertFalse(gate.requestTermination())
#expect(!gate.requestTermination())
gate.markFinished()
XCTAssertFalse(
gate.markLaunched(),
#expect(
!gate.markLaunched(),
"If launch fails and the run is already finished, no deferred termination should be applied."
)
}
Expand Down
Loading