diff --git a/CLI/cmux.swift b/CLI/cmux.swift index eefb3a698918..8748e750fb42 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -461,16 +461,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] = [:] @@ -19706,12 +19696,6 @@ struct CMUXCLI { case failure(CodexHookFailureCandidate) } - private enum CodexMonitorOwnerState { - case alive - case gone - case unknown - } - private func summarizeCodexHookFailure( parsedInput: ClaudeHookParsedInput, sessionId: String, @@ -20464,397 +20448,79 @@ 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?, - preservingLeasePath: String? = nil, - 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 preservingPath = preservingLeasePath.map { - URL(fileURLWithPath: $0, isDirectory: false).standardizedFileURL.path - } - let directory = codexMonitorLeaseDirectory(env: env) - let targetPaths = ((try? fileManager.contentsOfDirectory( - at: directory, - includingPropertiesForKeys: nil, - options: [.skipsHiddenFiles] - )) ?? []).map(\.path) - - for path in targetPaths { - let standardizedPath = URL(fileURLWithPath: path, isDirectory: false).standardizedFileURL.path - guard preservingPath == nil || standardizedPath != preservingPath else { - continue - } - 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, - !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 } - 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": normalizedWorkspaceId, + "session_id": normalizedSessionId, ] - if let surfaceId, !surfaceId.isEmpty { - monitorArgs += ["--surface", surfaceId] - } - if let turnId, !turnId.isEmpty { - monitorArgs += ["--turn", turnId] + if let surfaceId = normalizedHookValue(surfaceId) { + params["surface_id"] = surfaceId } - if let transcriptPath, !transcriptPath.isEmpty { - monitorArgs += ["--transcript", transcriptPath] + if let turnId = normalizedHookValue(turnId) { + params["turn_id"] = turnId } - if let cwd, !cwd.isEmpty { - monitorArgs += ["--cwd", cwd] + if let transcriptPath = normalizedHookValue(transcriptPath) { + params["transcript_path"] = transcriptPath } - if let leasePath, !leasePath.isEmpty { - monitorArgs += ["--lease", leasePath] + if let codexHome = normalizedHookValue(env["CODEX_HOME"]) { + params["codex_home"] = codexHome } - 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 - } - - 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)) - } - } - - 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? { @@ -24246,11 +23912,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 env, then the caller process. Grok strips CMUX_* from hook // subprocesses, so PID attribution is the only reliable live binding. @@ -24651,35 +24312,14 @@ export default function cmuxPiSessionExtension(pi: ExtensionAPI) { telemetry.breadcrumb("\(def.name)-hook.prompt-submit.nested-suppressed") } if def.name == "codex", !sessionId.isEmpty, !suppressVisibleMutations { - let leasePath = createCodexMonitorLease( - 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] - ) - } else { - retireCodexMonitorLeases( - sessionId: sessionId, - turnId: nil, - preservingLeasePath: leasePath, - env: env - ) - } - startCodexTranscriptMonitor( + requestCodexTranscriptMonitorStart( 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 ) } @@ -24688,7 +24328,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 + ) } } let mapped = sessionId.isEmpty ? nil : (try? store.lookup(sessionId: sessionId)) @@ -25118,7 +24763,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 def.name == "grok" || def.name == "antigravity" { if let mapped = sessionId.isEmpty ? nil : (try? store.lookup(sessionId: sessionId)) { diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index db674105e604..4bdf5f279e54 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -21913,6 +21913,10 @@ } } }, + "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": { diff --git a/Sources/BackgroundWorkspacePrimeCoordinator.swift b/Sources/BackgroundWorkspacePrimeCoordinator.swift index e74055467071..f1f01e42d8a9 100644 --- a/Sources/BackgroundWorkspacePrimeCoordinator.swift +++ b/Sources/BackgroundWorkspacePrimeCoordinator.swift @@ -52,18 +52,14 @@ 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() } } + func addCleanupAction(_ action: @escaping () -> Void) { + addCleanup(action) + } + func finish(reason: PrimeCompletionReason) { let drained: (CheckedContinuation?, [() -> Void])? lock.lock() @@ -94,8 +90,24 @@ final class BackgroundWorkspacePrimeCoordinator { } } + private struct RegisteredWaiter { + let id: UUID + weak var waiter: Waiter? + } + + private weak var observedTabManager: TabManager? + private var readinessWaitersByWorkspaceId: [UUID: [RegisteredWaiter]] = [:] + private var readinessCancellables: Set = [] + private var readinessObservers: [NSObjectProtocol] = [] + deinit { - // Explicit for the required_deinit lint; per-prime resources live on Waiter. + 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) } } func taskKey(for tabManager: TabManager) -> [String] { @@ -215,7 +227,7 @@ final class BackgroundWorkspacePrimeCoordinator { waiter.start(continuation: continuation) guard !waiter.isResolved else { return } - installReadinessObservers( + registerReadinessWaiter( waiter: waiter, workspaceId: workspaceId, tabManager: tabManager @@ -247,68 +259,130 @@ final class BackgroundWorkspacePrimeCoordinator { } } - private func installReadinessObservers( + private func registerReadinessWaiter( waiter: Waiter, workspaceId: UUID, tabManager: TabManager ) { + ensureSharedReadinessObservers(tabManager: tabManager) + let registrationId = UUID() + readinessWaitersByWorkspaceId[workspaceId, default: []].append( + RegisteredWaiter(id: registrationId, waiter: waiter) + ) + waiter.addCleanupAction { [weak self] in + Task { @MainActor in + self?.unregisterReadinessWaiter(registrationId: registrationId, 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) + cancelRegisteredReadinessWaiters() + observedTabManager = tabManager + 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 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 } + if waiters.isEmpty { + readinessWaitersByWorkspaceId.removeValue(forKey: workspaceId) + } else { + readinessWaitersByWorkspaceId[workspaceId] = waiters + } + } + + private func handlePendingWorkspaceIdsChange(_ pendingIds: Set, tabManager: TabManager) { + 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 removedWorkspaceIds = readinessWaitersByWorkspaceId.keys.filter { !tabIds.contains($0) } + for workspaceId in removedWorkspaceIds { + 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/CodexTranscriptMonitor/CodexTranscriptMonitor.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift new file mode 100644 index 000000000000..e08628f6e625 --- /dev/null +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitor.swift @@ -0,0 +1,483 @@ +import Darwin +import Foundation + +// 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 + static let retryInterval: TimeInterval = 1 + static let deadline: TimeInterval = 4 * 60 * 60 + } + + 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? + private var retryTimer: DispatchSourceTimer? + private var deadlineTimer: DispatchSourceTimer? + 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 + 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.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 { + cancel() + } + + func start() { + syncOnQueue { + self.startOnQueue() + } + } + + private func startOnQueue() { + guard !finished else { return } + armDeadline() + installSourceOrRetry() + } + + func matches(turnId: String?) -> Bool { + guard let turnId = CodexTranscriptMonitorParser.normalizedValue(turnId) else { return true } + return CodexTranscriptMonitorParser.normalizedValue(request.turnId) == turnId + } + + func cancel() { + syncOnQueue { + self.cancelOnQueue() + } + } + + private func cancelOnQueue() { + 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)) + } + cancelOnQueue() + 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 + resetTailState() + 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 + resetTailState() + 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 + 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 { + try handle.seek(toOffset: startOffset) + } catch { + readOffset = endOffset + return + } + 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 { + pendingData.removeAll(keepingCapacity: false) + discardingOversizedLine = true + readOffset = startOffset + bytesRead + return + } + data.removeSubrange(0...newline) + } + process(data: data) + 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 + resetTailState() + scheduleRetry() + return + } + defer { try? handle.close() } + let endOffset = (try? handle.seekToEnd()) ?? 0 + if readOffset > endOffset { + resetTailState() + readInitialTail(handle: handle, endOffset: endOffset) + return + } + 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) + } + + #if DEBUG + func debugReadIncrementalForTests(path: String) { + 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 + while cursor < data.endIndex { + if discardingOversizedLine { + guard let newline = data[cursor...].firstIndex(of: 0x0A) else { return } + discardingOversizedLine = false + cursor = data.index(after: newline) + continue + } + + guard let newline = data[cursor...].firstIndex(of: 0x0A) else { + if !appendPendingLineFragment(data[cursor...]) { + discardingOversizedLine = true + } + return + } + + let lineData = data[cursor.. 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) { + guard let object = try? JSONSerialization.jsonObject(with: lineData, options: []) as? [String: Any], + let objectType = object["type"] as? String else { + return + } + + if objectType == "turn_context", + let payload = object["payload"] as? [String: Any] { + updateRelevantTurn(payload: payload) + return + } + + if objectType == "response_item", + let payload = object["payload"] as? [String: Any] { + if CodexTranscriptMonitorParser.transcriptLineHasAssistantMessage(payload: payload), + turnMatches(payload: payload) || sawRelevantTurn { + sawAssistantMessage = true + } + if let userInput = userInputFunctionCallCandidate(from: payload) { + publishUserInput(userInput) + } + return + } + + guard objectType == "event_msg", + let payload = object["payload"] as? [String: Any], + let eventType = payload["type"] as? String else { + return + } + + switch eventType { + case "task_started": + if updateRelevantTurn(payload: payload) { + sawAssistantMessage = false + } + + case "request_user_input": + if let userInput = userInputEventCandidate(from: payload) { + publishUserInput(userInput) + } + + case "error", "stream_error": + updateRelevantTurn(payload: payload, onlyWhenMatching: true) + guard turnMatches(payload: payload) || sawRelevantTurn else { return } + if let failure = CodexTranscriptMonitorParser.failureCandidate( + from: payload, + isStreamError: eventType == "stream_error", + requireFailureSignal: false + ) { + publishFailure(failure) + finish() + } + + case "task_complete", "turn_complete": + guard turnMatches(payload: payload) else { return } + sawRelevantTurn = true + if let lastMessage = payload["last_agent_message"] as? String, + !lastMessage.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + sawAssistantMessage = true + finish(publishCompletion: true) + } else if !sawAssistantMessage { + publishFailure( + CodexTranscriptFailureCandidate( + message: String( + localized: "agent.codex.error.noFinalResponse", + defaultValue: "Codex ended before sending a final response" + ), + codexErrorInfo: nil, + additionalDetails: nil, + isStreamError: false + ) + ) + finish() + } else { + finish(publishCompletion: true) + } + + default: + break + } + } + + @discardableResult + private func updateRelevantTurn(payload: [String: Any], onlyWhenMatching: Bool = false) -> Bool { + guard let requestTurnId = CodexTranscriptMonitorParser.normalizedValue(request.turnId) else { + sawRelevantTurn = true + return true + } + guard let payloadTurnId = CodexTranscriptMonitorParser.firstString(in: payload, keys: ["turn_id", "turnId"]) else { + return false + } + let matches = payloadTurnId == requestTurnId + if matches || !onlyWhenMatching { + sawRelevantTurn = matches + } + return matches + } + + 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 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 func userInputFunctionCallCandidate(from payload: [String: Any]) -> CodexTranscriptUserInputCandidate? { + guard (payload["type"] as? String) == "function_call", + (payload["name"] as? String) == "request_user_input" else { + return nil + } + 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 userInputCandidate( + from: arguments ?? payload, + payloadTurnId: payloadTurnId, + fallbackCallId: CodexTranscriptMonitorParser.firstString(in: payload, keys: ["call_id", "callId"]) + ) + } + + 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 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 func publishFailure(_ failure: CodexTranscriptFailureCandidate) { + onEvent(.failure(request: request, summary: CodexTranscriptMonitorParser.summarizeFailure(failure))) + } + + private func findTranscriptPath() -> String? { + CodexTranscriptPathResolver.findTranscriptPath( + sessionId: request.sessionId, + codexHome: request.codexHome + ) + } + + private func resetTailState() { + readOffset = 0 + pendingData.removeAll(keepingCapacity: false) + discardingOversizedLine = false + publishedUserInputCallIds.removeAll(keepingCapacity: false) + sawRelevantTurn = Self.initialSawRelevantTurn(for: request) + sawAssistantMessage = false + } + + private static func initialSawRelevantTurn(for request: CodexTranscriptMonitorRequest) -> Bool { + CodexTranscriptMonitorParser.normalizedValue(request.turnId) == nil + } +} diff --git a/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorModels.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorModels.swift new file mode 100644 index 000000000000..ea3d44bcd26e --- /dev/null +++ b/Sources/CodexTranscriptMonitor/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/CodexTranscriptMonitor/CodexTranscriptMonitorParsing.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorParsing.swift new file mode 100644 index 000000000000..d9f8bedb4b47 --- /dev/null +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorParsing.swift @@ -0,0 +1,198 @@ +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 + 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") || + 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") + 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." + ) + } + + return CodexTranscriptFailureSummary( + statusValue: statusValue, + subtitle: subtitle, + body: body + ) + } + + 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/CodexTranscriptMonitor/CodexTranscriptMonitorRegistry.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorRegistry.swift new file mode 100644 index 000000000000..229318bc38e6 --- /dev/null +++ b/Sources/CodexTranscriptMonitor/CodexTranscriptMonitorRegistry.swift @@ -0,0 +1,66 @@ +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) { + DispatchQueue.main.async { + MainActor.assumeIsolated { + TerminalController.shared.handleCodexTranscriptMonitorEvent(event) + } + } + } +} diff --git a/Sources/CodexTranscriptMonitor/CodexTranscriptPathResolver.swift b/Sources/CodexTranscriptMonitor/CodexTranscriptPathResolver.swift new file mode 100644 index 000000000000..5c7efb6ad19e --- /dev/null +++ b/Sources/CodexTranscriptMonitor/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/ContentView.swift b/Sources/ContentView.swift index e7e58e8dc44f..6f76846cf3b3 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -12994,6 +12994,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/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.. 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") + 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]) + } + 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]) + } + + nonisolated static func stopCodexTranscriptMonitors(forWorkspaceId workspaceId: UUID) { + CodexTranscriptMonitorRegistry.shared.stopWorkspace(workspaceId) + } + + func handleCodexTranscriptMonitorEvent(_ event: CodexTranscriptMonitorEvent) { + let request: CodexTranscriptMonitorRequest + switch event { + case .userInput(let eventRequest, _), .failure(let eventRequest, _), .completion(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 + ) + + case .completion: + if tab.statusEntries["codex"]?.icon == "bell.fill" { + tab.statusEntries.removeValue(forKey: "codex") + } + } + } + // MARK: - V2 App Focus Methods private func v2AppFocusOverride(params: [String: Any]) -> V2CallResult { @@ -18140,12 +18262,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 } @@ -18157,7 +18274,7 @@ class TerminalController { result = "ERROR: Tab not found" return } - tab.logEntries.removeAll() + tab.clearSidebarLogEntries() } return result } @@ -18181,6 +18298,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 0959bc7a89f1..014b5a0e0e05 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -165,6 +165,7 @@ extension Workspace { restorableAgentIndex: RestorableAgentSessionIndex? = nil, surfaceResumeBindingIndex: SurfaceResumeBindingIndex? = nil ) -> SessionWorkspaceSnapshot { + flushPendingSidebarLogEntries() let tree = bonsplitController.treeSnapshot() let layout = sessionLayoutSnapshot(from: tree) if let surfaceResumeBindingIndex { @@ -307,14 +308,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) } @@ -7373,6 +7374,7 @@ final class Workspace: Identifiable, ObservableObject { static let terminalScrollBarHiddenDidChangeNotification = Notification.Name( "cmux.workspaceTerminalScrollBarHiddenDidChange" ) + private static let sidebarLogFlushDelay: RunLoop.SchedulerTimeType.Stride = .milliseconds(50) let id: UUID @Published var title: String @@ -7569,6 +7571,11 @@ final class Workspace: Identifiable, ObservableObject { var restoredAgentResumeStatesByPanelId: [UUID: RestoredAgentResumeState] = [:] var invalidatedRestoredAgentFingerprintsByPanelId: [UUID: Int] = [:] private var pendingTerminalInputObserversByPanelId: [UUID: [WorkspacePendingTerminalInputObserver]] = [:] + private var sidebarLogEntryLimit = Workspace.cachedSidebarLogEntryLimit() + private lazy var sidebarLogBuffer = SidebarLogRingBuffer(limit: sidebarLogEntryLimit) + private var pendingSidebarLogEntries: [SidebarLogEntry] = [] + private let sidebarLogFlushSignal = PassthroughSubject() + private var sidebarLogFlushCancellable: AnyCancellable? private func sidebarObservationSignal( _ publisher: Published.Publisher @@ -7582,11 +7589,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), ] @@ -8128,6 +8142,8 @@ final class Workspace: Identifiable, ObservableObject { } activeRemoteSessionControllerID = nil remoteSessionController?.stop() + sidebarLogFlushCancellable?.cancel() + TerminalController.stopCodexTranscriptMonitors(forWorkspaceId: id) } func refreshSplitButtonTooltips() { @@ -9232,7 +9248,7 @@ final class Workspace: Identifiable, ObservableObject { agentPIDKeysByPanelId.removeAll() agentListeningPorts.removeAll() latestConversationMessage = nil - logEntries.removeAll() + clearSidebarLogEntries() progress = nil gitBranch = nil panelGitBranches.removeAll() @@ -10121,7 +10137,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 @@ -10156,7 +10172,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" @@ -10222,7 +10238,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" @@ -10236,15 +10252,56 @@ 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() { + pendingSidebarLogEntries.removeAll(keepingCapacity: false) + sidebarLogBuffer.removeAll() + logEntries.removeAll() + } + + private func setSidebarLogEntries(_ entries: [SidebarLogEntry]) { + pendingSidebarLogEntries.removeAll(keepingCapacity: false) + sidebarLogBuffer.replaceAll(entries, limit: sidebarLogEntryLimit) + logEntries = sidebarLogBuffer.entries() + } + + private func scheduleSidebarLogFlush() { + 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 + MainActor.assumeIsolated { + self?.flushPendingSidebarLogEntries() + } + } + } + + func flushPendingSidebarLogEntries() { + 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 diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index fe7cac4b2187..ab3043332856 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -203,6 +203,12 @@ 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 */; }; + 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 */; }; @@ -748,6 +754,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/CodexTranscriptMonitor.swift; sourceTree = ""; }; + C0DE412700000000000004 /* SidebarLogRingBuffer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarLogRingBuffer.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 = ""; }; @@ -1302,6 +1314,7 @@ A5001511 /* UITestRecorder.swift */, A5001520 /* PostHogAnalytics.swift */, A5001416 /* Workspace.swift */, + C0DE412700000000000004 /* SidebarLogRingBuffer.swift */, D7AB3605C10DEF0000000004 /* WorkspaceCloseTabsBatching.swift */, C3744E020000000000000001 /* Workspace+PanelLifecycle.swift */, E30780000000000000000001 /* WorkspaceRemoteConfiguration.swift */, @@ -1341,6 +1354,11 @@ E7E00000000000000000000C /* CmuxLifecycleEventPublishing.swift */, 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 */, @@ -2047,6 +2065,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 */, @@ -2090,6 +2109,11 @@ E7E00000000000000000000B /* CmuxLifecycleEventPublishing.swift in Sources */, 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/cmuxTests/TerminalControllerSocketWriteTests.swift b/cmuxTests/TerminalControllerSocketWriteTests.swift index e4e735e2e1a6..c4501be91da3 100644 --- a/cmuxTests/TerminalControllerSocketWriteTests.swift +++ b/cmuxTests/TerminalControllerSocketWriteTests.swift @@ -77,3 +77,202 @@ 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( + [ + Self.eventLine(type: "task_started", payload: ["turn_id": turnId]), + [ + "type": "response_item", + "payload": [ + "type": "message", + "role": "assistant", + "content": [["text": "done"]] + ] + ], + Self.eventLine(type: "task_started", payload: [:]), + Self.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 + }) + } + + 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( + 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 + 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(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 + } +}