Skip to content
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
import Foundation

/// Extracts the agent's in-progress prose from a snapshot of the terminal's
/// rendered screen, for the live streaming preview.
///
/// The agent CLIs paint their turn with a cursor-addressed TUI and never write
/// token-level deltas to their JSONL transcript, so the only token-grained
/// source of a streaming answer is the emulated screen grid. This extractor is
/// deliberately conservative and **best-effort**: the preview it returns is
/// always superseded by the authoritative JSONL line when the turn settles, so
/// a transient mis-extraction self-corrects within one turn. It returns `nil`
/// whenever it cannot confidently locate an actively-streaming answer, which the
/// caller treats as "show nothing" rather than guess.
///
/// Strategy (the "spinner anchor"): while a turn is in flight the agent renders
/// a working/status line carrying an elapsed timer (`(4s · ↓ 21 tokens)`,
/// `Thinking… (esc to interrupt)`). That line sits directly below the streaming
/// answer and above the input box, so it is a stable local landmark that needs
/// no knowledge of the prompt text or the input-box format. Everything at or
/// below it is chrome; the contiguous text block immediately above it, up to the
/// previous committed block, is the in-progress answer.
public struct AgentChatProseScreenExtractor: Sendable {
/// Hard cap on how many lines above the anchor are considered, so a screen
/// with no committed-block boundary can't fold the whole scrollback into one
/// preview.
private static let maxAnswerLines = 200

public init() {}

/// Extracts the current streaming answer from rendered screen rows.
///
/// - Parameters:
/// - lines: Rendered screen rows, top to bottom (e.g. a render-grid
/// snapshot's plain rows). Trailing whitespace per row is ignored.
/// - agentKind: Selects per-agent boundary markers.
/// - Returns: The cleaned in-progress prose, or `nil` when no actively
/// streaming answer is present.
public func extract(lines: [String], agentKind: ChatAgentKind) -> String? {
let rows = lines.map { Self.trimTrailing($0) }
guard let anchor = Self.statusLineIndex(in: rows) else { return nil }
guard anchor > 0 else { return nil }

let lowerBound = max(0, anchor - Self.maxAnswerLines)
var collected: [String] = []
var index = anchor - 1
while index >= lowerBound {
let row = rows[index]
if Self.isBoundary(row, agentKind: agentKind) { break }
collected.append(row)
index -= 1
}
collected.reverse()

// Strip a leading committed-block bullet if the answer just committed
// on screen (e.g. Claude prefixes a finalized block with "⏺ ").
if let first = collected.first {
collected[0] = Self.strippingLeadingBullet(first, agentKind: agentKind)
}

let cleaned = Self.collapsingBlankRuns(collected)
.joined(separator: "\n")
.trimmingCharacters(in: .whitespacesAndNewlines)
return cleaned.isEmpty ? nil : cleaned
}

// MARK: - Anchoring

/// The highest-indexed row that looks like the agent's working/status line
/// (an elapsed-time timer, or an explicit interrupt hint). Scanning from the
/// bottom skips the input box and footer, which always sit below it.
static func statusLineIndex(in rows: [String]) -> Int? {
for index in stride(from: rows.count - 1, through: 0, by: -1) {
if isStatusLine(rows[index]) { return index }
}
return nil
}

/// Whether a row is the agent's working/status line. Matched on stable
/// signals rather than the (randomized, localized) gerund or spinner glyph:
/// an `(<n>s` elapsed timer, or an explicit "esc to interrupt" hint.
static func isStatusLine(_ row: String) -> Bool {
let trimmed = row.trimmingCharacters(in: .whitespaces)
guard !trimmed.isEmpty else { return false }
let lower = trimmed.lowercased()
if lower.contains("esc to interrupt") || lower.contains("esc to cancel") {
return true
}
// An elapsed timer like "(4s", "(12s ", "(1m05s" rendered on the status
// line. Require a leading spinner glyph or the token/throughput markers
// Claude shows alongside it, so a parenthesized "(3s ...)" inside prose
// is not mistaken for the anchor.
guard trimmed.contains(where: { Self.spinnerGlyphs.contains($0) })
|| lower.contains("token")
|| trimmed.contains("↓") || trimmed.contains("↑")
else { return false }
return Self.containsElapsedTimer(trimmed)
}

/// Whether the row contains an elapsed-time token of the form `(<digits>s`
/// or `(<digits>m<digits>s`, e.g. `(4s`, `(12s`, `(1m05s`. Hand-scanned to
/// avoid a regex literal, whose `/.../ ` parse is ambiguous next to division.
static func containsElapsedTimer(_ text: String) -> Bool {
let chars = Array(text)
var index = 0
while index < chars.count {
guard chars[index] == "(" else { index += 1; continue }
var cursor = index + 1
var sawDigits = false
// digits
while cursor < chars.count, chars[cursor].isNumber { cursor += 1; sawDigits = true }
// optional minutes group: m<digits>
if sawDigits, cursor < chars.count, chars[cursor] == "m" {
cursor += 1
while cursor < chars.count, chars[cursor].isNumber { cursor += 1 }
}
if sawDigits, cursor < chars.count, chars[cursor] == "s" {
return true
}
index += 1
}
return false
}

/// Glyphs Claude/Codex cycle through for the working spinner.
private static let spinnerGlyphs: Set<Character> = [
"✢", "✶", "✻", "✽", "✳", "·", "∗", "⟢", "✦", "✧", "◐", "◓", "◑", "◒",
]

// MARK: - Boundaries

/// Whether a row marks the top boundary of the current answer: a previous
/// committed block (tool call / earlier answer) or a user-prompt line. The
/// streaming answer is the uncommitted text between the boundary and the
/// status line.
static func isBoundary(_ row: String, agentKind: ChatAgentKind) -> Bool {
guard let first = row.trimmingCharacters(in: .whitespaces).first else {
return false
}
return boundaryLeadingGlyphs(for: agentKind).contains(first)
}

/// Leading glyphs that begin a committed block or prompt line for an agent.
static func boundaryLeadingGlyphs(for agentKind: ChatAgentKind) -> Set<Character> {
switch agentKind {
case .claude, .other:
// ⏺ committed block bullet, ● tool bullet, ⎿ tool-result continuation,
// > user prompt echo, │ prompt-box border.
return ["⏺", "●", "⎿", ">", "│"]
case .codex:
// Codex marks user turns with "user" headers and tool calls with
// bullets; ">" / box borders are the reliable cross-version anchors.
return ["•", "›", ">", "│", "⎿"]
}
}

/// Removes a leading committed-block bullet ("⏺ ", "● ", "• ") from a row.
static func strippingLeadingBullet(_ row: String, agentKind: ChatAgentKind) -> String {
var working = row
let leading = Set<Character>(["⏺", "●", "•", "›"])
if let first = working.first, leading.contains(first) {
working.removeFirst()
if working.first == " " { working.removeFirst() }
}
return working
}

// MARK: - Cleanup

private static func trimTrailing(_ row: String) -> String {
var scalars = Array(row.unicodeScalars)
while let last = scalars.last, last == " " || last == "\t" {
scalars.removeLast()
}
return String(String.UnicodeScalarView(scalars))
}

/// Trims leading/trailing blank rows and collapses runs of 2+ blank rows to
/// a single blank, so paragraph spacing survives but TUI padding does not.
static func collapsingBlankRuns(_ rows: [String]) -> [String] {
var out: [String] = []
var previousBlank = false
for row in rows {
let isBlank = row.trimmingCharacters(in: .whitespaces).isEmpty
if isBlank {
if previousBlank { continue }
previousBlank = true
} else {
previousBlank = false
}
out.append(row)
}
while out.first?.trimmingCharacters(in: .whitespaces).isEmpty == true { out.removeFirst() }
while out.last?.trimmingCharacters(in: .whitespaces).isEmpty == true { out.removeLast() }
return out
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,10 @@ public actor FixtureChatEventSource: ChatEventSource {
case .reset:
backlog = []
terminalBacklog = []
case .streamingProse:
// A live preview is transient and not part of history; forward it to
// subscribers but never fold it into the backlog.
break
case .unknown:
break
case .stateChanged, .descriptorChanged:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ public final class ChatConversationStore {

@ObservationIgnored private var messages: [ChatMessage] = []
@ObservationIgnored private var pending: [ChatPendingOutbound] = []
/// Live, not-yet-committed preview of the agent's in-progress prose for the
/// current turn, scraped from the rendered terminal screen. Held outside
/// ``messages`` (so it never collides with window dedup/paging/seq) and
/// rendered as a trailing agent bubble. Cleared the instant the authoritative
/// agent prose lands via ``ChatSessionEvent/appended`` or an explicit
/// ``ChatSessionEvent/streamingProse`` `nil`, so it never duplicates a real
/// message.
@ObservationIgnored private var streamingMessage: ChatMessage?
@ObservationIgnored private var firstUnreadSeq: Int?
/// Terminal command-blocks for a `.terminal`-kind session, upserted by
/// id; `terminalBlockOrder` preserves arrival order. Unused (and the
Expand Down Expand Up @@ -458,6 +466,13 @@ public final class ChatConversationStore {
switch event {
case .appended(let newMessages):
reconcilePending(against: newMessages)
// The authoritative agent prose for the in-flight turn just landed:
// drop the live preview so the committed message takes over with no
// duplicate, even if the host's explicit clear is delayed or lost.
if streamingMessage != nil,
newMessages.contains(where: { $0.role == .agent && Self.isProse($0) }) {
streamingMessage = nil
}
// A live append whose seq regresses below the window tail means
// the transcript was truncated/replaced and the tailer reset;
// appending would corrupt window ordering. Re-anchor instead.
Expand Down Expand Up @@ -499,6 +514,14 @@ public final class ChatConversationStore {
// optimistic pending row it came from so it doesn't linger or leak.
reconcileTerminalPending(against: blocks)
reproject()
case .streamingProse(let message):
// The preview is a whole-value replace; an agent session only. A
// terminal session has no agent prose, so ignore it there.
guard descriptor.kind != .terminal else { break }
let next = message.flatMap { Self.isProse($0) ? $0 : nil }
guard next != streamingMessage else { break }
streamingMessage = next
Comment on lines +517 to +523

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Fail closed on malformed .streamingProse payloads.

Line 521 only checks message kind (.prose) and will accept non-agent prose. Restrict this path to .agent prose so invalid frames are ignored instead of rendered.

As per path instructions, “Correctness-critical state must come from a single authoritative source … fail closed (disable/empty state) rather than guessing.”

🔧 Suggested fix
-            let next = message.flatMap { Self.isProse($0) ? $0 : nil }
+            let next = message.flatMap { ($0.role == .agent && Self.isProse($0)) ? $0 : nil }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Store/ChatConversationStore.swift`
around lines 517 - 523, In the `.streamingProse` case within
ChatConversationStore, the message validation on line 521 only checks if the
message is prose using `Self.isProse($0)` but does not verify it is specifically
`.agent` prose. Modify the flatMap condition in the `let next = message.flatMap
{ ... }` line to additionally validate that the message kind is `.agent` in
addition to passing the isProse check, so that only valid agent prose is
accepted and malformed non-agent frames are ignored.

Source: Path instructions

reproject()
case .reset:
// The transcript was truncated/replaced on the Mac (tailer
// re-read from scratch). The window's seq space is void; clear
Expand All @@ -507,6 +530,8 @@ public final class ChatConversationStore {
// their retry and in-flight sends may still land in the new
// transcript and reconcile normally.
messages = []
// The preview belongs to the old seq space; drop it on re-anchor.
streamingMessage = nil
// Terminal blocks must clear here too: the terminal reproject()
// does not consult `messages`, so without this the synchronous
// reproject below would re-render stale blocks (and they'd persist
Expand Down Expand Up @@ -713,10 +738,27 @@ public final class ChatConversationStore {
+ pending.map(ChatTranscriptRow.pendingOutbound)
return
}
// The live preview renders as a trailing agent bubble after the
// committed window. Appending it to the projector input lets it group
// with adjacent agent prose exactly like a real message; it carries no
// window identity (never paged, deduped, or reconciled by id).
let projected: [ChatMessage]
if let streamingMessage, !messages.contains(where: { $0.id == streamingMessage.id }) {
projected = messages + [streamingMessage]
} else {
projected = messages
}
rows = projector.rows(
messages: messages,
messages: projected,
pending: pending,
firstUnreadSeq: firstUnreadSeq
)
}

/// Whether a message is renderable agent/user prose (used to settle the
/// live preview against the authoritative transcript line).
private static func isProse(_ message: ChatMessage) -> Bool {
if case .prose = message.kind { return true }
return false
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public struct ChatSessionListReducer: Sendable {
var updated = sessions
updated[index] = updated[index].withState(state)
return updated
case .appended, .updated, .terminalBlocks, .reset, .unknown:
case .appended, .updated, .terminalBlocks, .streamingProse, .reset, .unknown:
// Transcript-content frames don't affect the session list.
return sessions
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ public enum ChatSessionEvent: Sendable, Equatable {
/// reconnect is idempotent.
case terminalBlocks([TerminalCommandBlock])

/// A live, not-yet-committed preview of the agent's in-progress prose for
/// the current turn, scraped from the terminal's rendered screen while the
/// authoritative JSONL line has not been written yet. The payload replaces
/// any prior preview wholesale; `nil` clears it. It lives outside the
/// message window and is superseded the instant the authoritative agent
/// prose lands via ``appended``, so it never duplicates a real message.
case streamingProse(ChatMessage?)

/// The producing transcript was truncated or replaced; the session's
/// seq space restarted and clients must re-anchor from history.
case reset
Expand All @@ -30,6 +38,7 @@ extension ChatSessionEvent: Codable {
private enum CodingKeys: String, CodingKey {
case event
case messages
case message
case state
case descriptor
case blocks
Expand All @@ -41,6 +50,7 @@ extension ChatSessionEvent: Codable {
case stateChanged = "state_changed"
case descriptorChanged = "descriptor_changed"
case terminalBlocks = "terminal_blocks"
case streamingProse = "streaming_prose"
case reset
}

Expand All @@ -58,6 +68,8 @@ extension ChatSessionEvent: Codable {
self = .descriptorChanged(try container.decode(ChatSessionDescriptor.self, forKey: .descriptor))
case .terminalBlocks:
self = .terminalBlocks(try container.decode([TerminalCommandBlock].self, forKey: .blocks))
case .streamingProse:
self = .streamingProse(try container.decodeIfPresent(ChatMessage.self, forKey: .message))
case .reset:
self = .reset
case .none:
Expand Down Expand Up @@ -86,6 +98,9 @@ extension ChatSessionEvent: Codable {
case .terminalBlocks(let blocks):
try container.encode(EventName.terminalBlocks.rawValue, forKey: .event)
try container.encode(blocks, forKey: .blocks)
case .streamingProse(let message):
try container.encode(EventName.streamingProse.rawValue, forKey: .event)
try container.encodeIfPresent(message, forKey: .message)
case .reset:
try container.encode(EventName.reset.rawValue, forKey: .event)
case .unknown(let raw):
Expand Down
Loading
Loading