From 678e7ceca3c78dab79543f70e55f4c6a1c0548ef Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 15 Jul 2026 03:57:08 -0700 Subject: [PATCH 1/3] Add regression test for Codex terminal errors --- cmux.xcodeproj/project.pbxproj | 4 + .../CodexTerminalErrorNotificationTests.swift | 256 ++++++++++++++++++ 2 files changed, 260 insertions(+) create mode 100644 cmuxTests/CodexTerminalErrorNotificationTests.swift diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index c561cdbda1b5..f127859ced26 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -650,6 +650,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources A9E040000000000000000002 /* CodexAppServerSessionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9E040000000000000000001 /* CodexAppServerSessionTests.swift */; }; C0DECAFE0000000000000001 /* CodexTeamsApprovalBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DECAFE0000000000000002 /* CodexTeamsApprovalBridge.swift */; }; C0DECAFE0000000000000003 /* CodexTeamsApprovalBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DECAFE0000000000000002 /* CodexTeamsApprovalBridge.swift */; }; + C0DE7100C0DE7100C0DE7100 /* CodexTerminalErrorNotificationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE7101C0DE7101C0DE7101 /* CodexTerminalErrorNotificationTests.swift */; }; C4041001000000000000001B /* CommandClickFileOpenRouter.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4041001000000000000001A /* CommandClickFileOpenRouter.swift */; }; C0DEC0DE000000000000F302 /* CommandPaletteEmojiTitleSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DEC0DE000000000000F301 /* CommandPaletteEmojiTitleSearchTests.swift */; }; C0DE32470000000000000005 /* CommandPaletteIdentifierClipboardUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE32470000000000000006 /* CommandPaletteIdentifierClipboardUITests.swift */; }; @@ -2564,6 +2565,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A9E01000000000000000000E /* CodexAppServerSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/CodexAppServerSession.swift; sourceTree = ""; }; A9E040000000000000000001 /* CodexAppServerSessionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexAppServerSessionTests.swift; sourceTree = ""; }; C0DECAFE0000000000000002 /* CodexTeamsApprovalBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTeamsApprovalBridge.swift; sourceTree = ""; }; + C0DE7101C0DE7101C0DE7101 /* CodexTerminalErrorNotificationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTerminalErrorNotificationTests.swift; sourceTree = ""; }; C4041001000000000000001A /* CommandClickFileOpenRouter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandClickFileOpenRouter.swift; sourceTree = ""; }; C0DEC0DE000000000000F301 /* CommandPaletteEmojiTitleSearchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandPaletteEmojiTitleSearchTests.swift; sourceTree = ""; }; C0DE32470000000000000006 /* CommandPaletteIdentifierClipboardUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandPaletteIdentifierClipboardUITests.swift; sourceTree = ""; }; @@ -5444,6 +5446,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = F6001001A1B2C3D4E5F60718 /* ShortcutUnbindingTests.swift */, C73660030000000000000002 /* WorkspaceRemoteBadgeTruthTests.swift */, F6100001A1B2C3D4E5F60718 /* WorkspaceRemoteConnectionTests.swift */, + C0DE7101C0DE7101C0DE7101 /* CodexTerminalErrorNotificationTests.swift */, 7277B0017277B0017277B001 /* WorkspaceRemoteDirectoryProvenanceTests.swift */, F6357301A1B2C3D4E5F60718 /* WorkspaceRemoteReconnectPolicyTests.swift */, C77070000000000000000007 /* SSHPTYAttachExitCodeClassifierTests.swift */, @@ -7781,6 +7784,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A6AC72080000000000000001 /* CMUXWorkspaceLoadingCLIRegressionTests.swift in Sources */, A9E040000000000000000002 /* CodexAppServerSessionTests.swift in Sources */, C0DECAFE0000000000000003 /* CodexTeamsApprovalBridge.swift in Sources */, + C0DE7100C0DE7100C0DE7100 /* CodexTerminalErrorNotificationTests.swift in Sources */, C0DEC0DE000000000000F302 /* CommandPaletteEmojiTitleSearchTests.swift in Sources */, C0DEC0DE000000000000F202 /* CommandPaletteNucleoFFILibrarySupport.swift in Sources */, C0DEC0DE000000000000F102 /* CommandPaletteNucleoFFITests.swift in Sources */, diff --git a/cmuxTests/CodexTerminalErrorNotificationTests.swift b/cmuxTests/CodexTerminalErrorNotificationTests.swift new file mode 100644 index 000000000000..2f9e3b031105 --- /dev/null +++ b/cmuxTests/CodexTerminalErrorNotificationTests.swift @@ -0,0 +1,256 @@ +import Darwin +import Foundation +import Testing + +private final class CodexTerminalErrorBundleMarker: NSObject {} + +@Suite("Codex terminal error notifications", .serialized) +struct CodexTerminalErrorNotificationTests { + @Test("A persisted terminal error wins over partial assistant output") + func nestedTurnCompleteErrorNotifies() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-codex-terminal-error-\(UUID().uuidString)", isDirectory: true) + let socketPath = root.appendingPathComponent("cmux.sock").path + let transcriptURL = root.appendingPathComponent("rollout.jsonl") + let workspaceID = "11111111-1111-1111-1111-111111111111" + let surfaceID = "22222222-2222-2222-2222-222222222222" + let sessionID = "codex-session-terminal-error" + let turnID = "turn-terminal-error" + + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + + try """ + {"timestamp":"2026-07-15T07:55:29.462Z","type":"session_meta","payload":{"id":"\(sessionID)","cwd":"\(root.path)"}} + {"timestamp":"2026-07-15T07:55:29.500Z","type":"event_msg","payload":{"type":"task_started","turn_id":"\(turnID)","started_at":1784102129}} + {"timestamp":"2026-07-15T07:55:29.600Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Partial response"}]}} + {"timestamp":"2026-07-15T07:55:29.804Z","type":"event_msg","payload":{"type":"task_complete","turn_id":"\(turnID)","last_agent_message":"Partial response","error":{"message":"Selected model is at capacity. Please try a different model.","codex_error_info":"server_overloaded"}}} + """.write(to: transcriptURL, atomically: true, encoding: .utf8) + + let server = try CodexTerminalErrorSocketServer( + socketPath: socketPath, + surfaceID: surfaceID + ) + server.start() + defer { server.stop() } + + var environment = ProcessInfo.processInfo.environment + environment["CMUX_SOCKET_PATH"] = socketPath + environment["CMUX_WORKSPACE_ID"] = workspaceID + environment["CMUX_SURFACE_ID"] = surfaceID + environment["CMUX_AGENT_HOOK_STATE_DIR"] = root.path + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + + let hookInput = """ + {"session_id":"\(sessionID)","turn_id":"\(turnID)","transcript_path":"\(transcriptURL.path)","cwd":"\(root.path)","hook_event_name":"Stop","model":"gpt-5.5","permission_mode":"default","stop_hook_active":false,"last_assistant_message":"Partial response"} + """ + let cliPath = try BundledCLITestSupport.bundledCLIPath( + for: CodexTerminalErrorBundleMarker.self + ) + let result = CodexTerminalErrorProcess.run( + executablePath: cliPath, + arguments: ["hooks", "codex", "stop"], + environment: environment, + standardInput: hookInput, + timeout: 5 + ) + + #expect(!result.timedOut, "\(result.stderr)") + #expect(result.status == 0, "\(result.stderr)") + #expect( + server.commands.contains { command in + command.contains( + "notify_target \(workspaceID) \(surfaceID) Codex|Error|Selected model is at capacity. Please try a different model." + ) + }, + "Expected the nested terminal error to notify, saw \(server.commands)" + ) + #expect( + server.commands.contains { command in + command.contains("set_status codex Codex error") && + command.contains("--icon=exclamationmark.triangle.fill") && + command.contains("--color=#FF453A") && + command.contains("--priority=100") + }, + "Expected the nested terminal error to set error status, saw \(server.commands)" + ) + } +} + +private final class CodexTerminalErrorSocketServer: @unchecked Sendable { + private let listenerFD: Int32 + private let surfaceID: String + private let lock = NSLock() + private var recordedCommands: [String] = [] + private let finished = DispatchSemaphore(value: 0) + + var commands: [String] { + lock.withLock { recordedCommands } + } + + init(socketPath: String, surfaceID: String) throws { + unlink(socketPath) + let listenerFD = Darwin.socket(AF_UNIX, SOCK_STREAM, 0) + guard listenerFD >= 0 else { throw Self.posixError("socket") } + + var address = sockaddr_un() + address.sun_family = sa_family_t(AF_UNIX) + let maxPathLength = MemoryLayout.size(ofValue: address.sun_path) + socketPath.withCString { source in + withUnsafeMutablePointer(to: &address.sun_path) { destination in + strncpy( + UnsafeMutableRawPointer(destination).assumingMemoryBound(to: CChar.self), + source, + maxPathLength - 1 + ) + } + } + let bindResult = withUnsafePointer(to: &address) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { + Darwin.bind(listenerFD, $0, socklen_t(MemoryLayout.size)) + } + } + guard bindResult == 0, Darwin.listen(listenerFD, 1) == 0 else { + Darwin.close(listenerFD) + throw Self.posixError("bind/listen") + } + self.listenerFD = listenerFD + self.surfaceID = surfaceID + } + + func start() { + DispatchQueue.global(qos: .userInitiated).async { [self] in + defer { finished.signal() } + var address = sockaddr_un() + var addressLength = socklen_t(MemoryLayout.size) + let clientFD = withUnsafeMutablePointer(to: &address) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { + Darwin.accept(listenerFD, $0, &addressLength) + } + } + guard clientFD >= 0 else { return } + defer { Darwin.close(clientFD) } + + var pending = Data() + var buffer = [UInt8](repeating: 0, count: 4096) + while true { + let count = Darwin.read(clientFD, &buffer, buffer.count) + if count < 0 { + if errno == EINTR { continue } + return + } + if count == 0 { return } + pending.append(buffer, count: count) + + while let newline = pending.firstRange(of: Data([0x0A])) { + let lineData = pending.subdata(in: 0.. String { + guard let data = line.data(using: .utf8), + let payload = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let id = payload["id"] as? String else { + return "OK" + } + let response: [String: Any] = [ + "id": id, + "ok": true, + "result": ["surfaces": [["id": surfaceID, "ref": surfaceID, "focused": true]]], + ] + let responseData = try? JSONSerialization.data(withJSONObject: response) + return String(data: responseData ?? Data("{}".utf8), encoding: .utf8) ?? "{}" + } + + private static func writeAll(_ string: String, to fd: Int32) -> Bool { + let bytes = Array(string.utf8) + var offset = 0 + while offset < bytes.count { + let written = bytes.withUnsafeBytes { buffer in + Darwin.write(fd, buffer.baseAddress!.advanced(by: offset), bytes.count - offset) + } + if written > 0 { + offset += written + } else if written < 0, errno == EINTR { + continue + } else { + return false + } + } + return true + } + + private static func posixError(_ operation: String) -> NSError { + NSError( + domain: NSPOSIXErrorDomain, + code: Int(errno), + userInfo: [NSLocalizedDescriptionKey: "\(operation) failed: \(String(cString: strerror(errno)))"] + ) + } +} + +private enum CodexTerminalErrorProcess { + struct Result { + let status: Int32 + let stdout: String + let stderr: String + let timedOut: Bool + } + + static func run( + executablePath: String, + arguments: [String], + environment: [String: String], + standardInput: String, + timeout: TimeInterval + ) -> Result { + let process = Process() + let stdout = Pipe() + let stderr = Pipe() + let stdin = Pipe() + process.executableURL = URL(fileURLWithPath: executablePath) + process.arguments = arguments + process.environment = environment + process.standardInput = stdin + process.standardOutput = stdout + process.standardError = stderr + + do { + try process.run() + } catch { + return Result(status: -1, stdout: "", stderr: String(describing: error), timedOut: false) + } + stdin.fileHandleForWriting.write(Data(standardInput.utf8)) + try? stdin.fileHandleForWriting.close() + + let finished = DispatchSemaphore(value: 0) + DispatchQueue.global(qos: .userInitiated).async { + process.waitUntilExit() + finished.signal() + } + let timedOut = finished.wait(timeout: .now() + timeout) == .timedOut + if timedOut { + process.terminate() + _ = finished.wait(timeout: .now() + 1) + } + return Result( + status: process.terminationStatus, + stdout: String(data: stdout.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "", + stderr: String(data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "", + timedOut: timedOut + ) + } +} From cb1cae5f8af99386a5b9c669cdbabe739ff44111 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 15 Jul 2026 04:01:51 -0700 Subject: [PATCH 2/3] Notify on Codex terminal errors --- CLI/cmux.swift | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 35bf1f53cb6e..c44e8a797dfc 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -25873,7 +25873,25 @@ struct CMUXCLI { } sawRelevantTurn = true sawTerminalTurn = true - if let lastMessage = payload["last_agent_message"] as? String, + // Codex persists fatal turn failures inside task_complete.error. Standalone + // error events are transient, and a failed turn may still contain partial + // assistant output, so the terminal error must be authoritative. + if let terminalError = payload["error"] as? [String: Any], + let failure = codexHookFailureCandidate( + from: terminalError, + requireFailureSignal: false + ) { + candidate = failure + candidateCanPublishBeforeTerminal = false + } else if let terminalError = codexHookStringValue(payload["error"]) { + candidate = CodexHookFailureCandidate( + message: terminalError, + codexErrorInfo: nil, + additionalDetails: nil, + isStreamError: false + ) + candidateCanPublishBeforeTerminal = false + } else if let lastMessage = payload["last_agent_message"] as? String, !lastMessage.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { sawAssistantMessage = true candidate = nil From 2f871507f3468788a6074a538a41ce502e73893e Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 15 Jul 2026 15:00:16 -0700 Subject: [PATCH 3/3] Harden Codex error notification test --- .../CodexTerminalErrorNotificationTests.swift | 34 +++++++++++++++---- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/cmuxTests/CodexTerminalErrorNotificationTests.swift b/cmuxTests/CodexTerminalErrorNotificationTests.swift index 2f9e3b031105..8251def9b00c 100644 --- a/cmuxTests/CodexTerminalErrorNotificationTests.swift +++ b/cmuxTests/CodexTerminalErrorNotificationTests.swift @@ -8,9 +8,11 @@ private final class CodexTerminalErrorBundleMarker: NSObject {} struct CodexTerminalErrorNotificationTests { @Test("A persisted terminal error wins over partial assistant output") func nestedTurnCompleteErrorNotifies() throws { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("cmux-codex-terminal-error-\(UUID().uuidString)", isDirectory: true) - let socketPath = root.appendingPathComponent("cmux.sock").path + let root = URL( + fileURLWithPath: "/tmp/cmux-cterr-\(UUID().uuidString.prefix(8))", + isDirectory: true + ) + let socketPath = root.appendingPathComponent("c.sock").path let transcriptURL = root.appendingPathComponent("rollout.jsonl") let workspaceID = "11111111-1111-1111-1111-111111111111" let surfaceID = "22222222-2222-2222-2222-222222222222" @@ -47,7 +49,7 @@ struct CodexTerminalErrorNotificationTests { let cliPath = try BundledCLITestSupport.bundledCLIPath( for: CodexTerminalErrorBundleMarker.self ) - let result = CodexTerminalErrorProcess.run( + let result = CodexTerminalErrorProcess().run( executablePath: cliPath, arguments: ["hooks", "codex", "stop"], environment: environment, @@ -96,6 +98,14 @@ private final class CodexTerminalErrorSocketServer: @unchecked Sendable { var address = sockaddr_un() address.sun_family = sa_family_t(AF_UNIX) let maxPathLength = MemoryLayout.size(ofValue: address.sun_path) + guard socketPath.utf8.count < maxPathLength else { + Darwin.close(listenerFD) + throw NSError( + domain: NSPOSIXErrorDomain, + code: Int(ENAMETOOLONG), + userInfo: [NSLocalizedDescriptionKey: "Socket path exceeds sockaddr_un.sun_path: \(socketPath)"] + ) + } socketPath.withCString { source in withUnsafeMutablePointer(to: &address.sun_path) { destination in strncpy( @@ -202,7 +212,7 @@ private final class CodexTerminalErrorSocketServer: @unchecked Sendable { } } -private enum CodexTerminalErrorProcess { +private struct CodexTerminalErrorProcess { struct Result { let status: Int32 let stdout: String @@ -210,7 +220,7 @@ private enum CodexTerminalErrorProcess { let timedOut: Bool } - static func run( + func run( executablePath: String, arguments: [String], environment: [String: String], @@ -244,7 +254,17 @@ private enum CodexTerminalErrorProcess { let timedOut = finished.wait(timeout: .now() + timeout) == .timedOut if timedOut { process.terminate() - _ = finished.wait(timeout: .now() + 1) + if finished.wait(timeout: .now() + 1) == .timedOut { + Darwin.kill(process.processIdentifier, SIGKILL) + guard finished.wait(timeout: .now() + 1) == .success else { + return Result( + status: -1, + stdout: "", + stderr: "Process did not terminate after timeout", + timedOut: true + ) + } + } } return Result( status: process.terminationStatus,