1use std::{
9 collections::HashSet,
10 io::Cursor,
11 path::{Path, PathBuf},
12 sync::{Arc, Mutex},
13};
14
15use aither_core::{
16 AnyIdAllocator, IdLease,
17 llm::{CommandStream, StoredFile},
18};
19use async_fs as fs;
20use futures_lite::{AsyncWriteExt as _, StreamExt as _};
21use image::{GenericImageView, ImageFormat, ImageReader, imageops::FilterType};
22use schemars::JsonSchema;
23use serde::{Deserialize, Serialize};
24use tracing::debug;
25
26use crate::output_policy::{MediaBounds, OutputPolicy};
27use crate::wording::{AnyShellWording, ShellWording};
28
29#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
31#[serde(rename_all = "snake_case")]
32pub enum OutputFormat {
33 #[default]
35 Text,
36 Image,
38 Video,
40 Binary,
42 Auto,
44}
45
46#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
49#[serde(rename_all = "snake_case")]
50#[allow(missing_docs, reason = "the schema's descriptions are the embedder's")]
51pub enum MediaResolution {
52 #[default]
54 Auto,
55 Low,
57 Medium,
59 High,
61 Native,
63}
64
65#[must_use]
67pub const fn empty_stream() -> CommandStream {
68 CommandStream::Inline {
69 text: String::new(),
70 }
71}
72
73#[must_use]
75pub fn stored_path(stream: &CommandStream) -> Option<PathBuf> {
76 match stream {
77 CommandStream::Stored { file, .. } | CommandStream::Image { file, .. } => {
78 Some(PathBuf::from(&file.path))
79 }
80 CommandStream::Inline { .. } => None,
81 }
82}
83
84fn stored_file(url: String, path: &Path) -> StoredFile {
85 StoredFile {
86 url,
87 path: path.display().to_string(),
88 }
89}
90
91struct CutText<'a> {
93 data: &'a [u8],
95 text: &'a str,
97 max_lines: usize,
98 byte_budget: usize,
99}
100
101async fn cut_text_output(
109 store: &OutputStore,
110 format: OutputFormat,
111 cut: CutText<'_>,
112) -> std::io::Result<CommandStream> {
113 let CutText {
114 data,
115 text,
116 max_lines,
117 byte_budget,
118 } = cut;
119
120 let wording: &dyn ShellWording = &**store.wording();
121 let folded = crate::output_compress::folded_code_content(text, wording)
122 .filter(|folded| folded.len() <= byte_budget);
123 let preview = folded.unwrap_or_else(|| {
124 crate::output_compress::stored_preview(text, max_lines, byte_budget, wording)
125 .trim_end_matches('\n')
126 .to_owned()
127 });
128 let ext = extension_for_data(data, format);
129
130 let mut taken = Vec::new();
133 let delivered = loop {
134 let name = store.name(ext, &mut taken).await?;
135 let stream = CommandStream::Stored {
136 file: stored_file(name.url.clone(), &name.path),
137 preview: preview.clone(),
138 truncated: true,
139 };
140
141 let rendered_len = stream.render_for_model().len();
142 if rendered_len >= data.len() {
143 debug!(
144 original = data.len(),
145 cut = rendered_len,
146 "cut form is not smaller than the output, returning it inline"
147 );
148 break Ok(CommandStream::Inline {
149 text: text.to_owned(),
150 });
151 }
152
153 match write_new(&name.path, data).await {
154 Ok(()) => {
155 debug!(size = data.len(), format = ?format, "saved output");
156 store.keep(name);
157 break Ok(stream);
158 }
159 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
160 taken.push(name.lease);
161 }
162 Err(error) => break Err(error),
163 }
164 };
165 drop(taken);
166 delivered
167}
168
169struct OutputName {
171 lease: IdLease,
172 url: String,
174 path: PathBuf,
175}
176
177#[derive(Clone, Debug)]
185pub struct OutputStore(Arc<StoreInner>);
186
187#[derive(Debug)]
188struct StoreInner {
189 dir: PathBuf,
191 ids: AnyIdAllocator,
192 policy: OutputPolicy,
193 wording: AnyShellWording,
195 names: Mutex<Vec<IdLease>>,
197 earlier: async_lock::OnceCell<HashSet<String>>,
200}
201
202impl OutputStore {
203 pub async fn new(
211 dir: impl Into<PathBuf>,
212 ids: AnyIdAllocator,
213 policy: OutputPolicy,
214 wording: AnyShellWording,
215 ) -> std::io::Result<Self> {
216 let dir = dir.into();
217 fs::create_dir_all(&dir).await?;
218 Ok(Self::at(dir, ids, policy, wording))
219 }
220
221 pub(crate) fn at(
223 dir: PathBuf,
224 ids: AnyIdAllocator,
225 policy: OutputPolicy,
226 wording: AnyShellWording,
227 ) -> Self {
228 Self(Arc::new(StoreInner {
229 dir,
230 ids,
231 policy,
232 wording,
233 names: Mutex::new(Vec::new()),
234 earlier: async_lock::OnceCell::new(),
235 }))
236 }
237
238 #[must_use]
240 pub fn policy(&self) -> &OutputPolicy {
241 &self.0.policy
242 }
243
244 #[must_use]
246 pub fn wording(&self) -> &AnyShellWording {
247 &self.0.wording
248 }
249
250 #[cfg(test)]
253 pub(crate) fn testing(dir: PathBuf, ids: AnyIdAllocator, policy: OutputPolicy) -> Self {
254 Self::at(dir, ids, policy, crate::test_wording::TestWording::any())
255 }
256
257 #[must_use]
259 pub fn dir(&self) -> &Path {
260 &self.0.dir
261 }
262
263 pub async fn save(
275 &self,
276 data: &[u8],
277 format: OutputFormat,
278 resolution: MediaResolution,
279 ) -> std::io::Result<CommandStream> {
280 let inline_bytes = self.policy().get().inline_bytes;
281 self.save_with_limit(data, format, resolution, Some(inline_bytes))
282 .await
283 }
284
285 pub async fn save_with_limit(
294 &self,
295 data: &[u8],
296 format: OutputFormat,
297 resolution: MediaResolution,
298 limit: Option<usize>,
299 ) -> std::io::Result<CommandStream> {
300 if data.is_empty() {
301 return Ok(empty_stream());
302 }
303
304 let format = if format == OutputFormat::Auto {
305 detect_format(data)
306 } else {
307 format
308 };
309
310 let exceeds_limit = limit.is_some_and(|max| data.len() > max);
311 if exceeds_limit && !matches!(format, OutputFormat::Image) {
312 return save_large_output(self, data, format).await;
313 }
314
315 match format {
316 OutputFormat::Text | OutputFormat::Auto => save_text_output(self, data, format).await,
317 OutputFormat::Image => {
318 let prepared =
319 prepare_image_for_context(data, resolution, self.policy().get().media)?;
320 let (url, path) = self.create(&prepared.bytes, format).await?;
321 Ok(CommandStream::Image {
322 media_type: prepared.media_type,
323 file: stored_file(url, &path),
324 })
325 }
326 OutputFormat::Video | OutputFormat::Binary => {
327 save_large_output(self, data, format).await
329 }
330 }
331 }
332
333 pub async fn save_text_with_line_limit(
343 &self,
344 data: &[u8],
345 format: OutputFormat,
346 resolution: MediaResolution,
347 max_lines: usize,
348 byte_limit: Option<usize>,
349 ) -> std::io::Result<CommandStream> {
350 if data.is_empty() {
351 return Ok(empty_stream());
352 }
353
354 let format = if format == OutputFormat::Auto {
355 detect_format(data)
356 } else {
357 format
358 };
359
360 if !matches!(format, OutputFormat::Text | OutputFormat::Auto) {
362 return self
363 .save_with_limit(data, format, resolution, byte_limit)
364 .await;
365 }
366
367 let text = String::from_utf8_lossy(data);
368 let line_count = text.lines().count();
369
370 let exceeds_bytes = byte_limit.is_some_and(|max| data.len() > max);
372 let exceeds_lines = line_count > max_lines;
373
374 if !exceeds_bytes && !exceeds_lines {
375 return Ok(CommandStream::Inline {
376 text: text.into_owned(),
377 });
378 }
379
380 let byte_budget = byte_limit.unwrap_or_else(|| self.policy().get().preview_bytes);
384 cut_text_output(
385 self,
386 format,
387 CutText {
388 data,
389 text: &text,
390 max_lines,
391 byte_budget,
392 },
393 )
394 .await
395 }
396
397 pub(crate) async fn stream_of_file(&self, path: &Path) -> std::io::Result<CommandStream> {
405 let name = path.strip_prefix(self.dir()).map_err(|_| {
406 std::io::Error::other(format!(
407 "{} is not a file of the output store",
408 path.display()
409 ))
410 })?;
411 let data = fs::read(path).await?;
412 let policy = self.policy().get();
413 let text = String::from_utf8_lossy(&data);
414 if data.len() <= policy.inline_bytes {
415 return Ok(CommandStream::Inline {
416 text: text.into_owned(),
417 });
418 }
419 let mut preview = String::new();
420 for line in text.lines() {
421 if preview.len() + line.len() > policy.preview_bytes {
422 break;
423 }
424 preview.push_str(line);
425 preview.push('\n');
426 }
427 preview.truncate(preview.trim_end().len());
428 Ok(CommandStream::Stored {
429 file: StoredFile {
430 url: format!("outputs/{}", name.display()),
431 path: path.display().to_string(),
432 },
433 preview,
434 truncated: true,
435 })
436 }
437
438 pub async fn save_raw(&self, data: &[u8]) -> std::io::Result<(String, PathBuf)> {
449 let (url, path) = self.create(data, OutputFormat::Text).await?;
450 debug!(url = %url, size = data.len(), "saved raw output");
451 Ok((url, path))
452 }
453
454 pub async fn save_binary(&self, data: &[u8], mime: &str) -> std::io::Result<(String, PathBuf)> {
463 let format = if mime.starts_with("image/") {
464 OutputFormat::Image
465 } else {
466 OutputFormat::Binary
467 };
468 self.create(data, format).await
469 }
470
471 pub async fn read(&self, url: &str) -> std::io::Result<Vec<u8>> {
477 let filename = url.strip_prefix("outputs/").unwrap_or(url);
478 let filepath = self.dir().join(filename);
479 fs::read(&filepath).await
480 }
481
482 async fn name(&self, ext: &str, taken: &mut Vec<IdLease>) -> std::io::Result<OutputName> {
487 let earlier = self
488 .0
489 .earlier
490 .get_or_try_init(|| earlier_words(self.dir()))
491 .await?;
492 let lease = loop {
493 let lease = self.0.ids.lease().map_err(std::io::Error::other)?;
494 if earlier.contains(lease.as_str()) {
495 taken.push(lease);
496 } else {
497 break lease;
498 }
499 };
500 let filename = format!("{lease}.{ext}");
501 Ok(OutputName {
502 url: format!("outputs/{filename}"),
503 path: self.dir().join(filename),
504 lease,
505 })
506 }
507
508 fn keep(&self, name: OutputName) {
510 self.0
511 .names
512 .lock()
513 .expect("output names lock poisoned")
514 .push(name.lease);
515 }
516
517 async fn create(
519 &self,
520 data: &[u8],
521 format: OutputFormat,
522 ) -> std::io::Result<(String, PathBuf)> {
523 let ext = extension_for_data(data, format);
524 let mut taken = Vec::new();
526 let created = loop {
527 let name = self.name(ext, &mut taken).await?;
528 match write_new(&name.path, data).await {
529 Ok(()) => {
530 debug!(url = %name.url, size = data.len(), format = ?format, "saved output");
531 let created = (name.url.clone(), name.path.clone());
532 self.keep(name);
533 break Ok(created);
534 }
535 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
536 taken.push(name.lease);
537 }
538 Err(error) => break Err(error),
539 }
540 };
541 drop(taken);
542 created
543 }
544}
545
546async fn earlier_words(dir: &Path) -> std::io::Result<HashSet<String>> {
548 let mut entries = fs::read_dir(dir).await?;
549 let mut words = HashSet::new();
550 while let Some(entry) = entries.try_next().await? {
551 let name = entry.file_name();
552 let name = name.to_string_lossy();
553 if let Some(word) = name.split('.').next() {
554 words.insert(word.to_owned());
555 }
556 }
557 Ok(words)
558}
559
560async fn write_new(path: &Path, data: &[u8]) -> std::io::Result<()> {
563 let mut file = fs::OpenOptions::new()
564 .write(true)
565 .create_new(true)
566 .open(path)
567 .await?;
568 file.write_all(data).await?;
569 file.flush().await
570}
571
572async fn save_text_output(
577 store: &OutputStore,
578 data: &[u8],
579 format: OutputFormat,
580) -> std::io::Result<CommandStream> {
581 if data.len() <= store.policy().get().inline_bytes {
582 Ok(CommandStream::Inline {
583 text: String::from_utf8_lossy(data).into_owned(),
584 })
585 } else {
586 save_large_output(store, data, format).await
587 }
588}
589
590async fn save_large_output(
593 store: &OutputStore,
594 data: &[u8],
595 format: OutputFormat,
596) -> std::io::Result<CommandStream> {
597 if matches!(format, OutputFormat::Text | OutputFormat::Auto) {
598 let text = String::from_utf8_lossy(data);
599 return cut_text_output(
600 store,
601 format,
602 CutText {
603 data,
604 text: &text,
605 max_lines: usize::MAX,
606 byte_budget: store.policy().get().preview_bytes,
607 },
608 )
609 .await;
610 }
611
612 let (url, path) = store.create(data, format).await?;
614 Ok(CommandStream::Stored {
615 file: stored_file(url, &path),
616 preview: String::new(),
617 truncated: false,
618 })
619}
620
621#[derive(Debug)]
622struct PreparedImage {
623 bytes: Vec<u8>,
624 media_type: String,
625}
626
627fn prepare_image_for_context(
628 data: &[u8],
629 resolution: MediaResolution,
630 bounds: MediaBounds,
631) -> std::io::Result<PreparedImage> {
632 let media_type = detect_image_media_type(data);
633 let Some(max_dimension) = bounds.bound(resolution) else {
634 return Ok(PreparedImage {
635 bytes: data.to_vec(),
636 media_type,
637 });
638 };
639
640 let image = ImageReader::new(Cursor::new(data))
641 .with_guessed_format()
642 .map_err(io_error)?
643 .decode()
644 .map_err(io_error)?;
645
646 let (width, height) = image.dimensions();
647 if width <= max_dimension && height <= max_dimension {
648 return Ok(PreparedImage {
649 bytes: data.to_vec(),
650 media_type,
651 });
652 }
653
654 let format = image_format_from_media_type(media_type.as_str()).ok_or_else(|| {
655 std::io::Error::other(format!(
656 "unsupported image media type for terminal resizing: {media_type}"
657 ))
658 })?;
659 let resized = image.resize(max_dimension, max_dimension, FilterType::Lanczos3);
660 let mut cursor = Cursor::new(Vec::new());
661 resized.write_to(&mut cursor, format).map_err(io_error)?;
662
663 Ok(PreparedImage {
664 bytes: cursor.into_inner(),
665 media_type,
666 })
667}
668
669fn io_error(error: impl std::fmt::Display) -> std::io::Error {
670 std::io::Error::other(error.to_string())
671}
672
673fn detect_format(data: &[u8]) -> OutputFormat {
675 if data.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
677 return OutputFormat::Image;
679 }
680 if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
681 return OutputFormat::Image;
683 }
684 if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
685 return OutputFormat::Image;
686 }
687 if data.starts_with(b"RIFF") && data.len() > 12 && &data[8..12] == b"WEBP" {
688 return OutputFormat::Image;
689 }
690
691 if data.len() > 12 && &data[4..8] == b"ftyp" {
693 return OutputFormat::Video;
695 }
696
697 if let Ok(text) = std::str::from_utf8(data) {
699 let is_text = text
700 .chars()
701 .all(|c| c == '\n' || c == '\r' || c == '\t' || (c >= ' ' && c != '\x7f'));
702 if is_text {
703 return OutputFormat::Text;
704 }
705 }
706
707 OutputFormat::Binary
708}
709
710const fn format_extension(format: OutputFormat) -> &'static str {
712 match format {
713 OutputFormat::Text | OutputFormat::Auto => "txt",
714 OutputFormat::Image | OutputFormat::Binary => "bin",
715 OutputFormat::Video => "mp4",
716 }
717}
718
719fn image_extension(data: &[u8]) -> Option<&'static str> {
720 if data.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
721 Some("png")
722 } else if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
723 Some("jpg")
724 } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
725 Some("gif")
726 } else if data.starts_with(b"RIFF") && data.len() > 12 && &data[8..12] == b"WEBP" {
727 Some("webp")
728 } else {
729 None
730 }
731}
732
733fn extension_for_data(data: &[u8], format: OutputFormat) -> &'static str {
734 if matches!(format, OutputFormat::Image) {
735 return image_extension(data).unwrap_or_else(|| format_extension(format));
736 }
737 format_extension(format)
738}
739
740fn detect_image_media_type(data: &[u8]) -> String {
742 if data.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
743 "image/png".to_string()
744 } else if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
745 "image/jpeg".to_string()
746 } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
747 "image/gif".to_string()
748 } else if data.starts_with(b"RIFF") && data.len() > 12 && &data[8..12] == b"WEBP" {
749 "image/webp".to_string()
750 } else {
751 "application/octet-stream".to_string()
752 }
753}
754
755fn image_format_from_media_type(media_type: &str) -> Option<ImageFormat> {
756 match media_type {
757 "image/png" => Some(ImageFormat::Png),
758 "image/jpeg" => Some(ImageFormat::Jpeg),
759 "image/gif" => Some(ImageFormat::Gif),
760 "image/webp" => Some(ImageFormat::WebP),
761 _ => None,
762 }
763}
764
765#[cfg(test)]
766mod tests {
767 use super::*;
768 use std::{fmt::Write, io::Cursor};
769
770 use image::{DynamicImage, ImageBuffer, Rgba};
771
772 #[test]
773 fn test_detect_format() {
774 assert_eq!(
776 detect_format(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]),
777 OutputFormat::Image
778 );
779
780 assert_eq!(detect_format(b"Hello, world!"), OutputFormat::Text);
782
783 assert_eq!(
785 detect_format(&[0x00, 0x01, 0x02, 0x03]),
786 OutputFormat::Binary
787 );
788 }
789
790 const INLINE_OUTPUT_LIMIT: usize = crate::output_policy::fixture::LIMITS.inline_bytes;
791
792 fn store(dir: &Path) -> OutputStore {
794 OutputStore::testing(
795 dir.to_path_buf(),
796 AnyIdAllocator::default(),
797 crate::output_policy::fixture::policy(),
798 )
799 }
800
801 const SMALL: crate::output_policy::OutputLimits = crate::output_policy::OutputLimits {
804 inline_bytes: 100,
805 preview_bytes: 60,
806 default_lines: 5,
807 ceiling_lines: 8,
808 read_bytes: 7,
809 media: crate::output_policy::MediaBounds {
810 low: 16,
811 medium: 32,
812 high: 64,
813 },
814 job_preview_bytes: 9,
815 };
816
817 #[test]
818 fn the_line_budget_defaults_and_clamps_to_the_policy() {
819 let policy = OutputPolicy::new(SMALL);
820 assert_eq!(policy.lines(None), 5);
821 assert_eq!(policy.lines(Some(3)), 3);
822 assert_eq!(policy.lines(Some(500)), 8);
823 let mut wider = SMALL;
824 wider.default_lines = 6;
825 wider.ceiling_lines = 9;
826 policy.set(wider);
827 assert_eq!(policy.lines(None), 6);
828 assert_eq!(policy.lines(Some(500)), 9);
829 }
830
831 #[tokio::test]
832 async fn a_non_default_policy_cuts_the_inline_output_and_follows_updates() {
833 let dir = tempfile::tempdir().unwrap();
834 let policy = OutputPolicy::new(SMALL);
835 let store = OutputStore::testing(
836 dir.path().to_path_buf(),
837 AnyIdAllocator::default(),
838 policy.clone(),
839 );
840 let text = "0123456789\n".repeat(200);
843 assert!(text.len() > SMALL.inline_bytes);
844
845 let cut = store
846 .save(text.as_bytes(), OutputFormat::Text, MediaResolution::Auto)
847 .await
848 .unwrap();
849 let CommandStream::Stored { preview, .. } = cut else {
850 panic!("a text over the policy's inline bytes is stored: {cut:?}");
851 };
852 assert!(preview.len() < text.len() / 4, "{preview}");
853
854 let mut roomy = SMALL;
856 roomy.inline_bytes = 10_000;
857 policy.set(roomy);
858 let inline = store
859 .save(text.as_bytes(), OutputFormat::Text, MediaResolution::Auto)
860 .await
861 .unwrap();
862 assert!(matches!(inline, CommandStream::Inline { .. }), "{inline:?}");
863 }
864
865 #[tokio::test]
866 async fn a_stored_file_is_named_by_a_word_leased_until_the_store_drops() {
867 let dir = tempfile::tempdir().unwrap();
868 let ids = crate::test_ids::RecordingIds::default();
869 let store = OutputStore::testing(
870 dir.path().to_path_buf(),
871 ids.allocator(),
872 crate::output_policy::fixture::policy(),
873 );
874
875 let (url, path) = store.save_raw(b"kept").await.unwrap();
876 let [word] = ids.leased().try_into().expect("one lease");
877 assert_eq!(url, format!("outputs/{word}.txt"));
878 assert_eq!(path, dir.path().join(format!("{word}.txt")));
879
880 store
882 .save(b"short", OutputFormat::Text, MediaResolution::Auto)
883 .await
884 .unwrap();
885 assert_eq!(ids.live(), std::slice::from_ref(&word));
886
887 let clone = store.clone();
888 drop(store);
889 assert_eq!(
890 ids.live(),
891 std::slice::from_ref(&word),
892 "a clone still addresses it"
893 );
894 drop(clone);
895 assert_eq!(ids.released(), [word]);
896 }
897
898 #[tokio::test]
899 async fn a_name_a_file_already_holds_is_skipped_and_released() {
900 let dir = tempfile::tempdir().unwrap();
901 let ids = crate::test_ids::RecordingIds::default();
902 std::fs::write(dir.path().join("alfa.png"), "earlier").unwrap();
905 std::fs::write(dir.path().join("bravo.txt"), "earlier").unwrap();
906 let store = OutputStore::testing(
907 dir.path().to_path_buf(),
908 ids.allocator(),
909 crate::output_policy::fixture::policy(),
910 );
911
912 let (url, _) = store.save_raw(b"new").await.unwrap();
913 assert_eq!(url, "outputs/charlie.txt");
914 assert!(!dir.path().join("alfa.txt").exists());
915 assert_eq!(
916 std::fs::read_to_string(dir.path().join("bravo.txt")).unwrap(),
917 "earlier"
918 );
919 assert_eq!(ids.released(), ["alfa", "bravo"]);
920 assert_eq!(ids.live(), ["charlie"]);
921 }
922
923 #[tokio::test]
926 async fn a_name_a_file_takes_later_is_skipped_too() {
927 let dir = tempfile::tempdir().unwrap();
928 let ids = crate::test_ids::RecordingIds::default();
929 let store = OutputStore::testing(
930 dir.path().to_path_buf(),
931 ids.allocator(),
932 crate::output_policy::fixture::policy(),
933 );
934 let (first, _) = store.save_raw(b"first").await.unwrap();
935 assert_eq!(first, "outputs/alfa.txt");
936
937 std::fs::write(dir.path().join("bravo.txt"), "later").unwrap();
938 let (second, _) = store.save_raw(b"second").await.unwrap();
939 assert_eq!(second, "outputs/charlie.txt");
940 assert_eq!(
941 std::fs::read_to_string(dir.path().join("bravo.txt")).unwrap(),
942 "later"
943 );
944 assert_eq!(ids.released(), ["bravo"]);
945 }
946
947 #[tokio::test]
948 async fn images_are_always_stored_downscaled_to_the_requested_resolution() {
949 let dir = tempfile::tempdir().unwrap();
950 let jpeg = encode_test_image(1200, 900, ImageFormat::Jpeg);
951
952 let stream = store(dir.path())
953 .save_with_limit(&jpeg, OutputFormat::Image, MediaResolution::Low, None)
954 .await
955 .unwrap();
956
957 let CommandStream::Image { media_type, file } = stream else {
958 panic!("expected a stored image");
959 };
960 assert_eq!(media_type, "image/jpeg");
961 assert!(
962 Path::new(&file.path)
963 .extension()
964 .is_some_and(|extension| extension.eq_ignore_ascii_case("jpg")
965 || extension.eq_ignore_ascii_case("jpeg"))
966 );
967 assert!(
968 dir.path()
969 .join(file.url.trim_start_matches("outputs/"))
970 .exists()
971 );
972
973 let stored = ImageReader::open(&file.path)
974 .unwrap()
975 .with_guessed_format()
976 .unwrap()
977 .decode()
978 .unwrap();
979 assert!(stored.width() <= 512);
980 assert!(stored.height() <= 512);
981 }
982
983 #[tokio::test]
984 async fn small_images_are_stored_too() {
985 let dir = tempfile::tempdir().unwrap();
986 let png = encode_test_image(8, 8, ImageFormat::Png);
987
988 let stream = store(dir.path())
989 .save(&png, OutputFormat::Auto, MediaResolution::Auto)
990 .await
991 .unwrap();
992
993 let CommandStream::Image { media_type, file } = stream else {
994 panic!("expected a stored image");
995 };
996 assert_eq!(media_type, "image/png");
997 assert_eq!(std::fs::read(&file.path).unwrap(), png);
998 }
999
1000 fn encode_test_image(width: u32, height: u32, format: ImageFormat) -> Vec<u8> {
1001 let image = ImageBuffer::from_fn(width, height, |x, y| {
1002 let r = u8::try_from((x * 255) / width.max(1)).expect("red channel fits in u8");
1003 let g = u8::try_from((y * 255) / height.max(1)).expect("green channel fits in u8");
1004 let b = u8::try_from(((x + y) * 255) / (width + height).max(1))
1005 .expect("blue channel fits in u8");
1006 Rgba([r, g, b, 255])
1007 });
1008 let dynamic = DynamicImage::ImageRgba8(image);
1009 let mut cursor = Cursor::new(Vec::new());
1010 dynamic.write_to(&mut cursor, format).unwrap();
1011 cursor.into_inner()
1012 }
1013
1014 #[tokio::test]
1015 async fn stored_text_output_includes_head_preview_and_guidance() {
1016 let dir = tempfile::tempdir().unwrap();
1017 let mut data = String::new();
1018 for i in 0..2000 {
1019 data.extend([format!("line number {i} with some padding text\n")]);
1020 }
1021 assert!(data.len() > INLINE_OUTPUT_LIMIT);
1022
1023 let entry = store(dir.path())
1024 .save_text_with_line_limit(
1025 data.as_bytes(),
1026 OutputFormat::Text,
1027 MediaResolution::Auto,
1028 10_000,
1029 Some(INLINE_OUTPUT_LIMIT),
1030 )
1031 .await
1032 .unwrap();
1033
1034 let rendered = entry.render_for_model();
1035 let CommandStream::Stored {
1036 preview: text,
1037 truncated,
1038 file,
1039 } = entry
1040 else {
1041 panic!("expected stored entry with text content");
1042 };
1043 assert!(truncated);
1044 assert!(
1045 text.starts_with("line number 0 "),
1046 "preview must lead with real content: {text}"
1047 );
1048 assert!(
1049 rendered.contains(&file.url) && rendered.contains(&file.path),
1050 "guidance must reference the saved file: {rendered}"
1051 );
1052 assert!(rendered.contains("Use head/tail/rg"));
1053 }
1054
1055 #[tokio::test]
1056 async fn stored_text_output_preview_honors_max_lines() {
1057 let dir = tempfile::tempdir().unwrap();
1058 let pad = "p".repeat(400);
1059 let data = format!("alpha{pad}\nbeta{pad}\ngamma{pad}\ndelta{pad}\n").repeat(2);
1060
1061 let entry = store(dir.path())
1062 .save_text_with_line_limit(
1063 data.as_bytes(),
1064 OutputFormat::Text,
1065 MediaResolution::Auto,
1066 3,
1067 Some(INLINE_OUTPUT_LIMIT),
1068 )
1069 .await
1070 .unwrap();
1071
1072 let CommandStream::Stored { preview: text, .. } = entry else {
1073 panic!("expected stored entry with text content");
1074 };
1075 assert!(
1077 text.starts_with(&format!("alpha{pad}\n[... lines 2-6 of 8 omitted")),
1078 "preview must stop at max_lines: {text}"
1079 );
1080 assert!(
1081 text.ends_with(&format!("gamma{pad}\ndelta{pad}")),
1082 "tail must close the preview: {text}"
1083 );
1084 }
1085
1086 #[tokio::test]
1087 async fn stored_preview_shows_the_failure_at_the_tail_with_matching_line_numbers() {
1088 let dir = tempfile::tempdir().unwrap();
1089 let mut data = String::new();
1090 for index in 0..4000 {
1091 writeln!(data, "test suite::case_{index} ... ok").expect("write to String");
1092 }
1093 data.push_str("test suite::case_4000 ... FAILED\n");
1094 data.push_str("thread 'suite::case_4000' panicked at sandbox/src/lib.rs:42:5:\n");
1095 data.push_str("assertion `left == right` failed\n");
1096 data.push_str("error: test failed\n");
1097 let total_lines = data.lines().count();
1098
1099 let entry = store(dir.path())
1100 .save_text_with_line_limit(
1101 data.as_bytes(),
1102 OutputFormat::Text,
1103 MediaResolution::Auto,
1104 usize::MAX,
1105 Some(INLINE_OUTPUT_LIMIT),
1106 )
1107 .await
1108 .unwrap();
1109
1110 let CommandStream::Stored {
1111 preview: text,
1112 file,
1113 ..
1114 } = entry
1115 else {
1116 panic!("expected stored entry with text content");
1117 };
1118 let path = file.path;
1119
1120 assert!(text.contains("error: test failed"), "{text}");
1122 assert!(text.contains("FAILED"), "{text}");
1123
1124 let marker = text
1126 .lines()
1127 .find(|line| line.starts_with("[... lines"))
1128 .expect("omitted range marker");
1129 let range = marker.split_whitespace().nth(2).expect("range");
1130 let (first, last) = range.split_once('-').expect("range bounds");
1131 let first: usize = first.parse().expect("first line number");
1132 let last: usize = last.parse().expect("last line number");
1133 assert!(
1134 marker.contains(&format!("of {total_lines} omitted")),
1135 "{marker}"
1136 );
1137
1138 let stored = std::fs::read_to_string(&path).expect("stored file is readable");
1139 let stored_lines: Vec<&str> = stored.lines().collect();
1140 assert_eq!(stored_lines.len(), total_lines);
1141
1142 let preview_lines: Vec<&str> = text.lines().collect();
1143 let marker_index = preview_lines
1144 .iter()
1145 .position(|line| line.starts_with("[... lines"))
1146 .expect("marker index");
1147 assert_eq!(stored_lines[first - 2], preview_lines[marker_index - 1]);
1150 assert_eq!(stored_lines[last], preview_lines[marker_index + 1]);
1151 assert_eq!(stored_lines[total_lines - 1], "error: test failed");
1152 }
1153
1154 fn stored_file_count(dir: &Path) -> usize {
1155 std::fs::read_dir(dir).expect("read dir").count()
1156 }
1157
1158 #[tokio::test]
1159 async fn output_just_over_max_lines_is_returned_inline_when_the_cut_is_larger() {
1160 let dir = tempfile::tempdir().unwrap();
1161 let data = (0..212).fold(String::new(), |mut data, i| {
1162 use std::fmt::Write as _;
1163 writeln!(data, "ok {i}").expect("writing to a String cannot fail");
1164 data
1165 });
1166
1167 let entry = store(dir.path())
1168 .save_text_with_line_limit(
1169 data.as_bytes(),
1170 OutputFormat::Text,
1171 MediaResolution::Auto,
1172 200,
1173 Some(INLINE_OUTPUT_LIMIT),
1174 )
1175 .await
1176 .unwrap();
1177
1178 let CommandStream::Inline { text } = entry else {
1179 panic!("expected the original inline");
1180 };
1181 assert_eq!(text, data);
1182 assert_eq!(stored_file_count(dir.path()), 0, "nothing may be stored");
1183 }
1184
1185 #[tokio::test]
1186 async fn large_output_that_shrinks_is_stored_with_its_preview() {
1187 let dir = tempfile::tempdir().unwrap();
1188 let data = "a reasonably long line of command output text\n".repeat(1000);
1189
1190 let entry = store(dir.path())
1191 .save_text_with_line_limit(
1192 data.as_bytes(),
1193 OutputFormat::Text,
1194 MediaResolution::Auto,
1195 200,
1196 Some(INLINE_OUTPUT_LIMIT),
1197 )
1198 .await
1199 .unwrap();
1200
1201 let CommandStream::Stored {
1202 preview: text,
1203 truncated,
1204 file,
1205 } = entry
1206 else {
1207 panic!("expected stored entry with text content");
1208 };
1209 assert!(truncated);
1210 assert!(text.len() < data.len());
1211 assert_eq!(std::fs::read_to_string(file.path).unwrap(), data);
1212 assert_eq!(stored_file_count(dir.path()), 1);
1213 }
1214
1215 #[tokio::test]
1216 async fn oversized_single_line_is_stored_only_when_the_cut_is_smaller() {
1217 let dir = tempfile::tempdir().unwrap();
1218 let data = "x".repeat(INLINE_OUTPUT_LIMIT * 2);
1219
1220 let entry = store(dir.path())
1221 .save(data.as_bytes(), OutputFormat::Text, MediaResolution::Auto)
1222 .await
1223 .unwrap();
1224
1225 let CommandStream::Stored { preview: text, .. } = entry else {
1226 panic!("expected stored entry with text content");
1227 };
1228 assert!(text.len() < data.len());
1229 }
1230
1231 #[cfg(feature = "code-folding")]
1232 fn rust_source(functions: usize) -> String {
1233 let mut source = String::new();
1234 for index in 0..functions {
1235 writeln!(source, "fn compute_{index}(input: u64) -> u64 {{").unwrap();
1236 for step in 0..8 {
1237 writeln!(
1238 source,
1239 " let step_{step} = input.wrapping_mul({step} + 3);"
1240 )
1241 .unwrap();
1242 }
1243 writeln!(source, " input + step_7\n}}\n").unwrap();
1244 }
1245 source
1246 }
1247
1248 #[cfg(feature = "code-folding")]
1249 #[tokio::test]
1250 async fn source_code_over_the_limit_is_stored_with_a_folded_preview() {
1251 let dir = tempfile::tempdir().unwrap();
1252 let data = rust_source(40);
1253 assert!(data.lines().count() > 200);
1254
1255 let entry = store(dir.path())
1256 .save_text_with_line_limit(
1257 data.as_bytes(),
1258 OutputFormat::Text,
1259 MediaResolution::Auto,
1260 200,
1261 Some(INLINE_OUTPUT_LIMIT),
1262 )
1263 .await
1264 .unwrap();
1265
1266 let CommandStream::Stored {
1267 preview: text,
1268 file,
1269 ..
1270 } = entry
1271 else {
1272 panic!("expected stored entry with a folded preview");
1273 };
1274 let path = file.path;
1275 assert!(text.contains("fn compute_0"), "{text}");
1276 assert!(text.contains("Code folded"), "{text}");
1277 assert!(!text.contains("step_3 ="), "bodies must be folded: {text}");
1278 assert!(text.len() < data.len());
1279 assert_eq!(std::fs::read_to_string(path).unwrap(), data);
1280 }
1281
1282 #[cfg(feature = "code-folding")]
1283 #[tokio::test]
1284 async fn small_source_code_is_left_untouched() {
1285 let dir = tempfile::tempdir().unwrap();
1286 let data = rust_source(3);
1287
1288 let entry = store(dir.path())
1289 .save_text_with_line_limit(
1290 data.as_bytes(),
1291 OutputFormat::Text,
1292 MediaResolution::Auto,
1293 200,
1294 Some(INLINE_OUTPUT_LIMIT),
1295 )
1296 .await
1297 .unwrap();
1298
1299 let CommandStream::Inline { text } = entry else {
1300 panic!("expected the source inline");
1301 };
1302 assert_eq!(text, data);
1303 assert_eq!(stored_file_count(dir.path()), 0);
1304 }
1305}