eclipse-core 0.13.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! `#499` end to end: a camera-sized picture enters the conversation.
//!
//! The stub endpoint counts what the *request* carried, so the two halves of the issue are both
//! asserted against bytes rather than against intent: the file on disk is byte-identical to the
//! upload, and the body the model saw is smaller than the wire limit. The fixture is a real PNG
//! built here (stored deflate blocks, so its size is the raster's size), because the point of the
//! test is a picture that is genuinely too big.

use eclipse_core::attachments::Store;
use eclipse_core::config::Config;
use eclipse_core::message::ImagePart;
use eclipse_core::runtime::RunOptions;
use eclipse_core::tools::AllowAll;
use eclipse_core::Agent;
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};

const WIRE: usize = 2 * 1024 * 1024;

fn answer(text: &str) -> String {
    serde_json::json!({"choices": [{"message": {"role": "assistant", "content": text}}]})
        .to_string()
}

/// A valid PNG of the requested size. Stored deflate blocks: no compression, so a 2000×1500 picture
/// is about 9 MB — which is the whole point.
fn png(width: u32, height: u32) -> Vec<u8> {
    let mut raw = Vec::with_capacity((height * (1 + width * 3)) as usize);
    for y in 0..height {
        raw.push(0);
        for x in 0..width {
            raw.extend_from_slice(&[(x % 251) as u8, (y % 241) as u8, 120]);
        }
    }
    let mut zlib = vec![0x78, 0x01];
    let mut rest: &[u8] = &raw;
    loop {
        let take = rest.len().min(65535);
        let last = take == rest.len();
        zlib.push(if last { 1 } else { 0 });
        zlib.extend_from_slice(&(take as u16).to_le_bytes());
        zlib.extend_from_slice(&(!(take as u16)).to_le_bytes());
        zlib.extend_from_slice(&rest[..take]);
        rest = &rest[take..];
        if last {
            break;
        }
    }
    let (mut a, mut b) = (1u32, 0u32);
    for byte in &raw {
        a = (a + *byte as u32) % 65521;
        b = (b + a) % 65521;
    }
    zlib.extend_from_slice(&((b << 16) | a).to_be_bytes());

    let mut out = Vec::new();
    out.extend_from_slice(b"\x89PNG\r\n\x1a\n");
    let mut ihdr = Vec::new();
    ihdr.extend_from_slice(&width.to_be_bytes());
    ihdr.extend_from_slice(&height.to_be_bytes());
    ihdr.extend_from_slice(&[8, 2, 0, 0, 0]);
    chunk(&mut out, b"IHDR", &ihdr);
    chunk(&mut out, b"IDAT", &zlib);
    chunk(&mut out, b"IEND", &[]);
    out
}

fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
    out.extend_from_slice(kind);
    out.extend_from_slice(data);
    let mut crc_input = kind.to_vec();
    crc_input.extend_from_slice(data);
    out.extend_from_slice(&crc(&crc_input).to_be_bytes());
}

fn crc(data: &[u8]) -> u32 {
    let mut crc = 0xFFFF_FFFFu32;
    for byte in data {
        crc ^= *byte as u32;
        for _ in 0..8 {
            let mask = (crc & 1).wrapping_neg();
            crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
        }
    }
    !crc
}

/// A stub that records every request body and answers a fixed line.
async fn stub() -> (String, Arc<Mutex<Vec<String>>>) {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let seen = Arc::new(Mutex::new(Vec::<String>::new()));
    let log = Arc::clone(&seen);
    tokio::spawn(async move {
        loop {
            let Ok((mut s, _)) = listener.accept().await else {
                break;
            };
            let log = Arc::clone(&log);
            tokio::spawn(async move {
                let mut buf = Vec::new();
                let body = loop {
                    let mut chunk = [0u8; 65536];
                    let read = s.read(&mut chunk).await.unwrap_or(0);
                    buf.extend_from_slice(&chunk[..read]);
                    let text = String::from_utf8_lossy(&buf).to_string();
                    let Some(idx) = text.find("\r\n\r\n") else {
                        if read == 0 {
                            return;
                        }
                        continue;
                    };
                    let len = text[..idx]
                        .to_lowercase()
                        .lines()
                        .find_map(|l| l.strip_prefix("content-length: ")?.trim().parse().ok())
                        .unwrap_or(0usize);
                    if buf.len() >= idx + 4 + len {
                        break text[idx + 4..].to_string();
                    }
                };
                log.lock().unwrap().push(body);
                let reply = answer("I can see the picture: a gradient.");
                let resp = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\
                     connection: close\r\n\r\n{reply}",
                    reply.len()
                );
                let _ = s.write_all(resp.as_bytes()).await;
            });
        }
    });
    (base, seen)
}

struct Fixture {
    agent: Agent,
    dir: tempfile::TempDir,
    seen: Arc<Mutex<Vec<String>>>,
    root: std::path::PathBuf,
}

async fn fixture() -> Fixture {
    let (base, seen) = stub().await;
    let dir = tempfile::tempdir().unwrap();
    let home = dir.path().join("home");
    let ws = dir.path().join("ws");
    std::fs::create_dir_all(home.join(".eclipse")).unwrap();
    std::fs::create_dir_all(&ws).unwrap();
    std::fs::write(
        home.join(".eclipse/config.toml"),
        format!(
            // `vision = true` is what declares the model able to see a picture at all; without it
            // the turn is refused before anything is sent, which is `#346`'s rule and not this test.
            "[provider]\nbase_url = \"{}\"\nmodel = \"m\"\nstream = false\nmax_retries = 0\n\
             vision = true\n\
             [tools]\nworkspace_root = \"{}\"\npolicy = \"ask\"\n\
             [sessions]\nautotitle = false\n\
             [vision]\nmode = \"native\"",
            base,
            ws.display()
        ),
    )
    .unwrap();
    let env = [("HOME".to_string(), home.display().to_string())];
    let lookup = |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
    let cfg = Config::load_with_profile(None, None, &lookup).expect("config loads");
    let root = cfg.attachments_dir(&lookup).expect("a state directory");
    let agent = Agent::from_config_with_env(&cfg, &lookup).expect("agent builds");
    Fixture {
        agent,
        dir,
        seen,
        root,
    }
}

#[tokio::test]
async fn a_camera_sized_picture_runs_and_the_original_stays_whole() {
    // A machine with none of the three resizers cannot derive the copy, and the refusal that
    // follows is the store's own test. CI has none of them; this box has two.
    if eclipse_core::attachments::Helper::probe().is_none() {
        return;
    }
    let fx = fixture().await;
    let picture = png(2000, 1500);
    assert!(
        picture.len() > WIRE,
        "the fixture has to be over the wire limit: {} bytes",
        picture.len()
    );
    let part = ImagePart::from_data_url(
        "camera.png",
        &eclipse_core::message::data_url("image/png", &picture),
    )
    .expect("a picture over the limit is accepted now");

    let opts = RunOptions {
        images: vec![part],
        ..Default::default()
    };
    fx.agent
        .run_with(
            Some("s1"),
            "what is in this picture?",
            &AllowAll,
            &|_| {},
            &opts,
        )
        .await
        .expect("the turn runs");

    // Acceptance 1: the original is byte-identical on disk, and the copy is under the wire limit.
    let stored = Store::new(fx.root.clone(), u64::MAX);
    let session_dir = fx.root.join("s1");
    let files: Vec<_> = std::fs::read_dir(&session_dir)
        .expect("the session's own directory")
        .flatten()
        .map(|e| e.path())
        .collect();
    let original = files
        .iter()
        .find(|p| std::fs::metadata(p).map(|m| m.len() as usize).unwrap_or(0) == picture.len())
        .unwrap_or_else(|| panic!("the original is on disk: {files:?}"));
    assert_eq!(std::fs::read(original).unwrap(), picture);
    let copy = files
        .iter()
        .find(|p| p != &original)
        .unwrap_or_else(|| panic!("a working copy beside it: {files:?}"));
    assert!(
        std::fs::metadata(copy).unwrap().len() as usize <= WIRE,
        "the copy fits the wire"
    );
    assert!(stored.total_bytes() >= picture.len() as u64);

    // Acceptance 2: the request carried the copy, not the original, and said both facts.
    let bodies = fx.seen.lock().unwrap().clone();
    let body = bodies.last().expect("the turn made a request");
    assert!(
        body.len() < picture.len(),
        "the request is {} bytes for a {} byte picture",
        body.len(),
        picture.len()
    );
    assert!(
        body.contains("the original is at"),
        "the message says where it is"
    );
    assert!(body.contains("2000×1500"), "the message says how big it is");
    assert!(body.contains("copy"), "the message names the copy a copy");
    assert!(
        body.contains(&original.display().to_string()),
        "the message names the original's path"
    );
    drop(fx.dir);
}

#[tokio::test]
async fn a_picture_under_the_wire_limit_is_sent_as_it_is_and_copied_nowhere() {
    let fx = fixture().await;
    let picture = png(120, 90);
    assert!(picture.len() < WIRE);
    let part = ImagePart::from_data_url(
        "screenshot.png",
        &eclipse_core::message::data_url("image/png", &picture),
    )
    .unwrap();
    let opts = RunOptions {
        images: vec![part],
        ..Default::default()
    };
    fx.agent
        .run_with(
            Some("s1"),
            "what is in this picture?",
            &AllowAll,
            &|_| {},
            &opts,
        )
        .await
        .unwrap();
    // Nothing kept: a small picture is its own working copy, so the store stays empty.
    let stored = Store::new(fx.root.clone(), u64::MAX);
    assert_eq!(stored.total_bytes(), 0, "no copy for a picture that fits");
    let bodies = fx.seen.lock().unwrap().clone();
    assert!(!bodies.last().unwrap().contains("attached:"), "and no note");
    drop(fx.dir);
}

#[tokio::test]
async fn the_store_says_where_the_originals_are() {
    let fx = fixture().await;
    assert_eq!(fx.root.file_name().unwrap(), "attachments");
    assert!(fx.root.starts_with(fx.dir.path()));
    drop(fx.dir);
}