use std::{
collections::HashSet,
io::Cursor,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
use aither_core::{
AnyIdAllocator, IdLease,
llm::{CommandStream, StoredFile},
};
use async_fs as fs;
use futures_lite::{AsyncWriteExt as _, StreamExt as _};
use image::{GenericImageView, ImageFormat, ImageReader, imageops::FilterType};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tracing::debug;
use crate::output_policy::{MediaBounds, OutputPolicy};
use crate::wording::{AnyShellWording, ShellWording};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OutputFormat {
#[default]
Text,
Image,
Video,
Binary,
Auto,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs, reason = "the schema's descriptions are the embedder's")]
pub enum MediaResolution {
#[default]
Auto,
Low,
Medium,
High,
Native,
}
#[must_use]
pub const fn empty_stream() -> CommandStream {
CommandStream::Inline {
text: String::new(),
}
}
#[must_use]
pub fn stored_path(stream: &CommandStream) -> Option<PathBuf> {
match stream {
CommandStream::Stored { file, .. } | CommandStream::Image { file, .. } => {
Some(PathBuf::from(&file.path))
}
CommandStream::Inline { .. } => None,
}
}
fn stored_file(url: String, path: &Path) -> StoredFile {
StoredFile {
url,
path: path.display().to_string(),
}
}
struct CutText<'a> {
data: &'a [u8],
text: &'a str,
max_lines: usize,
byte_budget: usize,
}
async fn cut_text_output(
store: &OutputStore,
format: OutputFormat,
cut: CutText<'_>,
) -> std::io::Result<CommandStream> {
let CutText {
data,
text,
max_lines,
byte_budget,
} = cut;
let wording: &dyn ShellWording = &**store.wording();
let folded = crate::output_compress::folded_code_content(text, wording)
.filter(|folded| folded.len() <= byte_budget);
let preview = folded.unwrap_or_else(|| {
crate::output_compress::stored_preview(text, max_lines, byte_budget, wording)
.trim_end_matches('\n')
.to_owned()
});
let ext = extension_for_data(data, format);
let mut taken = Vec::new();
let delivered = loop {
let name = store.name(ext, &mut taken).await?;
let stream = CommandStream::Stored {
file: stored_file(name.url.clone(), &name.path),
preview: preview.clone(),
truncated: true,
};
let rendered_len = stream.render_for_model().len();
if rendered_len >= data.len() {
debug!(
original = data.len(),
cut = rendered_len,
"cut form is not smaller than the output, returning it inline"
);
break Ok(CommandStream::Inline {
text: text.to_owned(),
});
}
match write_new(&name.path, data).await {
Ok(()) => {
debug!(size = data.len(), format = ?format, "saved output");
store.keep(name);
break Ok(stream);
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
taken.push(name.lease);
}
Err(error) => break Err(error),
}
};
drop(taken);
delivered
}
struct OutputName {
lease: IdLease,
url: String,
path: PathBuf,
}
#[derive(Clone, Debug)]
pub struct OutputStore(Arc<StoreInner>);
#[derive(Debug)]
struct StoreInner {
dir: PathBuf,
ids: AnyIdAllocator,
policy: OutputPolicy,
wording: AnyShellWording,
names: Mutex<Vec<IdLease>>,
earlier: async_lock::OnceCell<HashSet<String>>,
}
impl OutputStore {
pub async fn new(
dir: impl Into<PathBuf>,
ids: AnyIdAllocator,
policy: OutputPolicy,
wording: AnyShellWording,
) -> std::io::Result<Self> {
let dir = dir.into();
fs::create_dir_all(&dir).await?;
Ok(Self::at(dir, ids, policy, wording))
}
pub(crate) fn at(
dir: PathBuf,
ids: AnyIdAllocator,
policy: OutputPolicy,
wording: AnyShellWording,
) -> Self {
Self(Arc::new(StoreInner {
dir,
ids,
policy,
wording,
names: Mutex::new(Vec::new()),
earlier: async_lock::OnceCell::new(),
}))
}
#[must_use]
pub fn policy(&self) -> &OutputPolicy {
&self.0.policy
}
#[must_use]
pub fn wording(&self) -> &AnyShellWording {
&self.0.wording
}
#[cfg(test)]
pub(crate) fn testing(dir: PathBuf, ids: AnyIdAllocator, policy: OutputPolicy) -> Self {
Self::at(dir, ids, policy, crate::test_wording::TestWording::any())
}
#[must_use]
pub fn dir(&self) -> &Path {
&self.0.dir
}
pub async fn save(
&self,
data: &[u8],
format: OutputFormat,
resolution: MediaResolution,
) -> std::io::Result<CommandStream> {
let inline_bytes = self.policy().get().inline_bytes;
self.save_with_limit(data, format, resolution, Some(inline_bytes))
.await
}
pub async fn save_with_limit(
&self,
data: &[u8],
format: OutputFormat,
resolution: MediaResolution,
limit: Option<usize>,
) -> std::io::Result<CommandStream> {
if data.is_empty() {
return Ok(empty_stream());
}
let format = if format == OutputFormat::Auto {
detect_format(data)
} else {
format
};
let exceeds_limit = limit.is_some_and(|max| data.len() > max);
if exceeds_limit && !matches!(format, OutputFormat::Image) {
return save_large_output(self, data, format).await;
}
match format {
OutputFormat::Text | OutputFormat::Auto => save_text_output(self, data, format).await,
OutputFormat::Image => {
let prepared =
prepare_image_for_context(data, resolution, self.policy().get().media)?;
let (url, path) = self.create(&prepared.bytes, format).await?;
Ok(CommandStream::Image {
media_type: prepared.media_type,
file: stored_file(url, &path),
})
}
OutputFormat::Video | OutputFormat::Binary => {
save_large_output(self, data, format).await
}
}
}
pub async fn save_text_with_line_limit(
&self,
data: &[u8],
format: OutputFormat,
resolution: MediaResolution,
max_lines: usize,
byte_limit: Option<usize>,
) -> std::io::Result<CommandStream> {
if data.is_empty() {
return Ok(empty_stream());
}
let format = if format == OutputFormat::Auto {
detect_format(data)
} else {
format
};
if !matches!(format, OutputFormat::Text | OutputFormat::Auto) {
return self
.save_with_limit(data, format, resolution, byte_limit)
.await;
}
let text = String::from_utf8_lossy(data);
let line_count = text.lines().count();
let exceeds_bytes = byte_limit.is_some_and(|max| data.len() > max);
let exceeds_lines = line_count > max_lines;
if !exceeds_bytes && !exceeds_lines {
return Ok(CommandStream::Inline {
text: text.into_owned(),
});
}
let byte_budget = byte_limit.unwrap_or_else(|| self.policy().get().preview_bytes);
cut_text_output(
self,
format,
CutText {
data,
text: &text,
max_lines,
byte_budget,
},
)
.await
}
pub(crate) async fn stream_of_file(&self, path: &Path) -> std::io::Result<CommandStream> {
let name = path.strip_prefix(self.dir()).map_err(|_| {
std::io::Error::other(format!(
"{} is not a file of the output store",
path.display()
))
})?;
let data = fs::read(path).await?;
let policy = self.policy().get();
let text = String::from_utf8_lossy(&data);
if data.len() <= policy.inline_bytes {
return Ok(CommandStream::Inline {
text: text.into_owned(),
});
}
let mut preview = String::new();
for line in text.lines() {
if preview.len() + line.len() > policy.preview_bytes {
break;
}
preview.push_str(line);
preview.push('\n');
}
preview.truncate(preview.trim_end().len());
Ok(CommandStream::Stored {
file: StoredFile {
url: format!("outputs/{}", name.display()),
path: path.display().to_string(),
},
preview,
truncated: true,
})
}
pub async fn save_raw(&self, data: &[u8]) -> std::io::Result<(String, PathBuf)> {
let (url, path) = self.create(data, OutputFormat::Text).await?;
debug!(url = %url, size = data.len(), "saved raw output");
Ok((url, path))
}
pub async fn save_binary(&self, data: &[u8], mime: &str) -> std::io::Result<(String, PathBuf)> {
let format = if mime.starts_with("image/") {
OutputFormat::Image
} else {
OutputFormat::Binary
};
self.create(data, format).await
}
pub async fn read(&self, url: &str) -> std::io::Result<Vec<u8>> {
let filename = url.strip_prefix("outputs/").unwrap_or(url);
let filepath = self.dir().join(filename);
fs::read(&filepath).await
}
async fn name(&self, ext: &str, taken: &mut Vec<IdLease>) -> std::io::Result<OutputName> {
let earlier = self
.0
.earlier
.get_or_try_init(|| earlier_words(self.dir()))
.await?;
let lease = loop {
let lease = self.0.ids.lease().map_err(std::io::Error::other)?;
if earlier.contains(lease.as_str()) {
taken.push(lease);
} else {
break lease;
}
};
let filename = format!("{lease}.{ext}");
Ok(OutputName {
url: format!("outputs/{filename}"),
path: self.dir().join(filename),
lease,
})
}
fn keep(&self, name: OutputName) {
self.0
.names
.lock()
.expect("output names lock poisoned")
.push(name.lease);
}
async fn create(
&self,
data: &[u8],
format: OutputFormat,
) -> std::io::Result<(String, PathBuf)> {
let ext = extension_for_data(data, format);
let mut taken = Vec::new();
let created = loop {
let name = self.name(ext, &mut taken).await?;
match write_new(&name.path, data).await {
Ok(()) => {
debug!(url = %name.url, size = data.len(), format = ?format, "saved output");
let created = (name.url.clone(), name.path.clone());
self.keep(name);
break Ok(created);
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
taken.push(name.lease);
}
Err(error) => break Err(error),
}
};
drop(taken);
created
}
}
async fn earlier_words(dir: &Path) -> std::io::Result<HashSet<String>> {
let mut entries = fs::read_dir(dir).await?;
let mut words = HashSet::new();
while let Some(entry) = entries.try_next().await? {
let name = entry.file_name();
let name = name.to_string_lossy();
if let Some(word) = name.split('.').next() {
words.insert(word.to_owned());
}
}
Ok(words)
}
async fn write_new(path: &Path, data: &[u8]) -> std::io::Result<()> {
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.await?;
file.write_all(data).await?;
file.flush().await
}
async fn save_text_output(
store: &OutputStore,
data: &[u8],
format: OutputFormat,
) -> std::io::Result<CommandStream> {
if data.len() <= store.policy().get().inline_bytes {
Ok(CommandStream::Inline {
text: String::from_utf8_lossy(data).into_owned(),
})
} else {
save_large_output(store, data, format).await
}
}
async fn save_large_output(
store: &OutputStore,
data: &[u8],
format: OutputFormat,
) -> std::io::Result<CommandStream> {
if matches!(format, OutputFormat::Text | OutputFormat::Auto) {
let text = String::from_utf8_lossy(data);
return cut_text_output(
store,
format,
CutText {
data,
text: &text,
max_lines: usize::MAX,
byte_budget: store.policy().get().preview_bytes,
},
)
.await;
}
let (url, path) = store.create(data, format).await?;
Ok(CommandStream::Stored {
file: stored_file(url, &path),
preview: String::new(),
truncated: false,
})
}
#[derive(Debug)]
struct PreparedImage {
bytes: Vec<u8>,
media_type: String,
}
fn prepare_image_for_context(
data: &[u8],
resolution: MediaResolution,
bounds: MediaBounds,
) -> std::io::Result<PreparedImage> {
let media_type = detect_image_media_type(data);
let Some(max_dimension) = bounds.bound(resolution) else {
return Ok(PreparedImage {
bytes: data.to_vec(),
media_type,
});
};
let image = ImageReader::new(Cursor::new(data))
.with_guessed_format()
.map_err(io_error)?
.decode()
.map_err(io_error)?;
let (width, height) = image.dimensions();
if width <= max_dimension && height <= max_dimension {
return Ok(PreparedImage {
bytes: data.to_vec(),
media_type,
});
}
let format = image_format_from_media_type(media_type.as_str()).ok_or_else(|| {
std::io::Error::other(format!(
"unsupported image media type for terminal resizing: {media_type}"
))
})?;
let resized = image.resize(max_dimension, max_dimension, FilterType::Lanczos3);
let mut cursor = Cursor::new(Vec::new());
resized.write_to(&mut cursor, format).map_err(io_error)?;
Ok(PreparedImage {
bytes: cursor.into_inner(),
media_type,
})
}
fn io_error(error: impl std::fmt::Display) -> std::io::Error {
std::io::Error::other(error.to_string())
}
fn detect_format(data: &[u8]) -> OutputFormat {
if data.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
return OutputFormat::Image;
}
if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
return OutputFormat::Image;
}
if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
return OutputFormat::Image;
}
if data.starts_with(b"RIFF") && data.len() > 12 && &data[8..12] == b"WEBP" {
return OutputFormat::Image;
}
if data.len() > 12 && &data[4..8] == b"ftyp" {
return OutputFormat::Video;
}
if let Ok(text) = std::str::from_utf8(data) {
let is_text = text
.chars()
.all(|c| c == '\n' || c == '\r' || c == '\t' || (c >= ' ' && c != '\x7f'));
if is_text {
return OutputFormat::Text;
}
}
OutputFormat::Binary
}
const fn format_extension(format: OutputFormat) -> &'static str {
match format {
OutputFormat::Text | OutputFormat::Auto => "txt",
OutputFormat::Image | OutputFormat::Binary => "bin",
OutputFormat::Video => "mp4",
}
}
fn image_extension(data: &[u8]) -> Option<&'static str> {
if data.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
Some("png")
} else if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
Some("jpg")
} else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
Some("gif")
} else if data.starts_with(b"RIFF") && data.len() > 12 && &data[8..12] == b"WEBP" {
Some("webp")
} else {
None
}
}
fn extension_for_data(data: &[u8], format: OutputFormat) -> &'static str {
if matches!(format, OutputFormat::Image) {
return image_extension(data).unwrap_or_else(|| format_extension(format));
}
format_extension(format)
}
fn detect_image_media_type(data: &[u8]) -> String {
if data.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
"image/png".to_string()
} else if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
"image/jpeg".to_string()
} else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
"image/gif".to_string()
} else if data.starts_with(b"RIFF") && data.len() > 12 && &data[8..12] == b"WEBP" {
"image/webp".to_string()
} else {
"application/octet-stream".to_string()
}
}
fn image_format_from_media_type(media_type: &str) -> Option<ImageFormat> {
match media_type {
"image/png" => Some(ImageFormat::Png),
"image/jpeg" => Some(ImageFormat::Jpeg),
"image/gif" => Some(ImageFormat::Gif),
"image/webp" => Some(ImageFormat::WebP),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{fmt::Write, io::Cursor};
use image::{DynamicImage, ImageBuffer, Rgba};
#[test]
fn test_detect_format() {
assert_eq!(
detect_format(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]),
OutputFormat::Image
);
assert_eq!(detect_format(b"Hello, world!"), OutputFormat::Text);
assert_eq!(
detect_format(&[0x00, 0x01, 0x02, 0x03]),
OutputFormat::Binary
);
}
const INLINE_OUTPUT_LIMIT: usize = crate::output_policy::fixture::LIMITS.inline_bytes;
fn store(dir: &Path) -> OutputStore {
OutputStore::testing(
dir.to_path_buf(),
AnyIdAllocator::default(),
crate::output_policy::fixture::policy(),
)
}
const SMALL: crate::output_policy::OutputLimits = crate::output_policy::OutputLimits {
inline_bytes: 100,
preview_bytes: 60,
default_lines: 5,
ceiling_lines: 8,
read_bytes: 7,
media: crate::output_policy::MediaBounds {
low: 16,
medium: 32,
high: 64,
},
job_preview_bytes: 9,
};
#[test]
fn the_line_budget_defaults_and_clamps_to_the_policy() {
let policy = OutputPolicy::new(SMALL);
assert_eq!(policy.lines(None), 5);
assert_eq!(policy.lines(Some(3)), 3);
assert_eq!(policy.lines(Some(500)), 8);
let mut wider = SMALL;
wider.default_lines = 6;
wider.ceiling_lines = 9;
policy.set(wider);
assert_eq!(policy.lines(None), 6);
assert_eq!(policy.lines(Some(500)), 9);
}
#[tokio::test]
async fn a_non_default_policy_cuts_the_inline_output_and_follows_updates() {
let dir = tempfile::tempdir().unwrap();
let policy = OutputPolicy::new(SMALL);
let store = OutputStore::testing(
dir.path().to_path_buf(),
AnyIdAllocator::default(),
policy.clone(),
);
let text = "0123456789\n".repeat(200);
assert!(text.len() > SMALL.inline_bytes);
let cut = store
.save(text.as_bytes(), OutputFormat::Text, MediaResolution::Auto)
.await
.unwrap();
let CommandStream::Stored { preview, .. } = cut else {
panic!("a text over the policy's inline bytes is stored: {cut:?}");
};
assert!(preview.len() < text.len() / 4, "{preview}");
let mut roomy = SMALL;
roomy.inline_bytes = 10_000;
policy.set(roomy);
let inline = store
.save(text.as_bytes(), OutputFormat::Text, MediaResolution::Auto)
.await
.unwrap();
assert!(matches!(inline, CommandStream::Inline { .. }), "{inline:?}");
}
#[tokio::test]
async fn a_stored_file_is_named_by_a_word_leased_until_the_store_drops() {
let dir = tempfile::tempdir().unwrap();
let ids = crate::test_ids::RecordingIds::default();
let store = OutputStore::testing(
dir.path().to_path_buf(),
ids.allocator(),
crate::output_policy::fixture::policy(),
);
let (url, path) = store.save_raw(b"kept").await.unwrap();
let [word] = ids.leased().try_into().expect("one lease");
assert_eq!(url, format!("outputs/{word}.txt"));
assert_eq!(path, dir.path().join(format!("{word}.txt")));
store
.save(b"short", OutputFormat::Text, MediaResolution::Auto)
.await
.unwrap();
assert_eq!(ids.live(), std::slice::from_ref(&word));
let clone = store.clone();
drop(store);
assert_eq!(
ids.live(),
std::slice::from_ref(&word),
"a clone still addresses it"
);
drop(clone);
assert_eq!(ids.released(), [word]);
}
#[tokio::test]
async fn a_name_a_file_already_holds_is_skipped_and_released() {
let dir = tempfile::tempdir().unwrap();
let ids = crate::test_ids::RecordingIds::default();
std::fs::write(dir.path().join("alfa.png"), "earlier").unwrap();
std::fs::write(dir.path().join("bravo.txt"), "earlier").unwrap();
let store = OutputStore::testing(
dir.path().to_path_buf(),
ids.allocator(),
crate::output_policy::fixture::policy(),
);
let (url, _) = store.save_raw(b"new").await.unwrap();
assert_eq!(url, "outputs/charlie.txt");
assert!(!dir.path().join("alfa.txt").exists());
assert_eq!(
std::fs::read_to_string(dir.path().join("bravo.txt")).unwrap(),
"earlier"
);
assert_eq!(ids.released(), ["alfa", "bravo"]);
assert_eq!(ids.live(), ["charlie"]);
}
#[tokio::test]
async fn a_name_a_file_takes_later_is_skipped_too() {
let dir = tempfile::tempdir().unwrap();
let ids = crate::test_ids::RecordingIds::default();
let store = OutputStore::testing(
dir.path().to_path_buf(),
ids.allocator(),
crate::output_policy::fixture::policy(),
);
let (first, _) = store.save_raw(b"first").await.unwrap();
assert_eq!(first, "outputs/alfa.txt");
std::fs::write(dir.path().join("bravo.txt"), "later").unwrap();
let (second, _) = store.save_raw(b"second").await.unwrap();
assert_eq!(second, "outputs/charlie.txt");
assert_eq!(
std::fs::read_to_string(dir.path().join("bravo.txt")).unwrap(),
"later"
);
assert_eq!(ids.released(), ["bravo"]);
}
#[tokio::test]
async fn images_are_always_stored_downscaled_to_the_requested_resolution() {
let dir = tempfile::tempdir().unwrap();
let jpeg = encode_test_image(1200, 900, ImageFormat::Jpeg);
let stream = store(dir.path())
.save_with_limit(&jpeg, OutputFormat::Image, MediaResolution::Low, None)
.await
.unwrap();
let CommandStream::Image { media_type, file } = stream else {
panic!("expected a stored image");
};
assert_eq!(media_type, "image/jpeg");
assert!(
Path::new(&file.path)
.extension()
.is_some_and(|extension| extension.eq_ignore_ascii_case("jpg")
|| extension.eq_ignore_ascii_case("jpeg"))
);
assert!(
dir.path()
.join(file.url.trim_start_matches("outputs/"))
.exists()
);
let stored = ImageReader::open(&file.path)
.unwrap()
.with_guessed_format()
.unwrap()
.decode()
.unwrap();
assert!(stored.width() <= 512);
assert!(stored.height() <= 512);
}
#[tokio::test]
async fn small_images_are_stored_too() {
let dir = tempfile::tempdir().unwrap();
let png = encode_test_image(8, 8, ImageFormat::Png);
let stream = store(dir.path())
.save(&png, OutputFormat::Auto, MediaResolution::Auto)
.await
.unwrap();
let CommandStream::Image { media_type, file } = stream else {
panic!("expected a stored image");
};
assert_eq!(media_type, "image/png");
assert_eq!(std::fs::read(&file.path).unwrap(), png);
}
fn encode_test_image(width: u32, height: u32, format: ImageFormat) -> Vec<u8> {
let image = ImageBuffer::from_fn(width, height, |x, y| {
let r = u8::try_from((x * 255) / width.max(1)).expect("red channel fits in u8");
let g = u8::try_from((y * 255) / height.max(1)).expect("green channel fits in u8");
let b = u8::try_from(((x + y) * 255) / (width + height).max(1))
.expect("blue channel fits in u8");
Rgba([r, g, b, 255])
});
let dynamic = DynamicImage::ImageRgba8(image);
let mut cursor = Cursor::new(Vec::new());
dynamic.write_to(&mut cursor, format).unwrap();
cursor.into_inner()
}
#[tokio::test]
async fn stored_text_output_includes_head_preview_and_guidance() {
let dir = tempfile::tempdir().unwrap();
let mut data = String::new();
for i in 0..2000 {
data.extend([format!("line number {i} with some padding text\n")]);
}
assert!(data.len() > INLINE_OUTPUT_LIMIT);
let entry = store(dir.path())
.save_text_with_line_limit(
data.as_bytes(),
OutputFormat::Text,
MediaResolution::Auto,
10_000,
Some(INLINE_OUTPUT_LIMIT),
)
.await
.unwrap();
let rendered = entry.render_for_model();
let CommandStream::Stored {
preview: text,
truncated,
file,
} = entry
else {
panic!("expected stored entry with text content");
};
assert!(truncated);
assert!(
text.starts_with("line number 0 "),
"preview must lead with real content: {text}"
);
assert!(
rendered.contains(&file.url) && rendered.contains(&file.path),
"guidance must reference the saved file: {rendered}"
);
assert!(rendered.contains("Use head/tail/rg"));
}
#[tokio::test]
async fn stored_text_output_preview_honors_max_lines() {
let dir = tempfile::tempdir().unwrap();
let pad = "p".repeat(400);
let data = format!("alpha{pad}\nbeta{pad}\ngamma{pad}\ndelta{pad}\n").repeat(2);
let entry = store(dir.path())
.save_text_with_line_limit(
data.as_bytes(),
OutputFormat::Text,
MediaResolution::Auto,
3,
Some(INLINE_OUTPUT_LIMIT),
)
.await
.unwrap();
let CommandStream::Stored { preview: text, .. } = entry else {
panic!("expected stored entry with text content");
};
assert!(
text.starts_with(&format!("alpha{pad}\n[... lines 2-6 of 8 omitted")),
"preview must stop at max_lines: {text}"
);
assert!(
text.ends_with(&format!("gamma{pad}\ndelta{pad}")),
"tail must close the preview: {text}"
);
}
#[tokio::test]
async fn stored_preview_shows_the_failure_at_the_tail_with_matching_line_numbers() {
let dir = tempfile::tempdir().unwrap();
let mut data = String::new();
for index in 0..4000 {
writeln!(data, "test suite::case_{index} ... ok").expect("write to String");
}
data.push_str("test suite::case_4000 ... FAILED\n");
data.push_str("thread 'suite::case_4000' panicked at sandbox/src/lib.rs:42:5:\n");
data.push_str("assertion `left == right` failed\n");
data.push_str("error: test failed\n");
let total_lines = data.lines().count();
let entry = store(dir.path())
.save_text_with_line_limit(
data.as_bytes(),
OutputFormat::Text,
MediaResolution::Auto,
usize::MAX,
Some(INLINE_OUTPUT_LIMIT),
)
.await
.unwrap();
let CommandStream::Stored {
preview: text,
file,
..
} = entry
else {
panic!("expected stored entry with text content");
};
let path = file.path;
assert!(text.contains("error: test failed"), "{text}");
assert!(text.contains("FAILED"), "{text}");
let marker = text
.lines()
.find(|line| line.starts_with("[... lines"))
.expect("omitted range marker");
let range = marker.split_whitespace().nth(2).expect("range");
let (first, last) = range.split_once('-').expect("range bounds");
let first: usize = first.parse().expect("first line number");
let last: usize = last.parse().expect("last line number");
assert!(
marker.contains(&format!("of {total_lines} omitted")),
"{marker}"
);
let stored = std::fs::read_to_string(&path).expect("stored file is readable");
let stored_lines: Vec<&str> = stored.lines().collect();
assert_eq!(stored_lines.len(), total_lines);
let preview_lines: Vec<&str> = text.lines().collect();
let marker_index = preview_lines
.iter()
.position(|line| line.starts_with("[... lines"))
.expect("marker index");
assert_eq!(stored_lines[first - 2], preview_lines[marker_index - 1]);
assert_eq!(stored_lines[last], preview_lines[marker_index + 1]);
assert_eq!(stored_lines[total_lines - 1], "error: test failed");
}
fn stored_file_count(dir: &Path) -> usize {
std::fs::read_dir(dir).expect("read dir").count()
}
#[tokio::test]
async fn output_just_over_max_lines_is_returned_inline_when_the_cut_is_larger() {
let dir = tempfile::tempdir().unwrap();
let data = (0..212).fold(String::new(), |mut data, i| {
use std::fmt::Write as _;
writeln!(data, "ok {i}").expect("writing to a String cannot fail");
data
});
let entry = store(dir.path())
.save_text_with_line_limit(
data.as_bytes(),
OutputFormat::Text,
MediaResolution::Auto,
200,
Some(INLINE_OUTPUT_LIMIT),
)
.await
.unwrap();
let CommandStream::Inline { text } = entry else {
panic!("expected the original inline");
};
assert_eq!(text, data);
assert_eq!(stored_file_count(dir.path()), 0, "nothing may be stored");
}
#[tokio::test]
async fn large_output_that_shrinks_is_stored_with_its_preview() {
let dir = tempfile::tempdir().unwrap();
let data = "a reasonably long line of command output text\n".repeat(1000);
let entry = store(dir.path())
.save_text_with_line_limit(
data.as_bytes(),
OutputFormat::Text,
MediaResolution::Auto,
200,
Some(INLINE_OUTPUT_LIMIT),
)
.await
.unwrap();
let CommandStream::Stored {
preview: text,
truncated,
file,
} = entry
else {
panic!("expected stored entry with text content");
};
assert!(truncated);
assert!(text.len() < data.len());
assert_eq!(std::fs::read_to_string(file.path).unwrap(), data);
assert_eq!(stored_file_count(dir.path()), 1);
}
#[tokio::test]
async fn oversized_single_line_is_stored_only_when_the_cut_is_smaller() {
let dir = tempfile::tempdir().unwrap();
let data = "x".repeat(INLINE_OUTPUT_LIMIT * 2);
let entry = store(dir.path())
.save(data.as_bytes(), OutputFormat::Text, MediaResolution::Auto)
.await
.unwrap();
let CommandStream::Stored { preview: text, .. } = entry else {
panic!("expected stored entry with text content");
};
assert!(text.len() < data.len());
}
#[cfg(feature = "code-folding")]
fn rust_source(functions: usize) -> String {
let mut source = String::new();
for index in 0..functions {
writeln!(source, "fn compute_{index}(input: u64) -> u64 {{").unwrap();
for step in 0..8 {
writeln!(
source,
" let step_{step} = input.wrapping_mul({step} + 3);"
)
.unwrap();
}
writeln!(source, " input + step_7\n}}\n").unwrap();
}
source
}
#[cfg(feature = "code-folding")]
#[tokio::test]
async fn source_code_over_the_limit_is_stored_with_a_folded_preview() {
let dir = tempfile::tempdir().unwrap();
let data = rust_source(40);
assert!(data.lines().count() > 200);
let entry = store(dir.path())
.save_text_with_line_limit(
data.as_bytes(),
OutputFormat::Text,
MediaResolution::Auto,
200,
Some(INLINE_OUTPUT_LIMIT),
)
.await
.unwrap();
let CommandStream::Stored {
preview: text,
file,
..
} = entry
else {
panic!("expected stored entry with a folded preview");
};
let path = file.path;
assert!(text.contains("fn compute_0"), "{text}");
assert!(text.contains("Code folded"), "{text}");
assert!(!text.contains("step_3 ="), "bodies must be folded: {text}");
assert!(text.len() < data.len());
assert_eq!(std::fs::read_to_string(path).unwrap(), data);
}
#[cfg(feature = "code-folding")]
#[tokio::test]
async fn small_source_code_is_left_untouched() {
let dir = tempfile::tempdir().unwrap();
let data = rust_source(3);
let entry = store(dir.path())
.save_text_with_line_limit(
data.as_bytes(),
OutputFormat::Text,
MediaResolution::Auto,
200,
Some(INLINE_OUTPUT_LIMIT),
)
.await
.unwrap();
let CommandStream::Inline { text } = entry else {
panic!("expected the source inline");
};
assert_eq!(text, data);
assert_eq!(stored_file_count(dir.path()), 0);
}
}