From 1efb378055059e32e8acfa2cc7cc81109f0de599 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 14:30:00 -0700 Subject: [PATCH 01/25] perf: inline codex monitor tailing and sidebar batching --- CLI/cmux.swift | 633 ++------------ .../BackgroundWorkspacePrimeCoordinator.swift | 126 ++- Sources/ContentView.swift | 17 + Sources/TerminalController.swift | 803 +++++++++++++++++- Sources/Workspace.swift | 129 ++- 5 files changed, 1086 insertions(+), 622 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 6bd7088647d5..3ce0e86e71f6 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -409,16 +409,6 @@ private struct AgentHookLaunchCommandRecord: Codable { var source: String? } -private struct CodexMonitorLeaseRecord: Codable { - var leaseId: String - var sessionId: String - var turnId: String? - var workspaceId: String - var surfaceId: String? - var createdAt: TimeInterval - var retiredAt: TimeInterval? -} - private struct ClaudeHookSessionStoreFile: Codable { var version: Int = 1 var sessions: [String: ClaudeHookSessionRecord] = [:] @@ -17601,11 +17591,6 @@ struct CMUXCLI { let isStreamError: Bool } - private struct CodexHookUserInputCandidate { - let callId: String - let question: String? - } - private enum CodexTranscriptFailureReadResult { case unavailable case pending @@ -17613,12 +17598,6 @@ struct CMUXCLI { case failure(CodexHookFailureCandidate) } - private enum CodexMonitorOwnerState { - case alive - case gone - case unknown - } - private func summarizeCodexHookFailure( parsedInput: ClaudeHookParsedInput, sessionId: String, @@ -17807,184 +17786,6 @@ struct CMUXCLI { return .healthy } - private func readCodexTranscriptUserInput( - path: String, - turnId: String?, - excluding publishedCallIds: Set - ) -> CodexHookUserInputCandidate? { - guard let content = readTextFileTail(path: path, maxBytes: 512 * 1024) else { - return nil - } - - var sawRelevantTurn = turnId == nil - var candidate: CodexHookUserInputCandidate? - for line in content.split(separator: "\n", omittingEmptySubsequences: true) { - let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty, - let data = trimmed.data(using: .utf8), - let object = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], - let objectType = object["type"] as? String else { - continue - } - - if objectType == "turn_context", - let payload = object["payload"] as? [String: Any] { - let payloadTurnId = firstString(in: payload, keys: ["turn_id", "turnId"]) - if let turnId { - sawRelevantTurn = payloadTurnId == turnId - } else { - sawRelevantTurn = true - } - continue - } - - if objectType == "response_item", - let payload = object["payload"] as? [String: Any], - let userInput = codexUserInputFunctionCallCandidate( - from: payload, - turnId: turnId, - sawRelevantTurn: sawRelevantTurn, - excluding: publishedCallIds - ) { - candidate = userInput - continue - } - - guard objectType == "event_msg", - let payload = object["payload"] as? [String: Any], - let eventType = payload["type"] as? String else { - continue - } - - switch eventType { - case "task_started": - let payloadTurnId = firstString(in: payload, keys: ["turn_id", "turnId"]) - if let turnId { - sawRelevantTurn = payloadTurnId == turnId - } else { - sawRelevantTurn = true - } - - case "request_user_input": - if let userInput = codexUserInputEventCandidate( - from: payload, - turnId: turnId, - sawRelevantTurn: sawRelevantTurn, - excluding: publishedCallIds - ) { - candidate = userInput - } - - case "task_complete", "turn_complete": - let payloadTurnId = firstString(in: payload, keys: ["turn_id", "turnId"]) - if let turnId { - guard payloadTurnId == turnId else { continue } - } - sawRelevantTurn = true - candidate = nil - - default: - break - } - } - - return candidate - } - - private func codexUserInputEventCandidate( - from payload: [String: Any], - turnId: String?, - sawRelevantTurn: Bool, - excluding publishedCallIds: Set - ) -> CodexHookUserInputCandidate? { - let payloadTurnId = firstString(in: payload, keys: ["turn_id", "turnId"]) - if let turnId { - if let payloadTurnId { - guard payloadTurnId == turnId else { return nil } - } else { - guard sawRelevantTurn else { return nil } - } - } - return codexUserInputCandidate( - from: payload, - payloadTurnId: payloadTurnId, - turnId: turnId, - excluding: publishedCallIds - ) - } - - private func codexUserInputFunctionCallCandidate( - from payload: [String: Any], - turnId: String?, - sawRelevantTurn: Bool, - excluding publishedCallIds: Set - ) -> CodexHookUserInputCandidate? { - guard (payload["type"] as? String) == "function_call", - (payload["name"] as? String) == "request_user_input" else { - return nil - } - - let arguments = codexFunctionCallArgumentsObject(from: payload) - let payloadTurnId = firstString(in: payload, keys: ["turn_id", "turnId"]) - ?? arguments.flatMap { firstString(in: $0, keys: ["turn_id", "turnId"]) } - if let turnId { - if let payloadTurnId { - guard payloadTurnId == turnId else { return nil } - } else { - guard sawRelevantTurn else { return nil } - } - } - - return codexUserInputCandidate( - from: arguments ?? payload, - payloadTurnId: payloadTurnId, - turnId: turnId, - fallbackCallId: firstString(in: payload, keys: ["call_id", "callId"]), - excluding: publishedCallIds - ) - } - - private func codexFunctionCallArgumentsObject(from payload: [String: Any]) -> [String: Any]? { - if let arguments = payload["arguments"] as? [String: Any] { - return arguments - } - guard let rawArguments = payload["arguments"] as? String, - let data = rawArguments.data(using: .utf8), - let arguments = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { - return nil - } - return arguments - } - - private func codexUserInputCandidate( - from payload: [String: Any], - payloadTurnId: String?, - turnId: String?, - fallbackCallId: String? = nil, - excluding publishedCallIds: Set - ) -> CodexHookUserInputCandidate? { - let question = codexUserInputQuestionText(from: payload) - let rawCallId = firstString(in: payload, keys: ["call_id", "callId"]) ?? fallbackCallId - let callId = rawCallId?.trimmingCharacters(in: .whitespacesAndNewlines) - ?? "\(payloadTurnId ?? turnId ?? "session"):\(question ?? "request_user_input")" - guard !publishedCallIds.contains(callId) else { return nil } - return CodexHookUserInputCandidate(callId: callId, question: question) - } - - private func codexUserInputQuestionText(from payload: [String: Any]) -> String? { - guard let questions = payload["questions"] as? [[String: Any]] else { - return nil - } - for question in questions { - let text = firstString(in: question, keys: ["question", "header", "id"]) - let normalized = text.map(normalizedSingleLine)?.trimmingCharacters(in: .whitespacesAndNewlines) - if let normalized, !normalized.isEmpty { - return truncate(normalized, maxLength: 220) - } - } - return nil - } - private func codexHookStopPayloadHasAssistantMessage(_ object: [String: Any]?) -> Bool { guard let object, let message = firstString(in: object, keys: ["last_assistant_message", "lastAssistantMessage"]) else { @@ -18208,168 +18009,14 @@ struct CMUXCLI { return directories } - private static let codexMonitorLeaseDirectoryName = "codex-monitor-leases" - private static let codexMonitorLeaseMaxAgeSeconds: TimeInterval = 4 * 60 * 60 - private static let codexMonitorRetiredLeaseMaxAgeSeconds: TimeInterval = 2 * 60 - private static let codexMonitorOwnerCheckIntervalSeconds: TimeInterval = 60 - private static let codexMonitorOwnerCheckTimeoutSeconds: TimeInterval = 1 - - private func codexMonitorLeaseDirectory(env: [String: String]) -> URL { - let statePath = NSString( - string: agentHookStatePath(sessionStoreSuffix: "codex", env: env) - ).expandingTildeInPath - return URL(fileURLWithPath: statePath, isDirectory: false) - .deletingLastPathComponent() - .appendingPathComponent(Self.codexMonitorLeaseDirectoryName, isDirectory: true) - } - - private func codexMonitorLeasePath(leaseId: String, env: [String: String]) -> String { - return codexMonitorLeaseDirectory(env: env) - .appendingPathComponent("\(leaseId).json", isDirectory: false) - .path - } - - private func writeCodexMonitorLease(_ record: CodexMonitorLeaseRecord, to path: String) throws { - let url = URL(fileURLWithPath: path, isDirectory: false) - try FileManager.default.createDirectory( - at: url.deletingLastPathComponent(), - withIntermediateDirectories: true, - attributes: nil - ) - let encoder = JSONEncoder() - encoder.outputFormatting = [.prettyPrinted, .sortedKeys] - let data = try encoder.encode(record) - try data.write(to: url, options: .atomic) - } - - private func readCodexMonitorLease(path: String) -> CodexMonitorLeaseRecord? { - guard let data = try? Data(contentsOf: URL(fileURLWithPath: path, isDirectory: false)) else { - return nil - } - return try? JSONDecoder().decode(CodexMonitorLeaseRecord.self, from: data) - } - - private func createCodexMonitorLease( - sessionId: String, - turnId: String?, - workspaceId: String, - surfaceId: String?, - env: [String: String] - ) -> String? { - let leaseId = UUID().uuidString.lowercased() - let path = codexMonitorLeasePath(leaseId: leaseId, env: env) - let normalizedSessionId = sessionId.trimmingCharacters(in: .whitespacesAndNewlines) - let normalizedTurnId = turnId?.trimmingCharacters(in: .whitespacesAndNewlines) - guard !normalizedSessionId.isEmpty else { return nil } - let record = CodexMonitorLeaseRecord( - leaseId: leaseId, - sessionId: normalizedSessionId, - turnId: normalizedTurnId?.isEmpty == false ? normalizedTurnId : nil, - workspaceId: workspaceId, - surfaceId: surfaceId, - createdAt: Date().timeIntervalSince1970, - retiredAt: nil - ) - try? pruneExpiredCodexMonitorLeases(env: env) - do { - try writeCodexMonitorLease(record, to: path) - return path - } catch { - return nil - } - } - - private func retireCodexMonitorLeases(sessionId: String, turnId: String?, env: [String: String]) { - let normalizedSessionId = sessionId.trimmingCharacters(in: .whitespacesAndNewlines) - guard !normalizedSessionId.isEmpty else { return } - - let fileManager = FileManager.default - let now = Date().timeIntervalSince1970 - let normalizedTurnId = turnId?.trimmingCharacters(in: .whitespacesAndNewlines) - let shouldMatchTurn = normalizedTurnId?.isEmpty == false - let directory = codexMonitorLeaseDirectory(env: env) - let targetPaths = ((try? fileManager.contentsOfDirectory( - at: directory, - includingPropertiesForKeys: nil, - options: [.skipsHiddenFiles] - )) ?? []).map(\.path) - - for path in targetPaths { - guard var record = readCodexMonitorLease(path: path), - record.sessionId == normalizedSessionId, - !shouldMatchTurn || record.turnId == normalizedTurnId, - record.retiredAt == nil else { - continue - } - record.retiredAt = now - try? writeCodexMonitorLease(record, to: path) - } - try? pruneExpiredCodexMonitorLeases(env: env) - } - - private func pruneExpiredCodexMonitorLeases(env: [String: String]) throws { - let fileManager = FileManager.default - let directory = codexMonitorLeaseDirectory(env: env) - guard fileManager.fileExists(atPath: directory.path) else { return } - let now = Date().timeIntervalSince1970 - let activeLeaseCutoff = now - Self.codexMonitorLeaseMaxAgeSeconds - let retiredLeaseCutoff = now - Self.codexMonitorRetiredLeaseMaxAgeSeconds - let urls = try fileManager.contentsOfDirectory( - at: directory, - includingPropertiesForKeys: nil, - options: [.skipsHiddenFiles] - ) - for url in urls { - guard let record = readCodexMonitorLease(path: url.path) else { - continue - } - let activeLeaseExpired = record.createdAt < activeLeaseCutoff - let retiredLeaseExpired = record.retiredAt.map { $0 < retiredLeaseCutoff } ?? false - if activeLeaseExpired || retiredLeaseExpired { - try? fileManager.removeItem(at: url) - } - } - } - - private func isCodexMonitorLeaseRetired(path: String?) -> Bool { - guard let path, !path.isEmpty else { return false } - guard let record = readCodexMonitorLease(path: path) else { - return !FileManager.default.fileExists(atPath: path) - } - return record.retiredAt != nil - } - - private func removeCodexMonitorLease(path: String?) { - guard let path, !path.isEmpty else { return } - try? FileManager.default.removeItem(atPath: path) - } - - private func codexMonitorOwnerState(workspaceId: String, surfaceId: String?, client: SocketClient) -> CodexMonitorOwnerState { - guard client.connectionAppearsOpen() else { return client.isRelayBacked ? .unknown : .gone } - guard let payload = try? client.sendV2( - method: "surface.list", - params: ["workspace_id": workspaceId], - responseTimeout: Self.codexMonitorOwnerCheckTimeoutSeconds - ) else { - return .unknown - } - let surfaces = payload["surfaces"] as? [[String: Any]] ?? [] - guard let surfaceId, !surfaceId.isEmpty else { return surfaces.isEmpty ? .gone : .alive } - let ownerFound = surfaces.contains { surface in - (surface["id"] as? String) == surfaceId || (surface["ref"] as? String) == surfaceId - } - return ownerFound ? .alive : .gone - } - - private func startCodexTranscriptMonitor( + private func requestCodexTranscriptMonitorStart( sessionId: String, turnId: String?, transcriptPath: String?, - cwd: String?, workspaceId: String, surfaceId: String?, - leasePath: String?, env: [String: String], + client: SocketClient, telemetry: CLISocketSentryTelemetry ) { guard !sessionId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, @@ -18377,216 +18024,63 @@ struct CMUXCLI { return } - 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, - ] - telemetry.breadcrumb("codex-hook.monitor.start", data: monitorTelemetry) - - let executablePath = resolvedExecutableURL()?.path ?? args.first ?? "cmux" - let process = Process() - process.executableURL = URL(fileURLWithPath: executablePath) - var monitorArgs = [ - "hooks", "codex", - "monitor", - "--workspace", - workspaceId, - "--session", - sessionId, + var params: [String: Any] = [ + "workspace_id": workspaceId, + "session_id": sessionId, ] - if let surfaceId, !surfaceId.isEmpty { - monitorArgs += ["--surface", surfaceId] - } - if let turnId, !turnId.isEmpty { - monitorArgs += ["--turn", turnId] - } - if let transcriptPath, !transcriptPath.isEmpty { - monitorArgs += ["--transcript", transcriptPath] - } - if let cwd, !cwd.isEmpty { - monitorArgs += ["--cwd", cwd] + if let surfaceId = normalizedHookValue(surfaceId) { + params["surface_id"] = surfaceId } - if let leasePath, !leasePath.isEmpty { - monitorArgs += ["--lease", leasePath] + if let turnId = normalizedHookValue(turnId) { + params["turn_id"] = turnId } - process.arguments = monitorArgs - process.environment = env.merging(["CMUX_CLI_SENTRY_DISABLED": "1"], uniquingKeysWith: { _, new in new }) - process.standardInput = FileHandle.nullDevice - process.standardOutput = FileHandle.nullDevice - process.standardError = FileHandle.nullDevice - do { - try process.run() - telemetry.breadcrumb("codex-hook.monitor.started", data: monitorTelemetry) - } catch { - telemetry.captureError(stage: "codex-monitor-start", error: error, data: monitorTelemetry) - } - } - - private func runCodexTranscriptMonitor(commandArgs: [String], client: SocketClient) 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"] - let sessionId = optionValue(commandArgs, name: "--session") - ?? env["CMUX_CODEX_SESSION_ID"] - ?? env["CODEX_SESSION_ID"] - ?? env["CMUX_AGENT_SESSION_ID"] - ?? "" - let turnId = optionValue(commandArgs, name: "--turn") - var transcriptPath = optionValue(commandArgs, name: "--transcript") - let leasePath = optionValue(commandArgs, name: "--lease") - - guard !workspaceId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, - !sessionId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { - return + if let transcriptPath = normalizedHookValue(transcriptPath) { + params["transcript_path"] = transcriptPath } - - defer { removeCodexMonitorLease(path: leasePath) } - let deadline = Date().addingTimeInterval(4 * 60 * 60) - var nextOwnerCheck = Date.distantPast - var publishedUserInputCallIds = Set() - while Date() < deadline { - if isCodexMonitorLeaseRetired(path: leasePath) { - return - } - let now = Date() - if now >= nextOwnerCheck { - nextOwnerCheck = now.addingTimeInterval(Self.codexMonitorOwnerCheckIntervalSeconds) - if codexMonitorOwnerState(workspaceId: workspaceId, surfaceId: surfaceId, client: client) == .gone { - return - } - } - - if transcriptPath == nil { - transcriptPath = findCodexTranscriptPath(sessionId: sessionId, env: env) - } - - if let currentTranscriptPath = transcriptPath { - if let userInput = readCodexTranscriptUserInput( - path: currentTranscriptPath, - turnId: turnId, - excluding: publishedUserInputCallIds - ) { - publishedUserInputCallIds.insert(userInput.callId) - publishCodexMonitorUserInput( - userInput, - workspaceId: workspaceId, - surfaceId: surfaceId, - client: client - ) - } - - switch readCodexTranscriptFailure( - path: currentTranscriptPath, - turnId: turnId, - requireTerminalCompletion: true - ) { - case .failure(let failure): - publishCodexMonitorFailure( - failure, - workspaceId: workspaceId, - surfaceId: surfaceId, - client: client - ) - return - case .healthy: - return - case .pending: - break - case .unavailable: - let unavailableTranscriptPath = currentTranscriptPath - transcriptPath = nil - if let resolvedTranscriptPath = findCodexTranscriptPath(sessionId: sessionId, env: env) { - transcriptPath = resolvedTranscriptPath - if resolvedTranscriptPath != unavailableTranscriptPath { - continue - } - } - } - } - - let remaining = deadline.timeIntervalSinceNow - guard remaining > 0 else { return } - waitForCodexTranscriptChange(path: transcriptPath, leasePath: leasePath, timeout: min(30, remaining)) + if let codexHome = normalizedHookValue(env["CODEX_HOME"]) { + params["codex_home"] = codexHome } - } - private func publishCodexMonitorUserInput( - _ userInput: CodexHookUserInputCandidate, - workspaceId: String, - surfaceId: String?, - client: SocketClient - ) { - let subtitle = String(localized: "agent.codex.input.subtitle.waiting", defaultValue: "Waiting") - let body = userInput.question ?? String( - localized: "agent.codex.input.body.needsInput", - defaultValue: "Codex is asking a question" + telemetry.breadcrumb( + "codex-hook.monitor.request-start", + data: [ + "has_turn_id": params["turn_id"] != nil, + "has_transcript": params["transcript_path"] != nil, + "has_surface_id": params["surface_id"] != nil, + ] ) - if let surfaceId, !surfaceId.isEmpty { - let payload = "Codex|\(sanitizeNotificationField(subtitle))|\(sanitizeNotificationField(body))" - _ = try? sendV1Command("notify_target \(workspaceId) \(surfaceId) \(payload)", client: client) + do { + _ = try client.sendV2( + method: "agent.codex_transcript_monitor.start", + params: params, + responseTimeout: 2 + ) + } catch { + telemetry.captureError(stage: "codex-monitor-start", error: error, data: params) } - let statusValue = String(localized: "agent.codex.input.status.needsInput", defaultValue: "Codex needs input") - _ = try? sendV1Command( - "set_status codex \(statusValue) --icon=bell.fill --color=#4C8DFF --priority=100 --tab=\(workspaceId)\(socketPanelOption(surfaceId))", - client: client - ) } - private func publishCodexMonitorFailure( - _ failure: CodexHookFailureCandidate, - workspaceId: String, - surfaceId: String?, - client: SocketClient + private func requestCodexTranscriptMonitorStop( + sessionId: String, + turnId: String?, + client: SocketClient, + telemetry: CLISocketSentryTelemetry ) { - let summary = summarizeCodexHookFailureCandidate(failure) - if let surfaceId, !surfaceId.isEmpty { - let payload = "Codex|\(sanitizeNotificationField(summary.subtitle))|\(sanitizeNotificationField(summary.body))" - _ = try? sendV1Command("notify_target \(workspaceId) \(surfaceId) \(payload)", client: client) + let normalizedSessionId = sessionId.trimmingCharacters(in: .whitespacesAndNewlines) + guard !normalizedSessionId.isEmpty else { return } + var params: [String: Any] = ["session_id": normalizedSessionId] + if let turnId = normalizedHookValue(turnId) { + params["turn_id"] = turnId } - _ = try? sendV1Command( - "set_status codex \(summary.statusValue) --icon=exclamationmark.triangle.fill --color=#FF453A --priority=100 --tab=\(workspaceId)\(socketPanelOption(surfaceId))", - client: client - ) - } - - private func waitForCodexTranscriptChange(path: String?, leasePath: String?, timeout: TimeInterval) { - guard timeout > 0 else { return } - - let semaphore = DispatchSemaphore(value: 0) - var sources: [DispatchSourceFileSystemObject] = [] - - func addFileSource(path: String?, eventMask: DispatchSource.FileSystemEvent) { - guard let path, !path.isEmpty else { return } - let expandedPath = NSString(string: path).expandingTildeInPath - let fd = open(expandedPath, O_EVTONLY) - guard fd >= 0 else { return } - let source = DispatchSource.makeFileSystemObjectSource( - fileDescriptor: fd, - eventMask: eventMask, - queue: DispatchQueue.global(qos: .utility) + do { + _ = try client.sendV2( + method: "agent.codex_transcript_monitor.stop", + params: params, + responseTimeout: 2 ) - source.setEventHandler { - semaphore.signal() - } - source.setCancelHandler { - close(fd) - } - source.resume() - sources.append(source) - } - - addFileSource(path: path, eventMask: [.write, .extend, .delete, .rename]) - addFileSource(path: leasePath, eventMask: [.write, .delete, .rename]) - - guard !sources.isEmpty else { - _ = DispatchSemaphore(value: 0).wait(timeout: .now() + timeout) - return + } catch { + telemetry.captureError(stage: "codex-monitor-stop", error: error, data: params) } - - _ = semaphore.wait(timeout: .now() + timeout) - sources.forEach { $0.cancel() } } private func extractMessageText(from message: [String: Any]) -> String? { @@ -20512,11 +20006,6 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { let hookArgs = Array(commandArgs.dropFirst()) telemetry.breadcrumb("\(def.name)-hook.\(subcommand)") - if def.name == "codex", subcommand == "monitor" { - try runCodexTranscriptMonitor(commandArgs: hookArgs, client: client) - return - } - // Workspace/surface resolution: prefer --workspace/--surface flags, then session store, then env let hookWsFlag = optionValue(hookArgs, name: "--workspace") let workspaceArg = hookWsFlag ?? env["CMUX_WORKSPACE_ID"] @@ -20624,28 +20113,14 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { client: client ) if def.name == "codex", !sessionId.isEmpty { - let leasePath = createCodexMonitorLease( + requestCodexTranscriptMonitorStart( sessionId: sessionId, turnId: input.turnId, workspaceId: workspaceId, surfaceId: surfaceId, - env: env - ) - if leasePath == nil { - telemetry.breadcrumb( - "codex-hook.monitor.lease-unavailable", - data: ["has_turn_id": normalizedHookValue(input.turnId) != nil] - ) - } - startCodexTranscriptMonitor( - sessionId: sessionId, - turnId: input.turnId, transcriptPath: normalizedHookValue(input.transcriptPath), - cwd: hookCwd ?? mapped?.cwd, - workspaceId: workspaceId, - surfaceId: surfaceId, - leasePath: leasePath, env: env, + client: client, telemetry: telemetry ) } @@ -20654,7 +20129,12 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { if def.name == "codex", !sessionId.isEmpty { let stopTurnId = input.turnId?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" if !stopTurnId.isEmpty { - retireCodexMonitorLeases(sessionId: sessionId, turnId: stopTurnId, env: env) + requestCodexTranscriptMonitorStop( + sessionId: sessionId, + turnId: stopTurnId, + client: client, + telemetry: telemetry + ) } } do { @@ -20743,7 +20223,12 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { case .sessionEnd: if def.name == "codex", !sessionId.isEmpty { - retireCodexMonitorLeases(sessionId: sessionId, turnId: nil, env: env) + requestCodexTranscriptMonitorStop( + sessionId: sessionId, + turnId: nil, + client: client, + telemetry: telemetry + ) } if let mapped = try? store.consume(sessionId: sessionId, workspaceId: nil, surfaceId: nil) { sendAgentFeedTelemetry(workspaceId: mapped.workspaceId) diff --git a/Sources/BackgroundWorkspacePrimeCoordinator.swift b/Sources/BackgroundWorkspacePrimeCoordinator.swift index f0707260c079..b72d0a0541e3 100644 --- a/Sources/BackgroundWorkspacePrimeCoordinator.swift +++ b/Sources/BackgroundWorkspacePrimeCoordinator.swift @@ -63,6 +63,10 @@ final class BackgroundWorkspacePrimeCoordinator { addCleanup { task.cancel() } } + func addCleanupAction(_ action: @escaping () -> Void) { + addCleanup(action) + } + func finish(reason: PrimeCompletionReason) { let drained: (CheckedContinuation?, [() -> Void])? lock.lock() @@ -93,8 +97,20 @@ final class BackgroundWorkspacePrimeCoordinator { } } + private struct RegisteredWaiter { + weak var waiter: Waiter? + } + + private weak var observedTabManager: TabManager? + private var readinessWaitersByWorkspaceId: [UUID: [RegisteredWaiter]] = [:] + private var readinessCancellables: Set = [] + private var readinessObservers: [NSObjectProtocol] = [] + private var lastPendingBackgroundWorkspaceLoadIds: Set = [] + private var lastTabIds: Set = [] + deinit { - // Explicit for the required_deinit lint; per-prime resources live on Waiter. + readinessCancellables.forEach { $0.cancel() } + readinessObservers.forEach { NotificationCenter.default.removeObserver($0) } } func taskKey(for tabManager: TabManager) -> [String] { @@ -193,7 +209,7 @@ final class BackgroundWorkspacePrimeCoordinator { waiter.start(continuation: continuation) guard !waiter.isResolved else { return } - installReadinessObservers( + registerReadinessWaiter( waiter: waiter, workspaceId: workspaceId, tabManager: tabManager @@ -225,68 +241,124 @@ final class BackgroundWorkspacePrimeCoordinator { } } - private func installReadinessObservers( + private func registerReadinessWaiter( waiter: Waiter, workspaceId: UUID, tabManager: TabManager ) { + ensureSharedReadinessObservers(tabManager: tabManager) + readinessWaitersByWorkspaceId[workspaceId, default: []].append(RegisteredWaiter(waiter: waiter)) + waiter.addCleanupAction { [weak self, weak waiter] in + Task { @MainActor in + guard let waiter else { return } + self?.unregisterReadinessWaiter(waiter, workspaceId: workspaceId) + } + } + } + + private func ensureSharedReadinessObservers(tabManager: TabManager) { + if let observedTabManager, observedTabManager === tabManager { + return + } + + readinessCancellables.forEach { $0.cancel() } + readinessCancellables.removeAll(keepingCapacity: false) + readinessObservers.forEach { NotificationCenter.default.removeObserver($0) } + readinessObservers.removeAll(keepingCapacity: false) + readinessWaitersByWorkspaceId.removeAll(keepingCapacity: false) + observedTabManager = tabManager + lastPendingBackgroundWorkspaceLoadIds = tabManager.pendingBackgroundWorkspaceLoadIds + lastTabIds = Set(tabManager.tabs.map(\.id)) + let readyObserver = NotificationCenter.default.addObserver( forName: .terminalSurfaceDidBecomeReady, object: nil, queue: .main - ) { [weak self, weak waiter, weak tabManager] notification in + ) { [weak self, weak tabManager] notification in guard let readyWorkspaceId = notification.userInfo?["workspaceId"] as? UUID, - readyWorkspaceId == workspaceId, let self, - let waiter, let tabManager else { return } Task { @MainActor in - self.evaluate(waiter: waiter, workspaceId: workspaceId, tabManager: tabManager) + self.evaluateRegisteredWaiters(for: readyWorkspaceId, tabManager: tabManager) } } - waiter.addObserver(readyObserver) + readinessObservers.append(readyObserver) let hostedViewObserver = NotificationCenter.default.addObserver( forName: .terminalSurfaceHostedViewDidMoveToWindow, object: nil, queue: .main - ) { [weak self, weak waiter, weak tabManager] notification in + ) { [weak self, weak tabManager] notification in guard let readyWorkspaceId = notification.userInfo?["workspaceId"] as? UUID, - readyWorkspaceId == workspaceId, let self, - let waiter, let tabManager else { return } Task { @MainActor in - self.evaluate(waiter: waiter, workspaceId: workspaceId, tabManager: tabManager) + self.evaluateRegisteredWaiters(for: readyWorkspaceId, tabManager: tabManager) } } - waiter.addObserver(hostedViewObserver) + readinessObservers.append(hostedViewObserver) let pendingObserver = tabManager.$pendingBackgroundWorkspaceLoadIds .dropFirst() - .sink { [weak self, weak waiter, weak tabManager] pendingIds in - guard !pendingIds.contains(workspaceId), - let self, - let waiter, - let tabManager else { return } + .sink { [weak self, weak tabManager] pendingIds in + guard let self, let tabManager else { return } Task { @MainActor in - self.evaluate(waiter: waiter, workspaceId: workspaceId, tabManager: tabManager) + self.handlePendingWorkspaceIdsChange(pendingIds, tabManager: tabManager) } } - waiter.addCancellable(pendingObserver) + readinessCancellables.insert(pendingObserver) let tabsObserver = tabManager.$tabs .dropFirst() - .sink { [weak self, weak waiter, weak tabManager] tabs in - guard !tabs.contains(where: { $0.id == workspaceId }), - let self, - let waiter, - let tabManager else { return } + .sink { [weak self, weak tabManager] tabs in + let tabIds = Set(tabs.map(\.id)) + guard let self, let tabManager else { return } Task { @MainActor in - self.evaluate(waiter: waiter, workspaceId: workspaceId, tabManager: tabManager) + self.handleTabIdsChange(tabIds, tabManager: tabManager) } } - waiter.addCancellable(tabsObserver) + readinessCancellables.insert(tabsObserver) + } + + private func unregisterReadinessWaiter(_ waiter: Waiter, workspaceId: UUID) { + guard var waiters = readinessWaitersByWorkspaceId[workspaceId] else { return } + waiters.removeAll { $0.waiter == nil || $0.waiter === waiter || $0.waiter?.isResolved == true } + if waiters.isEmpty { + readinessWaitersByWorkspaceId.removeValue(forKey: workspaceId) + } else { + readinessWaitersByWorkspaceId[workspaceId] = waiters + } + } + + private func handlePendingWorkspaceIdsChange(_ pendingIds: Set, tabManager: TabManager) { + let removedIds = lastPendingBackgroundWorkspaceLoadIds.subtracting(pendingIds) + lastPendingBackgroundWorkspaceLoadIds = pendingIds + for workspaceId in removedIds { + evaluateRegisteredWaiters(for: workspaceId, tabManager: tabManager) + } + } + + private func handleTabIdsChange(_ tabIds: Set, tabManager: TabManager) { + let removedIds = lastTabIds.subtracting(tabIds) + lastTabIds = tabIds + for workspaceId in removedIds { + evaluateRegisteredWaiters(for: workspaceId, tabManager: tabManager) + } + } + + private func evaluateRegisteredWaiters(for workspaceId: UUID, tabManager: TabManager) { + guard var waiters = readinessWaitersByWorkspaceId[workspaceId] else { return } + waiters.removeAll { $0.waiter == nil || $0.waiter?.isResolved == true } + for registration in waiters { + guard let waiter = registration.waiter else { continue } + evaluate(waiter: waiter, workspaceId: workspaceId, tabManager: tabManager) + } + waiters.removeAll { $0.waiter == nil || $0.waiter?.isResolved == true } + if waiters.isEmpty { + readinessWaitersByWorkspaceId.removeValue(forKey: workspaceId) + } else { + readinessWaitersByWorkspaceId[workspaceId] = waiters + } } private func evaluate(waiter: Waiter, workspaceId: UUID, tabManager: TabManager) { diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index d7962fa66af4..21af39798785 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -12637,6 +12637,23 @@ private struct TabItemView: View, Equatable { "descLen=\((description as NSString).length) " + "desc=\"\(debugCommandPaletteTextPreview(description))\"" ) +#endif + refreshWorkspaceSnapshot() + } + .onReceive( + tab.sidebarAgentObservationPublisher + .receive(on: RunLoop.main) + .throttle(for: .milliseconds(80), scheduler: RunLoop.main, latest: true) + ) { _ in +#if DEBUG + let description = tab.customDescription ?? "" + cmuxDebugLog( + "sidebar.row.invalidate workspace=\(tab.id.uuidString.prefix(8)) " + + "source=agentThrottled " + + "title=\"\(debugCommandPaletteTextPreview(tab.title))\" " + + "descLen=\((description as NSString).length) " + + "desc=\"\(debugCommandPaletteTextPreview(description))\"" + ) #endif refreshWorkspaceSnapshot() } diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 23704a31ee61..3b7eadc57cf2 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -1,6 +1,7 @@ import AppKit import Carbon.HIToolbox import CMUXWorkstream +import Darwin import Foundation import Bonsplit import WebKit @@ -19,6 +20,690 @@ nonisolated private struct SocketLineProcessingResult: Sendable { let authenticated: Bool } +fileprivate struct CodexTranscriptMonitorRequest: Sendable { + let workspaceId: UUID + let surfaceId: UUID? + let sessionId: String + let turnId: String? + let transcriptPath: String? + let codexHome: String? +} + +fileprivate struct CodexTranscriptFailureSummary: Sendable { + let statusValue: String + let subtitle: String + let body: String +} + +fileprivate enum CodexTranscriptMonitorEvent: Sendable { + case userInput(request: CodexTranscriptMonitorRequest, body: String) + case failure(request: CodexTranscriptMonitorRequest, summary: CodexTranscriptFailureSummary) +} + +private final class CodexTranscriptMonitorRegistry: @unchecked Sendable { + static let shared = CodexTranscriptMonitorRegistry() + + private let queue = DispatchQueue(label: "com.cmux.codex-transcript-monitor", qos: .utility) + private var monitorsBySessionId: [String: Monitor] = [:] + + private init() {} + + func start(_ request: CodexTranscriptMonitorRequest) { + queue.async { [weak self] in + guard let self else { return } + let key = request.sessionId + self.monitorsBySessionId[key]?.cancel() + let monitor = Monitor( + request: request, + queue: self.queue, + onEvent: { [weak self] event in self?.publish(event) }, + onFinish: { [weak self] sessionId, monitor in + guard let self else { return } + if self.monitorsBySessionId[sessionId] === monitor { + self.monitorsBySessionId.removeValue(forKey: sessionId) + } + } + ) + self.monitorsBySessionId[key] = monitor + monitor.start() + } + } + + func stop(sessionId: String, turnId: String?) { + queue.async { [weak self] in + guard let self else { return } + if let monitor = self.monitorsBySessionId[sessionId], + turnId == nil || monitor.matches(turnId: turnId) { + monitor.cancel() + self.monitorsBySessionId.removeValue(forKey: sessionId) + } + } + } + + func stopWorkspace(_ workspaceId: UUID) { + queue.async { [weak self] in + guard let self else { return } + let matchingSessionIds = self.monitorsBySessionId.compactMap { sessionId, monitor in + monitor.workspaceId == workspaceId ? sessionId : nil + } + for sessionId in matchingSessionIds { + self.monitorsBySessionId[sessionId]?.cancel() + self.monitorsBySessionId.removeValue(forKey: sessionId) + } + } + } + + private func publish(_ event: CodexTranscriptMonitorEvent) { + Task { @MainActor in + TerminalController.shared.handleCodexTranscriptMonitorEvent(event) + } + } + + private final class Monitor { + private struct FailureCandidate { + let message: String + let codexErrorInfo: String? + let additionalDetails: String? + let isStreamError: Bool + } + + private struct UserInputCandidate { + let callId: String + let question: String? + } + + private enum Policy { + static let maxTailBytes: UInt64 = 512 * 1024 + static let retryInterval: TimeInterval = 1 + static let deadline: TimeInterval = 4 * 60 * 60 + } + + let workspaceId: UUID + + private let request: CodexTranscriptMonitorRequest + private let queue: DispatchQueue + private let onEvent: (CodexTranscriptMonitorEvent) -> Void + private let onFinish: (String, Monitor) -> Void + private var source: DispatchSourceFileSystemObject? + private var retryTimer: DispatchSourceTimer? + private var deadlineTimer: DispatchSourceTimer? + private var transcriptPath: String? + private var readOffset: UInt64 = 0 + private var pendingData = Data() + private var publishedUserInputCallIds = Set() + private var sawRelevantTurn = false + private var sawAssistantMessage = false + private var finished = false + + init( + request: CodexTranscriptMonitorRequest, + queue: DispatchQueue, + onEvent: @escaping (CodexTranscriptMonitorEvent) -> Void, + onFinish: @escaping (String, Monitor) -> Void + ) { + self.request = request + self.queue = queue + self.onEvent = onEvent + self.onFinish = onFinish + self.workspaceId = request.workspaceId + self.transcriptPath = Self.normalizedValue(request.transcriptPath) + self.sawRelevantTurn = Self.normalizedValue(request.turnId) == nil + } + + func start() { + armDeadline() + installSourceOrRetry() + } + + func matches(turnId: String?) -> Bool { + guard let turnId = Self.normalizedValue(turnId) else { return true } + return Self.normalizedValue(request.turnId) == turnId + } + + func cancel() { + finished = true + source?.cancel() + source = nil + retryTimer?.cancel() + retryTimer = nil + deadlineTimer?.cancel() + deadlineTimer = nil + } + + private func finish() { + guard !finished else { return } + cancel() + onFinish(request.sessionId, self) + } + + private func armDeadline() { + let timer = DispatchSource.makeTimerSource(queue: queue) + timer.schedule(deadline: .now() + Policy.deadline) + timer.setEventHandler { [weak self] in + self?.finish() + } + timer.resume() + deadlineTimer = timer + } + + private func installSourceOrRetry() { + guard !finished else { return } + if transcriptPath == nil { + transcriptPath = findTranscriptPath() + } + guard let path = transcriptPath else { + scheduleRetry() + return + } + installFileSource(path: path) + } + + private func installFileSource(path: String) { + source?.cancel() + source = nil + + let expandedPath = NSString(string: path).expandingTildeInPath + let fd = open(expandedPath, O_EVTONLY) + guard fd >= 0 else { + transcriptPath = nil + scheduleRetry() + return + } + + let newSource = DispatchSource.makeFileSystemObjectSource( + fileDescriptor: fd, + eventMask: [.write, .extend, .delete, .rename], + queue: queue + ) + newSource.setEventHandler { [weak self] in + self?.handleFileEvent() + } + newSource.setCancelHandler { + close(fd) + } + source = newSource + newSource.resume() + readInitialTail(path: expandedPath) + } + + private func handleFileEvent() { + guard !finished, let path = transcriptPath else { return } + let expandedPath = NSString(string: path).expandingTildeInPath + if let eventData = source?.data, + eventData.contains(.delete) || eventData.contains(.rename) { + source?.cancel() + source = nil + transcriptPath = nil + readOffset = 0 + pendingData.removeAll(keepingCapacity: false) + scheduleRetry() + return + } + readIncremental(path: expandedPath) + } + + private func scheduleRetry() { + retryTimer?.cancel() + let timer = DispatchSource.makeTimerSource(queue: queue) + timer.schedule(deadline: .now() + Policy.retryInterval) + timer.setEventHandler { [weak self] in + guard let self else { return } + self.retryTimer?.cancel() + self.retryTimer = nil + self.installSourceOrRetry() + } + timer.resume() + retryTimer = timer + } + + private func readInitialTail(path: String) { + guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else { return } + defer { try? handle.close() } + let endOffset = (try? handle.seekToEnd()) ?? 0 + let startOffset = endOffset > Policy.maxTailBytes ? endOffset - Policy.maxTailBytes : 0 + do { + try handle.seek(toOffset: startOffset) + } catch { + readOffset = endOffset + return + } + var data = handle.readDataToEndOfFile() + if startOffset > 0, let newline = data.firstIndex(of: 0x0A) { + data.removeSubrange(0...newline) + } + readOffset = endOffset + process(data: data) + } + + private func readIncremental(path: String) { + guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else { + transcriptPath = nil + scheduleRetry() + return + } + defer { try? handle.close() } + let endOffset = (try? handle.seekToEnd()) ?? 0 + if readOffset > endOffset { + readOffset = 0 + pendingData.removeAll(keepingCapacity: false) + } + do { + try handle.seek(toOffset: readOffset) + } catch { + readOffset = endOffset + return + } + let data = handle.readDataToEndOfFile() + readOffset = endOffset + process(data: data) + } + + private func process(data: Data) { + guard !data.isEmpty else { return } + pendingData.append(data) + while let newline = pendingData.firstIndex(of: 0x0A) { + let lineData = pendingData[.. Bool { + guard let requestTurnId = Self.normalizedValue(request.turnId) else { return true } + return Self.firstString(in: payload, keys: ["turn_id", "turnId"]) == requestTurnId + } + + private func userInputEventCandidate(from payload: [String: Any]) -> UserInputCandidate? { + guard turnMatches(payload: payload) || sawRelevantTurn else { return nil } + return userInputCandidate(from: payload, payloadTurnId: Self.firstString(in: payload, keys: ["turn_id", "turnId"])) + } + + private func userInputFunctionCallCandidate(from payload: [String: Any]) -> UserInputCandidate? { + guard (payload["type"] as? String) == "function_call", + (payload["name"] as? String) == "request_user_input" else { + return nil + } + let arguments = Self.codexFunctionCallArgumentsObject(from: payload) + let payloadTurnId = Self.firstString(in: payload, keys: ["turn_id", "turnId"]) + ?? arguments.flatMap { Self.firstString(in: $0, keys: ["turn_id", "turnId"]) } + if let requestTurnId = Self.normalizedValue(request.turnId) { + if let payloadTurnId { + guard payloadTurnId == requestTurnId else { return nil } + } else { + guard sawRelevantTurn else { return nil } + } + } + return userInputCandidate( + from: arguments ?? payload, + payloadTurnId: payloadTurnId, + fallbackCallId: Self.firstString(in: payload, keys: ["call_id", "callId"]) + ) + } + + private func userInputCandidate( + from payload: [String: Any], + payloadTurnId: String?, + fallbackCallId: String? = nil + ) -> UserInputCandidate? { + let question = Self.userInputQuestionText(from: payload) + let requestTurnId = Self.normalizedValue(request.turnId) + let rawCallId = Self.firstString(in: payload, keys: ["call_id", "callId"]) ?? fallbackCallId + let callId = rawCallId?.trimmingCharacters(in: .whitespacesAndNewlines) + ?? "\(payloadTurnId ?? requestTurnId ?? "session"):\(question ?? "request_user_input")" + guard !publishedUserInputCallIds.contains(callId) else { return nil } + return UserInputCandidate(callId: callId, question: question) + } + + private func publishUserInput(_ userInput: UserInputCandidate) { + publishedUserInputCallIds.insert(userInput.callId) + let body = userInput.question ?? String( + localized: "agent.codex.input.body.needsInput", + defaultValue: "Codex is asking a question" + ) + onEvent(.userInput(request: request, body: body)) + } + + private func publishFailure(_ failure: FailureCandidate) { + onEvent(.failure(request: request, summary: Self.summarizeFailure(failure))) + } + + private func transcriptLineHasAssistantMessage(payload: [String: Any]) -> Bool { + guard (payload["type"] as? String) == "message", + (payload["role"] as? String) == "assistant", + let content = payload["content"] as? [[String: Any]] else { + return false + } + return content.contains { block in + guard let text = block["text"] as? String else { return false } + return !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + } + + private func findTranscriptPath() -> String? { + let normalizedSessionId = request.sessionId.trimmingCharacters(in: .whitespacesAndNewlines) + guard !normalizedSessionId.isEmpty else { return nil } + let codexHome = Self.normalizedValue(request.codexHome) ?? "~/.codex" + let sessionsURL = URL(fileURLWithPath: NSString(string: codexHome).expandingTildeInPath, isDirectory: true) + .appendingPathComponent("sessions", isDirectory: true) + let fileManager = FileManager.default + var newest: URL? + var newestModificationDate: Date? + for directoryURL in Self.recentSessionDirectories(sessionsURL: sessionsURL, fileManager: fileManager) { + guard let urls = try? fileManager.contentsOfDirectory( + at: directoryURL, + includingPropertiesForKeys: [.contentModificationDateKey], + options: [.skipsHiddenFiles] + ) else { + continue + } + for url in urls { + guard url.pathExtension == "jsonl", + url.lastPathComponent.contains(normalizedSessionId) else { + continue + } + let modificationDate = (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast + if newest == nil || modificationDate > (newestModificationDate ?? .distantPast) { + newest = url + newestModificationDate = modificationDate + } + } + } + return newest?.path + } + + private static func recentSessionDirectories(sessionsURL: URL, fileManager: FileManager) -> [URL] { + var directories: [URL] = [] + var seenPaths = Set() + + func appendIfDirectory(_ url: URL) { + guard seenPaths.insert(url.path).inserted else { return } + var isDirectory: ObjCBool = false + guard fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory), + isDirectory.boolValue else { + return + } + directories.append(url) + } + + appendIfDirectory(sessionsURL) + var utcCalendar = Calendar(identifier: .gregorian) + utcCalendar.timeZone = TimeZone(secondsFromGMT: 0) ?? .current + for calendar in [Calendar.current, utcCalendar] { + for dayOffset in -14...1 { + guard let date = calendar.date(byAdding: .day, value: dayOffset, to: Date.now) else { continue } + let components = calendar.dateComponents([.year, .month, .day], from: date) + guard let year = components.year, + let month = components.month, + let day = components.day else { + continue + } + appendIfDirectory( + sessionsURL + .appendingPathComponent(String(format: "%04d", year), isDirectory: true) + .appendingPathComponent(String(format: "%02d", month), isDirectory: true) + .appendingPathComponent(String(format: "%02d", day), isDirectory: true) + ) + } + } + return directories + } + + private static func failureCandidate( + from object: [String: Any], + isStreamError: Bool, + requireFailureSignal: Bool = true + ) -> FailureCandidate? { + let message = firstString(in: object, keys: ["message", "error", "body", "text", "description"]) + let additionalDetails = hookStringValue(object["additional_details"] ?? object["additionalDetails"]) + let codexErrorInfo = hookStringValue(object["codex_error_info"] ?? object["codexErrorInfo"]) + let eventType = firstString(in: object, keys: ["type", "kind"])?.lowercased() + let typedFailure = eventType == "error" || eventType == "stream_error" + let hasExplicitErrorField = object["error"].map { !($0 is NSNull) } ?? false + let signal = [message, additionalDetails, codexErrorInfo] + .compactMap { $0 } + .joined(separator: " ") + .lowercased() + guard !requireFailureSignal || + typedFailure || + hasExplicitErrorField || + codexErrorInfo != nil || + signal.contains("error") || + signal.contains("failed") || + signal.contains("exception") || + signal.contains("usage limit") || + signal.contains("rate limit") || + signal.contains("stream disconnected") || + signal.contains("connection") || + signal.contains("unauthorized") else { + return nil + } + return FailureCandidate( + message: message ?? additionalDetails ?? codexErrorInfo ?? String( + localized: "agent.codex.error.defaultMessage", + defaultValue: "Codex reported an error" + ), + codexErrorInfo: codexErrorInfo, + additionalDetails: additionalDetails, + isStreamError: isStreamError || eventType == "stream_error" + ) + } + + private static func summarizeFailure(_ candidate: FailureCandidate) -> CodexTranscriptFailureSummary { + let signal = [ + candidate.message, + candidate.codexErrorInfo, + candidate.additionalDetails, + candidate.isStreamError ? "stream_error" : nil + ] + .compactMap { $0 } + .joined(separator: " ") + .lowercased() + + let subtitle: String + let statusValue: String + if signal.contains("usage_limit") || + signal.contains("usage limit") || + signal.contains("rate limit") || + signal.contains("quota") { + subtitle = String(localized: "agent.codex.error.subtitle.rateLimit", defaultValue: "Rate limit") + statusValue = String(localized: "agent.codex.error.status.rateLimit", defaultValue: "Codex rate limit") + } else if signal.contains("unauthorized") || + signal.contains("auth") || + signal.contains("login") || + signal.contains("api key") { + subtitle = String(localized: "agent.codex.error.subtitle.auth", defaultValue: "Auth error") + statusValue = String(localized: "agent.codex.error.status.auth", defaultValue: "Codex auth error") + } else if candidate.isStreamError || + signal.contains("network") || + signal.contains("connection") || + signal.contains("stream disconnected") || + signal.contains("timed out") { + subtitle = String(localized: "agent.codex.error.subtitle.network", defaultValue: "Network error") + statusValue = String(localized: "agent.codex.error.status.network", defaultValue: "Codex network error") + } else { + subtitle = String(localized: "agent.codex.error.subtitle.generic", defaultValue: "Error") + statusValue = String(localized: "agent.codex.error.status.generic", defaultValue: "Codex error") + } + + let detail = [candidate.message, candidate.codexErrorInfo, candidate.additionalDetails] + .compactMap { normalizedValue($0).map(normalizedSingleLine) } + .first { !$0.isEmpty } ?? candidate.message + return CodexTranscriptFailureSummary( + statusValue: statusValue, + subtitle: subtitle, + body: truncate(detail, maxLength: 220) + ) + } + + private static func codexFunctionCallArgumentsObject(from payload: [String: Any]) -> [String: Any]? { + if let arguments = payload["arguments"] as? [String: Any] { + return arguments + } + guard let rawArguments = payload["arguments"] as? String, + let data = rawArguments.data(using: .utf8), + let arguments = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { + return nil + } + return arguments + } + + private static func userInputQuestionText(from payload: [String: Any]) -> String? { + guard let questions = payload["questions"] as? [[String: Any]] else { + return nil + } + for question in questions { + let text = firstString(in: question, keys: ["question", "header", "id"]) + let normalized = text.map(normalizedSingleLine)?.trimmingCharacters(in: .whitespacesAndNewlines) + if let normalized, !normalized.isEmpty { + return truncate(normalized, maxLength: 220) + } + } + return nil + } + + private static func hookStringValue(_ rawValue: Any?) -> String? { + guard let rawValue else { return nil } + if rawValue is NSNull { return nil } + if let value = rawValue as? String { + return normalizedValue(value) + } + if let array = rawValue as? [Any] { + let joined = array.compactMap(hookStringValue).joined(separator: " ") + return normalizedValue(joined) + } + if let dict = rawValue as? [String: Any] { + let joined = dict.keys.sorted().compactMap { hookStringValue(dict[$0]) }.joined(separator: " ") + return normalizedValue(joined) + } + return normalizedValue(String(describing: rawValue)) + } + + private static func firstString(in object: [String: Any], keys: [String]) -> String? { + for key in keys { + if let value = hookStringValue(object[key]) { + return value + } + } + return nil + } + + private static func normalizedValue(_ value: String?) -> String? { + let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed?.isEmpty == false ? trimmed : nil + } + + private static func normalizedSingleLine(_ value: String) -> String { + value + .replacingOccurrences(of: "\r\n", with: "\n") + .replacingOccurrences(of: "\r", with: "\n") + .split(whereSeparator: \.isNewline) + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + .joined(separator: " ") + } + + private static func truncate(_ value: String, maxLength: Int) -> String { + guard value.count > maxLength else { return value } + return String(value.prefix(maxLength - 3)) + "..." + } + } +} + /// Unix socket-based controller for programmatic terminal control /// Allows automated testing and external control of terminal tabs @MainActor @@ -2546,6 +3231,11 @@ class TerminalController { case "feed.list": return v2Result(id: id, self.v2FeedList(params: params)) + // Agent runtime hooks + case "agent.codex_transcript_monitor.start": + return v2Result(id: id, self.v2CodexTranscriptMonitorStart(params: params)) + case "agent.codex_transcript_monitor.stop": + return v2Result(id: id, self.v2CodexTranscriptMonitorStop(params: params)) // Surfaces / input case "surface.list": @@ -2954,6 +3644,8 @@ class TerminalController { "feed.exit_plan.reply", "feed.jump", "feed.list", + "agent.codex_transcript_monitor.start", + "agent.codex_transcript_monitor.stop", "surface.list", "surface.current", "surface.focus", @@ -8581,6 +9273,107 @@ class TerminalController { ]) } + // MARK: - V2 Agent Runtime Methods + + private func v2CodexTranscriptMonitorStart(params: [String: Any]) -> V2CallResult { + guard let workspaceId = v2UUID(params, "workspace_id") else { + return .err(code: "invalid_params", message: "agent.codex_transcript_monitor.start requires workspace_id", data: nil) + } + guard let sessionId = v2String(params, "session_id") else { + return .err(code: "invalid_params", message: "agent.codex_transcript_monitor.start requires session_id", data: nil) + } + let surfaceId = v2UUID(params, "surface_id") + + guard let workspace = tabForSidebarMutation(id: workspaceId) else { + return .err(code: "not_found", message: "Workspace not found", data: ["workspace_id": workspaceId.uuidString]) + } + if let surfaceId, workspace.panels[surfaceId] == nil { + return .err(code: "not_found", message: "Surface not found", data: ["surface_id": surfaceId.uuidString]) + } + + CodexTranscriptMonitorRegistry.shared.start( + CodexTranscriptMonitorRequest( + workspaceId: workspaceId, + surfaceId: surfaceId, + sessionId: sessionId, + turnId: v2String(params, "turn_id"), + transcriptPath: v2RawString(params, "transcript_path"), + codexHome: v2RawString(params, "codex_home") + ) + ) + return .ok(["started": true]) + } + + private func v2CodexTranscriptMonitorStop(params: [String: Any]) -> V2CallResult { + guard let sessionId = v2String(params, "session_id") else { + return .err(code: "invalid_params", message: "agent.codex_transcript_monitor.stop requires session_id", data: nil) + } + CodexTranscriptMonitorRegistry.shared.stop( + sessionId: sessionId, + turnId: v2String(params, "turn_id") + ) + return .ok(["stopped": true]) + } + + fileprivate func handleCodexTranscriptMonitorEvent(_ event: CodexTranscriptMonitorEvent) { + let request: CodexTranscriptMonitorRequest + switch event { + case .userInput(let eventRequest, _), .failure(let eventRequest, _): + request = eventRequest + } + + guard let tab = tabForSidebarMutation(id: request.workspaceId) else { + CodexTranscriptMonitorRegistry.shared.stop(sessionId: request.sessionId, turnId: request.turnId) + return + } + if let surfaceId = request.surfaceId, tab.panels[surfaceId] == nil { + CodexTranscriptMonitorRegistry.shared.stop(sessionId: request.sessionId, turnId: request.turnId) + return + } + + let title = String(localized: "sessionIndex.agent.codex", defaultValue: "Codex") + switch event { + case .userInput(_, let body): + let subtitle = String(localized: "agent.codex.input.subtitle.waiting", defaultValue: "Waiting") + if let surfaceId = request.surfaceId { + AppDelegate.shared?.notificationStore?.addNotification( + tabId: request.workspaceId, + surfaceId: surfaceId, + title: title, + subtitle: subtitle, + body: body + ) + } + tab.statusEntries["codex"] = SidebarStatusEntry( + key: "codex", + value: String(localized: "agent.codex.input.status.needsInput", defaultValue: "Codex needs input"), + icon: "bell.fill", + color: "#4C8DFF", + priority: 100, + timestamp: Date.now + ) + + case .failure(_, let summary): + if let surfaceId = request.surfaceId { + AppDelegate.shared?.notificationStore?.addNotification( + tabId: request.workspaceId, + surfaceId: surfaceId, + title: title, + subtitle: summary.subtitle, + body: summary.body + ) + } + tab.statusEntries["codex"] = SidebarStatusEntry( + key: "codex", + value: summary.statusValue, + icon: "exclamationmark.triangle.fill", + color: "#FF453A", + priority: 100, + timestamp: Date.now + ) + } + } + // MARK: - V2 App Focus Methods private func v2AppFocusOverride(params: [String: Any]) -> V2CallResult { @@ -16896,12 +17689,7 @@ class TerminalController { result = parsed.options["tab"] != nil ? "ERROR: Tab not found" : "ERROR: No tab selected" return } - tab.logEntries.append(SidebarLogEntry(message: message, level: level, source: source, timestamp: Date())) - 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) - } + tab.enqueueSidebarLog(message: message, level: level, source: source) } return result } @@ -16913,7 +17701,7 @@ class TerminalController { result = "ERROR: Tab not found" return } - tab.logEntries.removeAll() + tab.clearSidebarLogEntries() } return result } @@ -16937,6 +17725,7 @@ class TerminalController { result = parsed.options["tab"] != nil ? "ERROR: Tab not found" : "ERROR: No tab selected" return } + tab.flushPendingSidebarLogEntries() if tab.logEntries.isEmpty { result = "No log entries" return diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index eb2b909e6b58..e190d0ec2983 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -164,6 +164,7 @@ extension Workspace { includeScrollback: Bool, restorableAgentIndex: RestorableAgentSessionIndex? = nil ) -> SessionWorkspaceSnapshot { + flushPendingSidebarLogEntries() let tree = bonsplitController.treeSnapshot() let layout = sessionLayoutSnapshot(from: tree) @@ -289,14 +290,14 @@ extension Workspace { agentPIDPanelIdsByKey.removeAll() agentPIDKeysByPanelId.removeAll() agentListeningPorts.removeAll() - logEntries = snapshot.logEntries.map { entry in + setSidebarLogEntries(snapshot.logEntries.map { entry in SidebarLogEntry( message: entry.message, level: SidebarLogLevel(rawValue: entry.level) ?? .info, source: entry.source, timestamp: Date(timeIntervalSince1970: entry.timestamp) ) - } + }) progress = snapshot.progress.map { SidebarProgressState(value: $0.value, label: $0.label) } gitBranch = snapshot.gitBranch.map { SidebarGitBranchState(branch: $0.branch, isDirty: $0.isDirty) } @@ -6617,6 +6618,51 @@ struct SidebarLogEntry: Equatable { let timestamp: Date } +private struct SidebarLogRingBuffer { + private var storage: [SidebarLogEntry?] + private var head = 0 + private(set) var count = 0 + private(set) var limit: Int + + init(limit: Int) { + let normalizedLimit = max(1, min(500, limit)) + self.limit = normalizedLimit + self.storage = Array(repeating: nil, count: normalizedLimit) + } + + mutating func replaceAll(_ entries: [SidebarLogEntry], limit: Int) { + self = SidebarLogRingBuffer(limit: limit) + for entry in entries.suffix(self.limit) { + append(entry) + } + } + + mutating func append(_ entry: SidebarLogEntry) { + guard !storage.isEmpty else { return } + let index = (head + count) % storage.count + if count == storage.count { + storage[head] = entry + head = (head + 1) % storage.count + } else { + storage[index] = entry + count += 1 + } + } + + mutating func removeAll() { + storage = Array(repeating: nil, count: limit) + head = 0 + count = 0 + } + + func entries() -> [SidebarLogEntry] { + guard count > 0 else { return [] } + return (0..? private func sidebarObservationSignal( _ publisher: Published.Publisher @@ -7331,11 +7382,18 @@ final class Workspace: Identifiable, ObservableObject { lazy var sidebarImmediateObservationPublisher: AnyPublisher = { let publishers: [AnyPublisher] = [ - sidebarObservationSignal($title), - sidebarObservationSignal($customDescription), sidebarObservationSignal($isPinned), sidebarObservationSignal($customColor), sidebarObservationSignal($terminalScrollBarHidden), + ] + + return Publishers.MergeMany(publishers).eraseToAnyPublisher() + }() + + lazy var sidebarAgentObservationPublisher: AnyPublisher = { + let publishers: [AnyPublisher] = [ + sidebarObservationSignal($title), + sidebarObservationSignal($customDescription), sidebarObservationSignal($latestConversationMessage), ] @@ -7872,6 +7930,7 @@ final class Workspace: Identifiable, ObservableObject { } activeRemoteSessionControllerID = nil remoteSessionController?.stop() + sidebarLogFlushTask?.cancel() } func refreshSplitButtonTooltips() { @@ -8809,7 +8868,7 @@ final class Workspace: Identifiable, ObservableObject { agentPIDKeysByPanelId.removeAll() agentListeningPorts.removeAll() latestConversationMessage = nil - logEntries.removeAll() + clearSidebarLogEntries() progress = nil gitBranch = nil panelGitBranches.removeAll() @@ -9680,7 +9739,7 @@ final class Workspace: Identifiable, ObservableObject { let fingerprint = "connection:\(trimmedDetail)" if remoteLastErrorFingerprint != fingerprint { remoteLastErrorFingerprint = fingerprint - appendSidebarLog( + enqueueSidebarLog( message: "\(statusPrefix) (\(target)): \(trimmedDetail)", level: .error, source: logSource @@ -9715,7 +9774,7 @@ final class Workspace: Identifiable, ObservableObject { let fingerprint = "daemon:\(trimmedDetail)" guard remoteLastDaemonErrorFingerprint != fingerprint else { return } remoteLastDaemonErrorFingerprint = fingerprint - appendSidebarLog( + enqueueSidebarLog( message: "Remote daemon error (\(target)): \(trimmedDetail)", level: .error, source: "remote-daemon" @@ -9781,7 +9840,7 @@ final class Workspace: Identifiable, ObservableObject { let fingerprint = conflicts.map(String.init).joined(separator: ",") guard remoteLastPortConflictFingerprint != fingerprint else { return } remoteLastPortConflictFingerprint = fingerprint - appendSidebarLog( + enqueueSidebarLog( message: "Port conflicts while forwarding \(target): \(conflictsList)", level: .warning, source: "remote-forward" @@ -9795,15 +9854,57 @@ final class Workspace: Identifiable, ObservableObject { remoteDetectedSurfaceIds.removeAll() } - private func appendSidebarLog(message: String, level: SidebarLogLevel, source: String?) { + private static func cachedSidebarLogEntryLimit() -> Int { + let configuredLimit = UserDefaults.standard.object(forKey: "sidebarMaxLogEntries") as? Int ?? 50 + return max(1, min(500, configuredLimit)) + } + + func enqueueSidebarLog(message: String, level: SidebarLogLevel, source: String?) { let trimmed = message.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { return } - logEntries.append(SidebarLogEntry(message: trimmed, level: level, source: source, timestamp: Date())) - let configuredLimit = UserDefaults.standard.object(forKey: "sidebarMaxLogEntries") as? Int ?? 50 - let limit = max(1, min(500, configuredLimit)) - if logEntries.count > limit { - logEntries.removeFirst(logEntries.count - limit) + pendingSidebarLogEntries.append(SidebarLogEntry(message: trimmed, level: level, source: source, timestamp: Date())) + scheduleSidebarLogFlush() + } + + func clearSidebarLogEntries() { + sidebarLogFlushTask?.cancel() + sidebarLogFlushTask = nil + pendingSidebarLogEntries.removeAll(keepingCapacity: false) + sidebarLogBuffer.removeAll() + logEntries.removeAll() + } + + private func setSidebarLogEntries(_ entries: [SidebarLogEntry]) { + sidebarLogFlushTask?.cancel() + sidebarLogFlushTask = nil + pendingSidebarLogEntries.removeAll(keepingCapacity: false) + sidebarLogBuffer.replaceAll(entries, limit: sidebarLogEntryLimit) + logEntries = sidebarLogBuffer.entries() + } + + private func scheduleSidebarLogFlush() { + guard sidebarLogFlushTask == nil else { return } + sidebarLogFlushTask = Task { @MainActor [weak self] in + do { + try await Task.sleep(for: Self.sidebarLogFlushDelay) + } catch { + return + } + guard !Task.isCancelled else { return } + self?.flushPendingSidebarLogEntries() + } + } + + func flushPendingSidebarLogEntries() { + sidebarLogFlushTask?.cancel() + sidebarLogFlushTask = nil + guard !pendingSidebarLogEntries.isEmpty else { return } + let entries = pendingSidebarLogEntries + pendingSidebarLogEntries.removeAll(keepingCapacity: true) + for entry in entries { + sidebarLogBuffer.append(entry) } + logEntries = sidebarLogBuffer.entries() } // MARK: - Panel Operations From 719b62c3ea0bb3985cb809a916bb3bac4ba4eb2a Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 14:33:11 -0700 Subject: [PATCH 02/25] fix: order codex monitor start arguments --- CLI/cmux.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 3ce0e86e71f6..1a42734cce26 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -20116,9 +20116,9 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { requestCodexTranscriptMonitorStart( sessionId: sessionId, turnId: input.turnId, + transcriptPath: normalizedHookValue(input.transcriptPath), workspaceId: workspaceId, surfaceId: surfaceId, - transcriptPath: normalizedHookValue(input.transcriptPath), env: env, client: client, telemetry: telemetry From 357bbb3d40263970103acfcaaa6e145e5b30fb2e Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 14:36:29 -0700 Subject: [PATCH 03/25] fix: qualify codex monitor failure helper --- Sources/TerminalController.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 3b7eadc57cf2..03777625e184 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -351,7 +351,7 @@ private final class CodexTranscriptMonitorRegistry: @unchecked Sendable { case "error", "stream_error": updateRelevantTurn(payload: payload, onlyWhenMatching: true) guard turnMatches(payload: payload) || sawRelevantTurn else { return } - if let failure = failureCandidate( + if let failure = Self.failureCandidate( from: payload, isStreamError: eventType == "stream_error", requireFailureSignal: false From 0079eb1cd6efa8e453263f59a425c0a803974ec8 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 14:46:49 -0700 Subject: [PATCH 04/25] fix: clean up codex monitors and sidebar debounce --- Sources/TabManager.swift | 1 + Sources/TerminalController.swift | 21 ++++++++++++++++---- Sources/Workspace.swift | 33 ++++++++++++++++---------------- 3 files changed, 34 insertions(+), 21 deletions(-) diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 6cfe074cdb16..5334e32869c0 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -4196,6 +4196,7 @@ class TabManager: ObservableObject { sidebarSelectedWorkspaceIds.remove(workspace.id) AppDelegate.shared?.notificationStore?.clearNotifications(forTabId: workspace.id) + TerminalController.shared.stopCodexTranscriptMonitors(forWorkspaceId: workspace.id) workspace.teardownAllPanels() workspace.teardownRemoteConnection() unwireClosedBrowserTracking(for: workspace) diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 03777625e184..b7949540cdfe 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -38,6 +38,7 @@ fileprivate struct CodexTranscriptFailureSummary: Sendable { fileprivate enum CodexTranscriptMonitorEvent: Sendable { case userInput(request: CodexTranscriptMonitorRequest, body: String) case failure(request: CodexTranscriptMonitorRequest, summary: CodexTranscriptFailureSummary) + case completion(request: CodexTranscriptMonitorRequest) } private final class CodexTranscriptMonitorRegistry: @unchecked Sendable { @@ -170,8 +171,11 @@ private final class CodexTranscriptMonitorRegistry: @unchecked Sendable { deadlineTimer = nil } - private func finish() { + private func finish(publishCompletion: Bool = false) { guard !finished else { return } + if publishCompletion { + onEvent(.completion(request: request)) + } cancel() onFinish(request.sessionId, self) } @@ -366,7 +370,7 @@ private final class CodexTranscriptMonitorRegistry: @unchecked Sendable { if let lastMessage = payload["last_agent_message"] as? String, !lastMessage.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { sawAssistantMessage = true - finish() + finish(publishCompletion: true) } else if !sawAssistantMessage { publishFailure( FailureCandidate( @@ -381,7 +385,7 @@ private final class CodexTranscriptMonitorRegistry: @unchecked Sendable { ) finish() } else { - finish() + finish(publishCompletion: true) } default: @@ -9315,10 +9319,14 @@ class TerminalController { return .ok(["stopped": true]) } + func stopCodexTranscriptMonitors(forWorkspaceId workspaceId: UUID) { + CodexTranscriptMonitorRegistry.shared.stopWorkspace(workspaceId) + } + fileprivate func handleCodexTranscriptMonitorEvent(_ event: CodexTranscriptMonitorEvent) { let request: CodexTranscriptMonitorRequest switch event { - case .userInput(let eventRequest, _), .failure(let eventRequest, _): + case .userInput(let eventRequest, _), .failure(let eventRequest, _), .completion(let eventRequest): request = eventRequest } @@ -9371,6 +9379,11 @@ class TerminalController { priority: 100, timestamp: Date.now ) + + case .completion: + if tab.statusEntries["codex"]?.icon == "bell.fill" { + tab.statusEntries.removeValue(forKey: "codex") + } } } diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index e190d0ec2983..cb4cef7b2f5b 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -7175,7 +7175,7 @@ final class Workspace: Identifiable, ObservableObject { static let terminalScrollBarHiddenDidChangeNotification = Notification.Name( "cmux.workspaceTerminalScrollBarHiddenDidChange" ) - private static let sidebarLogFlushDelay: Duration = .milliseconds(50) + private static let sidebarLogFlushDelay: DispatchTimeInterval = .milliseconds(50) let id: UUID @Published var title: String @@ -7368,7 +7368,7 @@ final class Workspace: Identifiable, ObservableObject { private var sidebarLogEntryLimit = Workspace.cachedSidebarLogEntryLimit() private lazy var sidebarLogBuffer = SidebarLogRingBuffer(limit: sidebarLogEntryLimit) private var pendingSidebarLogEntries: [SidebarLogEntry] = [] - private var sidebarLogFlushTask: Task? + private var sidebarLogFlushTimer: DispatchSourceTimer? private func sidebarObservationSignal( _ publisher: Published.Publisher @@ -7930,7 +7930,8 @@ final class Workspace: Identifiable, ObservableObject { } activeRemoteSessionControllerID = nil remoteSessionController?.stop() - sidebarLogFlushTask?.cancel() + sidebarLogFlushTimer?.cancel() + TerminalController.shared.stopCodexTranscriptMonitors(forWorkspaceId: id) } func refreshSplitButtonTooltips() { @@ -9867,37 +9868,35 @@ final class Workspace: Identifiable, ObservableObject { } func clearSidebarLogEntries() { - sidebarLogFlushTask?.cancel() - sidebarLogFlushTask = nil + sidebarLogFlushTimer?.cancel() + sidebarLogFlushTimer = nil pendingSidebarLogEntries.removeAll(keepingCapacity: false) sidebarLogBuffer.removeAll() logEntries.removeAll() } private func setSidebarLogEntries(_ entries: [SidebarLogEntry]) { - sidebarLogFlushTask?.cancel() - sidebarLogFlushTask = nil + sidebarLogFlushTimer?.cancel() + sidebarLogFlushTimer = nil pendingSidebarLogEntries.removeAll(keepingCapacity: false) sidebarLogBuffer.replaceAll(entries, limit: sidebarLogEntryLimit) logEntries = sidebarLogBuffer.entries() } private func scheduleSidebarLogFlush() { - guard sidebarLogFlushTask == nil else { return } - sidebarLogFlushTask = Task { @MainActor [weak self] in - do { - try await Task.sleep(for: Self.sidebarLogFlushDelay) - } catch { - return - } - guard !Task.isCancelled else { return } + guard sidebarLogFlushTimer == nil else { return } + let timer = DispatchSource.makeTimerSource(queue: .main) + timer.schedule(deadline: .now() + Self.sidebarLogFlushDelay) + timer.setEventHandler { [weak self] in self?.flushPendingSidebarLogEntries() } + sidebarLogFlushTimer = timer + timer.resume() } func flushPendingSidebarLogEntries() { - sidebarLogFlushTask?.cancel() - sidebarLogFlushTask = nil + sidebarLogFlushTimer?.cancel() + sidebarLogFlushTimer = nil guard !pendingSidebarLogEntries.isEmpty else { return } let entries = pendingSidebarLogEntries pendingSidebarLogEntries.removeAll(keepingCapacity: true) From 8ca6cc9fd900d3ffeeaad5af282daa33cffee13b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 15:07:45 -0700 Subject: [PATCH 05/25] fix: make codex monitor cleanup nonisolated --- Sources/TabManager.swift | 2 +- Sources/TerminalController.swift | 2 +- Sources/Workspace.swift | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 5334e32869c0..b73ee8ea8704 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -4196,7 +4196,7 @@ class TabManager: ObservableObject { sidebarSelectedWorkspaceIds.remove(workspace.id) AppDelegate.shared?.notificationStore?.clearNotifications(forTabId: workspace.id) - TerminalController.shared.stopCodexTranscriptMonitors(forWorkspaceId: workspace.id) + TerminalController.stopCodexTranscriptMonitors(forWorkspaceId: workspace.id) workspace.teardownAllPanels() workspace.teardownRemoteConnection() unwireClosedBrowserTracking(for: workspace) diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index b7949540cdfe..9fdc9a5d4a55 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -9319,7 +9319,7 @@ class TerminalController { return .ok(["stopped": true]) } - func stopCodexTranscriptMonitors(forWorkspaceId workspaceId: UUID) { + nonisolated static func stopCodexTranscriptMonitors(forWorkspaceId workspaceId: UUID) { CodexTranscriptMonitorRegistry.shared.stopWorkspace(workspaceId) } diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index cb4cef7b2f5b..fcdba9c2bd28 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -7931,7 +7931,7 @@ final class Workspace: Identifiable, ObservableObject { activeRemoteSessionControllerID = nil remoteSessionController?.stop() sidebarLogFlushTimer?.cancel() - TerminalController.shared.stopCodexTranscriptMonitors(forWorkspaceId: id) + TerminalController.stopCodexTranscriptMonitors(forWorkspaceId: id) } func refreshSplitButtonTooltips() { From 111e7c33b7bdb51178e05b2fa94f40f8ba5fa4ce Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 15:16:03 -0700 Subject: [PATCH 06/25] fix: hop sidebar log timer onto main actor --- Sources/Workspace.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index fcdba9c2bd28..6ed0fedf324f 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -6650,7 +6650,6 @@ private struct SidebarLogRingBuffer { } mutating func removeAll() { - storage = Array(repeating: nil, count: limit) head = 0 count = 0 } @@ -9888,7 +9887,9 @@ final class Workspace: Identifiable, ObservableObject { let timer = DispatchSource.makeTimerSource(queue: .main) timer.schedule(deadline: .now() + Self.sidebarLogFlushDelay) timer.setEventHandler { [weak self] in - self?.flushPendingSidebarLogEntries() + Task { @MainActor in + self?.flushPendingSidebarLogEntries() + } } sidebarLogFlushTimer = timer timer.resume() From 70fa2f342bd534fbcfa2798bb7a2112d786f1175 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 15:16:34 -0700 Subject: [PATCH 07/25] fix: assume main actor for sidebar log timer --- Sources/Workspace.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 6ed0fedf324f..72f9dc2b7088 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -9887,8 +9887,9 @@ final class Workspace: Identifiable, ObservableObject { let timer = DispatchSource.makeTimerSource(queue: .main) timer.schedule(deadline: .now() + Self.sidebarLogFlushDelay) timer.setEventHandler { [weak self] in - Task { @MainActor in - self?.flushPendingSidebarLogEntries() + guard let self else { return } + MainActor.assumeIsolated { + self.flushPendingSidebarLogEntries() } } sidebarLogFlushTimer = timer From a11ce49b3ff2ef29d36956e9b79212b6f845fe0a Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 15:24:58 -0700 Subject: [PATCH 08/25] fix: address codex monitor review feedback --- CLI/cmux.swift | 9 +- GhosttyTabs.xcodeproj/project.pbxproj | 4 + Sources/CodexTranscriptMonitor.swift | 695 ++++++++++++++++++++++++++ Sources/TerminalController.swift | 689 +------------------------ 4 files changed, 705 insertions(+), 692 deletions(-) create mode 100644 Sources/CodexTranscriptMonitor.swift diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 1a42734cce26..e182879255a5 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -18019,14 +18019,15 @@ struct CMUXCLI { client: SocketClient, telemetry: CLISocketSentryTelemetry ) { - guard !sessionId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, - !workspaceId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + let normalizedSessionId = sessionId.trimmingCharacters(in: .whitespacesAndNewlines) + let normalizedWorkspaceId = workspaceId.trimmingCharacters(in: .whitespacesAndNewlines) + guard !normalizedSessionId.isEmpty, !normalizedWorkspaceId.isEmpty else { return } var params: [String: Any] = [ - "workspace_id": workspaceId, - "session_id": sessionId, + "workspace_id": normalizedWorkspaceId, + "session_id": normalizedSessionId, ] if let surfaceId = normalizedHookValue(surfaceId) { params["surface_id"] = surfaceId diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index bfb8b23e6750..a75eaaaae6f0 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -187,6 +187,7 @@ E7E00000000000000000000B /* CmuxLifecycleEventPublishing.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E00000000000000000000C /* CmuxLifecycleEventPublishing.swift */; }; E7E000000000000000000007 /* CmuxEventPublishing.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E000000000000000000008 /* CmuxEventPublishing.swift */; }; A5001007 /* TerminalController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001019 /* TerminalController.swift */; }; + C0DE412700000000000001 /* CodexTranscriptMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE412700000000000002 /* CodexTranscriptMonitor.swift */; }; E7E000000000000000000001 /* CmuxEventStream.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E000000000000000000002 /* CmuxEventStream.swift */; }; E7E000000000000000000009 /* CmuxSocketEventMapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E00000000000000000000A /* CmuxSocketEventMapper.swift */; }; D7AB0000000000000000000B /* TerminalController+MoveTabToNewWorkspace.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB0000000000000000000C /* TerminalController+MoveTabToNewWorkspace.swift */; }; @@ -688,6 +689,7 @@ A5001017 /* ghostty.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ghostty.h; sourceTree = ""; }; A5001018 /* cmux-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "cmux-Bridging-Header.h"; sourceTree = ""; }; A5001019 /* TerminalController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalController.swift; sourceTree = ""; }; + C0DE412700000000000002 /* CodexTranscriptMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitor.swift; sourceTree = ""; }; E7E000000000000000000006 /* CmuxEventBus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxEventBus.swift; sourceTree = ""; }; E7E00000000000000000000E /* CmuxEventLogWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxEventLogWriter.swift; sourceTree = ""; }; E7E00000000000000000000C /* CmuxLifecycleEventPublishing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxLifecycleEventPublishing.swift; sourceTree = ""; }; @@ -1240,6 +1242,7 @@ E7E00000000000000000000C /* CmuxLifecycleEventPublishing.swift */, E7E000000000000000000008 /* CmuxEventPublishing.swift */, A5001019 /* TerminalController.swift */, + C0DE412700000000000002 /* CodexTranscriptMonitor.swift */, E7E000000000000000000002 /* CmuxEventStream.swift */, E7E00000000000000000000A /* CmuxSocketEventMapper.swift */, A5001440A5001440A5001440 /* FileOpenSocketSupport.swift */, @@ -1919,6 +1922,7 @@ E7E00000000000000000000B /* CmuxLifecycleEventPublishing.swift in Sources */, E7E000000000000000000007 /* CmuxEventPublishing.swift in Sources */, A5001007 /* TerminalController.swift in Sources */, + C0DE412700000000000001 /* CodexTranscriptMonitor.swift in Sources */, E7E000000000000000000001 /* CmuxEventStream.swift in Sources */, E7E000000000000000000009 /* CmuxSocketEventMapper.swift in Sources */, A5001441A5001441A5001441 /* FileOpenSocketSupport.swift in Sources */, diff --git a/Sources/CodexTranscriptMonitor.swift b/Sources/CodexTranscriptMonitor.swift new file mode 100644 index 000000000000..a8c6408a286d --- /dev/null +++ b/Sources/CodexTranscriptMonitor.swift @@ -0,0 +1,695 @@ +import Darwin +import Foundation + +struct CodexTranscriptMonitorRequest: Sendable { + let workspaceId: UUID + let surfaceId: UUID? + let sessionId: String + let turnId: String? + let transcriptPath: String? + let codexHome: String? +} + +struct CodexTranscriptFailureSummary: Sendable { + let statusValue: String + let subtitle: String + let body: String +} + +enum CodexTranscriptMonitorEvent: Sendable { + case userInput(request: CodexTranscriptMonitorRequest, body: String) + case failure(request: CodexTranscriptMonitorRequest, summary: CodexTranscriptFailureSummary) + case completion(request: CodexTranscriptMonitorRequest) +} + +// Mutable registry state is confined to `queue`; callers interact through async queue hops. +final class CodexTranscriptMonitorRegistry: @unchecked Sendable { + static let shared = CodexTranscriptMonitorRegistry() + + private let queue = DispatchQueue(label: "com.cmux.codex-transcript-monitor", qos: .utility) + private var monitorsBySessionId: [String: Monitor] = [:] + + private init() {} + + deinit {} + + func start(_ request: CodexTranscriptMonitorRequest) { + queue.async { [weak self] in + guard let self else { return } + let key = request.sessionId + self.monitorsBySessionId[key]?.cancel() + let monitor = Monitor( + request: request, + queue: self.queue, + onEvent: { [weak self] event in self?.publish(event) }, + onFinish: { [weak self] sessionId, monitor in + guard let self else { return } + if self.monitorsBySessionId[sessionId] === monitor { + self.monitorsBySessionId.removeValue(forKey: sessionId) + } + } + ) + self.monitorsBySessionId[key] = monitor + monitor.start() + } + } + + func stop(sessionId: String, turnId: String?) { + queue.async { [weak self] in + guard let self else { return } + if let monitor = self.monitorsBySessionId[sessionId], + turnId == nil || monitor.matches(turnId: turnId) { + monitor.cancel() + self.monitorsBySessionId.removeValue(forKey: sessionId) + } + } + } + + func stopWorkspace(_ workspaceId: UUID) { + queue.async { [weak self] in + guard let self else { return } + let matchingSessionIds = self.monitorsBySessionId.compactMap { sessionId, monitor in + monitor.workspaceId == workspaceId ? sessionId : nil + } + for sessionId in matchingSessionIds { + self.monitorsBySessionId[sessionId]?.cancel() + self.monitorsBySessionId.removeValue(forKey: sessionId) + } + } + } + + private func publish(_ event: CodexTranscriptMonitorEvent) { + Task { @MainActor in + TerminalController.shared.handleCodexTranscriptMonitorEvent(event) + } + } + + private final class Monitor { + private struct FailureCandidate { + let message: String + let codexErrorInfo: String? + let additionalDetails: String? + let isStreamError: Bool + } + + private struct UserInputCandidate { + let callId: String + let question: String? + } + + private enum Policy { + static let maxTailBytes: UInt64 = 512 * 1024 + static let retryInterval: TimeInterval = 1 + static let deadline: TimeInterval = 4 * 60 * 60 + } + + let workspaceId: UUID + + private let request: CodexTranscriptMonitorRequest + private let queue: DispatchQueue + private let onEvent: (CodexTranscriptMonitorEvent) -> Void + private let onFinish: (String, Monitor) -> Void + private var source: DispatchSourceFileSystemObject? + private var retryTimer: DispatchSourceTimer? + private var deadlineTimer: DispatchSourceTimer? + private var transcriptPath: String? + private var readOffset: UInt64 = 0 + private var pendingData = Data() + private var publishedUserInputCallIds = Set() + private var sawRelevantTurn = false + private var sawAssistantMessage = false + private var finished = false + + init( + request: CodexTranscriptMonitorRequest, + queue: DispatchQueue, + onEvent: @escaping (CodexTranscriptMonitorEvent) -> Void, + onFinish: @escaping (String, Monitor) -> Void + ) { + self.request = request + self.queue = queue + self.onEvent = onEvent + self.onFinish = onFinish + self.workspaceId = request.workspaceId + self.transcriptPath = Self.normalizedValue(request.transcriptPath) + self.sawRelevantTurn = Self.normalizedValue(request.turnId) == nil + } + + deinit { + cancel() + } + + func start() { + armDeadline() + installSourceOrRetry() + } + + func matches(turnId: String?) -> Bool { + guard let turnId = Self.normalizedValue(turnId) else { return true } + return Self.normalizedValue(request.turnId) == turnId + } + + func cancel() { + finished = true + source?.cancel() + source = nil + retryTimer?.cancel() + retryTimer = nil + deadlineTimer?.cancel() + deadlineTimer = nil + } + + private func finish(publishCompletion: Bool = false) { + guard !finished else { return } + if publishCompletion { + onEvent(.completion(request: request)) + } + cancel() + onFinish(request.sessionId, self) + } + + private func armDeadline() { + let timer = DispatchSource.makeTimerSource(queue: queue) + timer.schedule(deadline: .now() + Policy.deadline) + timer.setEventHandler { [weak self] in + self?.finish(publishCompletion: true) + } + timer.resume() + deadlineTimer = timer + } + + private func installSourceOrRetry() { + guard !finished else { return } + if transcriptPath == nil { + transcriptPath = findTranscriptPath() + } + guard let path = transcriptPath else { + scheduleRetry() + return + } + installFileSource(path: path) + } + + private func installFileSource(path: String) { + source?.cancel() + source = nil + + let expandedPath = NSString(string: path).expandingTildeInPath + let fd = open(expandedPath, O_EVTONLY) + guard fd >= 0 else { + transcriptPath = nil + scheduleRetry() + return + } + + let newSource = DispatchSource.makeFileSystemObjectSource( + fileDescriptor: fd, + eventMask: [.write, .extend, .delete, .rename], + queue: queue + ) + newSource.setEventHandler { [weak self] in + self?.handleFileEvent() + } + newSource.setCancelHandler { + close(fd) + } + source = newSource + newSource.resume() + readInitialTail(path: expandedPath) + } + + private func handleFileEvent() { + guard !finished, let path = transcriptPath else { return } + let expandedPath = NSString(string: path).expandingTildeInPath + if let eventData = source?.data, + eventData.contains(.delete) || eventData.contains(.rename) { + source?.cancel() + source = nil + transcriptPath = nil + readOffset = 0 + pendingData.removeAll(keepingCapacity: false) + scheduleRetry() + return + } + readIncremental(path: expandedPath) + } + + private func scheduleRetry() { + retryTimer?.cancel() + let timer = DispatchSource.makeTimerSource(queue: queue) + timer.schedule(deadline: .now() + Policy.retryInterval) + timer.setEventHandler { [weak self] in + guard let self else { return } + self.retryTimer?.cancel() + self.retryTimer = nil + self.installSourceOrRetry() + } + timer.resume() + retryTimer = timer + } + + private func readInitialTail(path: String) { + guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else { return } + defer { try? handle.close() } + let endOffset = (try? handle.seekToEnd()) ?? 0 + let startOffset = endOffset > Policy.maxTailBytes ? endOffset - Policy.maxTailBytes : 0 + do { + try handle.seek(toOffset: startOffset) + } catch { + readOffset = endOffset + return + } + var data = handle.readDataToEndOfFile() + if startOffset > 0, let newline = data.firstIndex(of: 0x0A) { + data.removeSubrange(0...newline) + } + readOffset = endOffset + process(data: data) + } + + private func readIncremental(path: String) { + guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else { + transcriptPath = nil + scheduleRetry() + return + } + defer { try? handle.close() } + let endOffset = (try? handle.seekToEnd()) ?? 0 + if readOffset > endOffset { + readOffset = 0 + pendingData.removeAll(keepingCapacity: false) + } + do { + try handle.seek(toOffset: readOffset) + } catch { + readOffset = endOffset + return + } + let data = handle.readDataToEndOfFile() + readOffset = endOffset + process(data: data) + } + + private func process(data: Data) { + guard !data.isEmpty else { return } + pendingData.append(data) + while let newline = pendingData.firstIndex(of: 0x0A) { + let lineData = pendingData[.. Bool { + guard let requestTurnId = Self.normalizedValue(request.turnId) else { return true } + return Self.firstString(in: payload, keys: ["turn_id", "turnId"]) == requestTurnId + } + + private func userInputEventCandidate(from payload: [String: Any]) -> UserInputCandidate? { + guard turnMatches(payload: payload) || sawRelevantTurn else { return nil } + return userInputCandidate(from: payload, payloadTurnId: Self.firstString(in: payload, keys: ["turn_id", "turnId"])) + } + + private func userInputFunctionCallCandidate(from payload: [String: Any]) -> UserInputCandidate? { + guard (payload["type"] as? String) == "function_call", + (payload["name"] as? String) == "request_user_input" else { + return nil + } + let arguments = Self.codexFunctionCallArgumentsObject(from: payload) + let payloadTurnId = Self.firstString(in: payload, keys: ["turn_id", "turnId"]) + ?? arguments.flatMap { Self.firstString(in: $0, keys: ["turn_id", "turnId"]) } + if let requestTurnId = Self.normalizedValue(request.turnId) { + if let payloadTurnId { + guard payloadTurnId == requestTurnId else { return nil } + } else { + guard sawRelevantTurn else { return nil } + } + } + return userInputCandidate( + from: arguments ?? payload, + payloadTurnId: payloadTurnId, + fallbackCallId: Self.firstString(in: payload, keys: ["call_id", "callId"]) + ) + } + + private func userInputCandidate( + from payload: [String: Any], + payloadTurnId: String?, + fallbackCallId: String? = nil + ) -> UserInputCandidate? { + let question = Self.userInputQuestionText(from: payload) + let requestTurnId = Self.normalizedValue(request.turnId) + let rawCallId = Self.firstString(in: payload, keys: ["call_id", "callId"]) ?? fallbackCallId + let callId = rawCallId?.trimmingCharacters(in: .whitespacesAndNewlines) + ?? "\(payloadTurnId ?? requestTurnId ?? "session"):\(question ?? "request_user_input")" + guard !publishedUserInputCallIds.contains(callId) else { return nil } + return UserInputCandidate(callId: callId, question: question) + } + + private func publishUserInput(_ userInput: UserInputCandidate) { + publishedUserInputCallIds.insert(userInput.callId) + let body = userInput.question ?? String( + localized: "agent.codex.input.body.needsInput", + defaultValue: "Codex is asking a question" + ) + onEvent(.userInput(request: request, body: body)) + } + + private func publishFailure(_ failure: FailureCandidate) { + onEvent(.failure(request: request, summary: Self.summarizeFailure(failure))) + } + + private func transcriptLineHasAssistantMessage(payload: [String: Any]) -> Bool { + guard (payload["type"] as? String) == "message", + (payload["role"] as? String) == "assistant", + let content = payload["content"] as? [[String: Any]] else { + return false + } + return content.contains { block in + guard let text = block["text"] as? String else { return false } + return !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + } + + private func findTranscriptPath() -> String? { + let normalizedSessionId = request.sessionId.trimmingCharacters(in: .whitespacesAndNewlines) + guard !normalizedSessionId.isEmpty else { return nil } + let codexHome = Self.normalizedValue(request.codexHome) ?? "~/.codex" + let sessionsURL = URL(fileURLWithPath: NSString(string: codexHome).expandingTildeInPath, isDirectory: true) + .appendingPathComponent("sessions", isDirectory: true) + let fileManager = FileManager.default + var newest: URL? + var newestModificationDate: Date? + for directoryURL in Self.recentSessionDirectories(sessionsURL: sessionsURL, fileManager: fileManager) { + guard let urls = try? fileManager.contentsOfDirectory( + at: directoryURL, + includingPropertiesForKeys: [.contentModificationDateKey], + options: [.skipsHiddenFiles] + ) else { + continue + } + for url in urls { + guard url.pathExtension == "jsonl", + url.lastPathComponent.contains(normalizedSessionId) else { + continue + } + let modificationDate = (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast + if newest == nil || modificationDate > (newestModificationDate ?? .distantPast) { + newest = url + newestModificationDate = modificationDate + } + } + } + return newest?.path + } + + private static func recentSessionDirectories(sessionsURL: URL, fileManager: FileManager) -> [URL] { + var directories: [URL] = [] + var seenPaths = Set() + + func appendIfDirectory(_ url: URL) { + guard seenPaths.insert(url.path).inserted else { return } + var isDirectory: ObjCBool = false + guard fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory), + isDirectory.boolValue else { + return + } + directories.append(url) + } + + appendIfDirectory(sessionsURL) + var utcCalendar = Calendar(identifier: .gregorian) + utcCalendar.timeZone = TimeZone(secondsFromGMT: 0) ?? .current + for calendar in [Calendar.current, utcCalendar] { + for dayOffset in -14...1 { + guard let date = calendar.date(byAdding: .day, value: dayOffset, to: Date.now) else { continue } + let components = calendar.dateComponents([.year, .month, .day], from: date) + guard let year = components.year, + let month = components.month, + let day = components.day else { + continue + } + appendIfDirectory( + sessionsURL + .appendingPathComponent(String(format: "%04d", year), isDirectory: true) + .appendingPathComponent(String(format: "%02d", month), isDirectory: true) + .appendingPathComponent(String(format: "%02d", day), isDirectory: true) + ) + } + } + return directories + } + + private static func failureCandidate( + from object: [String: Any], + isStreamError: Bool, + requireFailureSignal: Bool = true + ) -> FailureCandidate? { + let message = firstString(in: object, keys: ["message", "error", "body", "text", "description"]) + let additionalDetails = hookStringValue(object["additional_details"] ?? object["additionalDetails"]) + let codexErrorInfo = hookStringValue(object["codex_error_info"] ?? object["codexErrorInfo"]) + let eventType = firstString(in: object, keys: ["type", "kind"])?.lowercased() + let typedFailure = eventType == "error" || eventType == "stream_error" + let hasExplicitErrorField = object["error"].map { !($0 is NSNull) } ?? false + let signal = [message, additionalDetails, codexErrorInfo] + .compactMap { $0 } + .joined(separator: " ") + .lowercased() + guard !requireFailureSignal || + typedFailure || + hasExplicitErrorField || + codexErrorInfo != nil || + signal.contains("error") || + signal.contains("failed") || + signal.contains("exception") || + signal.contains("usage limit") || + signal.contains("rate limit") || + signal.contains("stream disconnected") || + signal.contains("connection") || + signal.contains("unauthorized") else { + return nil + } + return FailureCandidate( + message: message ?? additionalDetails ?? codexErrorInfo ?? String( + localized: "agent.codex.error.defaultMessage", + defaultValue: "Codex reported an error" + ), + codexErrorInfo: codexErrorInfo, + additionalDetails: additionalDetails, + isStreamError: isStreamError || eventType == "stream_error" + ) + } + + private static func summarizeFailure(_ candidate: FailureCandidate) -> CodexTranscriptFailureSummary { + let signal = [ + candidate.message, + candidate.codexErrorInfo, + candidate.additionalDetails, + candidate.isStreamError ? "stream_error" : nil + ] + .compactMap { $0 } + .joined(separator: " ") + .lowercased() + + let subtitle: String + let statusValue: String + if signal.contains("usage_limit") || + signal.contains("usage limit") || + signal.contains("rate limit") || + signal.contains("quota") { + subtitle = String(localized: "agent.codex.error.subtitle.rateLimit", defaultValue: "Rate limit") + statusValue = String(localized: "agent.codex.error.status.rateLimit", defaultValue: "Codex rate limit") + } else if signal.contains("unauthorized") || + signal.contains("auth") || + signal.contains("login") || + signal.contains("api key") { + subtitle = String(localized: "agent.codex.error.subtitle.auth", defaultValue: "Auth error") + statusValue = String(localized: "agent.codex.error.status.auth", defaultValue: "Codex auth error") + } else if candidate.isStreamError || + signal.contains("network") || + signal.contains("connection") || + signal.contains("stream disconnected") || + signal.contains("timed out") { + subtitle = String(localized: "agent.codex.error.subtitle.network", defaultValue: "Network error") + statusValue = String(localized: "agent.codex.error.status.network", defaultValue: "Codex network error") + } else { + subtitle = String(localized: "agent.codex.error.subtitle.generic", defaultValue: "Error") + statusValue = String(localized: "agent.codex.error.status.generic", defaultValue: "Codex error") + } + + let detail = [candidate.message, candidate.codexErrorInfo, candidate.additionalDetails] + .compactMap { normalizedValue($0).map(normalizedSingleLine) } + .first { !$0.isEmpty } ?? candidate.message + return CodexTranscriptFailureSummary( + statusValue: statusValue, + subtitle: subtitle, + body: truncate(detail, maxLength: 220) + ) + } + + private static func codexFunctionCallArgumentsObject(from payload: [String: Any]) -> [String: Any]? { + if let arguments = payload["arguments"] as? [String: Any] { + return arguments + } + guard let rawArguments = payload["arguments"] as? String, + let data = rawArguments.data(using: .utf8), + let arguments = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { + return nil + } + return arguments + } + + private static func userInputQuestionText(from payload: [String: Any]) -> String? { + let questions = payload["questions"] as? [[String: Any]] ?? [] + for question in questions { + let text = firstString(in: question, keys: ["question", "header", "id"]) + let normalized = text.map(normalizedSingleLine)?.trimmingCharacters(in: .whitespacesAndNewlines) + if let normalized, !normalized.isEmpty { + return truncate(normalized, maxLength: 220) + } + } + return nil + } + + private static func hookStringValue(_ rawValue: Any?) -> String? { + guard let rawValue else { return nil } + if rawValue is NSNull { return nil } + if let value = rawValue as? String { + return normalizedValue(value) + } + if let array = rawValue as? [Any] { + let joined = array.compactMap(hookStringValue).joined(separator: " ") + return normalizedValue(joined) + } + if let dict = rawValue as? [String: Any] { + let joined = dict.keys.sorted().compactMap { hookStringValue(dict[$0]) }.joined(separator: " ") + return normalizedValue(joined) + } + return normalizedValue(String(describing: rawValue)) + } + + private static func firstString(in object: [String: Any], keys: [String]) -> String? { + for key in keys { + if let value = hookStringValue(object[key]) { + return value + } + } + return nil + } + + private static func normalizedValue(_ value: String?) -> String? { + let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed?.isEmpty == false ? trimmed : nil + } + + private static func normalizedSingleLine(_ value: String) -> String { + value + .replacingOccurrences(of: "\r\n", with: "\n") + .replacingOccurrences(of: "\r", with: "\n") + .split(whereSeparator: \.isNewline) + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + .joined(separator: " ") + } + + private static func truncate(_ value: String, maxLength: Int) -> String { + guard value.count > maxLength else { return value } + return String(value.prefix(maxLength - 3)) + "..." + } + } +} diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 9fdc9a5d4a55..d48be0df721e 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -20,693 +20,6 @@ nonisolated private struct SocketLineProcessingResult: Sendable { let authenticated: Bool } -fileprivate struct CodexTranscriptMonitorRequest: Sendable { - let workspaceId: UUID - let surfaceId: UUID? - let sessionId: String - let turnId: String? - let transcriptPath: String? - let codexHome: String? -} - -fileprivate struct CodexTranscriptFailureSummary: Sendable { - let statusValue: String - let subtitle: String - let body: String -} - -fileprivate enum CodexTranscriptMonitorEvent: Sendable { - case userInput(request: CodexTranscriptMonitorRequest, body: String) - case failure(request: CodexTranscriptMonitorRequest, summary: CodexTranscriptFailureSummary) - case completion(request: CodexTranscriptMonitorRequest) -} - -private final class CodexTranscriptMonitorRegistry: @unchecked Sendable { - static let shared = CodexTranscriptMonitorRegistry() - - private let queue = DispatchQueue(label: "com.cmux.codex-transcript-monitor", qos: .utility) - private var monitorsBySessionId: [String: Monitor] = [:] - - private init() {} - - func start(_ request: CodexTranscriptMonitorRequest) { - queue.async { [weak self] in - guard let self else { return } - let key = request.sessionId - self.monitorsBySessionId[key]?.cancel() - let monitor = Monitor( - request: request, - queue: self.queue, - onEvent: { [weak self] event in self?.publish(event) }, - onFinish: { [weak self] sessionId, monitor in - guard let self else { return } - if self.monitorsBySessionId[sessionId] === monitor { - self.monitorsBySessionId.removeValue(forKey: sessionId) - } - } - ) - self.monitorsBySessionId[key] = monitor - monitor.start() - } - } - - func stop(sessionId: String, turnId: String?) { - queue.async { [weak self] in - guard let self else { return } - if let monitor = self.monitorsBySessionId[sessionId], - turnId == nil || monitor.matches(turnId: turnId) { - monitor.cancel() - self.monitorsBySessionId.removeValue(forKey: sessionId) - } - } - } - - func stopWorkspace(_ workspaceId: UUID) { - queue.async { [weak self] in - guard let self else { return } - let matchingSessionIds = self.monitorsBySessionId.compactMap { sessionId, monitor in - monitor.workspaceId == workspaceId ? sessionId : nil - } - for sessionId in matchingSessionIds { - self.monitorsBySessionId[sessionId]?.cancel() - self.monitorsBySessionId.removeValue(forKey: sessionId) - } - } - } - - private func publish(_ event: CodexTranscriptMonitorEvent) { - Task { @MainActor in - TerminalController.shared.handleCodexTranscriptMonitorEvent(event) - } - } - - private final class Monitor { - private struct FailureCandidate { - let message: String - let codexErrorInfo: String? - let additionalDetails: String? - let isStreamError: Bool - } - - private struct UserInputCandidate { - let callId: String - let question: String? - } - - private enum Policy { - static let maxTailBytes: UInt64 = 512 * 1024 - static let retryInterval: TimeInterval = 1 - static let deadline: TimeInterval = 4 * 60 * 60 - } - - let workspaceId: UUID - - private let request: CodexTranscriptMonitorRequest - private let queue: DispatchQueue - private let onEvent: (CodexTranscriptMonitorEvent) -> Void - private let onFinish: (String, Monitor) -> Void - private var source: DispatchSourceFileSystemObject? - private var retryTimer: DispatchSourceTimer? - private var deadlineTimer: DispatchSourceTimer? - private var transcriptPath: String? - private var readOffset: UInt64 = 0 - private var pendingData = Data() - private var publishedUserInputCallIds = Set() - private var sawRelevantTurn = false - private var sawAssistantMessage = false - private var finished = false - - init( - request: CodexTranscriptMonitorRequest, - queue: DispatchQueue, - onEvent: @escaping (CodexTranscriptMonitorEvent) -> Void, - onFinish: @escaping (String, Monitor) -> Void - ) { - self.request = request - self.queue = queue - self.onEvent = onEvent - self.onFinish = onFinish - self.workspaceId = request.workspaceId - self.transcriptPath = Self.normalizedValue(request.transcriptPath) - self.sawRelevantTurn = Self.normalizedValue(request.turnId) == nil - } - - func start() { - armDeadline() - installSourceOrRetry() - } - - func matches(turnId: String?) -> Bool { - guard let turnId = Self.normalizedValue(turnId) else { return true } - return Self.normalizedValue(request.turnId) == turnId - } - - func cancel() { - finished = true - source?.cancel() - source = nil - retryTimer?.cancel() - retryTimer = nil - deadlineTimer?.cancel() - deadlineTimer = nil - } - - private func finish(publishCompletion: Bool = false) { - guard !finished else { return } - if publishCompletion { - onEvent(.completion(request: request)) - } - cancel() - onFinish(request.sessionId, self) - } - - private func armDeadline() { - let timer = DispatchSource.makeTimerSource(queue: queue) - timer.schedule(deadline: .now() + Policy.deadline) - timer.setEventHandler { [weak self] in - self?.finish() - } - timer.resume() - deadlineTimer = timer - } - - private func installSourceOrRetry() { - guard !finished else { return } - if transcriptPath == nil { - transcriptPath = findTranscriptPath() - } - guard let path = transcriptPath else { - scheduleRetry() - return - } - installFileSource(path: path) - } - - private func installFileSource(path: String) { - source?.cancel() - source = nil - - let expandedPath = NSString(string: path).expandingTildeInPath - let fd = open(expandedPath, O_EVTONLY) - guard fd >= 0 else { - transcriptPath = nil - scheduleRetry() - return - } - - let newSource = DispatchSource.makeFileSystemObjectSource( - fileDescriptor: fd, - eventMask: [.write, .extend, .delete, .rename], - queue: queue - ) - newSource.setEventHandler { [weak self] in - self?.handleFileEvent() - } - newSource.setCancelHandler { - close(fd) - } - source = newSource - newSource.resume() - readInitialTail(path: expandedPath) - } - - private func handleFileEvent() { - guard !finished, let path = transcriptPath else { return } - let expandedPath = NSString(string: path).expandingTildeInPath - if let eventData = source?.data, - eventData.contains(.delete) || eventData.contains(.rename) { - source?.cancel() - source = nil - transcriptPath = nil - readOffset = 0 - pendingData.removeAll(keepingCapacity: false) - scheduleRetry() - return - } - readIncremental(path: expandedPath) - } - - private func scheduleRetry() { - retryTimer?.cancel() - let timer = DispatchSource.makeTimerSource(queue: queue) - timer.schedule(deadline: .now() + Policy.retryInterval) - timer.setEventHandler { [weak self] in - guard let self else { return } - self.retryTimer?.cancel() - self.retryTimer = nil - self.installSourceOrRetry() - } - timer.resume() - retryTimer = timer - } - - private func readInitialTail(path: String) { - guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else { return } - defer { try? handle.close() } - let endOffset = (try? handle.seekToEnd()) ?? 0 - let startOffset = endOffset > Policy.maxTailBytes ? endOffset - Policy.maxTailBytes : 0 - do { - try handle.seek(toOffset: startOffset) - } catch { - readOffset = endOffset - return - } - var data = handle.readDataToEndOfFile() - if startOffset > 0, let newline = data.firstIndex(of: 0x0A) { - data.removeSubrange(0...newline) - } - readOffset = endOffset - process(data: data) - } - - private func readIncremental(path: String) { - guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else { - transcriptPath = nil - scheduleRetry() - return - } - defer { try? handle.close() } - let endOffset = (try? handle.seekToEnd()) ?? 0 - if readOffset > endOffset { - readOffset = 0 - pendingData.removeAll(keepingCapacity: false) - } - do { - try handle.seek(toOffset: readOffset) - } catch { - readOffset = endOffset - return - } - let data = handle.readDataToEndOfFile() - readOffset = endOffset - process(data: data) - } - - private func process(data: Data) { - guard !data.isEmpty else { return } - pendingData.append(data) - while let newline = pendingData.firstIndex(of: 0x0A) { - let lineData = pendingData[.. Bool { - guard let requestTurnId = Self.normalizedValue(request.turnId) else { return true } - return Self.firstString(in: payload, keys: ["turn_id", "turnId"]) == requestTurnId - } - - private func userInputEventCandidate(from payload: [String: Any]) -> UserInputCandidate? { - guard turnMatches(payload: payload) || sawRelevantTurn else { return nil } - return userInputCandidate(from: payload, payloadTurnId: Self.firstString(in: payload, keys: ["turn_id", "turnId"])) - } - - private func userInputFunctionCallCandidate(from payload: [String: Any]) -> UserInputCandidate? { - guard (payload["type"] as? String) == "function_call", - (payload["name"] as? String) == "request_user_input" else { - return nil - } - let arguments = Self.codexFunctionCallArgumentsObject(from: payload) - let payloadTurnId = Self.firstString(in: payload, keys: ["turn_id", "turnId"]) - ?? arguments.flatMap { Self.firstString(in: $0, keys: ["turn_id", "turnId"]) } - if let requestTurnId = Self.normalizedValue(request.turnId) { - if let payloadTurnId { - guard payloadTurnId == requestTurnId else { return nil } - } else { - guard sawRelevantTurn else { return nil } - } - } - return userInputCandidate( - from: arguments ?? payload, - payloadTurnId: payloadTurnId, - fallbackCallId: Self.firstString(in: payload, keys: ["call_id", "callId"]) - ) - } - - private func userInputCandidate( - from payload: [String: Any], - payloadTurnId: String?, - fallbackCallId: String? = nil - ) -> UserInputCandidate? { - let question = Self.userInputQuestionText(from: payload) - let requestTurnId = Self.normalizedValue(request.turnId) - let rawCallId = Self.firstString(in: payload, keys: ["call_id", "callId"]) ?? fallbackCallId - let callId = rawCallId?.trimmingCharacters(in: .whitespacesAndNewlines) - ?? "\(payloadTurnId ?? requestTurnId ?? "session"):\(question ?? "request_user_input")" - guard !publishedUserInputCallIds.contains(callId) else { return nil } - return UserInputCandidate(callId: callId, question: question) - } - - private func publishUserInput(_ userInput: UserInputCandidate) { - publishedUserInputCallIds.insert(userInput.callId) - let body = userInput.question ?? String( - localized: "agent.codex.input.body.needsInput", - defaultValue: "Codex is asking a question" - ) - onEvent(.userInput(request: request, body: body)) - } - - private func publishFailure(_ failure: FailureCandidate) { - onEvent(.failure(request: request, summary: Self.summarizeFailure(failure))) - } - - private func transcriptLineHasAssistantMessage(payload: [String: Any]) -> Bool { - guard (payload["type"] as? String) == "message", - (payload["role"] as? String) == "assistant", - let content = payload["content"] as? [[String: Any]] else { - return false - } - return content.contains { block in - guard let text = block["text"] as? String else { return false } - return !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - } - } - - private func findTranscriptPath() -> String? { - let normalizedSessionId = request.sessionId.trimmingCharacters(in: .whitespacesAndNewlines) - guard !normalizedSessionId.isEmpty else { return nil } - let codexHome = Self.normalizedValue(request.codexHome) ?? "~/.codex" - let sessionsURL = URL(fileURLWithPath: NSString(string: codexHome).expandingTildeInPath, isDirectory: true) - .appendingPathComponent("sessions", isDirectory: true) - let fileManager = FileManager.default - var newest: URL? - var newestModificationDate: Date? - for directoryURL in Self.recentSessionDirectories(sessionsURL: sessionsURL, fileManager: fileManager) { - guard let urls = try? fileManager.contentsOfDirectory( - at: directoryURL, - includingPropertiesForKeys: [.contentModificationDateKey], - options: [.skipsHiddenFiles] - ) else { - continue - } - for url in urls { - guard url.pathExtension == "jsonl", - url.lastPathComponent.contains(normalizedSessionId) else { - continue - } - let modificationDate = (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast - if newest == nil || modificationDate > (newestModificationDate ?? .distantPast) { - newest = url - newestModificationDate = modificationDate - } - } - } - return newest?.path - } - - private static func recentSessionDirectories(sessionsURL: URL, fileManager: FileManager) -> [URL] { - var directories: [URL] = [] - var seenPaths = Set() - - func appendIfDirectory(_ url: URL) { - guard seenPaths.insert(url.path).inserted else { return } - var isDirectory: ObjCBool = false - guard fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory), - isDirectory.boolValue else { - return - } - directories.append(url) - } - - appendIfDirectory(sessionsURL) - var utcCalendar = Calendar(identifier: .gregorian) - utcCalendar.timeZone = TimeZone(secondsFromGMT: 0) ?? .current - for calendar in [Calendar.current, utcCalendar] { - for dayOffset in -14...1 { - guard let date = calendar.date(byAdding: .day, value: dayOffset, to: Date.now) else { continue } - let components = calendar.dateComponents([.year, .month, .day], from: date) - guard let year = components.year, - let month = components.month, - let day = components.day else { - continue - } - appendIfDirectory( - sessionsURL - .appendingPathComponent(String(format: "%04d", year), isDirectory: true) - .appendingPathComponent(String(format: "%02d", month), isDirectory: true) - .appendingPathComponent(String(format: "%02d", day), isDirectory: true) - ) - } - } - return directories - } - - private static func failureCandidate( - from object: [String: Any], - isStreamError: Bool, - requireFailureSignal: Bool = true - ) -> FailureCandidate? { - let message = firstString(in: object, keys: ["message", "error", "body", "text", "description"]) - let additionalDetails = hookStringValue(object["additional_details"] ?? object["additionalDetails"]) - let codexErrorInfo = hookStringValue(object["codex_error_info"] ?? object["codexErrorInfo"]) - let eventType = firstString(in: object, keys: ["type", "kind"])?.lowercased() - let typedFailure = eventType == "error" || eventType == "stream_error" - let hasExplicitErrorField = object["error"].map { !($0 is NSNull) } ?? false - let signal = [message, additionalDetails, codexErrorInfo] - .compactMap { $0 } - .joined(separator: " ") - .lowercased() - guard !requireFailureSignal || - typedFailure || - hasExplicitErrorField || - codexErrorInfo != nil || - signal.contains("error") || - signal.contains("failed") || - signal.contains("exception") || - signal.contains("usage limit") || - signal.contains("rate limit") || - signal.contains("stream disconnected") || - signal.contains("connection") || - signal.contains("unauthorized") else { - return nil - } - return FailureCandidate( - message: message ?? additionalDetails ?? codexErrorInfo ?? String( - localized: "agent.codex.error.defaultMessage", - defaultValue: "Codex reported an error" - ), - codexErrorInfo: codexErrorInfo, - additionalDetails: additionalDetails, - isStreamError: isStreamError || eventType == "stream_error" - ) - } - - private static func summarizeFailure(_ candidate: FailureCandidate) -> CodexTranscriptFailureSummary { - let signal = [ - candidate.message, - candidate.codexErrorInfo, - candidate.additionalDetails, - candidate.isStreamError ? "stream_error" : nil - ] - .compactMap { $0 } - .joined(separator: " ") - .lowercased() - - let subtitle: String - let statusValue: String - if signal.contains("usage_limit") || - signal.contains("usage limit") || - signal.contains("rate limit") || - signal.contains("quota") { - subtitle = String(localized: "agent.codex.error.subtitle.rateLimit", defaultValue: "Rate limit") - statusValue = String(localized: "agent.codex.error.status.rateLimit", defaultValue: "Codex rate limit") - } else if signal.contains("unauthorized") || - signal.contains("auth") || - signal.contains("login") || - signal.contains("api key") { - subtitle = String(localized: "agent.codex.error.subtitle.auth", defaultValue: "Auth error") - statusValue = String(localized: "agent.codex.error.status.auth", defaultValue: "Codex auth error") - } else if candidate.isStreamError || - signal.contains("network") || - signal.contains("connection") || - signal.contains("stream disconnected") || - signal.contains("timed out") { - subtitle = String(localized: "agent.codex.error.subtitle.network", defaultValue: "Network error") - statusValue = String(localized: "agent.codex.error.status.network", defaultValue: "Codex network error") - } else { - subtitle = String(localized: "agent.codex.error.subtitle.generic", defaultValue: "Error") - statusValue = String(localized: "agent.codex.error.status.generic", defaultValue: "Codex error") - } - - let detail = [candidate.message, candidate.codexErrorInfo, candidate.additionalDetails] - .compactMap { normalizedValue($0).map(normalizedSingleLine) } - .first { !$0.isEmpty } ?? candidate.message - return CodexTranscriptFailureSummary( - statusValue: statusValue, - subtitle: subtitle, - body: truncate(detail, maxLength: 220) - ) - } - - private static func codexFunctionCallArgumentsObject(from payload: [String: Any]) -> [String: Any]? { - if let arguments = payload["arguments"] as? [String: Any] { - return arguments - } - guard let rawArguments = payload["arguments"] as? String, - let data = rawArguments.data(using: .utf8), - let arguments = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { - return nil - } - return arguments - } - - private static func userInputQuestionText(from payload: [String: Any]) -> String? { - guard let questions = payload["questions"] as? [[String: Any]] else { - return nil - } - for question in questions { - let text = firstString(in: question, keys: ["question", "header", "id"]) - let normalized = text.map(normalizedSingleLine)?.trimmingCharacters(in: .whitespacesAndNewlines) - if let normalized, !normalized.isEmpty { - return truncate(normalized, maxLength: 220) - } - } - return nil - } - - private static func hookStringValue(_ rawValue: Any?) -> String? { - guard let rawValue else { return nil } - if rawValue is NSNull { return nil } - if let value = rawValue as? String { - return normalizedValue(value) - } - if let array = rawValue as? [Any] { - let joined = array.compactMap(hookStringValue).joined(separator: " ") - return normalizedValue(joined) - } - if let dict = rawValue as? [String: Any] { - let joined = dict.keys.sorted().compactMap { hookStringValue(dict[$0]) }.joined(separator: " ") - return normalizedValue(joined) - } - return normalizedValue(String(describing: rawValue)) - } - - private static func firstString(in object: [String: Any], keys: [String]) -> String? { - for key in keys { - if let value = hookStringValue(object[key]) { - return value - } - } - return nil - } - - private static func normalizedValue(_ value: String?) -> String? { - let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed?.isEmpty == false ? trimmed : nil - } - - private static func normalizedSingleLine(_ value: String) -> String { - value - .replacingOccurrences(of: "\r\n", with: "\n") - .replacingOccurrences(of: "\r", with: "\n") - .split(whereSeparator: \.isNewline) - .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } - .filter { !$0.isEmpty } - .joined(separator: " ") - } - - private static func truncate(_ value: String, maxLength: Int) -> String { - guard value.count > maxLength else { return value } - return String(value.prefix(maxLength - 3)) + "..." - } - } -} /// Unix socket-based controller for programmatic terminal control /// Allows automated testing and external control of terminal tabs @@ -9323,7 +8636,7 @@ class TerminalController { CodexTranscriptMonitorRegistry.shared.stopWorkspace(workspaceId) } - fileprivate func handleCodexTranscriptMonitorEvent(_ event: CodexTranscriptMonitorEvent) { + func handleCodexTranscriptMonitorEvent(_ event: CodexTranscriptMonitorEvent) { let request: CodexTranscriptMonitorRequest switch event { case .userInput(let eventRequest, _), .failure(let eventRequest, _), .completion(let eventRequest): From aafacac6f60f6899d893f46853ce7344fbc2ad3d Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 16:43:55 -0700 Subject: [PATCH 09/25] fix: address codex monitor review edge cases --- GhosttyTabs.xcodeproj/project.pbxproj | 4 +++ Sources/CodexTranscriptMonitor.swift | 18 ++++++----- Sources/SidebarLogRingBuffer.swift | 44 +++++++++++++++++++++++++++ Sources/Workspace.swift | 44 --------------------------- 4 files changed, 59 insertions(+), 51 deletions(-) create mode 100644 Sources/SidebarLogRingBuffer.swift diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index a75eaaaae6f0..cd1ce05f85bf 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -188,6 +188,7 @@ E7E000000000000000000007 /* CmuxEventPublishing.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E000000000000000000008 /* CmuxEventPublishing.swift */; }; A5001007 /* TerminalController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001019 /* TerminalController.swift */; }; C0DE412700000000000001 /* CodexTranscriptMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE412700000000000002 /* CodexTranscriptMonitor.swift */; }; + C0DE412700000000000003 /* SidebarLogRingBuffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE412700000000000004 /* SidebarLogRingBuffer.swift */; }; E7E000000000000000000001 /* CmuxEventStream.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E000000000000000000002 /* CmuxEventStream.swift */; }; E7E000000000000000000009 /* CmuxSocketEventMapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E00000000000000000000A /* CmuxSocketEventMapper.swift */; }; D7AB0000000000000000000B /* TerminalController+MoveTabToNewWorkspace.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB0000000000000000000C /* TerminalController+MoveTabToNewWorkspace.swift */; }; @@ -690,6 +691,7 @@ A5001018 /* cmux-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "cmux-Bridging-Header.h"; sourceTree = ""; }; A5001019 /* TerminalController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalController.swift; sourceTree = ""; }; C0DE412700000000000002 /* CodexTranscriptMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitor.swift; sourceTree = ""; }; + C0DE412700000000000004 /* SidebarLogRingBuffer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarLogRingBuffer.swift; sourceTree = ""; }; E7E000000000000000000006 /* CmuxEventBus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxEventBus.swift; sourceTree = ""; }; E7E00000000000000000000E /* CmuxEventLogWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxEventLogWriter.swift; sourceTree = ""; }; E7E00000000000000000000C /* CmuxLifecycleEventPublishing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxLifecycleEventPublishing.swift; sourceTree = ""; }; @@ -1203,6 +1205,7 @@ A5001511 /* UITestRecorder.swift */, A5001520 /* PostHogAnalytics.swift */, A5001416 /* Workspace.swift */, + C0DE412700000000000004 /* SidebarLogRingBuffer.swift */, D7AB3605C10DEF0000000004 /* WorkspaceCloseTabsBatching.swift */, C3744E020000000000000001 /* Workspace+PanelLifecycle.swift */, E30780000000000000000001 /* WorkspaceRemoteConfiguration.swift */, @@ -1879,6 +1882,7 @@ A5001501 /* UITestRecorder.swift in Sources */, A5001521 /* PostHogAnalytics.swift in Sources */, A5001406 /* Workspace.swift in Sources */, + C0DE412700000000000003 /* SidebarLogRingBuffer.swift in Sources */, D7AB3605C10DEF0000000003 /* WorkspaceCloseTabsBatching.swift in Sources */, C3744E010000000000000001 /* Workspace+PanelLifecycle.swift in Sources */, E30780000000000000000002 /* WorkspaceRemoteConfiguration.swift in Sources */, diff --git a/Sources/CodexTranscriptMonitor.swift b/Sources/CodexTranscriptMonitor.swift index a8c6408a286d..efde751ca243 100644 --- a/Sources/CodexTranscriptMonitor.swift +++ b/Sources/CodexTranscriptMonitor.swift @@ -79,8 +79,10 @@ final class CodexTranscriptMonitorRegistry: @unchecked Sendable { } private func publish(_ event: CodexTranscriptMonitorEvent) { - Task { @MainActor in - TerminalController.shared.handleCodexTranscriptMonitorEvent(event) + DispatchQueue.main.async { + MainActor.assumeIsolated { + TerminalController.shared.handleCodexTranscriptMonitorEvent(event) + } } } @@ -260,11 +262,12 @@ final class CodexTranscriptMonitorRegistry: @unchecked Sendable { return } var data = handle.readDataToEndOfFile() + let bytesRead = UInt64(data.count) if startOffset > 0, let newline = data.firstIndex(of: 0x0A) { data.removeSubrange(0...newline) } - readOffset = endOffset process(data: data) + readOffset = startOffset + bytesRead } private func readIncremental(path: String) { @@ -279,15 +282,16 @@ final class CodexTranscriptMonitorRegistry: @unchecked Sendable { readOffset = 0 pendingData.removeAll(keepingCapacity: false) } + let seekOffset = readOffset do { - try handle.seek(toOffset: readOffset) + try handle.seek(toOffset: seekOffset) } catch { readOffset = endOffset return } let data = handle.readDataToEndOfFile() - readOffset = endOffset process(data: data) + readOffset = seekOffset + UInt64(data.count) } private func process(data: Data) { @@ -353,7 +357,7 @@ final class CodexTranscriptMonitorRegistry: @unchecked Sendable { } case "task_complete", "turn_complete": - guard turnMatches(payload: payload) || Self.normalizedValue(request.turnId) == nil else { return } + guard turnMatches(payload: payload) else { return } sawRelevantTurn = true if let lastMessage = payload["last_agent_message"] as? String, !lastMessage.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { @@ -435,7 +439,7 @@ final class CodexTranscriptMonitorRegistry: @unchecked Sendable { let question = Self.userInputQuestionText(from: payload) let requestTurnId = Self.normalizedValue(request.turnId) let rawCallId = Self.firstString(in: payload, keys: ["call_id", "callId"]) ?? fallbackCallId - let callId = rawCallId?.trimmingCharacters(in: .whitespacesAndNewlines) + let callId = Self.normalizedValue(rawCallId) ?? "\(payloadTurnId ?? requestTurnId ?? "session"):\(question ?? "request_user_input")" guard !publishedUserInputCallIds.contains(callId) else { return nil } return UserInputCandidate(callId: callId, question: question) diff --git a/Sources/SidebarLogRingBuffer.swift b/Sources/SidebarLogRingBuffer.swift new file mode 100644 index 000000000000..b8f137d01505 --- /dev/null +++ b/Sources/SidebarLogRingBuffer.swift @@ -0,0 +1,44 @@ +struct SidebarLogRingBuffer { + private var storage: [SidebarLogEntry?] + private var head = 0 + private(set) var count = 0 + private(set) var limit: Int + + init(limit: Int) { + let normalizedLimit = max(1, min(500, limit)) + self.limit = normalizedLimit + self.storage = Array(repeating: nil, count: normalizedLimit) + } + + mutating func replaceAll(_ entries: [SidebarLogEntry], limit: Int) { + self = SidebarLogRingBuffer(limit: limit) + for entry in entries.suffix(self.limit) { + append(entry) + } + } + + mutating func append(_ entry: SidebarLogEntry) { + guard !storage.isEmpty else { return } + let index = (head + count) % storage.count + if count == storage.count { + storage[head] = entry + head = (head + 1) % storage.count + } else { + storage[index] = entry + count += 1 + } + } + + mutating func removeAll() { + storage = Array(repeating: nil, count: limit) + head = 0 + count = 0 + } + + func entries() -> [SidebarLogEntry] { + guard count > 0 else { return [] } + return (0.. [SidebarLogEntry] { - guard count > 0 else { return [] } - return (0.. Date: Wed, 13 May 2026 16:57:11 -0700 Subject: [PATCH 10/25] fix: hop sidebar log flush to main actor --- Sources/Workspace.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 10bec20c6131..0cd498ce14e8 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -9844,7 +9844,7 @@ final class Workspace: Identifiable, ObservableObject { timer.schedule(deadline: .now() + Self.sidebarLogFlushDelay) timer.setEventHandler { [weak self] in guard let self else { return } - MainActor.assumeIsolated { + Task { @MainActor in self.flushPendingSidebarLogEntries() } } From 14a1c4653667cf86f0fbebb5d3d709ccbcb70417 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 17:12:50 -0700 Subject: [PATCH 11/25] fix: lower codex monitor review risk --- GhosttyTabs.xcodeproj/project.pbxproj | 16 + Sources/CodexTranscriptMonitor.swift | 956 ++++++------------- Sources/CodexTranscriptMonitorModels.swift | 22 + Sources/CodexTranscriptMonitorParsing.swift | 184 ++++ Sources/CodexTranscriptMonitorRegistry.swift | 64 ++ Sources/CodexTranscriptPathResolver.swift | 72 ++ Sources/Workspace.swift | 39 +- 7 files changed, 692 insertions(+), 661 deletions(-) create mode 100644 Sources/CodexTranscriptMonitorModels.swift create mode 100644 Sources/CodexTranscriptMonitorParsing.swift create mode 100644 Sources/CodexTranscriptMonitorRegistry.swift create mode 100644 Sources/CodexTranscriptPathResolver.swift diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index cd1ce05f85bf..c74b881db669 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -189,6 +189,10 @@ A5001007 /* TerminalController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001019 /* TerminalController.swift */; }; C0DE412700000000000001 /* CodexTranscriptMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE412700000000000002 /* CodexTranscriptMonitor.swift */; }; C0DE412700000000000003 /* SidebarLogRingBuffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE412700000000000004 /* SidebarLogRingBuffer.swift */; }; + C0DE412700000000000005 /* CodexTranscriptMonitorModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE412700000000000006 /* CodexTranscriptMonitorModels.swift */; }; + C0DE412700000000000007 /* CodexTranscriptMonitorRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE412700000000000008 /* CodexTranscriptMonitorRegistry.swift */; }; + C0DE412700000000000009 /* CodexTranscriptMonitorParsing.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE41270000000000000A /* CodexTranscriptMonitorParsing.swift */; }; + C0DE41270000000000000B /* CodexTranscriptPathResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE41270000000000000C /* CodexTranscriptPathResolver.swift */; }; E7E000000000000000000001 /* CmuxEventStream.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E000000000000000000002 /* CmuxEventStream.swift */; }; E7E000000000000000000009 /* CmuxSocketEventMapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E00000000000000000000A /* CmuxSocketEventMapper.swift */; }; D7AB0000000000000000000B /* TerminalController+MoveTabToNewWorkspace.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB0000000000000000000C /* TerminalController+MoveTabToNewWorkspace.swift */; }; @@ -692,6 +696,10 @@ A5001019 /* TerminalController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalController.swift; sourceTree = ""; }; C0DE412700000000000002 /* CodexTranscriptMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitor.swift; sourceTree = ""; }; C0DE412700000000000004 /* SidebarLogRingBuffer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarLogRingBuffer.swift; sourceTree = ""; }; + C0DE412700000000000006 /* CodexTranscriptMonitorModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitorModels.swift; sourceTree = ""; }; + C0DE412700000000000008 /* CodexTranscriptMonitorRegistry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitorRegistry.swift; sourceTree = ""; }; + C0DE41270000000000000A /* CodexTranscriptMonitorParsing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitorParsing.swift; sourceTree = ""; }; + C0DE41270000000000000C /* CodexTranscriptPathResolver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptPathResolver.swift; sourceTree = ""; }; E7E000000000000000000006 /* CmuxEventBus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxEventBus.swift; sourceTree = ""; }; E7E00000000000000000000E /* CmuxEventLogWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxEventLogWriter.swift; sourceTree = ""; }; E7E00000000000000000000C /* CmuxLifecycleEventPublishing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxLifecycleEventPublishing.swift; sourceTree = ""; }; @@ -1246,6 +1254,10 @@ E7E000000000000000000008 /* CmuxEventPublishing.swift */, A5001019 /* TerminalController.swift */, C0DE412700000000000002 /* CodexTranscriptMonitor.swift */, + C0DE412700000000000006 /* CodexTranscriptMonitorModels.swift */, + C0DE412700000000000008 /* CodexTranscriptMonitorRegistry.swift */, + C0DE41270000000000000A /* CodexTranscriptMonitorParsing.swift */, + C0DE41270000000000000C /* CodexTranscriptPathResolver.swift */, E7E000000000000000000002 /* CmuxEventStream.swift */, E7E00000000000000000000A /* CmuxSocketEventMapper.swift */, A5001440A5001440A5001440 /* FileOpenSocketSupport.swift */, @@ -1927,6 +1939,10 @@ E7E000000000000000000007 /* CmuxEventPublishing.swift in Sources */, A5001007 /* TerminalController.swift in Sources */, C0DE412700000000000001 /* CodexTranscriptMonitor.swift in Sources */, + C0DE412700000000000005 /* CodexTranscriptMonitorModels.swift in Sources */, + C0DE412700000000000007 /* CodexTranscriptMonitorRegistry.swift in Sources */, + C0DE412700000000000009 /* CodexTranscriptMonitorParsing.swift in Sources */, + C0DE41270000000000000B /* CodexTranscriptPathResolver.swift in Sources */, E7E000000000000000000001 /* CmuxEventStream.swift in Sources */, E7E000000000000000000009 /* CmuxSocketEventMapper.swift in Sources */, A5001441A5001441A5001441 /* FileOpenSocketSupport.swift in Sources */, diff --git a/Sources/CodexTranscriptMonitor.swift b/Sources/CodexTranscriptMonitor.swift index efde751ca243..cacda8bc4707 100644 --- a/Sources/CodexTranscriptMonitor.swift +++ b/Sources/CodexTranscriptMonitor.swift @@ -1,699 +1,373 @@ import Darwin import Foundation -struct CodexTranscriptMonitorRequest: Sendable { - let workspaceId: UUID - let surfaceId: UUID? - let sessionId: String - let turnId: String? - let transcriptPath: String? - let codexHome: String? -} - -struct CodexTranscriptFailureSummary: Sendable { - let statusValue: String - let subtitle: String - let body: String -} - -enum CodexTranscriptMonitorEvent: Sendable { - case userInput(request: CodexTranscriptMonitorRequest, body: String) - case failure(request: CodexTranscriptMonitorRequest, summary: CodexTranscriptFailureSummary) - case completion(request: CodexTranscriptMonitorRequest) -} - -// Mutable registry state is confined to `queue`; callers interact through async queue hops. -final class CodexTranscriptMonitorRegistry: @unchecked Sendable { - static let shared = CodexTranscriptMonitorRegistry() - - private let queue = DispatchQueue(label: "com.cmux.codex-transcript-monitor", qos: .utility) - private var monitorsBySessionId: [String: Monitor] = [:] - - private init() {} +final class CodexTranscriptMonitorSession { + private enum Policy { + static let maxTailBytes: UInt64 = 512 * 1024 + static let retryInterval: TimeInterval = 1 + static let deadline: TimeInterval = 4 * 60 * 60 + } - deinit {} + let workspaceId: UUID - func start(_ request: CodexTranscriptMonitorRequest) { - queue.async { [weak self] in - guard let self else { return } - let key = request.sessionId - self.monitorsBySessionId[key]?.cancel() - let monitor = Monitor( - request: request, - queue: self.queue, - onEvent: { [weak self] event in self?.publish(event) }, - onFinish: { [weak self] sessionId, monitor in - guard let self else { return } - if self.monitorsBySessionId[sessionId] === monitor { - self.monitorsBySessionId.removeValue(forKey: sessionId) - } - } - ) - self.monitorsBySessionId[key] = monitor - monitor.start() - } + private let request: CodexTranscriptMonitorRequest + private let queue: DispatchQueue + private let onEvent: (CodexTranscriptMonitorEvent) -> Void + private let onFinish: (String, CodexTranscriptMonitorSession) -> Void + private var source: DispatchSourceFileSystemObject? + private var retryTimer: DispatchSourceTimer? + private var deadlineTimer: DispatchSourceTimer? + private var transcriptPath: String? + private var readOffset: UInt64 = 0 + private var pendingData = Data() + private var publishedUserInputCallIds = Set() + private var sawRelevantTurn = false + private var sawAssistantMessage = false + private var finished = false + + init( + request: CodexTranscriptMonitorRequest, + queue: DispatchQueue, + onEvent: @escaping (CodexTranscriptMonitorEvent) -> Void, + onFinish: @escaping (String, CodexTranscriptMonitorSession) -> Void + ) { + self.request = request + self.queue = queue + self.onEvent = onEvent + self.onFinish = onFinish + self.workspaceId = request.workspaceId + self.transcriptPath = CodexTranscriptMonitorParser.normalizedValue(request.transcriptPath) + self.sawRelevantTurn = CodexTranscriptMonitorParser.normalizedValue(request.turnId) == nil } - func stop(sessionId: String, turnId: String?) { - queue.async { [weak self] in - guard let self else { return } - if let monitor = self.monitorsBySessionId[sessionId], - turnId == nil || monitor.matches(turnId: turnId) { - monitor.cancel() - self.monitorsBySessionId.removeValue(forKey: sessionId) - } - } + deinit { + cancel() } - func stopWorkspace(_ workspaceId: UUID) { - queue.async { [weak self] in - guard let self else { return } - let matchingSessionIds = self.monitorsBySessionId.compactMap { sessionId, monitor in - monitor.workspaceId == workspaceId ? sessionId : nil - } - for sessionId in matchingSessionIds { - self.monitorsBySessionId[sessionId]?.cancel() - self.monitorsBySessionId.removeValue(forKey: sessionId) - } - } + func start() { + armDeadline() + installSourceOrRetry() } - private func publish(_ event: CodexTranscriptMonitorEvent) { - DispatchQueue.main.async { - MainActor.assumeIsolated { - TerminalController.shared.handleCodexTranscriptMonitorEvent(event) - } - } + func matches(turnId: String?) -> Bool { + guard let turnId = CodexTranscriptMonitorParser.normalizedValue(turnId) else { return true } + return CodexTranscriptMonitorParser.normalizedValue(request.turnId) == turnId } - private final class Monitor { - private struct FailureCandidate { - let message: String - let codexErrorInfo: String? - let additionalDetails: String? - let isStreamError: Bool - } + func cancel() { + finished = true + source?.cancel() + source = nil + retryTimer?.cancel() + retryTimer = nil + deadlineTimer?.cancel() + deadlineTimer = nil + } - private struct UserInputCandidate { - let callId: String - let question: String? + private func finish(publishCompletion: Bool = false) { + guard !finished else { return } + if publishCompletion { + onEvent(.completion(request: request)) } + cancel() + onFinish(request.sessionId, self) + } - private enum Policy { - static let maxTailBytes: UInt64 = 512 * 1024 - static let retryInterval: TimeInterval = 1 - static let deadline: TimeInterval = 4 * 60 * 60 + private func armDeadline() { + let timer = DispatchSource.makeTimerSource(queue: queue) + timer.schedule(deadline: .now() + Policy.deadline) + timer.setEventHandler { [weak self] in + self?.finish(publishCompletion: true) } + timer.resume() + deadlineTimer = timer + } - let workspaceId: UUID - - private let request: CodexTranscriptMonitorRequest - private let queue: DispatchQueue - private let onEvent: (CodexTranscriptMonitorEvent) -> Void - private let onFinish: (String, Monitor) -> Void - private var source: DispatchSourceFileSystemObject? - private var retryTimer: DispatchSourceTimer? - private var deadlineTimer: DispatchSourceTimer? - private var transcriptPath: String? - private var readOffset: UInt64 = 0 - private var pendingData = Data() - private var publishedUserInputCallIds = Set() - private var sawRelevantTurn = false - private var sawAssistantMessage = false - private var finished = false - - init( - request: CodexTranscriptMonitorRequest, - queue: DispatchQueue, - onEvent: @escaping (CodexTranscriptMonitorEvent) -> Void, - onFinish: @escaping (String, Monitor) -> Void - ) { - self.request = request - self.queue = queue - self.onEvent = onEvent - self.onFinish = onFinish - self.workspaceId = request.workspaceId - self.transcriptPath = Self.normalizedValue(request.transcriptPath) - self.sawRelevantTurn = Self.normalizedValue(request.turnId) == nil + private func installSourceOrRetry() { + guard !finished else { return } + if transcriptPath == nil { + transcriptPath = findTranscriptPath() } - - deinit { - cancel() + guard let path = transcriptPath else { + scheduleRetry() + return } + installFileSource(path: path) + } - func start() { - armDeadline() - installSourceOrRetry() - } + private func installFileSource(path: String) { + source?.cancel() + source = nil - func matches(turnId: String?) -> Bool { - guard let turnId = Self.normalizedValue(turnId) else { return true } - return Self.normalizedValue(request.turnId) == turnId + let expandedPath = NSString(string: path).expandingTildeInPath + let fd = open(expandedPath, O_EVTONLY) + guard fd >= 0 else { + transcriptPath = nil + scheduleRetry() + return } - func cancel() { - finished = true - source?.cancel() - source = nil - retryTimer?.cancel() - retryTimer = nil - deadlineTimer?.cancel() - deadlineTimer = nil + let newSource = DispatchSource.makeFileSystemObjectSource( + fileDescriptor: fd, + eventMask: [.write, .extend, .delete, .rename], + queue: queue + ) + newSource.setEventHandler { [weak self] in + self?.handleFileEvent() } - - private func finish(publishCompletion: Bool = false) { - guard !finished else { return } - if publishCompletion { - onEvent(.completion(request: request)) - } - cancel() - onFinish(request.sessionId, self) - } - - private func armDeadline() { - let timer = DispatchSource.makeTimerSource(queue: queue) - timer.schedule(deadline: .now() + Policy.deadline) - timer.setEventHandler { [weak self] in - self?.finish(publishCompletion: true) - } - timer.resume() - deadlineTimer = timer - } - - private func installSourceOrRetry() { - guard !finished else { return } - if transcriptPath == nil { - transcriptPath = findTranscriptPath() - } - guard let path = transcriptPath else { - scheduleRetry() - return - } - installFileSource(path: path) + newSource.setCancelHandler { + close(fd) } + source = newSource + newSource.resume() + readInitialTail(path: expandedPath) + } - private func installFileSource(path: String) { + private func handleFileEvent() { + guard !finished, let path = transcriptPath else { return } + let expandedPath = NSString(string: path).expandingTildeInPath + if let eventData = source?.data, + eventData.contains(.delete) || eventData.contains(.rename) { source?.cancel() source = nil - - let expandedPath = NSString(string: path).expandingTildeInPath - let fd = open(expandedPath, O_EVTONLY) - guard fd >= 0 else { - transcriptPath = nil - scheduleRetry() - return - } - - let newSource = DispatchSource.makeFileSystemObjectSource( - fileDescriptor: fd, - eventMask: [.write, .extend, .delete, .rename], - queue: queue - ) - newSource.setEventHandler { [weak self] in - self?.handleFileEvent() - } - newSource.setCancelHandler { - close(fd) - } - source = newSource - newSource.resume() - readInitialTail(path: expandedPath) - } - - private func handleFileEvent() { - guard !finished, let path = transcriptPath else { return } - let expandedPath = NSString(string: path).expandingTildeInPath - if let eventData = source?.data, - eventData.contains(.delete) || eventData.contains(.rename) { - source?.cancel() - source = nil - transcriptPath = nil - readOffset = 0 - pendingData.removeAll(keepingCapacity: false) - scheduleRetry() - return - } - readIncremental(path: expandedPath) + transcriptPath = nil + readOffset = 0 + pendingData.removeAll(keepingCapacity: false) + scheduleRetry() + return } + readIncremental(path: expandedPath) + } - private func scheduleRetry() { - retryTimer?.cancel() - let timer = DispatchSource.makeTimerSource(queue: queue) - timer.schedule(deadline: .now() + Policy.retryInterval) - timer.setEventHandler { [weak self] in - guard let self else { return } - self.retryTimer?.cancel() - self.retryTimer = nil - self.installSourceOrRetry() - } - timer.resume() - retryTimer = timer + private func scheduleRetry() { + retryTimer?.cancel() + let timer = DispatchSource.makeTimerSource(queue: queue) + timer.schedule(deadline: .now() + Policy.retryInterval) + timer.setEventHandler { [weak self] in + guard let self else { return } + self.retryTimer?.cancel() + self.retryTimer = nil + self.installSourceOrRetry() } + timer.resume() + retryTimer = timer + } - private func readInitialTail(path: String) { - guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else { return } - defer { try? handle.close() } - let endOffset = (try? handle.seekToEnd()) ?? 0 - let startOffset = endOffset > Policy.maxTailBytes ? endOffset - Policy.maxTailBytes : 0 - do { - try handle.seek(toOffset: startOffset) - } catch { - readOffset = endOffset - return - } - var data = handle.readDataToEndOfFile() - let bytesRead = UInt64(data.count) - if startOffset > 0, let newline = data.firstIndex(of: 0x0A) { - data.removeSubrange(0...newline) - } - process(data: data) - readOffset = startOffset + bytesRead - } + private func readInitialTail(path: String) { + guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else { return } + defer { try? handle.close() } + let endOffset = (try? handle.seekToEnd()) ?? 0 + let startOffset = endOffset > Policy.maxTailBytes ? endOffset - Policy.maxTailBytes : 0 + do { + try handle.seek(toOffset: startOffset) + } catch { + readOffset = endOffset + return + } + var data = handle.readDataToEndOfFile() + let bytesRead = UInt64(data.count) + if startOffset > 0, let newline = data.firstIndex(of: 0x0A) { + data.removeSubrange(0...newline) + } + process(data: data) + readOffset = startOffset + bytesRead + } - private func readIncremental(path: String) { - guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else { - transcriptPath = nil - scheduleRetry() - return - } - defer { try? handle.close() } - let endOffset = (try? handle.seekToEnd()) ?? 0 - if readOffset > endOffset { - readOffset = 0 - pendingData.removeAll(keepingCapacity: false) - } - let seekOffset = readOffset - do { - try handle.seek(toOffset: seekOffset) - } catch { - readOffset = endOffset - return - } - let data = handle.readDataToEndOfFile() - process(data: data) - readOffset = seekOffset + UInt64(data.count) - } + private func readIncremental(path: String) { + guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else { + transcriptPath = nil + scheduleRetry() + return + } + defer { try? handle.close() } + let endOffset = (try? handle.seekToEnd()) ?? 0 + if readOffset > endOffset { + readOffset = 0 + pendingData.removeAll(keepingCapacity: false) + } + let seekOffset = readOffset + do { + try handle.seek(toOffset: seekOffset) + } catch { + readOffset = endOffset + return + } + let data = handle.readDataToEndOfFile() + process(data: data) + readOffset = seekOffset + UInt64(data.count) + } - private func process(data: Data) { - guard !data.isEmpty else { return } - pendingData.append(data) - while let newline = pendingData.firstIndex(of: 0x0A) { - let lineData = pendingData[.. Bool { - guard let requestTurnId = Self.normalizedValue(request.turnId) else { return true } - return Self.firstString(in: payload, keys: ["turn_id", "turnId"]) == requestTurnId - } - - private func userInputEventCandidate(from payload: [String: Any]) -> UserInputCandidate? { - guard turnMatches(payload: payload) || sawRelevantTurn else { return nil } - return userInputCandidate(from: payload, payloadTurnId: Self.firstString(in: payload, keys: ["turn_id", "turnId"])) - } - - private func userInputFunctionCallCandidate(from payload: [String: Any]) -> UserInputCandidate? { - guard (payload["type"] as? String) == "function_call", - (payload["name"] as? String) == "request_user_input" else { - return nil - } - let arguments = Self.codexFunctionCallArgumentsObject(from: payload) - let payloadTurnId = Self.firstString(in: payload, keys: ["turn_id", "turnId"]) - ?? arguments.flatMap { Self.firstString(in: $0, keys: ["turn_id", "turnId"]) } - if let requestTurnId = Self.normalizedValue(request.turnId) { - if let payloadTurnId { - guard payloadTurnId == requestTurnId else { return nil } - } else { - guard sawRelevantTurn else { return nil } - } - } - return userInputCandidate( - from: arguments ?? payload, - payloadTurnId: payloadTurnId, - fallbackCallId: Self.firstString(in: payload, keys: ["call_id", "callId"]) - ) - } - - private func userInputCandidate( - from payload: [String: Any], - payloadTurnId: String?, - fallbackCallId: String? = nil - ) -> UserInputCandidate? { - let question = Self.userInputQuestionText(from: payload) - let requestTurnId = Self.normalizedValue(request.turnId) - let rawCallId = Self.firstString(in: payload, keys: ["call_id", "callId"]) ?? fallbackCallId - let callId = Self.normalizedValue(rawCallId) - ?? "\(payloadTurnId ?? requestTurnId ?? "session"):\(question ?? "request_user_input")" - guard !publishedUserInputCallIds.contains(callId) else { return nil } - return UserInputCandidate(callId: callId, question: question) - } - - private func publishUserInput(_ userInput: UserInputCandidate) { - publishedUserInputCallIds.insert(userInput.callId) - let body = userInput.question ?? String( - localized: "agent.codex.input.body.needsInput", - defaultValue: "Codex is asking a question" - ) - onEvent(.userInput(request: request, body: body)) - } - - private func publishFailure(_ failure: FailureCandidate) { - onEvent(.failure(request: request, summary: Self.summarizeFailure(failure))) - } - - private func transcriptLineHasAssistantMessage(payload: [String: Any]) -> Bool { - guard (payload["type"] as? String) == "message", - (payload["role"] as? String) == "assistant", - let content = payload["content"] as? [[String: Any]] else { - return false - } - return content.contains { block in - guard let text = block["text"] as? String else { return false } - return !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + ) + finish() + } else { + finish(publishCompletion: true) } - } - private func findTranscriptPath() -> String? { - let normalizedSessionId = request.sessionId.trimmingCharacters(in: .whitespacesAndNewlines) - guard !normalizedSessionId.isEmpty else { return nil } - let codexHome = Self.normalizedValue(request.codexHome) ?? "~/.codex" - let sessionsURL = URL(fileURLWithPath: NSString(string: codexHome).expandingTildeInPath, isDirectory: true) - .appendingPathComponent("sessions", isDirectory: true) - let fileManager = FileManager.default - var newest: URL? - var newestModificationDate: Date? - for directoryURL in Self.recentSessionDirectories(sessionsURL: sessionsURL, fileManager: fileManager) { - guard let urls = try? fileManager.contentsOfDirectory( - at: directoryURL, - includingPropertiesForKeys: [.contentModificationDateKey], - options: [.skipsHiddenFiles] - ) else { - continue - } - for url in urls { - guard url.pathExtension == "jsonl", - url.lastPathComponent.contains(normalizedSessionId) else { - continue - } - let modificationDate = (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast - if newest == nil || modificationDate > (newestModificationDate ?? .distantPast) { - newest = url - newestModificationDate = modificationDate - } - } - } - return newest?.path + default: + break } + } - private static func recentSessionDirectories(sessionsURL: URL, fileManager: FileManager) -> [URL] { - var directories: [URL] = [] - var seenPaths = Set() - - func appendIfDirectory(_ url: URL) { - guard seenPaths.insert(url.path).inserted else { return } - var isDirectory: ObjCBool = false - guard fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory), - isDirectory.boolValue else { - return - } - directories.append(url) - } - - appendIfDirectory(sessionsURL) - var utcCalendar = Calendar(identifier: .gregorian) - utcCalendar.timeZone = TimeZone(secondsFromGMT: 0) ?? .current - for calendar in [Calendar.current, utcCalendar] { - for dayOffset in -14...1 { - guard let date = calendar.date(byAdding: .day, value: dayOffset, to: Date.now) else { continue } - let components = calendar.dateComponents([.year, .month, .day], from: date) - guard let year = components.year, - let month = components.month, - let day = components.day else { - continue - } - appendIfDirectory( - sessionsURL - .appendingPathComponent(String(format: "%04d", year), isDirectory: true) - .appendingPathComponent(String(format: "%02d", month), isDirectory: true) - .appendingPathComponent(String(format: "%02d", day), isDirectory: true) - ) - } - } - return directories + private func updateRelevantTurn(payload: [String: Any], onlyWhenMatching: Bool = false) { + guard let requestTurnId = CodexTranscriptMonitorParser.normalizedValue(request.turnId) else { + sawRelevantTurn = true + return } - - private static func failureCandidate( - from object: [String: Any], - isStreamError: Bool, - requireFailureSignal: Bool = true - ) -> FailureCandidate? { - let message = firstString(in: object, keys: ["message", "error", "body", "text", "description"]) - let additionalDetails = hookStringValue(object["additional_details"] ?? object["additionalDetails"]) - let codexErrorInfo = hookStringValue(object["codex_error_info"] ?? object["codexErrorInfo"]) - let eventType = firstString(in: object, keys: ["type", "kind"])?.lowercased() - let typedFailure = eventType == "error" || eventType == "stream_error" - let hasExplicitErrorField = object["error"].map { !($0 is NSNull) } ?? false - let signal = [message, additionalDetails, codexErrorInfo] - .compactMap { $0 } - .joined(separator: " ") - .lowercased() - guard !requireFailureSignal || - typedFailure || - hasExplicitErrorField || - codexErrorInfo != nil || - signal.contains("error") || - signal.contains("failed") || - signal.contains("exception") || - signal.contains("usage limit") || - signal.contains("rate limit") || - signal.contains("stream disconnected") || - signal.contains("connection") || - signal.contains("unauthorized") else { - return nil + guard let payloadTurnId = CodexTranscriptMonitorParser.firstString(in: payload, keys: ["turn_id", "turnId"]) else { + if !onlyWhenMatching { + sawRelevantTurn = false } - return FailureCandidate( - message: message ?? additionalDetails ?? codexErrorInfo ?? String( - localized: "agent.codex.error.defaultMessage", - defaultValue: "Codex reported an error" - ), - codexErrorInfo: codexErrorInfo, - additionalDetails: additionalDetails, - isStreamError: isStreamError || eventType == "stream_error" - ) + return } + sawRelevantTurn = payloadTurnId == requestTurnId + } - private static func summarizeFailure(_ candidate: FailureCandidate) -> CodexTranscriptFailureSummary { - let signal = [ - candidate.message, - candidate.codexErrorInfo, - candidate.additionalDetails, - candidate.isStreamError ? "stream_error" : nil - ] - .compactMap { $0 } - .joined(separator: " ") - .lowercased() - - let subtitle: String - let statusValue: String - if signal.contains("usage_limit") || - signal.contains("usage limit") || - signal.contains("rate limit") || - signal.contains("quota") { - subtitle = String(localized: "agent.codex.error.subtitle.rateLimit", defaultValue: "Rate limit") - statusValue = String(localized: "agent.codex.error.status.rateLimit", defaultValue: "Codex rate limit") - } else if signal.contains("unauthorized") || - signal.contains("auth") || - signal.contains("login") || - signal.contains("api key") { - subtitle = String(localized: "agent.codex.error.subtitle.auth", defaultValue: "Auth error") - statusValue = String(localized: "agent.codex.error.status.auth", defaultValue: "Codex auth error") - } else if candidate.isStreamError || - signal.contains("network") || - signal.contains("connection") || - signal.contains("stream disconnected") || - signal.contains("timed out") { - subtitle = String(localized: "agent.codex.error.subtitle.network", defaultValue: "Network error") - statusValue = String(localized: "agent.codex.error.status.network", defaultValue: "Codex network error") - } else { - subtitle = String(localized: "agent.codex.error.subtitle.generic", defaultValue: "Error") - statusValue = String(localized: "agent.codex.error.status.generic", defaultValue: "Codex error") - } - - let detail = [candidate.message, candidate.codexErrorInfo, candidate.additionalDetails] - .compactMap { normalizedValue($0).map(normalizedSingleLine) } - .first { !$0.isEmpty } ?? candidate.message - return CodexTranscriptFailureSummary( - statusValue: statusValue, - subtitle: subtitle, - body: truncate(detail, maxLength: 220) - ) - } + private func turnMatches(payload: [String: Any]) -> Bool { + guard let requestTurnId = CodexTranscriptMonitorParser.normalizedValue(request.turnId) else { return true } + return CodexTranscriptMonitorParser.firstString(in: payload, keys: ["turn_id", "turnId"]) == requestTurnId + } - private static func codexFunctionCallArgumentsObject(from payload: [String: Any]) -> [String: Any]? { - if let arguments = payload["arguments"] as? [String: Any] { - return arguments - } - guard let rawArguments = payload["arguments"] as? String, - let data = rawArguments.data(using: .utf8), - let arguments = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { - return nil - } - return arguments - } + private func userInputEventCandidate(from payload: [String: Any]) -> CodexTranscriptUserInputCandidate? { + guard turnMatches(payload: payload) || sawRelevantTurn else { return nil } + return userInputCandidate( + from: payload, + payloadTurnId: CodexTranscriptMonitorParser.firstString(in: payload, keys: ["turn_id", "turnId"]) + ) + } - private static func userInputQuestionText(from payload: [String: Any]) -> String? { - let questions = payload["questions"] as? [[String: Any]] ?? [] - for question in questions { - let text = firstString(in: question, keys: ["question", "header", "id"]) - let normalized = text.map(normalizedSingleLine)?.trimmingCharacters(in: .whitespacesAndNewlines) - if let normalized, !normalized.isEmpty { - return truncate(normalized, maxLength: 220) - } - } + private func userInputFunctionCallCandidate(from payload: [String: Any]) -> CodexTranscriptUserInputCandidate? { + guard (payload["type"] as? String) == "function_call", + (payload["name"] as? String) == "request_user_input" else { return nil } - - private static func hookStringValue(_ rawValue: Any?) -> String? { - guard let rawValue else { return nil } - if rawValue is NSNull { return nil } - if let value = rawValue as? String { - return normalizedValue(value) - } - if let array = rawValue as? [Any] { - let joined = array.compactMap(hookStringValue).joined(separator: " ") - return normalizedValue(joined) - } - if let dict = rawValue as? [String: Any] { - let joined = dict.keys.sorted().compactMap { hookStringValue(dict[$0]) }.joined(separator: " ") - return normalizedValue(joined) + let arguments = CodexTranscriptMonitorParser.codexFunctionCallArgumentsObject(from: payload) + let payloadTurnId = CodexTranscriptMonitorParser.firstString(in: payload, keys: ["turn_id", "turnId"]) + ?? arguments.flatMap { CodexTranscriptMonitorParser.firstString(in: $0, keys: ["turn_id", "turnId"]) } + if let requestTurnId = CodexTranscriptMonitorParser.normalizedValue(request.turnId) { + if let payloadTurnId { + guard payloadTurnId == requestTurnId else { return nil } + } else { + guard sawRelevantTurn else { return nil } } - return normalizedValue(String(describing: rawValue)) } + return userInputCandidate( + from: arguments ?? payload, + payloadTurnId: payloadTurnId, + fallbackCallId: CodexTranscriptMonitorParser.firstString(in: payload, keys: ["call_id", "callId"]) + ) + } - private static func firstString(in object: [String: Any], keys: [String]) -> String? { - for key in keys { - if let value = hookStringValue(object[key]) { - return value - } - } - return nil - } + private func userInputCandidate( + from payload: [String: Any], + payloadTurnId: String?, + fallbackCallId: String? = nil + ) -> CodexTranscriptUserInputCandidate? { + let question = CodexTranscriptMonitorParser.userInputQuestionText(from: payload) + let requestTurnId = CodexTranscriptMonitorParser.normalizedValue(request.turnId) + let rawCallId = CodexTranscriptMonitorParser.firstString(in: payload, keys: ["call_id", "callId"]) ?? fallbackCallId + let callId = CodexTranscriptMonitorParser.normalizedValue(rawCallId) + ?? "\(payloadTurnId ?? requestTurnId ?? "session"):\(question ?? "request_user_input")" + guard !publishedUserInputCallIds.contains(callId) else { return nil } + return CodexTranscriptUserInputCandidate(callId: callId, question: question) + } - private static func normalizedValue(_ value: String?) -> String? { - let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed?.isEmpty == false ? trimmed : nil - } + private func publishUserInput(_ userInput: CodexTranscriptUserInputCandidate) { + publishedUserInputCallIds.insert(userInput.callId) + let body = userInput.question ?? String( + localized: "agent.codex.input.body.needsInput", + defaultValue: "Codex is asking a question" + ) + onEvent(.userInput(request: request, body: body)) + } - private static func normalizedSingleLine(_ value: String) -> String { - value - .replacingOccurrences(of: "\r\n", with: "\n") - .replacingOccurrences(of: "\r", with: "\n") - .split(whereSeparator: \.isNewline) - .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } - .filter { !$0.isEmpty } - .joined(separator: " ") - } + private func publishFailure(_ failure: CodexTranscriptFailureCandidate) { + onEvent(.failure(request: request, summary: CodexTranscriptMonitorParser.summarizeFailure(failure))) + } - private static func truncate(_ value: String, maxLength: Int) -> String { - guard value.count > maxLength else { return value } - return String(value.prefix(maxLength - 3)) + "..." - } + private func findTranscriptPath() -> String? { + CodexTranscriptPathResolver.findTranscriptPath( + sessionId: request.sessionId, + codexHome: request.codexHome + ) } } diff --git a/Sources/CodexTranscriptMonitorModels.swift b/Sources/CodexTranscriptMonitorModels.swift new file mode 100644 index 000000000000..ea3d44bcd26e --- /dev/null +++ b/Sources/CodexTranscriptMonitorModels.swift @@ -0,0 +1,22 @@ +import Foundation + +struct CodexTranscriptMonitorRequest: Sendable { + let workspaceId: UUID + let surfaceId: UUID? + let sessionId: String + let turnId: String? + let transcriptPath: String? + let codexHome: String? +} + +struct CodexTranscriptFailureSummary: Sendable { + let statusValue: String + let subtitle: String + let body: String +} + +enum CodexTranscriptMonitorEvent: Sendable { + case userInput(request: CodexTranscriptMonitorRequest, body: String) + case failure(request: CodexTranscriptMonitorRequest, summary: CodexTranscriptFailureSummary) + case completion(request: CodexTranscriptMonitorRequest) +} diff --git a/Sources/CodexTranscriptMonitorParsing.swift b/Sources/CodexTranscriptMonitorParsing.swift new file mode 100644 index 000000000000..ec5389bff9cf --- /dev/null +++ b/Sources/CodexTranscriptMonitorParsing.swift @@ -0,0 +1,184 @@ +import Foundation + +struct CodexTranscriptFailureCandidate { + let message: String + let codexErrorInfo: String? + let additionalDetails: String? + let isStreamError: Bool +} + +struct CodexTranscriptUserInputCandidate { + let callId: String + let question: String? +} + +enum CodexTranscriptMonitorParser { + static func transcriptLineHasAssistantMessage(payload: [String: Any]) -> Bool { + guard (payload["type"] as? String) == "message", + (payload["role"] as? String) == "assistant", + let content = payload["content"] as? [[String: Any]] else { + return false + } + return content.contains { block in + guard let text = block["text"] as? String else { return false } + return !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + } + + static func failureCandidate( + from object: [String: Any], + isStreamError: Bool, + requireFailureSignal: Bool = true + ) -> CodexTranscriptFailureCandidate? { + let message = firstString(in: object, keys: ["message", "error", "body", "text", "description"]) + let additionalDetails = hookStringValue(object["additional_details"] ?? object["additionalDetails"]) + let codexErrorInfo = hookStringValue(object["codex_error_info"] ?? object["codexErrorInfo"]) + let eventType = firstString(in: object, keys: ["type", "kind"])?.lowercased() + let typedFailure = eventType == "error" || eventType == "stream_error" + let hasExplicitErrorField = object["error"].map { !($0 is NSNull) } ?? false + let signal = [message, additionalDetails, codexErrorInfo] + .compactMap { $0 } + .joined(separator: " ") + .lowercased() + guard !requireFailureSignal || + typedFailure || + hasExplicitErrorField || + codexErrorInfo != nil || + signal.contains("error") || + signal.contains("failed") || + signal.contains("exception") || + signal.contains("usage limit") || + signal.contains("rate limit") || + signal.contains("stream disconnected") || + signal.contains("connection") || + signal.contains("unauthorized") else { + return nil + } + return CodexTranscriptFailureCandidate( + message: message ?? additionalDetails ?? codexErrorInfo ?? String( + localized: "agent.codex.error.defaultMessage", + defaultValue: "Codex reported an error" + ), + codexErrorInfo: codexErrorInfo, + additionalDetails: additionalDetails, + isStreamError: isStreamError || eventType == "stream_error" + ) + } + + static func summarizeFailure(_ candidate: CodexTranscriptFailureCandidate) -> CodexTranscriptFailureSummary { + let signal = [ + candidate.message, + candidate.codexErrorInfo, + candidate.additionalDetails, + candidate.isStreamError ? "stream_error" : nil + ] + .compactMap { $0 } + .joined(separator: " ") + .lowercased() + + let subtitle: String + let statusValue: String + if signal.contains("usage_limit") || + signal.contains("usage limit") || + signal.contains("rate limit") || + signal.contains("quota") { + subtitle = String(localized: "agent.codex.error.subtitle.rateLimit", defaultValue: "Rate limit") + statusValue = String(localized: "agent.codex.error.status.rateLimit", defaultValue: "Codex rate limit") + } else if signal.contains("unauthorized") || + signal.contains("auth") || + signal.contains("login") || + signal.contains("api key") { + subtitle = String(localized: "agent.codex.error.subtitle.auth", defaultValue: "Auth error") + statusValue = String(localized: "agent.codex.error.status.auth", defaultValue: "Codex auth error") + } else if candidate.isStreamError || + signal.contains("network") || + signal.contains("connection") || + signal.contains("stream disconnected") || + signal.contains("timed out") { + subtitle = String(localized: "agent.codex.error.subtitle.network", defaultValue: "Network error") + statusValue = String(localized: "agent.codex.error.status.network", defaultValue: "Codex network error") + } else { + subtitle = String(localized: "agent.codex.error.subtitle.generic", defaultValue: "Error") + statusValue = String(localized: "agent.codex.error.status.generic", defaultValue: "Codex error") + } + + let detail = [candidate.message, candidate.codexErrorInfo, candidate.additionalDetails] + .compactMap { normalizedValue($0).map(normalizedSingleLine) } + .first { !$0.isEmpty } ?? candidate.message + return CodexTranscriptFailureSummary( + statusValue: statusValue, + subtitle: subtitle, + body: truncate(detail, maxLength: 220) + ) + } + + static func codexFunctionCallArgumentsObject(from payload: [String: Any]) -> [String: Any]? { + if let arguments = payload["arguments"] as? [String: Any] { + return arguments + } + guard let rawArguments = payload["arguments"] as? String, + let data = rawArguments.data(using: .utf8), + let arguments = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { + return nil + } + return arguments + } + + static func userInputQuestionText(from payload: [String: Any]) -> String? { + let questions = payload["questions"] as? [[String: Any]] ?? [] + for question in questions { + let text = firstString(in: question, keys: ["question", "header", "id"]) + let normalized = text.map(normalizedSingleLine)?.trimmingCharacters(in: .whitespacesAndNewlines) + if let normalized, !normalized.isEmpty { + return truncate(normalized, maxLength: 220) + } + } + return nil + } + + static func hookStringValue(_ rawValue: Any?) -> String? { + guard let rawValue else { return nil } + if rawValue is NSNull { return nil } + if let value = rawValue as? String { + return normalizedValue(value) + } + if let array = rawValue as? [Any] { + let joined = array.compactMap(hookStringValue).joined(separator: " ") + return normalizedValue(joined) + } + if let dict = rawValue as? [String: Any] { + let joined = dict.keys.sorted().compactMap { hookStringValue(dict[$0]) }.joined(separator: " ") + return normalizedValue(joined) + } + return normalizedValue(String(describing: rawValue)) + } + + static func firstString(in object: [String: Any], keys: [String]) -> String? { + for key in keys { + if let value = hookStringValue(object[key]) { + return value + } + } + return nil + } + + static func normalizedValue(_ value: String?) -> String? { + let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed?.isEmpty == false ? trimmed : nil + } + + static func normalizedSingleLine(_ value: String) -> String { + value + .replacingOccurrences(of: "\r\n", with: "\n") + .replacingOccurrences(of: "\r", with: "\n") + .split(whereSeparator: \.isNewline) + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + .joined(separator: " ") + } + + static func truncate(_ value: String, maxLength: Int) -> String { + guard value.count > maxLength else { return value } + return String(value.prefix(maxLength - 3)) + "..." + } +} diff --git a/Sources/CodexTranscriptMonitorRegistry.swift b/Sources/CodexTranscriptMonitorRegistry.swift new file mode 100644 index 000000000000..3edd27dba52a --- /dev/null +++ b/Sources/CodexTranscriptMonitorRegistry.swift @@ -0,0 +1,64 @@ +import Foundation + +// Mutable registry state is confined to `queue`; callers interact through async queue hops. +final class CodexTranscriptMonitorRegistry: @unchecked Sendable { + static let shared = CodexTranscriptMonitorRegistry() + + private let queue = DispatchQueue(label: "com.cmux.codex-transcript-monitor", qos: .utility) + private var monitorsBySessionId: [String: CodexTranscriptMonitorSession] = [:] + + private init() {} + + deinit {} + + func start(_ request: CodexTranscriptMonitorRequest) { + queue.async { [weak self] in + guard let self else { return } + let key = request.sessionId + self.monitorsBySessionId[key]?.cancel() + let monitor = CodexTranscriptMonitorSession( + request: request, + queue: self.queue, + onEvent: { [weak self] event in self?.publish(event) }, + onFinish: { [weak self] sessionId, monitor in + guard let self else { return } + if self.monitorsBySessionId[sessionId] === monitor { + self.monitorsBySessionId.removeValue(forKey: sessionId) + } + } + ) + self.monitorsBySessionId[key] = monitor + monitor.start() + } + } + + func stop(sessionId: String, turnId: String?) { + queue.async { [weak self] in + guard let self else { return } + if let monitor = self.monitorsBySessionId[sessionId], + turnId == nil || monitor.matches(turnId: turnId) { + monitor.cancel() + self.monitorsBySessionId.removeValue(forKey: sessionId) + } + } + } + + func stopWorkspace(_ workspaceId: UUID) { + queue.async { [weak self] in + guard let self else { return } + let matchingSessionIds = self.monitorsBySessionId.compactMap { sessionId, monitor in + monitor.workspaceId == workspaceId ? sessionId : nil + } + for sessionId in matchingSessionIds { + self.monitorsBySessionId[sessionId]?.cancel() + self.monitorsBySessionId.removeValue(forKey: sessionId) + } + } + } + + private func publish(_ event: CodexTranscriptMonitorEvent) { + Task { @MainActor in + TerminalController.shared.handleCodexTranscriptMonitorEvent(event) + } + } +} diff --git a/Sources/CodexTranscriptPathResolver.swift b/Sources/CodexTranscriptPathResolver.swift new file mode 100644 index 000000000000..5c7efb6ad19e --- /dev/null +++ b/Sources/CodexTranscriptPathResolver.swift @@ -0,0 +1,72 @@ +import Foundation + +enum CodexTranscriptPathResolver { + static func findTranscriptPath(sessionId: String, codexHome: String?) -> String? { + let normalizedSessionId = sessionId.trimmingCharacters(in: .whitespacesAndNewlines) + guard !normalizedSessionId.isEmpty else { return nil } + let codexHome = CodexTranscriptMonitorParser.normalizedValue(codexHome) ?? "~/.codex" + let sessionsURL = URL(fileURLWithPath: NSString(string: codexHome).expandingTildeInPath, isDirectory: true) + .appendingPathComponent("sessions", isDirectory: true) + let fileManager = FileManager.default + var newest: URL? + var newestModificationDate: Date? + for directoryURL in recentSessionDirectories(sessionsURL: sessionsURL, fileManager: fileManager) { + guard let urls = try? fileManager.contentsOfDirectory( + at: directoryURL, + includingPropertiesForKeys: [.contentModificationDateKey], + options: [.skipsHiddenFiles] + ) else { + continue + } + for url in urls { + guard url.pathExtension == "jsonl", + url.lastPathComponent.contains(normalizedSessionId) else { + continue + } + let modificationDate = (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast + if newest == nil || modificationDate > (newestModificationDate ?? .distantPast) { + newest = url + newestModificationDate = modificationDate + } + } + } + return newest?.path + } + + private static func recentSessionDirectories(sessionsURL: URL, fileManager: FileManager) -> [URL] { + var directories: [URL] = [] + var seenPaths = Set() + + func appendIfDirectory(_ url: URL) { + guard seenPaths.insert(url.path).inserted else { return } + var isDirectory: ObjCBool = false + guard fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory), + isDirectory.boolValue else { + return + } + directories.append(url) + } + + appendIfDirectory(sessionsURL) + var utcCalendar = Calendar(identifier: .gregorian) + utcCalendar.timeZone = TimeZone(secondsFromGMT: 0) ?? .current + for calendar in [Calendar.current, utcCalendar] { + for dayOffset in -14...1 { + guard let date = calendar.date(byAdding: .day, value: dayOffset, to: Date.now) else { continue } + let components = calendar.dateComponents([.year, .month, .day], from: date) + guard let year = components.year, + let month = components.month, + let day = components.day else { + continue + } + appendIfDirectory( + sessionsURL + .appendingPathComponent(String(format: "%04d", year), isDirectory: true) + .appendingPathComponent(String(format: "%02d", month), isDirectory: true) + .appendingPathComponent(String(format: "%02d", day), isDirectory: true) + ) + } + } + return directories + } +} diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 0cd498ce14e8..636dcedb5dca 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -7130,7 +7130,7 @@ final class Workspace: Identifiable, ObservableObject { static let terminalScrollBarHiddenDidChangeNotification = Notification.Name( "cmux.workspaceTerminalScrollBarHiddenDidChange" ) - private static let sidebarLogFlushDelay: DispatchTimeInterval = .milliseconds(50) + private static let sidebarLogFlushDelay: RunLoop.SchedulerTimeType.Stride = .milliseconds(50) let id: UUID @Published var title: String @@ -7323,7 +7323,8 @@ final class Workspace: Identifiable, ObservableObject { private var sidebarLogEntryLimit = Workspace.cachedSidebarLogEntryLimit() private lazy var sidebarLogBuffer = SidebarLogRingBuffer(limit: sidebarLogEntryLimit) private var pendingSidebarLogEntries: [SidebarLogEntry] = [] - private var sidebarLogFlushTimer: DispatchSourceTimer? + private let sidebarLogFlushSignal = PassthroughSubject() + private var sidebarLogFlushCancellable: AnyCancellable? private func sidebarObservationSignal( _ publisher: Published.Publisher @@ -7885,7 +7886,7 @@ final class Workspace: Identifiable, ObservableObject { } activeRemoteSessionControllerID = nil remoteSessionController?.stop() - sidebarLogFlushTimer?.cancel() + sidebarLogFlushCancellable?.cancel() TerminalController.stopCodexTranscriptMonitors(forWorkspaceId: id) } @@ -9823,39 +9824,37 @@ final class Workspace: Identifiable, ObservableObject { } func clearSidebarLogEntries() { - sidebarLogFlushTimer?.cancel() - sidebarLogFlushTimer = nil pendingSidebarLogEntries.removeAll(keepingCapacity: false) sidebarLogBuffer.removeAll() logEntries.removeAll() } private func setSidebarLogEntries(_ entries: [SidebarLogEntry]) { - sidebarLogFlushTimer?.cancel() - sidebarLogFlushTimer = nil pendingSidebarLogEntries.removeAll(keepingCapacity: false) sidebarLogBuffer.replaceAll(entries, limit: sidebarLogEntryLimit) logEntries = sidebarLogBuffer.entries() } private func scheduleSidebarLogFlush() { - guard sidebarLogFlushTimer == nil else { return } - let timer = DispatchSource.makeTimerSource(queue: .main) - timer.schedule(deadline: .now() + Self.sidebarLogFlushDelay) - timer.setEventHandler { [weak self] in - guard let self else { return } - Task { @MainActor in - self.flushPendingSidebarLogEntries() + ensureSidebarLogBatchingConfigured() + sidebarLogFlushSignal.send(()) + } + + private func ensureSidebarLogBatchingConfigured() { + guard sidebarLogFlushCancellable == nil else { return } + sidebarLogFlushCancellable = sidebarLogFlushSignal + .throttle(for: Self.sidebarLogFlushDelay, scheduler: RunLoop.main, latest: true) + .sink { [weak self] _ in + Task { @MainActor [weak self] in + self?.flushPendingSidebarLogEntries() + } } - } - sidebarLogFlushTimer = timer - timer.resume() } func flushPendingSidebarLogEntries() { - sidebarLogFlushTimer?.cancel() - sidebarLogFlushTimer = nil - guard !pendingSidebarLogEntries.isEmpty else { return } + guard !pendingSidebarLogEntries.isEmpty else { + return + } let entries = pendingSidebarLogEntries pendingSidebarLogEntries.removeAll(keepingCapacity: true) for entry in entries { From 1b537e03660f10cb4fa8562968aed05ff0e03259 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 13 May 2026 17:21:17 -0700 Subject: [PATCH 12/25] fix: address codex monitor review comments --- GhosttyTabs.xcodeproj/project.pbxproj | 10 +++++----- .../CodexTranscriptMonitor.swift | 3 ++- .../CodexTranscriptMonitorModels.swift | 0 .../CodexTranscriptMonitorParsing.swift | 0 .../CodexTranscriptMonitorRegistry.swift | 6 ++++-- .../CodexTranscriptPathResolver.swift | 0 6 files changed, 11 insertions(+), 8 deletions(-) rename Sources/{ => CodexTranscriptMonitor}/CodexTranscriptMonitor.swift (99%) rename Sources/{ => CodexTranscriptMonitor}/CodexTranscriptMonitorModels.swift (100%) rename Sources/{ => CodexTranscriptMonitor}/CodexTranscriptMonitorParsing.swift (100%) rename Sources/{ => CodexTranscriptMonitor}/CodexTranscriptMonitorRegistry.swift (93%) rename Sources/{ => CodexTranscriptMonitor}/CodexTranscriptPathResolver.swift (100%) diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index c74b881db669..a0d68073b017 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -694,12 +694,12 @@ A5001017 /* ghostty.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ghostty.h; sourceTree = ""; }; A5001018 /* cmux-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "cmux-Bridging-Header.h"; sourceTree = ""; }; A5001019 /* TerminalController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalController.swift; sourceTree = ""; }; - C0DE412700000000000002 /* CodexTranscriptMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitor.swift; sourceTree = ""; }; + C0DE412700000000000002 /* CodexTranscriptMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitor/CodexTranscriptMonitor.swift; sourceTree = ""; }; C0DE412700000000000004 /* SidebarLogRingBuffer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarLogRingBuffer.swift; sourceTree = ""; }; - C0DE412700000000000006 /* CodexTranscriptMonitorModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitorModels.swift; sourceTree = ""; }; - C0DE412700000000000008 /* CodexTranscriptMonitorRegistry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitorRegistry.swift; sourceTree = ""; }; - C0DE41270000000000000A /* CodexTranscriptMonitorParsing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitorParsing.swift; sourceTree = ""; }; - C0DE41270000000000000C /* CodexTranscriptPathResolver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptPathResolver.swift; sourceTree = ""; }; + C0DE412700000000000006 /* CodexTranscriptMonitorModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitor/CodexTranscriptMonitorModels.swift; sourceTree = ""; }; + C0DE412700000000000008 /* CodexTranscriptMonitorRegistry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitor/CodexTranscriptMonitorRegistry.swift; sourceTree = ""; }; + C0DE41270000000000000A /* CodexTranscriptMonitorParsing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitor/CodexTranscriptMonitorParsing.swift; sourceTree = ""; }; + C0DE41270000000000000C /* CodexTranscriptPathResolver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexTranscriptMonitor/CodexTranscriptPathResolver.swift; sourceTree = ""; }; E7E000000000000000000006 /* CmuxEventBus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxEventBus.swift; sourceTree = ""; }; E7E00000000000000000000E /* CmuxEventLogWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxEventLogWriter.swift; sourceTree = ""; }; E7E00000000000000000000C /* CmuxLifecycleEventPublishing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxLifecycleEventPublishing.swift; sourceTree = ""; }; diff --git a/Sources/CodexTranscriptMonitor.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift similarity index 99% rename from Sources/CodexTranscriptMonitor.swift rename to Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift index cacda8bc4707..aa1159423253 100644 --- a/Sources/CodexTranscriptMonitor.swift +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift @@ -222,7 +222,8 @@ final class CodexTranscriptMonitorSession { if objectType == "response_item", let payload = object["payload"] as? [String: Any] { - if CodexTranscriptMonitorParser.transcriptLineHasAssistantMessage(payload: payload) { + if CodexTranscriptMonitorParser.transcriptLineHasAssistantMessage(payload: payload), + turnMatches(payload: payload) || sawRelevantTurn { sawAssistantMessage = true } if let userInput = userInputFunctionCallCandidate(from: payload) { diff --git a/Sources/CodexTranscriptMonitorModels.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorModels.swift similarity index 100% rename from Sources/CodexTranscriptMonitorModels.swift rename to Sources/CodexTranscriptMonitor/CodexTranscriptMonitorModels.swift diff --git a/Sources/CodexTranscriptMonitorParsing.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorParsing.swift similarity index 100% rename from Sources/CodexTranscriptMonitorParsing.swift rename to Sources/CodexTranscriptMonitor/CodexTranscriptMonitorParsing.swift diff --git a/Sources/CodexTranscriptMonitorRegistry.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorRegistry.swift similarity index 93% rename from Sources/CodexTranscriptMonitorRegistry.swift rename to Sources/CodexTranscriptMonitor/CodexTranscriptMonitorRegistry.swift index 3edd27dba52a..229318bc38e6 100644 --- a/Sources/CodexTranscriptMonitorRegistry.swift +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorRegistry.swift @@ -57,8 +57,10 @@ final class CodexTranscriptMonitorRegistry: @unchecked Sendable { } private func publish(_ event: CodexTranscriptMonitorEvent) { - Task { @MainActor in - TerminalController.shared.handleCodexTranscriptMonitorEvent(event) + DispatchQueue.main.async { + MainActor.assumeIsolated { + TerminalController.shared.handleCodexTranscriptMonitorEvent(event) + } } } } diff --git a/Sources/CodexTranscriptPathResolver.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptPathResolver.swift similarity index 100% rename from Sources/CodexTranscriptPathResolver.swift rename to Sources/CodexTranscriptMonitor/CodexTranscriptPathResolver.swift From e80601c008cdccd79f88368cadddc372e69cdb5d Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 14 May 2026 16:52:32 -0700 Subject: [PATCH 13/25] fix: keep codex monitor turn state scoped --- .../CodexTranscriptMonitor.swift | 21 +++--- .../TerminalControllerSocketWriteTests.swift | 75 +++++++++++++++++++ 2 files changed, 87 insertions(+), 9 deletions(-) diff --git a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift index aa1159423253..cae7b5d9b9a4 100644 --- a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift @@ -240,8 +240,9 @@ final class CodexTranscriptMonitorSession { switch eventType { case "task_started": - updateRelevantTurn(payload: payload) - sawAssistantMessage = false + if updateRelevantTurn(payload: payload) { + sawAssistantMessage = false + } case "request_user_input": if let userInput = userInputEventCandidate(from: payload) { @@ -289,18 +290,20 @@ final class CodexTranscriptMonitorSession { } } - private func updateRelevantTurn(payload: [String: Any], onlyWhenMatching: Bool = false) { + @discardableResult + private func updateRelevantTurn(payload: [String: Any], onlyWhenMatching: Bool = false) -> Bool { guard let requestTurnId = CodexTranscriptMonitorParser.normalizedValue(request.turnId) else { sawRelevantTurn = true - return + return true } guard let payloadTurnId = CodexTranscriptMonitorParser.firstString(in: payload, keys: ["turn_id", "turnId"]) else { - if !onlyWhenMatching { - sawRelevantTurn = false - } - return + return false + } + let matches = payloadTurnId == requestTurnId + if matches || !onlyWhenMatching { + sawRelevantTurn = matches } - sawRelevantTurn = payloadTurnId == requestTurnId + return matches } private func turnMatches(payload: [String: Any]) -> Bool { diff --git a/cmuxTests/TerminalControllerSocketWriteTests.swift b/cmuxTests/TerminalControllerSocketWriteTests.swift index e4e735e2e1a6..9cc9ddec9cb5 100644 --- a/cmuxTests/TerminalControllerSocketWriteTests.swift +++ b/cmuxTests/TerminalControllerSocketWriteTests.swift @@ -77,3 +77,78 @@ final class TerminalControllerSocketWriteTests: XCTestCase { ) } } + +@MainActor +final class CodexTranscriptMonitorSessionTests: XCTestCase { + func testTaskStartedWithoutTurnDoesNotClearAssistantMessageForMonitoredTurn() throws { + let transcriptURL = FileManager.default.temporaryDirectory + .appendingPathComponent("codex-monitor-\(UUID().uuidString).jsonl") + defer { try? FileManager.default.removeItem(at: transcriptURL) } + + let turnId = "turn-target" + try writeTranscript( + [ + eventLine(type: "task_started", payload: ["turn_id": turnId]), + [ + "type": "response_item", + "payload": [ + "type": "message", + "role": "assistant", + "content": [["text": "done"]] + ] + ], + eventLine(type: "task_started", payload: [:]), + eventLine(type: "task_complete", payload: ["turn_id": turnId]) + ], + to: transcriptURL + ) + + let sessionId = "session-1" + var events: [CodexTranscriptMonitorEvent] = [] + var finishedSessionIds: [String] = [] + let session = CodexTranscriptMonitorSession( + request: CodexTranscriptMonitorRequest( + workspaceId: UUID(), + surfaceId: nil, + sessionId: sessionId, + turnId: turnId, + transcriptPath: transcriptURL.path, + codexHome: nil + ), + queue: DispatchQueue(label: "com.cmux.tests.codex-transcript-monitor"), + onEvent: { events.append($0) }, + onFinish: { finishedSessionId, _ in finishedSessionIds.append(finishedSessionId) } + ) + defer { session.cancel() } + + session.start() + + XCTAssertEqual(finishedSessionIds, [sessionId]) + XCTAssertTrue(events.contains { event in + if case .completion = event { + return true + } + return false + }) + XCTAssertFalse(events.contains { event in + if case .failure = event { + return true + } + return false + }) + } + + private static func eventLine(type: String, payload: [String: Any]) -> [String: Any] { + var eventPayload = payload + eventPayload["type"] = type + return ["type": "event_msg", "payload": eventPayload] + } + + private func writeTranscript(_ objects: [[String: Any]], to url: URL) throws { + let lines = try objects.map { object in + let data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) + return try XCTUnwrap(String(data: data, encoding: .utf8)) + } + try (lines.joined(separator: "\n") + "\n").write(to: url, atomically: true, encoding: .utf8) + } +} From caa0e3497f12d6f136f69f81157cb6cd44618300 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sun, 17 May 2026 23:18:13 -0700 Subject: [PATCH 14/25] fix: address codex monitor review feedback --- Sources/BackgroundWorkspacePrimeCoordinator.swift | 14 ++++---------- cmuxTests/TerminalControllerSocketWriteTests.swift | 6 +++--- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/Sources/BackgroundWorkspacePrimeCoordinator.swift b/Sources/BackgroundWorkspacePrimeCoordinator.swift index b72d0a0541e3..350bef0de88c 100644 --- a/Sources/BackgroundWorkspacePrimeCoordinator.swift +++ b/Sources/BackgroundWorkspacePrimeCoordinator.swift @@ -105,8 +105,6 @@ final class BackgroundWorkspacePrimeCoordinator { private var readinessWaitersByWorkspaceId: [UUID: [RegisteredWaiter]] = [:] private var readinessCancellables: Set = [] private var readinessObservers: [NSObjectProtocol] = [] - private var lastPendingBackgroundWorkspaceLoadIds: Set = [] - private var lastTabIds: Set = [] deinit { readinessCancellables.forEach { $0.cancel() } @@ -267,8 +265,6 @@ final class BackgroundWorkspacePrimeCoordinator { readinessObservers.removeAll(keepingCapacity: false) readinessWaitersByWorkspaceId.removeAll(keepingCapacity: false) observedTabManager = tabManager - lastPendingBackgroundWorkspaceLoadIds = tabManager.pendingBackgroundWorkspaceLoadIds - lastTabIds = Set(tabManager.tabs.map(\.id)) let readyObserver = NotificationCenter.default.addObserver( forName: .terminalSurfaceDidBecomeReady, @@ -331,17 +327,15 @@ final class BackgroundWorkspacePrimeCoordinator { } private func handlePendingWorkspaceIdsChange(_ pendingIds: Set, tabManager: TabManager) { - let removedIds = lastPendingBackgroundWorkspaceLoadIds.subtracting(pendingIds) - lastPendingBackgroundWorkspaceLoadIds = pendingIds - for workspaceId in removedIds { + let readyWorkspaceIds = readinessWaitersByWorkspaceId.keys.filter { !pendingIds.contains($0) } + for workspaceId in readyWorkspaceIds { evaluateRegisteredWaiters(for: workspaceId, tabManager: tabManager) } } private func handleTabIdsChange(_ tabIds: Set, tabManager: TabManager) { - let removedIds = lastTabIds.subtracting(tabIds) - lastTabIds = tabIds - for workspaceId in removedIds { + let removedWorkspaceIds = readinessWaitersByWorkspaceId.keys.filter { !tabIds.contains($0) } + for workspaceId in removedWorkspaceIds { evaluateRegisteredWaiters(for: workspaceId, tabManager: tabManager) } } diff --git a/cmuxTests/TerminalControllerSocketWriteTests.swift b/cmuxTests/TerminalControllerSocketWriteTests.swift index 9cc9ddec9cb5..806c0e3ad5c3 100644 --- a/cmuxTests/TerminalControllerSocketWriteTests.swift +++ b/cmuxTests/TerminalControllerSocketWriteTests.swift @@ -88,7 +88,7 @@ final class CodexTranscriptMonitorSessionTests: XCTestCase { let turnId = "turn-target" try writeTranscript( [ - eventLine(type: "task_started", payload: ["turn_id": turnId]), + Self.eventLine(type: "task_started", payload: ["turn_id": turnId]), [ "type": "response_item", "payload": [ @@ -97,8 +97,8 @@ final class CodexTranscriptMonitorSessionTests: XCTestCase { "content": [["text": "done"]] ] ], - eventLine(type: "task_started", payload: [:]), - eventLine(type: "task_complete", payload: ["turn_id": turnId]) + Self.eventLine(type: "task_started", payload: [:]), + Self.eventLine(type: "task_complete", payload: ["turn_id": turnId]) ], to: transcriptURL ) From 165e096323175330d087b1c1a2779ffe66c586c2 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 18 May 2026 00:02:21 -0700 Subject: [PATCH 15/25] fix: harden codex transcript monitor feedback --- Resources/Localizable.xcstrings | 68 +++++++++++++++++++ .../CodexTranscriptMonitor.swift | 10 ++- .../CodexTranscriptMonitorParsing.swift | 22 ++++-- .../TerminalControllerSocketWriteTests.swift | 21 ++++++ 4 files changed, 115 insertions(+), 6 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index ea49fe732408..f7d4aea8d032 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -20859,6 +20859,74 @@ } } }, + "agent.codex.error.body.auth": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Check Codex authentication and try again." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Codex の認証を確認して、もう一度お試しください。" + } + } + } + }, + "agent.codex.error.body.generic": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Codex stopped with an error. Try again." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Codex がエラーで停止しました。もう一度お試しください。" + } + } + } + }, + "agent.codex.error.body.network": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Check your network connection and try again." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ネットワーク接続を確認して、もう一度お試しください。" + } + } + } + }, + "agent.codex.error.body.rateLimit": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Codex usage is currently rate limited. Try again later." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "現在 Codex の利用がレート制限されています。後でもう一度お試しください。" + } + } + } + }, "agent.codex.input.body.needsInput": { "extractionState": "manual", "localizations": { diff --git a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift index cae7b5d9b9a4..475534a27bec 100644 --- a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift @@ -103,6 +103,7 @@ final class CodexTranscriptMonitorSession { let fd = open(expandedPath, O_EVTONLY) guard fd >= 0 else { transcriptPath = nil + resetTailState() scheduleRetry() return } @@ -131,8 +132,7 @@ final class CodexTranscriptMonitorSession { source?.cancel() source = nil transcriptPath = nil - readOffset = 0 - pendingData.removeAll(keepingCapacity: false) + resetTailState() scheduleRetry() return } @@ -176,6 +176,7 @@ final class CodexTranscriptMonitorSession { private func readIncremental(path: String) { guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else { transcriptPath = nil + resetTailState() scheduleRetry() return } @@ -374,4 +375,9 @@ final class CodexTranscriptMonitorSession { codexHome: request.codexHome ) } + + private func resetTailState() { + readOffset = 0 + pendingData.removeAll(keepingCapacity: false) + } } diff --git a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorParsing.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorParsing.swift index ec5389bff9cf..d9f8bedb4b47 100644 --- a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorParsing.swift +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorParsing.swift @@ -78,18 +78,27 @@ enum CodexTranscriptMonitorParser { let subtitle: String let statusValue: String + let body: String if signal.contains("usage_limit") || signal.contains("usage limit") || signal.contains("rate limit") || signal.contains("quota") { subtitle = String(localized: "agent.codex.error.subtitle.rateLimit", defaultValue: "Rate limit") statusValue = String(localized: "agent.codex.error.status.rateLimit", defaultValue: "Codex rate limit") + body = String( + localized: "agent.codex.error.body.rateLimit", + defaultValue: "Codex usage is currently rate limited. Try again later." + ) } else if signal.contains("unauthorized") || signal.contains("auth") || signal.contains("login") || signal.contains("api key") { subtitle = String(localized: "agent.codex.error.subtitle.auth", defaultValue: "Auth error") statusValue = String(localized: "agent.codex.error.status.auth", defaultValue: "Codex auth error") + body = String( + localized: "agent.codex.error.body.auth", + defaultValue: "Check Codex authentication and try again." + ) } else if candidate.isStreamError || signal.contains("network") || signal.contains("connection") || @@ -97,18 +106,23 @@ enum CodexTranscriptMonitorParser { signal.contains("timed out") { subtitle = String(localized: "agent.codex.error.subtitle.network", defaultValue: "Network error") statusValue = String(localized: "agent.codex.error.status.network", defaultValue: "Codex network error") + body = String( + localized: "agent.codex.error.body.network", + defaultValue: "Check your network connection and try again." + ) } else { subtitle = String(localized: "agent.codex.error.subtitle.generic", defaultValue: "Error") statusValue = String(localized: "agent.codex.error.status.generic", defaultValue: "Codex error") + body = String( + localized: "agent.codex.error.body.generic", + defaultValue: "Codex stopped with an error. Try again." + ) } - let detail = [candidate.message, candidate.codexErrorInfo, candidate.additionalDetails] - .compactMap { normalizedValue($0).map(normalizedSingleLine) } - .first { !$0.isEmpty } ?? candidate.message return CodexTranscriptFailureSummary( statusValue: statusValue, subtitle: subtitle, - body: truncate(detail, maxLength: 220) + body: body ) } diff --git a/cmuxTests/TerminalControllerSocketWriteTests.swift b/cmuxTests/TerminalControllerSocketWriteTests.swift index 806c0e3ad5c3..bf23a495dbe5 100644 --- a/cmuxTests/TerminalControllerSocketWriteTests.swift +++ b/cmuxTests/TerminalControllerSocketWriteTests.swift @@ -138,6 +138,27 @@ final class CodexTranscriptMonitorSessionTests: XCTestCase { }) } + func testFailureSummaryBodyDoesNotExposeRawUpstreamDetails() { + let summary = CodexTranscriptMonitorParser.summarizeFailure( + CodexTranscriptFailureCandidate( + message: "authentication failed: invalid API key sk-test-secret", + codexErrorInfo: "provider=gpt-example quota=private", + additionalDetails: nil, + isStreamError: false + ) + ) + + XCTAssertEqual( + summary.body, + String( + localized: "agent.codex.error.body.auth", + defaultValue: "Check Codex authentication and try again." + ) + ) + XCTAssertFalse(summary.body.contains("sk-test-secret")) + XCTAssertFalse(summary.body.contains("provider=")) + } + private static func eventLine(type: String, payload: [String: Any]) -> [String: Any] { var eventPayload = payload eventPayload["type"] = type From bd7773095b31093841c61a68ef87391a1190b681 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 18 May 2026 01:57:12 -0700 Subject: [PATCH 16/25] fix: address codex monitor review followups --- .../BackgroundWorkspacePrimeCoordinator.swift | 23 ++++----- .../CodexTranscriptMonitor.swift | 48 ++++++++++++++++--- Sources/TerminalController.swift | 3 ++ 3 files changed, 53 insertions(+), 21 deletions(-) diff --git a/Sources/BackgroundWorkspacePrimeCoordinator.swift b/Sources/BackgroundWorkspacePrimeCoordinator.swift index 350bef0de88c..b016060a0b20 100644 --- a/Sources/BackgroundWorkspacePrimeCoordinator.swift +++ b/Sources/BackgroundWorkspacePrimeCoordinator.swift @@ -51,14 +51,6 @@ final class BackgroundWorkspacePrimeCoordinator { } } - func addObserver(_ observer: NSObjectProtocol) { - addCleanup { NotificationCenter.default.removeObserver(observer) } - } - - func addCancellable(_ cancellable: AnyCancellable) { - addCleanup { cancellable.cancel() } - } - func addTask(_ task: Task) { addCleanup { task.cancel() } } @@ -98,6 +90,7 @@ final class BackgroundWorkspacePrimeCoordinator { } private struct RegisteredWaiter { + let id: UUID weak var waiter: Waiter? } @@ -245,11 +238,13 @@ final class BackgroundWorkspacePrimeCoordinator { tabManager: TabManager ) { ensureSharedReadinessObservers(tabManager: tabManager) - readinessWaitersByWorkspaceId[workspaceId, default: []].append(RegisteredWaiter(waiter: waiter)) - waiter.addCleanupAction { [weak self, weak waiter] in + let registrationId = UUID() + readinessWaitersByWorkspaceId[workspaceId, default: []].append( + RegisteredWaiter(id: registrationId, waiter: waiter) + ) + waiter.addCleanupAction { [weak self] in Task { @MainActor in - guard let waiter else { return } - self?.unregisterReadinessWaiter(waiter, workspaceId: workspaceId) + self?.unregisterReadinessWaiter(registrationId: registrationId, workspaceId: workspaceId) } } } @@ -316,9 +311,9 @@ final class BackgroundWorkspacePrimeCoordinator { readinessCancellables.insert(tabsObserver) } - private func unregisterReadinessWaiter(_ waiter: Waiter, workspaceId: UUID) { + private func unregisterReadinessWaiter(registrationId: UUID, workspaceId: UUID) { guard var waiters = readinessWaitersByWorkspaceId[workspaceId] else { return } - waiters.removeAll { $0.waiter == nil || $0.waiter === waiter || $0.waiter?.isResolved == true } + waiters.removeAll { $0.id == registrationId || $0.waiter == nil || $0.waiter?.isResolved == true } if waiters.isEmpty { readinessWaitersByWorkspaceId.removeValue(forKey: workspaceId) } else { diff --git a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift index 475534a27bec..d80aa7a51af5 100644 --- a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift @@ -4,6 +4,7 @@ import Foundation final class CodexTranscriptMonitorSession { private enum Policy { static let maxTailBytes: UInt64 = 512 * 1024 + static let maxBufferedLineBytes = 1 * 1024 * 1024 static let retryInterval: TimeInterval = 1 static let deadline: TimeInterval = 4 * 60 * 60 } @@ -20,6 +21,7 @@ final class CodexTranscriptMonitorSession { private var transcriptPath: String? private var readOffset: UInt64 = 0 private var pendingData = Data() + private var discardingOversizedLine = false private var publishedUserInputCallIds = Set() private var sawRelevantTurn = false private var sawAssistantMessage = false @@ -183,8 +185,7 @@ final class CodexTranscriptMonitorSession { defer { try? handle.close() } let endOffset = (try? handle.seekToEnd()) ?? 0 if readOffset > endOffset { - readOffset = 0 - pendingData.removeAll(keepingCapacity: false) + resetTailState() } let seekOffset = readOffset do { @@ -200,13 +201,45 @@ final class CodexTranscriptMonitorSession { private func process(data: Data) { guard !data.isEmpty else { return } - pendingData.append(data) - while let newline = pendingData.firstIndex(of: 0x0A) { - let lineData = pendingData[.. Bool { + guard !fragment.isEmpty else { return true } + guard pendingData.count + fragment.count <= Policy.maxBufferedLineBytes else { + pendingData.removeAll(keepingCapacity: false) + return false } + pendingData.append(contentsOf: fragment) + return true } private func processLine(_ lineData: Data) { @@ -379,5 +412,6 @@ final class CodexTranscriptMonitorSession { private func resetTailState() { readOffset = 0 pendingData.removeAll(keepingCapacity: false) + discardingOversizedLine = false } } diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 90d11a1b5156..6f0a0c6500fa 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -8651,6 +8651,9 @@ class TerminalController { return .err(code: "invalid_params", message: "agent.codex_transcript_monitor.start requires session_id", data: nil) } let surfaceId = v2UUID(params, "surface_id") + if v2HasNonNullParam(params, "surface_id"), surfaceId == nil { + return .err(code: "invalid_params", message: "Missing or invalid surface_id", data: nil) + } guard let workspace = tabForSidebarMutation(id: workspaceId) else { return .err(code: "not_found", message: "Workspace not found", data: ["workspace_id": workspaceId.uuidString]) From e7288cc6169ca52eb140197f244a26cbdb3664f3 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 18 May 2026 03:04:13 -0700 Subject: [PATCH 17/25] fix: preserve codex tail line boundaries --- .../CodexTranscriptMonitor/CodexTranscriptMonitor.swift | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift index d80aa7a51af5..540f481067ca 100644 --- a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift @@ -168,7 +168,13 @@ final class CodexTranscriptMonitorSession { } var data = handle.readDataToEndOfFile() let bytesRead = UInt64(data.count) - if startOffset > 0, let newline = data.firstIndex(of: 0x0A) { + if startOffset > 0 { + guard let newline = data.firstIndex(of: 0x0A) else { + pendingData.removeAll(keepingCapacity: false) + discardingOversizedLine = true + readOffset = startOffset + bytesRead + return + } data.removeSubrange(0...newline) } process(data: data) From ce08ee589b1df79c0abd2d3d0b61a2be77579dbd Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 18 May 2026 03:17:54 -0700 Subject: [PATCH 18/25] fix: keep codex tail boundary aware --- .../CodexTranscriptMonitor.swift | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift index 540f481067ca..c92533c8e4f7 100644 --- a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift @@ -160,6 +160,7 @@ final class CodexTranscriptMonitorSession { defer { try? handle.close() } let endOffset = (try? handle.seekToEnd()) ?? 0 let startOffset = endOffset > Policy.maxTailBytes ? endOffset - Policy.maxTailBytes : 0 + let startsAtLineBoundary = initialTailStartsAtLineBoundary(handle: handle, startOffset: startOffset) do { try handle.seek(toOffset: startOffset) } catch { @@ -168,7 +169,7 @@ final class CodexTranscriptMonitorSession { } var data = handle.readDataToEndOfFile() let bytesRead = UInt64(data.count) - if startOffset > 0 { + if startOffset > 0, !startsAtLineBoundary { guard let newline = data.firstIndex(of: 0x0A) else { pendingData.removeAll(keepingCapacity: false) discardingOversizedLine = true @@ -181,6 +182,16 @@ final class CodexTranscriptMonitorSession { readOffset = startOffset + bytesRead } + private func initialTailStartsAtLineBoundary(handle: FileHandle, startOffset: UInt64) -> Bool { + guard startOffset > 0 else { return true } + do { + try handle.seek(toOffset: startOffset - 1) + } catch { + return false + } + return handle.readData(ofLength: 1).first == 0x0A + } + private func readIncremental(path: String) { guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else { transcriptPath = nil From 3a99881e7066812474dd48426347815c1f6c2faf Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 18 May 2026 19:06:59 -0700 Subject: [PATCH 19/25] fix: cancel stale background prime waiters --- Sources/BackgroundWorkspacePrimeCoordinator.swift | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Sources/BackgroundWorkspacePrimeCoordinator.swift b/Sources/BackgroundWorkspacePrimeCoordinator.swift index b016060a0b20..b3c9f98fb78d 100644 --- a/Sources/BackgroundWorkspacePrimeCoordinator.swift +++ b/Sources/BackgroundWorkspacePrimeCoordinator.swift @@ -258,7 +258,7 @@ final class BackgroundWorkspacePrimeCoordinator { readinessCancellables.removeAll(keepingCapacity: false) readinessObservers.forEach { NotificationCenter.default.removeObserver($0) } readinessObservers.removeAll(keepingCapacity: false) - readinessWaitersByWorkspaceId.removeAll(keepingCapacity: false) + cancelRegisteredReadinessWaiters() observedTabManager = tabManager let readyObserver = NotificationCenter.default.addObserver( @@ -311,6 +311,14 @@ final class BackgroundWorkspacePrimeCoordinator { readinessCancellables.insert(tabsObserver) } + private func cancelRegisteredReadinessWaiters() { + let waiters = readinessWaitersByWorkspaceId.values.flatMap { registrations in + registrations.compactMap(\.waiter) + } + readinessWaitersByWorkspaceId.removeAll(keepingCapacity: false) + waiters.forEach { $0.finish(reason: .cancelled) } + } + private func unregisterReadinessWaiter(registrationId: UUID, workspaceId: UUID) { guard var waiters = readinessWaitersByWorkspaceId[workspaceId] else { return } waiters.removeAll { $0.id == registrationId || $0.waiter == nil || $0.waiter?.isResolved == true } From d16df4346e77f85ab7d1a225bb699f6d035794c0 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 19 May 2026 06:56:43 -0700 Subject: [PATCH 20/25] fix: reset codex monitor turn state on retail --- .../CodexTranscriptMonitor/CodexTranscriptMonitor.swift | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift index c92533c8e4f7..235552084e09 100644 --- a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift @@ -39,7 +39,7 @@ final class CodexTranscriptMonitorSession { self.onFinish = onFinish self.workspaceId = request.workspaceId self.transcriptPath = CodexTranscriptMonitorParser.normalizedValue(request.transcriptPath) - self.sawRelevantTurn = CodexTranscriptMonitorParser.normalizedValue(request.turnId) == nil + self.sawRelevantTurn = Self.initialSawRelevantTurn(for: request) } deinit { @@ -430,5 +430,11 @@ final class CodexTranscriptMonitorSession { readOffset = 0 pendingData.removeAll(keepingCapacity: false) discardingOversizedLine = false + sawRelevantTurn = Self.initialSawRelevantTurn(for: request) + sawAssistantMessage = false + } + + private static func initialSawRelevantTurn(for request: CodexTranscriptMonitorRequest) -> Bool { + CodexTranscriptMonitorParser.normalizedValue(request.turnId) == nil } } From 6f7571d6ec9b5a3984feccbdffc974d415b3ba06 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 21 May 2026 18:50:13 -0700 Subject: [PATCH 21/25] fix: localize codex error notification bodies --- Resources/Localizable.xcstrings | 72 ++------------------------------- 1 file changed, 4 insertions(+), 68 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index d1938b8fdf15..28197708ac5e 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -21901,74 +21901,10 @@ } } }, - "agent.codex.error.body.auth": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Check Codex authentication and try again." - } - }, - "ja": { - "stringUnit": { - "state": "translated", - "value": "Codex の認証を確認して、もう一度お試しください。" - } - } - } - }, - "agent.codex.error.body.generic": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Codex stopped with an error. Try again." - } - }, - "ja": { - "stringUnit": { - "state": "translated", - "value": "Codex がエラーで停止しました。もう一度お試しください。" - } - } - } - }, - "agent.codex.error.body.network": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Check your network connection and try again." - } - }, - "ja": { - "stringUnit": { - "state": "translated", - "value": "ネットワーク接続を確認して、もう一度お試しください。" - } - } - } - }, - "agent.codex.error.body.rateLimit": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Codex usage is currently rate limited. Try again later." - } - }, - "ja": { - "stringUnit": { - "state": "translated", - "value": "現在 Codex の利用がレート制限されています。後でもう一度お試しください。" - } - } - } - }, + "agent.codex.error.body.auth": { "extractionState": "manual", "localizations": { "ar": { "stringUnit": { "state": "translated", "value": "تحقق من مصادقة Codex وحاول مجددًا." } }, "bs": { "stringUnit": { "state": "translated", "value": "Provjerite Codex autentifikaciju i pokušajte ponovo." } }, "da": { "stringUnit": { "state": "translated", "value": "Kontrollér Codex-godkendelsen, og prøv igen." } }, "de": { "stringUnit": { "state": "translated", "value": "Überprüfen Sie die Codex-Authentifizierung und versuchen Sie es erneut." } }, "en": { "stringUnit": { "state": "translated", "value": "Check Codex authentication and try again." } }, "es": { "stringUnit": { "state": "translated", "value": "Comprueba la autenticación de Codex e inténtalo de nuevo." } }, "fr": { "stringUnit": { "state": "translated", "value": "Vérifiez l’authentification Codex et réessayez." } }, "it": { "stringUnit": { "state": "translated", "value": "Controlla l’autenticazione di Codex e riprova." } }, "ja": { "stringUnit": { "state": "translated", "value": "Codex の認証を確認して、もう一度お試しください。" } }, "km": { "stringUnit": { "state": "translated", "value": "ពិនិត្យការផ្ទៀងផ្ទាត់ Codex ហើយព្យាយាមម្ដងទៀត។" } }, "ko": { "stringUnit": { "state": "translated", "value": "Codex 인증을 확인하고 다시 시도하세요." } }, "nb": { "stringUnit": { "state": "translated", "value": "Kontroller Codex-autentiseringen og prøv igjen." } }, "pl": { "stringUnit": { "state": "translated", "value": "Sprawdź uwierzytelnianie Codex i spróbuj ponownie." } }, "pt-BR": { "stringUnit": { "state": "translated", "value": "Verifique a autenticação do Codex e tente novamente." } }, "ru": { "stringUnit": { "state": "translated", "value": "Проверьте аутентификацию Codex и повторите попытку." } }, "th": { "stringUnit": { "state": "translated", "value": "ตรวจสอบการตรวจสอบสิทธิ์ Codex แล้วลองอีกครั้ง" } }, "tr": { "stringUnit": { "state": "translated", "value": "Codex kimlik doğrulamasını kontrol edip tekrar deneyin." } }, "uk": { "stringUnit": { "state": "translated", "value": "Перевірте автентифікацію Codex і спробуйте ще раз." } }, "zh-Hans": { "stringUnit": { "state": "translated", "value": "检查 Codex 身份验证,然后重试。" } }, "zh-Hant": { "stringUnit": { "state": "translated", "value": "請檢查 Codex 驗證後再試一次。" } } } }, + "agent.codex.error.body.generic": { "extractionState": "manual", "localizations": { "ar": { "stringUnit": { "state": "translated", "value": "توقف Codex بسبب خطأ. حاول مرة أخرى." } }, "bs": { "stringUnit": { "state": "translated", "value": "Codex se zaustavio s greškom. Pokušajte ponovo." } }, "da": { "stringUnit": { "state": "translated", "value": "Codex stoppede med en fejl. Prøv igen." } }, "de": { "stringUnit": { "state": "translated", "value": "Codex wurde mit einem Fehler beendet. Versuchen Sie es erneut." } }, "en": { "stringUnit": { "state": "translated", "value": "Codex stopped with an error. Try again." } }, "es": { "stringUnit": { "state": "translated", "value": "Codex se detuvo con un error. Inténtalo de nuevo." } }, "fr": { "stringUnit": { "state": "translated", "value": "Codex s’est arrêté avec une erreur. Réessayez." } }, "it": { "stringUnit": { "state": "translated", "value": "Codex si è arrestato con un errore. Riprova." } }, "ja": { "stringUnit": { "state": "translated", "value": "Codex がエラーで停止しました。もう一度お試しください。" } }, "km": { "stringUnit": { "state": "translated", "value": "Codex បានឈប់ដោយមានកំហុស។ ព្យាយាមម្ដងទៀត។" } }, "ko": { "stringUnit": { "state": "translated", "value": "Codex가 오류로 중지되었습니다. 다시 시도하세요." } }, "nb": { "stringUnit": { "state": "translated", "value": "Codex stoppet med en feil. Prøv igjen." } }, "pl": { "stringUnit": { "state": "translated", "value": "Codex zatrzymał się z błędem. Spróbuj ponownie." } }, "pt-BR": { "stringUnit": { "state": "translated", "value": "O Codex parou com um erro. Tente novamente." } }, "ru": { "stringUnit": { "state": "translated", "value": "Codex остановился с ошибкой. Повторите попытку." } }, "th": { "stringUnit": { "state": "translated", "value": "Codex หยุดทำงานโดยมีข้อผิดพลาด ลองอีกครั้ง" } }, "tr": { "stringUnit": { "state": "translated", "value": "Codex bir hatayla durdu. Tekrar deneyin." } }, "uk": { "stringUnit": { "state": "translated", "value": "Codex зупинився з помилкою. Спробуйте ще раз." } }, "zh-Hans": { "stringUnit": { "state": "translated", "value": "Codex 因错误而停止。请重试。" } }, "zh-Hant": { "stringUnit": { "state": "translated", "value": "Codex 因發生錯誤而停止。請再試一次。" } } } }, + "agent.codex.error.body.network": { "extractionState": "manual", "localizations": { "ar": { "stringUnit": { "state": "translated", "value": "تحقق من اتصال الشبكة وحاول مجددًا." } }, "bs": { "stringUnit": { "state": "translated", "value": "Provjerite mrežnu vezu i pokušajte ponovo." } }, "da": { "stringUnit": { "state": "translated", "value": "Kontroller din netværksforbindelse, og prøv igen." } }, "de": { "stringUnit": { "state": "translated", "value": "Überprüfen Sie Ihre Netzwerkverbindung und versuchen Sie es erneut." } }, "en": { "stringUnit": { "state": "translated", "value": "Check your network connection and try again." } }, "es": { "stringUnit": { "state": "translated", "value": "Comprueba tu conexión de red e inténtalo de nuevo." } }, "fr": { "stringUnit": { "state": "translated", "value": "Vérifiez votre connexion réseau et réessayez." } }, "it": { "stringUnit": { "state": "translated", "value": "Controlla la connessione di rete e riprova." } }, "ja": { "stringUnit": { "state": "translated", "value": "ネットワーク接続を確認して、もう一度お試しください。" } }, "km": { "stringUnit": { "state": "translated", "value": "ពិនិត្យការតភ្ជាប់បណ្ដាញ រួចព្យាយាមម្ដងទៀត។" } }, "ko": { "stringUnit": { "state": "translated", "value": "네트워크 연결을 확인하고 다시 시도하세요." } }, "nb": { "stringUnit": { "state": "translated", "value": "Kontroller nettverkstilkoblingen og prøv igjen." } }, "pl": { "stringUnit": { "state": "translated", "value": "Sprawdź połączenie sieciowe i spróbuj ponownie." } }, "pt-BR": { "stringUnit": { "state": "translated", "value": "Verifique sua conexão de rede e tente novamente." } }, "ru": { "stringUnit": { "state": "translated", "value": "Проверьте сетевое подключение и повторите попытку." } }, "th": { "stringUnit": { "state": "translated", "value": "ตรวจสอบการเชื่อมต่อเครือข่ายแล้วลองอีกครั้ง" } }, "tr": { "stringUnit": { "state": "translated", "value": "Ağ bağlantınızı kontrol edip tekrar deneyin." } }, "uk": { "stringUnit": { "state": "translated", "value": "Перевірте підключення до мережі та спробуйте ще раз." } }, "zh-Hans": { "stringUnit": { "state": "translated", "value": "请检查您的网络连接,然后重试。" } }, "zh-Hant": { "stringUnit": { "state": "translated", "value": "請檢查您的網路連線後再試一次。" } } } }, + "agent.codex.error.body.rateLimit": { "extractionState": "manual", "localizations": { "ar": { "stringUnit": { "state": "translated", "value": "استخدام Codex محدود حاليًا. حاول مرة أخرى لاحقًا." } }, "bs": { "stringUnit": { "state": "translated", "value": "Korištenje Codexa je trenutno ograničeno stopom. Pokušajte ponovo kasnije." } }, "da": { "stringUnit": { "state": "translated", "value": "Brugen af Codex er i øjeblikket hastighedsbegrænset. Prøv igen senere." } }, "de": { "stringUnit": { "state": "translated", "value": "Die Codex-Nutzung ist derzeit durch ein Ratenlimit begrenzt. Versuchen Sie es später erneut." } }, "en": { "stringUnit": { "state": "translated", "value": "Codex usage is currently rate limited. Try again later." } }, "es": { "stringUnit": { "state": "translated", "value": "El uso de Codex tiene un límite de frecuencia en este momento. Inténtalo de nuevo más tarde." } }, "fr": { "stringUnit": { "state": "translated", "value": "L’utilisation de Codex est actuellement limitée par un quota. Réessayez plus tard." } }, "it": { "stringUnit": { "state": "translated", "value": "L’uso di Codex è attualmente soggetto a limite di frequenza. Riprova più tardi." } }, "ja": { "stringUnit": { "state": "translated", "value": "現在 Codex の利用がレート制限されています。後でもう一度お試しください。" } }, "km": { "stringUnit": { "state": "translated", "value": "ការប្រើប្រាស់ Codex កំពុងត្រូវបានកំណត់អត្រា។ សូមព្យាយាមម្ដងទៀតនៅពេលក្រោយ។" } }, "ko": { "stringUnit": { "state": "translated", "value": "현재 Codex 사용이 속도 제한을 받고 있습니다. 나중에 다시 시도하세요." } }, "nb": { "stringUnit": { "state": "translated", "value": "Codex-bruken er for øyeblikket hastighetsbegrenset. Prøv igjen senere." } }, "pl": { "stringUnit": { "state": "translated", "value": "Użycie Codex jest obecnie ograniczone limitem żądań. Spróbuj ponownie później." } }, "pt-BR": { "stringUnit": { "state": "translated", "value": "O uso do Codex está limitado por taxa no momento. Tente novamente mais tarde." } }, "ru": { "stringUnit": { "state": "translated", "value": "Использование Codex сейчас ограничено лимитом запросов. Повторите попытку позже." } }, "th": { "stringUnit": { "state": "translated", "value": "ขณะนี้การใช้งาน Codex ถูกจำกัดอัตรา ลองอีกครั้งภายหลัง" } }, "tr": { "stringUnit": { "state": "translated", "value": "Codex kullanımı şu anda hız sınırına takıldı. Daha sonra tekrar deneyin." } }, "uk": { "stringUnit": { "state": "translated", "value": "Використання Codex зараз обмежено лімітом запитів. Спробуйте пізніше." } }, "zh-Hans": { "stringUnit": { "state": "translated", "value": "Codex 用量目前受到速率限制。请稍后重试。" } }, "zh-Hant": { "stringUnit": { "state": "translated", "value": "Codex 使用量目前受到速率限制。請稍後再試。" } } } }, "agent.codex.input.body.needsInput": { "extractionState": "manual", "localizations": { From 65470829de51afb51048051a7eb38a3d5b517b6c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 21 May 2026 18:51:04 -0700 Subject: [PATCH 22/25] fix: flush sidebar logs inline on main run loop --- Sources/Workspace.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 368810b9de48..014b5a0e0e05 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -10286,7 +10286,7 @@ final class Workspace: Identifiable, ObservableObject { sidebarLogFlushCancellable = sidebarLogFlushSignal .throttle(for: Self.sidebarLogFlushDelay, scheduler: RunLoop.main, latest: true) .sink { [weak self] _ in - Task { @MainActor [weak self] in + MainActor.assumeIsolated { self?.flushPendingSidebarLogEntries() } } From 98c34853da471609a50146570eb81fafc7fed64a Mon Sep 17 00:00:00 2001 From: austinywang Date: Fri, 22 May 2026 13:07:54 -0700 Subject: [PATCH 23/25] fix: bound codex transcript retail after truncation --- .../CodexTranscriptMonitor.swift | 16 ++- .../TerminalControllerSocketWriteTests.swift | 111 +++++++++++++++++- 2 files changed, 122 insertions(+), 5 deletions(-) diff --git a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift index 235552084e09..57a9e6737a59 100644 --- a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift @@ -159,6 +159,10 @@ final class CodexTranscriptMonitorSession { guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: path)) else { return } defer { try? handle.close() } let endOffset = (try? handle.seekToEnd()) ?? 0 + readInitialTail(handle: handle, endOffset: endOffset) + } + + private func readInitialTail(handle: FileHandle, endOffset: UInt64) { let startOffset = endOffset > Policy.maxTailBytes ? endOffset - Policy.maxTailBytes : 0 let startsAtLineBoundary = initialTailStartsAtLineBoundary(handle: handle, startOffset: startOffset) do { @@ -167,7 +171,8 @@ final class CodexTranscriptMonitorSession { readOffset = endOffset return } - var data = handle.readDataToEndOfFile() + let bytesToRead = Int(endOffset - startOffset) + var data = handle.readData(ofLength: bytesToRead) let bytesRead = UInt64(data.count) if startOffset > 0, !startsAtLineBoundary { guard let newline = data.firstIndex(of: 0x0A) else { @@ -203,6 +208,8 @@ final class CodexTranscriptMonitorSession { let endOffset = (try? handle.seekToEnd()) ?? 0 if readOffset > endOffset { resetTailState() + readInitialTail(handle: handle, endOffset: endOffset) + return } let seekOffset = readOffset do { @@ -216,6 +223,12 @@ final class CodexTranscriptMonitorSession { readOffset = seekOffset + UInt64(data.count) } + #if DEBUG + func debugReadIncrementalForTests(path: String) { + readIncremental(path: path) + } + #endif + private func process(data: Data) { guard !data.isEmpty else { return } var cursor = data.startIndex @@ -430,6 +443,7 @@ final class CodexTranscriptMonitorSession { readOffset = 0 pendingData.removeAll(keepingCapacity: false) discardingOversizedLine = false + publishedUserInputCallIds.removeAll(keepingCapacity: false) sawRelevantTurn = Self.initialSawRelevantTurn(for: request) sawAssistantMessage = false } diff --git a/cmuxTests/TerminalControllerSocketWriteTests.swift b/cmuxTests/TerminalControllerSocketWriteTests.swift index bf23a495dbe5..c4501be91da3 100644 --- a/cmuxTests/TerminalControllerSocketWriteTests.swift +++ b/cmuxTests/TerminalControllerSocketWriteTests.swift @@ -138,6 +138,58 @@ final class CodexTranscriptMonitorSessionTests: XCTestCase { }) } + func testTruncationRecoveryOnlyReadsBoundedTail() throws { + let transcriptURL = FileManager.default.temporaryDirectory + .appendingPathComponent("codex-monitor-\(UUID().uuidString).jsonl") + defer { try? FileManager.default.removeItem(at: transcriptURL) } + + try Data(repeating: 0x70, count: 1_200_000).write(to: transcriptURL) + + let events = LockedUserInputBodies() + let session = makeMonitorSession(transcriptURL: transcriptURL, onEvent: events.record) + defer { session.cancel() } + + session.start() + XCTAssertEqual(events.snapshot(), []) + + let outsideTailLine = try transcriptLine(Self.userInputEvent(callId: "call-outside-tail", question: "outside tail")) + var replacement = Data() + replacement.append(Data(outsideTailLine.utf8)) + replacement.append(0x0A) + replacement.append(Data(repeating: 0x78, count: 700 * 1024)) + try replacement.write(to: transcriptURL) + + session.debugReadIncrementalForTests(path: transcriptURL.path) + + XCTAssertEqual(events.snapshot(), []) + } + + func testTruncationRecoveryClearsUserInputDedupeForReplacementTranscript() throws { + let transcriptURL = FileManager.default.temporaryDirectory + .appendingPathComponent("codex-monitor-\(UUID().uuidString).jsonl") + defer { try? FileManager.default.removeItem(at: transcriptURL) } + + let duplicateInputLine = try transcriptLine(Self.userInputEvent(callId: "call-duplicate", question: "continue?")) + var initial = Data() + initial.append(Data(String(repeating: "padding\n", count: 90_000).utf8)) + initial.append(Data(duplicateInputLine.utf8)) + initial.append(0x0A) + try initial.write(to: transcriptURL) + + let events = LockedUserInputBodies() + let session = makeMonitorSession(transcriptURL: transcriptURL, onEvent: events.record) + defer { session.cancel() } + + session.start() + XCTAssertEqual(events.snapshot(), ["continue?"]) + + try (duplicateInputLine + "\n").write(to: transcriptURL, atomically: true, encoding: .utf8) + + session.debugReadIncrementalForTests(path: transcriptURL.path) + + XCTAssertEqual(events.snapshot(), ["continue?", "continue?"]) + } + func testFailureSummaryBodyDoesNotExposeRawUpstreamDetails() { let summary = CodexTranscriptMonitorParser.summarizeFailure( CodexTranscriptFailureCandidate( @@ -165,11 +217,62 @@ final class CodexTranscriptMonitorSessionTests: XCTestCase { return ["type": "event_msg", "payload": eventPayload] } + private static func userInputEvent(callId: String, question: String) -> [String: Any] { + eventLine( + type: "request_user_input", + payload: [ + "call_id": callId, + "questions": [ + ["question": question] + ] + ] + ) + } + + private func makeMonitorSession( + transcriptURL: URL, + onEvent: @escaping (CodexTranscriptMonitorEvent) -> Void + ) -> CodexTranscriptMonitorSession { + CodexTranscriptMonitorSession( + request: CodexTranscriptMonitorRequest( + workspaceId: UUID(), + surfaceId: nil, + sessionId: "session-\(UUID().uuidString)", + turnId: nil, + transcriptPath: transcriptURL.path, + codexHome: nil + ), + queue: DispatchQueue(label: "com.cmux.tests.codex-transcript-monitor"), + onEvent: onEvent, + onFinish: { _, _ in } + ) + } + private func writeTranscript(_ objects: [[String: Any]], to url: URL) throws { - let lines = try objects.map { object in - let data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) - return try XCTUnwrap(String(data: data, encoding: .utf8)) - } + let lines = try objects.map(transcriptLine) try (lines.joined(separator: "\n") + "\n").write(to: url, atomically: true, encoding: .utf8) } + + private func transcriptLine(_ object: [String: Any]) throws -> String { + let data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) + return try XCTUnwrap(String(data: data, encoding: .utf8)) + } +} + +private final class LockedUserInputBodies: @unchecked Sendable { + private let lock = NSLock() + private var bodies: [String] = [] + + func record(_ event: CodexTranscriptMonitorEvent) { + guard case let .userInput(_, body) = event else { return } + lock.lock() + bodies.append(body) + lock.unlock() + } + + func snapshot() -> [String] { + lock.lock() + defer { lock.unlock() } + return bodies + } } From 7e317ee59d6a72c1e998dc36628cac777547be78 Mon Sep 17 00:00:00 2001 From: austinywang Date: Fri, 22 May 2026 14:05:05 -0700 Subject: [PATCH 24/25] fix: confine codex transcript session state --- .../BackgroundWorkspacePrimeCoordinator.swift | 1 + .../CodexTranscriptMonitor.swift | 35 +++++++++++++++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/Sources/BackgroundWorkspacePrimeCoordinator.swift b/Sources/BackgroundWorkspacePrimeCoordinator.swift index 82d0fd2e4268..3a4a8147d8c2 100644 --- a/Sources/BackgroundWorkspacePrimeCoordinator.swift +++ b/Sources/BackgroundWorkspacePrimeCoordinator.swift @@ -101,6 +101,7 @@ final class BackgroundWorkspacePrimeCoordinator { private var readinessObservers: [NSObjectProtocol] = [] deinit { + cancelRegisteredReadinessWaiters() readinessCancellables.forEach { $0.cancel() } readinessObservers.forEach { NotificationCenter.default.removeObserver($0) } } diff --git a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift index 57a9e6737a59..e08628f6e625 100644 --- a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift @@ -1,7 +1,9 @@ import Darwin import Foundation -final class CodexTranscriptMonitorSession { +// Mutable monitor state is confined to `queue`; public lifecycle entrypoints +// synchronously enter that queue so tests and registry callers share one owner. +final class CodexTranscriptMonitorSession: @unchecked Sendable { private enum Policy { static let maxTailBytes: UInt64 = 512 * 1024 static let maxBufferedLineBytes = 1 * 1024 * 1024 @@ -10,9 +12,11 @@ final class CodexTranscriptMonitorSession { } let workspaceId: UUID + private static let queueKey = DispatchSpecificKey() private let request: CodexTranscriptMonitorRequest private let queue: DispatchQueue + private let queueIdentifier: ObjectIdentifier private let onEvent: (CodexTranscriptMonitorEvent) -> Void private let onFinish: (String, CodexTranscriptMonitorSession) -> Void private var source: DispatchSourceFileSystemObject? @@ -35,11 +39,13 @@ final class CodexTranscriptMonitorSession { ) { self.request = request self.queue = queue + self.queueIdentifier = ObjectIdentifier(queue) self.onEvent = onEvent self.onFinish = onFinish self.workspaceId = request.workspaceId self.transcriptPath = CodexTranscriptMonitorParser.normalizedValue(request.transcriptPath) self.sawRelevantTurn = Self.initialSawRelevantTurn(for: request) + queue.setSpecific(key: Self.queueKey, value: queueIdentifier) } deinit { @@ -47,6 +53,13 @@ final class CodexTranscriptMonitorSession { } func start() { + syncOnQueue { + self.startOnQueue() + } + } + + private func startOnQueue() { + guard !finished else { return } armDeadline() installSourceOrRetry() } @@ -57,6 +70,12 @@ final class CodexTranscriptMonitorSession { } func cancel() { + syncOnQueue { + self.cancelOnQueue() + } + } + + private func cancelOnQueue() { finished = true source?.cancel() source = nil @@ -71,7 +90,7 @@ final class CodexTranscriptMonitorSession { if publishCompletion { onEvent(.completion(request: request)) } - cancel() + cancelOnQueue() onFinish(request.sessionId, self) } @@ -225,10 +244,20 @@ final class CodexTranscriptMonitorSession { #if DEBUG func debugReadIncrementalForTests(path: String) { - readIncremental(path: path) + syncOnQueue { + self.readIncremental(path: path) + } } #endif + private func syncOnQueue(_ operation: @Sendable () -> Void) { + if DispatchQueue.getSpecific(key: Self.queueKey) == queueIdentifier { + operation() + } else { + queue.sync(execute: operation) + } + } + private func process(data: Data) { guard !data.isEmpty else { return } var cursor = data.startIndex From 0c3cc114f9783860deec6a170edc06e17b913229 Mon Sep 17 00:00:00 2001 From: austinywang Date: Fri, 22 May 2026 14:09:40 -0700 Subject: [PATCH 25/25] fix: cancel readiness waiters from deinit --- Sources/BackgroundWorkspacePrimeCoordinator.swift | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Sources/BackgroundWorkspacePrimeCoordinator.swift b/Sources/BackgroundWorkspacePrimeCoordinator.swift index 3a4a8147d8c2..f1f01e42d8a9 100644 --- a/Sources/BackgroundWorkspacePrimeCoordinator.swift +++ b/Sources/BackgroundWorkspacePrimeCoordinator.swift @@ -101,7 +101,11 @@ final class BackgroundWorkspacePrimeCoordinator { private var readinessObservers: [NSObjectProtocol] = [] deinit { - cancelRegisteredReadinessWaiters() + let waiters = readinessWaitersByWorkspaceId.values.flatMap { registrations in + registrations.compactMap(\.waiter) + } + readinessWaitersByWorkspaceId.removeAll(keepingCapacity: false) + waiters.forEach { $0.finish(reason: .cancelled) } readinessCancellables.forEach { $0.cancel() } readinessObservers.forEach { NotificationCenter.default.removeObserver($0) } }