| 1 | use std::collections::VecDeque; |
| 2 | use std::time::{Duration, Instant}; |
| 3 | |
| 4 | use unicode_width::UnicodeWidthStr; |
| 5 | |
| 6 | pub(crate) const THINKING_STREAMING_PREVIEW_LINE_LIMIT: usize = 3; |
| 7 | |
| 8 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 9 | pub(crate) struct Checkpoints { |
| 10 | pub excerpts: [Option<(usize, usize)>; 2], |
| 11 | pub tail: usize, |
| 12 | pub emphasis: u8, |
| 13 | } |
| 14 | |
| 15 | #[derive(Default, Debug)] |
| 16 | pub(crate) struct ThinkingReadWindow { |
| 17 | recent_rows: VecDeque<Instant>, |
| 18 | column: usize, |
| 19 | unread_rows: usize, |
| 20 | fast: bool, |
| 21 | line_start: usize, |
| 22 | processed: usize, |
| 23 | paragraph: Option<(usize, usize)>, |
| 24 | completed: bool, |
| 25 | fence: Option<(u8, usize)>, |
| 26 | checkpoints: Checkpoints, |
| 27 | settling_since: Option<Instant>, |
| 28 | } |
| 29 | |
| 30 | impl ThinkingReadWindow { |
| 31 | pub fn skip_to(&mut self, offset: usize) { |
| 32 | *self = Self { |
| 33 | line_start: offset, |
| 34 | processed: offset, |
| 35 | ..Self::default() |
| 36 | }; |
| 37 | } |
| 38 | |
| 39 | pub fn projection(&self) -> Checkpoints { |
| 40 | if self.fast { |
| 41 | self.checkpoints |
| 42 | } else { |
| 43 | Checkpoints::default() |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | pub fn start_settling(&mut self, now: Instant) { |
| 48 | self.checkpoints.emphasis = 2; |
| 49 | self.settling_since = Some(now); |
| 50 | } |
| 51 | |
| 52 | pub fn is_settling(&self) -> bool { |
| 53 | self.settling_since.is_some() |
| 54 | } |
| 55 | |
| 56 | pub fn advance_settling(&mut self, now: Instant) -> bool { |
| 57 | let Some(since) = self.settling_since else { |
| 58 | return false; |
| 59 | }; |
| 60 | let elapsed = now.saturating_duration_since(since).as_millis(); |
| 61 | let next = match elapsed { |
| 62 | 0..100 => 2, |
| 63 | 100..200 => 1, |
| 64 | _ => 0, |
| 65 | }; |
| 66 | if next == 0 { |
| 67 | self.settling_since = None; |
| 68 | } |
| 69 | let previous = std::mem::replace(&mut self.checkpoints.emphasis, next); |
| 70 | previous != next |
| 71 | } |
| 72 | |
| 73 | pub fn append( |
| 74 | &mut self, |
| 75 | source: &str, |
| 76 | start: usize, |
| 77 | now: Instant, |
| 78 | width: usize, |
| 79 | height: usize, |
| 80 | following: bool, |
| 81 | ) { |
| 82 | if start != self.processed { |
| 83 | self.skip_to(start); |
| 84 | } |
| 85 | self.processed = source.len(); |
| 86 | let added = &source[start..]; |
| 87 | let width = width.max(1); |
| 88 | if !self.fast { |
| 89 | let mut added_rows = 0; |
| 90 | for piece in added.split_inclusive('\n') { |
| 91 | let line = piece.trim_end_matches('\n'); |
| 92 | self.column += UnicodeWidthStr::width(line); |
| 93 | let wrapped = self.column.saturating_sub(1) / width; |
| 94 | self.column -= wrapped * width; |
| 95 | let ended = piece.ends_with('\n'); |
| 96 | added_rows += wrapped + usize::from(ended); |
| 97 | if ended { |
| 98 | self.column = 0; |
| 99 | } |
| 100 | } |
| 101 | self.unread_rows = if following { |
| 102 | 0 |
| 103 | } else { |
| 104 | self.unread_rows + added_rows |
| 105 | }; |
| 106 | while self |
| 107 | .recent_rows |
| 108 | .front() |
| 109 | .is_some_and(|&then| now.saturating_duration_since(then) >= Duration::from_secs(2)) |
| 110 | { |
| 111 | self.recent_rows.pop_front(); |
| 112 | } |
| 113 | let preview_rows = height.clamp(1, THINKING_STREAMING_PREVIEW_LINE_LIMIT); |
| 114 | self.fast = self.recent_rows.len() + added_rows >= 3 * preview_rows |
| 115 | || self.unread_rows >= height.max(THINKING_STREAMING_PREVIEW_LINE_LIMIT); |
| 116 | if !self.fast { |
| 117 | self.recent_rows |
| 118 | .extend(std::iter::repeat_n(now, added_rows)); |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | for (offset, _) in added.match_indices('\n') { |
| 123 | let end = start + offset; |
| 124 | let line_start = self.line_start; |
| 125 | self.line_start = end + 1; |
| 126 | let line = &source[line_start..end]; |
| 127 | let trimmed = line.trim(); |
| 128 | if trimmed.is_empty() { |
| 129 | if self.fence.is_none() { |
| 130 | self.completed = true; |
| 131 | } |
| 132 | continue; |
| 133 | } |
| 134 | let fence = trimmed.as_bytes()[0]; |
| 135 | let run = trimmed.bytes().take_while(|&c| c == fence).count(); |
| 136 | if let Some((marker, size)) = self.fence { |
| 137 | if fence == marker && run >= size && trimmed[run..].trim().is_empty() { |
| 138 | self.fence = None; |
| 139 | } |
| 140 | continue; |
| 141 | } |
| 142 | let heading = trimmed.trim_start_matches('#'); |
| 143 | let is_heading = heading.len() != trimmed.len() && heading.starts_with(' '); |
| 144 | if self.completed || is_heading { |
| 145 | self.settle(line_start); |
| 146 | } |
| 147 | if matches!(fence, b'`' | b'~') && run >= 3 { |
| 148 | self.fence = Some((fence, run)); |
| 149 | continue; |
| 150 | } |
| 151 | if self.paragraph.is_none() && !line.starts_with(" ") && !trimmed.starts_with('|') { |
| 152 | let title = if is_heading { heading.trim() } else { trimmed }; |
| 153 | let title = title |
| 154 | .strip_prefix("**") |
| 155 | .and_then(|s| s.strip_suffix("**")) |
| 156 | .unwrap_or(title); |
| 157 | let excerpt = first_sentence(title); |
| 158 | let excerpt_limit = if excerpt.ends_with(['.', '!', '?', '。', '!', '?']) { |
| 159 | width.saturating_mul(THINKING_STREAMING_PREVIEW_LINE_LIMIT) |
| 160 | } else { |
| 161 | width |
| 162 | }; |
| 163 | if (is_heading || excerpt.width() <= excerpt_limit) |
| 164 | && excerpt.chars().any(char::is_alphanumeric) |
| 165 | { |
| 166 | let from = |
| 167 | line_start + line.find(excerpt).expect("excerpt comes from this line"); |
| 168 | self.paragraph = Some((from, from + excerpt.len())); |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | if self.completed && !source[self.line_start..].trim().is_empty() { |
| 173 | self.settle(self.line_start); |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | fn settle(&mut self, tail: usize) { |
| 178 | if let Some(excerpt) = self.paragraph.take() { |
| 179 | self.checkpoints.excerpts.rotate_left(1); |
| 180 | self.checkpoints.excerpts[1] = Some(excerpt); |
| 181 | self.checkpoints.tail = tail; |
| 182 | } |
| 183 | self.completed = false; |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | fn first_sentence(line: &str) -> &str { |
| 188 | for (idx, ch) in line.char_indices() { |
| 189 | let end = idx + ch.len_utf8(); |
| 190 | if matches!(ch, '。' | '!' | '?') |
| 191 | || (matches!(ch, '.' | '!' | '?') && line[end..].starts_with(char::is_whitespace)) |
| 192 | { |
| 193 | return &line[..end]; |
| 194 | } |
| 195 | } |
| 196 | line |
| 197 | } |
| 198 | |
| 199 | #[cfg(test)] |
| 200 | mod tests { |
| 201 | use super::*; |
| 202 | |
| 203 | #[test] |
| 204 | fn a_fast_window_folds_completed_passages_at_the_next_live_passage() { |
| 205 | let now = Instant::now(); |
| 206 | let mut window = ThinkingReadWindow::default(); |
| 207 | let mut text = String::new(); |
| 208 | let mut append = |piece: &str, when, window: &mut ThinkingReadWindow| { |
| 209 | let start = text.len(); |
| 210 | text.push_str(piece); |
| 211 | window.append(&text, start, when, 40, 8, true); |
| 212 | }; |
| 213 | append("Inspect the config. Keep defaults.\n\n", now, &mut window); |
| 214 | assert_eq!(window.projection(), Checkpoints::default()); |
| 215 | let middle = format!( |
| 216 | "Found the stale path. Use the workspace root.\n{}\n\n", |
| 217 | "tracked line\n".repeat(20) |
| 218 | ); |
| 219 | append(&middle, now + Duration::from_millis(80), &mut window); |
| 220 | append( |
| 221 | "Checking the fallback", |
| 222 | now + Duration::from_millis(96), |
| 223 | &mut window, |
| 224 | ); |
| 225 | let projection = window.projection(); |
| 226 | assert_eq!( |
| 227 | projection |
| 228 | .excerpts |
| 229 | .map(|range| range.map(|(a, b)| &text[a..b])), |
| 230 | [Some("Inspect the config."), Some("Found the stale path.")] |
| 231 | ); |
| 232 | assert_eq!(&text[projection.tail..], "Checking the fallback"); |
| 233 | } |
| 234 | |
| 235 | #[test] |
| 236 | fn slow_passages_stay_direct_and_unread_output_accumulates() { |
| 237 | let now = Instant::now(); |
| 238 | for following in [true, false] { |
| 239 | let mut window = ThinkingReadWindow::default(); |
| 240 | let mut text = String::new(); |
| 241 | for i in 0..12 { |
| 242 | let start = text.len(); |
| 243 | text.push_str(&format!("Reading src/path.rs. Step {i}.\n\n")); |
| 244 | window.append( |
| 245 | &text, |
| 246 | start, |
| 247 | now + Duration::from_secs(i * 3), |
| 248 | 80, |
| 249 | 8, |
| 250 | following, |
| 251 | ); |
| 252 | } |
| 253 | assert_eq!(window.projection().excerpts[1].is_some(), !following); |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | #[test] |
| 258 | fn pace_depends_on_the_preview_and_arrival_rate_across_chunk_sizes() { |
| 259 | let mut source = String::from("The first note contains its title.\n\n"); |
| 260 | for i in 0..72 { |
| 261 | source.push_str(&format!( |
| 262 | "Entry {i:02} from the saved workspace notes is present.\n" |
| 263 | )); |
| 264 | } |
| 265 | source.push_str( |
| 266 | "\nThe second note has its original heading. The draft matches.\n\nChecking the rest.", |
| 267 | ); |
| 268 | for (width, rate, folded) in [ |
| 269 | (96, 120, false), |
| 270 | (96, 400, true), |
| 271 | (96, 1400, true), |
| 272 | (36, 120, true), |
| 273 | ] { |
| 274 | for chunk in [13, 53, 137] { |
| 275 | let now = Instant::now(); |
| 276 | let mut window = ThinkingReadWindow::default(); |
| 277 | for start in (0..source.len()).step_by(chunk) { |
| 278 | let end = (start + chunk).min(source.len()); |
| 279 | let elapsed = Duration::from_secs_f64(end as f64 / f64::from(rate)); |
| 280 | window.append(&source[..end], start, now + elapsed, width, 26, true); |
| 281 | } |
| 282 | let checkpoint = window.projection().excerpts[1].map(|(a, b)| &source[a..b]); |
| 283 | assert_eq!( |
| 284 | checkpoint, |
| 285 | folded.then_some("The second note has its original heading."), |
| 286 | "width={width}, rate={rate}, chunk={chunk}" |
| 287 | ); |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | #[test] |
| 293 | fn a_dense_unsectioned_line_does_not_become_a_checkpoint() { |
| 294 | let mut window = ThinkingReadWindow::default(); |
| 295 | let now = Instant::now(); |
| 296 | let mut text = format!("{}. More detail.\n\nNext passage", "dense".repeat(200)); |
| 297 | window.append(&text, 0, now, 40, 20, true); |
| 298 | assert_eq!(window.projection(), Checkpoints::default()); |
| 299 | |
| 300 | let start = text.len(); |
| 301 | text.push_str(" has a short first sentence. Details follow.\n\nStill reading."); |
| 302 | window.append(&text, start, now, 40, 20, true); |
| 303 | let checkpoint = window.projection(); |
| 304 | assert_eq!( |
| 305 | checkpoint |
| 306 | .excerpts |
| 307 | .map(|range| range.map(|(a, b)| &text[a..b])), |
| 308 | [None, Some("Next passage has a short first sentence.")] |
| 309 | ); |
| 310 | assert_eq!(&text[checkpoint.tail..], "Still reading."); |
| 311 | } |
| 312 | |
| 313 | #[test] |
| 314 | fn emphasis_settles_in_two_beats_and_stops() { |
| 315 | let now = Instant::now(); |
| 316 | let mut window = ThinkingReadWindow::default(); |
| 317 | window.start_settling(now); |
| 318 | assert!(window.is_settling()); |
| 319 | assert!(!window.advance_settling(now + Duration::from_millis(80))); |
| 320 | assert!(window.advance_settling(now + Duration::from_millis(110))); |
| 321 | assert_eq!(window.checkpoints.emphasis, 1); |
| 322 | assert!(window.advance_settling(now + Duration::from_millis(215))); |
| 323 | assert_eq!(window.checkpoints.emphasis, 0); |
| 324 | assert!(!window.is_settling()); |
| 325 | } |
| 326 | |
| 327 | #[test] |
| 328 | fn fenced_examples_never_become_headlines_across_chunk_boundaries() { |
| 329 | let text = format!( |
| 330 | "## Résultat\n\n{}\n\nComparing paths.\n\nNext", |
| 331 | "```\n\n# bogus\n\n```\n".repeat(10) |
| 332 | ); |
| 333 | let mut window = ThinkingReadWindow::default(); |
| 334 | let now = Instant::now(); |
| 335 | for (start, ch) in text.char_indices() { |
| 336 | window.append(&text[..start + ch.len_utf8()], start, now, 40, 8, true); |
| 337 | } |
| 338 | let projection = window.projection(); |
| 339 | assert_eq!( |
| 340 | projection |
| 341 | .excerpts |
| 342 | .map(|range| range.map(|(a, b)| &text[a..b])), |
| 343 | [Some("Résultat"), Some("Comparing paths.")] |
| 344 | ); |
| 345 | assert_eq!(&text[projection.tail..], "Next"); |
| 346 | } |
| 347 | } |
| 348 |