Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions Sources/AgentWatchApp/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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() },
Expand Down
2 changes: 1 addition & 1 deletion Sources/AgentWatchApp/CodexQuestionRecovery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
4 changes: 3 additions & 1 deletion Sources/AgentWatchApp/SessionHistoryStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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]) {
Expand Down
7 changes: 7 additions & 0 deletions Sources/AgentWatchApp/SessionSupervisor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
16 changes: 15 additions & 1 deletion Sources/AgentWatchApp/WaitingChatsWindow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,26 @@ final class WaitingChatsModel: ObservableObject {
let id: String
let title: String
let detail: String
let canResetBeacon: Bool

init(_ session: SessionSnapshot) {
id = session.id
title = session.title ?? session.projectName ?? "Chat \(session.id.suffix(8))"
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]) {
Expand All @@ -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
Expand Down Expand Up @@ -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) }
}
}
}
}
}
Expand Down
11 changes: 8 additions & 3 deletions Sources/AgentWatchCore/SessionHistory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
}
}
Expand Down
4 changes: 3 additions & 1 deletion Sources/AgentWatchCore/SessionModels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand Down
17 changes: 16 additions & 1 deletion Sources/AgentWatchCore/SessionReducer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
20 changes: 17 additions & 3 deletions Sources/AgentWatchCore/SessionStateEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?? [:]
Expand All @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 }
Expand Down
20 changes: 16 additions & 4 deletions Sources/AgentWatchCore/TranscriptReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
}

Expand All @@ -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
}
}
}
Expand Down Expand Up @@ -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:
Expand Down
9 changes: 4 additions & 5 deletions TROUBLESHOOTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
2 changes: 1 addition & 1 deletion Tests/AgentWatchAppTests/ProjectBrowserTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
Expand Down
22 changes: 22 additions & 0 deletions Tests/AgentWatchAppTests/SessionHistoryStoreTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
18 changes: 18 additions & 0 deletions Tests/AgentWatchAppTests/TranscriptWatcherTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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]"}]}}"#
Expand Down
Loading
Loading