1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Delta renderer trait definition.
//
// Contains the DeltaRenderer trait and compute_append_only_suffix helper.
//
// # CCS Spam Prevention Architecture
//
// This module implements a three-layer approach to prevent repeated prefixed lines
// for streaming deltas in non-TTY modes (logs, CI output):
use Write;
//
// ## Layer 1: Suppression at Renderer Level
//
// Delta renderers (`TextDeltaRenderer`, `ThinkingDeltaRenderer`) return empty strings
// in `TerminalMode::Basic` and `TerminalMode::None` for both `render_first_delta` and
// `render_subsequent_delta`. This prevents per-delta spam at the source.
//
// ## Layer 2: Accumulation in StreamingSession
//
// `StreamingSession` (in `streaming_state/session`) accumulates all content by
// (ContentType, index) across deltas. This state is preserved across all delta
// events for a single message.
//
// ## Layer 3: Flush at Completion Boundaries
//
// Parser layer (ClaudeParser, CodexParser) flushes accumulated content ONCE at
// completion boundaries:
// - ClaudeParser: `handle_message_stop` (in `claude/delta_handling.rs`)
// - CodexParser: `item.completed` handlers (in `codex/event_handlers/*.rs`)
//
// This ensures:
// - **Full mode (TTY)**: Real-time append-only streaming (no cursor movement)
// - **Basic/None modes**: One prefixed line per content block, regardless of delta count
//
// ## Validation
//
// Regression tests validate this architecture:
// - `ccs_delta_spam_systematic_reproduction.rs`: systematic reproduction (all delta types, both parsers, both modes)
// - `ccs_all_delta_types_spam_reproduction.rs`: 1000+ deltas per block
// - `ccs_streaming_spam_all_deltas.rs`: all delta types (text/thinking/tool)
// - `ccs_nuclear_full_log_regression.rs`: large captured logs (thousands of deltas)
// - `ccs_streaming_edge_cases.rs`: edge cases (empty deltas, rapid transitions)
// - `ccs_wrapping_waterfall_reproduction.rs`: wrapping/cursor-up failure reproduction
// - `ccs_ansi_stripping_console.rs`: ANSI-stripping console behavior
// - `codex_reasoning_spam_regression.rs`: Codex reasoning regression
/// Renderer for streaming delta content.
///
/// This trait defines the contract for rendering streaming deltas consistently
/// across all parsers using the append-only pattern.
///
/// # Append-Only Pattern (Full Mode)
///
/// The renderer supports true append-only streaming that works correctly under
/// terminal line wrapping and in ANSI-stripping environments:
///
/// 1. **First delta**: Shows prefix with accumulated content, NO newline
/// - Example: `[ccs/glm] Hello`
/// - No cursor movement, content stays on current line
///
/// 2. **Subsequent deltas**: Parser computes and emits ONLY new suffix
/// - Parser responsibility: track last rendered content and emit only delta
/// - Example: parser emits ` World` (just the new text with color codes)
/// - NO prefix rewrite, NO `\r` (carriage return), NO cursor movement
/// - Renderers provide `render_subsequent_delta` for backward compatibility
/// but parsers implementing append-only should bypass it
///
/// 3. **Completion**: Single newline to finalize the line
/// - Example: `\n`
/// - Moves cursor to next line after streaming completes
///
/// This pattern works correctly even when content wraps to multiple terminal rows
/// because there is NO cursor movement. The terminal naturally handles wrapping,
/// and content appears to grow incrementally on the same logical line.
///
/// # Why Append-Only?
///
/// Previous patterns using `\r` (carriage return) or `\n\x1b[1A` (newline + cursor up)
/// fail in two scenarios:
///
/// 1. **Line wrapping**: When content exceeds terminal width and wraps to multiple rows,
/// `\r` only returns to column 0 of current row (not start of logical line), and
/// `\x1b[1A` (cursor up 1 row) + `\x1b[2K` (clear 1 row) cannot erase all wrapped rows
/// 2. **ANSI-stripping consoles**: Many CI/log environments strip or ignore ANSI sequences,
/// so `\n` becomes a literal newline causing waterfall spam
///
/// Append-only streaming eliminates both issues by never using cursor movement.
///
/// # Non-TTY Modes (Basic/None)
///
/// Per-delta output is suppressed. Content is flushed ONCE at completion boundaries
/// by the parser layer to prevent spam in logs and CI output.
///
/// # Rendering Rules
///
/// - `render_first_delta()`: Called for the first delta of a content block
/// - Must include prefix
/// - Must NOT include newline (stays on current line for append-only)
/// - Shows the accumulated content so far
///
/// - `render_subsequent_delta()`: Called for subsequent deltas
/// - **Parsers implementing append-only MUST compute the suffix and bypass this method**
/// - Renderer implementations in this repo intentionally return empty strings in all modes
/// to avoid reintroducing cursor/CR patterns.
///
/// - `render_completion()`: Called when streaming completes
/// - Returns single newline (`\n`) in Full mode to finalize the line
/// - Returns empty string in Basic/None mode (parser already flushed with newline)
///
/// # Terminal Mode Awareness
///
/// The renderer automatically adapts output based on terminal capability:
/// - **Full mode**: Append-only streaming (no cursor movement during deltas)
/// - **Basic mode**: Per-delta output suppressed; parser flushes once at completion
/// - **None mode**: Per-delta output suppressed; parser flushes once at completion, plain text
///
/// # Example
///
/// ```ignore
/// use crate::json_parser::delta_display::DeltaRenderer;
/// use crate::logger::Colors;
/// use crate::json_parser::TerminalMode;
///
/// let colors = Colors { enabled: true };
/// let terminal_mode = TerminalMode::detect();
///
/// // First chunk
/// let output = DeltaRenderer::render_first_delta(
/// "Hello",
/// "ccs-glm",
/// colors,
/// terminal_mode
/// );
///
/// // Second chunk
/// let output = DeltaRenderer::render_subsequent_delta(
/// "Hello World",
/// "ccs-glm",
/// colors,
/// terminal_mode
/// );
///
/// // Complete
/// let output = DeltaRenderer::render_completion(terminal_mode);
/// ```
/// Compute the append-only suffix to emit for a snapshot-style accumulated string.
///
/// Providers differ in what they send as a "delta": some stream true incremental suffixes,
/// others send the full accumulated content repeatedly (snapshot-style). Our append-only
/// rendering contract treats the parser's sanitized accumulated content as the source of truth.
///
/// Given the last rendered sanitized content and the current sanitized content, return
/// the string that should be appended to the terminal to advance the visible output.
///
/// Rules:
/// - If `last_rendered` is empty, emit `current` (first delta).
/// - If `current` starts with `last_rendered`, emit the new suffix only.
/// - Otherwise, treat as a discontinuity/reset and emit an empty suffix.
///
/// ## Why discontinuities emit nothing
///
/// In an append-only renderer, emitting `current` on a discontinuity would append an entire
/// replacement snapshot onto already-rendered output, producing duplicated/corrupted display.
/// Callers that need to surface a reset must do so explicitly (e.g., finalize the current line
/// and start a new one).
///
/// ## Discontinuity Detection
///
/// A discontinuity occurs when `current` does not start with `last_rendered` (i.e.,
/// `current.strip_prefix(last_rendered)` returns `None`). This indicates:
/// - Non-monotonic deltas from the provider (e.g., "Hello World" followed by "Hello Universe")
/// - Protocol violations where content changes unexpectedly
/// - Content resets that should be handled explicitly by the caller
///
/// When a discontinuity is detected, this function returns an empty string. Callers should
/// detect this condition (when both `last_rendered` and `current` are non-empty but the
/// result is empty) and emit appropriate warnings or metrics to track provider behavior.