CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
refactor: 统一外部命令执行与资源清理
Bob501dc1031972
diff --git a/CodexBar/Controllers/CodexBarAppDelegate.swift b/CodexBar/Controllers/CodexBarAppDelegate.swiftindex 63bfbee..ea7ba18 100644--- a/CodexBar/Controllers/CodexBarAppDelegate.swift+++ b/CodexBar/Controllers/CodexBarAppDelegate.swift@@ -5,6 +5,7 @@ import os@MainActorfinal class CodexBarAppDelegate: NSObject, NSApplicationDelegate {private let codexStatusService = CodexStatusService()+ private lazy var appServerStartup = AppServerStartup()lazy var viewModel = CodexStatusViewModel(service: codexStatusService)let historyViewModel = HistoryViewModel()lazy var tuiNotificationSettings = TUINotificationSettings(@@ -96,10 +97,10 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {self.taskGlowController = taskGlowControllerkeepAliveController.start()logLaunchState()- startupTask = Task { [weak self] in+ startupTask = Task { [weak self, startup = appServerStartup] invar startupError: String?do {- try await AppServerStartup().ensureStarted()+ try await startup.ensureStarted()} catch is CancellationError {return} catch {diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstringsindex 30bdc4a..541425a 100644--- a/CodexBar/Resources/Localizable.xcstrings+++ b/CodexBar/Resources/Localizable.xcstrings@@ -3980,7 +3980,7 @@"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 后台服务"+ "value" : "Codex Daemon"}}}diff --git a/CodexBar/Services/AppServer/AppServerStartup.swift b/CodexBar/Services/AppServer/AppServerStartup.swiftindex cd503b6..f9f4cba 100644--- a/CodexBar/Services/AppServer/AppServerStartup.swift+++ b/CodexBar/Services/AppServer/AppServerStartup.swift@@ -8,6 +8,8 @@ actor AppServerStartup {private let probeConnection: @Sendable () throws -> Voidprivate let commandTimeout: TimeIntervalprivate let readinessAttempts: Int+ private var isStarting = false+ private var unfinishedProcess: Process?init(socketURL: URL = AppServerActivityReader.defaultSocketURL,@@ -29,6 +31,11 @@ actor AppServerStartup {func ensureStarted() async throws {try Task.checkCancellation()+ // 异步命令执行期间允许 actor 重入, 但不能重叠启动命令+ guard !isStarting, unfinishedProcess?.isRunning != true else { throw StartupError.notReady }+ unfinishedProcess = nil+ isStarting = true+ defer { isStarting = false }do {try probeConnection()AppLog.codex.notice("Codex 后台服务已就绪: source=existing")@@ -37,7 +44,7 @@ actor AppServerStartup {// 只有明确缺少监听者才启动, 权限或协议错误不改变服务状态}- let executable = try supportedExecutable()+ let executable = try await supportedExecutable()try Task.checkCancellation()// 能力检测期间其他客户端可能已经启动服务do {@@ -46,12 +53,13 @@ actor AppServerStartup {} catch let error as AppServerConnectionError where error.serverIsAbsent {}AppLog.codex.notice("Codex 后台服务启动请求已发送")- let result = BoundedProcess.run(+ let result = await BoundedProcess.runAsync(executable: executable,arguments: ["app-server", "daemon", "start"],timeout: commandTimeout,environment: environment)+ unfinishedProcess = result.runningProcesstry Task.checkCancellation()// 命令失败也探测一次, 允许与其他客户端并发启动后复用已就绪的服务for attempt in 0 ..< readinessAttempts {@@ -70,7 +78,7 @@ actor AppServerStartup {}}- private func supportedExecutable() throws -> URL {+ private func supportedExecutable() async throws -> URL {let installations = installations ?? CodexPaths.resolveInstallations(environment: environment)let paths = [installations.globalPath, installations.bundledPath].compactMap(\.self)guard !paths.isEmpty else { throw StartupError.notInstalled }@@ -78,13 +86,15 @@ actor AppServerStartup {for path in paths where checked.insert(CodexPaths.canonicalPath(path)).inserted {try Task.checkCancellation()let executable = URL(fileURLWithPath: path)- let result = BoundedProcess.run(+ let result = await BoundedProcess.runAsync(executable: executable,arguments: ["app-server", "daemon", "start", "--help"],timeout: 2.5,environment: environment)+ unfinishedProcess = result.runningProcesstry Task.checkCancellation()+ guard result.runningProcess == nil else { throw StartupError.notReady }if result.exitCode == 0, result.output.contains("daemon start") {return executable}diff --git a/CodexBar/Services/Codex/CodexVersionService.swift b/CodexBar/Services/Codex/CodexVersionService.swiftindex 934b3d6..2fadcd5 100644--- a/CodexBar/Services/Codex/CodexVersionService.swift+++ b/CodexBar/Services/Codex/CodexVersionService.swift@@ -47,33 +47,31 @@ nonisolated struct CodexVersionItem: Equatable, Identifiable {/// 并发检测 Codex CLI 与 Codex App 内置 CLI 的磁盘版本actor CodexVersionService {private let timeout: TimeInterval- private static let pipeDrainTimeout: TimeInterval = 0.25- private static let maxPipeOutputBytes = 64 * 1024+ private let environment: [String: String]?+ private let installations: CodexInstallations?+ private var activeSources = Set<CodexExecutableSource>()+ private var unfinishedProcesses: [CodexExecutableSource: Process] = [:]- init(timeout: TimeInterval = 5) {+ init(timeout: TimeInterval = 5, environment: [String: String]? = nil, installations: CodexInstallations? = nil) {self.timeout = timeout+ self.environment = environment+ self.installations = installations}func fetchSnapshot() async -> CodexVersionSnapshot {- await Self.fetchSnapshot(timeout: timeout)- }-- private static func fetchSnapshot(timeout: TimeInterval) async -> CodexVersionSnapshot {- let environment = CodexPaths.environment- let installations = CodexPaths.resolveInstallations(environment: environment)+ let environment = environment ?? CodexPaths.environment+ let installations = installations ?? CodexPaths.resolveInstallations(environment: environment)// 两个安装源互不依赖, 并发检测避免两个超时串行叠加async let global = probeVersion(source: .global,path: installations.globalPath,- environment: environment,- timeout: timeout+ environment: environment)async let bundled = probeVersion(source: .bundled,path: installations.bundledPath,- environment: environment,- timeout: timeout+ environment: environment)let (globalItem, bundledItem) = await (global, bundled)@@ -84,90 +82,58 @@ actor CodexVersionService {)}- private static func probeVersion(+ private func probeVersion(source: CodexExecutableSource,path: String?,- environment: [String: String],- timeout: TimeInterval+ environment: [String: String]) async -> CodexVersionItem {- guard let path else {- return CodexVersionItem(source: source)- }-- let deadline = Date().addingTimeInterval(timeout)- let process = Process()- process.executableURL = URL(fileURLWithPath: path)- process.arguments = ["--version"]- process.environment = environment-- let standardOutput = Pipe()- let standardError = Pipe()- let outputCollector = PipeReadBuffer(- fileHandle: standardOutput.fileHandleForReading,- maxBytes: Self.maxPipeOutputBytes- )- let errorCollector = PipeReadBuffer(- fileHandle: standardError.fileHandleForReading,- maxBytes: Self.maxPipeOutputBytes- )- let exitWaiter = ProcessExitWaiter()-- process.standardOutput = standardOutput- process.standardError = standardError- process.terminationHandler = { _ in- exitWaiter.finish(true)- }-- do {- try process.run()- } catch {- process.terminationHandler = nil- stopCollectors(outputCollector: outputCollector, errorCollector: errorCollector)- logVersionDetectionFailure(- source: source,- stage: "launch",- detail: error.localizedDescription- )- return failedVersionItem(source: source, path: path, failure: .launch)- }- defer {- process.terminationHandler = nil- }-- guard await exitWaiter.wait(timeout: max(0, deadline.timeIntervalSinceNow)) else {- terminateTimedOutProbe(- process: process,- outputCollector: outputCollector,- errorCollector: errorCollector- )- logVersionDetectionFailure(source: source, stage: "timeout")- return failedVersionItem(source: source, path: path, failure: .timeout)+ guard let path else { return CodexVersionItem(source: source) }+ // await 会让出 actor, 同一安装源的旧命令退出前不能再次启动+ guard !activeSources.contains(source), unfinishedProcesses[source]?.isRunning != true else {+ Self.logVersionDetectionFailure(source: source, stage: "busy")+ return Self.failedVersionItem(source: source, path: path, failure: .read)}-- let output = collectedText(from: outputCollector, deadline: deadline)- let errorOutput = collectedText(from: errorCollector, deadline: deadline)-- guard process.terminationStatus == 0 else {- logVersionDetectionFailure(- source: source,- stage: "exit",- exitCode: process.terminationStatus+ unfinishedProcesses[source] = nil+ activeSources.insert(source)+ defer { activeSources.remove(source) }+ let result = await BoundedProcess.runAsync(+ executable: URL(fileURLWithPath: path), arguments: ["--version"], timeout: timeout, environment: environment,+ configuration: .init(+ outputMode: .separate, gracefulTimeout: 0.2, killTimeout: 0.2,+ deadline: timeout.isFinite ? ContinuousClock.now.advanced(by: .seconds(max(0, timeout))) : nil)- return failedVersionItem(source: source, path: path, failure: .read)+ )+ unfinishedProcesses[source] = result.runningProcess+ switch result.completion {+ case .exited:+ guard result.exitCode == 0 else {+ Self.logVersionDetectionFailure(source: source, stage: "exit", exitCode: result.exitCode)+ return Self.failedVersionItem(source: source, path: path, failure: .read)+ }+ case let .launchFailed(detail):+ Self.logVersionDetectionFailure(source: source, stage: "launch", detail: detail)+ return Self.failedVersionItem(source: source, path: path, failure: .launch)+ case .timedOut:+ Self.logVersionDetectionFailure(source: source, stage: "timeout")+ return Self.failedVersionItem(source: source, path: path, failure: .timeout)+ case .cancelled:+ // 刷新协调器会丢弃取消结果, 不将主动取消记录为超时+ return Self.failedVersionItem(source: source, path: path, failure: .timeout)+ case .ioFailed, .invalidConfiguration:+ Self.logVersionDetectionFailure(source: source, stage: "read")+ return Self.failedVersionItem(source: source, path: path, failure: .read)}- guard let version = firstLine(in: output) ?? firstLine(in: errorOutput) else {- logVersionDetectionFailure(source: source, stage: "parse")- return failedVersionItem(source: source, path: path, failure: .parse)+ let output = String(data: result.standardOutput.data, encoding: .utf8) ?? ""+ let errorOutput = String(data: result.standardError.data, encoding: .utf8) ?? ""+ guard let version = Self.firstLine(in: output) ?? Self.firstLine(in: errorOutput) else {+ Self.logVersionDetectionFailure(source: source, stage: "parse")+ return Self.failedVersionItem(source: source, path: path, failure: .parse)}let displayVersion = CodexVersionReader.displayVersion(from: version)- logVersionDetectionCompleted(source: source, version: displayVersion)- return CodexVersionItem(- source: source,- path: path,- version: displayVersion- )+ Self.logVersionDetectionCompleted(source: source, version: displayVersion)+ return CodexVersionItem(source: source, path: path, version: displayVersion)}private static func logVersionDetectionFailure(@@ -201,19 +167,6 @@ actor CodexVersionService {AppLog.codex.notice("版本检测完成: \(details, privacy: .public)")}- private static func terminateTimedOutProbe(- process: Process,- outputCollector: PipeReadBuffer,- errorCollector: PipeReadBuffer- ) {- _ = ProcessTermination.terminate(- process,- gracefulTimeout: 0.2,- killTimeout: 0.2- )- stopCollectors(outputCollector: outputCollector, errorCollector: errorCollector)- }-private static func failedVersionItem(source: CodexExecutableSource,path: String,@@ -222,17 +175,6 @@ actor CodexVersionService {CodexVersionItem(source: source, path: path, errorMessage: failure.message)}- private static func stopCollectors(outputCollector: PipeReadBuffer, errorCollector: PipeReadBuffer) {- _ = outputCollector.stopAndRead()- _ = errorCollector.stopAndRead()- }-- private static func collectedText(from collector: PipeReadBuffer, deadline: Date) -> String {- let drainTimeout = min(Self.pipeDrainTimeout, max(0, deadline.timeIntervalSinceNow))- _ = collector.waitUntilClosed(timeout: drainTimeout)- return String(bytes: collector.stopAndRead(), encoding: .utf8) ?? ""- }-private static func firstLine(in text: String) -> String? {text.split(whereSeparator: \.isNewline)@@ -261,65 +203,6 @@ actor CodexVersionService {}}-/// 将 Process.terminationHandler 桥接成可超时等待的 async 结果-private final nonisolated class ProcessExitWaiter: Sendable {- private struct State {- var continuation: CheckedContinuation<Bool, Never>?- var result: Bool?- }-- private let state = OSAllocatedUnfairLock(initialState: State())-- func wait(timeout: TimeInterval) async -> Bool {- await withTaskCancellationHandler {- let timeoutTask = Task { [weak self] in- do {- try await Task.sleep(for: .seconds(max(0, timeout)))- } catch {- return- }-- self?.finish(false)- }- defer {- timeoutTask.cancel()- }-- return await withCheckedContinuation { continuation in- let immediateResult: Bool? = state.withLock {- if let result = $0.result {- return result- }-- $0.continuation = continuation- return nil- }-- if let immediateResult {- continuation.resume(returning: immediateResult)- }- }- } onCancel: {- finish(false)- }- }-- func finish(_ result: Bool) {- let continuation: CheckedContinuation<Bool, Never>? = state.withLock {- guard $0.result == nil else {- return nil- }-- $0.result = result- let continuation = $0.continuation- $0.continuation = nil- return continuation- }-- continuation?.resume(returning: result)- }-}-/// CodexBar 各能力依赖的 app-server 最低版本nonisolated enum CodexMinimumVersion {static let account = "0.157.0"diff --git a/CodexBar/Services/Codex/PipeReadBuffer.swift b/CodexBar/Services/Codex/PipeReadBuffer.swiftdeleted file mode 100644index a018b29..0000000--- a/CodexBar/Services/Codex/PipeReadBuffer.swift+++ /dev/null@@ -1,113 +0,0 @@-import Foundation--/// 底层 pipe 读取桥接了 FileHandle, DispatchSourceRead 和 semaphore-/// 这些非 Sendable 类型-/// 对外 Sendable 边界只保留在这里-/// 可变状态全部经由 lock 保护, 读事件固定在 readQueue 上执行-final nonisolated class PipeReadBuffer: @unchecked Sendable {- private let lock = NSLock()- private let closedSemaphore = DispatchSemaphore(value: 0)- private let fileHandle: FileHandle- private let readQueue: DispatchQueue- private let readQueueKey = DispatchSpecificKey<Void>()- private let readSource: DispatchSourceRead- private let maxBytes: Int- private var collectedData = Data()- private var closed = false- private var readSourceCancelled = false-- init(fileHandle: FileHandle, maxBytes: Int) {- self.fileHandle = fileHandle- self.maxBytes = max(maxBytes, 0)- readQueue = DispatchQueue(label: "CodexBar.pipe-read", qos: .userInitiated)- readSource = DispatchSource.makeReadSource(- fileDescriptor: fileHandle.fileDescriptor,- queue: readQueue- )-- readQueue.setSpecific(key: readQueueKey, value: ())- readSource.setEventHandler { [weak self] in- self?.readAvailableData()- }- readSource.resume()- }-- private func readAvailableData() {- let data = fileHandle.availableData- guard !data.isEmpty else {- cancelReadSourceIfNeeded()- markClosed()- return- }-- append(data)- }-- private func append(_ data: Data) {- withLock {- if maxBytes > 0, collectedData.count < maxBytes {- collectedData.append(data.prefix(maxBytes - collectedData.count))- }- }- }-- func waitUntilClosed(timeout: TimeInterval) -> Bool {- let isClosed = withLock { closed }-- guard !isClosed else {- return true- }-- return closedSemaphore.wait(timeout: .now() + max(0, timeout)) == .success- }-- func stopAndRead() -> Data {- cancelReadSourceIfNeeded()- waitForReadQueueToDrain()- try? fileHandle.close()-- let snapshot = withLock {- closed = true- return collectedData- }- closedSemaphore.signal()-- return snapshot- }-- private func cancelReadSourceIfNeeded() {- let shouldCancel = withLock {- guard !readSourceCancelled else {- return false- }-- readSourceCancelled = true- return true- }-- if shouldCancel {- readSource.cancel()- }- }-- private func waitForReadQueueToDrain() {- guard DispatchQueue.getSpecific(key: readQueueKey) == nil else {- return- }-- readQueue.sync {}- }-- private func markClosed() {- withLock {- closed = true- }- closedSemaphore.signal()- }-- private func withLock<T>(_ work: () -> T) -> T {- lock.lock()- defer { lock.unlock() }- return work()- }-}diff --git a/CodexBar/Services/Process/ProcessTermination.swift b/CodexBar/Services/Process/ProcessTermination.swiftdeleted file mode 100644index dd2b9c2..0000000--- a/CodexBar/Services/Process/ProcessTermination.swift+++ /dev/null@@ -1,46 +0,0 @@-import Darwin-import Foundation--/// 子进程关闭结果, 让调用方区分正常退出和强杀兜底-nonisolated enum ProcessTerminationResult: Equatable {- case alreadyExited- case terminated- case killed- case stillRunning-}--/// 先 terminate, 超时后 SIGKILL 的统一收口-nonisolated enum ProcessTermination {- private static let pollInterval: TimeInterval = 0.02-- static func terminate(- _ process: Process,- gracefulTimeout: TimeInterval,- killTimeout: TimeInterval- ) -> ProcessTerminationResult {- guard process.isRunning else {- return .alreadyExited- }-- process.terminate()- if waitUntilExit(process, timeout: gracefulTimeout) {- return .terminated- }-- kill(process.processIdentifier, SIGKILL)- if waitUntilExit(process, timeout: killTimeout) {- return .killed- }-- return .stillRunning- }-- private static func waitUntilExit(_ process: Process, timeout: TimeInterval) -> Bool {- let deadline = Date().addingTimeInterval(max(timeout, 0))- while process.isRunning, Date() < deadline {- Thread.sleep(forTimeInterval: pollInterval)- }-- return !process.isRunning- }-}diff --git a/CodexBarTests/AppServerStartupTests.swift b/CodexBarTests/AppServerStartupTests.swiftindex 9e8b7c1..6f589fd 100644--- a/CodexBarTests/AppServerStartupTests.swift+++ b/CodexBarTests/AppServerStartupTests.swift@@ -18,8 +18,8 @@ struct AppServerStartupTests {@Test func startsMissingServiceWithResolvedEnvironmentAndBundledFallback() async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let unsupported = try executable(in: directory, name: "old codex", body: "exit 2")- let supported = try executable(in: directory, body: """+ let unsupported = try directory.executable("exit 2", named: "old codex")+ let supported = try directory.executable("""printf '%s\\n' "$*" >> "$HOME/calls"if [ "$4" = '--help' ]; thenprintf 'Usage: codex app-server daemon start [OPTIONS]'@@ -28,7 +28,7 @@ struct AppServerStartupTests {elseexit 4fi- """)+ """, named: "fake codex")let server = try SharedServerFixture { _ in }defer { server.close() }let marker = directory.url.appendingPathComponent("started")@@ -79,7 +79,7 @@ struct AppServerStartupTests {@Test func reportsMissingAndUnsupportedInstallations() async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let unsupported = try executable(in: directory, body: "exit 2")+ let unsupported = try directory.executable("exit 2", named: "fake codex")for path in [nil, unsupported.path] {let startup = AppServerStartup(environment: [:], installations: CodexInstallations(globalPath: path, bundledPath: nil),@@ -102,14 +102,14 @@ struct AppServerStartupTests {func boundsFailedStartsAndReadinessRetries(_ body: String) async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let command = try executable(in: directory, body: """+ let command = try directory.executable("""if [ "$4" = '--help' ]; thenprintf 'Usage: codex app-server daemon start [OPTIONS]'exit 0fiprintf 'start\\n' >> "$HOME/calls"\(body)- """)+ """, named: "fake codex")let startup = AppServerStartup(environment: ["HOME": directory.url.path],installations: CodexInstallations(globalPath: command.path, bundledPath: nil),@@ -135,13 +135,13 @@ struct AppServerStartupTests {@Test func rechecksConnectionBeforeIssuingStart() async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let command = try executable(in: directory, body: """+ let command = try directory.executable("""if [ "$4" != '--help' ]; thenprintf 'unexpected start' > "$HOME/started"exit 1fiprintf 'Usage: codex app-server daemon start [OPTIONS]'- """)+ """, named: "fake codex")let probes = OSAllocatedUnfairLock(initialState: 0)let startup = AppServerStartup(environment: ["HOME": directory.url.path],@@ -160,6 +160,72 @@ struct AppServerStartupTests {#expect(!FileManager.default.fileExists(atPath: directory.url.appendingPathComponent("started").path))}+ @Test func reusesServiceEvenWhenTheStartCommandFails() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let command = try directory.executable("""+ if [ "$4" = '--help' ]; then printf 'daemon start'; exit 0; fi+ printf ready > "$PROCESS_TEST_DIR/started"+ exit 7+ """)+ let marker = directory.url.appendingPathComponent("started")+ let startup = AppServerStartup(+ environment: ["PROCESS_TEST_DIR": directory.url.path],+ installations: .init(globalPath: command.path, bundledPath: nil),+ probeConnection: {+ if !FileManager.default.fileExists(atPath: marker.path) {+ throw AppServerConnectionError(code: ENOENT)+ }+ }+ )+ try await startup.ensureStarted()+ #expect(FileManager.default.fileExists(atPath: marker.path))+ }++ @Test(arguments: ["help", "start"])+ func preventsOverlappingCommandsAndAllowsRetryAfterCancellation(_ stage: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let command = try directory.executable("""+ if [ -f "$PROCESS_TEST_DIR/retry" ]; then+ if [ "$4" = '--help' ]; then printf 'daemon start'+ else printf ready > "$PROCESS_TEST_DIR/started"; fi+ exit 0+ fi+ if [ "$4" = '--help' ] && [ "$PROCESS_TEST_STAGE" = 'start' ]; then printf 'daemon start'; exit 0; fi+ trap '' TERM+ printf blocked >> "$PROCESS_TEST_DIR/calls"+ printf ready > "$PROCESS_TEST_DIR/blocked"+ while :; do :; done+ """)+ let marker = directory.url.appendingPathComponent("started")+ let startup = AppServerStartup(+ environment: ["PROCESS_TEST_DIR": directory.url.path, "PROCESS_TEST_STAGE": stage],+ installations: .init(globalPath: command.path, bundledPath: nil),+ probeConnection: {+ if !FileManager.default.fileExists(atPath: marker.path) {+ throw AppServerConnectionError(code: ENOENT)+ }+ }+ )+ let task = Task { try await startup.ensureStarted() }+ defer { task.cancel() }+ try await directory.waitForFile("blocked")+ do {+ try await startup.ensureStarted()+ Issue.record("Expected overlapping startup to be rejected")+ } catch let error as AppServerStartup.StartupError {+ guard case .notReady = error else { throw error }+ }+ task.cancel()+ await #expect(throws: CancellationError.self) { try await task.value }+ #expect(!FileManager.default.fileExists(atPath: marker.path))+ #expect(try String(contentsOf: directory.url.appendingPathComponent("calls"), encoding: .utf8) == "blocked")+ _ = try directory.write("retry", to: "retry")+ try await startup.ensureStarted()+ #expect(FileManager.default.fileExists(atPath: marker.path))+ }+@Test nonisolated func missingSocketPreservesConnectionErrno() throws {let socket = URL(fileURLWithPath: "/tmp/\(UUID().uuidString).sock")do {@@ -170,10 +236,4 @@ struct AppServerStartupTests {#expect(error.serverIsAbsent)}}-- private func executable(in directory: TestDirectory, name: String = "fake codex", body: String) throws -> URL {- let url = try directory.write("#!/bin/sh\n\(body)\n", to: name)- try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: url.path)- return url- }}diff --git a/CodexBarTests/BoundedProcessTests.swift b/CodexBarTests/BoundedProcessTests.swiftindex 8109ef5..27ce29c 100644--- a/CodexBarTests/BoundedProcessTests.swift+++ b/CodexBarTests/BoundedProcessTests.swift@@ -1,21 +1,49 @@+import Darwinimport Foundationimport Testingstruct BoundedProcessTests {+ @Test nonisolated func preservesArgumentsEnvironmentAndMergedOutput() {+ let result = BoundedProcess.run(+ executable: URL(fileURLWithPath: "/bin/sh"),+ arguments: ["-c", "printf '%s' \"$1\"; printf '%s' \"$PROCESS_TEST_VALUE\" >&2; exit 7", "test", "a $value `literal`"],+ environment: ["PROCESS_TEST_VALUE": " with spaces"]+ )+ #expect(result.exitCode == 7)+ #expect(result.output == "a $value `literal` with spaces")+ #expect(!result.timedOut)+ #expect(result.runningProcess == nil)+ }++ @Test nonisolated func missingExecutableDoesNotReportTimeout() {+ let result = BoundedProcess.run(+ executable: URL(fileURLWithPath: "/tmp/\(UUID().uuidString)/missing"), arguments: []+ )+ #expect(result.exitCode == -1)+ #expect(!result.output.isEmpty)+ #expect(!result.timedOut)+ #expect(result.runningProcess == nil)+ }+@Test func cancellationTerminatesOnlyTheCommandPromptly() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }let task = Task.detached {BoundedProcess.run(executable: URL(fileURLWithPath: "/bin/sh"),- arguments: ["-c", "trap '' TERM; while :; do :; done"], timeout: 15+ arguments: ["-c", "trap '' TERM; printf ready > \"$PROCESS_TEST_DIR/ready\"; while :; do :; done"],+ timeout: 15, environment: ["PROCESS_TEST_DIR": directory.url.path])}- try await Task.sleep(for: .milliseconds(100))+ defer { task.cancel() }+ try await directory.waitForFile("ready")let started = ContinuousClock.nowtask.cancel()let result = await task.value#expect(result.exitCode != 0)#expect(!result.timedOut)#expect(result.runningProcess == nil)+ #expect(result.completion == .cancelled)#expect(started.duration(to: .now) < .seconds(3))}@@ -34,4 +62,217 @@ struct BoundedProcessTests {#expect(next.exitCode == 0)#expect(next.output == "recovered")}++ @Test func separatesAndBoundsBothStreamsWithoutBlockingTheChild() async {+ let result = await BoundedProcess.runAsync(+ executable: URL(fileURLWithPath: "/bin/sh"),+ arguments: ["-c", """+ i=0+ while [ "$i" -lt 6000 ]; do+ printf '0123456789abcdef'+ printf 'fedcba9876543210' >&2+ i=$((i + 1))+ done+ """], timeout: 5, configuration: .init(outputMode: .separate)+ )+ #expect(result.completion == .exited)+ #expect(result.exitCode == 0)+ #expect(result.standardOutput.data == Data(String(repeating: "0123456789abcdef", count: 4096).utf8))+ #expect(result.standardError.data == Data(String(repeating: "fedcba9876543210", count: 4096).utf8))+ #expect(result.standardOutput.isTruncated)+ #expect(result.standardError.isTruncated)+ #expect(result.standardOutput.reachedEOF)+ #expect(result.standardError.reachedEOF)+ }++ @Test(arguments: [65535, 65536, 65537])+ func capturesTheTailAndReportsActualTruncation(_ size: Int) async {+ let text = String(repeating: "x", count: size - 1) + "!"+ let result = await BoundedProcess.runAsync(executable: URL(fileURLWithPath: "/usr/bin/printf"), arguments: ["%s", text])+ #expect(result.exitCode == 0)+ #expect(result.standardOutput.data == Data(text.utf8.prefix(65536)))+ #expect(result.standardOutput.isTruncated == (size > 65536))+ #expect(result.standardOutput.reachedEOF)+ }++ @Test func preservesRawBytesForCallerSpecificDecoding() async {+ let result = await BoundedProcess.runAsync(+ executable: URL(fileURLWithPath: "/bin/sh"), arguments: ["-c", "printf '\\377'; printf 'fallback' >&2"],+ configuration: .init(outputMode: .separate)+ )+ #expect(result.standardOutput.data == Data([255]))+ #expect(String(data: result.standardOutput.data, encoding: .utf8) == nil)+ #expect(result.output == "�")+ #expect(String(data: result.standardError.data, encoding: .utf8) == "fallback")+ }++ @Test(arguments: [false, true])+ func alreadyCancelledTaskDoesNotLaunch(_ synchronous: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let task = Task.detached {+ withUnsafeCurrentTask { $0?.cancel() }+ let arguments = ["-c", "printf started > \"$PROCESS_TEST_DIR/started\""]+ if synchronous {+ return BoundedProcess.run(+ executable: URL(fileURLWithPath: "/bin/sh"), arguments: arguments,+ environment: ["PROCESS_TEST_DIR": directory.url.path]+ )+ }+ return await BoundedProcess.runAsync(+ executable: URL(fileURLWithPath: "/bin/sh"), arguments: arguments,+ environment: ["PROCESS_TEST_DIR": directory.url.path]+ )+ }+ let result = await task.value+ #expect(result.completion == .cancelled)+ #expect(result.terminationStatus == nil)+ #expect(!FileManager.default.fileExists(atPath: directory.url.appendingPathComponent("started").path))+ }++ @Test(arguments: [false, true])+ func asyncCancellationWaitsForGracefulOrForcedCleanup(_ ignoresTermination: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let script = try directory.executable("""+ \(ignoresTermination ? "trap '' TERM" : "trap 'printf stopped; exit 23' TERM")+ printf ready > "$PROCESS_TEST_DIR/ready"+ while :; do :; done+ """)+ let task = Task {+ await BoundedProcess.runAsync(+ executable: script, arguments: [], timeout: 15, environment: ["PROCESS_TEST_DIR": directory.url.path]+ )+ }+ defer { task.cancel() }+ try await directory.waitForFile("ready")+ let started = ContinuousClock.now+ task.cancel()+ let result = await task.value+ #expect(result.completion == .cancelled)+ #expect(result.runningProcess == nil)+ #expect(result.terminationStatus == (ignoresTermination ? SIGKILL : 23))+ #expect(result.terminationReason == (ignoresTermination ? .uncaughtSignal : .exit))+ if !ignoresTermination {+ #expect(result.output == "stopped")+ }+ #expect(started.duration(to: .now) < .seconds(3))+ }++ @Test(arguments: ["while :; do :; done", "while :; do printf x; printf y >&2; done"])+ func asyncTimeoutRemainsBoundedWithIdleOrBusyPipes(_ body: String) async {+ let started = ContinuousClock.now+ let result = await BoundedProcess.runAsync(+ executable: URL(fileURLWithPath: "/bin/sh"), arguments: ["-c", "trap '' TERM; " + body],+ timeout: 0.15, configuration: .init(outputMode: .separate)+ )+ #expect(result.completion == .timedOut)+ #expect(result.runningProcess == nil)+ #expect(result.standardOutput.data.count <= 65536)+ #expect(result.standardError.data.count <= 65536)+ #expect(started.duration(to: .now) < .seconds(3))+ }++ @Test func signalExitIsDistinctFromTimeout() async {+ let result = await BoundedProcess.runAsync(+ executable: URL(fileURLWithPath: "/bin/sh"), arguments: ["-c", "kill -KILL $$"]+ )+ #expect(result.completion == .exited)+ #expect(result.exitCode == SIGKILL)+ #expect(result.terminationReason == .uncaughtSignal)+ }++ @Test func inheritedWriterDoesNotPreventCompletionOrKillTheDescendant() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let pidURL = directory.url.appendingPathComponent("child.pid")+ defer {+ if let text = try? String(contentsOf: pidURL, encoding: .utf8), let pid = Int32(text.trimmingCharacters(in: .whitespacesAndNewlines)) {+ kill(pid, SIGKILL)+ }+ }+ let started = ContinuousClock.now+ let result = await BoundedProcess.runAsync(+ executable: URL(fileURLWithPath: "/bin/sh"), arguments: ["-c", """+ /bin/sleep 10 &+ printf '%s' "$!" > "$PROCESS_TEST_DIR/child.pid"+ printf tail+ """], environment: ["PROCESS_TEST_DIR": directory.url.path]+ )+ #expect(result.exitCode == 0)+ #expect(result.output == "tail")+ #expect(!result.standardOutput.reachedEOF)+ #expect(started.duration(to: .now) < .seconds(3))+ let pid = try #require(Int32(String(contentsOf: pidURL, encoding: .utf8)))+ #expect(kill(pid, 0) == 0)+ }++ @Test func expiredDeadlineAndInvalidBudgetDoNotLaunch() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let script = try directory.executable("printf started > \"$PROCESS_TEST_DIR/started\"")+ let expired = await BoundedProcess.runAsync(+ executable: script, arguments: [], environment: ["PROCESS_TEST_DIR": directory.url.path],+ configuration: .init(deadline: .now.advanced(by: .seconds(-1)))+ )+ #expect(expired.completion == .timedOut)+ let invalid = await BoundedProcess.runAsync(+ executable: script, arguments: [], timeout: .infinity, environment: ["PROCESS_TEST_DIR": directory.url.path]+ )+ #expect(invalid.completion == .invalidConfiguration)+ #expect(!FileManager.default.fileExists(atPath: directory.url.appendingPathComponent("started").path))+ }++ @Test func cancellationRacingExitAlwaysFinishesOnce() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let command = try directory.executable("""+ printf ready > "$PROCESS_TEST_DIR/$PROCESS_TEST_INDEX.ready"+ while [ ! -f "$PROCESS_TEST_DIR/$PROCESS_TEST_INDEX.exit" ]; do :; done+ printf done+ """)+ for iteration in 0 ..< 20 {+ let task = Task {+ await BoundedProcess.runAsync(+ executable: command, arguments: [], timeout: 5,+ environment: ["PROCESS_TEST_DIR": directory.url.path, "PROCESS_TEST_INDEX": String(iteration)]+ )+ }+ defer { task.cancel() }+ try await directory.waitForFile("\(iteration).ready")+ _ = try directory.write("exit", to: "\(iteration).exit")+ if iteration.isMultiple(of: 2) {+ await Task.yield()+ }+ task.cancel()+ let result = await task.value+ #expect(result.completion == .cancelled || result.completion == .exited)+ #expect(result.runningProcess == nil)+ if result.completion == .exited {+ #expect(result.output == "done")+ }+ }+ }++ @Test func repeatedLaunchFailuresAndCompletionsDoNotAccumulateDescriptors() async throws {+ let executable = URL(fileURLWithPath: "/usr/bin/true")+ for _ in 0 ..< 3 {+ _ = await BoundedProcess.runAsync(executable: executable, arguments: [])+ }+ let before = try FileManager.default.contentsOfDirectory(atPath: "/dev/fd").count+ let missing = URL(fileURLWithPath: "/tmp/\(UUID().uuidString)/missing")+ for _ in 0 ..< 20 {+ let failed = await BoundedProcess.runAsync(executable: missing, arguments: [], configuration: .init(outputMode: .separate))+ guard case .launchFailed = failed.completion else {+ Issue.record("Expected launch failure")+ return+ }+ let completed = await BoundedProcess.runAsync(executable: executable, arguments: [], configuration: .init(outputMode: .separate))+ #expect(completed.exitCode == 0)+ #expect(completed.runningProcess == nil)+ }+ let after = try FileManager.default.contentsOfDirectory(atPath: "/dev/fd").count+ // Foundation 和测试框架可能延迟打开描述符, 不要求全进程数量完全一致+ #expect(after <= before + 2)+ }}diff --git a/CodexBarTests/CodexVersionProcessTests.swift b/CodexBarTests/CodexVersionProcessTests.swiftnew file mode 100644index 0000000..b6945a7--- /dev/null+++ b/CodexBarTests/CodexVersionProcessTests.swift@@ -0,0 +1,104 @@+import Foundation+import Testing++struct CodexVersionProcessTests {+ @Test(arguments: [+ ("printf 'codex-cli 0.157.0\\nignored'; printf 'codex-cli 0.156.0' >&2", "0.157.0"),+ ("printf ' \\n'; printf 'codex-cli 0.157.0\\n' >&2", "0.157.0"),+ ("printf '\\377'; printf 'codex-cli 0.157.0' >&2", "0.157.0")+ ])+ func preservesOutputPriorityAndStrictDecoding(_ fixture: (String, String)) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let command = try directory.executable(fixture.0)+ let service = CodexVersionService(environment: [:], installations: .init(globalPath: command.path, bundledPath: nil))+ let snapshot = await service.fetchSnapshot()+ #expect(snapshot.global.version == fixture.1)+ #expect(snapshot.global.errorMessage == nil)+ #expect(snapshot.bundled.path == nil)+ }++ @Test(arguments: ["exit 7", "exit 0", "trap '' TERM; while :; do :; done"])+ func preservesFailureMessages(_ body: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let command = try directory.executable(body)+ let service = CodexVersionService(+ timeout: body.hasPrefix("trap") ? 0.15 : 5, environment: [:],+ installations: .init(globalPath: command.path, bundledPath: nil)+ )+ let snapshot = await service.fetchSnapshot()+ let message = switch body {+ case "exit 7": String(localized: "codex.version.read-failed")+ case "exit 0": String(localized: "codex.version.parse-failed")+ default: String(localized: "codex.version.read-timeout")+ }+ #expect(snapshot.global.errorMessage == message)+ #expect(snapshot.global.version == nil)+ }++ @Test func preservesLaunchFailureForANonExecutableFile() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let command = try directory.write("not executable", to: "codex")+ let service = CodexVersionService(environment: [:], installations: .init(globalPath: command.path, bundledPath: nil))+ let snapshot = await service.fetchSnapshot()+ #expect(snapshot.global.errorMessage == String(localized: "codex.version.launch-failed"))+ }++ @Test func probesBothSourcesConcurrently() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let global = try directory.executable("""+ printf ready > "$PROCESS_TEST_DIR/global.ready"+ while [ ! -f "$PROCESS_TEST_DIR/bundled.ready" ]; do /bin/sleep 0.01; done+ printf 'codex-cli 0.157.0'+ """, named: "global")+ let bundled = try directory.executable("""+ printf ready > "$PROCESS_TEST_DIR/bundled.ready"+ while [ ! -f "$PROCESS_TEST_DIR/global.ready" ]; do /bin/sleep 0.01; done+ printf 'codex-cli 0.158.0'+ """, named: "bundled")+ let service = CodexVersionService(+ timeout: 3, environment: ["PROCESS_TEST_DIR": directory.url.path],+ installations: .init(globalPath: global.path, bundledPath: bundled.path)+ )+ let snapshot = await service.fetchSnapshot()+ #expect(snapshot.global.version == "0.157.0")+ #expect(snapshot.bundled.version == "0.158.0")+ }++ @Test func cancellationCleansBothSourcesAndAllowsAnotherRefresh() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ func command(named name: String) throws -> URL {+ try directory.executable("""+ if [ -f "$PROCESS_TEST_DIR/retry" ]; then printf 'codex-cli 0.157.0'; exit 0; fi+ trap '' TERM+ printf ready > "$PROCESS_TEST_DIR/\(name).ready"+ while :; do :; done+ """, named: name)+ }+ let global = try command(named: "global")+ let bundled = try command(named: "bundled")+ let service = CodexVersionService(+ timeout: 15, environment: ["PROCESS_TEST_DIR": directory.url.path],+ installations: .init(globalPath: global.path, bundledPath: bundled.path)+ )+ let task = Task { await service.fetchSnapshot() }+ defer { task.cancel() }+ try await directory.waitForFile("global.ready")+ try await directory.waitForFile("bundled.ready")+ let overlapping = await service.fetchSnapshot()+ #expect(overlapping.global.errorMessage == String(localized: "codex.version.read-failed"))+ #expect(overlapping.bundled.errorMessage == String(localized: "codex.version.read-failed"))+ let started = ContinuousClock.now+ task.cancel()+ _ = await task.value+ #expect(started.duration(to: .now) < .seconds(3))+ _ = try directory.write("retry", to: "retry")+ let retried = await service.fetchSnapshot()+ #expect(retried.global.version == "0.157.0")+ #expect(retried.bundled.version == "0.157.0")+ }+}diff --git a/CodexBarTests/TestSupport.swift b/CodexBarTests/TestSupport.swiftindex a6ecfeb..5a4e54d 100644--- a/CodexBarTests/TestSupport.swift+++ b/CodexBarTests/TestSupport.swift@@ -63,6 +63,21 @@ nonisolated struct TestDirectory {func remove() throws {try FileManager.default.removeItem(at: url)}++ func executable(_ body: String, named name: String = "test command") throws -> URL {+ let command = try write("#!/bin/sh\n\(body)\n", to: name)+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: command.path)+ return command+ }++ func waitForFile(_ name: String) async throws {+ let path = url.appendingPathComponent(name).path+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))+ while !FileManager.default.fileExists(atPath: path), ContinuousClock.now < deadline {+ try await Task.sleep(for: .milliseconds(10))+ }+ try #require(FileManager.default.fileExists(atPath: path), "Test process did not create \(name)")+ }}struct TestPreferences {diff --git a/Shared/BoundedProcess.swift b/Shared/BoundedProcess.swiftindex ee593ad..dba28cb 100644--- a/Shared/BoundedProcess.swift+++ b/Shared/BoundedProcess.swift@@ -1,76 +1,293 @@import Darwinimport Foundation+import Synchronization-/// 同步调用必须在非主队列执行, 管道读取和进程终止均有期限+/// 同步入口只能在后台执行, 异步入口将阻塞 I/O 放到独立队列nonisolated enum BoundedProcess {- struct Result {- let exitCode: Int32- let output: String- let timedOut: Bool- let runningProcess: Process?+ enum OutputMode: Sendable {+ case merged+ case separate}- static func run(executable: URL, arguments: [String], timeout: TimeInterval = 2.5, environment: [String: String]? = nil) -> Result {+ struct Configuration: Sendable {+ var outputMode: OutputMode = .merged+ var gracefulTimeout: TimeInterval = 0.25+ var killTimeout: TimeInterval = 0.5+ var drainTimeout: TimeInterval = 0.25+ /// 指定时执行与输出排空共用期限, 并计入排队和启动耗时+ var deadline: ContinuousClock.Instant?+ }++ enum Completion: Equatable, Sendable {+ case exited+ case launchFailed(String)+ case ioFailed(Int32)+ case invalidConfiguration+ case timedOut+ case cancelled+ }++ struct Output: Sendable {+ var data = Data()+ var isTruncated = false+ var reachedEOF = false+ }++ struct Result: Sendable {+ let completion: Completion+ var standardOutput = Output(reachedEOF: true)+ var standardError = Output(reachedEOF: true)+ var terminationStatus: Int32?+ var terminationReason: Process.TerminationReason?+ /// 返回后由调用方接管, 内核不再访问该进程+ var runningProcess: Process?++ var exitCode: Int32 {+ completion == .exited ? terminationStatus ?? -1 : -1+ }++ var timedOut: Bool {+ completion == .timedOut+ }++ var output: String {+ if case let .launchFailed(message) = completion {+ return message+ }+ // helper 和后台服务保留替换无效 UTF-8 字节的展示行为+ // swiftlint:disable:next optional_data_string_conversion+ return String(decoding: standardOutput.data, as: UTF8.self)+ }+ }++ private static let workers = DispatchQueue(label: "CodexBar.process", qos: .userInitiated, attributes: .concurrent)++ static func run(+ executable: URL,+ arguments: [String],+ timeout: TimeInterval = 2.5,+ environment: [String: String]? = nil,+ configuration: Configuration = Configuration()+ ) -> Result {+ execute(executable: executable, arguments: arguments, timeout: timeout, environment: environment, configuration: configuration) {+ Task.isCancelled+ }+ }++ static func runAsync(+ executable: URL,+ arguments: [String],+ timeout: TimeInterval = 2.5,+ environment: [String: String]? = nil,+ configuration: Configuration = Configuration()+ ) async -> Result {+ let cancelled = Mutex(false)+ return await withTaskCancellationHandler {+ await withCheckedContinuation { continuation in+ workers.async {+ let result = execute(+ executable: executable, arguments: arguments, timeout: timeout,+ environment: environment, configuration: configuration,+ isCancelled: { cancelled.withLock { $0 } }+ )+ // 只有执行者完成清理后才能返回, 取消回调不接触进程或 continuation+ continuation.resume(returning: result)+ }+ }+ } onCancel: {+ cancelled.withLock { $0 = true }+ }+ }++ private static func execute(+ executable: URL,+ arguments: [String],+ timeout: TimeInterval,+ environment: [String: String]?,+ configuration: Configuration,+ isCancelled: () -> Bool+ ) -> Result {+ guard !isCancelled() else { return Result(completion: .cancelled) }+ guard [timeout, configuration.gracefulTimeout, configuration.killTimeout, configuration.drainTimeout].allSatisfy(\.isFinite) else {+ return Result(completion: .invalidConfiguration)+ }+ if let deadline = configuration.deadline, ContinuousClock.now >= deadline {+ return Result(completion: .timedOut)+ }+let process = Process()process.executableURL = executableprocess.arguments = argumentsprocess.environment = environment- guard !Task.isCancelled else {- return Result(exitCode: -1, output: "", timedOut: false, runningProcess: nil)+ let readers = configuration.outputMode == .merged ? [PipeReader()] : [PipeReader(), PipeReader()]+ defer { readers.forEach { $0.close() } }+ for reader in readers {+ if let error = reader.configure() {+ return Result(completion: .ioFailed(error))+ }}- let pipe = Pipe()- process.standardOutput = pipe- process.standardError = pipe- do { try process.run() } catch {- return Result(exitCode: -1, output: error.localizedDescription, timedOut: false, runningProcess: nil)- }- pipe.fileHandleForWriting.closeFile()- let descriptor = pipe.fileHandleForReading.fileDescriptor- _ = fcntl(descriptor, F_SETFL, O_NONBLOCK)- defer { pipe.fileHandleForReading.closeFile() }- let clock = ContinuousClock()- let deadline = clock.now.advanced(by: .seconds(max(0, timeout)))- var killDeadline = deadline.advanced(by: .milliseconds(250))- var end = killDeadline.advanced(by: .milliseconds(500))- var output = Data()- var buffer = [UInt8](repeating: 0, count: 8192)- var terminated = false- var timedOut = false- var killed = false- while true {- // 每轮读取有界, 持续输出不能阻止检查超时- for _ in 0 ..< 8 {- let count = Darwin.read(descriptor, &buffer, buffer.count)- guard count > 0 else { break }- if output.count < 65536 {- output.append(contentsOf: buffer.prefix(min(count, 65536 - output.count)))+ process.standardOutput = readers[0].pipe+ process.standardError = readers.last!.pipe+ guard !isCancelled() else { return Result(completion: .cancelled) }+ do {+ try process.run()+ } catch {+ return Result(completion: .launchFailed(error.localizedDescription))+ }+ readers.forEach { $0.closeWriter() }+ let deadline = configuration.deadline ?? ContinuousClock.now.advanced(by: .seconds(max(0, timeout)))+ var execution = Execution(process: process, readers: readers, configuration: configuration, deadline: deadline)+ return execution.wait(isCancelled: isCancelled)+ }++ private enum Phase {+ case running+ case terminating(until: ContinuousClock.Instant)+ case killing(until: ContinuousClock.Instant)+ case draining(until: ContinuousClock.Instant)+ }++ private struct Execution {+ let process: Process+ let readers: [PipeReader]+ let configuration: Configuration+ let deadline: ContinuousClock.Instant+ var phase = Phase.running+ var completion: Completion?++ mutating func wait(isCancelled: () -> Bool) -> Result {+ while true {+ for reader in readers {+ if let error = reader.drain(), completion == nil || completion == .exited {+ completion = .ioFailed(error)+ }}+ let now = ContinuousClock.now+ if !process.isRunning {+ if case .draining = phase {} else {+ completion = completion ?? .exited+ var end = now.advanced(by: .seconds(max(0, configuration.drainTimeout)))+ if configuration.deadline != nil {+ end = min(end, deadline)+ }+ phase = .draining(until: end)+ // 退出可能发生在本轮读取之后, 再读取一次已到达的尾部字节+ continue+ }+ }++ switch phase {+ case .running:+ if completion == nil {+ if now >= deadline {+ completion = .timedOut+ } else if isCancelled() {+ completion = .cancelled+ }+ }+ if completion != nil {+ phase = .terminating(until: now.advanced(by: .seconds(max(0, configuration.gracefulTimeout))))+ if process.isRunning {+ process.terminate()+ }+ }+ case let .terminating(end):+ if now >= end {+ phase = .killing(until: now.advanced(by: .seconds(max(0, configuration.killTimeout))))+ if process.isRunning {+ kill(process.processIdentifier, SIGKILL)+ }+ }+ case let .killing(end):+ if now >= end {+ return result()+ }+ case let .draining(end):+ if readers.allSatisfy(\.output.reachedEOF) || now >= end || isCancelled() {+ return result()+ }+ }+ pause()}- if !process.isRunning {- break- }- if clock.now >= deadline || Task.isCancelled, !terminated {- timedOut = clock.now >= deadline- terminated = true- killDeadline = clock.now.advanced(by: .milliseconds(250))- end = killDeadline.advanced(by: .milliseconds(500))- process.terminate()+ }++ private func pause() {+ let next: ContinuousClock.Instant = switch phase {+ case .running: deadline+ case let .terminating(end), let .killing(end), let .draining(end): end}- if clock.now >= killDeadline, !killed {- killed = true- kill(process.processIdentifier, SIGKILL)+ let remaining = ContinuousClock.now.duration(to: next)+ if remaining > .zero {+ let duration = min(remaining, .milliseconds(10)).components+ Thread.sleep(forTimeInterval: Double(duration.seconds) + Double(duration.attoseconds) / 1e18)}- if clock.now >= end {- break+ }++ private func result() -> Result {+ let running = process.isRunning+ return Result(+ completion: completion ?? .exited,+ standardOutput: readers[0].output,+ standardError: readers.count == 2 ? readers[1].output : Output(reachedEOF: true),+ terminationStatus: running ? nil : process.terminationStatus,+ terminationReason: running ? nil : process.terminationReason,+ runningProcess: running ? process : nil+ )+ }+ }++ /// 仅由执行线程访问, 字节上限与每轮读取次数分别限制内存和取消延迟+ private final class PipeReader {+ let pipe = Pipe()+ var output = Output()+ private var writerClosed = false+ private var readFailed = false+ private var buffer = [UInt8](repeating: 0, count: 8192)++ func configure() -> Int32? {+ let descriptor = pipe.fileHandleForReading.fileDescriptor+ let flags = fcntl(descriptor, F_GETFL)+ guard flags != -1, fcntl(descriptor, F_SETFL, flags | O_NONBLOCK) != -1 else { return errno }+ return nil+ }++ func drain() -> Int32? {+ guard !output.reachedEOF, !readFailed else { return nil }+ for _ in 0 ..< 8 {+ let count = Darwin.read(pipe.fileHandleForReading.fileDescriptor, &buffer, buffer.count)+ if count > 0 {+ let kept = min(count, 65536 - output.data.count)+ output.data.append(contentsOf: buffer.prefix(kept))+ if kept < count {+ output.isTruncated = true+ }+ } else if count == 0 {+ output.reachedEOF = true+ return nil+ } else {+ let code = errno+ if code == EINTR {+ continue+ }+ if code == EAGAIN || code == EWOULDBLOCK {+ return nil+ }+ readFailed = true+ return code+ }}- Thread.sleep(forTimeInterval: 0.01)- }- let running = process.isRunning- return Result(- exitCode: terminated || running ? -1 : process.terminationStatus,- output: String(decoding: output, as: UTF8.self),- timedOut: timedOut,- runningProcess: running ? process : nil- )+ return nil+ }++ func closeWriter() {+ guard !writerClosed else { return }+ writerClosed = true+ try? pipe.fileHandleForWriting.close()+ }++ func close() {+ closeWriter()+ try? pipe.fileHandleForReading.close()+ }}}