1const EARLY_FLUSH_CHARS: usize = 120;
8
9#[derive(Debug, Default, PartialEq, Eq)]
12pub struct Chunk {
13 pub text: String,
14 pub append: bool,
15}
16
17#[derive(Default)]
19pub struct StreamBuf {
20 kind: &'static str,
22 text: String,
23 open: bool,
26}
27
28impl StreamBuf {
29 fn decorate(kind: &str, line: &str, continuation: bool) -> String {
32 if kind == "think" && !continuation {
33 format!("⋯ {line}")
34 } else {
35 line.to_string()
36 }
37 }
38
39 fn early_flush_split(text: &str, limit: usize) -> usize {
43 let cut = text
44 .char_indices()
45 .nth(limit)
46 .map_or(text.len(), |(i, _)| i);
47 let head = &text[..cut];
48 head.char_indices()
49 .rev()
50 .find(|(_, ch)| ch.is_whitespace())
51 .map(|(i, ch)| i + ch.len_utf8())
52 .filter(|end| *end >= cut.saturating_sub(24))
53 .unwrap_or(cut)
54 }
55
56 pub fn push(&mut self, kind: &'static str, text: &str) -> String {
58 self.push_chunk(kind, text).text
59 }
60
61 pub fn push_chunk(&mut self, kind: &'static str, text: &str) -> Chunk {
63 let append = self.open;
64 let mut out = String::new();
65 if self.kind != kind {
66 out.push_str(&self.take().text);
67 self.kind = kind;
68 }
69 let mut cont = self.open;
72 self.text.push_str(text);
73 while let Some(idx) = self.text.find('\n') {
74 let line: String = self.text.drain(..=idx).collect();
75 out.push_str(&Self::decorate(kind, &line, cont));
76 cont = false;
77 self.open = false;
78 }
79 if kind == "think" && self.text.chars().count() >= EARLY_FLUSH_CHARS {
82 let split = Self::early_flush_split(&self.text, EARLY_FLUSH_CHARS);
83 let line: String = self.text.drain(..split).collect();
84 out.push_str(&Self::decorate(kind, line.trim_end(), cont));
85 out.push('\n');
86 self.open = false;
87 }
88 Chunk {
89 append: append && !out.is_empty(),
90 text: out,
91 }
92 }
93
94 pub fn flush(&mut self) -> String {
96 self.take().text
97 }
98
99 pub fn flush_chunk(&mut self) -> Chunk {
101 self.take()
102 }
103
104 pub fn idle_flush_chunk(&mut self) -> Chunk {
107 if self.text.is_empty() {
108 return Chunk::default();
109 }
110 let line = std::mem::take(&mut self.text);
111 let append = self.open;
112 self.open = true;
113 Chunk {
114 text: Self::decorate(self.kind, &line, append),
115 append,
116 }
117 }
118
119 fn take(&mut self) -> Chunk {
120 let append = std::mem::take(&mut self.open);
121 if self.text.is_empty() {
122 return if append {
124 Chunk {
125 text: "\n".to_string(),
126 append: true,
127 }
128 } else {
129 Chunk::default()
130 };
131 }
132 let line = std::mem::take(&mut self.text);
133 let mut s = Self::decorate(self.kind, &line, append);
134 s.push('\n');
135 Chunk { text: s, append }
136 }
137}
138
139#[cfg(test)]
140mod tests {
141 use super::{Chunk, StreamBuf};
142
143 #[test]
144 fn coalesces_token_chunks_into_lines() {
145 let mut b = StreamBuf::default();
146 assert_eq!(b.push("msg", "Hel"), "");
147 assert_eq!(b.push("msg", "lo"), "");
148 assert_eq!(b.push("msg", " world\n"), "Hello world\n");
149 assert_eq!(b.push("msg", "next"), "");
150 assert_eq!(b.flush(), "next\n");
151 }
152
153 #[test]
154 fn prefixes_thoughts_and_flushes_on_kind_change() {
155 let mut b = StreamBuf::default();
156 assert_eq!(b.push("think", "hmm"), "");
157 assert_eq!(b.push("msg", "ok\n"), "⋯ hmm\nok\n");
158 }
159
160 #[test]
161 fn flushes_long_thought_without_newline() {
162 let mut b = StreamBuf::default();
163 let chunk = "a".repeat(130);
164 let out = b.push("think", &chunk);
165 assert!(out.starts_with("⋯ "), "{out:?}");
166 assert!(out.ends_with('\n'));
167 assert_eq!(out.chars().count(), 123); assert_eq!(b.flush(), format!("⋯ {}\n", "a".repeat(10)));
169 }
170
171 #[test]
172 fn flushes_long_thought_at_word_boundary() {
173 let mut b = StreamBuf::default();
174 let chunk = "word ".repeat(30);
175 let out = b.push("think", &chunk);
176 let body = out.strip_prefix("⋯ ").unwrap().trim_end_matches('\n');
177 assert!(body.chars().count() <= 120, "{body:?}");
178 assert!(body.ends_with("word"), "{body:?}");
179 assert!(!b.text.is_empty());
180 assert!(!b.flush().starts_with("⋯ "));
181 }
182
183 #[test]
184 fn handles_multiple_lines_in_one_chunk() {
185 let mut b = StreamBuf::default();
186 assert_eq!(b.push("msg", "a\nb\nc"), "a\nb\n");
187 assert_eq!(b.flush(), "c\n");
188 }
189
190 #[test]
191 fn idle_flush_emits_partial_line_without_newline_then_appends() {
192 let mut b = StreamBuf::default();
193 assert_eq!(b.push_chunk("msg", "foo `00:03"), Chunk::default());
194 let first = b.idle_flush_chunk();
195 assert_eq!(
196 first,
197 Chunk {
198 text: "foo `00:03".into(),
199 append: false
200 }
201 );
202 assert_eq!(b.idle_flush_chunk(), Chunk::default());
204 let rest = b.push_chunk("msg", ":00` bar\nnext");
205 assert_eq!(
206 rest,
207 Chunk {
208 text: ":00` bar\n".into(),
209 append: true
210 }
211 );
212 assert_eq!(
213 b.flush_chunk(),
214 Chunk {
215 text: "next\n".into(),
216 append: false
217 }
218 );
219 }
220
221 #[test]
222 fn closing_an_open_line_with_nothing_buffered_sends_bare_newline() {
223 let mut b = StreamBuf::default();
224 b.push_chunk("msg", "abc");
225 b.idle_flush_chunk();
226 assert_eq!(
227 b.flush_chunk(),
228 Chunk {
229 text: "\n".into(),
230 append: true
231 }
232 );
233 assert_eq!(b.flush_chunk(), Chunk::default());
234 }
235
236 #[test]
237 fn continuation_of_thought_has_no_second_prefix() {
238 let mut b = StreamBuf::default();
239 b.push_chunk("think", "hmm");
240 assert_eq!(b.idle_flush_chunk().text, "⋯ hmm");
241 let c = b.push_chunk("think", " more\n");
242 assert_eq!(
243 c,
244 Chunk {
245 text: " more\n".into(),
246 append: true
247 }
248 );
249 }
250
251 #[test]
252 fn kind_switch_closes_open_line_then_starts_new() {
253 let mut b = StreamBuf::default();
254 b.push_chunk("think", "hmm");
255 b.idle_flush_chunk();
256 let c = b.push_chunk("msg", "ok\n");
257 assert_eq!(
258 c,
259 Chunk {
260 text: "\nok\n".into(),
261 append: true
262 }
263 );
264 }
265
266 #[test]
267 fn flush_on_empty_is_noop() {
268 let mut b = StreamBuf::default();
269 assert_eq!(b.flush(), "");
270 assert_eq!(b.push("msg", "\n"), "\n");
271 }
272}