diff --git a/Sources/AgentWatchApp/AppDelegate.swift b/Sources/AgentWatchApp/AppDelegate.swift index f6e6bda..bfa4413 100644 --- a/Sources/AgentWatchApp/AppDelegate.swift +++ b/Sources/AgentWatchApp/AppDelegate.swift @@ -163,9 +163,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate { host: self, version: updater.ownVersion ) - private lazy var waitingChats = WaitingChatsModel { [weak self] id in - self?.supervisor.focusSession(id: id, requireDesktopLink: true) ?? .nothingRaised - } + private lazy var waitingChats = WaitingChatsModel( + focus: { [weak self] id in + self?.supervisor.focusSession(id: id, requireDesktopLink: true) ?? .nothingRaised + }, + resetBeacon: { [weak self] id in self?.supervisor.resetCodexQuestionBeacon(forSessionWithID: id) }) private lazy var waitingWindow = WaitingChatsWindow(model: waitingChats) private lazy var fullScreenDot = FullScreenDot( openWaiting: { [weak self] in self?.waitingWindow.present() }, diff --git a/Sources/AgentWatchApp/CodexQuestionRecovery.swift b/Sources/AgentWatchApp/CodexQuestionRecovery.swift index ef23582..9155df9 100644 --- a/Sources/AgentWatchApp/CodexQuestionRecovery.swift +++ b/Sources/AgentWatchApp/CodexQuestionRecovery.swift @@ -60,7 +60,7 @@ struct CodexQuestionRecovery { if unresolved.remove(id) != nil { open.insert(id) } case let .codexQuestionAnswered(id, _): unresolved.remove(id) - case .turnInterrupted: + case .turnInterrupted, .codexTextSubmitted: unresolved.removeAll() default: break } diff --git a/Sources/AgentWatchApp/SessionHistoryStore.swift b/Sources/AgentWatchApp/SessionHistoryStore.swift index b033ba0..b695865 100644 --- a/Sources/AgentWatchApp/SessionHistoryStore.swift +++ b/Sources/AgentWatchApp/SessionHistoryStore.swift @@ -98,7 +98,9 @@ final class SessionHistoryStore { // apart by the call alone, the second dialog opening would look like no change and // the file would not be written. let dialogs = record.unansweredDialogs.flatMap { [$0.agentID ?? "", $0.activityID ?? ""] } - return ([record.id, record.phase.rawValue] + dialogs).joined(separator: "\u{1}") + let questions = record.pendingCodexQuestions?.keys.sorted() ?? [] + return ([record.id, record.phase.rawValue, String(dialogs.count)] + dialogs + questions) + .joined(separator: "\u{1}") } private func write(_ records: [SessionSnapshot], agentProcesses: [RememberedAgentProcess]) { diff --git a/Sources/AgentWatchApp/SessionSupervisor.swift b/Sources/AgentWatchApp/SessionSupervisor.swift index a8fa5fb..d08f269 100644 --- a/Sources/AgentWatchApp/SessionSupervisor.swift +++ b/Sources/AgentWatchApp/SessionSupervisor.swift @@ -811,6 +811,12 @@ final class SessionSupervisor { onNotableEvent("\(Self.label(snapshot)) · session removed") } + func resetCodexQuestionBeacon(forSessionWithID id: String) { + guard let snapshot = engine.resetCodexQuestionBeacon(forSessionWithID: id, at: now()) else { return } + publish() + onNotableEvent("\(Self.label(snapshot)) · Codex question beacon reset") + } + private func handleAgentProcessExit(sessionID: String) { // A row built from a process is not a session that ended — it is a row that was // never more than the process it named. Closing it would leave a tombstone for a @@ -1268,6 +1274,7 @@ final class SessionSupervisor { switch fact { case .codexQuestionAsked: "Codex question opened" case .codexQuestionAnswered: "Codex question answered" + case .codexTextSubmitted: "text submitted in Codex" case let .callStarted(_, kind, _): "\(kind.rawValue) call started" case .callReturned: "call ended" case .callFailed: "call failed" diff --git a/Sources/AgentWatchApp/WaitingChatsWindow.swift b/Sources/AgentWatchApp/WaitingChatsWindow.swift index 79dedd0..5dc4bd2 100644 --- a/Sources/AgentWatchApp/WaitingChatsWindow.swift +++ b/Sources/AgentWatchApp/WaitingChatsWindow.swift @@ -8,6 +8,7 @@ final class WaitingChatsModel: ObservableObject { let id: String let title: String let detail: String + let canResetBeacon: Bool init(_ session: SessionSnapshot) { id = session.id @@ -15,15 +16,18 @@ final class WaitingChatsModel: ObservableObject { let agent = session.source == .codex ? "Codex" : "Claude" detail = [agent, session.projectName == title ? nil : session.projectName].compactMap { $0 }.joined( separator: " · ") + canResetBeacon = session.source == .codex && session.pendingCodexQuestions?.isEmpty == false } } @Published private(set) var rows: [Row] = [] @Published private(set) var unavailableID: String? private let focus: (String) -> SessionClick + private let resetBeacon: (String) -> Void - init(focus: @escaping (String) -> SessionClick) { + init(focus: @escaping (String) -> SessionClick, resetBeacon: @escaping (String) -> Void) { self.focus = focus + self.resetBeacon = resetBeacon } func update(_ sessions: [SessionSnapshot]) { @@ -42,6 +46,11 @@ final class WaitingChatsModel: ObservableObject { unavailableID = opened ? nil : id return opened } + + func resetBeacon(for id: String) { + guard rows.contains(where: { $0.id == id && $0.canResetBeacon }) else { return } + resetBeacon(id) + } } @MainActor @@ -108,6 +117,11 @@ private struct WaitingChatsView: View { .padding(.vertical, 4).contentShape(Rectangle()) } .buttonStyle(.plain) + .contextMenu { + if row.canResetBeacon { + Button("Reset Beacon") { model.resetBeacon(for: row.id) } + } + } } } } diff --git a/Sources/AgentWatchCore/SessionHistory.swift b/Sources/AgentWatchCore/SessionHistory.swift index 1c16c34..02fedef 100644 --- a/Sources/AgentWatchCore/SessionHistory.swift +++ b/Sources/AgentWatchCore/SessionHistory.swift @@ -59,6 +59,7 @@ public enum SessionHistory { var remembered = snapshot remembered.activities = [] remembered.codexQuestionsClearedAt = nil + remembered.codexTextSubmittedAt = nil remembered.rateLimitReachedAt = nil // And what the last turn left running goes with them, for the same reason: the row // draws that list as something happening now, and after a restart nobody is left to @@ -76,8 +77,12 @@ public enum SessionHistory { if let awaiting { remembered.discoveredProcess = nil - remembered.pendingCodexQuestions = (snapshot.pendingCodexQuestions ?? [:]).merging(awaiting.codexQuestions) - { current, _ in current } + let questions = awaiting.codexQuestions.filter { _, askedAt in + snapshot.canTrackCodexQuestion(askedAt: askedAt) + } + remembered.pendingCodexQuestions = (snapshot.pendingCodexQuestions ?? [:]).merging(questions) { + current, _ in current + } remembered.phase = awaiting.dialogs.isEmpty ? .disconnected : .waitingForUser remembered.setAwaitedDialogs(awaiting.dialogs) return remembered @@ -165,7 +170,7 @@ public enum SessionHistory { switch fact { case let .codexQuestionAsked(id, _): openCodexQuestions.insert(id) case let .codexQuestionAnswered(id, _): openCodexQuestions.remove(id) - case .turnInterrupted: openCodexQuestions.removeAll() + case .turnInterrupted, .codexTextSubmitted: openCodexQuestions.removeAll() default: break } } diff --git a/Sources/AgentWatchCore/SessionModels.swift b/Sources/AgentWatchCore/SessionModels.swift index 4f880cd..cac8a6f 100644 --- a/Sources/AgentWatchCore/SessionModels.swift +++ b/Sources/AgentWatchCore/SessionModels.swift @@ -365,8 +365,10 @@ public struct SessionSnapshot: Identifiable, Codable, Equatable, Sendable { /// Desktop Codex can keep working after asking a question. Only the question identity is retained. public internal(set) var pendingCodexQuestions: [String: Date]? - /// Ignore older questions read from disk after their turn was cancelled. + /// Ignore questions through a reset or cancellation, even if the transcript brings them late. var codexQuestionsClearedAt: Date? + /// Ordinary messages and questions can share a timestamp. The transcript orders those records. + var codexTextSubmittedAt: Date? public var attention: SessionAttention { needsUserReply ? .needsPerson : phase.attention } diff --git a/Sources/AgentWatchCore/SessionReducer.swift b/Sources/AgentWatchCore/SessionReducer.swift index 11ef5a6..92bbb0e 100644 --- a/Sources/AgentWatchCore/SessionReducer.swift +++ b/Sources/AgentWatchCore/SessionReducer.swift @@ -395,10 +395,25 @@ public enum SessionReducer { } extension SessionSnapshot { - fileprivate mutating func clearCodexQuestions(at moment: Date) { + mutating func clearCodexQuestions(at moment: Date) { guard source == .codex else { return } let boundary = max(moment, codexQuestionsClearedAt ?? moment) codexQuestionsClearedAt = boundary + removeCodexQuestions(through: boundary) + } + + mutating func noteCodexTextSubmitted(at moment: Date) { + guard codexTextSubmittedAt.map({ moment >= $0 }) ?? true else { return } + codexTextSubmittedAt = moment + removeCodexQuestions(through: moment) + } + + func canTrackCodexQuestion(askedAt: Date) -> Bool { + (codexQuestionsClearedAt.map { askedAt > $0 } ?? true) + && (codexTextSubmittedAt.map { askedAt >= $0 } ?? true) + } + + private mutating func removeCodexQuestions(through boundary: Date) { let remaining = pendingCodexQuestions?.filter { $0.value > boundary } pendingCodexQuestions = remaining?.isEmpty == false ? remaining : nil } diff --git a/Sources/AgentWatchCore/SessionStateEngine.swift b/Sources/AgentWatchCore/SessionStateEngine.swift index 90140b5..895f78f 100644 --- a/Sources/AgentWatchCore/SessionStateEngine.swift +++ b/Sources/AgentWatchCore/SessionStateEngine.swift @@ -609,7 +609,7 @@ public struct SessionStateEngine: Sendable { switch fact { case let .codexQuestionAsked(activityID, at): guard previous.source == .codex, previous.phase != .disconnected, previous.phase != .terminalClosed, - previous.codexQuestionsClearedAt.map({ at > $0 }) ?? true + previous.canTrackCodexQuestion(askedAt: at) else { return nil } next = previous var pending = next.pendingCodexQuestions ?? [:] @@ -623,6 +623,11 @@ public struct SessionStateEngine: Sendable { next = previous next.pendingCodexQuestions = pending.isEmpty ? nil : pending next.lastObservedAt = at + case let .codexTextSubmitted(at): + guard previous.source == .codex else { return nil } + next = previous + next.noteCodexTextSubmitted(at: at) + next.lastObservedAt = at case let .callReturned(activityID, at): next = SessionReducer.reduce(previous, event: .activityCompleted(id: activityID, at: at)) case let .callFailed(activityID, at): @@ -669,6 +674,16 @@ public struct SessionStateEngine: Sendable { return withoutAge == previous ? nil : next } + @discardableResult + public mutating func resetCodexQuestionBeacon(forSessionWithID id: String, at moment: Date) -> SessionSnapshot? { + guard var snapshot = liveRow(id), snapshot.source == .codex, + snapshot.pendingCodexQuestions?.isEmpty == false + else { return nil } + snapshot.clearCodexQuestions(at: moment) + snapshots[id] = snapshot + return snapshot + } + /// Applies what a session said about itself in its own transcript. /// /// Never a lifecycle fact: not one field here can move a phase, which is why it is a @@ -938,8 +953,7 @@ public struct SessionStateEngine: Sendable { } guard var snapshot = liveRow(id), let evidence else { return nil } let verified = wait.codexQuestions.filter { key, askedAt in - evidence.openCodexQuestions.contains(key) - && (snapshot.codexQuestionsClearedAt.map { askedAt > $0 } ?? true) + evidence.openCodexQuestions.contains(key) && snapshot.canTrackCodexQuestion(askedAt: askedAt) } let blocking = snapshot.phase == .disconnected && SessionHistory.waitStillHolds(wait, evidence: evidence) guard blocking || !verified.isEmpty else { return nil } diff --git a/Sources/AgentWatchCore/TranscriptReader.swift b/Sources/AgentWatchCore/TranscriptReader.swift index aa52a7a..1a36f8b 100644 --- a/Sources/AgentWatchCore/TranscriptReader.swift +++ b/Sources/AgentWatchCore/TranscriptReader.swift @@ -30,6 +30,7 @@ public enum TranscriptFact: Equatable, Sendable { /// A Codex async question was delivered, or the user answered that exact question. case codexQuestionAsked(activityID: String, at: Date) case codexQuestionAnswered(activityID: String, at: Date) + case codexTextSubmitted(at: Date) /// The turn was interrupted by a person. /// /// Measured with a control: an interrupted turn delivers no hook at all — not `Stop`, not @@ -45,7 +46,7 @@ public enum TranscriptFact: Equatable, Sendable { case let .workEnded(_, at): at case let .callStarted(_, _, at): at case let .codexQuestionAsked(_, at), let .codexQuestionAnswered(_, at): at - case let .turnInterrupted(at): at + case let .codexTextSubmitted(at), let .turnInterrupted(at): at } } @@ -59,7 +60,8 @@ public enum TranscriptFact: Equatable, Sendable { switch self { case let .callReturned(id, _), let .callFailed(id, _), let .workEnded(id, _): return SessionReducer.dialogEnds(dialog, atActivityID: id) - case .callStarted, .turnInterrupted, .codexQuestionAsked, .codexQuestionAnswered: return false + case .callStarted, .turnInterrupted, .codexQuestionAsked, .codexQuestionAnswered, .codexTextSubmitted: + return false } } } @@ -291,8 +293,18 @@ public enum TranscriptReader { return .codexQuestionAsked(activityID: questionLabel(callID: raw, index: index), at: at) } } - if item["type"] as? String == "UserMessage", let answers = codexAnswers(in: item, at: at) { - return answers + if item["type"] as? String == "UserMessage" { + if let answers = codexAnswers(in: item, at: at) { + return answers + } + if let content = item["content"] as? [[String: Any]], + content.contains(where: { + guard $0["type"] as? String == "text", let text = $0["text"] as? String else { return false } + return !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + }) + { + return [.codexTextSubmitted(at: at)] + } } return [.callReturned(activityID: HookCaptureRedactor.label(forRawIdentifier: raw), at: at)] default: diff --git a/TROUBLESHOOTING.md b/TROUBLESHOOTING.md index 7e7ce3b..723796e 100644 --- a/TROUBLESHOOTING.md +++ b/TROUBLESHOOTING.md @@ -226,11 +226,10 @@ not the chat, so capturing that event alone cannot identify which row to clear. The exact chat and question were observed inside the interface handler during a manual Skip, using a temporary debugger; this is a diagnostic result, not an implemented integration. -**What to do:** Check the question in Codex before relying on the lamp. If you deliberately -skipped it, the pending marker can remain until a recorded reply or session interruption clears -it. You can remove the stale row when Agent Watch offers its × button. Continued work and the -end of a turn do not prove that a question was closed, so Agent Watch does not clear it on -those events. +**What to do:** Open the waiting chats list, right-click the Codex chat, and choose +`Reset Beacon`. Sending a regular text message in the same chat also clears the signal for +earlier questions. A new question lights the beacon again. Continued work and the end of a +turn leave the beacon on. The [investigation report](docs/research/codex-question-skip.md) records the completed checks and links to the [request for a supported event](https://github.com/openai/codex/issues/44648#issuecomment-7149227298). diff --git a/Tests/AgentWatchAppTests/ProjectBrowserTests.swift b/Tests/AgentWatchAppTests/ProjectBrowserTests.swift index 3feb182..b09954d 100644 --- a/Tests/AgentWatchAppTests/ProjectBrowserTests.swift +++ b/Tests/AgentWatchAppTests/ProjectBrowserTests.swift @@ -78,7 +78,7 @@ final class ProjectBrowserTests: XCTestCase { let working = testSession(index: 3, phase: .executing, lastObservedAt: now) var answered = question answered.pendingCodexQuestions = nil - let beacon = WaitingChatsModel { _ in .raised } + let beacon = WaitingChatsModel(focus: { _ in .raised }, resetBeacon: { _ in }) for sessions in [[question, reply, working], [answered, reply, working]] { beacon.update(sessions) let filtered = sessions.filter { ProjectBrowserFilter.waiting.includes($0, now: now) } diff --git a/Tests/AgentWatchAppTests/SessionHistoryStoreTests.swift b/Tests/AgentWatchAppTests/SessionHistoryStoreTests.swift index cb7f7a9..c2c97c6 100644 --- a/Tests/AgentWatchAppTests/SessionHistoryStoreTests.swift +++ b/Tests/AgentWatchAppTests/SessionHistoryStoreTests.swift @@ -111,6 +111,28 @@ final class SessionHistoryStoreTests: XCTestCase { XCTAssertEqual(SessionHistoryStore(directoryURL: directory).remembered.first?.phase, .disconnected) } + func testAnAsyncQuestionAndItsResetAreWrittenWithoutWaitingForTheWindow() throws { + let directory = try makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let store = SessionHistoryStore(directoryURL: directory) + var engine = SessionStateEngine() + let session = try engine.ingest( + EventEnvelope(source: .codex, sessionID: "thread", observedAt: moment, kind: .turnStarted)) + store.update([session], at: moment) + + let pending = try XCTUnwrap( + engine.apply(.codexQuestionAsked(activityID: "q1", at: moment + 1), toSessionWithID: session.id)) + store.update([pending], at: moment + 1) + let remembered = try XCTUnwrap(SessionHistoryStore(directoryURL: directory).remembered.first) + XCTAssertEqual(remembered.pendingCodexQuestions, ["q1": moment + 1]) + + store.update([pending], at: moment + 90) + let reset = try XCTUnwrap(engine.resetCodexQuestionBeacon(forSessionWithID: session.id, at: moment + 91)) + store.update([reset], at: moment + 91) + let afterReset = try XCTUnwrap(SessionHistoryStore(directoryURL: directory).remembered.first) + XCTAssertNil(afterReset.pendingCodexQuestions) + } + /// The age moves on nearly every event, several times a minute, and being a minute behind /// on it costs a restored row a minute of apparent silence. So it is written now and then /// rather than on every publish. diff --git a/Tests/AgentWatchAppTests/TranscriptWatcherTests.swift b/Tests/AgentWatchAppTests/TranscriptWatcherTests.swift index decff44..3cf8522 100644 --- a/Tests/AgentWatchAppTests/TranscriptWatcherTests.swift +++ b/Tests/AgentWatchAppTests/TranscriptWatcherTests.swift @@ -769,6 +769,24 @@ final class TranscriptWatcherTests: XCTestCase { XCTAssertEqual(next.flatMap(\.facts), [.codexQuestionAnswered(activityID: first, at: clock)]) } + func testRestartKeepsOnlyQuestionsAskedAfterAnOrdinaryTextMessage() async throws { + let cleared = HookCaptureRedactor.label(forRawIdentifier: "request_user_input_async:call_old:0") + let pending = HookCaptureRedactor.label(forRawIdentifier: "request_user_input_async:call_new:0") + try writeCodex([ + Self.codexOpening, + #"{"type":"event_msg","payload":{"type":"item_completed","item":{"type":"AgentMessage","id":"call_old","delivery":"async","questions":[{"title":"Old"}]}}}"#, + #"{"type":"event_msg","payload":{"type":"item_completed","item":{"type":"UserMessage","id":"item_reply","content":[{"type":"text","text":"Continue."}]}}}"#, + #"{"type":"event_msg","payload":{"type":"item_completed","item":{"type":"AgentMessage","id":"call_new","delivery":"async","questions":[{"title":"New"}]}}}"#, + ]) + let watcher = try makeWatcher() + var row = workingCodex() + row.phase = .disconnected + let wait = SessionHistory.RememberedWait( + dialogs: [], observedAt: start, codexQuestions: [cleared: start, pending: start + 2]) + let recovered = try await catchUp(watcher, sessions: [row], waits: [row.id: wait]) + XCTAssertEqual(recovered.first?.waitEvidence?.openCodexQuestions, Set([pending])) + } + func testUndatedHistoricalInterruptionDoesNotRetractARememberedWait() async throws { try write( #"{"type":"user","interruptedMessageId":"old-message","message":{"role":"user","content":[{"type":"text","text":"[Request interrupted by user]"}]}}"# diff --git a/Tests/AgentWatchAppTests/WaitingChatsTests.swift b/Tests/AgentWatchAppTests/WaitingChatsTests.swift index 1724ed6..2cdd001 100644 --- a/Tests/AgentWatchAppTests/WaitingChatsTests.swift +++ b/Tests/AgentWatchAppTests/WaitingChatsTests.swift @@ -16,10 +16,11 @@ final class WaitingChatsTests: XCTestCase { let third = testSession( index: 4, source: .codex, phase: .waitingForUser, lastObservedAt: start.addingTimeInterval(2)) var focused: [String] = [] - let model = WaitingChatsModel { id in - focused.append(id) - return .raised - } + let model = WaitingChatsModel( + focus: { id in + focused.append(id) + return .raised + }, resetBeacon: { _ in }) model.update([first, headless, second]) XCTAssertEqual(model.rows.map(\.id), [second.id, first.id]) @@ -36,7 +37,7 @@ final class WaitingChatsTests: XCTestCase { func testCodexCanKeepWorkingWhileItsQuestionIsInTheList() { var session = testSession(source: .codex, phase: .executing, lastObservedAt: .now) session.pendingCodexQuestions = ["question-1": .now] - let model = WaitingChatsModel { _ in .raised } + let model = WaitingChatsModel(focus: { _ in .raised }, resetBeacon: { _ in }) model.update([session]) XCTAssertEqual(model.rows.map(\.id), [session.id]) session.pendingCodexQuestions = nil @@ -44,6 +45,21 @@ final class WaitingChatsTests: XCTestCase { XCTAssertTrue(model.rows.isEmpty) } + func testOnlyTheSelectedCodexChatWithAnAsyncQuestionCanResetItsBeacon() { + var first = testSession(index: 1, source: .codex, phase: .executing, lastObservedAt: .now) + first.pendingCodexQuestions = ["q1": .now] + var second = testSession(index: 2, source: .codex, phase: .executing, lastObservedAt: .now) + second.pendingCodexQuestions = ["q2": .now] + let permission = testSession(index: 3, source: .codex, phase: .waitingForUser, lastObservedAt: .now) + var resetIDs: [String] = [] + let model = WaitingChatsModel(focus: { _ in .nothingRaised }, resetBeacon: { resetIDs.append($0) }) + model.update([first, second, permission]) + XCTAssertEqual(Set(model.rows.filter(\.canResetBeacon).map(\.id)), Set([first.id, second.id])) + model.resetBeacon(for: permission.id) + model.resetBeacon(for: second.id) + XCTAssertEqual(resetIDs, [second.id]) + } + func testDesktopBeaconSucceedsOnlyWhenTheSelectedChatLinkWasSent() throws { var opened: [URL] = [] var accepted = true @@ -72,7 +88,7 @@ final class WaitingChatsTests: XCTestCase { func testUnavailableChatCanBeRetriedWhileItStillNeedsAnAnswer() { let session = testSession(phase: .waitingForUser, lastObservedAt: .now) var result = SessionClick.nothingRaised - let model = WaitingChatsModel { _ in result } + let model = WaitingChatsModel(focus: { _ in result }, resetBeacon: { _ in }) model.update([session]) XCTAssertFalse(model.open(session.id)) XCTAssertEqual(model.unavailableID, session.id) diff --git a/Tests/AgentWatchCoreTests/CodexQuestionStateTests.swift b/Tests/AgentWatchCoreTests/CodexQuestionStateTests.swift index 2a6de19..2d2556b 100644 --- a/Tests/AgentWatchCoreTests/CodexQuestionStateTests.swift +++ b/Tests/AgentWatchCoreTests/CodexQuestionStateTests.swift @@ -64,4 +64,67 @@ final class CodexQuestionStateTests: XCTestCase { XCTAssertFalse(try XCTUnwrap(restored.snapshots[id]).needsUserReply) } + func testTextClearsEarlierQuestionsInThatChatAndDoesNotClearALaterQuestion() throws { + var engine = SessionStateEngine() + let id = try engine.ingest(event(.turnStarted, after: 0)).id + let other = try engine.ingest( + EventEnvelope(source: .codex, sessionID: "other", observedAt: start, kind: .turnStarted) + ).id + let older = TranscriptFact.codexQuestionAsked(activityID: "older", at: start + 1) + engine.apply(older, toSessionWithID: id) + engine.apply(older, toSessionWithID: other) + try engine.ingest(event(.turnStarted, after: 2)) + XCTAssertTrue(engine.snapshots[id]?.needsUserReply == true) + engine.apply(.codexQuestionAsked(activityID: "newer", at: start + 4), toSessionWithID: id) + engine.apply(.codexTextSubmitted(at: start + 3), toSessionWithID: id) + engine.apply(older, toSessionWithID: id) + XCTAssertEqual(engine.snapshots[id]?.pendingCodexQuestions, ["newer": start + 4]) + XCTAssertEqual(engine.snapshots[other]?.pendingCodexQuestions, ["older": start + 1]) + + engine.apply(.codexTextSubmitted(at: start + 5), toSessionWithID: id) + XCTAssertFalse(try XCTUnwrap(engine.snapshots[id]).needsUserReply) + } + + func testManualResetSurvivesRestartAndKeepsABlockingPermission() throws { + var engine = SessionStateEngine() + let id = try engine.ingest(event(.turnStarted, after: 0)).id + let asked = TranscriptFact.codexQuestionAsked(activityID: "prior", at: start + 1) + engine.apply(asked, toSessionWithID: id) + try engine.ingest( + EventEnvelope( + source: .codex, sessionID: "thread", observedAt: start + 2, kind: .userInputRequired, + userInputRequestKind: .approval)) + + let reset = try XCTUnwrap(engine.resetCodexQuestionBeacon(forSessionWithID: id, at: start + 3)) + XCTAssertNil(reset.pendingCodexQuestions) + XCTAssertEqual(reset.phase, .waitingForUser) + XCTAssertEqual(reset.unansweredDialogs.map(\.kind), [.approval]) + XCTAssertEqual(reset.lastObservedAt, start + 2) + engine.apply(asked, toSessionWithID: id) + XCTAssertNil(engine.snapshots[id]?.pendingCodexQuestions) + + var restored = SessionStateEngine() + restored.restore(SessionHistory.records(of: engine.snapshots.values)) + XCTAssertTrue(restored.rememberedWaitsAwaitingEvidence[id]?.codexQuestions.isEmpty == true) + + engine.apply(.codexQuestionAsked(activityID: "fresh", at: start + 4), toSessionWithID: id) + XCTAssertEqual(engine.snapshots[id]?.pendingCodexQuestions, ["fresh": start + 4]) + } + + func testQuestionAfterTextCanHaveTheSameTimestamp() throws { + var engine = SessionStateEngine() + let id = try engine.ingest(event(.turnStarted, after: 0)).id + let records = """ + {"type":"event_msg","payload":{"type":"item_completed","item":{"type":"AgentMessage","id":"call_before","delivery":"async","questions":[{"title":"Before"}]}}} + {"type":"event_msg","payload":{"type":"item_completed","item":{"type":"UserMessage","id":"item_reply","content":[{"type":"text","text":"Continue."}]}}} + {"type":"event_msg","payload":{"type":"item_completed","item":{"type":"AgentMessage","id":"call_after","delivery":"async","questions":[{"title":"After"}]}}} + """ + let increment = try TranscriptReader.read( + increment: Data((records + "\n").utf8), source: .codex, observedAt: start + 2) + for fact in increment.facts { engine.apply(fact, toSessionWithID: id) } + engine.apply(.codexTextSubmitted(at: start + 1), toSessionWithID: id) + let after = HookCaptureRedactor.label(forRawIdentifier: "request_user_input_async:call_after:0") + XCTAssertEqual(engine.snapshots[id]?.pendingCodexQuestions, [after: start + 2]) + } + } diff --git a/Tests/AgentWatchCoreTests/TranscriptReaderTests.swift b/Tests/AgentWatchCoreTests/TranscriptReaderTests.swift index 6485970..c9ecbfb 100644 --- a/Tests/AgentWatchCoreTests/TranscriptReaderTests.swift +++ b/Tests/AgentWatchCoreTests/TranscriptReaderTests.swift @@ -255,16 +255,30 @@ final class TranscriptReaderTests: XCTestCase { XCTAssertEqual(try read([reply], source: .codex).facts, [.codexQuestionAnswered(activityID: third, at: now)]) } - func testQuestionWordingQuotedEnvelopesAndDeliveryAcknowledgementsAreNotQuestionEvents() throws { + func testOnlyUserTextCanResetTheQuestionBeaconWithoutAnExactAnswer() throws { let envelope = try codexReply([ ["questionItemId": #"["request_user_input_async","call_fixture",0]"#, "answer": "A"] ]) let content = [["type": "text", "text": envelope]] let questions = [["title": "Answer this?"]] - let items: [[String: Any]] = [ + let nonReplies: [[String: Any]] = [ ["type": "AgentMessage", "id": "call_fixture", "delivery": "async", "content": content], ["type": "AgentMessage", "id": "call_fixture", "questions": questions, "content": content], ["type": "AgentMessage", "id": "call_fixture", "delivery": "async", "questions": [], "content": content], + ["type": "UserMessage", "id": "item_empty", "content": [["type": "text", "text": " \n"]]], + ["type": "UserMessage", "id": "item_image", "content": [["type": "image", "url": "example"]]], + ] + for item in nonReplies { + let id = try XCTUnwrap(item["id"] as? String) + XCTAssertEqual( + try read([completedCodexItem(item)], source: .codex).facts, + [.callReturned(activityID: HookCaptureRedactor.label(forRawIdentifier: id), at: now)]) + } + let textItems: [[String: Any]] = [ + [ + "type": "UserMessage", "id": "item_reply", "client_id": "client", + "content": [["type": "text", "text": String(repeating: "Continue. ", count: 10)]], + ], [ "type": "UserMessage", "id": "item_reply", "content": [["type": "text", "text": "Example:\n" + envelope]], @@ -278,11 +292,10 @@ final class TranscriptReaderTests: XCTestCase { "content": content + [["type": "text", "text": "quoted above"]], ], ] - for item in items { - let id = try XCTUnwrap(item["id"] as? String) + for item in textItems { XCTAssertEqual( try read([completedCodexItem(item)], source: .codex).facts, - [.callReturned(activityID: HookCaptureRedactor.label(forRawIdentifier: id), at: now)]) + [.codexTextSubmitted(at: now)]) } let ack = #"{"type":"response_item","payload":{"type":"function_call_output","call_id":"call_fixture","output":"Questions submitted"}}"# @@ -555,7 +568,7 @@ extension TranscriptFact { fileprivate var endedActivityID: String? { switch self { case let .callReturned(id, _), let .callFailed(id, _), let .workEnded(id, _): id - case .callStarted, .turnInterrupted, .codexQuestionAsked, .codexQuestionAnswered: nil + case .callStarted, .turnInterrupted, .codexQuestionAsked, .codexQuestionAnswered, .codexTextSubmitted: nil } } } diff --git a/docs/menu-bar.md b/docs/menu-bar.md index f4b7d82..62f6137 100644 --- a/docs/menu-bar.md +++ b/docs/menu-bar.md @@ -82,6 +82,13 @@ появляется оранжевое кольцо с числом чатов, которые ждут ответа. Щелчок открывает их список. Выберите чат в списке, чтобы вернуться к вопросу. Для настольных Claude и Codex список закрывается после передачи ссылки на выбранный чат. Если ссылку получить или открыть не удалось, строка предлагает открыть чат в приложении или повторить попытку. + +Чтобы убрать сигнал об уже показанных асинхронных вопросах Codex, нажмите правой кнопкой на чат +в списке и выберите `Reset Beacon`. Обычное текстовое сообщение в том же чате тоже сбрасывает +сигнал о более ранних вопросах. Карточки в Codex могут оставаться открытыми. Новый вопрос +снова включает маячок, а блокирующие запросы Codex, например разрешение на команду, продолжают +отображаться. + По окружности движется оранжевый огонёк. При включённом в macOS уменьшении движения он остаётся на месте. После ответа последнему чату кольцо исчезает. Щелчок правой кнопкой по маячку открывает меню с пунктом `Waiting Beacon Settings…`. Тот же раздел доступен из боковой панели настроек, diff --git a/docs/session-recovery.md b/docs/session-recovery.md index 778b04c..620d1c0 100644 --- a/docs/session-recovery.md +++ b/docs/session-recovery.md @@ -90,8 +90,10 @@ hook-sender: по десяти транскриптам последнее им Если в памяти остались вопросы Codex, приложение проверяет их отдельно. Оно читает журнал с конца блоками по 256 КиБ и останавливается, когда найдёт последнее относящееся к каждому сохранённому -идентификатору событие. Вопрос снова появляется в списке ожидающих, ответ снимает его. Расстояние -до начала вопроса может быть любым. Для длинной записи блок растёт до предела читателя в 4 МиБ; +идентификатору событие. Вопрос снова появляется в списке, если его не сняли ответом через карточку +или более поздним текстовым сообщением. Ручной сброс [маячка](menu-bar.md#маячок-ожидающих-чатов) +убирает вопросы из сохранённого списка. Расстояние до начала вопроса может быть любым. Для длинной +записи блок растёт до предела читателя в 4 МиБ; если одну завершённую запись разобрать в этом пределе невозможно, более старые вопросы считаются неподтверждёнными. Незавершённая строка остаётся до следующего чтения. diff --git a/docs/transcript-reader.md b/docs/transcript-reader.md index da3aff3..6e43289 100644 --- a/docs/transcript-reader.md +++ b/docs/transcript-reader.md @@ -151,7 +151,10 @@ hook-процесс. Принято как риск: сессии агентов Skip не даёт такого ответа: в проверенном журнале пропущенный вопрос остаётся без записи закрытия (замер: Codex Desktop 26.1120.41243, Codex 0.171.0-alpha.13.2). -Продолжение работы агента не доказывает ответ на асинхронный вопрос. Проверки истории, +Обычное сообщение с непустым текстом в `event_msg/item_completed` с элементом `UserMessage` +сбрасывает сигнал о предыдущих асинхронных вопросах того же чата. Читатель передаёт только время +сообщения. Ответ через карточку по-прежнему снимает сигнал только о вопросах, указанных в ответе. +Продолжение работы агента и конец хода сами по себе сигнал не снимают. Проверки истории, телеметрии и обработчика Skip собраны в [закрытом исследовании](research/codex-question-skip.md); там же ссылка на запрос внешнего события у Codex.