subspace_dashboard/chat_input/
attachments.rs1use gpui_kit::{ClipboardEntry, ClipboardItem};
3use std::fmt;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use subspace_agent_model::{DRAFT_ATTACHMENT_LIMIT, ImageAttachment};
7
8pub const MAX_DRAFT_IMAGES: usize = 16;
9pub const ATTACHMENT_LIMIT_ERROR: &str =
10 "Image drafts are limited to 16 files and 20 MiB total. Remove an image first.";
11
12#[derive(Clone)]
13pub enum AttachmentSource {
14 Path(PathBuf),
15 ClipboardImage {
16 bytes: Arc<[u8]>,
17 mime_type: &'static str,
18 display_name: String,
19 },
20}
21
22#[derive(Clone)]
23#[non_exhaustive]
24pub struct IngestionBatch {
25 pub sources: Vec<AttachmentSource>,
26 pub notice: Option<String>,
27}
28
29impl fmt::Debug for IngestionBatch {
30 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
31 formatter
32 .debug_struct("IngestionBatch")
33 .field("source_count", &self.sources.len())
34 .field("has_notice", &self.notice.is_some())
35 .finish()
36 }
37}
38
39#[derive(Clone, Copy)]
40#[non_exhaustive]
41pub struct AttachmentBudget {
42 pub remaining_images: usize,
43 pub remaining_bytes: usize,
44 image_limit: usize,
45}
46
47impl AttachmentBudget {
48 pub fn new(remaining_images: usize, remaining_bytes: usize) -> Self {
49 Self {
50 remaining_images,
51 remaining_bytes,
52 image_limit: crate::images::MAX_ENCODED_BYTES,
53 }
54 }
55
56 pub fn with_image_limit(mut self, bytes: usize) -> Self {
57 self.image_limit = bytes;
58 self
59 }
60
61 pub fn empty_draft() -> Self {
62 Self {
63 remaining_images: MAX_DRAFT_IMAGES,
64 remaining_bytes: DRAFT_ATTACHMENT_LIMIT,
65 image_limit: crate::images::MAX_ENCODED_BYTES,
66 }
67 }
68
69 pub fn from_images(images: &[ImageAttachment]) -> Self {
70 let used_bytes = images.iter().fold(0usize, |total, image| {
71 total.saturating_add(image.data.len())
72 });
73 Self {
74 remaining_images: MAX_DRAFT_IMAGES.saturating_sub(images.len()),
75 remaining_bytes: DRAFT_ATTACHMENT_LIMIT.saturating_sub(used_bytes),
76 image_limit: crate::images::MAX_ENCODED_BYTES,
77 }
78 }
79
80 pub fn accepts(self, bytes: usize) -> bool {
81 self.remaining_images > 0 && self.remaining_bytes > 0 && bytes <= self.remaining_bytes
82 }
83
84 pub fn consume(&mut self, bytes: usize) {
85 self.remaining_images = self.remaining_images.saturating_sub(1);
86 self.remaining_bytes = self.remaining_bytes.saturating_sub(bytes);
87 }
88}
89
90pub fn path_batch(paths: impl IntoIterator<Item = PathBuf>) -> IngestionBatch {
91 let mut paths = paths.into_iter();
92 let sources = paths
93 .by_ref()
94 .take(MAX_DRAFT_IMAGES)
95 .map(AttachmentSource::Path)
96 .collect();
97 let notice = paths.next().map(|_| ATTACHMENT_LIMIT_ERROR.into());
98 IngestionBatch { sources, notice }
99}
100
101pub fn clipboard_batch(item: &ClipboardItem, budget: AttachmentBudget) -> IngestionBatch {
102 clipboard_batch_with(item, budget, |bytes| Arc::<[u8]>::from(bytes))
103}
104
105pub fn clipboard_batch_with(
106 item: &ClipboardItem,
107 mut budget: AttachmentBudget,
108 clone_bytes: impl Fn(&[u8]) -> Arc<[u8]>,
109) -> IngestionBatch {
110 let mut sources = Vec::with_capacity(MAX_DRAFT_IMAGES);
111 let mut notice = None;
112 for entry in item.entries() {
113 match entry {
114 ClipboardEntry::Image(image) if sources.len() < MAX_DRAFT_IMAGES => {
115 if budget.accepts(image.bytes.len()) && image.bytes.len() <= budget.image_limit {
116 budget.consume(image.bytes.len());
117 sources.push(AttachmentSource::ClipboardImage {
118 bytes: clone_bytes(&image.bytes),
119 mime_type: image.format.mime_type(),
120 display_name: format!("pasted-image.{}", image.format.extension()),
121 });
122 } else {
123 notice = Some(ATTACHMENT_LIMIT_ERROR.into());
124 }
125 }
126 ClipboardEntry::ExternalPaths(paths) => {
127 let available = MAX_DRAFT_IMAGES.saturating_sub(sources.len());
128 sources.extend(
129 paths
130 .0
131 .iter()
132 .take(available)
133 .cloned()
134 .map(AttachmentSource::Path),
135 );
136 if paths.0.len() > available {
137 notice = Some(ATTACHMENT_LIMIT_ERROR.into());
138 }
139 }
140 ClipboardEntry::Image(_) => notice = Some(ATTACHMENT_LIMIT_ERROR.into()),
141 ClipboardEntry::String(_) => {}
142 }
143 }
144 IngestionBatch { sources, notice }
145}
146
147impl AttachmentSource {
148 pub fn is_image(&self) -> bool {
149 match self {
150 Self::Path(path) => image_mime(path).is_some(),
151 Self::ClipboardImage { .. } => true,
152 }
153 }
154}
155
156pub fn image_mime(path: &Path) -> Option<&'static str> {
157 match path.extension()?.to_str()?.to_ascii_lowercase().as_str() {
158 "png" => Some("image/png"),
159 "jpg" | "jpeg" => Some("image/jpeg"),
160 "gif" => Some("image/gif"),
161 "webp" => Some("image/webp"),
162 _ => None,
163 }
164}
165
166#[cfg(test)]
167mod tests {
168 use super::{AttachmentBudget, clipboard_batch};
169 use gpui_kit::{ClipboardEntry, ClipboardItem, Image, ImageFormat};
170 #[test]
171 fn service_clipboard_limit_can_increase_without_changing_chat_defaults() {
172 let bytes = crate::images::MAX_ENCODED_BYTES + 1;
173 let item = ClipboardItem {
174 entries: vec![ClipboardEntry::Image(Image::from_bytes(
175 ImageFormat::Png,
176 vec![0; bytes],
177 ))],
178 };
179 assert!(
180 clipboard_batch(&item, AttachmentBudget::new(8, 32 * 1024 * 1024))
181 .sources
182 .is_empty()
183 );
184 let batch = clipboard_batch(
185 &item,
186 AttachmentBudget::new(8, 32 * 1024 * 1024).with_image_limit(10 * 1024 * 1024),
187 );
188 assert_eq!(batch.sources.len(), 1);
189 assert!(batch.notice.is_none());
190 }
191}