Skip to main content

qualia_client_core/
chat_files.rs

1//! Session-scoped chat file attachments — PDF/text extraction, image sharing, vision ingest.
2
3use std::fs::{self, File, OpenOptions};
4use std::io::{BufRead, BufReader, Read, Write};
5use std::path::{Path, PathBuf};
6
7use qualia_core_db::{q_hash, wal::WriteAheadLog, NQuin};
8use serde::{Deserialize, Serialize};
9use sha2::{Digest, Sha256};
10
11use crate::chat_session::{self, SessionKind};
12
13const OBJECT_HASH_MASK: u64 = 0x0FFF_FFFF_FFFF_FFFF;
14const MAX_EXTRACTED_CHARS: usize = 512_000;
15const PREVIEW_CHARS: usize = 400;
16
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
18#[serde(rename_all = "snake_case")]
19pub enum FileVisibility {
20    OwnerOnly,
21    SessionParticipants,
22    SpecificDids,
23    PublicInSession,
24}
25
26impl FileVisibility {
27    /// `str` form.
28    pub fn as_str(&self) -> &'static str {
29        match self {
30            FileVisibility::OwnerOnly => "owner_only",
31            FileVisibility::SessionParticipants => "session_participants",
32            FileVisibility::SpecificDids => "specific_dids",
33            FileVisibility::PublicInSession => "public_in_session",
34        }
35    }
36
37    /// Constructs from str.
38    pub fn from_str(s: &str) -> Result<Self, String> {
39        match s {
40            "owner_only" => Ok(FileVisibility::OwnerOnly),
41            "session_participants" => Ok(FileVisibility::SessionParticipants),
42            "specific_dids" => Ok(FileVisibility::SpecificDids),
43            "public_in_session" => Ok(FileVisibility::PublicInSession),
44            _ => Err(format!("unknown file visibility: {s}")),
45        }
46    }
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
50pub struct ChatFileSharing {
51    pub visibility: FileVisibility,
52    pub allow_download: bool,
53    pub allow_llm_context: bool,
54    pub allow_relay_sync: bool,
55    #[serde(default = "default_chat_file_sensitivity")]
56    pub sensitivity_level: u8,
57    #[serde(default)]
58    pub allowed_dids: Vec<String>,
59    #[serde(default)]
60    pub expires_at: Option<u64>,
61}
62
63impl Default for ChatFileSharing {
64    fn default() -> Self {
65        Self {
66            visibility: FileVisibility::SessionParticipants,
67            allow_download: true,
68            allow_llm_context: true,
69            allow_relay_sync: false,
70            sensitivity_level: NQuin::SENSITIVITY_RESTRICTED,
71            allowed_dids: vec![],
72            expires_at: None,
73        }
74    }
75}
76
77/// Default sharing for a session.
78pub fn default_sharing_for_session(kind: SessionKind) -> ChatFileSharing {
79    match kind {
80        SessionKind::Solo => ChatFileSharing {
81            visibility: FileVisibility::OwnerOnly,
82            allow_download: true,
83            allow_llm_context: true,
84            allow_relay_sync: false,
85            sensitivity_level: NQuin::SENSITIVITY_CLASSIFIED,
86            allowed_dids: vec![],
87            expires_at: None,
88        },
89        SessionKind::Group => ChatFileSharing::default(),
90    }
91}
92
93#[derive(Debug, Clone, Serialize, Deserialize)]
94pub struct PdfPageExtract {
95    pub page_index: u32,
96    pub text: String,
97}
98
99#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
100#[serde(rename_all = "snake_case")]
101pub enum MediaKind {
102    #[default]
103    Document,
104    Image,
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct ParsedDocument {
109    pub media_kind: MediaKind,
110    pub mime_type: String,
111    pub extension: String,
112    pub page_count: Option<u32>,
113    pub image_width: Option<u32>,
114    pub image_height: Option<u32>,
115    pub full_text: String,
116    pub pages: Vec<PdfPageExtract>,
117    pub parse_status: String,
118    pub parse_error: Option<String>,
119    #[serde(default)]
120    pub thumbnail_rel_path: Option<String>,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct ChatFileRecord {
125    pub file_id: String,
126    pub original_name: String,
127    pub mime_type: String,
128    pub extension: String,
129    pub sha256: String,
130    pub byte_size: u64,
131    pub page_count: Option<u32>,
132    pub text_preview: String,
133    pub storage_rel_path: String,
134    pub text_rel_path: String,
135    pub author_did: String,
136    pub author_name: Option<String>,
137    pub message_lamport: Option<u64>,
138    pub attached_at: u64,
139    pub sharing: ChatFileSharing,
140    pub parse_status: String,
141    pub parse_error: Option<String>,
142    #[serde(default = "default_chat_file_sensitivity")]
143    pub sensitivity_level: u8,
144    #[serde(default)]
145    pub media_kind: MediaKind,
146    #[serde(default)]
147    pub image_width: Option<u32>,
148    #[serde(default)]
149    pub image_height: Option<u32>,
150    #[serde(default)]
151    pub thumbnail_rel_path: Option<String>,
152    #[serde(default)]
153    pub vision_lexicon_id: Option<String>,
154    #[serde(default)]
155    pub vision_facet: Option<String>,
156    #[serde(default)]
157    pub vision_status: Option<String>,
158}
159
160fn default_chat_file_sensitivity() -> u8 {
161    NQuin::SENSITIVITY_PUBLIC
162}
163
164fn infer_sensitivity_from_sharing(sharing: &ChatFileSharing) -> u8 {
165    match sharing.visibility {
166        FileVisibility::PublicInSession => NQuin::SENSITIVITY_PUBLIC,
167        FileVisibility::SessionParticipants | FileVisibility::SpecificDids => {
168            NQuin::SENSITIVITY_RESTRICTED
169        }
170        FileVisibility::OwnerOnly => NQuin::SENSITIVITY_CLASSIFIED,
171    }
172}
173
174fn clamp_sensitivity_level(level: u8) -> u8 {
175    level.min(NQuin::SENSITIVITY_CLASSIFIED)
176}
177
178fn effective_sensitivity_from_sharing(sharing: &ChatFileSharing) -> u8 {
179    let inferred = infer_sensitivity_from_sharing(sharing);
180    clamp_sensitivity_level(sharing.sensitivity_level).max(inferred)
181}
182
183fn normalize_chat_file_sensitivity(record: &mut ChatFileRecord) {
184    let effective = effective_sensitivity_from_sharing(&record.sharing);
185    record.sharing.sensitivity_level = effective;
186    if record.sensitivity_level > NQuin::SENSITIVITY_CLASSIFIED {
187        record.sensitivity_level = effective;
188        return;
189    }
190    record.sensitivity_level = clamp_sensitivity_level(record.sensitivity_level).max(effective);
191}
192
193#[derive(Debug, Clone, Serialize, Deserialize)]
194pub struct AttachChatFileResult {
195    pub file: ChatFileRecord,
196    pub message_lamport: u64,
197}
198
199fn files_index_path(storage_root: &Path, session_id: &str) -> PathBuf {
200    chat_session::chats_dir(storage_root)
201        .join(session_id)
202        .join("files.jsonl")
203}
204
205fn files_dir(storage_root: &Path, session_id: &str) -> PathBuf {
206    chat_session::chats_dir(storage_root)
207        .join(session_id)
208        .join("files")
209}
210
211fn unix_now() -> u64 {
212    std::time::SystemTime::now()
213        .duration_since(std::time::UNIX_EPOCH)
214        .unwrap_or_default()
215        .as_secs()
216}
217
218fn sha256_hex(bytes: &[u8]) -> String {
219    let digest = Sha256::digest(bytes);
220    digest.iter().map(|b| format!("{b:02x}")).collect()
221}
222
223fn extension_of(name: &str) -> String {
224    Path::new(name)
225        .extension()
226        .and_then(|s| s.to_str())
227        .unwrap_or("")
228        .to_lowercase()
229}
230
231fn mime_for_extension(ext: &str) -> &'static str {
232    match ext {
233        "pdf" => "application/pdf",
234        "txt" => "text/plain",
235        "md" | "markdown" => "text/markdown",
236        "png" => "image/png",
237        "jpg" | "jpeg" => "image/jpeg",
238        "webp" => "image/webp",
239        "gif" => "image/gif",
240        _ => "application/octet-stream",
241    }
242}
243
244/// `true` when image-extension.
245pub fn is_image_extension(ext: &str) -> bool {
246    matches!(ext, "png" | "jpg" | "jpeg" | "webp" | "gif")
247}
248
249/// `true` when image-record.
250pub fn is_image_record(record: &ChatFileRecord) -> bool {
251    record.media_kind == MediaKind::Image || is_image_extension(&record.extension)
252}
253
254/// Parses document-bytes.
255pub fn parse_document_bytes(name: &str, bytes: &[u8]) -> ParsedDocument {
256    parse_document_bytes_with_dir(name, bytes, None)
257}
258
259/// Parses document-bytes-with-dir.
260pub fn parse_document_bytes_with_dir(
261    name: &str,
262    bytes: &[u8],
263    thumb_dir: Option<&Path>,
264) -> ParsedDocument {
265    let ext = extension_of(name);
266    let mime_type = mime_for_extension(&ext).to_string();
267
268    if is_image_extension(&ext) {
269        return parse_image_bytes(bytes, mime_type, ext, thumb_dir);
270    }
271
272    if ext == "pdf" {
273        return parse_pdf_bytes(bytes, mime_type, ext);
274    }
275
276    if ext == "txt" || ext == "md" || ext == "markdown" {
277        let text = String::from_utf8_lossy(bytes).into_owned();
278        let truncated = truncate_text(&text);
279        return ParsedDocument {
280            media_kind: MediaKind::Document,
281            mime_type,
282            extension: ext,
283            page_count: None,
284            image_width: None,
285            image_height: None,
286            full_text: truncated.clone(),
287            pages: vec![],
288            parse_status: "ok".to_string(),
289            parse_error: None,
290            thumbnail_rel_path: None,
291        };
292    }
293
294    let ext_copy = ext.clone();
295    ParsedDocument {
296        media_kind: MediaKind::Document,
297        mime_type,
298        extension: ext,
299        page_count: None,
300        image_width: None,
301        image_height: None,
302        full_text: String::new(),
303        pages: vec![],
304        parse_status: "unsupported".to_string(),
305        parse_error: Some(format!("Unsupported extension for chat file: {ext_copy}")),
306        thumbnail_rel_path: None,
307    }
308}
309
310fn parse_image_bytes(
311    bytes: &[u8],
312    mime_type: String,
313    ext: String,
314    thumb_dir: Option<&Path>,
315) -> ParsedDocument {
316    match image::load_from_memory(bytes) {
317        Ok(img) => {
318            let (w, h) = (img.width(), img.height());
319            let thumb_rel = None;
320            let _ = thumb_dir;
321            let facet = format!(
322                "image attachment {w}x{h} {mime_type} sha256:{}",
323                &sha256_hex(bytes)[..16]
324            );
325            let full_text = format!(
326                "[Image attachment]\nfilename_extension: {ext}\nmime: {mime_type}\ndimensions: {w}x{h}\nsha256: {}\nvision_facet: {facet}",
327                sha256_hex(bytes)
328            );
329            ParsedDocument {
330                media_kind: MediaKind::Image,
331                mime_type,
332                extension: ext,
333                page_count: None,
334                image_width: Some(w),
335                image_height: Some(h),
336                full_text,
337                pages: vec![],
338                parse_status: "ok".to_string(),
339                parse_error: None,
340                thumbnail_rel_path: thumb_rel,
341            }
342        }
343        Err(e) => ParsedDocument {
344            media_kind: MediaKind::Image,
345            mime_type,
346            extension: ext,
347            page_count: None,
348            image_width: None,
349            image_height: None,
350            full_text: String::new(),
351            pages: vec![],
352            parse_status: "failed".to_string(),
353            parse_error: Some(format!("Image decode failed: {e}")),
354            thumbnail_rel_path: None,
355        },
356    }
357}
358
359fn write_thumbnail(dir: &Path, file_id: &str, img: &image::DynamicImage) -> Option<String> {
360    let name = format!("{file_id}_thumb.jpg");
361    let path = dir.join(&name);
362    let thumb = img.thumbnail(320, 320);
363    thumb
364        .save_with_format(&path, image::ImageFormat::Jpeg)
365        .ok()?;
366    Some(format!("files/{name}"))
367}
368
369fn parse_pdf_bytes(bytes: &[u8], mime_type: String, ext: String) -> ParsedDocument {
370    match pdf_extract::extract_text_from_mem_by_pages(bytes) {
371        Ok(pages) => {
372            let page_count = pages.len() as u32;
373            let mut full = String::new();
374            let mut page_extracts = Vec::with_capacity(pages.len());
375            for (i, page_text) in pages.into_iter().enumerate() {
376                if !full.is_empty() {
377                    full.push_str("\n\n");
378                }
379                full.push_str(&format!("--- Page {} ---\n{}", i + 1, page_text));
380                page_extracts.push(PdfPageExtract {
381                    page_index: i as u32,
382                    text: page_text,
383                });
384            }
385            let truncated = truncate_text(&full);
386            let status = if truncated.trim().is_empty() {
387                "partial"
388            } else {
389                "ok"
390            };
391            ParsedDocument {
392                media_kind: MediaKind::Document,
393                mime_type,
394                extension: ext,
395                page_count: Some(page_count),
396                image_width: None,
397                image_height: None,
398                full_text: truncated,
399                pages: page_extracts,
400                parse_status: status.to_string(),
401                parse_error: if status == "partial" {
402                    Some("PDF parsed but no extractable text (scanned image PDF)".to_string())
403                } else {
404                    None
405                },
406                thumbnail_rel_path: None,
407            }
408        }
409        Err(e) => ParsedDocument {
410            media_kind: MediaKind::Document,
411            mime_type,
412            extension: ext,
413            page_count: None,
414            image_width: None,
415            image_height: None,
416            full_text: String::new(),
417            pages: vec![],
418            parse_status: "failed".to_string(),
419            parse_error: Some(format!("{e}")),
420            thumbnail_rel_path: None,
421        },
422    }
423}
424
425fn try_vision_bind(
426    storage_root: &Path,
427    source_path: &Path,
428) -> (Option<String>, Option<String>, String) {
429    let active = crate::api::load_active_model_record_from_disk();
430    match crate::vision_ingest::ingest_image_with_active_record(
431        storage_root,
432        active,
433        source_path,
434        "ChatShare",
435    ) {
436        Ok(result) => (
437            Some(result.lexicon_id),
438            Some(result.facet),
439            "ok".to_string(),
440        ),
441        Err(e) => (None, None, format!("skipped:{e}")),
442    }
443}
444
445fn truncate_text(text: &str) -> String {
446    if text.len() <= MAX_EXTRACTED_CHARS {
447        return text.to_string();
448    }
449    let mut end = MAX_EXTRACTED_CHARS;
450    while end > 0 && !text.is_char_boundary(end) {
451        end -= 1;
452    }
453    format!("{}…", &text[..end])
454}
455
456fn preview_text(text: &str) -> String {
457    let flat = text.replace('\n', " ");
458    if flat.chars().count() <= PREVIEW_CHARS {
459        return flat;
460    }
461    flat.chars().take(PREVIEW_CHARS).collect::<String>() + "…"
462}
463
464fn load_all_records(storage_root: &Path, session_id: &str) -> Result<Vec<ChatFileRecord>, String> {
465    let path = files_index_path(storage_root, session_id);
466    if !path.is_file() {
467        return Ok(vec![]);
468    }
469    let file = File::open(path).map_err(|e| e.to_string())?;
470    let reader = BufReader::new(file);
471    let mut out = Vec::new();
472    for line in reader.lines() {
473        let line = line.map_err(|e| e.to_string())?;
474        if line.trim().is_empty() {
475            continue;
476        }
477        let mut record: ChatFileRecord = serde_json::from_str(&line).map_err(|e| e.to_string())?;
478        normalize_chat_file_sensitivity(&mut record);
479        out.push(record);
480    }
481    Ok(out)
482}
483
484fn write_all_records(
485    storage_root: &Path,
486    session_id: &str,
487    records: &[ChatFileRecord],
488) -> Result<(), String> {
489    let path = files_index_path(storage_root, session_id);
490    if let Some(parent) = path.parent() {
491        fs::create_dir_all(parent).map_err(|e| e.to_string())?;
492    }
493    let mut file = OpenOptions::new()
494        .create(true)
495        .write(true)
496        .truncate(true)
497        .open(path)
498        .map_err(|e| e.to_string())?;
499    for r in records {
500        writeln!(
501            file,
502            "{}",
503            serde_json::to_string(r).map_err(|e| e.to_string())?
504        )
505        .map_err(|e| e.to_string())?;
506    }
507    Ok(())
508}
509
510fn session_participant_dids(storage_root: &Path, session_id: &str) -> Vec<String> {
511    let Ok(session) = chat_session::load_session(storage_root, session_id) else {
512        return vec![];
513    };
514    session
515        .environment
516        .participants
517        .iter()
518        .map(|p| p.did.clone())
519        .collect()
520}
521
522/// `true` when able to view-file.
523pub fn can_view_file(
524    record: &ChatFileRecord,
525    viewer_did: &str,
526    participant_dids: &[String],
527) -> bool {
528    if record
529        .sharing
530        .expires_at
531        .is_some_and(|exp| unix_now() > exp)
532    {
533        return false;
534    }
535    if record.author_did == viewer_did {
536        return true;
537    }
538    match record.sharing.visibility {
539        FileVisibility::OwnerOnly => false,
540        FileVisibility::SessionParticipants | FileVisibility::PublicInSession => {
541            participant_dids.iter().any(|d| d == viewer_did) || participant_dids.is_empty()
542        }
543        FileVisibility::SpecificDids => record.sharing.allowed_dids.iter().any(|d| d == viewer_did),
544    }
545}
546
547/// `true` when able to use-in-llm-context.
548pub fn can_use_in_llm_context(
549    record: &ChatFileRecord,
550    viewer_did: &str,
551    participants: &[String],
552) -> bool {
553    record.sharing.allow_llm_context && can_view_file(record, viewer_did, participants)
554}
555
556/// Attaches a file to a chat.
557pub fn attach_chat_file(
558    storage_root: &Path,
559    session_id: &str,
560    source_path: &Path,
561    sharing: ChatFileSharing,
562) -> Result<AttachChatFileResult, String> {
563    if !source_path.is_file() {
564        return Err(format!("File not found: {}", source_path.display()));
565    }
566
567    let ext = extension_of(
568        source_path
569            .file_name()
570            .and_then(|s| s.to_str())
571            .unwrap_or(""),
572    );
573    if ext != "pdf" && ext != "txt" && ext != "md" && ext != "markdown" && !is_image_extension(&ext)
574    {
575        return Err(format!(
576            "Unsupported file type '.{ext}' — attach PDF, TXT, Markdown, or image (PNG/JPEG/WebP/GIF)"
577        ));
578    }
579
580    let mut bytes = Vec::new();
581    File::open(source_path)
582        .and_then(|mut f| f.read_to_end(&mut bytes))
583        .map_err(|e| e.to_string())?;
584
585    let sha = sha256_hex(&bytes);
586    let file_id = format!("{:016x}", q_hash(&format!("chatfile:{session_id}:{sha}")));
587    let original_name = source_path
588        .file_name()
589        .and_then(|s| s.to_str())
590        .unwrap_or("attachment")
591        .to_string();
592
593    let dir = files_dir(storage_root, session_id);
594    fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
595
596    let mut parsed = parse_document_bytes(&original_name, &bytes);
597    if parsed.media_kind == MediaKind::Image {
598        if let Ok(img) = image::load_from_memory(&bytes) {
599            parsed.thumbnail_rel_path = write_thumbnail(&dir, &file_id, &img);
600        }
601    }
602
603    let (vision_lexicon_id, vision_facet, vision_status) = if parsed.media_kind == MediaKind::Image
604    {
605        let (lex, facet, status) = try_vision_bind(storage_root, source_path);
606        if let Some(ref f) = facet {
607            parsed.full_text.push_str(&format!("\nvision_ingest: {f}"));
608        }
609        (lex, facet, status)
610    } else {
611        (None, None, String::new())
612    };
613
614    let bin_name = format!("{file_id}.bin");
615    let txt_name = format!("{file_id}.txt");
616    fs::write(dir.join(&bin_name), &bytes).map_err(|e| e.to_string())?;
617    fs::write(dir.join(&txt_name), &parsed.full_text).map_err(|e| e.to_string())?;
618
619    let profile = crate::user_profile::load_profile();
620    let author_name = profile
621        .sharing
622        .share_display_name
623        .then(|| profile.display_name.clone());
624
625    let text_preview = if parsed.media_kind == MediaKind::Image {
626        match (parsed.image_width, parsed.image_height) {
627            (Some(w), Some(h)) => format!("{w}×{h} {}", parsed.mime_type),
628            _ => parsed.mime_type.clone(),
629        }
630    } else {
631        preview_text(&parsed.full_text)
632    };
633
634    let mut sharing = sharing;
635    let sensitivity_level = effective_sensitivity_from_sharing(&sharing);
636    sharing.sensitivity_level = sensitivity_level;
637    let record = ChatFileRecord {
638        file_id: file_id.clone(),
639        original_name: original_name.clone(),
640        mime_type: parsed.mime_type,
641        extension: parsed.extension,
642        sha256: sha,
643        byte_size: bytes.len() as u64,
644        page_count: parsed.page_count,
645        text_preview,
646        storage_rel_path: format!("files/{bin_name}"),
647        text_rel_path: format!("files/{txt_name}"),
648        author_did: profile.public_did.clone(),
649        author_name,
650        message_lamport: None,
651        attached_at: unix_now(),
652        sharing,
653        parse_status: parsed.parse_status,
654        parse_error: parsed.parse_error,
655        sensitivity_level,
656        media_kind: parsed.media_kind,
657        image_width: parsed.image_width,
658        image_height: parsed.image_height,
659        thumbnail_rel_path: parsed.thumbnail_rel_path.clone(),
660        vision_lexicon_id: vision_lexicon_id.clone(),
661        vision_facet: vision_facet.clone(),
662        vision_status: if vision_status.is_empty() {
663            None
664        } else {
665            Some(vision_status)
666        },
667    };
668
669    let size_note = if record.media_kind == MediaKind::Image {
670        match (record.image_width, record.image_height) {
671            (Some(w), Some(h)) => format!(" ({w}×{h})"),
672            _ => String::new(),
673        }
674    } else {
675        record
676            .page_count
677            .map(|n| format!(" ({n} pages)"))
678            .unwrap_or_default()
679    };
680    let icon = if record.media_kind == MediaKind::Image {
681        "🖼️"
682    } else {
683        "📎"
684    };
685    let msg_content = format!(
686        "{icon} Attached {}: {original_name}{size_note} [{}]",
687        if record.media_kind == MediaKind::Image {
688            "image"
689        } else {
690            "file"
691        },
692        record.sharing.visibility.as_str()
693    );
694    let lamport = chat_session::append_message_with_author(
695        storage_root,
696        session_id,
697        chat_session::Role::User,
698        &msg_content,
699        None,
700        Some("chat_file".to_string()),
701        Some(profile.public_did.clone()),
702        record.author_name.clone(),
703        None,
704    )
705    .map_err(|e| e.to_string())?;
706
707    let mut record = record;
708    record.message_lamport = Some(lamport);
709
710    let mut records = load_all_records(storage_root, session_id)?;
711    records.push(record.clone());
712    write_all_records(storage_root, session_id, &records)?;
713
714    append_file_wal_quin(storage_root, session_id, &record)?;
715
716    Ok(AttachChatFileResult {
717        file: record,
718        message_lamport: lamport,
719    })
720}
721
722fn append_file_wal_quin(
723    storage_root: &Path,
724    session_id: &str,
725    record: &ChatFileRecord,
726) -> Result<(), String> {
727    let wal_path = chat_session::chats_dir(storage_root)
728        .join(session_id)
729        .join("chat.wal");
730    if !wal_path.is_file() {
731        return Ok(());
732    }
733    let subject = q_hash(&format!("chat:session:{session_id}"));
734    let predicate = q_hash("chat:hasFile");
735    let object = u64::from_str_radix(&record.file_id, 16).unwrap_or(0) & OBJECT_HASH_MASK;
736    let context = q_hash(&record.author_did);
737    let metadata = (record.byte_size.min(0x1FFF_FFFF)) << 32;
738    let parity = subject ^ predicate ^ object ^ context ^ metadata;
739    let mut quin = NQuin {
740        subject,
741        predicate,
742        object,
743        context,
744        metadata,
745        parity,
746    };
747    quin.set_sensitivity_byte(record.sensitivity_level);
748    if let Ok(mut wal) = WriteAheadLog::open(&wal_path) {
749        wal.append_mutation(&quin).map_err(|e| e.to_string())?;
750    }
751    Ok(())
752}
753
754/// Sets chat-file-sharing.
755pub fn set_chat_file_sharing(
756    storage_root: &Path,
757    session_id: &str,
758    file_id: &str,
759    sharing: ChatFileSharing,
760) -> Result<ChatFileRecord, String> {
761    let profile = crate::user_profile::load_profile();
762    let mut records = load_all_records(storage_root, session_id)?;
763    let idx = records
764        .iter()
765        .position(|r| r.file_id == file_id)
766        .ok_or_else(|| format!("Chat file not found: {file_id}"))?;
767    if records[idx].author_did != profile.public_did {
768        return Err("Only the file owner can change sharing permissions".to_string());
769    }
770    let mut sharing = sharing;
771    let sensitivity_level = effective_sensitivity_from_sharing(&sharing);
772    sharing.sensitivity_level = sensitivity_level;
773    records[idx].sharing = sharing;
774    records[idx].sensitivity_level = sensitivity_level;
775    let updated = records[idx].clone();
776    write_all_records(storage_root, session_id, &records)?;
777    Ok(updated)
778}
779
780/// Lists chat files.
781pub fn list_chat_files(
782    storage_root: &Path,
783    session_id: &str,
784    viewer_did: Option<&str>,
785) -> Result<Vec<ChatFileRecord>, String> {
786    let viewer = viewer_did
787        .map(|s| s.to_string())
788        .unwrap_or_else(|| crate::user_profile::load_profile().public_did);
789    let participants = session_participant_dids(storage_root, session_id);
790    let records = load_all_records(storage_root, session_id)?;
791    Ok(records
792        .into_iter()
793        .filter(|r| can_view_file(r, &viewer, &participants))
794        .collect())
795}
796
797/// Reads a chat file as text.
798pub fn read_file_text(
799    storage_root: &Path,
800    session_id: &str,
801    file_id: &str,
802    viewer_did: Option<&str>,
803) -> Result<String, String> {
804    let viewer = viewer_did
805        .map(|s| s.to_string())
806        .unwrap_or_else(|| crate::user_profile::load_profile().public_did);
807    let participants = session_participant_dids(storage_root, session_id);
808    let records = load_all_records(storage_root, session_id)?;
809    let record = records
810        .iter()
811        .find(|r| r.file_id == file_id)
812        .ok_or_else(|| format!("Chat file not found: {file_id}"))?;
813    if !can_view_file(record, &viewer, &participants) {
814        return Err("You do not have permission to view this file".to_string());
815    }
816    let text_path = chat_session::chats_dir(storage_root)
817        .join(session_id)
818        .join(&record.text_rel_path);
819    fs::read_to_string(text_path).map_err(|e| e.to_string())
820}
821
822/// Builds chat-files-context-block.
823pub fn build_chat_files_context_block(
824    storage_root: &Path,
825    session_id: &str,
826    max_chars: usize,
827) -> String {
828    let profile = crate::user_profile::load_profile();
829    let participants = session_participant_dids(storage_root, session_id);
830    let Ok(files) = list_chat_files(storage_root, session_id, Some(&profile.public_did)) else {
831        return String::new();
832    };
833
834    let mut lines = vec!["[Chat attached files]".to_string()];
835    let mut used = 0usize;
836
837    for f in &files {
838        if !can_use_in_llm_context(f, &profile.public_did, &participants) {
839            continue;
840        }
841        let dim = match (f.image_width, f.image_height) {
842            (Some(w), Some(h)) => format!(", {w}x{h}"),
843            _ => String::new(),
844        };
845        let header = format!(
846            "- {} ({}{}{} bytes, visibility={})",
847            f.original_name,
848            f.mime_type,
849            dim,
850            f.byte_size,
851            f.sharing.visibility.as_str()
852        );
853        used += header.len();
854        lines.push(header);
855
856        if let Some(ref facet) = f.vision_facet {
857            let line = format!("  vision_facet: {facet}");
858            used += line.len();
859            lines.push(line);
860        }
861
862        if used >= max_chars {
863            lines.push("  … (truncated)".to_string());
864            break;
865        }
866
867        if is_image_record(f) {
868            lines.push(
869                "  note: multimodal image — use active VLM mmproj when vision_status=ok"
870                    .to_string(),
871            );
872            continue;
873        }
874
875        if let Ok(text) = read_file_text(
876            storage_root,
877            session_id,
878            &f.file_id,
879            Some(&profile.public_did),
880        ) {
881            let budget = max_chars.saturating_sub(used);
882            let excerpt = if text.len() <= budget {
883                text
884            } else {
885                let mut end = budget;
886                while end > 0 && !text.is_char_boundary(end) {
887                    end -= 1;
888                }
889                format!("{}…", &text[..end])
890            };
891            used += excerpt.len();
892            lines.push(format!("  excerpt: {excerpt}"));
893        }
894    }
895
896    if lines.len() == 1 {
897        return String::new();
898    }
899    lines.join("\n")
900}
901
902/// Resolves a chat file path.
903pub fn resolve_chat_file_path(
904    storage_root: &Path,
905    session_id: &str,
906    file_id: &str,
907    variant: &str,
908    viewer_did: Option<&str>,
909) -> Result<PathBuf, String> {
910    let viewer = viewer_did
911        .map(|s| s.to_string())
912        .unwrap_or_else(|| crate::user_profile::load_profile().public_did);
913    let participants = session_participant_dids(storage_root, session_id);
914    let records = load_all_records(storage_root, session_id)?;
915    let record = records
916        .iter()
917        .find(|r| r.file_id == file_id)
918        .ok_or_else(|| format!("Chat file not found: {file_id}"))?;
919    if !can_view_file(record, &viewer, &participants) {
920        return Err("You do not have permission to view this file".to_string());
921    }
922    let rel = match variant {
923        "thumbnail" => record
924            .thumbnail_rel_path
925            .as_deref()
926            .unwrap_or(&record.storage_rel_path),
927        _ => &record.storage_rel_path,
928    };
929    Ok(chat_session::chats_dir(storage_root)
930        .join(session_id)
931        .join(rel))
932}
933
934#[cfg(test)]
935mod tests {
936    use super::*;
937    use std::env;
938
939    #[test]
940    fn default_sharing_differs_by_session_kind() {
941        let solo = default_sharing_for_session(SessionKind::Solo);
942        assert_eq!(solo.visibility, FileVisibility::OwnerOnly);
943        assert_eq!(solo.sensitivity_level, NQuin::SENSITIVITY_CLASSIFIED);
944        let group = default_sharing_for_session(SessionKind::Group);
945        assert_eq!(group.visibility, FileVisibility::SessionParticipants);
946        assert_eq!(group.sensitivity_level, NQuin::SENSITIVITY_RESTRICTED);
947    }
948
949    #[test]
950    fn parse_png_image() {
951        let img = image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 20, 30, 255]));
952        let dyn_img = image::DynamicImage::ImageRgba8(img);
953        let mut buf = Vec::new();
954        dyn_img
955            .write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
956            .expect("encode png");
957        let parsed = parse_document_bytes("snap.png", &buf);
958        assert_eq!(parsed.media_kind, MediaKind::Image);
959        assert_eq!(parsed.image_width, Some(2));
960        assert_eq!(parsed.parse_status, "ok");
961    }
962
963    #[test]
964    fn parse_txt_document() {
965        let parsed = parse_document_bytes("notes.txt", b"hello chat files");
966        assert_eq!(parsed.parse_status, "ok");
967        assert!(parsed.full_text.contains("hello"));
968    }
969
970    #[test]
971    fn sharing_permission_gate() {
972        let record = ChatFileRecord {
973            file_id: "abc".to_string(),
974            original_name: "x.pdf".to_string(),
975            mime_type: "application/pdf".to_string(),
976            extension: "pdf".to_string(),
977            sha256: "00".to_string(),
978            byte_size: 10,
979            page_count: Some(1),
980            text_preview: "p".to_string(),
981            storage_rel_path: "files/a.bin".to_string(),
982            text_rel_path: "files/a.txt".to_string(),
983            author_did: "did:owner".to_string(),
984            author_name: None,
985            message_lamport: Some(1),
986            attached_at: 0,
987            sharing: ChatFileSharing {
988                visibility: FileVisibility::OwnerOnly,
989                allow_download: false,
990                allow_llm_context: true,
991                allow_relay_sync: false,
992                sensitivity_level: NQuin::SENSITIVITY_CLASSIFIED,
993                allowed_dids: vec![],
994                expires_at: None,
995            },
996            parse_status: "ok".to_string(),
997            parse_error: None,
998            sensitivity_level: NQuin::SENSITIVITY_CLASSIFIED,
999            media_kind: MediaKind::Document,
1000            image_width: None,
1001            image_height: None,
1002            thumbnail_rel_path: None,
1003            vision_lexicon_id: None,
1004            vision_facet: None,
1005            vision_status: None,
1006        };
1007        assert!(can_view_file(&record, "did:owner", &[]));
1008        assert!(!can_view_file(&record, "did:other", &[]));
1009    }
1010
1011    #[test]
1012    fn attach_and_list_round_trip() {
1013        let mut storage = env::temp_dir();
1014        storage.push(format!("qualia-chat-files-{}", rand::random::<u32>()));
1015        let session_id =
1016            chat_session::create_session(&storage, Some("Files test".to_string()), None)
1017                .expect("create session");
1018
1019        let src = storage.join("sample.md");
1020        fs::write(&src, "# Title\n\nBody text for chat.").unwrap();
1021
1022        let sharing = default_sharing_for_session(SessionKind::Group);
1023        let attached = attach_chat_file(&storage, &session_id, &src, sharing).expect("attach");
1024        assert_eq!(attached.file.extension, "md");
1025        assert!(attached.message_lamport > 0);
1026
1027        let owner_did = attached.file.author_did.clone();
1028        let listed = list_chat_files(&storage, &session_id, Some(&owner_did)).unwrap();
1029        assert_eq!(listed.len(), 1);
1030        assert_eq!(listed[0].sensitivity_level, NQuin::SENSITIVITY_RESTRICTED);
1031
1032        let updated = set_chat_file_sharing(
1033            &storage,
1034            &session_id,
1035            &attached.file.file_id,
1036            ChatFileSharing {
1037                visibility: FileVisibility::SpecificDids,
1038                allow_download: true,
1039                allow_llm_context: false,
1040                allow_relay_sync: false,
1041                sensitivity_level: NQuin::SENSITIVITY_PUBLIC,
1042                allowed_dids: vec!["did:friend".to_string()],
1043                expires_at: None,
1044            },
1045        )
1046        .expect("set sharing");
1047        assert_eq!(updated.sharing.visibility, FileVisibility::SpecificDids);
1048        assert_eq!(updated.sensitivity_level, NQuin::SENSITIVITY_RESTRICTED);
1049        assert_eq!(
1050            updated.sharing.sensitivity_level,
1051            NQuin::SENSITIVITY_RESTRICTED
1052        );
1053    }
1054
1055    #[test]
1056    fn explicit_sensitivity_can_raise_but_not_lower_visibility_floor() {
1057        let restricted = ChatFileSharing {
1058            visibility: FileVisibility::SessionParticipants,
1059            allow_download: true,
1060            allow_llm_context: true,
1061            allow_relay_sync: false,
1062            sensitivity_level: NQuin::SENSITIVITY_CLASSIFIED,
1063            allowed_dids: vec![],
1064            expires_at: None,
1065        };
1066        assert_eq!(
1067            effective_sensitivity_from_sharing(&restricted),
1068            NQuin::SENSITIVITY_CLASSIFIED
1069        );
1070
1071        let owner_only = ChatFileSharing {
1072            visibility: FileVisibility::OwnerOnly,
1073            allow_download: true,
1074            allow_llm_context: true,
1075            allow_relay_sync: false,
1076            sensitivity_level: NQuin::SENSITIVITY_PUBLIC,
1077            allowed_dids: vec![],
1078            expires_at: None,
1079        };
1080        assert_eq!(
1081            effective_sensitivity_from_sharing(&owner_only),
1082            NQuin::SENSITIVITY_CLASSIFIED
1083        );
1084    }
1085}