use iced::widget::{Column, image, markdown, text};
use iced::{ContentFit, Element, Length};
use std::borrow::{Borrow, Cow};
use std::collections::{HashMap, VecDeque};
use std::hash::Hash;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
use std::time::SystemTime;
use super::{selectable, theme, widgets};
use crate::gui::markdown_breaks;
use crate::util::markdown::iced_markdown_options;
use crate::util::media_target::{self, MarkerTarget};
use crate::util::{
MEDIA_MARKER_RE, MediaMarkerKind, UnwrapPoison, file_name_or_path, parse_media_marker,
};
use ::image as image_crate;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct MediaAttachment {
pub image: Option<String>,
pub label: String,
pub reveal: Option<String>,
}
pub(crate) struct Preprocessed {
pub text: String,
pub attachments: Vec<MediaAttachment>,
}
impl Preprocessed {
#[must_use]
pub fn display_text(&self) -> String {
let mut out = self
.attachments
.iter()
.map(|attachment| attachment.label.as_str())
.collect::<Vec<_>>()
.join("\n");
if !self.text.is_empty() {
if !out.is_empty() {
out.push('\n');
}
out.push_str(&self.text);
}
out
}
}
pub(crate) fn preprocess(content: &str, workspace: Option<&Path>) -> Preprocessed {
let s = replace_saved_annotations(&replace_transcription(content));
if !MEDIA_MARKER_RE.is_match(&s) && !s.contains("![") {
return Preprocessed {
text: s,
attachments: Vec::new(),
};
}
let (code, mut edits) = scan(&s);
edits.extend(marker_edits(&s, workspace, &code));
edits.sort_by_key(|edit| edit.range.start);
apply_edits(&s, edits)
}
pub(crate) fn parse_body(
content: &str,
workspace: Option<&Path>,
) -> (Vec<markdown::Item>, Vec<MediaAttachment>) {
let rendered = preprocess(content, workspace);
let escaped = markdown_breaks::escape_html_blocks(&rendered.text);
let with_breaks = markdown_breaks::hard_breaks(&escaped);
(
markdown::parse(&with_breaks).collect(),
rendered.attachments,
)
}
fn replace_transcription(s: &str) -> String {
static RE: LazyLock<regex::Regex> = LazyLock::new(|| {
regex::Regex::new(r"\[(Audio|Video) transcription of [^\]]+\]:\s*")
.expect("transcription regex must compile")
});
RE.replace_all(s, |caps: ®ex::Captures| {
match caps.get(1).map(|m| m.as_str()) {
Some("Audio") => "🔊 ",
_ => "🎬 ",
}
})
.to_string()
}
fn render_marker(kind: MediaMarkerKind, target: &str, roots: &[PathBuf]) -> Option<Replacement> {
let target = referenced_target(target)?;
match media_target::resolve_marker_target(&target, roots) {
MarkerTarget::NotAReference => None,
MarkerTarget::Inline => Some(match kind {
MediaMarkerKind::Image => {
Replacement::Attachment(delivered_marker(kind, &target, None))
}
MediaMarkerKind::Audio | MediaMarkerKind::Video | MediaMarkerKind::File => {
Replacement::Text(media_target::inline_marker_refusal(kind))
}
}),
MarkerTarget::Remote => Some(match media_target::remote_marker(kind, &target) {
media_target::RemoteMarker::Refused(reason) => {
Replacement::Text(media_target::marker_refusal_for(&target, reason))
}
media_target::RemoteMarker::Deliverable => {
Replacement::Attachment(delivered_marker(kind, &target, None))
}
}),
MarkerTarget::Local(path) => {
let path = media_target::repaired_local_target(&path).unwrap_or(path);
Some(Replacement::Attachment(delivered_marker(
kind,
&target,
Some(&path.to_string_lossy()),
)))
}
}
}
fn referenced_target(target: &str) -> Option<Cow<'_, str>> {
let target = target.trim();
if target.is_empty() {
return None;
}
let Some(scheme) = scheme_of(target) else {
return Some(Cow::Borrowed(target));
};
let canonical = if scheme.chars().any(|c| c.is_ascii_uppercase()) {
let rest = &target[scheme.len() + 3..];
Cow::Owned(format!("{}://{rest}", scheme.to_ascii_lowercase()))
} else {
Cow::Borrowed(target)
};
media_target::is_valid_remote_url(&canonical).then_some(canonical)
}
fn scheme_of(target: &str) -> Option<&str> {
let (scheme, _) = target.split_once("://")?;
let mut chars = scheme.chars();
(chars.next()?.is_ascii_alphabetic()
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')))
.then_some(scheme)
}
fn delivered_marker(
kind: MediaMarkerKind,
target: &str,
resolved: Option<&str>,
) -> MediaAttachment {
let resolved = resolved.unwrap_or(target);
match kind {
MediaMarkerKind::Image => picture_attachment(resolved, Some(target)),
MediaMarkerKind::File => MediaAttachment {
image: None,
label: format!("📄 {}", file_name_or_path(target)),
reveal: Some(resolved.to_string()),
},
MediaMarkerKind::Audio | MediaMarkerKind::Video => MediaAttachment {
image: None,
label: media_label(kind, target),
reveal: None,
},
}
}
fn picture_attachment(image: &str, label_target: Option<&str>) -> MediaAttachment {
let stripped = image.starts_with(crate::util::DATA_URI_OMITTED_PREFIX);
MediaAttachment {
image: (!stripped).then(|| image.to_string()),
label: if media_target::is_inline_payload(image) {
"🖼️ image".to_string()
} else {
format!("🖼️ {}", file_name_or_path(label_target.unwrap_or(image)))
},
reveal: None,
}
}
fn media_label(kind: MediaMarkerKind, target: &str) -> String {
match kind {
MediaMarkerKind::Audio => format!("🎵 {}", file_name_or_path(target)),
_ => format!("🎬 Video: {}", file_name_or_path(target)),
}
}
fn replace_saved_annotations(s: &str) -> String {
static SAVED_IMAGE_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
regex::Regex::new(r"\n*\[Saved image: [^\]]*\]")
.expect("saved image annotation regex must compile")
});
static SAVED_VIDEO_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
regex::Regex::new(r"\[Saved video: ([^\]]*)\]")
.expect("saved video annotation regex must compile")
});
let s = SAVED_IMAGE_RE.replace_all(s, "").to_string();
SAVED_VIDEO_RE
.replace_all(&s, |caps: ®ex::Captures| {
let path = caps.get(1).map_or("", |m| m.as_str());
format!("🎬 Video: {}", file_name_or_path(path))
})
.to_string()
}
struct Edit {
range: Range<usize>,
replacement: Replacement,
}
enum Replacement {
Text(String),
Attachment(MediaAttachment),
}
fn scan(text: &str) -> (Vec<Range<usize>>, Vec<Edit>) {
let mut code = Vec::new();
let mut pictures = Vec::new();
let mut block: Option<usize> = None;
let mut picture: Option<(usize, String)> = None;
for (event, range) in
pulldown_cmark::Parser::new_ext(text, iced_markdown_options()).into_offset_iter()
{
match event {
pulldown_cmark::Event::Code(_) => code.push(range),
pulldown_cmark::Event::Start(pulldown_cmark::Tag::CodeBlock(_)) => {
block = Some(range.start);
}
pulldown_cmark::Event::End(pulldown_cmark::TagEnd::CodeBlock) => {
if let Some(start) = block.take() {
code.push(start..range.end);
}
}
pulldown_cmark::Event::Start(pulldown_cmark::Tag::Image { dest_url, .. }) => {
picture = Some((range.start, dest_url.into_string()));
}
pulldown_cmark::Event::End(pulldown_cmark::TagEnd::Image) => {
let Some((start, dest)) = picture.take() else {
continue;
};
let dest = dest.trim();
let replacement = if dest.is_empty() {
Replacement::Text(String::new())
} else {
Replacement::Attachment(picture_attachment(dest, None))
};
pictures.push(Edit {
range: start..range.end,
replacement,
});
}
_ => {}
}
}
(code, pictures)
}
fn marker_edits(text: &str, workspace: Option<&Path>, code: &[Range<usize>]) -> Vec<Edit> {
let roots: Vec<PathBuf> = workspace.map(Path::to_path_buf).into_iter().collect();
let mut edits = Vec::new();
for caps in MEDIA_MARKER_RE.captures_iter(text) {
let whole = caps.get_match();
if code.iter().any(|range| range.contains(&whole.start())) {
continue;
}
let (kind, target) = parse_media_marker(&caps);
let Some(replacement) = render_marker(kind, target, &roots) else {
continue;
};
edits.push(Edit {
range: whole.range(),
replacement,
});
}
edits
}
fn apply_edits(text: &str, edits: Vec<Edit>) -> Preprocessed {
let mut out = String::with_capacity(text.len());
let mut attachments = Vec::new();
let mut cursor = 0usize;
let mut edits = edits.into_iter().peekable();
while let Some(edit) = edits.next() {
if edit.range.start < cursor {
continue;
}
match edit.replacement {
Replacement::Text(replacement) => {
out.push_str(&text[cursor..edit.range.start]);
out.push_str(&replacement);
cursor = edit.range.end;
}
Replacement::Attachment(attachment) => {
let next_start = edits.peek().map(|next| next.range.start);
let removal = removal_range(text, &edit.range, cursor, next_start);
out.push_str(&text[cursor..removal.start]);
cursor = join_after_removal(&mut out, text, removal.end);
attachments.push(attachment);
}
}
}
out.push_str(&text[cursor..]);
Preprocessed {
text: out,
attachments,
}
}
fn removal_range(
text: &str,
range: &Range<usize>,
cursor: usize,
next_start: Option<usize>,
) -> Range<usize> {
let line_start = text[..range.start]
.rfind('\n')
.map_or(0, |newline| newline + 1);
let line_end = text[range.end..]
.find('\n')
.map_or(text.len(), |offset| range.end + offset);
let line_shared = line_start < cursor || next_start.is_some_and(|start| start < line_end);
let beside = format!(
"{}{}",
&text[line_start..range.start],
&text[range.end..line_end]
);
let alone = !line_shared && (beside.trim().is_empty() || only_list_marker(&beside));
if alone {
line_start..(line_end + 1).min(text.len())
} else {
range.clone()
}
}
fn join_after_removal(out: &mut String, text: &str, cursor: usize) -> usize {
let mut newlines = 0;
let mut opened = false;
while let Some(&byte) = out.as_bytes().last() {
if !matches!(byte, b' ' | b'\t' | b'\r' | b'\n') {
break;
}
newlines += usize::from(byte == b'\n');
opened = true;
out.pop();
}
let after = &text[cursor..];
let run = after.len() - after.trim_start_matches([' ', '\t', '\r', '\n']).len();
newlines += after[..run].matches('\n').count();
let rest = &after[run..];
match newlines {
0 => {
if (opened || run > 0) && !out.is_empty() && !rest.is_empty() {
out.push(' ');
}
}
1 => out.push('\n'),
_ => out.push_str("\n\n"),
}
cursor + run
}
fn only_list_marker(line: &str) -> bool {
let trimmed = line.trim();
if matches!(trimmed, "-" | "*" | "+") {
return true;
}
trimmed.strip_suffix(['.', ')']).is_some_and(|digits| {
!digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
})
}
const MAX_IMAGE_LONGEST_SIDE_PX: u32 = 2048;
fn downscale_raster(width: u32, height: u32, rgba: Vec<u8>) -> Option<(u32, u32, Vec<u8>)> {
if width <= MAX_IMAGE_LONGEST_SIDE_PX && height <= MAX_IMAGE_LONGEST_SIDE_PX {
return Some((width, height, rgba));
}
let img = image_crate::DynamicImage::ImageRgba8(image_crate::RgbaImage::from_raw(
width, height, rgba,
)?);
let resized = img
.thumbnail(MAX_IMAGE_LONGEST_SIDE_PX, MAX_IMAGE_LONGEST_SIDE_PX)
.into_rgba8();
Some((resized.width(), resized.height(), resized.into_raw()))
}
#[must_use]
fn render_raster(bytes: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
let (width, height, rgba) =
media_target::decode_raster_bytes(bytes, media_target::raster_decode_limits())?;
downscale_raster(width, height, rgba)
}
#[must_use]
fn decode_data_uri_image(uri: &str) -> Option<(u32, u32, Vec<u8>)> {
let (width, height, rgba) =
media_target::decode_native_data_uri(uri, media_target::raster_decode_limits())?;
downscale_raster(width, height, rgba)
}
pub(super) struct BoundedLruCache<K, V> {
entries: HashMap<K, V>,
lru: VecDeque<K>,
cap: usize,
}
impl<K, V> BoundedLruCache<K, V>
where
K: Hash + Eq + Clone,
{
pub(super) fn with_capacity(cap: usize) -> Self {
Self {
entries: HashMap::new(),
lru: VecDeque::new(),
cap,
}
}
pub(super) fn get<Q>(&mut self, key: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
let hit = self.entries.get(key);
if hit.is_some() {
if let Some(pos) = self.lru.iter().position(|k| k.borrow() == key) {
let key = self.lru.remove(pos).expect("position found by iteration");
self.lru.push_back(key);
}
}
hit
}
pub(super) fn insert(&mut self, key: K, value: V) {
if let Some(pos) = self.lru.iter().position(|k| k == &key) {
self.lru.remove(pos);
}
self.entries.insert(key.clone(), value);
self.lru.push_back(key);
while self.entries.len() > self.cap {
let oldest = self
.lru
.pop_front()
.expect("lru mirrors entries, so a front key always exists");
self.entries.remove(&oldest);
}
}
}
const MAX_CACHED_IMAGES: usize = 32;
#[derive(Debug)]
pub(super) enum CachedImage {
Decoded(image::Handle),
Failed,
}
impl CachedImage {
fn from_raster(raster: Option<(u32, u32, Vec<u8>)>) -> Self {
match raster {
Some((width, height, rgba)) => {
Self::Decoded(image::Handle::from_rgba(width, height, rgba))
}
None => Self::Failed,
}
}
fn handle(&self) -> Option<image::Handle> {
match self {
Self::Decoded(handle) => Some(handle.clone()),
Self::Failed => None,
}
}
}
static DATA_URI_IMAGE_CACHE: LazyLock<Mutex<BoundedLruCache<String, CachedImage>>> =
LazyLock::new(|| Mutex::new(BoundedLruCache::with_capacity(MAX_CACHED_IMAGES)));
#[must_use]
pub(super) fn cached_image<K, Q>(
cache: &Mutex<BoundedLruCache<K, CachedImage>>,
key: &Q,
decode: impl FnOnce() -> Option<(u32, u32, Vec<u8>)>,
) -> Option<image::Handle>
where
K: Hash + Eq + Clone + Borrow<Q>,
Q: Hash + Eq + ToOwned<Owned = K> + ?Sized,
{
if let Some(cached) = cache.lock().unwrap_poison().get(key) {
return cached.handle();
}
let outcome = CachedImage::from_raster(decode());
let handle = outcome.handle();
cache.lock().unwrap_poison().insert(key.to_owned(), outcome);
handle
}
#[must_use]
fn data_uri_image_handle(uri: &str) -> Option<image::Handle> {
media_target::data_uri_base64_payload(uri)?;
cached_image(&DATA_URI_IMAGE_CACHE, uri, || decode_data_uri_image(uri))
}
static LOCAL_IMAGE_CACHE: LazyLock<Mutex<BoundedLruCache<(PathBuf, SystemTime), CachedImage>>> =
LazyLock::new(|| Mutex::new(BoundedLruCache::with_capacity(MAX_CACHED_IMAGES)));
#[must_use]
fn local_path_image_handle(path: &str) -> Option<image::Handle> {
let p = Path::new(path);
if !p.is_absolute() {
return None;
}
let meta = std::fs::metadata(p).ok()?;
if !meta.is_file() || meta.len() > crate::util::INBOUND_IMAGE_MAX_INPUT_BYTES {
return None;
}
let mtime = meta.modified().ok()?;
let canonical = std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
cached_image(&LOCAL_IMAGE_CACHE, &(canonical.clone(), mtime), || {
std::fs::read(&canonical)
.ok()
.and_then(|b| render_raster(&b))
})
}
const FILE_LINK_PREFIX: &str = "mahbot-file:";
pub(crate) fn file_link_target(uri: &str) -> Option<&str> {
uri.strip_prefix(FILE_LINK_PREFIX)
}
fn file_link_uri(target: &str) -> String {
format!("{FILE_LINK_PREFIX}{target}")
}
fn resolve_file_marker_target(target: &str, workspace: Option<&Path>) -> Result<PathBuf, String> {
let raw = Path::new(target);
if raw.is_absolute() {
return Ok(raw.to_path_buf());
}
workspace
.map(|root| root.join(raw))
.ok_or_else(|| format!("Cannot open '{target}': the conversation's workspace is unknown."))
}
pub(crate) fn reveal_file_marker(target: &str, workspace: Option<&Path>) -> Result<(), String> {
let path = resolve_file_marker_target(target, workspace)?;
if !path.exists() {
return Err(format!("File not found: {}", path.display()));
}
if !path.is_file() {
return Err(format!("Not a file: {}", path.display()));
}
super::reveal_in_file_manager(&path)
}
#[expect(
clippy::large_types_passed_by_value,
reason = "mirrors `markdown::view`, which hands the settings over by value"
)]
pub(crate) fn body<'a, Message: 'a>(
attachments: &'a [MediaAttachment],
items: &'a [markdown::Item],
settings: markdown::Settings,
on_link_click: impl Fn(String) -> Message + Clone + 'a,
fallback: impl FnOnce() -> Element<'a, Message>,
) -> Element<'a, Message> {
let text_size = f32::from(settings.text_size);
let group = attachment_group(attachments, text_size, on_link_click.clone());
let text =
(!items.is_empty()).then(|| selectable::markdown::view(items, settings).map(on_link_click));
match (group, text) {
(Some(group), Some(text)) => Column::with_children(vec![group, text])
.spacing(theme::SPACE_6)
.into(),
(Some(group), None) => group,
(None, Some(text)) => text,
(None, None) => fallback(),
}
}
fn attachment_group<'a, Message: 'a>(
attachments: &'a [MediaAttachment],
text_size: f32,
on_link_click: impl Fn(String) -> Message + Clone + 'a,
) -> Option<Element<'a, Message>> {
if attachments.is_empty() {
return None;
}
let rows: Vec<Element<'a, Message>> = attachments
.iter()
.map(|attachment| match &attachment.image {
Some(url) => picture_row(url, &attachment.label, text_size),
None => label_row(attachment, text_size, on_link_click.clone()),
})
.collect();
Some(Column::with_children(rows).spacing(theme::SPACE_6).into())
}
fn picture_row<'a, Message: 'a>(
url: &'a str,
label: &'a str,
text_size: f32,
) -> Element<'a, Message> {
let handle = if url.starts_with("data:") {
data_uri_image_handle(url)
} else {
local_path_image_handle(url)
};
match handle {
Some(handle) => image::Image::new(handle)
.width(Length::Fill)
.content_fit(ContentFit::Contain)
.into(),
None => label_text(label, text_size),
}
}
fn label_row<'a, Message: 'a>(
attachment: &'a MediaAttachment,
text_size: f32,
on_link_click: impl Fn(String) -> Message + 'a,
) -> Element<'a, Message> {
match &attachment.reveal {
Some(target) => {
let label = text::Span::new(attachment.label.as_str()).link(file_link_uri(target));
selectable::rich_text([label])
.size(text_size)
.on_link_click(on_link_click)
.into()
}
None => label_text(&attachment.label, text_size),
}
}
fn label_text<'a, Message: 'a>(label: &'a str, text_size: f32) -> Element<'a, Message> {
widgets::selectable_text(label, theme::TEXT_PRIMARY)
.size(text_size)
.into()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::util::DATA_URI_OMITTED_PREFIX;
use base64::{Engine as _, engine::general_purpose::STANDARD};
use iced::widget::markdown;
use std::io::Cursor;
fn picture(image: Option<&str>, label: &str) -> MediaAttachment {
MediaAttachment {
image: image.map(str::to_string),
label: label.to_string(),
reveal: None,
}
}
fn named(label: &str, reveal: Option<&str>) -> MediaAttachment {
MediaAttachment {
image: None,
label: label.to_string(),
reveal: reveal.map(str::to_string),
}
}
fn img(path: &str) -> MediaAttachment {
picture(Some(path), &format!("🖼️ {}", file_name_or_path(path)))
}
fn snd(path: &str) -> MediaAttachment {
named(&format!("🎵 {}", file_name_or_path(path)), None)
}
fn clip(path: &str) -> MediaAttachment {
named(&format!("🎬 Video: {}", file_name_or_path(path)), None)
}
fn doc(path: &str, reveal: &str) -> MediaAttachment {
named(&format!("📄 {}", file_name_or_path(path)), Some(reveal))
}
fn paragraph_text(items: &[markdown::Item]) -> String {
let style = crate::gui::theme::markdown_settings().style;
items
.iter()
.filter_map(|item| match item {
markdown::Item::Paragraph(text) => Some(text.spans(style)),
_ => None,
})
.map(|spans| spans.iter().map(|s| s.text.to_string()).collect::<String>())
.collect()
}
fn only_bullet(name: &str, items: &[markdown::Item]) -> String {
let [markdown::Item::List { bullets, .. }] = items else {
panic!("case {name}: expected the list to survive, got {items:?}");
};
let [markdown::Bullet::Point { items }] = bullets.as_slice() else {
panic!("case {name}: expected one bullet, got {bullets:?}");
};
paragraph_text(items)
}
fn tiny_png(width: u32, height: u32) -> Vec<u8> {
let img = ::image::RgbaImage::from_pixel(width, height, ::image::Rgba([255, 0, 0, 255]));
let mut buf = Vec::new();
img.write_to(&mut Cursor::new(&mut buf), ::image::ImageFormat::Png)
.expect("test PNG must encode");
buf
}
fn data_uri(png: &[u8]) -> String {
format!("data:image/png;base64,{}", STANDARD.encode(png))
}
#[expect(clippy::too_many_lines)] #[test]
fn preprocess_table() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::write(root.join("photo.png"), tiny_png(2, 1)).unwrap();
std::fs::write(root.join("my file.png"), tiny_png(2, 1)).unwrap();
std::fs::write(root.join("recording.ogg"), b"ogg").unwrap();
std::fs::create_dir_all(root.join("dir/subdir")).unwrap();
std::fs::write(root.join("dir/subdir/rec.ogg"), b"ogg").unwrap();
std::fs::write(root.join("video.mp4"), b"mp4").unwrap();
std::fs::create_dir_all(root.join("generated")).unwrap();
std::fs::write(root.join("generated/report.pdf"), b"pdf").unwrap();
std::fs::write(root.join("README"), b"readme").unwrap();
std::fs::write(root.join("notes.txt"), b"not an image").unwrap();
let abs = |path: &str| root.join(path).to_string_lossy().into_owned();
let (photo_str, spaced_str) = (abs("photo.png"), abs("my file.png"));
let (report_str, readme_str) = (abs("generated/report.pdf"), abs("README"));
let (gone_str, gone_file_str) = (abs("cleaned_up.png"), abs("generated/gone.pdf"));
let not_an_image_str = abs("notes.txt");
let valid_uri = data_uri(&tiny_png(2, 1));
let cases: Vec<(&str, String, &str, Vec<MediaAttachment>)> = vec![
(
"resolves a workspace-relative image marker and takes an absolute one as it is",
format!("Look [IMAGE:photo.png] and [IMAGE:{photo_str}] here"),
"Look and here",
vec![img(&photo_str), img(&photo_str)],
),
(
"delivers markers written in lowercase",
"img [image:photo.png] hear [audio:recording.ogg]".into(),
"img hear",
vec![img(&photo_str), snd("recording.ogg")],
),
(
"draws markers whose file is gone like any missing file",
format!("see [image:cleaned_up.png] and [IMAGE:{gone_str}] here"),
"see and here",
vec![img(&gone_str), img(&gone_str)],
),
(
"resolves a relative image marker with spaces in the path",
"img [IMAGE:my file.png]".into(),
"img",
vec![img(&spaced_str)],
),
(
"draws a target that is not an image, letting the viewer show its placeholder",
format!("[IMAGE:{not_an_image_str}]"),
"",
vec![img(¬_an_image_str)],
),
(
"keeps an address it cannot show as written",
"see [IMAGE:https://exa mple.com/x.png], [FILE:https://exa mple.com/a.pdf] \
and [FILE:ftp://example.com/a.pdf] here"
.into(),
"see [IMAGE:https://exa mple.com/x.png], [FILE:https://exa mple.com/a.pdf] \
and [FILE:ftp://example.com/a.pdf] here",
Vec::new(),
),
(
"reads an address in a non-canonical scheme casing",
"see [IMAGE:HTTPS://Example.com/x.png] here".into(),
"see here",
vec![img("https://Example.com/x.png")],
),
(
"names the stripped-data-URI placeholder generically and draws nothing",
format!("Look [IMAGE:{DATA_URI_OMITTED_PREFIX} (35 bytes)>] here"),
"Look here",
vec![picture(None, "🖼️ image")],
),
(
"draws an inline image payload",
format!("Look [IMAGE:{valid_uri}] here"),
"Look here",
vec![picture(Some(&valid_uri), "🖼️ image")],
),
(
"draws an inline payload whose body holds an address",
r#"Look [IMAGE:data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>] here"#
.into(),
"Look here",
vec![picture(
Some(r#"data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>"#),
"🖼️ image",
)],
),
(
"keeps prose marker examples as written, beside a reference that draws",
"send with [IMAGE:path], [VIDEO:path] or [FILE:<path in your workspace>]; \
then [VIDEO:video.mp4]"
.into(),
"send with [IMAGE:path], [VIDEO:path] or [FILE:<path in your workspace>]; then",
vec![clip("video.mp4")],
),
(
"keeps an empty marker target as written",
"an empty [FILE: ] names nothing".into(),
"an empty [FILE: ] names nothing",
Vec::new(),
),
(
"resolves a relative audio marker",
"Listen [AUDIO:recording.ogg]".into(),
"Listen",
vec![snd("recording.ogg")],
),
(
"resolves a relative audio marker in a nested path",
"hear [AUDIO:dir/subdir/rec.ogg]".into(),
"hear",
vec![snd("dir/subdir/rec.ogg")],
),
(
"draws a missing audio marker like any missing file",
"Listen [AUDIO:gone.ogg]".into(),
"Listen",
vec![snd("gone.ogg")],
),
(
"resolves a relative video marker",
"Watch [VIDEO:video.mp4]".into(),
"Watch",
vec![clip("video.mp4")],
),
(
"names a file marker's resolved target",
"Get [FILE:generated/report.pdf]".into(),
"Get",
vec![doc("generated/report.pdf", &report_str)],
),
(
"delivers a workspace file whose name is a bare word",
"Get [FILE:README]".into(),
"Get",
vec![doc("README", &readme_str)],
),
(
"draws a file marker whose file is gone, revealing where it was",
"Get [FILE:generated/gone.pdf]".into(),
"Get",
vec![doc("generated/gone.pdf", &gone_file_str)],
),
(
"reports a file marker that names an address",
"Get [FILE:https://example.com/a.pdf]".into(),
"Get Could not send \"a.pdf\": an address is not a local file.",
Vec::new(),
),
(
"refuses a file marker's inline payload, which cannot become a file row",
"Get [FILE:data:text/plain;base64,aGVsbG8=]".into(),
"Get Could not send \"file\": it carries an inline payload, not a file.",
Vec::new(),
),
(
"replaces an audio transcription block",
"[Audio transcription of recording.ogg]: Hello world".into(),
"🔊 Hello world",
Vec::new(),
),
(
"renders every line of a multiline audio transcription under 🔊",
"[Audio transcription of voice.ogg]: Line one\nLine two".into(),
"🔊 Line one\nLine two",
Vec::new(),
),
(
"audio-transcription format contains Audio and is handled before the [AUDIO:...] pattern",
"[Audio transcription of msg.ogg]: hi there [AUDIO:recording.ogg]".into(),
"🔊 hi there",
vec![snd("recording.ogg")],
),
(
"replaces a legacy video transcription block",
"[Video transcription of clip.mp4]: A dog runs across the room.".into(),
"🎬 A dog runs across the room.",
Vec::new(),
),
(
"video-transcription format contains Video and is handled before the [VIDEO:...] pattern",
"[Video transcription of clip.mp4]: a dog [VIDEO:other.mp4]".into(),
"🎬 a dog",
vec![clip("other.mp4")],
),
(
"separates mixed image/audio/video markers from the text around them",
"![]() [IMAGE:photo.png] and [AUDIO:recording.ogg] end [VIDEO:video.mp4]".into(),
"and end",
vec![img(&photo_str), snd("recording.ogg"), clip("video.mp4")],
),
(
"drops a bullet whose only content was the picture",
"- [IMAGE:photo.png]".into(),
"",
vec![img(&photo_str)],
),
(
"keeps the rest of a list whose first bullet was a picture",
"1. [IMAGE:photo.png]\n2. the rest".into(),
"2. the rest",
vec![img(&photo_str)],
),
(
"leaves content without markers unchanged",
"Hello world".into(),
"Hello world",
Vec::new(),
),
(
"returns the empty string unchanged",
String::new(),
"",
Vec::new(),
),
(
"strips a saved image annotation and its blank-line separator",
format!("[IMAGE:{valid_uri}]\n\n[Saved image: /uploads/img.png]"),
"",
vec![picture(Some(&valid_uri), "🖼️ image")],
),
(
"strips a saved image annotation at the start with no preceding separator",
"[Saved image: /uploads/img.png]".into(),
"",
Vec::new(),
),
(
"turns a saved video annotation into a visible clip label",
"Clip [Saved video: /uploads/clip.mp4] here".into(),
"Clip 🎬 Video: clip.mp4 here",
Vec::new(),
),
];
for (name, input, text, attachments) in &cases {
let rendered = preprocess(input, Some(root));
assert_eq!(rendered.text, *text, "case {name}: text");
assert_eq!(rendered.attachments, *attachments, "case {name}: files");
}
}
#[test]
fn pictures_are_extracted_from_the_body() {
let tmp = tempfile::tempdir().unwrap();
let img = tmp.path().join("shot.png");
std::fs::write(&img, b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR").unwrap();
let img_str = img.to_string_lossy().into_owned();
let uri = data_uri(&tiny_png(2, 1));
let marker = picture(Some(&img_str), "🖼️ shot.png");
let literal = picture(Some("second.png"), "🖼️ second.png");
let cases = vec here".to_string(),
"Look here".to_string(),
vec![picture(Some("url"), "🖼️ url")],
(1, None),
),
(
"picture on its own line keeps the paragraph",
"before\n\nafter".to_string(),
"before\nafter".to_string(),
vec![picture(Some("url"), "🖼️ url")],
(1, None),
),
(
"blank lines on either side stay a paragraph gap",
"before\n\n\n\nafter".to_string(),
"before\n\nafter".to_string(),
vec![picture(Some("url"), "🖼️ url")],
(2, None),
),
(
"text beside a picture survives the parse",
format!("8. the body [IMAGE:{uri}]"),
"8. the body".to_string(),
vec![picture(Some(&uri), "🖼️ image")],
(1, Some("the body")),
),
(
"fenced code keeps its marker and image source",
format!("```\n[IMAGE:{img_str}]\n\n```"),
format!("```\n[IMAGE:{img_str}]\n\n```"),
Vec::new(),
(1, None),
),
(
"indented code keeps its marker and image source",
format!(" [IMAGE:{img_str}]\n "),
format!(" [IMAGE:{img_str}]\n "),
Vec::new(),
(1, None),
),
(
"inline code span keeps its marker and image source",
format!("use `[IMAGE:{img_str}]` and `` here"),
format!("use `[IMAGE:{img_str}]` and `` here"),
Vec::new(),
(1, None),
),
(
"body order: marker before literal picture",
format!("[IMAGE:{img_str}] and "),
"and".to_string(),
vec![marker.clone(), literal.clone()],
(1, None),
),
(
"body order: literal picture before marker",
format!(" and [IMAGE:{img_str}]"),
"and".to_string(),
vec![literal, marker],
(1, None),
),
];
for (name, body, text, attachments, (items_expected, bullet)) in cases {
let rendered = preprocess(&body, Some(tmp.path()));
assert_eq!(rendered.text, text, "case {name}: text");
assert_eq!(rendered.attachments, attachments, "case {name}: files");
if !attachments.is_empty() {
let survived = rendered.text.contains("![") || rendered.text.contains("[IMAGE:");
assert!(!survived, "case {name}: marker survived");
}
let items: Vec<_> = markdown::parse(&rendered.text).collect();
assert_eq!(items.len(), items_expected, "case {name}: items {items:?}");
if let Some(expected) = bullet {
let bullet_text = only_bullet(name, &items);
assert_eq!(bullet_text, expected, "case {name}: bullet text");
}
}
}
#[test]
fn file_marker_targets_resolve_against_the_workspace() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let relative = resolve_file_marker_target("generated/report.pdf", Some(root)).unwrap();
let expected = root.join("generated/report.pdf");
assert_eq!(
relative, expected,
"a relative target resolves against the workspace"
);
let absolute = root.join("elsewhere/report.pdf");
let resolved = resolve_file_marker_target(&absolute.to_string_lossy(), Some(root));
assert_eq!(
resolved.unwrap(),
absolute,
"an absolute target is used as it is"
);
let error = resolve_file_marker_target("report.pdf", None).unwrap_err();
let expected = "Cannot open 'report.pdf': the conversation's workspace is unknown.";
assert_eq!(error, expected);
}
#[test]
fn reveal_file_marker_refuses_a_target_that_is_not_a_file() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let missing = root.join("generated/report.pdf");
let error = reveal_file_marker("generated/report.pdf", Some(root)).unwrap_err();
let expected = format!("File not found: {}", missing.display());
assert_eq!(
error, expected,
"a relative target must resolve against the workspace"
);
std::fs::create_dir(root.join("folder")).unwrap();
let error = reveal_file_marker("folder", Some(root)).unwrap_err();
let expected = format!("Not a file: {}", root.join("folder").display());
assert_eq!(error, expected);
}
#[test]
fn file_name_or_path_table() {
let cases: &[(&str, &str, &str)] = &[
("unix path", "/foo/bar.txt", "bar.txt"),
("nested path", "/foo/bar/doc.txt", "doc.txt"),
("no directory component", "bar.txt", "bar.txt"),
("trailing slash", "/foo/bar/", "bar"),
];
for &(name, input, expected) in cases {
assert_eq!(file_name_or_path(input), expected, "case {name}");
}
}
#[test]
fn decode_data_uri_image_table() {
let valid_uri = data_uri(&tiny_png(2, 1));
let invalid_base64 = "data:image/png;base64,%%%not-base64%%%".to_string();
let non_image = format!("data:text/plain;base64,{}", STANDARD.encode(b"hello world"));
let huge_payload = format!(
"data:image/png;base64,{}",
"A".repeat(media_target::MAX_DATA_URI_ENCODED_BYTES + 1)
);
let oversized = data_uri(&tiny_png(MAX_IMAGE_LONGEST_SIDE_PX + 1, 1));
let missing_marker = "data:image/png,AAAA".to_string();
let mut jbuf = Vec::new();
::image::RgbImage::from_pixel(1, 1, ::image::Rgb([255, 0, 0]))
.write_to(&mut Cursor::new(&mut jbuf), ::image::ImageFormat::Jpeg)
.expect("test JPEG must encode");
let mismatched = format!("data:image/png;base64,{}", STANDARD.encode(&jbuf));
let rejects: &[(&str, String)] = &[
("invalid base64", invalid_base64),
("non-image bytes", non_image),
("oversized payload length", huge_payload),
("missing base64 marker", missing_marker),
("subtype mismatches bytes", mismatched),
];
for (name, uri) in rejects {
assert_eq!(decode_data_uri_image(uri), None, "case {name}");
}
let png = decode_data_uri_image(&valid_uri);
let red = vec![255, 0, 0, 255, 255, 0, 0, 255];
assert_eq!(png, Some((2, 1, red)), "case decodes a solid-red 2×1 PNG");
let downscaled = decode_data_uri_image(&oversized);
let cap = [255, 0, 0, 255].repeat(MAX_IMAGE_LONGEST_SIDE_PX as usize);
let expected = Some((MAX_IMAGE_LONGEST_SIDE_PX, 1, cap));
assert_eq!(downscaled, expected, "case downscales to the cap");
}
#[test]
fn data_uri_image_handle_caches_stable_handle() {
let uri = data_uri(&tiny_png(3, 2));
let first = data_uri_image_handle(&uri).expect("valid data URI decodes");
let second = data_uri_image_handle(&uri).expect("cached hit still decodes");
assert_eq!(first.id(), second.id());
}
#[test]
fn data_uri_image_handle_caches_failures_and_skips_oversized() {
let huge = "A".repeat(media_target::MAX_DATA_URI_ENCODED_BYTES + 1);
let cases: &[(&str, String, bool)] = &[
(
"decode failure cached",
"data:image/png;base64,%%%not-base64%%%".to_string(),
true,
),
(
"oversized payload not cached",
format!("data:image/png;base64,{huge}"),
false,
),
];
for (name, uri, failure) in cases {
assert_eq!(data_uri_image_handle(uri), None, "case {name}: handle");
let (cached, failed) = {
let cache = DATA_URI_IMAGE_CACHE.lock().unwrap_poison();
let failed = matches!(cache.entries.get(uri), Some(CachedImage::Failed));
(cache.entries.contains_key(uri), failed)
};
if *failure {
assert!(failed, "case {name}: failed decode must be cached");
} else {
assert!(!cached, "case {name}: over-cap payload must not be cached");
}
assert_eq!(
data_uri_image_handle(uri),
None,
"case {name}: answer is stable"
);
}
}
#[test]
fn bounded_cache_duplicate_insert_keeps_eviction_exact() {
let mut cache = BoundedLruCache::with_capacity(2);
cache.insert(1, "a");
cache.insert(1, "a2"); cache.insert(2, "b");
assert_eq!(cache.lru.len(), 2, "duplicate key must not survive in lru");
assert_eq!(cache.entries.len(), 2);
assert_eq!(cache.get(&2), Some(&"b"));
cache.insert(3, "c");
assert_eq!(cache.lru.len(), 2, "eviction must stay exact");
assert_eq!(cache.get(&1), None, "oldest (1) must be evicted");
assert_eq!(cache.get(&2), Some(&"b"));
assert_eq!(cache.get(&3), Some(&"c"));
}
#[test]
fn cached_image_hits_cached_failures_and_decodes_outside_the_lock() {
let cache = Mutex::new(BoundedLruCache::with_capacity(MAX_CACHED_IMAGES));
cache
.lock()
.unwrap_poison()
.insert(String::from("bad"), CachedImage::Failed);
let handle = cached_image(&cache, "bad", || {
panic!("a cached failure must not be decoded again")
});
assert!(handle.is_none(), "a cached failure yields no handle");
let handle = cached_image(&cache, "raster", || {
assert!(cache.try_lock().is_ok(), "decode must run unlocked");
Some((1, 1, vec![0, 0, 0, 0]))
});
assert!(handle.is_some(), "the decoded handle is returned");
let mut guard = cache.lock().unwrap_poison();
assert!(matches!(guard.get("raster"), Some(CachedImage::Decoded(_))));
}
}