Skip to content

Commit 1454a92

Browse files
committed
fix(macos): bound ocx CLI runs with timeout and concurrent pipe drain
Prevent hung or chatty ocx subprocesses from deadlocking the serial CLI queue by draining stdout/stderr while the process runs and terminating after a deadline.
1 parent fbc9c84 commit 1454a92

1 file changed

Lines changed: 32 additions & 2 deletions

File tree

‎apps/macos-menu-bar/Sources/OpenCodexMenuBarCore/OcxClient.swift‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ public final class OcxClient {
8181
return url
8282
}
8383

84+
private static let commandTimeout: TimeInterval = 15
85+
8486
private func run(_ executable: URL, arguments: [String]) throws -> String {
8587
let process = configuredProcess(executable, arguments: arguments)
8688
let output = Pipe()
@@ -89,10 +91,34 @@ public final class OcxClient {
8991
process.standardError = errors
9092
process.standardInput = FileHandle.nullDevice
9193

94+
let stdoutBox = DataBox()
95+
let stderrBox = DataBox()
96+
let group = DispatchGroup()
97+
98+
group.enter()
99+
DispatchQueue.global(qos: .utility).async {
100+
stdoutBox.data = output.fileHandleForReading.readDataToEndOfFile()
101+
group.leave()
102+
}
103+
group.enter()
104+
DispatchQueue.global(qos: .utility).async {
105+
stderrBox.data = errors.fileHandleForReading.readDataToEndOfFile()
106+
group.leave()
107+
}
108+
92109
try process.run()
110+
111+
let deadline = DispatchTime.now() + Self.commandTimeout
112+
let waitResult = group.wait(timeout: deadline)
113+
if waitResult == .timedOut || process.isRunning {
114+
process.terminate()
115+
_ = group.wait(timeout: .now() + 1)
116+
throw OcxClientError.commandFailed("ocx timed out after \(Int(Self.commandTimeout))s.")
117+
}
118+
93119
process.waitUntilExit()
94-
let stdout = output.fileHandleForReading.readDataToEndOfFile()
95-
let stderr = errors.fileHandleForReading.readDataToEndOfFile()
120+
let stdout = stdoutBox.data
121+
let stderr = stderrBox.data
96122
guard process.terminationStatus == 0 else {
97123
let raw = String(decoding: stderr.isEmpty ? stdout : stderr, as: UTF8.self)
98124
let message = raw.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -102,6 +128,10 @@ public final class OcxClient {
102128
return String(decoding: stdout, as: UTF8.self)
103129
}
104130

131+
private final class DataBox: @unchecked Sendable {
132+
var data = Data()
133+
}
134+
105135
private func launch(_ executable: URL, arguments: [String]) throws {
106136
let process = configuredProcess(executable, arguments: arguments)
107137
process.standardOutput = FileHandle.nullDevice

0 commit comments

Comments
 (0)