1pub mod extract;
11pub mod kind;
12pub mod process;
13pub mod prompt;
14pub mod store;
15
16use std::collections::HashMap;
17use std::path::{Path, PathBuf};
18use std::sync::atomic::{AtomicBool, Ordering};
19use std::sync::{Arc, Mutex, OnceLock};
20use std::time::{Duration, Instant};
21
22use crate::backend::mps::Broker;
23use crate::backend::rpc_types::{
24 AttachmentBatchDoneEvent, AttachmentFailedEvent, AttachmentInfo, AttachmentPending,
25 AttachmentProgressEvent, AttachmentReadyEvent, AttachmentRejected, AttachmentsIngestResult,
26 CommandAttachmentsIngestData,
27};
28use crate::backend::wconfig::ConfigState;
29
30pub use kind::FileKind;
31pub use store::{is_valid_id, Kind, Store};
32
33pub const DEFAULT_MAX_FILES: u32 = 128;
34pub const DEFAULT_MAX_TOTAL_MB: u64 = 1024;
35pub const DEFAULT_SEND_MAX_EDGE: u32 = 2000;
36pub const DEFAULT_RETENTION_DAYS: u64 = 30;
37
38const MAX_WALK_ENTRIES: usize = 10_000;
41const DECODE_BUDGET_MIB: u32 = 2048;
45const PROGRESS_INTERVAL: Duration = Duration::from_millis(100);
47const SWEEP_INTERVAL: Duration = Duration::from_secs(6 * 60 * 60);
48
49const SKIPPED_DIRS: &[&str] = &[
53 "node_modules",
54 "target",
55 "dist",
56 "build",
57 "out",
58 "__pycache__",
59 ".venv",
60 "venv",
61 "bower_components",
62];
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct Limits {
67 pub max_files: u32,
68 pub max_total_bytes: u64,
69 pub send_max_edge: u32,
70 pub retention: Duration,
71 pub claude_inline_max: usize,
73 pub claude_session_inline_bytes: u64,
75}
76
77impl Default for Limits {
78 fn default() -> Self {
79 Self {
80 max_files: DEFAULT_MAX_FILES,
81 max_total_bytes: DEFAULT_MAX_TOTAL_MB * 1024 * 1024,
82 send_max_edge: DEFAULT_SEND_MAX_EDGE,
83 retention: Duration::from_secs(DEFAULT_RETENTION_DAYS * 24 * 3600),
84 claude_inline_max: prompt::DEFAULT_INLINE_MAX_COUNT,
85 claude_session_inline_bytes: prompt::DEFAULT_SESSION_INLINE_MB * 1024 * 1024,
86 }
87 }
88}
89
90impl Limits {
91 pub fn from_settings(extra: &HashMap<String, serde_json::Value>) -> Self {
92 let num = |k: &str| {
93 extra
94 .get(k)
95 .and_then(|v| v.as_f64())
96 .filter(|n| n.is_finite() && *n > 0.0)
97 };
98 let d = Self::default();
99 Self {
100 max_files: num("attachments:maxfiles")
101 .map(|n| n as u32)
102 .unwrap_or(d.max_files),
103 max_total_bytes: num("attachments:maxtotalmb")
104 .map(|n| (n * 1024.0 * 1024.0) as u64)
105 .unwrap_or(d.max_total_bytes),
106 send_max_edge: num("attachments:sendmaxedge")
107 .map(|n| (n as u32).clamp(256, 8000))
108 .unwrap_or(d.send_max_edge),
109 retention: num("attachments:retentiondays")
110 .map(|n| Duration::from_secs((n * 24.0 * 3600.0) as u64))
111 .unwrap_or(d.retention),
112 claude_inline_max: extra
114 .get("attachments:claudeinlinemax")
115 .and_then(|v| v.as_f64())
116 .filter(|n| n.is_finite() && *n >= 0.0)
117 .map(|n| (n as usize).min(100))
118 .unwrap_or(d.claude_inline_max),
119 claude_session_inline_bytes: extra
120 .get("attachments:claudesessioninlinemb")
121 .and_then(|v| v.as_f64())
122 .filter(|n| n.is_finite() && *n >= 0.0)
123 .map(|n| (n * 1024.0 * 1024.0) as u64)
124 .unwrap_or(d.claude_session_inline_bytes),
125 }
126 }
127}
128
129pub struct Service {
130 store: Store,
131 broker: Arc<Broker>,
132 config: Arc<ConfigState>,
133 permits: Arc<tokio::sync::Semaphore>,
135 memory: Arc<tokio::sync::Semaphore>,
137 batches: Mutex<HashMap<String, Arc<AtomicBool>>>,
139 inflight: Arc<Mutex<HashMap<String, usize>>>,
144 session_budget: Mutex<()>,
148}
149
150struct InflightGuard {
152 map: Arc<Mutex<HashMap<String, usize>>>,
153 id: String,
154}
155
156impl Drop for InflightGuard {
157 fn drop(&mut self) {
158 let mut map = self.map.lock().unwrap();
159 if let Some(n) = map.get_mut(&self.id) {
160 *n -= 1;
161 if *n == 0 {
162 map.remove(&self.id);
163 }
164 }
165 }
166}
167
168static SERVICE: OnceLock<Arc<Service>> = OnceLock::new();
169
170pub fn init(broker: Arc<Broker>, config: Arc<ConfigState>) -> Arc<Service> {
173 SERVICE
174 .get_or_init(|| {
175 let root = crate::backend::base::get_mux_data_dir().join("attachments");
176 let svc = Arc::new(Service::new(Store::new(root), broker, config));
177 svc.start_sweeper();
178 svc
179 })
180 .clone()
181}
182
183pub fn get() -> Option<Arc<Service>> {
186 SERVICE.get().cloned()
187}
188
189impl Service {
190 pub fn new(store: Store, broker: Arc<Broker>, config: Arc<ConfigState>) -> Self {
191 if let Err(e) = store.ensure_dirs() {
192 tracing::warn!(error = %e, root = %store.root().display(), "attachments: cannot create store");
193 }
194 let workers = std::thread::available_parallelism()
195 .map(|n| n.get())
196 .unwrap_or(2);
197 Self {
198 store,
199 broker,
200 config,
201 permits: Arc::new(tokio::sync::Semaphore::new((workers / 2).max(1))),
202 memory: Arc::new(tokio::sync::Semaphore::new(DECODE_BUDGET_MIB as usize)),
203 batches: Mutex::new(HashMap::new()),
204 inflight: Arc::new(Mutex::new(HashMap::new())),
205 session_budget: Mutex::new(()),
206 }
207 }
208
209 pub fn store(&self) -> &Store {
210 &self.store
211 }
212
213 pub fn limits(&self) -> Limits {
214 Limits::from_settings(&self.config.get_settings().extra)
215 }
216
217 fn start_sweeper(self: &Arc<Self>) {
218 let Ok(handle) = tokio::runtime::Handle::try_current() else {
219 return;
220 };
221 let svc = Arc::clone(self);
222 handle.spawn(async move {
223 tokio::time::sleep(Duration::from_secs(60)).await;
225 loop {
226 let store = svc.store.clone();
227 let retention = svc.limits().retention;
228 let removed = tokio::task::spawn_blocking(move || store.sweep(retention))
229 .await
230 .unwrap_or(0);
231 if removed > 0 {
232 tracing::info!(removed, "attachments: retention sweep");
233 }
234 tokio::time::sleep(SWEEP_INTERVAL).await;
235 }
236 });
237 }
238
239 pub fn ingest(self: &Arc<Self>, req: CommandAttachmentsIngestData) -> AttachmentsIngestResult {
242 let limits = self.limits();
243 let plan = plan(&req.paths, &limits, req.existing_count, req.existing_bytes);
244 let result = AttachmentsIngestResult {
245 batch_id: req.batch_id.clone(),
246 accepted: plan.accepted.clone(),
247 rejected: plan.rejected,
248 non_images: plan.non_images,
249 total_bytes: plan.accepted.iter().map(|a| a.bytes).sum(),
250 max_files: limits.max_files,
251 max_total_bytes: limits.max_total_bytes,
252 };
253 if req.dry_run || plan.accepted.is_empty() {
254 return result;
255 }
256 let cancel = Arc::new(AtomicBool::new(false));
257 self.batches
258 .lock()
259 .unwrap()
260 .insert(req.batch_id.clone(), Arc::clone(&cancel));
261 let svc = Arc::clone(self);
262 let items = plan.accepted;
263 tokio::spawn(async move {
264 svc.run_batch(req.block_id, req.batch_id, items, limits, cancel)
265 .await;
266 });
267 result
268 }
269
270 pub fn cancel(&self, batch_id: &str) -> bool {
271 match self.batches.lock().unwrap().get(batch_id) {
272 Some(flag) => {
273 flag.store(true, Ordering::SeqCst);
274 true
275 }
276 None => false,
277 }
278 }
279
280 pub async fn info(self: &Arc<Self>, ids: &[String]) -> Vec<AttachmentInfo> {
283 let mut out = Vec::with_capacity(ids.len());
284 for id in ids {
285 if let Some(meta) = self.ensure_derived(id).await {
286 out.push(meta.to_info(id, ""));
287 } else if let Some(info) = self.unread_info(id) {
288 out.push(info);
289 }
290 }
291 out
292 }
293
294 fn unread_info(&self, id: &str) -> Option<AttachmentInfo> {
297 if !self.store.is_unread(id) {
298 return None;
299 }
300 let bytes = self.store.blob_len(id)?;
301 let mime = "application/octet-stream".to_string();
302 Some(AttachmentInfo {
303 id: id.to_string(),
304 name: String::new(),
305 send_mime: mime.clone(),
306 mime,
307 bytes,
308 width: 0,
309 height: 0,
310 send_bytes: bytes,
311 send_width: 0,
312 send_height: 0,
313 first_frame_only: false,
314 kind: FileKind::Other.as_str().to_string(),
315 page_count: None,
316 text_bytes: 0,
317 text_note: None,
318 macros: false,
319 })
320 }
321
322 pub async fn ensure_derived(self: &Arc<Self>, id: &str) -> Option<store::StoredMeta> {
332 self.derive_for(id, false).await
333 }
334
335 pub async fn open_derived(self: &Arc<Self>, id: &str) -> Option<store::StoredMeta> {
338 self.derive_for(id, true).await
339 }
340
341 async fn derive_for(self: &Arc<Self>, id: &str, opened: bool) -> Option<store::StoredMeta> {
342 let edge = self.limits().send_max_edge;
343 let fp = store::fingerprint(edge);
344 if let Some(meta) = self.store.meta(id, &fp) {
345 return Some(meta);
346 }
347 if !opened && self.store.is_unread(id) {
348 return None;
349 }
350 let (blob, kind) = self.store.find_blob(id)?;
351 let _cpu = self.permits.clone().acquire_owned().await.ok()?;
352 if let Some(meta) = self.store.meta(id, &fp) {
354 return Some(meta);
355 }
356 let name = blob.file_name()?.to_string_lossy().into_owned();
357 self.derive_kind(id, blob, kind, &name, edge).await.ok()
358 }
359
360 async fn derive_kind(
364 self: &Arc<Self>,
365 id: &str,
366 blob: PathBuf,
367 kind: FileKind,
368 name: &str,
369 edge: u32,
370 ) -> Result<store::StoredMeta, process::ProcessError> {
371 let _mem = if matches!(kind, FileKind::Image(_)) {
372 let blob_for_dims = blob.clone();
373 let (w, h) = blocking(move || process::header_dimensions(&blob_for_dims)).await?;
374 self.reserve_memory(w, h).await
375 } else {
376 None
377 };
378 let svc = Arc::clone(self);
379 let (id, name) = (id.to_string(), name.to_string());
380 blocking(move || svc.store.derive_and_save(&id, &blob, kind, &name, edge)).await
381 }
382
383 pub fn refund_session_inline(&self, key: &str, bytes: u64) {
386 let _guard = self.session_budget.lock().unwrap();
387 self.store.refund_session_inline_bytes(key, bytes);
388 }
389
390 pub fn with_session_inline_budget<T>(
395 &self,
396 key: &str,
397 carry_from: Option<&str>,
398 max: u64,
399 f: impl FnOnce(u64) -> (T, u64),
400 ) -> T {
401 let _guard = self.session_budget.lock().unwrap();
402 if let Some(from) = carry_from.filter(|from| *from != key) {
403 self.store.adopt_session_inline_bytes(from, key);
404 }
405 let used = self.store.session_inline_bytes(key);
406 let (out, spent) = f(max.saturating_sub(used));
407 self.store.add_session_inline_bytes(key, spent);
408 out
409 }
410
411 pub fn send_target(&self, id: &str, name: &str) -> Option<SendTarget> {
417 let fp = store::fingerprint(self.limits().send_max_edge);
418 let meta = self.store.meta(id, &fp)?;
419 let (path, mime) = if meta.is_image() {
420 self.store.file(id, &fp, Kind::Send)?
421 } else {
422 (self.store.named_link(id, name)?, meta.mime.clone())
423 };
424 let text_path = self.store.file(id, &fp, Kind::Text).map(|(p, _)| p);
425 self.store.mark_sent(id);
426 self.store.touch(id, &fp);
427 Some(SendTarget {
428 path,
429 mime,
430 page_count: meta.page_count,
431 note: file_note(&meta, text_path.as_deref()),
432 })
433 }
434
435 pub async fn store_undecoded(self: &Arc<Self>, tmp: PathBuf, id: String, name: String) -> Result<(), process::ProcessError> {
440 let svc = Arc::clone(self);
441 blocking(move || svc.store.place_undecoded(&tmp, &id, &name)).await
442 }
443
444 pub fn stored_len(&self, id: &str) -> Option<u64> {
446 self.store.blob_len(id)
447 }
448
449 pub fn unread_target(&self, id: &str, name: &str) -> Option<SendTarget> {
455 let fp = store::fingerprint(self.limits().send_max_edge);
456 if self.store.meta(id, &fp).is_some() {
457 return self.send_target(id, name);
458 }
459 let path = self.store.named_link(id, name)?;
460 self.store.mark_sent(id);
461 Some(SendTarget {
462 path,
463 mime: "application/octet-stream".to_string(),
464 page_count: None,
465 note: Some("not opened: the sender isn't verified".to_string()),
466 })
467 }
468
469 async fn reserve_memory(&self, w: u32, h: u32) -> Option<tokio::sync::OwnedSemaphorePermit> {
471 let mib = process::decode_cost_bytes(w, h).div_ceil(1024 * 1024);
472 let mib = (mib as u32).clamp(1, DECODE_BUDGET_MIB);
473 self.memory.clone().acquire_many_owned(mib).await.ok()
474 }
475
476 pub async fn commit_upload(
479 self: &Arc<Self>,
480 tmp: PathBuf,
481 id: String,
482 name: String,
483 ) -> Result<AttachmentInfo, process::ProcessError> {
484 let _cpu =
487 self.permits
488 .clone()
489 .acquire_owned()
490 .await
491 .map_err(|_| process::ProcessError {
492 code: "cancelled",
493 message: "Cancelled.".into(),
494 })?;
495 let edge = self.limits().send_max_edge;
496 let svc = Arc::clone(self);
497 let place_id = id.clone();
498 let place_name = name.clone();
499 let (blob, kind, guard) =
500 blocking(move || svc.place_tracked(&tmp, &place_id, &place_name)).await?;
501 let fp = store::fingerprint(edge);
502 if let Some(meta) = self.store.meta(&id, &fp) {
503 self.store.touch(&id, &fp);
504 return Ok(meta.to_info(&id, &name));
505 }
506 let result = self.derive_kind(&id, blob, kind, &name, edge).await;
507 match result {
508 Ok(meta) => Ok(meta.to_info(&id, &name)),
509 Err(e) => {
510 self.discard_unprocessed(guard).await;
511 Err(e)
512 }
513 }
514 }
515
516 fn place_tracked(
519 &self,
520 tmp: &Path,
521 id: &str,
522 name: &str,
523 ) -> Result<(PathBuf, FileKind, InflightGuard), process::ProcessError> {
524 let mut map = self.inflight.lock().unwrap();
525 *map.entry(id.to_string()).or_insert(0) += 1;
526 let guard = InflightGuard {
527 map: Arc::clone(&self.inflight),
528 id: id.to_string(),
529 };
530 match self.store.place(tmp, id, name) {
531 Ok((blob, kind)) => {
532 drop(map);
533 Ok((blob, kind, guard))
534 }
535 Err(e) => {
536 drop(map);
537 drop(guard);
538 Err(e)
539 }
540 }
541 }
542
543 async fn discard_unprocessed(&self, guard: InflightGuard) {
547 let store = self.store.clone();
548 let inflight = Arc::clone(&self.inflight);
549 let _ = tokio::task::spawn_blocking(move || {
550 let map = inflight.lock().unwrap();
551 if map.get(&guard.id).copied() == Some(1) {
552 store.discard_if_unprocessed(&guard.id);
553 }
554 drop(map);
555 drop(guard);
556 })
557 .await;
558 }
559
560 async fn run_batch(
561 self: Arc<Self>,
562 block_id: String,
563 batch_id: String,
564 items: Vec<AttachmentPending>,
565 limits: Limits,
566 cancel: Arc<AtomicBool>,
567 ) {
568 let mut tasks = Vec::with_capacity(items.len());
569 for item in items {
570 let svc = Arc::clone(&self);
571 let block_id = block_id.clone();
572 let batch_id = batch_id.clone();
573 let cancel = Arc::clone(&cancel);
574 tasks.push(tokio::spawn(async move {
575 let index = item.index;
576 let outcome = svc
577 .run_item(&block_id, &batch_id, item, limits, &cancel)
578 .await;
579 match outcome {
580 Ok(info) => svc.publish::<crate::backend::mps_events::AttachmentReady>(&block_id,
581 &AttachmentReadyEvent {
582 batch_id,
583 index,
584 info,
585 },
586 ),
587 Err(e) => svc.publish::<crate::backend::mps_events::AttachmentFailed>(&block_id,
588 &AttachmentFailedEvent {
589 batch_id,
590 index,
591 code: e.code.into(),
592 error: e.message,
593 },
594 ),
595 }
596 }));
597 }
598 for t in tasks {
599 let _ = t.await;
600 }
601 self.batches.lock().unwrap().remove(&batch_id);
602 self.publish::<crate::backend::mps_events::AttachmentBatchDone>(&block_id,
603 &AttachmentBatchDoneEvent { batch_id },
604 );
605 }
606
607 async fn run_item(
612 self: &Arc<Self>,
613 block_id: &str,
614 batch_id: &str,
615 item: AttachmentPending,
616 limits: Limits,
617 cancel: &Arc<AtomicBool>,
618 ) -> Result<AttachmentInfo, process::ProcessError> {
619 let cancelled = || process::ProcessError {
620 code: "cancelled",
621 message: "Cancelled.".into(),
622 };
623 let _cpu = self
624 .permits
625 .clone()
626 .acquire_owned()
627 .await
628 .map_err(|_| cancelled())?;
629 if cancel.load(Ordering::SeqCst) {
630 return Err(cancelled());
631 }
632
633 let svc = Arc::clone(self);
634 let (block, batch, it, flag) = (
635 block_id.to_string(),
636 batch_id.to_string(),
637 item.clone(),
638 Arc::clone(cancel),
639 );
640 let placed =
641 blocking(move || svc.copy_and_place(&block, &batch, &it, limits, &flag)).await?;
642 let (id, blob, kind, guard) = placed;
643
644 let fp = store::fingerprint(limits.send_max_edge);
645 if let Some(meta) = self.store.meta(&id, &fp) {
646 self.store.touch(&id, &fp);
647 return Ok(meta.to_info(&id, &item.name));
648 }
649
650 let result = self
651 .derive_placed(block_id, batch_id, &item, &id, blob, kind, limits, cancel)
652 .await;
653 if result.is_err() {
654 self.discard_unprocessed(guard).await;
657 }
658 result
659 }
660
661 #[allow(clippy::too_many_arguments)]
664 async fn derive_placed(
665 self: &Arc<Self>,
666 block_id: &str,
667 batch_id: &str,
668 item: &AttachmentPending,
669 id: &str,
670 blob: PathBuf,
671 kind: FileKind,
672 limits: Limits,
673 cancel: &Arc<AtomicBool>,
674 ) -> Result<AttachmentInfo, process::ProcessError> {
675 let cancelled = || process::ProcessError {
676 code: "cancelled",
677 message: "Cancelled.".into(),
678 };
679 if cancel.load(Ordering::SeqCst) {
680 return Err(cancelled());
681 }
682 self.publish::<crate::backend::mps_events::AttachmentProgress>(block_id,
683 &AttachmentProgressEvent {
684 batch_id: batch_id.to_string(),
685 index: item.index,
686 stage: "processing".into(),
687 done_bytes: item.bytes,
688 total_bytes: item.bytes,
689 },
690 );
691 let meta = self
692 .derive_kind(id, blob, kind, &item.name, limits.send_max_edge)
693 .await?;
694 if cancel.load(Ordering::SeqCst) {
695 return Err(cancelled());
696 }
697 Ok(meta.to_info(id, &item.name))
698 }
699
700 fn copy_and_place(
703 &self,
704 block_id: &str,
705 batch_id: &str,
706 item: &AttachmentPending,
707 limits: Limits,
708 cancel: &AtomicBool,
709 ) -> Result<(String, PathBuf, FileKind, InflightGuard), process::ProcessError> {
710 let mut last = Instant::now() - PROGRESS_INTERVAL;
711 let copied = self.store.copy_in(Path::new(&item.path), |done| {
712 if cancel.load(Ordering::SeqCst) {
713 return false;
714 }
715 if last.elapsed() >= PROGRESS_INTERVAL || done >= item.bytes {
716 last = Instant::now();
717 self.publish::<crate::backend::mps_events::AttachmentProgress>(block_id,
718 &AttachmentProgressEvent {
719 batch_id: batch_id.to_string(),
720 index: item.index,
721 stage: "copying".into(),
722 done_bytes: done,
723 total_bytes: item.bytes,
724 },
725 );
726 }
727 done <= limits.max_total_bytes
729 });
730 let (tmp, id, _) = copied.map_err(|e| {
731 if cancel.load(Ordering::SeqCst) {
732 process::ProcessError {
733 code: "cancelled",
734 message: "Cancelled.".into(),
735 }
736 } else {
737 process::ProcessError {
738 code: "io",
739 message: format!("Couldn't read the file: {e}"),
740 }
741 }
742 })?;
743 if cancel.load(Ordering::SeqCst) {
744 let _ = std::fs::remove_file(&tmp);
745 return Err(process::ProcessError {
746 code: "cancelled",
747 message: "Cancelled.".into(),
748 });
749 }
750 let (blob, kind, guard) = self.place_tracked(&tmp, &id, &item.name)?;
751 Ok((id, blob, kind, guard))
752 }
753
754 fn publish<E: crate::backend::mps_events::Event>(&self, block_id: &str, data: &E::Payload) {
755 self.broker.publish_event::<E>(data, vec![format!("block:{block_id}")], 0);
756 }
757}
758
759#[derive(Debug, Clone, PartialEq, Eq)]
761pub struct SendTarget {
762 pub path: PathBuf,
764 pub mime: String,
765 pub page_count: Option<u32>,
766 pub note: Option<String>,
768}
769
770fn file_note(meta: &store::StoredMeta, text_path: Option<&Path>) -> Option<String> {
774 if meta.is_image() {
775 return None;
776 }
777 let mut parts: Vec<String> = Vec::new();
778 let label = match meta.kind.as_str() {
779 "pdf" => "PDF",
780 "word" => "Word document",
781 "excel" => "spreadsheet",
782 "powerpoint" => "presentation",
783 "svg" => "SVG image",
784 "archive" => "archive",
785 "audio" => "audio",
786 "video" => "video",
787 "image_file" => "image (not decoded)",
788 _ => "",
789 };
790 match (label, meta.page_count) {
791 ("", _) => {}
792 (l, Some(n)) => parts.push(format!("{l}, {n} page{}", if n == 1 { "" } else { "s" })),
793 (l, None) => parts.push(l.to_string()),
794 }
795 if let Some(p) = text_path {
796 parts.push(format!("text version: {}", p.display()));
797 } else if let Some(n) = &meta.text_note {
798 parts.push(n.clone());
799 }
800 if meta.macros {
801 parts.push("contains macros".into());
802 }
803 (!parts.is_empty()).then(|| parts.join("; "))
804}
805
806async fn blocking<T: Send + 'static>(
808 f: impl FnOnce() -> Result<T, process::ProcessError> + Send + 'static,
809) -> Result<T, process::ProcessError> {
810 tokio::task::spawn_blocking(f).await.unwrap_or_else(|e| {
811 Err(process::ProcessError {
812 code: "decode",
813 message: format!("Processing crashed: {e}"),
814 })
815 })
816}
817
818#[derive(Debug, Default)]
820pub struct Plan {
821 pub accepted: Vec<AttachmentPending>,
822 pub rejected: Vec<AttachmentRejected>,
823 pub non_images: Vec<String>,
824}
825
826fn display_name(p: &Path) -> String {
827 p.file_name()
828 .map(|n| n.to_string_lossy().into_owned())
829 .unwrap_or_else(|| p.display().to_string())
830}
831
832fn files_in_dir(dir: &Path, budget: &mut usize, out: &mut Vec<PathBuf>) {
836 let Ok(rd) = std::fs::read_dir(dir) else {
837 return;
838 };
839 let mut entries: Vec<_> = rd.filter_map(Result::ok).collect();
840 entries.sort_by_key(|e| e.file_name());
841 for e in entries {
842 if *budget == 0 {
843 return;
844 }
845 *budget -= 1;
846 let name = e.file_name().to_string_lossy().into_owned();
847 if name.starts_with('.') {
848 continue;
849 }
850 let Ok(ft) = e.file_type() else { continue };
851 let path = e.path();
852 if ft.is_dir() {
853 if !SKIPPED_DIRS.contains(&name.as_str()) {
854 files_in_dir(&path, budget, out);
855 }
856 } else if ft.is_file() {
857 out.push(path);
858 }
859 }
860}
861
862pub fn plan(paths: &[String], limits: &Limits, existing_count: u32, existing_bytes: u64) -> Plan {
866 let mut out = Plan::default();
867 let mut count = existing_count;
868 let mut bytes = existing_bytes;
869 let mut budget = MAX_WALK_ENTRIES;
870
871 let mut candidates: Vec<PathBuf> = Vec::new();
872 for raw in paths {
873 let p = PathBuf::from(raw);
874 match std::fs::metadata(&p) {
875 Ok(m) if m.is_dir() => files_in_dir(&p, &mut budget, &mut candidates),
876 Ok(m) if m.is_file() => candidates.push(p),
877 _ => out.rejected.push(AttachmentRejected {
878 path: raw.clone(),
879 name: display_name(&p),
880 code: "not_found".into(),
881 reason: "The file doesn't exist or can't be read.".into(),
882 }),
883 }
884 }
885
886 for p in candidates {
887 let name = display_name(&p);
888 let path = p.to_string_lossy().into_owned();
889 let size = match std::fs::metadata(&p) {
890 Ok(m) => m.len(),
891 Err(_) => {
892 out.rejected.push(AttachmentRejected {
893 path,
894 name,
895 code: "unreadable".into(),
896 reason: "The file can't be read.".into(),
897 });
898 continue;
899 }
900 };
901 if count >= limits.max_files {
902 out.rejected.push(AttachmentRejected {
903 path,
904 name,
905 code: "too_many".into(),
906 reason: format!(
907 "A message can carry at most {} attachments.",
908 limits.max_files
909 ),
910 });
911 continue;
912 }
913 if bytes.saturating_add(size) > limits.max_total_bytes {
914 out.rejected.push(AttachmentRejected {
915 path,
916 name,
917 code: "too_large".into(),
918 reason: format!(
919 "Adding it would pass the {} limit for one prompt.",
920 format_limit(limits.max_total_bytes)
921 ),
922 });
923 continue;
924 }
925 out.accepted.push(AttachmentPending {
926 index: out.accepted.len() as u32,
927 path,
928 name,
929 bytes: size,
930 });
931 count += 1;
932 bytes += size;
933 }
934 out
935}
936
937fn format_limit(bytes: u64) -> String {
938 const GB: u64 = 1024 * 1024 * 1024;
939 const MB: u64 = 1024 * 1024;
940 if bytes >= GB && bytes % GB == 0 {
941 format!("{} GB", bytes / GB)
942 } else {
943 format!("{} MB", bytes / MB)
944 }
945}
946
947#[cfg(test)]
948mod tests {
949 use super::*;
950
951 fn touch_file(dir: &Path, name: &str, bytes: usize) -> String {
952 let p = dir.join(name);
953 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
954 let mut data = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
956 data.resize(bytes.max(8), 0);
957 std::fs::write(&p, data).unwrap();
958 p.to_string_lossy().into_owned()
959 }
960
961 #[tokio::test]
962 async fn a_failing_job_keeps_an_original_another_job_is_still_using() {
963 let d = tempfile::tempdir().unwrap();
964 let svc = Arc::new(Service::new(
965 Store::new(d.path().join("attachments")),
966 Arc::new(Broker::new()),
967 Arc::new(ConfigState::new()),
968 ));
969 let src = touch_file(d.path(), "same.png", 64);
971 let (tmp_a, id, _) = svc.store.copy_in(Path::new(&src), |_| true).unwrap();
972 let (tmp_b, id_b, _) = svc.store.copy_in(Path::new(&src), |_| true).unwrap();
973 assert_eq!(id, id_b);
974 let (blob, _, guard_a) = svc.place_tracked(&tmp_a, &id, "same.png").unwrap();
975 let (_, _, guard_b) = svc.place_tracked(&tmp_b, &id, "same.png").unwrap();
976
977 svc.discard_unprocessed(guard_a).await;
978 assert!(blob.is_file(), "job B still needs the shared original");
979 svc.discard_unprocessed(guard_b).await;
980 assert!(!blob.is_file(), "the last failing job cleans it up");
981 assert!(svc.inflight.lock().unwrap().is_empty());
982 }
983
984 #[test]
985 fn concurrent_turns_spend_one_session_budget_once() {
986 let d = tempfile::tempdir().unwrap();
987 let svc = Arc::new(Service::new(
988 Store::new(d.path().join("attachments")),
989 Arc::new(Broker::new()),
990 Arc::new(ConfigState::new()),
991 ));
992 let turns: Vec<_> = (0..8)
994 .map(|_| {
995 let svc = Arc::clone(&svc);
996 std::thread::spawn(move || {
997 svc.with_session_inline_budget("session:s", None, 100, |budget| {
998 std::thread::sleep(Duration::from_millis(2));
999 ((), budget.min(30))
1000 })
1001 })
1002 })
1003 .collect();
1004 for t in turns {
1005 t.join().unwrap();
1006 }
1007 assert_eq!(svc.store().session_inline_bytes("session:s"), 100);
1008 }
1009
1010 #[test]
1011 fn plan_accepts_every_file() {
1012 let d = tempfile::tempdir().unwrap();
1013 let img = touch_file(d.path(), "a.png", 100);
1014 let noext = touch_file(d.path(), "screenshot", 100);
1015 let txt = d.path().join("notes.md");
1016 std::fs::write(&txt, "# hi").unwrap();
1017 let svg = d.path().join("icon.svg");
1018 std::fs::write(&svg, "<svg/>").unwrap();
1019 let (txt, svg): (String, String) =
1020 (txt.to_string_lossy().into(), svg.to_string_lossy().into());
1021 let p = plan(
1022 &[img.clone(), noext.clone(), txt.clone(), svg.clone()],
1023 &Limits::default(),
1024 0,
1025 0,
1026 );
1027 assert_eq!(
1028 p.accepted
1029 .iter()
1030 .map(|a| a.path.clone())
1031 .collect::<Vec<_>>(),
1032 vec![img, noext, txt, svg]
1033 );
1034 assert!(p.non_images.is_empty());
1035 assert!(p.rejected.is_empty());
1036 }
1037
1038 #[test]
1039 fn plan_applies_count_limit_including_existing() {
1040 let d = tempfile::tempdir().unwrap();
1041 let paths: Vec<String> = (0..5)
1042 .map(|i| touch_file(d.path(), &format!("{i}.png"), 10))
1043 .collect();
1044 let limits = Limits {
1045 max_files: 4,
1046 ..Limits::default()
1047 };
1048 let p = plan(&paths, &limits, 2, 0);
1049 assert_eq!(p.accepted.len(), 2);
1050 assert_eq!(p.rejected.len(), 3);
1051 assert!(p.rejected.iter().all(|r| r.code == "too_many"));
1052 assert_eq!(
1053 p.accepted.iter().map(|a| a.index).collect::<Vec<_>>(),
1054 vec![0, 1]
1055 );
1056 }
1057
1058 #[test]
1059 fn plan_applies_byte_limit_and_skips_only_what_does_not_fit() {
1060 let d = tempfile::tempdir().unwrap();
1061 let big = touch_file(d.path(), "big.png", 800);
1062 let small = touch_file(d.path(), "small.png", 100);
1063 let limits = Limits {
1064 max_total_bytes: 1000,
1065 ..Limits::default()
1066 };
1067 let p = plan(&[big.clone(), big.clone(), small.clone()], &limits, 0, 0);
1068 assert_eq!(
1069 p.accepted
1070 .iter()
1071 .map(|a| a.path.clone())
1072 .collect::<Vec<_>>(),
1073 vec![big, small]
1074 );
1075 assert_eq!(p.rejected.len(), 1);
1076 assert_eq!(p.rejected[0].code, "too_large");
1077 }
1078
1079 #[test]
1080 fn plan_expands_folders_sorted_skipping_hidden_and_build_trees() {
1081 let d = tempfile::tempdir().unwrap();
1082 touch_file(d.path(), "proj/b.png", 10);
1083 touch_file(d.path(), "proj/a.jpg", 10);
1084 touch_file(d.path(), "proj/.cache/x.png", 10);
1085 touch_file(d.path(), "proj/node_modules/m/index.png", 10);
1086 touch_file(d.path(), "proj/target/debug/out.png", 10);
1087 std::fs::write(d.path().join("proj/readme.txt"), "x").unwrap();
1088 std::fs::write(d.path().join("proj/.env"), "SECRET=1").unwrap();
1089 let p = plan(
1090 &[d.path().join("proj").to_string_lossy().into()],
1091 &Limits::default(),
1092 0,
1093 0,
1094 );
1095 let names: Vec<_> = p.accepted.iter().map(|a| a.name.clone()).collect();
1096 assert_eq!(names, vec!["a.jpg", "b.png", "readme.txt"]);
1097 }
1098
1099 #[test]
1100 fn plan_reports_missing_paths() {
1101 let p = plan(
1102 &["Z:/definitely/not/here.png".into()],
1103 &Limits::default(),
1104 0,
1105 0,
1106 );
1107 assert_eq!(p.rejected.len(), 1);
1108 assert_eq!(p.rejected[0].code, "not_found");
1109 }
1110
1111 #[test]
1112 fn limits_read_from_settings_with_defaults() {
1113 let mut extra = HashMap::new();
1114 assert_eq!(Limits::from_settings(&extra), Limits::default());
1115 extra.insert("attachments:maxfiles".into(), serde_json::json!(10));
1116 extra.insert("attachments:maxtotalmb".into(), serde_json::json!(50));
1117 extra.insert("attachments:sendmaxedge".into(), serde_json::json!(99999));
1118 extra.insert("attachments:retentiondays".into(), serde_json::json!(-3));
1119 let l = Limits::from_settings(&extra);
1120 assert_eq!(l.max_files, 10);
1121 assert_eq!(l.max_total_bytes, 50 * 1024 * 1024);
1122 assert_eq!(l.send_max_edge, 8000);
1123 assert_eq!(l.retention, Limits::default().retention);
1124 assert_eq!(l.claude_inline_max, prompt::DEFAULT_INLINE_MAX_COUNT);
1125 extra.insert("attachments:claudeinlinemax".into(), serde_json::json!(0));
1126 assert_eq!(
1127 Limits::from_settings(&extra).claude_inline_max,
1128 0,
1129 "0 means paths only"
1130 );
1131 }
1132}