From 9246564394cb70f558c6f89db2386362f977ef33 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 05:52:15 -0700 Subject: [PATCH 01/15] Add Codex monitor owner lifecycle regression --- tests/test_codex_feed_hooks.py | 58 ++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/tests/test_codex_feed_hooks.py b/tests/test_codex_feed_hooks.py index 43aeaaaad14a..21abe44b40ea 100644 --- a/tests/test_codex_feed_hooks.py +++ b/tests/test_codex_feed_hooks.py @@ -420,6 +420,63 @@ def test_codex_monitor_exits_when_workspace_has_no_surfaces(cli_path: str, root: raise AssertionError(f"monitor did not query owner surfaces: {fake.frames!r}") +def test_codex_monitor_exits_when_owner_process_exits(cli_path: str, root: Path) -> None: + socket_path = root / "cmux-monitor-owner-pid.sock" + transcript_path = root / "codex-session-owner-pid.jsonl" + transcript_path.write_text("", encoding="utf-8") + + session_id = f"codex-monitor-owner-pid-session-{os.getpid()}" + env = os.environ.copy() + env["CMUX_SOCKET_PATH"] = str(socket_path) + env["CMUX_WORKSPACE_ID"] = FAKE_WORKSPACE_ID + env["CMUX_CODEX_MONITOR_UNRESOLVED_TRANSCRIPT_TIMEOUT_SECONDS"] = "30" + + owner = subprocess.Popen(["/bin/sleep", "30"]) + with FakeCmuxSocket(socket_path, None): + monitor = subprocess.Popen( + [ + cli_path, + "--socket", + str(socket_path), + "hooks", + "codex", + "monitor", + "--workspace", + FAKE_WORKSPACE_ID, + "--session", + session_id, + "--surface", + FAKE_SURFACE_ID, + "--owner-pid", + str(owner.pid), + "--transcript", + str(transcript_path), + ], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=env, + ) + try: + wait_for_monitor_pids(session_id, present=True, timeout=5) + owner.terminate() + owner.wait(timeout=5) + stdout, stderr = monitor.communicate(timeout=5) + if monitor.returncode != 0: + raise AssertionError( + f"hooks codex monitor failed exit={monitor.returncode}\n" + f"stdout={stdout}\nstderr={stderr}" + ) + wait_for_monitor_pids(session_id, present=False, timeout=1) + finally: + if owner.poll() is None: + owner.kill() + if monitor.poll() is None: + monitor.kill() + for pid in monitor_pids_for_session(session_id): + subprocess.run(["/bin/kill", str(pid)], check=False) + + def test_codex_monitor_survives_transient_owner_rpc_timeout(cli_path: str, root: Path) -> None: socket_path = root / "cmux-monitor-timeout.sock" transcript_path = root / "codex-session-timeout.jsonl" @@ -1611,6 +1668,7 @@ def main() -> int: test_codex_stop_without_turn_keeps_session_wide_monitor(cli_path, root) test_codex_prompt_submit_starts_monitor_when_lease_write_fails(cli_path, root) test_codex_monitor_exits_when_workspace_has_no_surfaces(cli_path, root) + test_codex_monitor_exits_when_owner_process_exits(cli_path, root) test_codex_monitor_survives_transient_owner_rpc_timeout(cli_path, root) test_install_adds_codex_permission_request_hook(cli_path, root) test_install_escapes_codex_hook_trust_state_keys(cli_path, root) From 52a17928e518acf22b2d2fd0d67955b31e38973e Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 05:53:09 -0700 Subject: [PATCH 02/15] Reduce resumed session UI hot paths --- CLI/cmux.swift | 46 +++++++++++++++++++++- Sources/AppDelegate.swift | 20 ++++++++++ Sources/ContentView.swift | 37 +++++++++++++++--- Sources/TerminalController.swift | 65 ++++++++++++++++++++++++-------- vendor/bonsplit | 2 +- 5 files changed, 147 insertions(+), 23 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index b31694365ed2..0ed582b5d8bb 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -16619,6 +16619,7 @@ struct CMUXCLI { private static let codexMonitorRetiredLeaseMaxAgeSeconds: TimeInterval = 2 * 60 private static let codexMonitorOwnerCheckIntervalSeconds: TimeInterval = 60 private static let codexMonitorOwnerCheckTimeoutSeconds: TimeInterval = 1 + private static let codexMonitorUnresolvedTranscriptTimeoutSeconds: TimeInterval = 5 * 60 private func codexMonitorLeaseDirectory(env: [String: String]) -> URL { let statePath = NSString( @@ -16767,6 +16768,23 @@ struct CMUXCLI { return ownerFound ? .alive : .gone } + private func codexMonitorOwnerProcessIsGone(_ ownerPID: Int?) -> Bool { + guard let ownerPID, ownerPID > 1 else { return false } + if kill(pid_t(ownerPID), 0) == 0 { + return false + } + return errno == ESRCH + } + + private func codexMonitorUnresolvedTranscriptTimeout(env: [String: String]) -> TimeInterval { + guard let rawValue = env["CMUX_CODEX_MONITOR_UNRESOLVED_TRANSCRIPT_TIMEOUT_SECONDS"], + let parsed = TimeInterval(rawValue), + parsed > 0 else { + return Self.codexMonitorUnresolvedTranscriptTimeoutSeconds + } + return min(max(parsed, 0.05), Self.codexMonitorUnresolvedTranscriptTimeoutSeconds) + } + private func startCodexTranscriptMonitor( sessionId: String, turnId: String?, @@ -16774,6 +16792,7 @@ struct CMUXCLI { cwd: String?, workspaceId: String, surfaceId: String?, + ownerPID: Int?, leasePath: String?, env: [String: String], telemetry: CLISocketSentryTelemetry @@ -16788,6 +16807,7 @@ struct CMUXCLI { "has_turn_id": normalizedHookValue(turnId) != nil, "has_transcript": normalizedHookValue(transcriptPath) != nil, "has_surface_id": normalizedHookValue(surfaceId) != nil, + "has_owner_pid": ownerPID != nil, ] telemetry.breadcrumb("codex-hook.monitor.start", data: monitorTelemetry) @@ -16814,6 +16834,9 @@ struct CMUXCLI { if let cwd, !cwd.isEmpty { monitorArgs += ["--cwd", cwd] } + if let ownerPID, ownerPID > 1 { + monitorArgs += ["--owner-pid", String(ownerPID)] + } if let leasePath, !leasePath.isEmpty { monitorArgs += ["--lease", leasePath] } @@ -16842,6 +16865,7 @@ struct CMUXCLI { let turnId = optionValue(commandArgs, name: "--turn") var transcriptPath = optionValue(commandArgs, name: "--transcript") let leasePath = optionValue(commandArgs, name: "--lease") + let ownerPID = optionValue(commandArgs, name: "--owner-pid").flatMap(Int.init) guard !workspaceId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, !sessionId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { @@ -16850,9 +16874,14 @@ struct CMUXCLI { defer { removeCodexMonitorLease(path: leasePath) } let deadline = Date().addingTimeInterval(4 * 60 * 60) + let unresolvedTranscriptTimeout = codexMonitorUnresolvedTranscriptTimeout(env: env) + var transcriptMissingSince: Date? var nextOwnerCheck = Date.distantPast var publishedUserInputCallIds = Set() while Date() < deadline { + if codexMonitorOwnerProcessIsGone(ownerPID) { + return + } if isCodexMonitorLeaseRetired(path: leasePath) { return } @@ -16867,6 +16896,15 @@ struct CMUXCLI { if transcriptPath == nil { transcriptPath = findCodexTranscriptPath(sessionId: sessionId, env: env) } + if transcriptPath == nil { + let missingSince = transcriptMissingSince ?? now + transcriptMissingSince = missingSince + if now.timeIntervalSince(missingSince) >= unresolvedTranscriptTimeout { + return + } + } else { + transcriptMissingSince = nil + } if let currentTranscriptPath = transcriptPath { if let userInput = readCodexTranscriptUserInput( @@ -16914,7 +16952,12 @@ struct CMUXCLI { let remaining = deadline.timeIntervalSinceNow guard remaining > 0 else { return } - waitForCodexTranscriptChange(path: transcriptPath, leasePath: leasePath, timeout: min(30, remaining)) + var waitTimeout = min(30, remaining) + if let transcriptMissingSince { + let unresolvedRemaining = unresolvedTranscriptTimeout - Date().timeIntervalSince(transcriptMissingSince) + waitTimeout = min(waitTimeout, max(0.05, unresolvedRemaining)) + } + waitForCodexTranscriptChange(path: transcriptPath, leasePath: leasePath, timeout: waitTimeout) } } @@ -19050,6 +19093,7 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { cwd: hookCwd ?? mapped?.cwd, workspaceId: workspaceId, surfaceId: surfaceId, + ownerPID: pid, leasePath: leasePath, env: env, telemetry: telemetry diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index f224610e3be1..128418f3f9d4 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -3982,6 +3982,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent var id: UUID { windowId } } + struct WindowMoveTargetSnapshot: Identifiable, Equatable { + let windowId: UUID + let label: String + let isCurrentWindow: Bool + + var id: UUID { windowId } + } + struct WorkspaceMoveTarget: Identifiable { let windowId: UUID let workspaceId: UUID @@ -3996,6 +4004,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent } } + func windowMoveTargetSnapshots(referenceWindowId: UUID?) -> [WindowMoveTargetSnapshot] { + let orderedSummaries = orderedMainWindowSummaries(referenceWindowId: referenceWindowId) + let labels = windowLabelsById(orderedSummaries: orderedSummaries, referenceWindowId: referenceWindowId) + return orderedSummaries.map { summary in + WindowMoveTargetSnapshot( + windowId: summary.windowId, + label: labels[summary.windowId] ?? "Window", + isCurrentWindow: summary.windowId == referenceWindowId + ) + } + } + func windowMoveTargets(referenceWindowId: UUID?) -> [WindowMoveTarget] { let orderedSummaries = orderedMainWindowSummaries(referenceWindowId: referenceWindowId) let labels = windowLabelsById(orderedSummaries: orderedSummaries, referenceWindowId: referenceWindowId) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 9c9dc725a9af..6670c5f79068 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -9107,6 +9107,7 @@ struct VerticalTabsSidebar: View { @State private var terminalScrollBarVisibilityGeneration: UInt64 = 0 @State private var laidOutWorkspaceRowIds: Set = [] @State private var pendingSelectedWorkspaceScrollId: UUID? + @State private var workspaceWindowMoveTargets: [AppDelegate.WindowMoveTargetSnapshot] = [] @AppStorage(WorkspacePresentationModeSettings.modeKey) private var workspacePresentationMode = WorkspacePresentationModeSettings.defaultMode.rawValue @AppStorage("sidebarMatchTerminalBackground") @@ -9184,6 +9185,7 @@ struct VerticalTabsSidebar: View { let allSelectedRemoteContextMenuTargetsConnecting: Bool let allSelectedRemoteContextMenuTargetsDisconnected: Bool let workspaceTerminalScrollBarHiddenById: [UUID: Bool] + let windowMoveTargets: [AppDelegate.WindowMoveTargetSnapshot] var workspaceIds: [UUID] { tabs.map(\.id) @@ -9224,7 +9226,8 @@ struct VerticalTabsSidebar: View { selectedRemoteContextMenuWorkspaceIds: selectedRemoteContextMenuWorkspaceIds, allSelectedRemoteContextMenuTargetsConnecting: allSelectedRemoteContextMenuTargetsConnecting, allSelectedRemoteContextMenuTargetsDisconnected: allSelectedRemoteContextMenuTargetsDisconnected, - workspaceTerminalScrollBarHiddenById: workspaceTerminalScrollBarHiddenById + workspaceTerminalScrollBarHiddenById: workspaceTerminalScrollBarHiddenById, + windowMoveTargets: workspaceWindowMoveTargets ) ZStack(alignment: .bottomLeading) { @@ -9243,6 +9246,15 @@ struct VerticalTabsSidebar: View { } .frame(width: 0, height: 0) ) + .onAppear { + refreshWorkspaceWindowMoveTargets() + } + .onReceive( + NotificationCenter.default.publisher(for: .mainWindowContextsDidChange) + .receive(on: RunLoop.main) + ) { _ in + refreshWorkspaceWindowMoveTargets() + } .onAppear { modifierKeyMonitor.start() draggedTabId = nil @@ -9591,6 +9603,7 @@ struct VerticalTabsSidebar: View { allRemoteContextMenuTargetsDisconnected: allRemoteContextMenuTargetsDisconnected, allContextMenuWorkspacesHideTerminalScrollBar: allContextMenuWorkspacesHideTerminalScrollBar, contextMenuPinState: contextMenuPinState, + workspaceWindowMoveTargets: renderContext.windowMoveTargets, settings: renderContext.tabItemSettings, livePresentation: livePresentation, frozenPresentation: $frozenTabItemPresentation @@ -9608,6 +9621,20 @@ struct VerticalTabsSidebar: View { guard let id else { return "nil" } return String(id.uuidString.prefix(5)) } + + private func refreshWorkspaceWindowMoveTargets() { + guard let app = AppDelegate.shared else { + if !workspaceWindowMoveTargets.isEmpty { + workspaceWindowMoveTargets = [] + } + return + } + let referenceWindowId = app.windowId(for: tabManager) + let targets = app.windowMoveTargetSnapshots(referenceWindowId: referenceWindowId) + if workspaceWindowMoveTargets != targets { + workspaceWindowMoveTargets = targets + } + } } private struct SidebarWorkspaceRowIdsPreferenceKey: PreferenceKey { @@ -12013,6 +12040,7 @@ private struct TabItemView: View, Equatable { lhs.allRemoteContextMenuTargetsDisconnected == rhs.allRemoteContextMenuTargetsDisconnected && lhs.allContextMenuWorkspacesHideTerminalScrollBar == rhs.allContextMenuWorkspacesHideTerminalScrollBar && lhs.contextMenuPinState == rhs.contextMenuPinState && + lhs.workspaceWindowMoveTargets == rhs.workspaceWindowMoveTargets && lhs.settings == rhs.settings } @@ -12045,6 +12073,7 @@ private struct TabItemView: View, Equatable { let allRemoteContextMenuTargetsDisconnected: Bool let allContextMenuWorkspacesHideTerminalScrollBar: Bool let contextMenuPinState: WorkspaceActionDispatcher.PinState? + let workspaceWindowMoveTargets: [AppDelegate.WindowMoveTargetSnapshot] let settings: SidebarTabItemSettingsSnapshot let livePresentation: SidebarTabItemPresentationSnapshot @Binding var frozenPresentation: SidebarTabItemPresentationSnapshot? @@ -12944,8 +12973,6 @@ private struct TabItemView: View, Equatable { } .disabled(targetIds.isEmpty) - let referenceWindowId = AppDelegate.shared?.windowId(for: tabManager) - let windowMoveTargets = AppDelegate.shared?.windowMoveTargets(referenceWindowId: referenceWindowId) ?? [] let moveMenuTitle = targetIds.count > 1 ? String(localized: "contextMenu.moveWorkspacesToWindow", defaultValue: "Move Workspaces to Window") : String(localized: "contextMenu.moveWorkspaceToWindow", defaultValue: "Move Workspace to Window") @@ -12955,11 +12982,11 @@ private struct TabItemView: View, Equatable { } .disabled(targetIds.isEmpty) - if !windowMoveTargets.isEmpty { + if !workspaceWindowMoveTargets.isEmpty { Divider() } - ForEach(windowMoveTargets) { target in + ForEach(workspaceWindowMoveTargets) { target in Button(target.label) { moveWorkspaces(targetIds, toWindow: target.windowId) } diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index fefcaf8efcc1..65f2031a0584 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -438,6 +438,22 @@ class TerminalController { return current.value != value || current.label != label } + nonisolated static func shouldAppendLogEntry( + after last: SidebarLogEntry?, + message: String, + level: SidebarLogLevel, + source: String?, + now: Date + ) -> Bool { + guard let last else { return true } + guard last.message == message, + last.level == level, + last.source == source else { + return true + } + return now.timeIntervalSince(last.timestamp) >= 5 + } + nonisolated static func shouldReplaceGitBranch( current: SidebarGitBranchState?, branch: String, @@ -16868,20 +16884,30 @@ class TerminalController { } let source = parsed.options["source"] - var result = "OK" - v2MainSync { - guard let tab = resolveTabForReport(args) else { - result = parsed.options["tab"] != nil ? "ERROR: Tab not found" : "ERROR: No tab selected" + let targetResolution = parseSidebarMutationTabTarget(options: parsed.options) + guard let target = targetResolution.target else { + return targetResolution.error ?? "ERROR: No tab selected" + } + + scheduleSidebarMutation(target: target) { _, tab in + let now = Date() + guard Self.shouldAppendLogEntry( + after: tab.logEntries.last, + message: message, + level: level, + source: source, + now: now + ) else { return } - tab.logEntries.append(SidebarLogEntry(message: message, level: level, source: source, timestamp: Date())) + tab.logEntries.append(SidebarLogEntry(message: message, level: level, source: source, timestamp: now)) let configuredLimit = UserDefaults.standard.object(forKey: "sidebarMaxLogEntries") as? Int ?? 50 let limit = max(1, min(500, configuredLimit)) if tab.logEntries.count > limit { tab.logEntries.removeFirst(tab.logEntries.count - limit) } } - return result + return "OK" } private func clearLog(_ args: String) -> String { @@ -16947,27 +16973,34 @@ class TerminalController { let clamped = min(1.0, max(0.0, value)) let label = parsed.options["label"] - var result = "OK" - v2MainSync { - guard let tab = resolveTabForReport(args) else { - result = parsed.options["tab"] != nil ? "ERROR: Tab not found" : "ERROR: No tab selected" + let targetResolution = parseSidebarMutationTabTarget(options: parsed.options) + guard let target = targetResolution.target else { + return targetResolution.error ?? "ERROR: No tab selected" + } + + scheduleSidebarMutation(target: target) { _, tab in + guard Self.shouldReplaceProgress(current: tab.progress, value: clamped, label: label) else { return } tab.progress = SidebarProgressState(value: clamped, label: label) } - return result + return "OK" } private func clearProgress(_ args: String) -> String { - var result = "OK" - v2MainSync { - guard let tab = resolveTabForReport(args) else { - result = "ERROR: Tab not found" + let parsed = parseOptions(args) + let targetResolution = parseSidebarMutationTabTarget(options: parsed.options) + guard let target = targetResolution.target else { + return targetResolution.error ?? "ERROR: No tab selected" + } + + scheduleSidebarMutation(target: target) { _, tab in + guard tab.progress != nil else { return } tab.progress = nil } - return result + return "OK" } private func reportGitBranch(_ args: String) -> String { diff --git a/vendor/bonsplit b/vendor/bonsplit index f65eccb2e4bf..b15d5be3bb2d 160000 --- a/vendor/bonsplit +++ b/vendor/bonsplit @@ -1 +1 @@ -Subproject commit f65eccb2e4bf3e77662902f7c44a650fba3b3540 +Subproject commit b15d5be3bb2d1b33c6b3c83b60992044b09d5b6d From a2cc1d99e7d2b5577412406c72aab5b040b8c4ef Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 06:05:02 -0700 Subject: [PATCH 03/15] Tighten Codex monitor owner PID regression --- tests/test_codex_feed_hooks.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/tests/test_codex_feed_hooks.py b/tests/test_codex_feed_hooks.py index 21abe44b40ea..4f3c5fba90b7 100644 --- a/tests/test_codex_feed_hooks.py +++ b/tests/test_codex_feed_hooks.py @@ -432,7 +432,11 @@ def test_codex_monitor_exits_when_owner_process_exits(cli_path: str, root: Path) env["CMUX_CODEX_MONITOR_UNRESOLVED_TRANSCRIPT_TIMEOUT_SECONDS"] = "30" owner = subprocess.Popen(["/bin/sleep", "30"]) - with FakeCmuxSocket(socket_path, None): + with FakeCmuxSocket( + socket_path, + None, + surfaces=[{"id": FAKE_SURFACE_ID, "ref": FAKE_SURFACE_ID}], + ) as fake: monitor = subprocess.Popen( [ cli_path, @@ -459,6 +463,27 @@ def test_codex_monitor_exits_when_owner_process_exits(cli_path: str, root: Path) ) try: wait_for_monitor_pids(session_id, present=True, timeout=5) + deadline = time.time() + 5 + while time.time() < deadline: + if monitor.poll() is not None: + stdout, stderr = monitor.communicate(timeout=1) + raise AssertionError( + "monitor exited before owner PID was terminated; " + f"stdout={stdout}\nstderr={stderr}" + ) + if any(frame.get("method") == "surface.list" for frame in fake.frames): + break + time.sleep(0.05) + else: + raise AssertionError(f"monitor did not query owner surfaces: {fake.frames!r}") + + if monitor.poll() is not None: + stdout, stderr = monitor.communicate(timeout=1) + raise AssertionError( + "monitor exited from surface ownership check before owner PID was terminated; " + f"stdout={stdout}\nstderr={stderr}" + ) + owner.terminate() owner.wait(timeout=5) stdout, stderr = monitor.communicate(timeout=5) From 61d63951058040bdbcd7f99248d49fafc07d6abd Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 06:18:41 -0700 Subject: [PATCH 04/15] Address Codex monitor review feedback --- CLI/cmux.swift | 36 ++++++++++++++++++++---- Sources/AppDelegate.swift | 15 +++++++++- Sources/ContentView.swift | 38 ++++++------------------- tests/test_codex_feed_hooks.py | 51 ++++++++++++++++++++++++++++++++++ 4 files changed, 104 insertions(+), 36 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 68cb1e3111a5..f73115988d24 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -16804,7 +16804,7 @@ struct CMUXCLI { parsed > 0 else { return Self.codexMonitorUnresolvedTranscriptTimeoutSeconds } - return min(max(parsed, 0.05), Self.codexMonitorUnresolvedTranscriptTimeoutSeconds) + return max(parsed, 0.05) } private func startCodexTranscriptMonitor( @@ -16824,12 +16824,20 @@ struct CMUXCLI { return } + let validOwnerPID = ownerPID.flatMap { $0 > 1 ? $0 : nil } + if ownerPID != nil, validOwnerPID == nil { + telemetry.breadcrumb( + "codex-hook.monitor.invalid-owner-pid", + data: ["owner_pid": ownerPID ?? -1] + ) + } + let monitorTelemetry: [String: Any] = [ "has_lease": normalizedHookValue(leasePath) != nil, "has_turn_id": normalizedHookValue(turnId) != nil, "has_transcript": normalizedHookValue(transcriptPath) != nil, "has_surface_id": normalizedHookValue(surfaceId) != nil, - "has_owner_pid": ownerPID != nil, + "has_owner_pid": validOwnerPID != nil, ] telemetry.breadcrumb("codex-hook.monitor.start", data: monitorTelemetry) @@ -16856,7 +16864,7 @@ struct CMUXCLI { if let cwd, !cwd.isEmpty { monitorArgs += ["--cwd", cwd] } - if let ownerPID, ownerPID > 1 { + if let ownerPID = validOwnerPID { monitorArgs += ["--owner-pid", String(ownerPID)] } if let leasePath, !leasePath.isEmpty { @@ -16875,7 +16883,11 @@ struct CMUXCLI { } } - private func runCodexTranscriptMonitor(commandArgs: [String], client: SocketClient) throws { + private func runCodexTranscriptMonitor( + commandArgs: [String], + client: SocketClient, + telemetry: CLISocketSentryTelemetry + ) throws { let env = ProcessInfo.processInfo.environment let workspaceId = optionValue(commandArgs, name: "--workspace") ?? env["CMUX_WORKSPACE_ID"] ?? "" let surfaceId = optionValue(commandArgs, name: "--surface") ?? env["CMUX_SURFACE_ID"] @@ -16887,7 +16899,19 @@ struct CMUXCLI { let turnId = optionValue(commandArgs, name: "--turn") var transcriptPath = optionValue(commandArgs, name: "--transcript") let leasePath = optionValue(commandArgs, name: "--lease") - let ownerPID = optionValue(commandArgs, name: "--owner-pid").flatMap(Int.init) + let ownerPID: Int? + if let rawOwnerPID = optionValue(commandArgs, name: "--owner-pid") { + guard let parsedOwnerPID = Int(rawOwnerPID), parsedOwnerPID > 1 else { + telemetry.breadcrumb( + "codex-hook.monitor.invalid-owner-pid", + data: ["raw": rawOwnerPID] + ) + return + } + ownerPID = parsedOwnerPID + } else { + ownerPID = nil + } guard !workspaceId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, !sessionId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { @@ -18984,7 +19008,7 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { telemetry.breadcrumb("\(def.name)-hook.\(subcommand)") if def.name == "codex", subcommand == "monitor" { - try runCodexTranscriptMonitor(commandArgs: hookArgs, client: client) + try runCodexTranscriptMonitor(commandArgs: hookArgs, client: client, telemetry: telemetry) return } diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 36187e912c40..faf8a1ddf1af 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -843,6 +843,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent var mainWindowContexts: [ObjectIdentifier: MainWindowContext] = [:] private var mainWindowControllers: [MainWindowController] = [] + private var windowMoveTargetSnapshotCache: [WindowMoveTargetSnapshotCacheKey: [WindowMoveTargetSnapshot]] = [:] /// Tracks the cascade point for new windows, matching Ghostty's upstream algorithm. /// Reset to `.zero` so the first window seeds the point from its own position. @@ -3833,6 +3834,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent #endif private func notifyMainWindowContextsDidChange() { + windowMoveTargetSnapshotCache.removeAll() NotificationCenter.default.post(name: .mainWindowContextsDidChange, object: self) } @@ -3990,6 +3992,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent var id: UUID { windowId } } + private struct WindowMoveTargetSnapshotCacheKey: Hashable { + let referenceWindowId: UUID? + } + struct WorkspaceMoveTarget: Identifiable { let windowId: UUID let workspaceId: UUID @@ -4005,15 +4011,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent } func windowMoveTargetSnapshots(referenceWindowId: UUID?) -> [WindowMoveTargetSnapshot] { + let cacheKey = WindowMoveTargetSnapshotCacheKey(referenceWindowId: referenceWindowId) + if let cached = windowMoveTargetSnapshotCache[cacheKey] { + return cached + } + let orderedSummaries = orderedMainWindowSummaries(referenceWindowId: referenceWindowId) let labels = windowLabelsById(orderedSummaries: orderedSummaries, referenceWindowId: referenceWindowId) - return orderedSummaries.map { summary in + let snapshots = orderedSummaries.map { summary in WindowMoveTargetSnapshot( windowId: summary.windowId, label: labels[summary.windowId] ?? "Window", isCurrentWindow: summary.windowId == referenceWindowId ) } + windowMoveTargetSnapshotCache[cacheKey] = snapshots + return snapshots } func windowMoveTargets(referenceWindowId: UUID?) -> [WindowMoveTarget] { diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 87f60e14780d..55d37b832848 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -9104,7 +9104,6 @@ struct VerticalTabsSidebar: View { @State private var terminalScrollBarVisibilityGeneration: UInt64 = 0 @State private var laidOutWorkspaceRowIds: Set = [] @State private var pendingSelectedWorkspaceScrollId: UUID? - @State private var workspaceWindowMoveTargets: [AppDelegate.WindowMoveTargetSnapshot] = [] @AppStorage(WorkspacePresentationModeSettings.modeKey) private var workspacePresentationMode = WorkspacePresentationModeSettings.defaultMode.rawValue @AppStorage("sidebarMatchTerminalBackground") @@ -9136,6 +9135,11 @@ struct VerticalTabsSidebar: View { return KeyboardShortcutSettings.shortcut(for: .selectWorkspaceByNumber) } + private func workspaceWindowMoveTargets() -> [AppDelegate.WindowMoveTargetSnapshot] { + guard let app = AppDelegate.shared else { return [] } + return app.windowMoveTargetSnapshots(referenceWindowId: app.windowId(for: tabManager)) + } + private func requestSelectedWorkspaceScroll(_ proxy: ScrollViewProxy, workspaceIds: [UUID]) { guard let selectedWorkspaceId = tabManager.selectedTabId, workspaceIds.contains(selectedWorkspaceId) else { @@ -9182,7 +9186,6 @@ struct VerticalTabsSidebar: View { let allSelectedRemoteContextMenuTargetsConnecting: Bool let allSelectedRemoteContextMenuTargetsDisconnected: Bool let workspaceTerminalScrollBarHiddenById: [UUID: Bool] - let windowMoveTargets: [AppDelegate.WindowMoveTargetSnapshot] var workspaceIds: [UUID] { tabs.map(\.id) @@ -9223,8 +9226,7 @@ struct VerticalTabsSidebar: View { selectedRemoteContextMenuWorkspaceIds: selectedRemoteContextMenuWorkspaceIds, allSelectedRemoteContextMenuTargetsConnecting: allSelectedRemoteContextMenuTargetsConnecting, allSelectedRemoteContextMenuTargetsDisconnected: allSelectedRemoteContextMenuTargetsDisconnected, - workspaceTerminalScrollBarHiddenById: workspaceTerminalScrollBarHiddenById, - windowMoveTargets: workspaceWindowMoveTargets + workspaceTerminalScrollBarHiddenById: workspaceTerminalScrollBarHiddenById ) ZStack(alignment: .bottomLeading) { @@ -9243,15 +9245,6 @@ struct VerticalTabsSidebar: View { } .frame(width: 0, height: 0) ) - .onAppear { - refreshWorkspaceWindowMoveTargets() - } - .onReceive( - NotificationCenter.default.publisher(for: .mainWindowContextsDidChange) - .receive(on: RunLoop.main) - ) { _ in - refreshWorkspaceWindowMoveTargets() - } .onAppear { modifierKeyMonitor.start() draggedTabId = nil @@ -9600,7 +9593,7 @@ struct VerticalTabsSidebar: View { allRemoteContextMenuTargetsDisconnected: allRemoteContextMenuTargetsDisconnected, allContextMenuWorkspacesHideTerminalScrollBar: allContextMenuWorkspacesHideTerminalScrollBar, contextMenuPinState: contextMenuPinState, - workspaceWindowMoveTargets: renderContext.windowMoveTargets, + workspaceWindowMoveTargetsProvider: workspaceWindowMoveTargets, settings: renderContext.tabItemSettings, livePresentation: livePresentation, frozenPresentation: $frozenTabItemPresentation @@ -9619,19 +9612,6 @@ struct VerticalTabsSidebar: View { return String(id.uuidString.prefix(5)) } - private func refreshWorkspaceWindowMoveTargets() { - guard let app = AppDelegate.shared else { - if !workspaceWindowMoveTargets.isEmpty { - workspaceWindowMoveTargets = [] - } - return - } - let referenceWindowId = app.windowId(for: tabManager) - let targets = app.windowMoveTargetSnapshots(referenceWindowId: referenceWindowId) - if workspaceWindowMoveTargets != targets { - workspaceWindowMoveTargets = targets - } - } } private struct SidebarWorkspaceRowIdsPreferenceKey: PreferenceKey { @@ -12037,7 +12017,6 @@ private struct TabItemView: View, Equatable { lhs.allRemoteContextMenuTargetsDisconnected == rhs.allRemoteContextMenuTargetsDisconnected && lhs.allContextMenuWorkspacesHideTerminalScrollBar == rhs.allContextMenuWorkspacesHideTerminalScrollBar && lhs.contextMenuPinState == rhs.contextMenuPinState && - lhs.workspaceWindowMoveTargets == rhs.workspaceWindowMoveTargets && lhs.settings == rhs.settings } @@ -12070,7 +12049,7 @@ private struct TabItemView: View, Equatable { let allRemoteContextMenuTargetsDisconnected: Bool let allContextMenuWorkspacesHideTerminalScrollBar: Bool let contextMenuPinState: WorkspaceActionDispatcher.PinState? - let workspaceWindowMoveTargets: [AppDelegate.WindowMoveTargetSnapshot] + let workspaceWindowMoveTargetsProvider: () -> [AppDelegate.WindowMoveTargetSnapshot] let settings: SidebarTabItemSettingsSnapshot let livePresentation: SidebarTabItemPresentationSnapshot @Binding var frozenPresentation: SidebarTabItemPresentationSnapshot? @@ -12788,6 +12767,7 @@ private struct TabItemView: View, Equatable { let isMulti = targetIds.count > 1 let tabColorPalette = WorkspaceTabColorSettings.palette() let shouldPin = contextMenuPinState?.pinned ?? !tab.isPinned + let workspaceWindowMoveTargets = workspaceWindowMoveTargetsProvider() let reconnectLabel = contextMenuLabel( multi: String(localized: "contextMenu.reconnectWorkspaces", defaultValue: "Reconnect Workspaces"), single: String(localized: "contextMenu.reconnectWorkspace", defaultValue: "Reconnect Workspace"), diff --git a/tests/test_codex_feed_hooks.py b/tests/test_codex_feed_hooks.py index 4f3c5fba90b7..d35602314946 100644 --- a/tests/test_codex_feed_hooks.py +++ b/tests/test_codex_feed_hooks.py @@ -502,6 +502,56 @@ def test_codex_monitor_exits_when_owner_process_exits(cli_path: str, root: Path) subprocess.run(["/bin/kill", str(pid)], check=False) +def test_codex_monitor_rejects_invalid_owner_pid(cli_path: str, root: Path) -> None: + socket_path = root / "cmux-monitor-invalid-owner-pid.sock" + transcript_path = root / "codex-session-invalid-owner-pid.jsonl" + transcript_path.write_text("", encoding="utf-8") + + session_id = f"codex-monitor-invalid-owner-pid-session-{os.getpid()}" + env = os.environ.copy() + env["CMUX_SOCKET_PATH"] = str(socket_path) + env["CMUX_WORKSPACE_ID"] = FAKE_WORKSPACE_ID + env["CMUX_CODEX_MONITOR_UNRESOLVED_TRANSCRIPT_TIMEOUT_SECONDS"] = "30" + + with FakeCmuxSocket( + socket_path, + None, + surfaces=[{"id": FAKE_SURFACE_ID, "ref": FAKE_SURFACE_ID}], + ) as fake: + result = subprocess.run( + [ + cli_path, + "--socket", + str(socket_path), + "hooks", + "codex", + "monitor", + "--workspace", + FAKE_WORKSPACE_ID, + "--session", + session_id, + "--surface", + FAKE_SURFACE_ID, + "--owner-pid", + "1", + "--transcript", + str(transcript_path), + ], + capture_output=True, + text=True, + check=False, + env=env, + timeout=3, + ) + if result.returncode != 0: + raise AssertionError( + f"hooks codex monitor failed exit={result.returncode}\n" + f"stdout={result.stdout}\nstderr={result.stderr}" + ) + if any(frame.get("method") == "surface.list" for frame in fake.frames): + raise AssertionError(f"invalid owner pid should exit before owner RPC: {fake.frames!r}") + + def test_codex_monitor_survives_transient_owner_rpc_timeout(cli_path: str, root: Path) -> None: socket_path = root / "cmux-monitor-timeout.sock" transcript_path = root / "codex-session-timeout.jsonl" @@ -1694,6 +1744,7 @@ def main() -> int: test_codex_prompt_submit_starts_monitor_when_lease_write_fails(cli_path, root) test_codex_monitor_exits_when_workspace_has_no_surfaces(cli_path, root) test_codex_monitor_exits_when_owner_process_exits(cli_path, root) + test_codex_monitor_rejects_invalid_owner_pid(cli_path, root) test_codex_monitor_survives_transient_owner_rpc_timeout(cli_path, root) test_install_adds_codex_permission_request_hook(cli_path, root) test_install_escapes_codex_hook_trust_state_keys(cli_path, root) From 378610d062551487600fbb0c80e0cb593b2e8c55 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 06:20:02 -0700 Subject: [PATCH 05/15] Bound Codex monitor owner polling --- CLI/cmux.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index f73115988d24..c0e2729824de 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -16641,6 +16641,7 @@ struct CMUXCLI { private static let codexMonitorRetiredLeaseMaxAgeSeconds: TimeInterval = 2 * 60 private static let codexMonitorOwnerCheckIntervalSeconds: TimeInterval = 60 private static let codexMonitorOwnerCheckTimeoutSeconds: TimeInterval = 1 + private static let codexMonitorOwnerProcessPollIntervalSeconds: TimeInterval = 1 private static let codexMonitorUnresolvedTranscriptTimeoutSeconds: TimeInterval = 5 * 60 private func codexMonitorLeaseDirectory(env: [String: String]) -> URL { @@ -17003,6 +17004,9 @@ struct CMUXCLI { let unresolvedRemaining = unresolvedTranscriptTimeout - Date().timeIntervalSince(transcriptMissingSince) waitTimeout = min(waitTimeout, max(0.05, unresolvedRemaining)) } + if ownerPID != nil { + waitTimeout = min(waitTimeout, Self.codexMonitorOwnerProcessPollIntervalSeconds) + } waitForCodexTranscriptChange(path: transcriptPath, leasePath: leasePath, timeout: waitTimeout) } } From c7a2816e427d84f54d45a9173aa4bc064d595b2a Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 06:31:50 -0700 Subject: [PATCH 06/15] Address Codex monitor cache review --- CLI/cmux.swift | 7 ++++++- Sources/AppDelegate.swift | 20 ++++++++++++++++++-- tests/test_codex_feed_hooks.py | 4 ++-- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index c0e2729824de..07b0e0ceb794 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -16907,7 +16907,12 @@ struct CMUXCLI { "codex-hook.monitor.invalid-owner-pid", data: ["raw": rawOwnerPID] ) - return + throw CLIError( + message: String( + localized: "cli.error.codexMonitorInvalidOwnerPID", + defaultValue: "hooks codex monitor: --owner-pid must be an integer greater than 1" + ) + ) } ownerPID = parsedOwnerPID } else { diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index faf8a1ddf1af..9c7329e78aba 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -3994,6 +3994,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent private struct WindowMoveTargetSnapshotCacheKey: Hashable { let referenceWindowId: UUID? + let orderingFingerprint: String } struct WorkspaceMoveTarget: Identifiable { @@ -4011,12 +4012,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent } func windowMoveTargetSnapshots(referenceWindowId: UUID?) -> [WindowMoveTargetSnapshot] { - let cacheKey = WindowMoveTargetSnapshotCacheKey(referenceWindowId: referenceWindowId) + let orderedSummaries = orderedMainWindowSummaries(referenceWindowId: referenceWindowId) + let cacheKey = WindowMoveTargetSnapshotCacheKey( + referenceWindowId: referenceWindowId, + orderingFingerprint: windowMoveTargetOrderingFingerprint(orderedSummaries) + ) if let cached = windowMoveTargetSnapshotCache[cacheKey] { return cached } - let orderedSummaries = orderedMainWindowSummaries(referenceWindowId: referenceWindowId) let labels = windowLabelsById(orderedSummaries: orderedSummaries, referenceWindowId: referenceWindowId) let snapshots = orderedSummaries.map { summary in WindowMoveTargetSnapshot( @@ -5074,6 +5078,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent } } + private func windowMoveTargetOrderingFingerprint(_ summaries: [MainWindowSummary]) -> String { + summaries.map { summary in + [ + summary.windowId.uuidString, + summary.isKeyWindow ? "key" : "not-key", + summary.isVisible ? "visible" : "hidden", + String(summary.workspaceCount), + summary.selectedWorkspaceId?.uuidString ?? "none", + ].joined(separator: ":") + }.joined(separator: "|") + } + private func windowLabelsById(orderedSummaries: [MainWindowSummary], referenceWindowId: UUID?) -> [UUID: String] { var labels: [UUID: String] = [:] for (index, summary) in orderedSummaries.enumerated() { diff --git a/tests/test_codex_feed_hooks.py b/tests/test_codex_feed_hooks.py index d35602314946..df3262bd2782 100644 --- a/tests/test_codex_feed_hooks.py +++ b/tests/test_codex_feed_hooks.py @@ -543,9 +543,9 @@ def test_codex_monitor_rejects_invalid_owner_pid(cli_path: str, root: Path) -> N env=env, timeout=3, ) - if result.returncode != 0: + if result.returncode == 0: raise AssertionError( - f"hooks codex monitor failed exit={result.returncode}\n" + "hooks codex monitor accepted invalid --owner-pid\n" f"stdout={result.stdout}\nstderr={result.stderr}" ) if any(frame.get("method") == "surface.list" for frame in fake.frames): From 70f3042c2ea9a52b660022d9675e0ed99fd7cd2f Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 06:43:46 -0700 Subject: [PATCH 07/15] Harden Codex monitor regression review cases --- Sources/AppDelegate.swift | 22 ++-- tests/test_codex_feed_hooks.py | 188 ++++++++++++++++++--------------- 2 files changed, 114 insertions(+), 96 deletions(-) diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 9c7329e78aba..5fab39732aac 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -843,7 +843,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent var mainWindowContexts: [ObjectIdentifier: MainWindowContext] = [:] private var mainWindowControllers: [MainWindowController] = [] - private var windowMoveTargetSnapshotCache: [WindowMoveTargetSnapshotCacheKey: [WindowMoveTargetSnapshot]] = [:] + private var windowMoveTargetSnapshotCache: [WindowMoveTargetSnapshotCacheKey: WindowMoveTargetSnapshotCacheEntry] = [:] /// Tracks the cascade point for new windows, matching Ghostty's upstream algorithm. /// Reset to `.zero` so the first window seeds the point from its own position. @@ -3994,7 +3994,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent private struct WindowMoveTargetSnapshotCacheKey: Hashable { let referenceWindowId: UUID? + } + + private struct WindowMoveTargetSnapshotCacheEntry { let orderingFingerprint: String + let snapshots: [WindowMoveTargetSnapshot] } struct WorkspaceMoveTarget: Identifiable { @@ -4013,12 +4017,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent func windowMoveTargetSnapshots(referenceWindowId: UUID?) -> [WindowMoveTargetSnapshot] { let orderedSummaries = orderedMainWindowSummaries(referenceWindowId: referenceWindowId) - let cacheKey = WindowMoveTargetSnapshotCacheKey( - referenceWindowId: referenceWindowId, - orderingFingerprint: windowMoveTargetOrderingFingerprint(orderedSummaries) - ) - if let cached = windowMoveTargetSnapshotCache[cacheKey] { - return cached + let cacheKey = WindowMoveTargetSnapshotCacheKey(referenceWindowId: referenceWindowId) + let fingerprint = windowMoveTargetOrderingFingerprint(orderedSummaries) + if let cached = windowMoveTargetSnapshotCache[cacheKey], + cached.orderingFingerprint == fingerprint { + return cached.snapshots } let labels = windowLabelsById(orderedSummaries: orderedSummaries, referenceWindowId: referenceWindowId) @@ -4029,7 +4032,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent isCurrentWindow: summary.windowId == referenceWindowId ) } - windowMoveTargetSnapshotCache[cacheKey] = snapshots + windowMoveTargetSnapshotCache[cacheKey] = WindowMoveTargetSnapshotCacheEntry( + orderingFingerprint: fingerprint, + snapshots: snapshots + ) return snapshots } diff --git a/tests/test_codex_feed_hooks.py b/tests/test_codex_feed_hooks.py index df3262bd2782..8507c675cd1d 100644 --- a/tests/test_codex_feed_hooks.py +++ b/tests/test_codex_feed_hooks.py @@ -431,40 +431,42 @@ def test_codex_monitor_exits_when_owner_process_exits(cli_path: str, root: Path) env["CMUX_WORKSPACE_ID"] = FAKE_WORKSPACE_ID env["CMUX_CODEX_MONITOR_UNRESOLVED_TRANSCRIPT_TIMEOUT_SECONDS"] = "30" - owner = subprocess.Popen(["/bin/sleep", "30"]) - with FakeCmuxSocket( - socket_path, - None, - surfaces=[{"id": FAKE_SURFACE_ID, "ref": FAKE_SURFACE_ID}], - ) as fake: - monitor = subprocess.Popen( - [ - cli_path, - "--socket", - str(socket_path), - "hooks", - "codex", - "monitor", - "--workspace", - FAKE_WORKSPACE_ID, - "--session", - session_id, - "--surface", - FAKE_SURFACE_ID, - "--owner-pid", - str(owner.pid), - "--transcript", - str(transcript_path), - ], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - env=env, - ) - try: + owner = None + monitor = None + try: + with FakeCmuxSocket( + socket_path, + None, + surfaces=[{"id": FAKE_SURFACE_ID, "ref": FAKE_SURFACE_ID}], + ) as fake: + owner = subprocess.Popen(["/bin/sleep", "30"]) + monitor = subprocess.Popen( + [ + cli_path, + "--socket", + str(socket_path), + "hooks", + "codex", + "monitor", + "--workspace", + FAKE_WORKSPACE_ID, + "--session", + session_id, + "--surface", + FAKE_SURFACE_ID, + "--owner-pid", + str(owner.pid), + "--transcript", + str(transcript_path), + ], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=env, + ) wait_for_monitor_pids(session_id, present=True, timeout=5) - deadline = time.time() + 5 - while time.time() < deadline: + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: if monitor.poll() is not None: stdout, stderr = monitor.communicate(timeout=1) raise AssertionError( @@ -492,64 +494,74 @@ def test_codex_monitor_exits_when_owner_process_exits(cli_path: str, root: Path) f"hooks codex monitor failed exit={monitor.returncode}\n" f"stdout={stdout}\nstderr={stderr}" ) - wait_for_monitor_pids(session_id, present=False, timeout=1) - finally: - if owner.poll() is None: - owner.kill() - if monitor.poll() is None: - monitor.kill() - for pid in monitor_pids_for_session(session_id): - subprocess.run(["/bin/kill", str(pid)], check=False) + wait_for_monitor_pids(session_id, present=False, timeout=5) + finally: + if owner is not None and owner.poll() is None: + owner.kill() + if monitor is not None and monitor.poll() is None: + monitor.kill() + for pid in monitor_pids_for_session(session_id): + subprocess.run(["/bin/kill", str(pid)], check=False) def test_codex_monitor_rejects_invalid_owner_pid(cli_path: str, root: Path) -> None: - socket_path = root / "cmux-monitor-invalid-owner-pid.sock" - transcript_path = root / "codex-session-invalid-owner-pid.jsonl" - transcript_path.write_text("", encoding="utf-8") - - session_id = f"codex-monitor-invalid-owner-pid-session-{os.getpid()}" - env = os.environ.copy() - env["CMUX_SOCKET_PATH"] = str(socket_path) - env["CMUX_WORKSPACE_ID"] = FAKE_WORKSPACE_ID - env["CMUX_CODEX_MONITOR_UNRESOLVED_TRANSCRIPT_TIMEOUT_SECONDS"] = "30" - - with FakeCmuxSocket( - socket_path, - None, - surfaces=[{"id": FAKE_SURFACE_ID, "ref": FAKE_SURFACE_ID}], - ) as fake: - result = subprocess.run( - [ - cli_path, - "--socket", - str(socket_path), - "hooks", - "codex", - "monitor", - "--workspace", - FAKE_WORKSPACE_ID, - "--session", - session_id, - "--surface", - FAKE_SURFACE_ID, - "--owner-pid", - "1", - "--transcript", - str(transcript_path), - ], - capture_output=True, - text=True, - check=False, - env=env, - timeout=3, - ) - if result.returncode == 0: - raise AssertionError( - "hooks codex monitor accepted invalid --owner-pid\n" - f"stdout={result.stdout}\nstderr={result.stderr}" - ) - if any(frame.get("method") == "surface.list" for frame in fake.frames): - raise AssertionError(f"invalid owner pid should exit before owner RPC: {fake.frames!r}") + for raw_owner_pid in ("1", "0", "-1", "abc"): + safe_owner_pid = raw_owner_pid.replace("-", "minus") + socket_path = root / f"cmux-monitor-invalid-owner-pid-{safe_owner_pid}.sock" + transcript_path = root / f"codex-session-invalid-owner-pid-{safe_owner_pid}.jsonl" + transcript_path.write_text("", encoding="utf-8") + + session_id = f"codex-monitor-invalid-owner-pid-{safe_owner_pid}-session-{os.getpid()}" + env = os.environ.copy() + env["CMUX_SOCKET_PATH"] = str(socket_path) + env["CMUX_WORKSPACE_ID"] = FAKE_WORKSPACE_ID + env["CMUX_CODEX_MONITOR_UNRESOLVED_TRANSCRIPT_TIMEOUT_SECONDS"] = "30" + + with FakeCmuxSocket( + socket_path, + None, + surfaces=[{"id": FAKE_SURFACE_ID, "ref": FAKE_SURFACE_ID}], + ) as fake: + try: + result = subprocess.run( + [ + cli_path, + "--socket", + str(socket_path), + "hooks", + "codex", + "monitor", + "--workspace", + FAKE_WORKSPACE_ID, + "--session", + session_id, + "--surface", + FAKE_SURFACE_ID, + "--owner-pid", + raw_owner_pid, + "--transcript", + str(transcript_path), + ], + capture_output=True, + text=True, + check=False, + env=env, + timeout=3, + ) + except subprocess.TimeoutExpired as exc: + raise AssertionError( + "hooks codex monitor timed out; likely still looping when " + f"invalid --owner-pid={raw_owner_pid!r} was passed" + ) from exc + if result.returncode == 0: + raise AssertionError( + f"hooks codex monitor accepted invalid --owner-pid={raw_owner_pid!r}\n" + f"stdout={result.stdout}\nstderr={result.stderr}" + ) + if any(frame.get("method") == "surface.list" for frame in fake.frames): + raise AssertionError( + f"invalid owner pid {raw_owner_pid!r} should exit before owner RPC: {fake.frames!r}" + ) def test_codex_monitor_survives_transient_owner_rpc_timeout(cli_path: str, root: Path) -> None: From 4499c0046fc43aa466a099b37488894d6c43e731 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 07:11:34 -0700 Subject: [PATCH 08/15] Run Codex feed hook regression in CI --- .circleci/config.yml | 1 + .github/workflows/ci.yml | 1 + 2 files changed, 2 insertions(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index c5efc1e45057..bebd33debfa1 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -226,6 +226,7 @@ jobs: CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_cli_contract_help.py CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_cli_layout_focus_contract.py CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_cli_socket_operation_deadline.py + CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_codex_feed_hooks.py CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_claude_hook_clear_running_status.py - save-swift-package-cache: prefix: unit diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d56a723ceebe..f17e40ab0f19 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -318,6 +318,7 @@ jobs: CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_cli_contract_help.py CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_cli_layout_focus_contract.py CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_cli_socket_operation_deadline.py + CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_codex_feed_hooks.py python3 tests/test_claude_wrapper_hooks.py CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_claude_hook_stop_last_assistant.py CMUX_CLI_BIN="$CLI_BIN" python3 tests/test_claude_hook_clear_running_status.py From 15f3f16f9e736f70ec5799a62fa893773200b909 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 07:25:00 -0700 Subject: [PATCH 09/15] Shorten Codex feed hook test sockets --- tests/test_codex_feed_hooks.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_codex_feed_hooks.py b/tests/test_codex_feed_hooks.py index 8507c675cd1d..930bdcb7df88 100644 --- a/tests/test_codex_feed_hooks.py +++ b/tests/test_codex_feed_hooks.py @@ -1748,7 +1748,7 @@ def main() -> int: print(f"FAIL: {exc}") return 1 - with tempfile.TemporaryDirectory(prefix="cmux-codex-feed-hooks-") as td: + with tempfile.TemporaryDirectory(prefix="cfh-", dir="/tmp") as td: root = Path(td) try: test_codex_stop_reaps_transcript_monitor(cli_path, root) From 522073f63bde75265689d088294baddbd5688169 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 07:27:27 -0700 Subject: [PATCH 10/15] Flush sidebar telemetry before log reads --- Sources/TerminalController.swift | 2 + Sources/TerminalNotificationQueue.swift | 21 +++++--- .../TerminalNotificationQueueTests.swift | 49 +++++++++++++++++++ 3 files changed, 64 insertions(+), 8 deletions(-) diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 65f2031a0584..a279c565e715 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -16913,6 +16913,7 @@ class TerminalController { private func clearLog(_ args: String) -> String { var result = "OK" v2MainSync { + TerminalMutationBus.shared.drainPendingMutationsSynchronously() guard let tab = resolveTabForReport(args) else { result = "ERROR: Tab not found" return @@ -16937,6 +16938,7 @@ class TerminalController { var result = "" v2MainSync { + TerminalMutationBus.shared.drainPendingMutationsSynchronously() guard let tab = resolveTabForReport(args) else { result = parsed.options["tab"] != nil ? "ERROR: Tab not found" : "ERROR: No tab selected" return diff --git a/Sources/TerminalNotificationQueue.swift b/Sources/TerminalNotificationQueue.swift index 7557c86e2232..33ae5e0cf17e 100644 --- a/Sources/TerminalNotificationQueue.swift +++ b/Sources/TerminalNotificationQueue.swift @@ -205,6 +205,18 @@ final class TerminalMutationBus: @unchecked Sendable { } } + @MainActor + func drainPendingMutationsSynchronously() { + while true { + let batch = takeNextBatch() + guard !batch.isEmpty else { + markDrainCompleteIfEmpty() + return + } + perform(batch) + } + } + #if DEBUG nonisolated func setDrainsSuspendedForTesting(_ suspended: Bool) { let shouldScheduleDrain: Bool @@ -220,14 +232,7 @@ final class TerminalMutationBus: @unchecked Sendable { @MainActor func drainForTesting() { - while true { - let batch = takeNextBatch() - guard !batch.isEmpty else { - markDrainCompleteIfEmpty() - return - } - perform(batch) - } + drainPendingMutationsSynchronously() } #endif diff --git a/cmuxTests/TerminalNotificationQueueTests.swift b/cmuxTests/TerminalNotificationQueueTests.swift index e588ad40a26e..18da099c6acb 100644 --- a/cmuxTests/TerminalNotificationQueueTests.swift +++ b/cmuxTests/TerminalNotificationQueueTests.swift @@ -141,6 +141,55 @@ final class TerminalNotificationQueueTests: XCTestCase { XCTAssertEqual(deliveredTitles, []) } + func testLogReadAndClearFlushPendingSidebarMutations() async throws { + let socketPath = makeSocketPath("log-order") + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = appDelegate.tabManager ?? TabManager() + + let originalTabManager = appDelegate.tabManager + appDelegate.tabManager = manager + let workspace = manager.addWorkspace(select: true) + TerminalMutationBus.shared.setDrainsSuspendedForTesting(true) + defer { + TerminalMutationBus.shared.setDrainsSuspendedForTesting(false) + TerminalMutationBus.shared.drainForTesting() + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + appDelegate.tabManager = originalTabManager + } + + TerminalController.shared.start( + tabManager: manager, + socketPath: socketPath, + accessMode: .allowAll + ) + try waitForSocket(at: socketPath) + + let tabArg = workspace.id.uuidString + let responses = try await withCheckedThrowingContinuation { continuation in + DispatchQueue.global(qos: .userInitiated).async { + do { + continuation.resume(returning: try self.sendCommands([ + "log --tab=\(tabArg) -- queued entry", + "list_log --tab=\(tabArg)", + "clear_log --tab=\(tabArg)", + "list_log --tab=\(tabArg)", + ], to: socketPath)) + } catch { + continuation.resume(throwing: error) + } + } + } + + XCTAssertEqual(responses, [ + "OK", + "[info] queued entry", + "OK", + "No log entries", + ]) + } + func testClearNotificationsIsBoundaryForFreshNotify() async throws { let store = TerminalNotificationStore.shared let appDelegate = AppDelegate.shared ?? AppDelegate() From bbbf10d3d644e9da40460ff8bf3d2bd9cd783660 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 13:41:29 -0700 Subject: [PATCH 11/15] Remove Codex monitor semaphore wait --- CLI/cmux.swift | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 1db4e52e2343..32a60f7074e5 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -1886,6 +1886,28 @@ struct CMUXCLI { private static let vmCreateResponseTimeoutSeconds: TimeInterval = 16 * 60 private static let vmAttachResponseTimeoutSeconds: TimeInterval = 16 * 60 + private final class CodexTranscriptChangeWaiter: @unchecked Sendable { + private let condition = NSCondition() + private var didObserveChange = false + + func signal() { + condition.lock() + didObserveChange = true + condition.signal() + condition.unlock() + } + + func wait(until deadline: Date) { + condition.lock() + while !didObserveChange, Date() < deadline { + if !condition.wait(until: deadline) { + break + } + } + condition.unlock() + } + } + private func captureSocketTransportError(telemetry: CLISocketSentryTelemetry, stage: String, error: Error, client: SocketClient) { if client.hasUnfinishedOperationTelemetry() { telemetry.captureError(stage: stage, error: error, data: client.operationTelemetryContext()) @@ -18630,7 +18652,8 @@ struct CMUXCLI { private func waitForCodexTranscriptChange(path: String?, leasePath: String?, timeout: TimeInterval) { guard timeout > 0 else { return } - let semaphore = DispatchSemaphore(value: 0) + let waiter = CodexTranscriptChangeWaiter() + let deadline = Date().addingTimeInterval(timeout) var sources: [DispatchSourceFileSystemObject] = [] func addFileSource(path: String?, eventMask: DispatchSource.FileSystemEvent) { @@ -18644,7 +18667,7 @@ struct CMUXCLI { queue: DispatchQueue.global(qos: .utility) ) source.setEventHandler { - semaphore.signal() + waiter.signal() } source.setCancelHandler { close(fd) @@ -18657,11 +18680,11 @@ struct CMUXCLI { addFileSource(path: leasePath, eventMask: [.write, .delete, .rename]) guard !sources.isEmpty else { - _ = DispatchSemaphore(value: 0).wait(timeout: .now() + timeout) + waiter.wait(until: deadline) return } - _ = semaphore.wait(timeout: .now() + timeout) + waiter.wait(until: deadline) sources.forEach { $0.cancel() } } From 7bf16690ef1042db8cb85ad8ef58ef08fd30c600 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 19 May 2026 06:50:31 -0700 Subject: [PATCH 12/15] fix: localize codex owner pid error --- Resources/Localizable.xcstrings | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 3ff037b10379..46ff42c058aa 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -2,7 +2,7 @@ "sourceLanguage": "en", "version": "1.0", "strings": { - "cli.error.codexMonitorInvalidOwnerPID": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid must be an integer greater than 1" } }, "ja": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid には 1 より大きい整数を指定してください" } } } }, + "cli.error.codexMonitorInvalidOwnerPID": { "extractionState": "manual", "localizations": { "ar": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: يجب أن تكون --owner-pid عددًا صحيحًا أكبر من 1" } }, "bs": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid mora biti cijeli broj veći od 1" } }, "da": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid skal være et heltal større end 1" } }, "de": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid muss eine ganze Zahl größer als 1 sein" } }, "en": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid must be an integer greater than 1" } }, "es": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid debe ser un entero mayor que 1" } }, "fr": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid doit être un entier supérieur à 1" } }, "it": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid deve essere un numero intero maggiore di 1" } }, "ja": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid には 1 より大きい整数を指定してください" } }, "ko": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid는 1보다 큰 정수여야 합니다" } }, "nb": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid må være et heltall større enn 1" } }, "pl": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid musi być liczbą całkowitą większą niż 1" } }, "pt-BR": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid deve ser um inteiro maior que 1" } }, "ru": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid должен быть целым числом больше 1" } }, "th": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid ต้องเป็นจำนวนเต็มที่มากกว่า 1" } }, "tr": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid 1'den büyük bir tam sayı olmalıdır" } }, "uk": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid має бути цілим числом більше 1" } }, "zh-Hans": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid 必须是大于 1 的整数" } }, "zh-Hant": { "stringUnit": { "state": "translated", "value": "hooks codex monitor: --owner-pid 必須是大於 1 的整數" } } } }, "cli.hooks.error.configDirectoryIsFile": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", "value": "cmux could not create the hooks directory: a file exists at %@; remove or rename the conflicting file and re-run `cmux hooks setup`" } }, "ja": { "stringUnit": { "state": "translated", "value": "cmux は hooks ディレクトリを作成できませんでした: %@ にファイルがあります。競合するファイルを削除または名前変更してから `cmux hooks setup` を再実行してください" } } } }, "cli.error.dismissNotificationSelector": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", "value": "dismiss-notification requires exactly one of --id or --all-read" } }, "ja": { "stringUnit": { "state": "translated", "value": "dismiss-notification には --id または --all-read のどちらか一方だけを指定してください" } } } }, "cli.error.markNotificationReadSelector": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", "value": "mark-notification-read requires exactly one selector: --id, --workspace, or --all" } }, "ja": { "stringUnit": { "state": "translated", "value": "mark-notification-read には --id、--workspace、--all のいずれか一つだけを指定してください" } } } }, From b7debc8be07949ed3b9e61ce38e973a9db1917fd Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 19 May 2026 11:30:18 -0700 Subject: [PATCH 13/15] fix: align codex hook regression expectations --- tests/test_codex_feed_hooks.py | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/tests/test_codex_feed_hooks.py b/tests/test_codex_feed_hooks.py index effc7656844d..55804afe24ef 100644 --- a/tests/test_codex_feed_hooks.py +++ b/tests/test_codex_feed_hooks.py @@ -698,19 +698,28 @@ def codex_command_hook_hash( return f"sha256:{hashlib.sha256(canonical).hexdigest()}" -def cmux_codex_hook_command(subcommand: str) -> str: +def cmux_codex_shell_command(routed_command: str) -> str: return ( - '[ -n "$CMUX_SURFACE_ID" ] && [ "$CMUX_CODEX_HOOKS_DISABLED" != "1" ] ' - f"&& command -v cmux >/dev/null 2>&1 && cmux hooks codex {subcommand} || echo '{{}}'" + 'cmux_cli="${CMUX_BUNDLED_CLI_PATH:-}"; ' + 'if [ -z "$cmux_cli" ] || [ ! -x "$cmux_cli" ]; then ' + 'cmux_cli="$(command -v cmux 2>/dev/null || true)"; ' + 'fi; ' + 'if [ -n "$CMUX_SURFACE_ID" ] && [ "$CMUX_CODEX_HOOKS_DISABLED" != "1" ] && [ -n "$cmux_cli" ]; then ' + '{ if [ -n "${CMUX_SOCKET_PATH:-}" ]; then ' + f'"$cmux_cli" --socket "$CMUX_SOCKET_PATH" {routed_command}; ' + "else " + f'"$cmux_cli" {routed_command}; ' + "fi; } || echo '{}'; " + "else echo '{}'; fi" ) +def cmux_codex_hook_command(subcommand: str) -> str: + return cmux_codex_shell_command(f"hooks codex {subcommand}") + + def cmux_codex_feed_command(agent_event: str) -> str: - return ( - '[ -n "$CMUX_SURFACE_ID" ] && [ "$CMUX_CODEX_HOOKS_DISABLED" != "1" ] ' - f"&& command -v cmux >/dev/null 2>&1 && cmux hooks feed --source codex --event {agent_event} " - "|| echo '{}'" - ) + return cmux_codex_shell_command(f"hooks feed --source codex --event {agent_event}") def is_cmux_codex_hook_command(command: str) -> bool: @@ -848,7 +857,7 @@ def test_install_adds_codex_permission_request_hook(cli_path: str, root: Path) - if not groups: raise AssertionError(f"missing {event_name} hook group: {hooks!r}") command = groups[-1]["hooks"][0]["command"] - if f"cmux hooks feed --source codex --event {event_name}" not in command: + if command != cmux_codex_feed_command(event_name): raise AssertionError(f"wrong {event_name} feed command: {command!r}") if groups[-1]["hooks"][0].get("timeout") != 120_000: raise AssertionError(f"wrong {event_name} timeout: {groups[-1]!r}") @@ -946,7 +955,7 @@ def test_install_preserves_codex_hook_position_with_third_party_hooks(cli_path: groups = hooks["hooks"]["PreToolUse"] first_command = groups[0]["hooks"][0]["command"] second_command = groups[1]["hooks"][0]["command"] - if "cmux hooks feed --source codex --event PreToolUse" not in first_command: + if first_command != cmux_codex_feed_command("PreToolUse"): raise AssertionError(f"cmux hook did not keep its existing position: {groups!r}") if second_command != orca_hook: raise AssertionError(f"third-party hook was not preserved after cmux hook: {groups!r}") From 5dd934e0dacdc557087968d289bd774dd58824a0 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 19 May 2026 11:47:55 -0700 Subject: [PATCH 14/15] fix: expect codex hook dedupe in regression --- tests/test_codex_feed_hooks.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tests/test_codex_feed_hooks.py b/tests/test_codex_feed_hooks.py index 55804afe24ef..d9c38878c01f 100644 --- a/tests/test_codex_feed_hooks.py +++ b/tests/test_codex_feed_hooks.py @@ -961,7 +961,7 @@ def test_install_preserves_codex_hook_position_with_third_party_hooks(cli_path: raise AssertionError(f"third-party hook was not preserved after cmux hook: {groups!r}") -def test_install_preserves_each_codex_hook_position_with_interleaved_third_party_hooks( +def test_install_preserves_first_codex_hook_position_with_interleaved_third_party_hooks( cli_path: str, root: Path ) -> None: codex_home = root / "codex-home-interleaved" @@ -1009,11 +1009,10 @@ def test_install_preserves_each_codex_hook_position_with_interleaved_third_party user_hook_before, cmux_pre_tool, user_hook_middle, - cmux_pre_tool, user_hook_after, ] if commands != expected: - raise AssertionError(f"interleaved cmux hook positions changed: {commands!r}") + raise AssertionError(f"interleaved cmux hook position or user hook order changed: {commands!r}") def test_install_collapses_consecutive_codex_hook_positions(cli_path: str, root: Path) -> None: @@ -2211,7 +2210,7 @@ def main() -> int: test_install_adds_codex_permission_request_hook(cli_path, root) test_install_escapes_codex_hook_trust_state_keys(cli_path, root) test_install_preserves_codex_hook_position_with_third_party_hooks(cli_path, root) - test_install_preserves_each_codex_hook_position_with_interleaved_third_party_hooks(cli_path, root) + test_install_preserves_first_codex_hook_position_with_interleaved_third_party_hooks(cli_path, root) test_install_collapses_consecutive_codex_hook_positions(cli_path, root) test_install_replaces_legacy_codex_hook_commands(cli_path, root) test_install_migrates_legacy_codex_hooks_feature(cli_path, root) From b70f60c9bb2521f7243410413026cb4b147a046c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 21 May 2026 19:39:51 -0700 Subject: [PATCH 15/15] Stabilize CLI version memory guard --- tests/test_cli_version_memory_guard.py | 41 ++++++++++++++++---------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/tests/test_cli_version_memory_guard.py b/tests/test_cli_version_memory_guard.py index 46d1497ebfd8..c2fa7c50b1f1 100644 --- a/tests/test_cli_version_memory_guard.py +++ b/tests/test_cli_version_memory_guard.py @@ -9,14 +9,14 @@ import glob import os import plistlib -import re +import resource import shutil +import signal import subprocess import tempfile import time -JUNK_APP_COUNT = 40000 RSS_LIMIT_KB = 64 * 1024 TIMEOUT_SECONDS = 10.0 EXPECTED_STDOUT = "cmux 9.9.9 (999)" @@ -84,31 +84,46 @@ def build_fixture(root: str, cli_path: str) -> str: with open(os.path.join(contents_path, "Info.plist"), "wb") as handle: plistlib.dump(info, handle) - # Regular files are enough here because the fallback scan keys off the - # ".app" suffix before it ever tries to inspect bundle contents. - for index in range(JUNK_APP_COUNT): - open(os.path.join(resources_path, f"junk-{index:05d}.app"), "wb").close() + # A sibling app's Info.plist should never be opened after the enclosing + # bundle Info.plist is found. The FIFO turns that regression into a timeout + # without creating tens of thousands of filesystem entries in CI. + trap_info = os.path.join(resources_path, "trap.app", "Contents", "Info.plist") + os.makedirs(os.path.dirname(trap_info), exist_ok=True) + os.mkfifo(trap_info) return fixture_cli +def kill_process_group(proc: subprocess.Popen[str]) -> None: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + return + + +def max_child_rss_kb() -> int: + peak_rss_raw = int(resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss) + return peak_rss_raw if peak_rss_raw <= RSS_LIMIT_KB * 16 else peak_rss_raw // 1024 + + def run_with_limits(cli_path: str, *args: str) -> dict[str, object]: env = dict(os.environ) env.pop("CMUX_COMMIT", None) proc = subprocess.Popen( - ["/usr/bin/time", "-l", cli_path, *args], + [cli_path, *args], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env, + start_new_session=True, ) started = time.time() try: stdout, stderr = proc.communicate(timeout=TIMEOUT_SECONDS) except subprocess.TimeoutExpired: - proc.kill() + kill_process_group(proc) stdout, stderr = proc.communicate() elapsed = time.time() - started return { @@ -116,16 +131,12 @@ def run_with_limits(cli_path: str, *args: str) -> dict[str, object]: "stdout": stdout.strip(), "stderr": stderr.strip(), "elapsed": elapsed, - "peak_rss_kb": 0, + "peak_rss_kb": max_child_rss_kb(), "failure_reason": f"timeout exceeded ({elapsed:.2f}s > {TIMEOUT_SECONDS:.2f}s)", } elapsed = time.time() - started - peak_rss_kb = 0 - rss_match = re.search(r"(\d+)\s+maximum resident set size", stderr) - if rss_match: - peak_rss_raw = int(rss_match.group(1)) - peak_rss_kb = peak_rss_raw if peak_rss_raw <= RSS_LIMIT_KB * 16 else peak_rss_raw // 1024 + peak_rss_kb = max_child_rss_kb() failure_reason: str | None = None if peak_rss_kb > RSS_LIMIT_KB: @@ -150,7 +161,7 @@ def main() -> int: print(f"FAIL: {exc}") return 1 - with tempfile.TemporaryDirectory(prefix="cmux-version-memory-guard-") as root: + with tempfile.TemporaryDirectory(prefix="cmux-version-memory-guard-", dir="/tmp") as root: fixture_cli = build_fixture(root, cli_path) result = run_with_limits(fixture_cli, "--version")