Skip to content

CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息

fix: 完善交互等待识别与防睡眠联动

Bob3bc55da30e42
diff --git a/CodexBar/Models/ActivityInput.swift b/CodexBar/Models/ActivityInput.swift
index 73b1ccc..ff7922c 100644
--- a/CodexBar/Models/ActivityInput.swift
+++ b/CodexBar/Models/ActivityInput.swift
@@ -21,6 +21,7 @@ nonisolated struct ActivityInput {
case reasoningSummaryProgress
case commandProgress
case inputRequested
+ case userInputRequested
case planChanged
case diffChanged
case modelChanged
@@ -38,7 +39,7 @@ nonisolated struct ActivityInput {
case .threadDiscovered, .threadStatusChanged, .usageUpdated, .turnStarted, .turnFinished, .itemStarted, .itemFinished,
.commandApprovalRequested, .fileApprovalRequested, .permissionsRequested, .requestResolved: .state
case .replyProgress, .reasoningProgress, .reasoningSummaryProgress, .commandProgress: .progress
- case .inputRequested, .planChanged, .diffChanged, .modelChanged, .verificationRequested,
+ case .inputRequested, .userInputRequested, .planChanged, .diffChanged, .modelChanged, .verificationRequested,
.authRecoveryStarted, .authRecoveryFinished, .safetyBufferingChanged, .hookStarted, .hookFinished, .errorReported: .presentation
case .ignored: .ignored
}
@@ -116,12 +117,17 @@ nonisolated struct ActivityItem {
enum ItemType: String, Codable {
case commandExecution, fileChange, webSearch, imageView, imageGeneration, sleep
case mcpToolCall, dynamicToolCall, collabAgentToolCall, contextCompaction, subAgentActivity
- case agentMessage, reasoning, enteredReviewMode, exitedReviewMode, unknown
+ case agentMessage, userMessage, reasoning, enteredReviewMode, exitedReviewMode, unknown
}
struct CommandAction { let type: String }
struct WebAction { var type: String? }
struct AgentState { var status: String? }
+ struct QuestionReply: Equatable {
+ let itemID: String
+ let index: Int
+ }
+
let id: String
let type: ItemType
var status: String?
@@ -136,6 +142,12 @@ nonisolated struct ActivityItem {
var action: WebAction?
var success: Bool?
var agentsStates: [String: AgentState]?
+ var asyncQuestionCount = 0
+ var answeredQuestions: [QuestionReply] = []
+ var affectsInputWait: Bool {
+ asyncQuestionCount > 0 || !answeredQuestions.isEmpty
+ }
+
var isToolCall: Bool {
Self.isToolType(type)
}
@@ -159,6 +171,7 @@ nonisolated struct ActivityLiveContext {
}
let inputMode: InputMode
+ let isBlocking: Bool?
let planCompleted: Int?
let planTotal: Int?
let run: Hook?
diff --git a/CodexBar/Models/ActivityModels.swift b/CodexBar/Models/ActivityModels.swift
index 6ec802d..73d8dd0 100644
--- a/CodexBar/Models/ActivityModels.swift
+++ b/CodexBar/Models/ActivityModels.swift
@@ -5,7 +5,7 @@ nonisolated enum ActivityRetention {
static let window: TimeInterval = 24 * 60 * 60
}
-/// 正在运行或等待批准的任务摘要, 不对 UI 暴露原始会话 ID
+/// 正在运行或等待回应的任务摘要, 不对 UI 暴露原始会话 ID
nonisolated struct ActivityTaskSnapshot: Equatable, Identifiable {
let id: UUID
let projectName: String?
@@ -81,6 +81,7 @@ nonisolated struct ProtectionNotice: Equatable, Sendable {
/// UI 只消费该快照, 不直接读取或解释 活动事件
nonisolated struct ActivitySnapshot: Equatable {
+ /// 仅包含审批等待, 其他交互等待由 panelWaitingTasks 合并展示
let waitingTasks: [ActivityTaskSnapshot]
let runningTasks: [ActivityTaskSnapshot]
let recentCompletions: [ActivityCompletion]
@@ -101,6 +102,20 @@ nonisolated struct ActivitySnapshot: Equatable {
runningTasks.filter { $0.presentation?.waiting == nil }
}
+ /// 防睡眠将明确阻塞的提问归入等待, 不改变任务的审批和保护状态
+ var keepAliveTaskIDs: (running: Set<UUID>, waiting: Set<UUID>) {
+ var running = Set<UUID>()
+ var waiting = Set(waitingTasks.map(\.id))
+ for task in runningTasks {
+ if task.presentation?.hasBlockingInputRequest == true {
+ waiting.insert(task.id)
+ } else {
+ running.insert(task.id)
+ }
+ }
+ return (running, waiting)
+ }
+
var panelPrimaryActivity: CodexPrimaryActivity {
if let task = panelWaitingTasks.first {
return .waiting(task)
@@ -155,7 +170,7 @@ nonisolated struct ActivitySnapshot: Equatable {
hasActiveTasks || !recentCompletions.isEmpty || !recentTerminations.isEmpty
}
- /// 活动卡片优先展示等待批准和运行中任务, 空闲时保留最近完成或终止记录
+ /// 主活动优先展示等待回应和运行中任务, 空闲时保留最近完成或终止记录
var primaryActivity: CodexPrimaryActivity {
if let task = primaryWaitingTask {
return .waiting(task)
diff --git a/CodexBar/Models/TaskGlowPresentationState.swift b/CodexBar/Models/TaskGlowPresentationState.swift
index 2fc51f3..3c6f2cc 100644
--- a/CodexBar/Models/TaskGlowPresentationState.swift
+++ b/CodexBar/Models/TaskGlowPresentationState.swift
@@ -104,9 +104,9 @@ struct TaskGlowPresentationState {
show(briefEvent, until: briefExpiration, fadeDuration: 0.5, now: now)
return
}
- if snapshot.waitingCount > 0 {
+ if !snapshot.panelWaitingTasks.isEmpty {
state = .waiting
- } else if snapshot.runningCount > 0 {
+ } else if !snapshot.panelRunningTasks.isEmpty {
state = .running
} else if let event = snapshot.latestTerminalEvent,
now < event.endedAt.addingTimeInterval(terminalDuration + terminalTimeOffset) {
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index 809823e..398c422 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -1612,7 +1612,7 @@
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "用户操作请求已结束"
+ "value" : "用户操作已结束"
}
}
}
@@ -1644,7 +1644,7 @@
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "代码审查模式"
+ "value" : "代码审查"
}
}
}
@@ -1884,60 +1884,60 @@
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "等待用户审批"
+ "value" : "等待审批"
}
}
}
},
- "activity.live.waiting-external" : {
+ "activity.live.waiting-default" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Awaiting external action"
+ "value" : "Awaiting response"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "等待外部操作"
+ "value" : "等待回应"
}
}
}
},
- "activity.live.waiting-form" : {
+ "activity.live.waiting-external" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Awaiting info"
+ "value" : "Awaiting response"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "等待提供信息"
+ "value" : "等待回应"
}
}
}
},
- "activity.live.waiting-input" : {
+ "activity.live.waiting-form" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Awaiting input"
+ "value" : "Awaiting response"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "等待用户输入"
+ "value" : "等待回应"
}
}
}
},
- "activity.live.waiting-service" : {
+ "activity.live.waiting-input" : {
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1948,23 +1948,23 @@
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "等待回应请求"
+ "value" : "等待回应"
}
}
}
},
- "activity.live.waiting-user" : {
+ "activity.live.waiting-service" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Awaiting user action"
+ "value" : "Awaiting response"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "等待用户操作"
+ "value" : "等待回应"
}
}
}
@@ -3990,13 +3990,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Prevent sleep while a task awaits approval"
+ "value" : "Prevent sleep while a task awaits a response"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "任务等待批准期间继续防止系统睡眠"
+ "value" : "任务等待回应期间继续防止系统睡眠"
}
}
}
@@ -4012,7 +4012,7 @@
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "等待批准时保持防睡眠"
+ "value" : "等待回应时保持防睡眠"
}
}
}
@@ -4710,13 +4710,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex is waiting for approval to continue"
+ "value" : "Codex is awaiting a response to continue"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex 正在等待批准下一步操作"
+ "value" : "Codex 正在等待回应以继续"
}
}
}
@@ -4726,13 +4726,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex needs approval %@"
+ "value" : "Codex is awaiting a response (%@)"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex 等待批准 %@"
+ "value" : "Codex 等待回应 (%@)"
}
}
}
@@ -4742,13 +4742,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "A task in \"%@\" is waiting for approval to continue"
+ "value" : "A task in \"%@\" is awaiting a response to continue"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "「%@」正在等待批准下一步操作"
+ "value" : "「%@」正在等待回应以继续"
}
}
}
@@ -4758,13 +4758,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "\"%1$@\" needs approval %2$@"
+ "value" : "\"%1$@\" is awaiting a response (%2$@)"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "「%1$@」等待批准 %2$@"
+ "value" : "「%1$@」等待回应 (%2$@)"
}
}
}
@@ -4774,13 +4774,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex Is Waiting for Approval"
+ "value" : "Codex Is Awaiting a Response"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex 等待批准"
+ "value" : "Codex 等待回应"
}
}
}
@@ -5638,13 +5638,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Trackpad haptics when tasks finish or await approval"
+ "value" : "Trackpad haptics when tasks finish or await a response"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "任务完成或等待批准时触发触摸板震动"
+ "value" : "任务完成或等待回应时触发触摸板震动"
}
}
}
@@ -5670,7 +5670,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Approval Requests"
+ "value" : "Task Waiting"
}
},
"zh-Hans" : {
@@ -6038,13 +6038,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Waiting for Approval"
+ "value" : "Waiting"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "等待批准"
+ "value" : "等待中"
}
}
}
diff --git a/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift b/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift
index 4d30e9a..447ac61 100644
--- a/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift
+++ b/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift
@@ -192,6 +192,8 @@ nonisolated extension ActivityLiveLabel {
String(localized: "activity.live.viewing-image")
case "waiting-approval":
String(localized: "activity.live.waiting-approval")
+ case "waiting-default":
+ String(localized: "activity.live.waiting-default")
case "waiting-external":
String(localized: "activity.live.waiting-external")
case "waiting-form":
@@ -200,8 +202,6 @@ nonisolated extension ActivityLiveLabel {
String(localized: "activity.live.waiting-input")
case "waiting-service":
String(localized: "activity.live.waiting-service")
- case "waiting-user":
- String(localized: "activity.live.waiting-user")
default:
String(localized: "activity.live.processing")
}
diff --git a/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift b/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift
index 6506c69..5f4f0bb 100644
--- a/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift
+++ b/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift
@@ -154,7 +154,7 @@ nonisolated extension ActivityDisplayFormat {
}
// 等待起点缺失时只展示等待事实, 不把订阅连接的时间当成请求开始时间
if waiting || live?.waiting != nil {
- return [running, waitingDuration ?? ActivityLiveLabel("waiting-user").text]
+ return [running, waitingDuration ?? ActivityLiveLabel("waiting-default").text]
}
let extra: String? = if let count = task.activeSubagentCount, count > 0 {
String(localized: "activity.live.subagent-count", defaultValue: "\(count, specifier: "%lld")")
diff --git a/CodexBar/Services/Activity/ActivityLivePresentation.swift b/CodexBar/Services/Activity/ActivityLivePresentation.swift
index 7ad2490..f0e3531 100644
--- a/CodexBar/Services/Activity/ActivityLivePresentation.swift
+++ b/CodexBar/Services/Activity/ActivityLivePresentation.swift
@@ -18,6 +18,8 @@ nonisolated struct ActivityLiveEvent: Equatable {
nonisolated struct ActivityLiveWait: Equatable {
let label: ActivityLiveLabel
let since: Date?
+ /// 仅提问请求提供阻塞信息, 其他来源保留未知
+ var isBlocking: Bool?
}
nonisolated struct ActivityLiveSummary: Equatable {
@@ -27,6 +29,7 @@ nonisolated struct ActivityLiveSummary: Equatable {
var toolCount: Int?
var planCompleted: Int?
var planTotal: Int?
+ var hasBlockingInputRequest = false
var isReviewing = false
var updatedAt: Date = .distantPast
}
@@ -39,9 +42,16 @@ nonisolated struct ActivityLivePresentation {
var isTool = false
}
+ private struct PendingQuestions {
+ let since: Date
+ let count: Int
+ var answered: Set<Int> = []
+ }
+
private var items: [String: Entry] = [:]
private var operations: [String: Entry] = [:]
private(set) var requests: [String: ActivityLiveWait] = [:]
+ private var questions: [String: PendingQuestions] = [:]
private var flagWait: ActivityLiveWait?
private var phase = Entry(label: ActivityLiveLabel("processing"), at: .distantPast)
private var phaseItemID: String?
@@ -52,22 +62,33 @@ nonisolated struct ActivityLivePresentation {
private var inventoryKnown = false
var summary: ActivityLiveSummary {
- let waiting = requests.min { lhs, rhs in
+ let requestWait = requests.min { lhs, rhs in
let left = lhs.value.since ?? .distantFuture
let right = rhs.value.since ?? .distantFuture
return left == right ? lhs.key < rhs.key : left < right
- }?.value ?? flagWait
+ }?.value
+ let questionWait = questions.values.map(\.since).min().map {
+ ActivityLiveWait(label: ActivityLiveLabel("waiting-input"), since: $0, isBlocking: false)
+ }
+ let waiting = [requestWait, questionWait].compactMap(\.self).min {
+ ($0.since ?? .distantFuture) < ($1.since ?? .distantFuture)
+ } ?? flagWait
let current = operations.values.max { $0.at < $1.at }
?? (Array(items.values) + [phase]).max { $0.at < $1.at } ?? phase
return ActivityLiveSummary(
current: waiting?.label ?? current.label, waiting: waiting, recent: recent,
toolCount: inventoryKnown ? items.values.filter(\.isTool).count : nil,
- planCompleted: planCompleted, planTotal: planTotal, isReviewing: isReviewing, updatedAt: current.at
+ planCompleted: planCompleted, planTotal: planTotal,
+ hasBlockingInputRequest: requests.values.contains { $0.isBlocking == true },
+ isReviewing: isReviewing, updatedAt: current.at
)
}
mutating func reconcile(status: ActivityThreadStatus?, observedAt: Date? = nil) {
guard let status, [.active, .idle].contains(status.type) else { return }
+ if status.type == .idle {
+ questions.removeAll()
+ }
guard let flags = status.type == .idle ? [] : status.activeFlags else { return }
let label: ActivityLiveLabel? = if flags.contains(.waitingOnApproval) {
ActivityLiveLabel("waiting-approval")
@@ -80,7 +101,8 @@ nonisolated struct ActivityLivePresentation {
flagWait = ActivityLiveWait(label: label, since: flagWait?.label == label ? flagWait?.since : observedAt)
} else {
flagWait = nil
- requests.removeAll()
+ // 非阻塞提问可与运行并存, active 状态不代表请求已被回应
+ requests = requests.filter { status.type == .active && $0.value.isBlocking == false }
}
}
@@ -92,8 +114,11 @@ nonisolated struct ActivityLivePresentation {
case .threadStatusChanged:
reconcile(status: params.status, observedAt: date)
case .itemStarted, .itemFinished:
- if let item = params.item, ActivityItem.isObservedType(item.type) {
- consume(item, starting: notification.kind == .itemStarted, at: date)
+ if let item = params.item {
+ consumeQuestions(item, at: date)
+ if ActivityItem.isObservedType(item.type) {
+ consume(item, starting: notification.kind == .itemStarted, at: date)
+ }
}
case .replyProgress, .reasoningProgress, .reasoningSummaryProgress:
let label = if notification.kind == .replyProgress {
@@ -111,7 +136,7 @@ nonisolated struct ActivityLivePresentation {
items[id] = Entry(label: label, at: date, isTool: true)
}
case .commandApprovalRequested, .fileApprovalRequested, .permissionsRequested,
- .inputRequested:
+ .inputRequested, .userInputRequested:
consumeRequest(notification, at: date)
case .requestResolved:
if let id = params.requestId, requests.removeValue(forKey: id) != nil {
@@ -127,6 +152,8 @@ nonisolated struct ActivityLivePresentation {
guard let id = notification.id else { return }
let key: String
switch notification.kind {
+ case .userInputRequested:
+ key = "waiting-input"
case .inputRequested:
guard notification.live.inputMode != .verification else { return }
key = switch notification.live.inputMode {
@@ -137,7 +164,10 @@ nonisolated struct ActivityLivePresentation {
default:
key = "waiting-approval"
}
- requests[id] = requests[id] ?? ActivityLiveWait(label: ActivityLiveLabel(key), since: date)
+ requests[id] = requests[id] ?? ActivityLiveWait(
+ label: ActivityLiveLabel(key), since: date,
+ isBlocking: notification.kind == .userInputRequested ? notification.live.isBlocking : nil
+ )
}
private mutating func consume(_ item: ActivityItem, starting: Bool, at date: Date) {
@@ -163,6 +193,25 @@ nonisolated struct ActivityLivePresentation {
}
}
+ private mutating func consumeQuestions(_ item: ActivityItem, at date: Date) {
+ if item.asyncQuestionCount > 0, questions[item.id] == nil {
+ // item/completed 只表示提问已发送, 等待持续到对应问题收到回应
+ questions[item.id] = PendingQuestions(since: date, count: item.asyncQuestionCount)
+ }
+ var resolved = false
+ for reply in item.answeredQuestions {
+ guard let pending = questions[reply.itemID], reply.index < pending.count,
+ questions[reply.itemID]?.answered.insert(reply.index).inserted == true else { continue }
+ resolved = true
+ if questions[reply.itemID]?.answered.count == pending.count {
+ questions.removeValue(forKey: reply.itemID)
+ }
+ }
+ if resolved {
+ record("request-ended", at: date)
+ }
+ }
+
private mutating func consumeSupplement(_ notification: ActivityInput, at date: Date) {
let live = notification.live
switch notification.kind {
@@ -228,8 +277,11 @@ nonisolated struct ActivityLivePresentation {
operations = Dictionary(uniqueKeysWithValues: operations.sorted { $0.value.at > $1.value.at }.prefix(128).map { ($0.key, $0.value) })
}
if requests.count > 128 {
- flagWait = ActivityLiveWait(label: ActivityLiveLabel("waiting-user"), since: nil)
+ flagWait = ActivityLiveWait(label: ActivityLiveLabel("waiting-default"), since: nil)
requests = Dictionary(uniqueKeysWithValues: requests.sorted { $0.key < $1.key }.prefix(128).map { ($0.key, $0.value) })
}
+ if questions.count > 128 {
+ questions = Dictionary(uniqueKeysWithValues: questions.sorted { $0.value.since > $1.value.since }.prefix(128).map { ($0.key, $0.value) })
+ }
}
}
diff --git a/CodexBar/Services/Activity/ActivityTask.swift b/CodexBar/Services/Activity/ActivityTask.swift
index 3667b14..cbcb5ed 100644
--- a/CodexBar/Services/Activity/ActivityTask.swift
+++ b/CodexBar/Services/Activity/ActivityTask.swift
@@ -139,6 +139,7 @@ nonisolated struct ActivityTask {
var result = (waiting ?? root ?? live.max { $0.1.updatedAt < $1.1.updatedAt })!.1
result.recent = live.compactMap(\.1.recent).max { $0.at < $1.at }
result.toolCount = live.allSatisfy { $0.1.toolCount != nil } ? live.reduce(0) { $0 + ($1.1.toolCount ?? 0) } : nil
+ result.hasBlockingInputRequest = live.contains { $0.1.hasBlockingInputRequest }
return result
}
diff --git a/CodexBar/Services/Activity/AppServerActivityModels.swift b/CodexBar/Services/Activity/AppServerActivityModels.swift
index abadb1e..2c9150f 100644
--- a/CodexBar/Services/Activity/AppServerActivityModels.swift
+++ b/CodexBar/Services/Activity/AppServerActivityModels.swift
@@ -134,9 +134,19 @@ private nonisolated struct WireActivityItem: Decodable {
var action: WebAction?
var success: Bool?
var agentsStates: [String: AgentState]?
+ var delivery: String?
+ var questions: [Question]?
+ var content: [Content]?
struct WebAction: Decodable { var type: String? }
struct AgentState: Decodable { var status: String? }
+ struct Question: Decodable { let title: String }
+ struct Content: Decodable {
+ let type: String
+ var text: String?
+ }
+
+ struct QuestionReply: Decodable { let questionItemId: String }
}
private nonisolated struct WireTokenUsageBreakdown: Decodable {
@@ -280,6 +290,7 @@ nonisolated enum AppServerActivityProtocol {
case "item/reasoning/summaryTextDelta": .reasoningSummaryProgress
case "item/commandExecution/outputDelta": .commandProgress
case "mcpServer/elicitation/request": .inputRequested
+ case "item/tool/requestUserInput": .userInputRequested
case "turn/plan/updated": .planChanged
case "turn/diff/updated": .diffChanged
case "model/rerouted": .modelChanged
@@ -359,9 +370,32 @@ private nonisolated extension WireActivityItem {
phase: phase,
action: action.map { .init(type: $0.type) },
success: success,
- agentsStates: agentsStates?.mapValues { .init(status: $0.status) }
+ agentsStates: agentsStates?.mapValues { .init(status: $0.status) },
+ asyncQuestionCount: type == "agentMessage" && delivery == "async" ? questions?.count ?? 0 : 0,
+ answeredQuestions: answeredQuestions
)
}
+
+ private var answeredQuestions: [ActivityItem.QuestionReply] {
+ guard type == "userMessage" else { return [] }
+ return (content ?? []).filter { $0.type == "text" }.flatMap { content -> [ActivityItem.QuestionReply] in
+ let text = content.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ let opening = "<send_user_message_question_reply>"
+ let closing = "</send_user_message_question_reply>"
+ // 异步回应通过用户消息携带问题标识, 仅解析完整信封, 不根据自然语言推断回应
+ guard text.hasPrefix(opening), text.hasSuffix(closing), text.count >= opening.count + closing.count,
+ let replies = try? JSONDecoder().decode(
+ [QuestionReply].self, from: Data(text.dropFirst(opening.count).dropLast(closing.count).utf8)
+ ) else { return [] }
+ return replies.compactMap { reply in
+ guard let value = try? JSONDecoder().decode(ActivityJSONValue.self, from: Data(reply.questionItemId.utf8)),
+ case let .array(parts) = value, parts.count == 3,
+ parts[0].string == "request_user_input_async", let itemID = parts[1].string, !itemID.isEmpty,
+ let number = parts[2].number, let index = Int(exactly: number), index >= 0 else { return nil }
+ return .init(itemID: itemID, index: index)
+ }
+ }
+ }
}
nonisolated extension ActivityInput: Decodable {
@@ -399,6 +433,7 @@ private nonisolated struct WireActivityLivePayload: Decodable {
var threadId: String?
var turnId: String?
var mode: String?
+ var isBlocking: Bool?
var plan: [Status]?
var run: Hook?
var showBufferingUi: Bool?
@@ -425,6 +460,7 @@ private nonisolated extension WireActivityLivePayload {
}
return ActivityLiveContext(
inputMode: inputMode,
+ isBlocking: isBlocking,
planCompleted: plan.map { $0.filter { $0.status == "completed" }.count },
planTotal: plan?.count,
run: run.map { .init(id: $0.id, status: $0.status.map { .init(rawValue: $0) ?? .unknown }, isSynchronous: $0.executionMode == "sync") },
diff --git a/CodexBar/Services/Activity/AppServerActivityReader.swift b/CodexBar/Services/Activity/AppServerActivityReader.swift
index aa81014..a44620a 100644
--- a/CodexBar/Services/Activity/AppServerActivityReader.swift
+++ b/CodexBar/Services/Activity/AppServerActivityReader.swift
@@ -762,8 +762,12 @@ actor AppServerActivityReader {
guard let id = notification.params.threadId ?? notification.params.thread?.id else { return }
switch notification.kind {
case .threadDiscovered, .threadStatusChanged, .turnStarted, .turnFinished,
- .commandApprovalRequested, .fileApprovalRequested, .permissionsRequested, .inputRequested, .requestResolved:
+ .commandApprovalRequested, .fileApprovalRequested, .permissionsRequested, .inputRequested, .userInputRequested, .requestResolved:
revisions[id, default: 0] += 1
+ case .itemStarted, .itemFinished:
+ if notification.params.item?.affectsInputWait == true {
+ revisions[id, default: 0] += 1
+ }
default: break
}
if notification.kind == .turnStarted, let turn = notification.params.turn, turn.startedAt.map({ $0 >= connectedAt }) ?? true {
diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swift
index 88ddb31..11221b9 100644
--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift
+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift
@@ -12,7 +12,7 @@ final class KeepAliveController: ObservableObject {
@Published private(set) var isPreventingSleep = false
@Published private(set) var sleepPreventionSource = CodexBarSleepPreventionSource.none
@Published private(set) var lowBatteryThreshold: LowBatteryThreshold
- /// 等待批准的任务算不算"有任务", 决定审批期间要不要继续挡住睡眠
+ /// 是否将审批等待和明确阻塞的提问计入防睡眠
@Published private(set) var keepsAwakeWhileWaiting: Bool
/// 防睡眠生效期间是否连屏幕一起留住, 顺带压住屏保与闲置锁屏
@Published private(set) var keepsDisplayAwake: Bool
@@ -147,7 +147,7 @@ final class KeepAliveController: ObservableObject {
// 默认关闭: 老版本升上来的用户不该多出一条中断任务的路径
lowBatteryThreshold = (defaults.object(forKey: Self.lowBatteryThresholdKey) as? Int)
.flatMap(LowBatteryThreshold.init(rawValue:)) ?? .off
- // 同样默认关闭: 等待批准没有终点, 开着它意味着无人值守时机器可能整夜不睡
+ // 默认关闭: 等待回应可能持续到用户返回, 避免无人值守时持续防睡眠
keepsAwakeWhileWaiting = defaults.bool(forKey: Self.keepsAwakeWhileWaitingKey)
// 默认关闭: 它会让人离开后机器一直停在解锁状态, 这个取舍只能由用户自己做
keepsDisplayAwake = defaults.bool(forKey: Self.keepsDisplayAwakeKey)
@@ -301,16 +301,16 @@ final class KeepAliveController: ObservableObject {
}
/// 只改"哪些任务算数", 不参与拦截判定
- /// 所以它不进 sleepBlockReason: 关着它时审批中的任务报的仍然是 noTasks, 与没有任务同一回事
+ /// 所以它不进 sleepBlockReason: 关着它时等待中的任务报的仍然是 noTasks, 与没有任务同一回事
func setKeepsAwakeWhileWaiting(_ enabled: Bool) {
guard enabled != keepsAwakeWhileWaiting else {
return
}
- AppLog.keepAlive.notice("KeepAlive 等待批准时保持防睡眠变更: enabled=\(enabled ? 1 : 0)")
+ AppLog.keepAlive.notice("KeepAlive 等待回应时保持防睡眠变更: enabled=\(enabled ? 1 : 0)")
keepsAwakeWhileWaiting = enabled
defaults.set(enabled, forKey: Self.keepsAwakeWhileWaitingKey)
- // 快照不会因为改设置重发一次, 正等着批准的那些任务只能在这里重新求值
+ // 快照不会因为改设置重发一次, 等待中的任务只能在这里重新求值
reconcileSleepState(trigger: .settings)
}
@@ -477,8 +477,7 @@ final class KeepAliveController: ObservableObject {
}
private func handleActivitySnapshot(_ snapshot: ActivitySnapshot) {
- let currentRunningTaskIDs = Set(snapshot.runningTasks.map(\.id))
- let currentWaitingTaskIDs = Set(snapshot.waitingTasks.map(\.id))
+ let (currentRunningTaskIDs, currentWaitingTaskIDs) = snapshot.keepAliveTaskIDs
// 运行与等待互斥, 新任务和等待后恢复都表现为运行集合新增成员
let hasEnteredRunning = !currentRunningTaskIDs.isSubset(of: runningTaskIDs)
runningTaskIDs = currentRunningTaskIDs
@@ -1407,7 +1406,7 @@ final class KeepAliveController: ObservableObject {
sleepBlockReason == nil
}
- /// 等待批准算不算"有任务"由用户开关决定, 快照与设置两条路径共用这一份规则
+ /// 等待任务算不算"有任务"由用户开关决定, 快照与设置两条路径共用这一份规则
private var hasKeepAliveTasks: Bool {
!runningTaskIDs.isEmpty || (keepsAwakeWhileWaiting && !waitingTaskIDs.isEmpty)
}
diff --git a/CodexBar/Views/Log/LogPreview.swift b/CodexBar/Views/Log/LogPreview.swift
index 6a0b45a..86880d3 100644
--- a/CodexBar/Views/Log/LogPreview.swift
+++ b/CodexBar/Views/Log/LogPreview.swift
@@ -283,29 +283,18 @@ final class LogPreviewPresentation {
/// 保留后台生成的文本存储和排版缓存, 窗口缩放只调整可滚动区域
final class LogPreviewScrollView: NSScrollView {
- private var previewDocument: LogPreviewDocument?
+ private let previewDocument: LogPreviewDocument
private static let textInset = NSSize(width: 12, height: 12)
init(document: LogPreviewDocument) {
+ previewDocument = document
super.init(frame: .zero)
hasVerticalScroller = true
hasHorizontalScroller = true
autohidesScrollers = false
drawsBackground = true
backgroundColor = .textBackgroundColor
- display(document)
- }
-
- @available(*, unavailable)
- required init?(coder _: NSCoder) {
- fatalError("init(coder:) is unavailable")
- }
-
- func display(_ document: LogPreviewDocument) {
- guard previewDocument?.storage !== document.storage else { return }
- previewDocument = document
- let size = fittedSize(for: document)
- let textView = NSTextView(frame: NSRect(origin: .zero, size: size), textContainer: document.container)
+ let textView = NSTextView(frame: NSRect(origin: .zero, size: fittedSize), textContainer: document.container)
textView.isEditable = false
textView.isSelectable = true
textView.isRichText = true
@@ -320,19 +309,24 @@ final class LogPreviewScrollView: NSScrollView {
documentView = textView
}
+ @available(*, unavailable)
+ required init?(coder _: NSCoder) {
+ fatalError("init(coder:) is unavailable")
+ }
+
override func layout() {
super.layout()
- guard let previewDocument, let documentView else { return }
- let size = fittedSize(for: previewDocument)
+ guard let documentView else { return }
+ let size = fittedSize
if documentView.frame.size != size {
documentView.setFrameSize(size)
}
}
- private func fittedSize(for document: LogPreviewDocument) -> NSSize {
+ private var fittedSize: NSSize {
NSSize(
- width: max(document.contentSize.width + Self.textInset.width * 2, contentSize.width),
- height: max(document.contentSize.height + Self.textInset.height * 2, contentSize.height)
+ width: max(previewDocument.contentSize.width + Self.textInset.width * 2, contentSize.width),
+ height: max(previewDocument.contentSize.height + Self.textInset.height * 2, contentSize.height)
)
}
}
@@ -344,7 +338,6 @@ struct LogCodePreviewView: NSViewRepresentable {
LogPreviewScrollView(document: document)
}
- func updateNSView(_ scrollView: LogPreviewScrollView, context _: Context) {
- scrollView.display(document)
- }
+ /// 每次预览由 item.id 创建独立视图, 文档在视图生命周期内保持不变
+ func updateNSView(_: LogPreviewScrollView, context _: Context) {}
}
diff --git a/CodexBar/Views/Log/LogView.swift b/CodexBar/Views/Log/LogView.swift
index d4ca137..74e2b02 100644
--- a/CodexBar/Views/Log/LogView.swift
+++ b/CodexBar/Views/Log/LogView.swift
@@ -5,6 +5,7 @@ import SwiftUI
struct LogView: View {
@ObservedObject var store: AppServerLogViewModel
@State private var preview = LogPreviewPresentation()
+ @State private var scrollPosition = ScrollPosition(idType: UUID.self, edge: .top)
var body: some View {
// 每轮渲染只取一次发布快照复用
@@ -89,8 +90,10 @@ struct LogView: View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
ForEach(entries) { entry in
- LogRow(entry: entry, preview: preview)
- Divider()
+ VStack(spacing: 0) {
+ LogRow(entry: entry, preview: preview)
+ Divider()
+ }
}
if store.hasMore {
ProgressView()
@@ -99,7 +102,16 @@ struct LogView: View {
.task(id: entries.last?.id) { await store.loadMore() }
}
}
+ .scrollTargetLayout()
+ }
+ .scrollPosition($scrollPosition, anchor: .top)
+ .onScrollPhaseChange { _, phase, context in
+ // 浏览时按日志身份保持位置, 回到顶部后才重新跟随新日志
+ if phase == .idle, context.geometry.contentOffset.y + context.geometry.contentInsets.top <= 1 {
+ scrollPosition.scrollTo(edge: .top)
+ }
}
+ .onDisappear { scrollPosition = ScrollPosition(idType: UUID.self, edge: .top) }
.background(Color(nsColor: .textBackgroundColor))
}
}
diff --git a/CodexBarTests/Activity/ActivityLivePresentationTests.swift b/CodexBarTests/Activity/ActivityLivePresentationTests.swift
index cb42be2..5f33cc2 100644
--- a/CodexBarTests/Activity/ActivityLivePresentationTests.swift
+++ b/CodexBarTests/Activity/ActivityLivePresentationTests.swift
@@ -24,6 +24,106 @@ struct ActivityLivePresentationTests {
try #require(reducer.states.values.first?.presentation?.summary)
}
+ @Test func asyncQuestionMessageWaitsAfterItemCompletionAndActiveRefresh() throws {
+ var reducer = try prepared()
+ let item = #""item":{"id":"question-call","type":"agentMessage","phase":"final_answer","delivery":"async","questions":[{"title":"Continue?","options":["Yes","No"]}]}"#
+ for method in ["item/started", "item/completed"] {
+ #expect(try reducer.consume(message(method, item), now: now).isEmpty)
+ #expect(try summary(reducer).current.key == "waiting-input")
+ }
+ _ = try reducer.consume(message("thread/status/changed", #""status":{"type":"active","activeFlags":[]}"#, turn: false), now: now.addingTimeInterval(1))
+ _ = try reducer.consume(message("item/agentMessage/delta", #""itemId":"answer","delta":"Still working""#), now: now.addingTimeInterval(2))
+ #expect(try summary(reducer).waiting?.since == now)
+ #expect(try summary(reducer).current.key == "waiting-input")
+ #expect(reducer.states.values.first?.isWaitingApproval == false)
+ }
+
+ private func userMessage(_ text: String) throws -> ActivityInput {
+ try JSONDecoder().decode(ActivityInput.self, from: JSONSerialization.data(withJSONObject: [
+ "method": "item/completed", "params": [
+ "threadId": "thread-a", "turnId": "turn-a",
+ "item": ["id": "reply", "type": "userMessage", "content": [["type": "text", "text": text]]]
+ ]
+ ]))
+ }
+
+ private func questionReply(_ itemID: String, index: Int) throws -> ActivityInput {
+ let identity = try JSONSerialization.data(withJSONObject: ["request_user_input_async", itemID, index])
+ let body = try JSONSerialization.data(withJSONObject: [["questionItemId": #require(String(data: identity, encoding: .utf8))]])
+ return try userMessage("<send_user_message_question_reply>\n" + #require(String(data: body, encoding: .utf8)) + "\n</send_user_message_question_reply>")
+ }
+
+ @Test func asyncQuestionsResolveIndividuallyWithoutClearingOtherWaits() throws {
+ var reducer = try prepared()
+ for id in ["first", "second"] {
+ _ = try reducer.consume(message("item/completed", """
+ "item":{"id":"\(id)","type":"agentMessage","delivery":"async","questions":[{"title":"One?"},{"title":"Two?"}]}
+ """), now: now)
+ }
+ let progress = reducer.states.values.first?.lastProgressAt
+ let unknown = try questionReply("unknown", index: 0)
+ #expect(reducer.consume(unknown, now: now.addingTimeInterval(1)).isEmpty)
+ for id in ["first", "second"] {
+ let reply = try questionReply(id, index: 0)
+ #expect(reply.params.item?.answeredQuestions == [.init(itemID: id, index: 0)])
+ #expect(reducer.consume(reply, now: now.addingTimeInterval(2)).isEmpty)
+ _ = reducer.consume(reply, now: now.addingTimeInterval(3))
+ #expect(try summary(reducer).waiting?.since == now)
+ }
+ _ = try reducer.consume(questionReply("first", index: 1), now: now.addingTimeInterval(4))
+ #expect(try summary(reducer).waiting != nil)
+ _ = try reducer.consume(message("mcpServer/elicitation/request", #""mode":"form""#, id: 7), now: now.addingTimeInterval(5))
+ _ = try reducer.consume(questionReply("second", index: 1), now: now.addingTimeInterval(6))
+ #expect(try summary(reducer).current.key == "waiting-form")
+ _ = try reducer.consume(message("serverRequest/resolved", #""requestId":7"#, turn: false), now: now.addingTimeInterval(7))
+ #expect(try summary(reducer).waiting == nil)
+ #expect(reducer.states.values.first?.lastProgressAt == progress)
+ #expect(reducer.states.values.first?.isWaitingApproval == false)
+ }
+
+ @Test(arguments: [
+ #""delivery":"async","questions":[]"#,
+ #""delivery":"async","questions":null"#,
+ #""questions":[{"title":"Plain message?"}]"#
+ ])
+ func ordinaryAgentMessagesDoNotCreateQuestionWaits(fields: String) throws {
+ var reducer = try prepared()
+ _ = try reducer.consume(message("item/completed", "\"item\":{\"id\":\"plain\",\"type\":\"agentMessage\",\(fields)}"), now: now)
+ #expect(try summary(reducer).waiting == nil)
+ }
+
+ @Test(arguments: [
+ "Yes", "<send_user_message_question_reply>invalid</send_user_message_question_reply>",
+ #"<send_user_message_question_reply>[{"questionItemId":"[\"other_tool\",\"question\",0]"}]</send_user_message_question_reply>"#,
+ #"<send_user_message_question_reply>[{"questionItemId":"[\"request_user_input_async\",\"question\",-1]"}]</send_user_message_question_reply>"#,
+ #"<send_user_message_question_reply>[{"questionItemId":"[\"request_user_input_async\",\"question\",0.5]"}]</send_user_message_question_reply>"#,
+ #"Quoted: <send_user_message_question_reply>[{"questionItemId":"[\"request_user_input_async\",\"question\",0]"}]</send_user_message_question_reply>"#
+ ])
+ func unrelatedOrMalformedUserMessagesDoNotClearAsyncQuestions(text: String) throws {
+ var reducer = try prepared()
+ _ = try reducer.consume(message("item/completed", #""item":{"id":"question","type":"agentMessage","delivery":"async","questions":[{"title":"Question?"}]}"#), now: now)
+ let reply = try userMessage(text)
+ #expect(reply.params.item?.answeredQuestions.isEmpty == true)
+ _ = reducer.consume(reply, now: now.addingTimeInterval(1))
+ #expect(try summary(reducer).waiting?.since == now)
+ }
+
+ @Test(arguments: ["idle", "completed", "reconnect"])
+ func asyncQuestionWaitsEndWithTheirTurnOrConnection(ending: String) throws {
+ var reducer = try prepared()
+ _ = try reducer.consume(message("item/completed", #""item":{"id":"question","type":"agentMessage","delivery":"async","questions":[{"title":"Question?"}]}"#), now: now)
+ #expect(try summary(reducer).waiting != nil)
+ switch ending {
+ case "idle":
+ _ = try reducer.consume(message("thread/status/changed", #""status":{"type":"idle"}"#, turn: false), now: now.addingTimeInterval(1))
+ case "completed":
+ _ = try reducer.consume(message("turn/completed", #""turn":{"id":"turn-a","status":"completed"}"#), now: now.addingTimeInterval(1))
+ default:
+ reducer.reconnect()
+ }
+ #expect(reducer.states.values.first?.presentation?.summary.waiting == nil)
+ }
+
@Test func toolCompletionDoesNotMaskReasoningOrAnswerDeltas() throws {
var reducer = try prepared()
_ = try reducer.consume(message("item/started", #""item":{"id":"cmd","type":"commandExecution","commandActions":[{"type":"read"}]}"#), now: now)
@@ -276,11 +376,105 @@ struct ActivityLivePresentationTests {
#expect(live.summary.waiting?.since == now.addingTimeInterval(1))
}
- @Test func nonblockingInputAndUncorrelatedElicitationNeverBecomeWaiting() throws {
+ @Test(arguments: [true, false, nil] as [Bool?])
+ func userInputWaitsEndByRequestIDWithoutChangingLifecycle(isBlocking: Bool?) throws {
+ var reducer = try prepared()
+ let before = try #require(reducer.states.values.first)
+ let blocking = isBlocking.map { String($0) } ?? "null"
+ let input = try message("item/tool/requestUserInput", """
+ "itemId":"question","isBlocking":\(blocking),"autoResolutionMs":null,
+ "questions":[{"id":"q","header":"Choice","question":"private question","isOther":true,"isSecret":true,"options":null}]
+ """, id: 1)
+ #expect(input.kind.category == .presentation)
+ #expect(reducer.consume(input, now: now).isEmpty)
+ #expect(try summary(reducer).current.key == "waiting-input")
+ #expect(try summary(reducer).current.detail == nil)
+ #expect(try summary(reducer).waiting?.isBlocking == isBlocking)
+ #expect(try summary(reducer).hasBlockingInputRequest == (isBlocking == true))
+ #expect(try summary(reducer).waiting?.since == now)
+ #expect(reducer.consume(input, now: now.addingTimeInterval(1)).isEmpty)
+ #expect(try summary(reducer).waiting?.since == now)
+ let state = try #require(reducer.states.values.first)
+ #expect(state.isWaitingApproval == before.isWaitingApproval)
+ #expect(state.pendingApprovals.isEmpty)
+ #expect(state.lastProgressAt == before.lastProgressAt)
+ _ = try reducer.consume(message("serverRequest/resolved", #""requestId":99"#, turn: false), now: now.addingTimeInterval(2))
+ #expect(try summary(reducer).waiting != nil)
+ #expect(try reducer.consume(message("serverRequest/resolved", #""requestId":1"#, turn: false), now: now.addingTimeInterval(3)).isEmpty)
+ #expect(try summary(reducer).waiting == nil)
+ #expect(try summary(reducer).hasBlockingInputRequest == false)
+ #expect(try summary(reducer).recent?.label.key == "request-ended")
+ }
+
+ @Test func earlierAsyncWaitDoesNotMaskBlockingRequests() throws {
+ var reducer = try prepared()
+ _ = try reducer.consume(message("item/completed", #""item":{"id":"async","type":"agentMessage","delivery":"async","questions":[{"title":"Question?"}]}"#), now: now)
+ _ = try reducer.consume(message("item/tool/requestUserInput", #""isBlocking":false"#, id: 1), now: now.addingTimeInterval(1))
+ for id in [2, 3] {
+ _ = try reducer.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: id), now: now.addingTimeInterval(Double(id)))
+ }
+ #expect(try summary(reducer).waiting?.since == now)
+ #expect(try summary(reducer).waiting?.isBlocking == false)
+ #expect(try summary(reducer).hasBlockingInputRequest == true)
+ for id in [99, 1, 2] {
+ _ = try reducer.consume(message("serverRequest/resolved", "\"requestId\":\(id)", turn: false), now: now.addingTimeInterval(4))
+ #expect(try summary(reducer).hasBlockingInputRequest == true)
+ }
+ _ = try reducer.consume(message("serverRequest/resolved", #""requestId":3"#, turn: false), now: now.addingTimeInterval(5))
+ #expect(try summary(reducer).hasBlockingInputRequest == false)
+ #expect(try summary(reducer).waiting?.since == now)
+ }
+
+ @Test(arguments: ["active", "idle", "completed", "failed", "interrupted", "reconnect"])
+ func blockingInputEndsWithAuthoritativeStateOrConnection(ending: String) throws {
+ var reducer = try prepared()
+ _ = try reducer.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: 1), now: now)
+ #expect(try summary(reducer).hasBlockingInputRequest == true)
+ switch ending {
+ case "active", "idle":
+ _ = try reducer.consume(message("thread/status/changed", "\"status\":{\"type\":\"\(ending)\",\"activeFlags\":[]}", turn: false), now: now.addingTimeInterval(1))
+ case "reconnect":
+ reducer.reconnect()
+ default:
+ _ = try reducer.consume(message("turn/completed", "\"turn\":{\"id\":\"turn-a\",\"status\":\"\(ending)\"}"), now: now.addingTimeInterval(1))
+ }
+ #expect(reducer.states.values.first?.presentation?.summary.hasBlockingInputRequest != true)
+ }
+
+ @Test func nonblockingQuestionsSurviveActiveStatusAndResolveIndependently() throws {
var reducer = try prepared()
_ = try reducer.consume(message("item/tool/requestUserInput", #""isBlocking":false"#, id: 1), now: now)
+ _ = try reducer.consume(message("item/tool/requestUserInput", #""isBlocking":false"#, id: 2), now: now.addingTimeInterval(1))
+ _ = try reducer.consume(message("item/agentMessage/delta", #""itemId":"answer""#), now: now.addingTimeInterval(2))
+ _ = try reducer.consume(message("thread/status/changed", #""status":{"type":"active","activeFlags":[]}"#, turn: false), now: now.addingTimeInterval(3))
+ let thread = ActivityThread(id: "thread-a", status: ActivityThreadStatus(type: .active, activeFlags: []))
+ _ = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn-a", status: .running)], now: now.addingTimeInterval(4))
+ #expect(try summary(reducer).waiting?.since == now)
+ _ = try reducer.consume(message("serverRequest/resolved", #""requestId":1"#, turn: false), now: now.addingTimeInterval(5))
+ #expect(try summary(reducer).waiting?.since == now.addingTimeInterval(1))
+ _ = try reducer.consume(message("serverRequest/resolved", #""requestId":2"#, turn: false), now: now.addingTimeInterval(6))
#expect(try summary(reducer).waiting == nil)
- _ = try reducer.consume(message("mcpServer/elicitation/request", #""mode":"url""#, id: 2, turn: false), now: now)
+ #expect(try summary(reducer).current.key == "replying")
+ }
+
+ @Test func activeStatusClearsBlockingRequestsButKeepsNonblockingQuestions() throws {
+ var live = ActivityLivePresentation()
+ try live.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: 1), at: now)
+ try live.consume(message("mcpServer/elicitation/request", #""mode":"form""#, id: 2), at: now)
+ try live.consume(message("item/tool/requestUserInput", #""isBlocking":false"#, id: 3), at: now.addingTimeInterval(1))
+ live.reconcile(status: ActivityThreadStatus(type: .active, activeFlags: []))
+ #expect(live.requests.count == 1)
+ #expect(live.summary.waiting?.since == now.addingTimeInterval(1))
+ try live.consume(message("serverRequest/resolved", #""requestId":3"#, turn: false), at: now.addingTimeInterval(2))
+ #expect(live.summary.waiting == nil)
+ }
+
+ @Test(arguments: ["mcpServer/elicitation/request", "item/tool/requestUserInput"])
+ func uncorrelatedInputNeverBecomesWaiting(method: String) throws {
+ var reducer = try prepared()
+ _ = try reducer.consume(message(method, #""mode":"url","isBlocking":false"#, id: 1, turn: false), now: now)
+ #expect(try summary(reducer).waiting == nil)
+ _ = try reducer.consume(message(method, #""mode":"url","isBlocking":false"#), now: now)
#expect(try summary(reducer).waiting == nil)
}
@@ -338,7 +532,11 @@ struct ActivityLivePresentationTests {
#expect(item.liveCompletionLabel?.key == (status == "unknown" ? nil : "image-" + status))
}
- @Test func displayWaitingDoesNotChangeApprovalOrProtectionState() throws {
+ @Test(arguments: [
+ ("thread/status/changed", false), ("mcpServer/elicitation/request", false),
+ ("item/tool/requestUserInput", false), ("item/tool/requestUserInput", true), ("item/completed", false)
+ ])
+ func displayWaitingDoesNotChangeApprovalOrProtectionState(method: String, isBlocking: Bool) throws {
let event = TestFixtures.event()
var task = try ActivityTask(
displayID: UUID(),
@@ -349,7 +547,10 @@ struct ActivityLivePresentationTests {
progressGeneration: 0
)
var reducer = try prepared()
- _ = try reducer.consume(message("thread/status/changed", #""status":{"type":"active","activeFlags":["waitingOnUserInput"]}"#, turn: false), now: now)
+ _ = try reducer.consume(message(method, """
+ "status":{"type":"active","activeFlags":["waitingOnUserInput"]},"isBlocking":\(isBlocking),
+ "item":{"id":"question","type":"agentMessage","delivery":"async","questions":[{"title":"Question?"}]}
+ """, id: 1), now: now)
let state = try #require(reducer.states.values.first)
task.mergeExecutionLifecycle(state, owner: ActivityExecutionKey(agentThreadID: nil, turnID: "turn-a"))
let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [task.snapshot], recentCompletions: [], recentTerminations: [])
@@ -359,15 +560,59 @@ struct ActivityLivePresentationTests {
#expect(snapshot.panelRunningTasks.isEmpty)
#expect(snapshot.primaryActivity == .running(task.snapshot))
#expect(snapshot.panelPrimaryActivity == .waiting(task.snapshot))
+ #expect(snapshot.keepAliveTaskIDs.waiting == (isBlocking ? [task.displayID] : []))
+ #expect(snapshot.keepAliveTaskIDs.running == (isBlocking ? [] : [task.displayID]))
let summary = ActivityDisplayFormat.liveSummaryComponents(for: task.snapshot, now: now)
#expect(summary.count == 2)
#expect(summary.first == ActivityLiveLabel("elapsed-running").text + " " + CodexDurationFormat.activityText(for: 0))
#expect(summary.last == ActivityLiveLabel("elapsed-waiting").text + " " + CodexDurationFormat.activityText(for: 0))
}
+ @Test(arguments: [false, true])
+ func keepAliveFindsBlockingInputAcrossExecutions(blockingInChild: Bool) throws {
+ let event = TestFixtures.event()
+ var task = try ActivityTask(
+ displayID: UUID(), key: #require(ActivityTaskKey(event: event)), event: event,
+ state: .running, startedAt: now, progressGeneration: 0
+ )
+ var nonblocking = ActivityLivePresentation()
+ try nonblocking.consume(message("item/completed", #""item":{"id":"async","type":"agentMessage","delivery":"async","questions":[{"title":"Question?"}]}"#), at: now)
+ var blocking = ActivityLivePresentation()
+ try blocking.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: 1), at: now.addingTimeInterval(1))
+ let rootOwner = ActivityExecutionKey(agentThreadID: nil, turnID: "turn-a")
+ let childOwner = ActivityExecutionKey(agentThreadID: "child", turnID: "child-turn")
+ task.executions[rootOwner] = ActivityExecution(presentation: blockingInChild ? nonblocking : blocking)
+ task.executions[childOwner] = ActivityExecution(presentation: blockingInChild ? blocking : nonblocking)
+ let waiting = task.snapshot
+ #expect(waiting.presentation?.waiting?.isBlocking == false)
+ #expect(waiting.presentation?.hasBlockingInputRequest == true)
+ let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [waiting], recentCompletions: [], recentTerminations: [])
+ #expect(snapshot.keepAliveTaskIDs.waiting == [task.displayID])
+ #expect(snapshot.keepAliveTaskIDs.running.isEmpty)
+
+ let concurrent = ActivityTaskSnapshot(
+ id: UUID(), projectName: nil, modelName: nil, effort: nil,
+ startedAt: now, stateChangedAt: now, activeSubagentCount: nil
+ )
+ let mixed = ActivitySnapshot(waitingTasks: [], runningTasks: [waiting, concurrent], recentCompletions: [], recentTerminations: [])
+ #expect(mixed.keepAliveTaskIDs.running == [concurrent.id])
+ #expect(mixed.keepAliveTaskIDs.waiting == [task.displayID])
+ let approval = ActivitySnapshot(waitingTasks: [concurrent], runningTasks: [waiting], recentCompletions: [], recentTerminations: [])
+ #expect(approval.keepAliveTaskIDs.running.isEmpty)
+ #expect(approval.keepAliveTaskIDs.waiting == [concurrent.id, task.displayID])
+
+ task.finishExecution(blockingInChild ? childOwner : rootOwner, at: now.addingTimeInterval(2))
+ #expect(task.snapshot.presentation?.waiting != nil)
+ #expect(task.snapshot.presentation?.hasBlockingInputRequest == false)
+ let resumed = ActivitySnapshot(waitingTasks: [], runningTasks: [task.snapshot], recentCompletions: [], recentTerminations: [])
+ #expect(resumed.keepAliveTaskIDs.running == [task.displayID])
+ #expect(resumed.keepAliveTaskIDs.waiting.isEmpty)
+ }
+
@Test func authoritativeIdleClearsRequestsWithoutInventingApproval() throws {
var live = ActivityLivePresentation()
try live.consume(message("mcpServer/elicitation/request", #""mode":"form""#, id: 1), at: now)
+ try live.consume(message("item/tool/requestUserInput", #""isBlocking":false"#, id: 2), at: now)
live.reconcile(status: ActivityThreadStatus(type: .idle))
#expect(live.summary.waiting == nil)
#expect(live.summary.recent == nil)
@@ -413,6 +658,7 @@ struct ActivityLivePresentationTests {
@Test func failedTurnKeepsItsOutcomeWithoutChangingTerminalPolicy() throws {
var reducer = try prepared()
+ _ = try reducer.consume(message("item/tool/requestUserInput", #""isBlocking":false"#, id: 1), now: now)
let events = try reducer.consume(message("turn/completed", #""turn":{"id":"turn-a","status":"failed"}"#), now: now)
let state = try #require(reducer.states.values.first)
#expect(state.turnStatus == .failed)
@@ -432,6 +678,15 @@ struct ActivityLivePresentationTests {
#expect(task.terminalFailed)
}
+ @Test func reconnectDiscardsPendingNonblockingQuestions() throws {
+ var reducer = try prepared()
+ _ = try reducer.consume(message("item/tool/requestUserInput", #""isBlocking":false"#, id: 1), now: now)
+ reducer.reconnect()
+ let thread = ActivityThread(id: "thread-a", status: ActivityThreadStatus(type: .active, activeFlags: []))
+ _ = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn-a", status: .running)], now: now.addingTimeInterval(1))
+ #expect(try summary(reducer).waiting == nil)
+ }
+
@Test func mixedCommandActionsResolveTheExplicitLocalizedKey() {
let item = ActivityItem(
id: "cmd", type: .commandExecution,
diff --git a/CodexBarTests/Activity/ActivitySchedulingTests.swift b/CodexBarTests/Activity/ActivitySchedulingTests.swift
index e83c990..20dc910 100644
--- a/CodexBarTests/Activity/ActivitySchedulingTests.swift
+++ b/CodexBarTests/Activity/ActivitySchedulingTests.swift
@@ -299,7 +299,8 @@ struct ActivitySchedulingTests {
}
extension ActivitySchedulingTests {
- @Test func snapshotCannotDismissNewMCPInputRequest() async throws {
+ @Test(arguments: ["mcpServer/elicitation/request", "item/tool/requestUserInput", "item/completed"])
+ func snapshotCannotDismissNewInputRequest(method: String) async throws {
let directory = try TestDirectory()
defer { try? directory.remove() }
let release = DispatchSemaphore(value: 0)
@@ -310,9 +311,11 @@ extension ActivitySchedulingTests {
let loaded = try peer.readMessage()
try peer.reply(to: loaded, result: ["data": ["thread"]])
let read = try peer.readMessage()
- try peer.send(["id": "input", "method": "mcpServer/elicitation/request", "params": [
- "threadId": "thread", "turnId": "turn", "mode": "form"
- ]])
+ var params: [String: Any] = ["threadId": "thread", "turnId": "turn", "mode": "form", "isBlocking": false]
+ if method == "item/completed" {
+ params["item"] = ["id": "input", "type": "agentMessage", "delivery": "async", "questions": [["title": "Question?"]]]
+ }
+ try peer.send(["id": "input", "method": method, "params": params])
try peer.reply(to: read, result: ["thread": Self.thread(timestamp, status: "idle")])
let turns = try peer.readMessage()
try peer.reply(to: turns, result: ["data": [["id": "turn", "rootTurnId": "turn", "status": "inProgress", "startedAt": timestamp]]])
@@ -334,7 +337,7 @@ extension ActivitySchedulingTests {
}
#expect(await reader.drainNow().status == .partial)
let state = await reader.lifecycleStatesForTesting(for: [.init(threadID: "thread", turnID: "turn")]).first
- #expect(state?.presentation?.requests["input"] != nil)
+ #expect(state?.presentation?.summary.waiting != nil)
await reader.stop()
release.signal()
try server.finish()
diff --git a/CodexBarTests/Activity/AppServerActivityTests.swift b/CodexBarTests/Activity/AppServerActivityTests.swift
index e548eef..5026f1d 100644
--- a/CodexBarTests/Activity/AppServerActivityTests.swift
+++ b/CodexBarTests/Activity/AppServerActivityTests.swift
@@ -73,7 +73,7 @@ struct AppServerActivityTests {
@Test(arguments: [
"thread/settings/updated", "thread/environment/connected", "thread/environment/disconnected",
- "item/plan/delta", "item/tool/requestUserInput", "item/autoApprovalReview/started", "item/autoApprovalReview/completed",
+ "item/plan/delta", "item/autoApprovalReview/started", "item/autoApprovalReview/completed",
"item/fileChange/outputDelta", "item/future/delta", "item/future/outputDelta", "hook/delta", "command/exec/outputDelta",
"process/outputDelta", "item/reasoning/textDelta/extra", "item/agentMessage/Delta"
])
diff --git a/CodexBarTests/AppServer/AppServerSessionTests.swift b/CodexBarTests/AppServer/AppServerSessionTests.swift
index 0dfe465..4324a09 100644
--- a/CodexBarTests/AppServer/AppServerSessionTests.swift
+++ b/CodexBarTests/AppServer/AppServerSessionTests.swift
@@ -277,6 +277,15 @@ struct AppServerSessionTests {
]))
}
try filtered.append(notification("item/agentMessage/delta", params: ["delta": 123]))
+ try retained.append(JSONSerialization.data(withJSONObject: [
+ "id": "question", "method": "item/tool/requestUserInput", "params": [
+ "threadId": "thread", "turnId": "turn", "itemId": "item", "isBlocking": false,
+ "questions": [[
+ "id": "q", "header": "Question", "question": "original question", "isSecret": true, "isOther": true,
+ "options": [["label": "Original option", "description": "original description"]]
+ ]]
+ ]
+ ]))
for count in 1 ... 3 {
try retained.append(notification("thread/tokenUsage/updated", params: ["total": count]))
}
@@ -321,7 +330,7 @@ struct AppServerSessionTests {
var messages: [Data] = []
for method in [
"thread/settings/updated", "thread/environment/connected", "thread/environment/disconnected",
- "item/tool/requestUserInput", "item/autoApprovalReview/started", "item/autoApprovalReview/completed",
+ "item/autoApprovalReview/started", "item/autoApprovalReview/completed",
"hook/futureEvent",
"remoteControl/status/changed", "thread/goal/cleared", "thread/name/updated", "future/tool/delta"
] {
diff --git a/CodexBarTests/Presentation/LogPreviewTests.swift b/CodexBarTests/Presentation/LogPreviewTests.swift
index 3268b9e..12635fc 100644
--- a/CodexBarTests/Presentation/LogPreviewTests.swift
+++ b/CodexBarTests/Presentation/LogPreviewTests.swift
@@ -122,7 +122,7 @@ struct LogPreviewTests {
#expect(presentation.item == nil)
}
- @Test func repeatedDisplayAndResizeKeepSelectionScrollAndLayout() async throws {
+ @Test func repeatedLayoutAndResizeKeepSelectionScrollAndLayout() async throws {
let document = try await LogPreviewPreparer.shared.document(for: Self.denseJSON)
let scrollView = LogPreviewScrollView(document: document)
scrollView.setFrameSize(NSSize(width: 860, height: 600))
@@ -138,7 +138,8 @@ struct LogPreviewTests {
let visibleOrigin = scrollView.contentView.bounds.origin
#expect(visibleOrigin.y > 0)
for _ in 0 ..< 3 {
- scrollView.display(document)
+ scrollView.needsLayout = true
+ scrollView.layoutSubtreeIfNeeded()
}
#expect(scrollView.documentView === textView)
#expect(textView.selectedRange() == selection)
@@ -166,16 +167,16 @@ struct LogPreviewTests {
#expect(scrollView.contentView.bounds.maxX >= document.contentSize.width)
let short = try await LogPreviewPreparer.shared.document(for: "🙂 汉字 é")
- scrollView.display(short)
- scrollView.layoutSubtreeIfNeeded()
- let replacement = try #require(scrollView.documentView as? NSTextView)
- #expect(replacement !== textView)
- #expect(replacement.string == "🙂 汉字 é")
- #expect(replacement.frame.width >= scrollView.contentSize.width)
- #expect(replacement.frame.height >= scrollView.contentSize.height)
- replacement.setSelectedRange(NSRange(location: 0, length: short.storage.length))
- #expect(replacement.selectedRange().length == short.storage.length)
- #expect(scrollView.contentView.bounds.origin.x == 0)
+ let shortScrollView = LogPreviewScrollView(document: short)
+ shortScrollView.setFrameSize(NSSize(width: 860, height: 600))
+ shortScrollView.layoutSubtreeIfNeeded()
+ let shortTextView = try #require(shortScrollView.documentView as? NSTextView)
+ #expect(shortTextView.string == "🙂 汉字 é")
+ #expect(shortTextView.frame.width >= shortScrollView.contentSize.width)
+ #expect(shortTextView.frame.height >= shortScrollView.contentSize.height)
+ shortTextView.setSelectedRange(NSRange(location: 0, length: short.storage.length))
+ #expect(shortTextView.selectedRange().length == short.storage.length)
+ #expect(shortScrollView.contentView.bounds.origin.x == 0)
}
private static var denseJSON: String {
diff --git a/CodexBarTests/Presentation/TaskGlowTests.swift b/CodexBarTests/Presentation/TaskGlowTests.swift
index da81194..81ae26b 100644
--- a/CodexBarTests/Presentation/TaskGlowTests.swift
+++ b/CodexBarTests/Presentation/TaskGlowTests.swift
@@ -199,13 +199,41 @@ struct TaskGlowTests {
#expect(presentation.terminal?.startedAt == nextPresentationTime)
}
- @Test func concurrentTaskCompletionStillShowsBrieflyThenRestoresRunning() throws {
+ @Test func liveInputWaitMatchesPanelAndReturnsToRunningAfterResponse() {
+ var task = ActivityTaskSnapshot(
+ id: UUID(), projectName: nil, modelName: nil, effort: nil, startedAt: TestFixtures.now,
+ stateChangedAt: TestFixtures.now, activeSubagentCount: nil
+ )
var presentation = TaskGlowPresentationState()
- let running = ActivityTaskSnapshot(
+ for waiting in [false, true, false] {
+ task.presentation = ActivityLiveSummary(
+ current: ActivityLiveLabel(waiting ? "waiting-input" : "replying"),
+ waiting: waiting ? ActivityLiveWait(label: ActivityLiveLabel("waiting-input"), since: TestFixtures.now) : nil
+ )
+ let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [task], recentCompletions: [], recentTerminations: [])
+ presentation.update(snapshot: snapshot, terminalEvents: [], isEnabled: true, acceptsBriefEvents: true, now: TestFixtures.now)
+ presentation.refresh(now: TestFixtures.now, terminalDuration: 10)
+ #expect(snapshot.waitingCount == 0)
+ #expect(snapshot.runningCount == 1)
+ #expect(snapshot.panelWaitingTasks.isEmpty == !waiting)
+ #expect(presentation.state == (waiting ? .waiting : .running))
+ }
+ }
+
+ @Test(arguments: [false, true])
+ func concurrentTaskCompletionStillShowsBrieflyThenRestoresActiveState(waiting: Bool) throws {
+ var presentation = TaskGlowPresentationState()
+ var running = ActivityTaskSnapshot(
id: UUID(), projectName: nil,
modelName: nil, effort: nil, startedAt: TestFixtures.now,
stateChangedAt: TestFixtures.now, activeSubagentCount: nil
)
+ if waiting {
+ running.presentation = ActivityLiveSummary(
+ current: ActivityLiveLabel("waiting-input"),
+ waiting: ActivityLiveWait(label: ActivityLiveLabel("waiting-input"), since: TestFixtures.now)
+ )
+ }
let snapshot = ActivitySnapshot(
waitingTasks: [], runningTasks: [running],
recentCompletions: completedSnapshot().recentCompletions, recentTerminations: []
@@ -219,7 +247,7 @@ struct TaskGlowTests {
#expect(presentation.state == .completed)
#expect(presentation.terminal?.expiresAt == TestFixtures.now.addingTimeInterval(3))
presentation.refresh(now: TestFixtures.now.addingTimeInterval(3), terminalDuration: 15)
- #expect(presentation.state == .running)
+ #expect(presentation.state == (waiting ? .waiting : .running))
}
private func completedSnapshot() -> ActivitySnapshot {
diff --git a/Protocol.en.md b/Protocol.en.md
index 510d83e..fa01545 100644
--- a/Protocol.en.md
+++ b/Protocol.en.md
@@ -1,32 +1,31 @@
# app-server API Inventory
-Applicable version Codex `0.162.0`
+Codex version: `0.162.0`
-## Outgoing Calls
-
-### Requests
+## Outgoing Requests
| API | Purpose |
| --- | --- |
| `initialize` | Initialize the connection and retrieve the server version |
-| `account/read` | Read account information and refresh authentication |
+| `account/read` | Read account information; `refreshToken` specifies whether to refresh authentication |
| `account/rateLimits/read` | Read rate limits, credit balance, and reset credits |
| `account/usage/read` | Read account usage summaries and daily token usage |
-| `account/rateLimitResetCredit/consume` | Consume a rate limit reset credit |
+| `account/rateLimitResetCredit/consume` | Consume a rate limit reset credit; `creditId` identifies the credit, and `idempotencyKey` prevents duplicate consumption |
| `config/read` | Read Codex TUI notification settings |
-| `config/batchWrite` | Update Codex TUI notification settings |
+| `config/batchWrite` | Update Codex TUI notification settings; `edits` specifies the value of `tui.notifications`, and `reloadUserConfig: true` applies the change |
| `thread/loaded/list` | List loaded threads |
-| `thread/read` | Read thread information and status |
-| `thread/resume` | Subscribe to messages from a loaded thread |
-| `thread/turns/list` | Read a thread's turns, statuses, root turn IDs, and sub-agent creation information |
+| `thread/read` | Read thread information and status; `threadId` identifies the thread, and `includeTurns: false` omits turn content |
+| `thread/resume` | Subscribe to messages from a loaded thread; `threadId` identifies the thread, and `excludeTurns: true` omits turn content |
+| `thread/turns/list` | Read paginated turn information for a thread; `threadId` identifies the thread, and `itemsView: "notLoaded"` omits item content |
+| `thread/items/list` | Read paginated items for a turn; `threadId` and `turnId` identify the target turn |
-### Notifications
+## Outgoing Notifications
| API | Purpose |
| --- | --- |
| `initialized` | Notify the server that initialization is complete |
-## Incoming Messages
+## Incoming Notifications
### Account Notifications
@@ -35,7 +34,7 @@ Applicable version Codex `0.162.0`
| `account/updated` | Receive account change notifications |
| `account/rateLimits/updated` | Receive rate limit change notifications |
-### Thread, Turn, and Item Notifications
+### Threads, Turns, and Items
| API | Purpose |
| --- | --- |
@@ -44,8 +43,8 @@ Applicable version Codex `0.162.0`
| `thread/tokenUsage/updated` | Receive thread token usage updates |
| `turn/started` | Receive turn start notifications |
| `turn/completed` | Receive turn end notifications |
-| `item/started` | Receive item start notifications |
-| `item/completed` | Receive item end notifications |
+| `item/started` | Receive item start notifications, including asynchronous questions and user responses |
+| `item/completed` | Receive item end notifications, including asynchronous questions and user responses |
### Progress Notifications
@@ -69,24 +68,16 @@ Applicable version Codex `0.162.0`
| `model/safetyBuffering/updated` | Receive safety buffering display status |
| `hook/started` | Observe the start of hook execution |
| `hook/completed` | Receive hook execution results |
-| `serverRequest/resolved` | Observe that a server request has been resolved |
+| `serverRequest/resolved` | Receive notifications that server requests, such as approvals or questions, have ended |
| `error` | Receive error notifications |
| `warning` | Log server warnings |
-### Server Requests
+## Server Requests
| API | Purpose |
| --- | --- |
| `item/commandExecution/requestApproval` | Observe command execution approval requests |
| `item/fileChange/requestApproval` | Observe file change approval requests |
| `item/permissions/requestApproval` | Observe permission approval requests |
+| `item/tool/requestUserInput` | Observe questions asked during a turn; `isBlocking` indicates whether the question blocks execution |
| `mcpServer/elicitation/request` | Observe MCP elicitation requests |
-
-## Root Turn and Sub-Agent Fields Used
-
-| API | Field | Purpose |
-| --- | --- | --- |
-| `thread/turns/list` | Request parameter `itemsView` | Use `notLoaded` to read turn information and `full` to read items containing sub-agent creation information |
-| `thread/turns/list`, `turn/started`, `turn/completed` | `Turn.rootTurnId` | Read the ID of the root turn in the chain of work leading to the current turn |
-| `thread/turns/list`, `item/started`, `item/completed` | `subAgentActivity.model` | Read the resolved model at sub-agent creation when `kind` is `started` |
-| `thread/turns/list`, `item/started`, `item/completed` | `subAgentActivity.reasoningEffort` | Read the resolved reasoning effort at sub-agent creation when `kind` is `started` |
diff --git a/Protocol.md b/Protocol.md
index 314fd5b..fb84ca6 100644
--- a/Protocol.md
+++ b/Protocol.md
@@ -1,33 +1,31 @@
# app-server 接口清单
-适用版本 Codex `0.162.0`
+Codex 版本:`0.162.0`
-## 主动调用
-
-### 请求
+## 主动请求
| 接口 | 作用 |
| --- | --- |
| `initialize` | 初始化连接,获取服务端版本 |
-| `account/read` | 读取账户信息、刷新认证 |
+| `account/read` | 读取账户信息;`refreshToken` 指定是否刷新认证 |
| `account/rateLimits/read` | 读取额度、余额和重置凭证 |
| `account/usage/read` | 读取账户用量汇总和每日 Token 用量 |
-| `account/rateLimitResetCredit/consume` | 消费额度重置凭证 |
+| `account/rateLimitResetCredit/consume` | 消费额度重置凭证;`creditId` 指定凭证,`idempotencyKey` 用于避免重复消费 |
| `config/read` | 读取 Codex TUI 通知配置 |
-| `config/batchWrite` | 修改 Codex TUI 通知配置 |
+| `config/batchWrite` | 修改 Codex TUI 通知配置;`edits` 指定 `tui.notifications` 的值,`reloadUserConfig: true` 使配置生效 |
| `thread/loaded/list` | 获取已加载会话列表 |
-| `thread/read` | 读取会话信息和状态 |
-| `thread/resume` | 订阅已加载会话的消息 |
-| `thread/turns/list` | 获取会话的轮次列表、状态和根轮次标识 |
-| `thread/items/list` | 分页读取目标轮次的执行项,补齐历史活动和子 Agent 创建信息 |
+| `thread/read` | 读取会话信息和状态;`threadId` 指定会话,`includeTurns: false` 不返回轮次内容 |
+| `thread/resume` | 订阅已加载会话的消息;`threadId` 指定会话,`excludeTurns: true` 不返回轮次内容 |
+| `thread/turns/list` | 分页读取会话的轮次信息;`threadId` 指定会话,`itemsView: "notLoaded"` 不加载执行项正文 |
+| `thread/items/list` | 分页读取轮次的执行项;`threadId` 和 `turnId` 指定目标轮次 |
-### 通知
+## 主动通知
| 接口 | 作用 |
| --- | --- |
| `initialized` | 告知服务端初始化已完成 |
-## 被动接收
+## 接收通知
### 账户通知
@@ -36,7 +34,7 @@
| `account/updated` | 接收账户变化通知 |
| `account/rateLimits/updated` | 接收额度变化通知 |
-### 会话、轮次和 item 通知
+### 会话、轮次和执行项
| 接口 | 作用 |
| --- | --- |
@@ -45,8 +43,8 @@
| `thread/tokenUsage/updated` | 接收会话 Token 用量更新 |
| `turn/started` | 接收轮次开始通知 |
| `turn/completed` | 接收轮次结束通知 |
-| `item/started` | 接收执行项开始通知 |
-| `item/completed` | 接收执行项结束通知 |
+| `item/started` | 接收执行项开始通知,包括异步提问和用户回应 |
+| `item/completed` | 接收执行项结束通知,包括异步提问和用户回应 |
### 进展通知
@@ -70,24 +68,16 @@
| `model/safetyBuffering/updated` | 接收安全缓冲展示状态 |
| `hook/started` | 感知 hook 执行开始 |
| `hook/completed` | 接收 hook 执行结果 |
-| `serverRequest/resolved` | 感知服务端请求已处理完毕 |
+| `serverRequest/resolved` | 接收审批、提问等服务端请求的结束通知 |
| `error` | 接收错误通知 |
| `warning` | 记录服务端警告 |
-### 服务端请求
+## 服务端请求
| 接口 | 作用 |
| --- | --- |
| `item/commandExecution/requestApproval` | 观察命令执行审批请求 |
| `item/fileChange/requestApproval` | 观察文件修改审批请求 |
| `item/permissions/requestApproval` | 观察权限审批请求 |
+| `item/tool/requestUserInput` | 观察运行期间的提问;`isBlocking` 表示是否阻塞执行 |
| `mcpServer/elicitation/request` | 观察 MCP 交互请求 |
-
-## 使用的根轮次和子 Agent 字段
-
-| 接口 | 字段 | 作用 |
-| --- | --- | --- |
-| `thread/turns/list` | 请求参数 `itemsView` | 使用 `notLoaded` 读取轮次信息,不加载执行项正文 |
-| `thread/turns/list`、`turn/started`、`turn/completed` | `Turn.rootTurnId` | 获取当前轮次所属工作链的根轮次 ID |
-| `thread/items/list`、`item/started`、`item/completed` | `subAgentActivity.model` | 获取 `kind` 为 `started` 时子 Agent 创建所用的实际模型 |
-| `thread/items/list`、`item/started`、`item/completed` | `subAgentActivity.reasoningEffort` | 获取 `kind` 为 `started` 时子 Agent 创建所用的实际推理强度 |
diff --git a/README.en.md b/README.en.md
index 3244f7f..2878414 100644
--- a/README.en.md
+++ b/README.en.md
@@ -35,7 +35,7 @@ CodexBar is a menu bar app for macOS that displays your Codex account informatio
### Follow your tasks in real time
- See each task's project, model, reasoning effort, duration, and token usage
-- Follow live states, actions that need your attention, task progress, and recent events
+- Follow live states, pending responses, task progress, and recent events
- Review concurrent tasks and recent completions, failures, and interruptions in Task Center
### Review your usage
@@ -46,14 +46,14 @@ CodexBar is a menu bar app for macOS that displays your Codex account informatio
### Get timely alerts
-- Receive alerts for task completions, approval requests, allowance changes, and protection events
+- Receive alerts for task completions, pending responses, allowance changes, and protection events
- Choose notification types, sounds, and task haptic feedback
- Follow status changes through customizable task glow at the top of your displays
### Keep long tasks running
- Keep your Mac awake while tasks run, then allow normal sleep when they finish
-- Optionally stay awake while waiting for approval or keep the display on as well
+- Optionally stay awake while awaiting a response or keep the display on as well
- Set a keep-awake time limit, low-battery protection, and stalled task protection
diff --git a/README.md b/README.md
index 62f2722..bd1e417 100644
--- a/README.md
+++ b/README.md
@@ -35,7 +35,7 @@ CodexBar 是 macOS 的菜单栏 App,用于集中展示 Codex 账户、额度
### 随时掌握任务进展
- 查看项目、模型、推理强度、任务耗时和 Token 用量
-- 实时显示执行状态、等待操作、任务进度和最近事件
+- 实时显示执行状态、等待回应、任务进度和最近事件
- 在任务中心集中查看并发任务及最近完成、失败和中断的记录
### 回顾使用情况
@@ -46,14 +46,14 @@ CodexBar 是 macOS 的菜单栏 App,用于集中展示 Codex 账户、额度
### 及时收到提醒
-- 接收任务完成、等待审批、额度变化和保护提醒
+- 接收任务完成、等待回应、额度变化和保护提醒
- 按需选择通知类型、音效和任务触觉反馈
- 通过屏幕顶部的任务流光感知状态变化,支持自定义外观
### 让长任务安心运行
- 任务运行时自动防止 Mac 睡眠,结束后恢复正常睡眠
-- 可在等待审批时继续保持唤醒,或同时保持屏幕常亮
+- 可在等待回应时继续保持唤醒,或同时保持屏幕常亮
- 支持防睡眠时限、低电量保护和异常任务保护