Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

Add exporters with ODT support and dropdown UI (#1667)

LearningCircuit5e210c477a0d
diff --git a/package-lock.json b/package-lock.json
index 23175f948d..3cec9ceb9b 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -970,6 +970,7 @@
"resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz",
"integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"@kurkle/color": "^0.3.0"
},
@@ -1022,6 +1023,7 @@
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz",
"integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==",
"license": "MIT",
+ "peer": true,
"funding": {
"type": "github",
"url": "https://github.com/sponsors/kossnocorp"
@@ -1275,6 +1277,7 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true,
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=12"
},
diff --git a/pyproject.toml b/pyproject.toml
index 57f97fe637..cdb12a8fb8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -86,6 +86,7 @@ dependencies = [
"jaraco-context>=6.1.0", # Transitive dep - pinned for GHSA-58pv-8j8x-9vj2
"apprise~=1.9",
"markdown~=3.10",
+ "pypandoc-binary~=1.16",
"datasets~=4.4",
"pyarrow~=22.0",
"langchain-experimental~=0.4",
diff --git a/src/local_deep_research/exporters/__init__.py b/src/local_deep_research/exporters/__init__.py
new file mode 100644
index 0000000000..2c7100a2cf
--- /dev/null
+++ b/src/local_deep_research/exporters/__init__.py
@@ -0,0 +1,41 @@
+"""Document exporters package.
+
+This package provides a modular system for exporting research reports
+to various document formats (PDF, ODT, LaTeX, etc.).
+
+Example usage:
+ from local_deep_research.exporters import ExporterRegistry, ExportOptions
+
+ # Get an exporter
+ exporter = ExporterRegistry.get_exporter("pdf")
+
+ # Export content
+ options = ExportOptions(title="My Research Report")
+ result = exporter.export(markdown_content, options)
+
+ # Use the result - content is available in memory as bytes
+ # result.content contains the file bytes
+ # result.filename is the suggested filename
+ # result.mimetype is the MIME type for HTTP responses
+
+Available formats can be queried with:
+ ExporterRegistry.get_available_formats()
+"""
+
+from .base import BaseExporter, ExportOptions, ExportResult
+from .registry import ExporterRegistry
+
+# Import all exporters to trigger registration
+# These imports must come after the base and registry imports
+from . import latex_exporter # noqa: F401
+from . import odt_exporter # noqa: F401
+from . import pdf_exporter # noqa: F401
+from . import quarto_exporter # noqa: F401
+from . import ris_exporter # noqa: F401
+
+__all__ = [
+ "BaseExporter",
+ "ExportOptions",
+ "ExportResult",
+ "ExporterRegistry",
+]
diff --git a/src/local_deep_research/exporters/base.py b/src/local_deep_research/exporters/base.py
new file mode 100644
index 0000000000..4c4ba82dec
--- /dev/null
+++ b/src/local_deep_research/exporters/base.py
@@ -0,0 +1,141 @@
+"""Base classes for document exporters.
+
+This module provides the abstract base class and data structures that all
+exporters must implement to participate in the export system.
+"""
+
+import re
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from typing import Any, Dict, Optional
+
+
+@dataclass
+class ExportResult:
+ """Result of an export operation."""
+
+ content: bytes
+ filename: str
+ mimetype: str
+
+
+@dataclass
+class ExportOptions:
+ """Common options for all exporters.
+
+ Attributes:
+ title: Optional document title
+ metadata: Optional metadata dict (author, date, etc.)
+ custom_options: Format-specific options (e.g., custom_css for PDF)
+ """
+
+ title: Optional[str] = None
+ metadata: Optional[Dict[str, Any]] = None
+ custom_options: Optional[Dict[str, Any]] = field(default_factory=dict)
+
+
+class BaseExporter(ABC):
+ """Abstract base class for document exporters.
+
+ All exporters must inherit from this class and implement the required
+ abstract methods to participate in the export registry.
+
+ Example:
+ class MyExporter(BaseExporter):
+ @property
+ def format_name(self) -> str:
+ return "myformat"
+
+ @property
+ def file_extension(self) -> str:
+ return ".myf"
+
+ @property
+ def mimetype(self) -> str:
+ return "application/x-myformat"
+
+ def export(self, markdown_content, options=None) -> ExportResult:
+ # Implementation here
+ ...
+ """
+
+ @property
+ @abstractmethod
+ def format_name(self) -> str:
+ """Return the format identifier (e.g., 'pdf', 'odt', 'latex').
+
+ This is used to look up the exporter in the registry.
+ """
+ pass
+
+ @property
+ @abstractmethod
+ def file_extension(self) -> str:
+ """Return the file extension including the dot (e.g., '.pdf', '.odt')."""
+ pass
+
+ @property
+ @abstractmethod
+ def mimetype(self) -> str:
+ """Return the MIME type for the exported file."""
+ pass
+
+ @abstractmethod
+ def export(
+ self,
+ markdown_content: str,
+ options: Optional[ExportOptions] = None,
+ ) -> ExportResult:
+ """Export markdown content to the target format.
+
+ Args:
+ markdown_content: The markdown text to convert
+ options: Optional export options
+
+ Returns:
+ ExportResult with content bytes, filename, and mimetype
+ """
+ pass
+
+ def _generate_safe_filename(self, title: Optional[str]) -> str:
+ """Generate a safe filename from the title.
+
+ Args:
+ title: Optional title to use in the filename
+
+ Returns:
+ A sanitized filename with the appropriate extension
+ """
+ if title:
+ safe_title = (
+ re.sub(r"[^\w\s-]", "", title).strip().replace(" ", "_")[:50]
+ )
+ else:
+ safe_title = "research_report"
+ return f"{safe_title}{self.file_extension}"
+
+ def _prepend_title_if_needed(
+ self, content: str, title: Optional[str]
+ ) -> str:
+ """Prepend title as H1 heading if content doesn't already have one.
+
+ This method is used by exporters that render markdown documents
+ (like PDF and ODT) to ensure the title appears in the output.
+ Exporters that don't render documents (like RIS) should not use this.
+
+ Args:
+ content: The markdown content
+ title: Optional title to prepend
+
+ Returns:
+ Content with title prepended if needed, otherwise unchanged
+ """
+ if not title:
+ return content
+ # Don't prepend if content already starts with this title
+ if content.startswith(f"# {title}"):
+ return content
+ # Only prepend if content doesn't start with any heading
+ if not content.lstrip().startswith("#"):
+ return f"# {title}\n\n{content}"
+ return content
diff --git a/src/local_deep_research/exporters/latex_exporter.py b/src/local_deep_research/exporters/latex_exporter.py
new file mode 100644
index 0000000000..5417e6b789
--- /dev/null
+++ b/src/local_deep_research/exporters/latex_exporter.py
@@ -0,0 +1,89 @@
+"""LaTeX export service.
+
+This module provides the LaTeXExporter class that wraps the existing
+LaTeXExporter implementation from text_optimization.citation_formatter.
+"""
+
+from typing import Optional
+
+from loguru import logger
+
+from .base import BaseExporter, ExportOptions, ExportResult
+from .registry import ExporterRegistry
+
+# Maximum content size (50 MB) to prevent OOM errors
+MAX_CONTENT_SIZE = 50 * 1024 * 1024
+
+
+class LaTeXExporter(BaseExporter):
+ """LaTeX exporter using the existing LaTeXExporter implementation.
+
+ This exporter converts markdown content to LaTeX format suitable for
+ compilation with pdflatex or similar LaTeX processors.
+ """
+
+ def __init__(self):
+ """Initialize LaTeX exporter."""
+ # Import here to avoid circular imports
+ from ..text_optimization.citation_formatter import (
+ LaTeXExporter as LegacyLaTeXExporter,
+ )
+
+ self._legacy = LegacyLaTeXExporter()
+
+ @property
+ def format_name(self) -> str:
+ return "latex"
+
+ @property
+ def file_extension(self) -> str:
+ return ".tex"
+
+ @property
+ def mimetype(self) -> str:
+ return "text/plain"
+
+ def export(
+ self,
+ markdown_content: str,
+ options: Optional[ExportOptions] = None,
+ ) -> ExportResult:
+ """Convert markdown content to LaTeX.
+
+ Args:
+ markdown_content: The markdown text to convert
+ options: Optional export options (title, metadata)
+
+ Returns:
+ ExportResult with LaTeX content as UTF-8 bytes, filename, and mimetype
+
+ Raises:
+ ValueError: If content exceeds maximum size limit
+ """
+ try:
+ # Check content size limit to prevent OOM errors
+ if len(markdown_content) > MAX_CONTENT_SIZE:
+ raise ValueError(
+ f"Content exceeds maximum size of "
+ f"{MAX_CONTENT_SIZE // (1024 * 1024)} MB"
+ )
+
+ options = options or ExportOptions()
+
+ content = self._legacy.export_to_latex(markdown_content)
+ filename = self._generate_safe_filename(options.title)
+
+ logger.info(
+ f"Generated LaTeX in memory, size: {len(content)} bytes"
+ )
+
+ return ExportResult(
+ content=content.encode("utf-8"),
+ filename=filename,
+ mimetype=self.mimetype,
+ )
+
+ except Exception as e:
+ logger.exception(f"Error generating LaTeX: {str(e)}")
+ raise
diff --git a/src/local_deep_research/exporters/odt_exporter.py b/src/local_deep_research/exporters/odt_exporter.py
new file mode 100644
index 0000000000..34cca3cbc6
--- /dev/null
+++ b/src/local_deep_research/exporters/odt_exporter.py
@@ -0,0 +1,196 @@
+"""ODT export service using pypandoc.
+
+This module provides the ODTExporter class for converting markdown content
+to OpenDocument Text (ODT) format using pypandoc (Pandoc wrapper).
+
+Pandoc is the industry standard for document conversion and handles all
+markdown features natively. Note: Requires Pandoc to be installed on the
+system or use pypandoc_binary which bundles it.
+"""
+
+import subprocess
+from typing import Optional
+
+from loguru import logger
+
+# pypandoc is optional - used only to locate the bundled pandoc binary
+try:
+ import pypandoc
+
+ PYPANDOC_AVAILABLE = True
+except ImportError:
+ pypandoc = None
+ PYPANDOC_AVAILABLE = False
+
+from .base import BaseExporter, ExportOptions, ExportResult
+from .registry import ExporterRegistry
+
+# Maximum content size (50 MB) to prevent OOM errors
+MAX_CONTENT_SIZE = 50 * 1024 * 1024
+
+
+class ODTExporter(BaseExporter):
+ """Service for converting markdown to ODT using pypandoc.
+
+ This exporter uses Pandoc (via pypandoc) to convert markdown content
+ to OpenDocument Text format, which can be opened in LibreOffice Writer,
+ Microsoft Word, and other office applications.
+
+ Pandoc is the industry standard for document conversion and handles
+ all markdown features (tables, code blocks, lists, etc.) natively.
+
+ The conversion is performed entirely in memory by piping markdown
+ to pandoc's stdin and capturing ODT output from stdout.
+ """
+
+ @property
+ def format_name(self) -> str:
+ return "odt"
+
+ @property
+ def file_extension(self) -> str:
+ return ".odt"
+
+ @property
+ def mimetype(self) -> str:
+ return "application/vnd.oasis.opendocument.text"
+
+ def export(
+ self,
+ markdown_content: str,
+ options: Optional[ExportOptions] = None,
+ ) -> ExportResult:
+ """Convert markdown content to ODT using Pandoc.
+
+ The conversion runs entirely in memory: markdown is piped to
+ pandoc's stdin and ODT bytes are captured from stdout, avoiding
+ any temporary files on disk.
+
+ Args:
+ markdown_content: The markdown text to convert
+ options: Optional export options (title, metadata)
+
+ Returns:
+ ExportResult with ODT content as bytes, filename, and mimetype
+
+ Raises:
+ ValueError: If content exceeds maximum size limit
+ RuntimeError: If Pandoc conversion fails
+ """
+ try:
+ # Check if pypandoc is available
+ if not PYPANDOC_AVAILABLE:
+ raise RuntimeError(
+ "ODT export requires pypandoc. Install with: pip install pypandoc-binary"
+ )
+
+ # Check content size limit to prevent OOM errors
+ if len(markdown_content) > MAX_CONTENT_SIZE:
+ raise ValueError(
+ f"Content exceeds maximum size of "
+ f"{MAX_CONTENT_SIZE // (1024 * 1024)} MB"
+ )
+
+ options = options or ExportOptions()
+
+ # Prepend title if needed (for document formats like ODT)
+ markdown_content = self._prepend_title_if_needed(
+ markdown_content, options.title
+ )
+
+ # Add LDR attribution footer
+ content_with_footer = self._add_footer(markdown_content)
+
+ # Build pandoc args for metadata (sanitized)
+ extra_args = []
+ if options.title:
+ safe_title = self._sanitize_metadata(options.title)
+ extra_args.append(f"--metadata=title:{safe_title}")
+ if options.metadata:
+ if options.metadata.get("author"):
+ safe_author = self._sanitize_metadata(
+ options.metadata["author"]
+ )
+ extra_args.append(f"--metadata=author:{safe_author}")
+ if options.metadata.get("date"):
+ safe_date = self._sanitize_metadata(
+ options.metadata["date"]
+ )
+ extra_args.append(f"--metadata=date:{safe_date}")
+
+ # Convert in memory: pipe markdown via stdin, capture ODT from stdout
+ pandoc_path = pypandoc.get_pandoc_path()
+ cmd = [pandoc_path, "-f", "markdown", "-t", "odt", "-o", "-"]
+ cmd.extend(extra_args)
+
+ result = subprocess.run(
+ cmd,
+ input=content_with_footer.encode("utf-8"),
+ capture_output=True,
+ check=True,
+ )
+
+ odt_bytes = result.stdout
+
+ if not odt_bytes:
+ raise RuntimeError(
+ "Pandoc conversion failed - no output produced"
+ )
+
+ filename = self._generate_safe_filename(options.title)
+
+ logger.info(
+ f"Generated ODT in memory, size: {len(odt_bytes)} bytes"
+ )
+
+ return ExportResult(
+ content=odt_bytes,
+ filename=filename,
+ mimetype=self.mimetype,
+ )
+
+ except subprocess.CalledProcessError as e:
+ stderr = (
+ e.stderr.decode("utf-8", errors="replace")
+ if e.stderr
+ else "unknown error"
+ )
+ logger.exception(f"Pandoc conversion failed: {stderr}")
+ raise RuntimeError(f"Pandoc conversion failed: {stderr}") from e
+ except Exception as e:
+ logger.exception(f"Error generating ODT: {str(e)}")
+ raise
+
+ def _add_footer(self, markdown_content: str) -> str:
+ """Add LDR attribution footer to markdown content.
+
+ Args:
+ markdown_content: The original markdown text
+
+ Returns:
+ Markdown with footer appended
+ """
+ footer = (
+ "\n\n---\n\n"
+ "*Generated by [LDR - Local Deep Research]"
+ "(https://github.com/LearningCircuit/local-deep-research) | "
+ "Open Source AI Research Assistant*"
+ )
+ return markdown_content + footer
+
+ def _sanitize_metadata(self, value: str) -> str:
+ """Sanitize metadata value to prevent argument injection.
+
+ Removes potential pandoc argument injection patterns from user-supplied
+ metadata values.
+
+ Args:
+ value: The metadata value to sanitize
+
+ Returns:
+ Sanitized metadata value safe for pandoc arguments
+ """
+ # Remove potential argument injection patterns
+ safe_value = value.replace("--", "").replace("\n", " ")
+ return safe_value
diff --git a/src/local_deep_research/exporters/pdf_exporter.py b/src/local_deep_research/exporters/pdf_exporter.py
new file mode 100644
index 0000000000..df63a91f61
--- /dev/null
+++ b/src/local_deep_research/exporters/pdf_exporter.py
@@ -0,0 +1,108 @@
+"""PDF export service wrapper.
+
+This module provides the PDFExporter class that wraps the existing
+PDFService implementation from web/services/pdf_service.py.
+
+The existing PDFService is kept unchanged - this is just a wrapper
+to integrate it with the modular exporter registry.
+"""
+
+from typing import Optional
+
+from loguru import logger
+
+from .base import BaseExporter, ExportOptions, ExportResult
+from .registry import ExporterRegistry
+
+# Maximum content size (50 MB) to prevent OOM errors
+MAX_CONTENT_SIZE = 50 * 1024 * 1024
+
+
+class PDFExporter(BaseExporter):
+ """PDF exporter wrapping the existing PDFService implementation.
+
+ This exporter delegates to the existing PDFService which uses
+ WeasyPrint for PDF generation. No changes are made to the
+ underlying PDF generation logic.
+ """
+
+ def __init__(self):
+ """Initialize PDF exporter."""
+ # Import here to avoid circular imports
+ from ..web.services.pdf_service import get_pdf_service
+
+ self._pdf_service = get_pdf_service()
+
+ @property
+ def format_name(self) -> str:
+ return "pdf"
+
+ @property
+ def file_extension(self) -> str:
+ return ".pdf"
+
+ @property
+ def mimetype(self) -> str:
+ return "application/pdf"
+
+ def export(
+ self,
+ markdown_content: str,
+ options: Optional[ExportOptions] = None,
+ ) -> ExportResult:
+ """Convert markdown content to PDF using existing PDFService.
+
+ Args:
+ markdown_content: The markdown text to convert
+ options: Optional export options (title, metadata, custom_css)
+
+ Returns:
+ ExportResult with PDF content as bytes, filename, and mimetype
+
+ Raises:
+ ValueError: If content exceeds maximum size limit
+ """
+ try:
+ # Check content size limit to prevent OOM errors
+ if len(markdown_content) > MAX_CONTENT_SIZE:
+ raise ValueError(
+ f"Content exceeds maximum size of "
+ f"{MAX_CONTENT_SIZE // (1024 * 1024)} MB"
+ )
+
+ options = options or ExportOptions()
+
+ # Prepend title if needed (for document formats like PDF)
+ markdown_content = self._prepend_title_if_needed(
+ markdown_content, options.title
+ )
+
+ # Extract custom_css if provided
+ custom_css = None
+ if options.custom_options:
+ custom_css = options.custom_options.get("custom_css")
+
+ # Delegate to existing PDFService
+ pdf_bytes = self._pdf_service.markdown_to_pdf(
+ markdown_content,
+ title=options.title,
+ metadata=options.metadata,
+ custom_css=custom_css,
+ )
+
+ filename = self._generate_safe_filename(options.title)
+
+ logger.info(
+ f"Generated PDF in memory, size: {len(pdf_bytes)} bytes"
+ )
+
+ return ExportResult(
+ content=pdf_bytes,
+ filename=filename,
+ mimetype=self.mimetype,
+ )
+
+ except Exception as e:
+ logger.exception(f"Error generating PDF: {str(e)}")
+ raise
diff --git a/src/local_deep_research/exporters/quarto_exporter.py b/src/local_deep_research/exporters/quarto_exporter.py
new file mode 100644
index 0000000000..08fc8cdb86
--- /dev/null
+++ b/src/local_deep_research/exporters/quarto_exporter.py
@@ -0,0 +1,131 @@
+"""Quarto export service.
+
+This module provides the QuartoExporter class that wraps the existing
+QuartoExporter implementation from text_optimization.citation_formatter.
+"""
+
+import io
+import re
+import zipfile
+from typing import Optional
+
+from loguru import logger
+
+from .base import BaseExporter, ExportOptions, ExportResult
+from .registry import ExporterRegistry
+
+# Maximum content size (50 MB) to prevent OOM errors
+MAX_CONTENT_SIZE = 50 * 1024 * 1024
+
+
+class QuartoExporter(BaseExporter):
+ """Quarto exporter using the existing QuartoExporter implementation.
+
+ This exporter converts markdown content to Quarto (.qmd) format,
+ which can be rendered to HTML, PDF, or other formats using the
+ Quarto publishing system.
+
+ The export produces a ZIP file containing:
+ - The .qmd document
+ - A references.bib bibliography file
+ """
+
+ def __init__(self):
+ """Initialize Quarto exporter."""
+ # Import here to avoid circular imports
+ from ..text_optimization.citation_formatter import (
+ QuartoExporter as LegacyQuartoExporter,
+ )
+
+ self._legacy = LegacyQuartoExporter()
+
+ @property
+ def format_name(self) -> str:
+ return "quarto"
+
+ @property
+ def file_extension(self) -> str:
+ return ".zip"
+
+ @property
+ def mimetype(self) -> str:
+ return "application/zip"
+
+ def export(
+ self,
+ markdown_content: str,
+ options: Optional[ExportOptions] = None,
+ ) -> ExportResult:
+ """Convert markdown content to Quarto format.
+
+ Args:
+ markdown_content: The markdown text to convert
+ options: Optional export options (title, metadata)
+
+ Returns:
+ ExportResult with ZIP content as bytes containing .qmd and .bib files
+
+ Raises:
+ ValueError: If content exceeds maximum size limit
+ """
+ try:
+ # Check content size limit to prevent OOM errors
+ if len(markdown_content) > MAX_CONTENT_SIZE:
+ raise ValueError(
+ f"Content exceeds maximum size of "
+ f"{MAX_CONTENT_SIZE // (1024 * 1024)} MB"
+ )
+
+ options = options or ExportOptions()
+
+ # Extract title from markdown if not provided
+ title = options.title
+ if not title:
+ title_match = re.search(
+ r"^#\s+(.+)$", markdown_content, re.MULTILINE
+ )
+ title = (
+ title_match.group(1) if title_match else "Research Report"
+ )
+
+ # Generate Quarto document
+ exported_content = self._legacy.export_to_quarto(
+ markdown_content, title
+ )
+
+ # Generate bibliography
+ bib_content = self._legacy._generate_bibliography(markdown_content)
+
+ # Use base class method for safe filename generation, then extract base name
+ base_filename = self._generate_safe_filename(options.title)
+ # Remove the .zip extension that _generate_safe_filename adds
+ safe_title = base_filename.replace(self.file_extension, "")
+
+ # Create a zip file in memory containing both files
+ zip_buffer = io.BytesIO()
+ with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf:
+ # Add the Quarto document
+ zipf.writestr(f"{safe_title}.qmd", exported_content)
+ # Add the bibliography file
+ zipf.writestr("references.bib", bib_content)
+
+ zip_bytes = zip_buffer.getvalue()
+ zip_buffer.close()
+
+ filename = f"{safe_title}_quarto.zip"
+
+ logger.info(
+ f"Generated Quarto with bibliography in memory (zip), "
+ f"size: {len(zip_bytes)} bytes"
+ )
+
+ return ExportResult(
+ content=zip_bytes,
+ filename=filename,
+ mimetype=self.mimetype,
+ )
+
+ except Exception as e:
+ logger.exception(f"Error generating Quarto: {str(e)}")
+ raise
diff --git a/src/local_deep_research/exporters/registry.py b/src/local_deep_research/exporters/registry.py
new file mode 100644
index 0000000000..b3e7202d2b
--- /dev/null
+++ b/src/local_deep_research/exporters/registry.py
@@ -0,0 +1,110 @@
+"""Exporter registry for document format discovery.
+
+This module provides the ExporterRegistry class that manages exporter
+registration and lookup. Exporters can be registered using the @register
+decorator for automatic discovery.
+"""
+
+from typing import Dict, List, Optional, Type
+
+from loguru import logger
+
+from .base import BaseExporter
+
+
+class ExporterRegistry:
+ """Registry for document exporters.
+
+ This class manages the registration and lookup of exporter classes.
+ Exporters can be registered using the @register class method as a decorator.
+
+ Example:
+ @ExporterRegistry.register
+ class PDFExporter(BaseExporter):
+ ...
+
+ # Later, to get the exporter:
+ exporter = ExporterRegistry.get_exporter("pdf")
+ """
+
+ _exporters: Dict[str, Type[BaseExporter]] = {}
+ _instances: Dict[str, BaseExporter] = {}
+
+ @classmethod
+ def register(cls, exporter_class: Type[BaseExporter]) -> Type[BaseExporter]:
+ """Register an exporter class.
+
+ Can be used as a decorator:
+ @ExporterRegistry.register
+ class MyExporter(BaseExporter):
+ ...
+
+ Args:
+ exporter_class: The exporter class to register
+
+ Returns:
+ The exporter class (unchanged), allowing use as decorator
+ """
+ # Instantiate temporarily to get format_name
+ instance = exporter_class()
+ format_name = instance.format_name.lower()
+ cls._exporters[format_name] = exporter_class
+ logger.debug(f"Registered exporter for format: {format_name}")
+ return exporter_class
+
+ @classmethod
+ def get_exporter(cls, format_name: str) -> Optional[BaseExporter]:
+ """Get an exporter instance for the given format.
+
+ Uses singleton pattern - returns cached instance if available.
+
+ Args:
+ format_name: The format identifier (e.g., 'pdf', 'odt')
+
+ Returns:
+ An exporter instance, or None if format not supported
+ """
+ format_name = format_name.lower()
+
+ # Return cached instance if available
+ if format_name in cls._instances:
+ return cls._instances[format_name]
+
+ # Create new instance
+ exporter_class = cls._exporters.get(format_name)
+ if exporter_class:
+ instance = exporter_class()
+ cls._instances[format_name] = instance
+ return instance
+
+ return None
+
+ @classmethod
+ def get_available_formats(cls) -> List[str]:
+ """Get list of available export formats.
+
+ Returns:
+ List of format identifiers (e.g., ['pdf', 'odt', 'latex'])
+ """
+ return list(cls._exporters.keys())
+
+ @classmethod
+ def is_format_supported(cls, format_name: str) -> bool:
+ """Check if a format is supported.
+
+ Args:
+ format_name: The format identifier to check
+
+ Returns:
+ True if the format is supported, False otherwise
+ """
+ return format_name.lower() in cls._exporters
+
+ @classmethod
+ def clear(cls) -> None:
+ """Clear all registered exporters.
+
+ Primarily useful for testing.
+ """
+ cls._exporters.clear()
+ cls._instances.clear()
diff --git a/src/local_deep_research/exporters/ris_exporter.py b/src/local_deep_research/exporters/ris_exporter.py
new file mode 100644
index 0000000000..1a433beba5
--- /dev/null
+++ b/src/local_deep_research/exporters/ris_exporter.py
@@ -0,0 +1,88 @@
+"""RIS export service.
+
+This module provides the RISExporter class that wraps the existing
+RISExporter implementation from text_optimization.citation_formatter.
+"""
+
+from typing import Optional
+
+from loguru import logger
+
+from .base import BaseExporter, ExportOptions, ExportResult
+from .registry import ExporterRegistry
+
+# Maximum content size (50 MB) to prevent OOM errors
+MAX_CONTENT_SIZE = 50 * 1024 * 1024
+
+
+class RISExporter(BaseExporter):
+ """RIS exporter using the existing RISExporter implementation.
+
+ This exporter extracts references from markdown content and converts
+ them to RIS (Research Information Systems) format, which can be
+ imported into reference managers like Zotero, Mendeley, or EndNote.
+ """
+
+ def __init__(self):
+ """Initialize RIS exporter."""
+ # Import here to avoid circular imports
+ from ..text_optimization.citation_formatter import (
+ RISExporter as LegacyRISExporter,
+ )
+
+ self._legacy = LegacyRISExporter()
+
+ @property
+ def format_name(self) -> str:
+ return "ris"
+
+ @property
+ def file_extension(self) -> str:
+ return ".ris"
+
+ @property
+ def mimetype(self) -> str:
+ return "text/plain"
+
+ def export(
+ self,
+ markdown_content: str,
+ options: Optional[ExportOptions] = None,
+ ) -> ExportResult:
+ """Extract references from markdown and convert to RIS format.
+
+ Args:
+ markdown_content: The markdown text containing sources/references
+ options: Optional export options (title, metadata)
+
+ Returns:
+ ExportResult with RIS content as UTF-8 bytes, filename, and mimetype
+
+ Raises:
+ ValueError: If content exceeds maximum size limit
+ """
+ try:
+ # Check content size limit to prevent OOM errors
+ if len(markdown_content) > MAX_CONTENT_SIZE:
+ raise ValueError(
+ f"Content exceeds maximum size of "
+ f"{MAX_CONTENT_SIZE // (1024 * 1024)} MB"
+ )
+
+ options = options or ExportOptions()
+
+ content = self._legacy.export_to_ris(markdown_content)
+ filename = self._generate_safe_filename(options.title)
+
+ logger.info(f"Generated RIS in memory, size: {len(content)} bytes")
+
+ return ExportResult(
+ content=content.encode("utf-8"),
+ filename=filename,
+ mimetype=self.mimetype,
+ )
+
+ except Exception as e:
+ logger.exception(f"Error generating RIS: {str(e)}")
+ raise
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index d0b0447d89..fa8e96a26d 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -1301,12 +1301,16 @@ def get_research_report(research_id):
)
@login_required
def export_research_report(research_id, format):
- """Export research report to different formats (LaTeX, Quarto, RIS, or PDF)"""
+ """Export research report to different formats (LaTeX, Quarto, RIS, PDF, ODT, etc.)"""
try:
- if format not in ["latex", "quarto", "ris", "pdf"]:
+ # Use the exporter registry to validate format
+ from ...exporters import ExporterRegistry
+
+ if not ExporterRegistry.is_format_supported(format):
+ available = ExporterRegistry.get_available_formats()
return jsonify(
{
- "error": "Invalid format. Use 'latex', 'quarto', 'ris', or 'pdf'"
+ "error": f"Invalid format. Available formats: {', '.join(available)}"
}
), 400
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 7b5bde6c77..c8379829fa 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -1,6 +1,5 @@
import hashlib
import json
-import re
import threading
from datetime import datetime, UTC
from pathlib import Path
@@ -54,115 +53,46 @@ def export_report_to_memory(
"""
Export a markdown report to different formats in memory.
+ Uses the modular exporter registry to support multiple formats.
+ Available formats can be queried with ExporterRegistry.get_available_formats().
+
Args:
markdown_content: The markdown content to export
- format: Export format ('latex', 'quarto', 'ris', or 'pdf')
+ format: Export format (e.g., 'pdf', 'odt', 'latex', 'quarto', 'ris')
title: Optional title for the document
Returns:
Tuple of (content_bytes, filename, mimetype)
"""
- if format == "pdf":
- # Use WeasyPrint for PDF generation
- from .pdf_service import get_pdf_service
-
- pdf_service = get_pdf_service()
-
- # Add title as H1 at the top if provided and not already present
- if title and not markdown_content.startswith(f"# {title}"):
- # Check if the content starts with any H1
- if not markdown_content.startswith("#"):
- markdown_content = f"# {title}\n\n{markdown_content}"
-
- # Pass the title if provided, but don't add duplicate content
- pdf_bytes = pdf_service.markdown_to_pdf(
- markdown_content,
- title=title, # Use the title from the research record (for HTML metadata)
- metadata=None, # Don't add extra metadata section
- )
-
- # Generate a filename based on title or use default
- safe_title = (
- re.sub(r"[^\w\s-]", "", title).strip().replace(" ", "_")[:50]
- if title
- else "research_report"
- )
- filename = f"{safe_title}.pdf"
-
- logger.info(f"Generated PDF in memory, size: {len(pdf_bytes)} bytes")
- return pdf_bytes, filename, "application/pdf"
-
- elif format == "latex":
- from ...text_optimization.citation_formatter import LaTeXExporter
-
- exporter = LaTeXExporter()
- exported_content = exporter.export_to_latex(markdown_content)
-
- safe_title = (
- re.sub(r"[^\w\s-]", "", title).strip().replace(" ", "_")[:50]
- if title
- else "research_report"
- )
- filename = f"{safe_title}.tex"
+ from ...exporters import ExporterRegistry, ExportOptions
- logger.info("Generated LaTeX in memory")
- return exported_content.encode("utf-8"), filename, "text/plain"
+ # Normalize format
+ format_lower = format.lower()
- elif format == "quarto":
- import zipfile
- import io
- from ...text_optimization.citation_formatter import QuartoExporter
+ # Get exporter from registry
+ exporter = ExporterRegistry.get_exporter(format_lower)
- exporter = QuartoExporter()
- # Extract title from markdown if not provided
- if not title:
- title_match = re.search(
- r"^#\s+(.+)$", markdown_content, re.MULTILINE
- )
- title = title_match.group(1) if title_match else "Research Report"
- exported_content = exporter.export_to_quarto(markdown_content, title)
-
- # Generate bibliography
- bib_content = exporter._generate_bibliography(markdown_content)
-
- safe_title = (
- re.sub(r"[^\w\s-]", "", title).strip().replace(" ", "_")[:50]
- if title
- else "research_report"
+ if exporter is None:
+ available = ExporterRegistry.get_available_formats()
+ raise ValueError(
+ f"Unsupported export format: {format}. "
+ f"Available formats: {', '.join(available)}"
)
- # Create a zip file in memory containing both files
- zip_buffer = io.BytesIO()
- with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf:
- # Add the Quarto document
- zipf.writestr(f"{safe_title}.qmd", exported_content)
- # Add the bibliography file
- zipf.writestr("references.bib", bib_content)
-
- zip_bytes = zip_buffer.getvalue()
- filename = f"{safe_title}_quarto.zip"
-
- logger.info("Generated Quarto with bibliography in memory (zip)")
- return zip_bytes, filename, "application/zip"
+ # Title prepending is now handled by each exporter via _prepend_title_if_needed()
+ # PDF and ODT exporters prepend titles; RIS and other formats ignore them
- elif format == "ris":
- from ...text_optimization.citation_formatter import RISExporter
+ # Create options
+ options = ExportOptions(title=title)
- exporter = RISExporter()
- exported_content = exporter.export_to_ris(markdown_content)
+ # Export
+ result = exporter.export(markdown_content, options)
- safe_title = (
- re.sub(r"[^\w\s-]", "", title).strip().replace(" ", "_")[:50]
- if title
- else "research_report"
- )
- filename = f"{safe_title}.ris"
-
- logger.info("Generated RIS in memory")
- return exported_content.encode("utf-8"), filename, "text/plain"
+ logger.info(
+ f"Generated {format_lower} in memory, size: {len(result.content)} bytes"
+ )
- else:
- raise ValueError(f"Unsupported export format: {format}")
+ return result.content, result.filename, result.mimetype
def save_research_strategy(research_id, strategy_name, username=None):
diff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.js
index 2cef88f609..30245fa236 100644
--- a/src/local_deep_research/web/static/js/components/results.js
+++ b/src/local_deep_research/web/static/js/components/results.js
@@ -67,32 +67,56 @@
});
}
- // Export button
+ // Export button (Markdown)
if (exportBtn) {
- exportBtn.addEventListener('click', handleExport);
+ exportBtn.addEventListener('click', (e) => {
+ e.preventDefault();
+ handleExport();
+ });
}
// PDF button
if (pdfBtn) {
- pdfBtn.addEventListener('click', handlePdfExport);
+ pdfBtn.addEventListener('click', (e) => {
+ e.preventDefault();
+ handlePdfExport();
+ });
}
// LaTeX export button
const latexBtn = document.getElementById('export-latex-btn');
if (latexBtn) {
- latexBtn.addEventListener('click', () => handleFormatExport('latex'));
+ latexBtn.addEventListener('click', (e) => {
+ e.preventDefault();
+ handleFormatExport('latex');
+ });
}
// Quarto export button
const quartoBtn = document.getElementById('export-quarto-btn');
if (quartoBtn) {
- quartoBtn.addEventListener('click', () => handleFormatExport('quarto'));
+ quartoBtn.addEventListener('click', (e) => {
+ e.preventDefault();
+ handleFormatExport('quarto');
+ });
+ }
+
+ // ODT export button
+ const odtBtn = document.getElementById('export-odt-btn');
+ if (odtBtn) {
+ odtBtn.addEventListener('click', (e) => {
+ e.preventDefault();
+ handleFormatExport('odt');
+ });
}
// RIS export button (for Zotero)
const risBtn = document.getElementById('export-ris-btn');
if (risBtn) {
- risBtn.addEventListener('click', () => handleFormatExport('ris'));
+ risBtn.addEventListener('click', (e) => {
+ e.preventDefault();
+ handleFormatExport('ris');
+ });
}
// Back to history button
@@ -752,7 +776,9 @@
throw new Error('No research ID available');
}
- const formatName = format === 'latex' ? 'LaTeX' : format === 'quarto' ? 'Quarto' : 'RIS';
+ const formatName = format === 'latex' ? 'LaTeX' :
+ format === 'quarto' ? 'Quarto' :
+ format === 'odt' ? 'ODT' : 'RIS';
SafeLogger.log(`Exporting to ${formatName}...`);
// Get CSRF token
@@ -775,7 +801,9 @@
const blob = await response.blob();
// Determine file extension
- const extension = format === 'latex' ? 'tex' : format === 'quarto' ? 'qmd' : 'ris';
+ const extension = format === 'latex' ? 'tex' :
+ format === 'quarto' ? 'qmd' :
+ format === 'odt' ? 'odt' : 'ris';
// Create download link
const link = document.createElement('a');
diff --git a/src/local_deep_research/web/templates/pages/results.html b/src/local_deep_research/web/templates/pages/results.html
index bd68ec2911..7d0077fa8a 100644
--- a/src/local_deep_research/web/templates/pages/results.html
+++ b/src/local_deep_research/web/templates/pages/results.html
@@ -13,10 +13,20 @@
<button class="btn btn-primary" id="ask-followup-btn" onclick="window.followUpResearch ? followUpResearch.showFollowUpModal() : alert('Follow-up feature loading...')" title="Ask a follow-up question using this research's sources and context"><i class="fas fa-question-circle"></i> Ask Follow-up Question</button>
<button class="btn ldr-btn-outline" id="view-metrics-btn" title="View token usage and cost metrics for this research session"><i class="fas fa-chart-bar"></i> View Metrics</button>
<button class="btn ldr-btn-outline" id="download-pdf-btn" title="Download as PDF document for sharing or printing"><i class="fas fa-file-pdf"></i> Download PDF</button>
- <button class="btn ldr-btn-outline" id="export-markdown-btn" title="Download as .md file for use in documentation or note apps"><i class="fas fa-file-alt"></i> Export Markdown</button>
- <button class="btn ldr-btn-outline" id="export-latex-btn" title="Download as .tex file for academic paper formatting"><i class="fas fa-file-code"></i> Export LaTeX</button>
- <button class="btn ldr-btn-outline" id="export-quarto-btn" title="Download as .qmd file for Quarto publishing system"><i class="fas fa-file-code"></i> Export Quarto</button>
- <button class="btn ldr-btn-outline" id="export-ris-btn" title="Download citation file for Zotero, Mendeley, or other reference managers"><i class="fas fa-file-export"></i> Export RIS (Zotero)</button>
+ <div class="dropdown d-inline-block">
+ <button class="btn ldr-btn-outline dropdown-toggle" type="button" id="export-dropdown-btn" data-bs-toggle="dropdown" aria-expanded="false" title="Export research to various formats">
+ <i class="fas fa-download"></i> Export
+ </button>
+ <ul class="dropdown-menu" aria-labelledby="export-dropdown-btn">
+ <li><a class="dropdown-item" href="#" id="export-markdown-btn"><i class="fas fa-file-alt"></i> Markdown</a></li>
+ <li><hr class="dropdown-divider"></li>
+ <li><a class="dropdown-item" href="#" id="export-latex-btn"><i class="fas fa-file-code"></i> LaTeX</a></li>
+ <li><a class="dropdown-item" href="#" id="export-quarto-btn"><i class="fas fa-file-code"></i> Quarto</a></li>
+ <li><a class="dropdown-item" href="#" id="export-odt-btn"><i class="fas fa-file-word"></i> ODT (LibreOffice)</a></li>
+ <li><hr class="dropdown-divider"></li>
+ <li><a class="dropdown-item" href="#" id="export-ris-btn"><i class="fas fa-file-export"></i> RIS (Zotero)</a></li>
+ </ul>
+ </div>
<button class="btn ldr-btn-outline" id="report-issue-btn" title="Report bugs, suggest features, or get help from the community"><i class="fas fa-hands-helping"></i> Help Improve</button>
<button class="btn ldr-btn-outline" id="back-to-history"><i class="fas fa-arrow-left"></i> Back to History</button>
</div>
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
index 7e61262060..bf7fa34dc1 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
@@ -57,6 +57,9 @@ class AdaptiveRateLimitTracker:
key,
settings_snapshot=self.settings_snapshot,
)
+ # Handle None values - return default instead of calling type_fn(None)
+ if value is None:
+ return default
return type_fn(value) if type_fn else value
except NoSettingsContextError:
return default
diff --git a/tests/exporters/__init__.py b/tests/exporters/__init__.py
new file mode 100644
index 0000000000..1edb62e1f5
--- /dev/null
+++ b/tests/exporters/__init__.py
@@ -0,0 +1 @@
+"""Tests for exporters package."""
diff --git a/tests/exporters/conftest.py b/tests/exporters/conftest.py
new file mode 100644
index 0000000000..279a937d9e
--- /dev/null
+++ b/tests/exporters/conftest.py
@@ -0,0 +1,96 @@
+"""Shared fixtures for exporters tests."""
+
+import pytest
+
+
+def sample_markdown():
+ """Sample markdown content for testing."""
+ return """# Test Document
+
+This is a test document with **bold** and *italic* text.
+
+## Section 1
+
+A paragraph with some content.
+
+| Column 1 | Column 2 |
+|----------|----------|
+| Data 1 | Data 2 |
+
+## Section 2
+
+- Item 1
+- Item 2
+- Item 3
+
+```python
+def example():
+ return "code block"
+```
+
+## Sources
+
+[1] First Source Title
+URL: https://example.com/source1
+
+[2] Second Source Title
+URL: https://example.com/source2
+"""
+
+
+def simple_markdown():
+ """Minimal markdown for basic tests."""
+ return "# Hello World\n\nThis is a test."
+
+
+def markdown_with_special_chars():
+ """Markdown with special characters."""
+ return """# Special Characters
+
+Testing: <>&"'
+Unicode: café, naïve, 日本語
+Symbols: © ® ™ € £ ¥
+"""
+
+
+def sample_metadata():
+ """Sample metadata for document generation."""
+ return {
+ "author": "Test Author",
+ "date": "2024-01-15",
+ "subject": "Test Subject",
+ }
+
+
+def markdown_with_nested_lists():
+ """Markdown with nested lists."""
+ return """# Nested Lists
+
+## Unordered
+- Item 1
+ - Nested 1.1
+ - Nested 1.2
+- Item 2
+
+## Ordered
+1. First
+2. Second
+ 1. Nested 2.1
+3. Third
+"""
+
+
+def markdown_with_links():
+ """Markdown with hyperlinks."""
+ return """# Document with Links
+
+Check out [this link](https://example.com) for more info.
+
+Also see [another link](https://test.org/page).
+"""
diff --git a/tests/exporters/test_base_exporter.py b/tests/exporters/test_base_exporter.py
new file mode 100644
index 0000000000..a510c12210
--- /dev/null
+++ b/tests/exporters/test_base_exporter.py
@@ -0,0 +1,173 @@
+"""Tests for BaseExporter helper methods."""
+
+
+class TestPrependTitleIfNeeded:
+ """Tests for BaseExporter._prepend_title_if_needed() method."""
+
+ def _get_exporter(self):
+ """Get a concrete exporter instance to test base class methods."""
+ from local_deep_research.exporters.latex_exporter import LaTeXExporter
+
+ return LaTeXExporter()
+
+ def test_prepends_title_when_no_heading(self):
+ """Title should be prepended when content has no heading."""
+ exporter = self._get_exporter()
+ content = "This is content without a heading."
+ title = "My Report"
+
+ result = exporter._prepend_title_if_needed(content, title)
+
+ assert result == "# My Report\n\nThis is content without a heading."
+
+ def test_does_not_prepend_when_same_title_exists(self):
+ """Title should NOT be prepended when content starts with same title."""
+ exporter = self._get_exporter()
+ content = "# My Report\n\nThis is the content."
+ title = "My Report"
+
+ result = exporter._prepend_title_if_needed(content, title)
+
+ assert result == content # Unchanged
+
+ def test_does_not_prepend_when_different_heading_exists(self):
+ """Title should NOT be prepended when content starts with any heading."""
+ exporter = self._get_exporter()
+ content = "# Different Heading\n\nThis is the content."
+ title = "My Report"
+
+ result = exporter._prepend_title_if_needed(content, title)
+
+ assert result == content # Unchanged - already has a heading
+
+ def test_does_not_prepend_when_h2_heading_exists(self):
+ """Title should NOT be prepended when content starts with H2."""
+ exporter = self._get_exporter()
+ content = "## Section Heading\n\nThis is the content."
+ title = "My Report"
+
+ result = exporter._prepend_title_if_needed(content, title)
+
+ assert result == content # Unchanged
+
+ def test_returns_unchanged_when_title_is_none(self):
+ """Content should be returned unchanged when title is None."""
+ exporter = self._get_exporter()
+ content = "This is content without a heading."
+
+ result = exporter._prepend_title_if_needed(content, None)
+
+ assert result == content
+
+ def test_returns_unchanged_when_title_is_empty(self):
+ """Content should be returned unchanged when title is empty string."""
+ exporter = self._get_exporter()
+ content = "This is content without a heading."
+
+ result = exporter._prepend_title_if_needed(content, "")
+
+ assert result == content
+
+ def test_handles_content_with_leading_whitespace(self):
+ """Should check for heading after stripping leading whitespace."""
+ exporter = self._get_exporter()
+ content = " # Existing Heading\n\nContent here."
+ title = "My Report"
+
+ result = exporter._prepend_title_if_needed(content, title)
+
+ # Should NOT prepend because content has a heading (after lstrip)
+ assert result == content
+
+ def test_handles_empty_content(self):
+ """Should handle empty content gracefully."""
+ exporter = self._get_exporter()
+ content = ""
+ title = "My Report"
+
+ result = exporter._prepend_title_if_needed(content, title)
+
+ assert result == "# My Report\n\n"
+
+ def test_handles_whitespace_only_content(self):
+ """Should handle whitespace-only content."""
+ exporter = self._get_exporter()
+ content = " \n\n "
+ title = "My Report"
+
+ result = exporter._prepend_title_if_needed(content, title)
+
+ assert result == "# My Report\n\n \n\n "
+
+ def test_preserves_special_characters_in_title(self):
+ """Title with special characters should be preserved."""
+ exporter = self._get_exporter()
+ content = "Some content here."
+ title = "Analysis: AI & ML (2024)"
+
+ result = exporter._prepend_title_if_needed(content, title)
+
+ assert result == "# Analysis: AI & ML (2024)\n\nSome content here."
+
+ def test_preserves_unicode_in_title(self):
+ """Unicode characters in title should be preserved."""
+ exporter = self._get_exporter()
+ content = "Some content here."
+ title = "Исследование машинного обучения"
+
+ result = exporter._prepend_title_if_needed(content, title)
+
+ assert result.startswith("# Исследование машинного обучения\n\n")
+
+
+class TestGenerateSafeFilename:
+ """Tests for BaseExporter._generate_safe_filename() method."""
+
+ def _get_exporter(self):
+ """Get a concrete exporter instance to test base class methods."""
+ from local_deep_research.exporters.latex_exporter import LaTeXExporter
+
+ return LaTeXExporter()
+
+ def test_generates_filename_from_title(self):
+ """Should generate filename from title."""
+ exporter = self._get_exporter()
+
+ result = exporter._generate_safe_filename("My Research Report")
+
+ assert result == "My_Research_Report.tex"
+
+ def test_removes_special_characters(self):
+ """Should remove special characters from filename."""
+ exporter = self._get_exporter()
+
+ result = exporter._generate_safe_filename("Report: AI & ML (2024)")
+
+ assert result == "Report_AI__ML_2024.tex"
+
+ def test_truncates_long_titles(self):
+ """Should truncate titles longer than 50 characters."""
+ exporter = self._get_exporter()
+ long_title = "A" * 100
+
+ result = exporter._generate_safe_filename(long_title)
+
+ # 50 chars + .tex extension
+ assert len(result) == 54
+ assert result.endswith(".tex")
+
+ def test_uses_default_when_title_is_none(self):
+ """Should use default filename when title is None."""
+ exporter = self._get_exporter()
+
+ result = exporter._generate_safe_filename(None)
+
+ assert result == "research_report.tex"
+
+ def test_uses_default_when_title_is_empty(self):
+ """Should use default filename when title is empty."""
+ exporter = self._get_exporter()
+
+ result = exporter._generate_safe_filename("")
+
+ assert result == "research_report.tex"
diff --git a/tests/exporters/test_latex_exporter.py b/tests/exporters/test_latex_exporter.py
new file mode 100644
index 0000000000..e469c9cd11
--- /dev/null
+++ b/tests/exporters/test_latex_exporter.py
@@ -0,0 +1,278 @@
+"""Tests for LaTeXExporter."""
+
+import pytest
+from unittest.mock import patch
+
+
+class TestLaTeXExporterProperties:
+ """Tests for LaTeXExporter properties."""
+
+ def test_format_name_is_latex(self):
+ """Test that format_name is 'latex'."""
+ from local_deep_research.exporters.latex_exporter import LaTeXExporter
+
+ exporter = LaTeXExporter()
+
+ assert exporter.format_name == "latex"
+
+ def test_file_extension_is_tex(self):
+ """Test that file_extension is '.tex'."""
+ from local_deep_research.exporters.latex_exporter import LaTeXExporter
+
+ exporter = LaTeXExporter()
+
+ assert exporter.file_extension == ".tex"
+
+ def test_mimetype_is_correct(self):
+ """Test that mimetype is correct for LaTeX."""
+ from local_deep_research.exporters.latex_exporter import LaTeXExporter
+
+ exporter = LaTeXExporter()
+
+ assert exporter.mimetype == "text/plain"
+
+
+class TestLaTeXExporterExport:
+ """Tests for LaTeXExporter.export method."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create LaTeXExporter instance."""
+ from local_deep_research.exporters.latex_exporter import LaTeXExporter
+
+ return LaTeXExporter()
+
+ def test_returns_export_result(self, exporter, simple_markdown):
+ """Test that export returns ExportResult."""
+ from local_deep_research.exporters import ExportResult
+
+ result = exporter.export(simple_markdown)
+
+ assert isinstance(result, ExportResult)
+
+ def test_result_content_is_bytes(self, exporter, simple_markdown):
+ """Test that result content is bytes."""
+ result = exporter.export(simple_markdown)
+
+ assert isinstance(result.content, bytes)
+
+ def test_result_content_is_valid_latex(self, exporter, simple_markdown):
+ """Test that result content is valid LaTeX."""
+ result = exporter.export(simple_markdown)
+
+ # LaTeX documents typically start with documentclass or contain common LaTeX commands
+ content_str = result.content.decode("utf-8")
+ # Should contain LaTeX-like structure (backslash commands or plain text)
+ assert len(content_str) > 0
+
+ def test_result_filename_uses_title(self, exporter, simple_markdown):
+ """Test that filename uses provided title."""
+ from local_deep_research.exporters import ExportOptions
+
+ options = ExportOptions(title="My Research Report")
+ result = exporter.export(simple_markdown, options)
+
+ assert "My_Research_Report" in result.filename
+ assert result.filename.endswith(".tex")
+
+ def test_result_filename_default_when_no_title(
+ self, exporter, simple_markdown
+ ):
+ """Test that filename uses default when no title."""
+ result = exporter.export(simple_markdown)
+
+ assert "research_report" in result.filename
+ assert result.filename.endswith(".tex")
+
+ def test_result_mimetype_is_correct(self, exporter, simple_markdown):
+ """Test that result mimetype is correct."""
+ result = exporter.export(simple_markdown)
+
+ assert result.mimetype == "text/plain"
+
+ def test_handles_empty_markdown(self, exporter):
+ """Test handling of empty markdown."""
+ result = exporter.export("")
+
+ assert isinstance(result.content, bytes)
+
+ def test_handles_markdown_with_all_features(
+ self, exporter, sample_markdown
+ ):
+ """Test handling of markdown with tables, code, lists."""
+ result = exporter.export(sample_markdown)
+
+ assert isinstance(result.content, bytes)
+ assert len(result.content) > 0
+
+ def test_handles_special_characters(
+ self, exporter, markdown_with_special_chars
+ ):
+ """Test handling of special characters."""
+ result = exporter.export(markdown_with_special_chars)
+
+ assert isinstance(result.content, bytes)
+
+ def test_handles_large_markdown(self, exporter):
+ """Test handling of large markdown content."""
+ large_content = "# Large Document\n\n"
+ large_content += ("This is a paragraph. " * 100 + "\n\n") * 50
+
+ result = exporter.export(large_content)
+
+ assert isinstance(result.content, bytes)
+ assert len(result.content) > 1000
+
+ def test_logs_latex_size(self, exporter, simple_markdown):
+ """Test that LaTeX size is logged."""
+ with patch(
+ "local_deep_research.exporters.latex_exporter.logger"
+ ) as mock_logger:
+ exporter.export(simple_markdown)
+
+ mock_logger.info.assert_called_once()
+ call_args = mock_logger.info.call_args[0][0]
+ assert "Generated LaTeX" in call_args
+ assert "bytes" in call_args
+
+
+class TestLaTeXExporterContentSizeLimit:
+ """Tests for content size limit enforcement."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create LaTeXExporter instance."""
+ from local_deep_research.exporters.latex_exporter import LaTeXExporter
+
+ return LaTeXExporter()
+
+ def test_raises_error_for_oversized_content(self, exporter):
+ """Test that ValueError is raised for content exceeding size limit."""
+ from local_deep_research.exporters.latex_exporter import (
+ MAX_CONTENT_SIZE,
+ )
+
+ # Create content that exceeds the limit
+ oversized_content = "x" * (MAX_CONTENT_SIZE + 1)
+
+ with pytest.raises(ValueError) as exc_info:
+ exporter.export(oversized_content)
+
+ assert "exceeds maximum size" in str(exc_info.value)
+
+ def test_accepts_content_at_limit(self, exporter):
+ """Test that content at exactly the limit is accepted."""
+ from local_deep_research.exporters.latex_exporter import (
+ MAX_CONTENT_SIZE,
+ )
+
+ # Create content at exactly the limit
+ content_at_limit = "x" * MAX_CONTENT_SIZE
+
+ # Mock the legacy exporter to avoid processing large content
+ with patch.object(
+ exporter._legacy,
+ "export_to_latex",
+ return_value="\\documentclass{article}",
+ ):
+ result = exporter.export(content_at_limit)
+ assert isinstance(result.content, bytes)
+
+ def test_accepts_content_under_limit(self, exporter, simple_markdown):
+ """Test that content under the limit is accepted."""
+ result = exporter.export(simple_markdown)
+
+ assert isinstance(result.content, bytes)
+
+
+class TestLaTeXExporterErrorHandling:
+ """Tests for error handling in LaTeXExporter."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create LaTeXExporter instance."""
+ from local_deep_research.exporters.latex_exporter import LaTeXExporter
+
+ return LaTeXExporter()
+
+ def test_logs_exception_on_error(self, exporter):
+ """Test that exceptions are logged."""
+ with patch.object(
+ exporter._legacy,
+ "export_to_latex",
+ side_effect=Exception("Test error"),
+ ):
+ with patch(
+ "local_deep_research.exporters.latex_exporter.logger"
+ ) as mock_logger:
+ with pytest.raises(Exception):
+ exporter.export("test")
+
+ mock_logger.exception.assert_called_once()
+
+
+class TestLaTeXExporterIntegration:
+ """Integration tests for LaTeXExporter with ExporterRegistry."""
+
+ def test_registered_in_registry(self):
+ """Test that LaTeXExporter is registered in the registry."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ assert ExporterRegistry.is_format_supported("latex")
+
+ def test_can_get_from_registry(self):
+ """Test that LaTeXExporter can be retrieved from registry."""
+ from local_deep_research.exporters import ExporterRegistry
+ from local_deep_research.exporters.latex_exporter import LaTeXExporter
+
+ exporter = ExporterRegistry.get_exporter("latex")
+
+ assert isinstance(exporter, LaTeXExporter)
+
+ def test_export_via_registry(self, simple_markdown):
+ """Test export via registry lookup."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ exporter = ExporterRegistry.get_exporter("latex")
+ result = exporter.export(simple_markdown)
+
+ assert isinstance(result.content, bytes)
+ assert result.filename.endswith(".tex")
+
+
+class TestLaTeXExporterFilenameTruncation:
+ """Tests for filename truncation with long titles."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create LaTeXExporter instance."""
+ from local_deep_research.exporters.latex_exporter import LaTeXExporter
+
+ return LaTeXExporter()
+
+ def test_filename_truncated_to_50_chars(self, exporter, simple_markdown):
+ """Test that filename is truncated when title exceeds 50 chars."""
+ from local_deep_research.exporters import ExportOptions
+
+ # Title with more than 50 characters
+ long_title = "A" * 60
+ options = ExportOptions(title=long_title)
+ result = exporter.export(simple_markdown, options)
+
+ # Filename should be truncated to 50 chars + extension
+ filename_without_ext = result.filename.rsplit(".", 1)[0]
+ assert len(filename_without_ext) == 50
+ assert result.filename.endswith(".tex")
+
+ def test_filename_not_truncated_under_50_chars(
+ self, exporter, simple_markdown
+ ):
+ """Test that filename is not truncated when under 50 chars."""
+ from local_deep_research.exporters import ExportOptions
+
+ title = "Short Title"
+ options = ExportOptions(title=title)
+ result = exporter.export(simple_markdown, options)
+
+ assert "Short_Title" in result.filename
+ assert result.filename.endswith(".tex")
diff --git a/tests/exporters/test_odt_exporter.py b/tests/exporters/test_odt_exporter.py
new file mode 100644
index 0000000000..5cc2fd95bf
--- /dev/null
+++ b/tests/exporters/test_odt_exporter.py
@@ -0,0 +1,528 @@
+"""Tests for ODTExporter using pypandoc."""
+
+import pytest
+from unittest.mock import patch
+
+# Check if pandoc is available (required by pypandoc)
+try:
+ import pypandoc
+
+ pypandoc.get_pandoc_version()
+ PANDOC_AVAILABLE = True
+except (ImportError, OSError):
+ PANDOC_AVAILABLE = False
+
+pytestmark = pytest.mark.skipif(
+ not PANDOC_AVAILABLE,
+ reason="Pandoc is not installed (required for ODT export)",
+)
+
+
+class TestODTExporterProperties:
+ """Tests for ODTExporter properties."""
+
+ def test_format_name_is_odt(self):
+ """Test that format_name is 'odt'."""
+ from local_deep_research.exporters.odt_exporter import ODTExporter
+
+ exporter = ODTExporter()
+
+ assert exporter.format_name == "odt"
+
+ def test_file_extension_is_odt(self):
+ """Test that file_extension is '.odt'."""
+ from local_deep_research.exporters.odt_exporter import ODTExporter
+
+ exporter = ODTExporter()
+
+ assert exporter.file_extension == ".odt"
+
+ def test_mimetype_is_correct(self):
+ """Test that mimetype is correct for ODT."""
+ from local_deep_research.exporters.odt_exporter import ODTExporter
+
+ exporter = ODTExporter()
+
+ assert exporter.mimetype == "application/vnd.oasis.opendocument.text"
+
+
+class TestODTExporterExport:
+ """Tests for ODTExporter.export method."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create ODTExporter instance."""
+ from local_deep_research.exporters.odt_exporter import ODTExporter
+
+ return ODTExporter()
+
+ def test_returns_export_result(self, exporter, simple_markdown):
+ """Test that export returns ExportResult."""
+ from local_deep_research.exporters import ExportResult
+
+ result = exporter.export(simple_markdown)
+
+ assert isinstance(result, ExportResult)
+
+ def test_result_content_is_bytes(self, exporter, simple_markdown):
+ """Test that result content is bytes."""
+ result = exporter.export(simple_markdown)
+
+ assert isinstance(result.content, bytes)
+
+ def test_result_is_valid_odt(self, exporter, simple_markdown):
+ """Test that result is a valid ODT file (ZIP archive)."""
+ result = exporter.export(simple_markdown)
+
+ # ODT files are ZIP archives, they start with PK
+ assert result.content[:2] == b"PK"
+
+ def test_result_has_reasonable_size(self, exporter, simple_markdown):
+ """Test that generated ODT has a reasonable size."""
+ result = exporter.export(simple_markdown)
+
+ # A simple ODT should be at least a few KB
+ assert len(result.content) > 1000
+
+ def test_result_filename_uses_title(self, exporter, simple_markdown):
+ """Test that filename uses provided title."""
+ from local_deep_research.exporters import ExportOptions
+
+ options = ExportOptions(title="My Research Report")
+ result = exporter.export(simple_markdown, options)
+
+ assert "My_Research_Report" in result.filename
+ assert result.filename.endswith(".odt")
+
+ def test_result_filename_default_when_no_title(
+ self, exporter, simple_markdown
+ ):
+ """Test that filename uses default when no title."""
+ result = exporter.export(simple_markdown)
+
+ assert "research_report" in result.filename
+ assert result.filename.endswith(".odt")
+
+ def test_result_mimetype_is_correct(self, exporter, simple_markdown):
+ """Test that result mimetype is correct."""
+ result = exporter.export(simple_markdown)
+
+ assert result.mimetype == "application/vnd.oasis.opendocument.text"
+
+ def test_handles_empty_markdown(self, exporter):
+ """Test handling of empty markdown."""
+ result = exporter.export("")
+
+ assert result.content[:2] == b"PK"
+
+ def test_handles_markdown_with_headings(self, exporter, sample_markdown):
+ """Test handling of markdown with multiple heading levels."""
+ result = exporter.export(sample_markdown)
+
+ assert result.content[:2] == b"PK"
+ assert len(result.content) > 1000
+
+ def test_handles_markdown_with_tables(self, exporter, sample_markdown):
+ """Test handling of markdown with tables."""
+ result = exporter.export(sample_markdown)
+
+ # Should create valid ODT
+ assert result.content[:2] == b"PK"
+
+ def test_handles_markdown_with_code_blocks(self, exporter, sample_markdown):
+ """Test handling of markdown with code blocks."""
+ result = exporter.export(sample_markdown)
+
+ assert result.content[:2] == b"PK"
+
+ def test_handles_markdown_with_lists(self, exporter, sample_markdown):
+ """Test handling of markdown with lists."""
+ result = exporter.export(sample_markdown)
+
+ assert result.content[:2] == b"PK"
+
+ def test_handles_special_characters(
+ self, exporter, markdown_with_special_chars
+ ):
+ """Test handling of special characters."""
+ result = exporter.export(markdown_with_special_chars)
+
+ assert result.content[:2] == b"PK"
+
+ def test_handles_nested_lists(self, exporter, markdown_with_nested_lists):
+ """Test handling of nested lists."""
+ result = exporter.export(markdown_with_nested_lists)
+
+ assert result.content[:2] == b"PK"
+
+ def test_handles_links(self, exporter, markdown_with_links):
+ """Test handling of markdown with links."""
+ result = exporter.export(markdown_with_links)
+
+ assert result.content[:2] == b"PK"
+
+ def test_handles_large_markdown(self, exporter):
+ """Test handling of large markdown content."""
+ # Create a large markdown document
+ large_content = "# Large Document\n\n"
+ large_content += ("This is a paragraph. " * 100 + "\n\n") * 50
+
+ result = exporter.export(large_content)
+
+ assert result.content[:2] == b"PK"
+ # Large content should produce larger ODT (Pandoc compresses efficiently)
+ assert len(result.content) > 5000
+
+ def test_includes_ldr_attribution(self, exporter, simple_markdown):
+ """Test that LDR attribution is included."""
+ # We can't easily check the content inside ODT without parsing it,
+ # but we verify the export succeeds
+ result = exporter.export(simple_markdown)
+
+ assert result.content[:2] == b"PK"
+
+ def test_logs_odt_size(self, exporter, simple_markdown):
+ """Test that ODT size is logged."""
+ with patch(
+ "local_deep_research.exporters.odt_exporter.logger"
+ ) as mock_logger:
+ exporter.export(simple_markdown)
+
+ mock_logger.info.assert_called_once()
+ call_args = mock_logger.info.call_args[0][0]
+ assert "Generated ODT" in call_args
+ assert "bytes" in call_args
+
+
+class TestODTExporterErrorHandling:
+ """Tests for error handling in ODTExporter."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create ODTExporter instance."""
+ from local_deep_research.exporters.odt_exporter import ODTExporter
+
+ return ODTExporter()
+
+ def test_logs_exception_on_error(self, exporter):
+ """Test that exceptions are logged when pandoc fails."""
+ import subprocess
+
+ with patch(
+ "local_deep_research.exporters.odt_exporter.subprocess.run",
+ side_effect=subprocess.CalledProcessError(
+ 1, "pandoc", stderr=b"Test error"
+ ),
+ ):
+ with patch(
+ "local_deep_research.exporters.odt_exporter.logger"
+ ) as mock_logger:
+ with pytest.raises(RuntimeError):
+ exporter.export("test")
+
+ mock_logger.exception.assert_called_once()
+
+
+class TestODTExporterIntegration:
+ """Integration tests for ODTExporter with ExporterRegistry."""
+
+ def test_registered_in_registry(self):
+ """Test that ODTExporter is registered in the registry."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ assert ExporterRegistry.is_format_supported("odt")
+
+ def test_can_get_from_registry(self):
+ """Test that ODTExporter can be retrieved from registry."""
+ from local_deep_research.exporters import ExporterRegistry
+ from local_deep_research.exporters.odt_exporter import ODTExporter
+
+ exporter = ExporterRegistry.get_exporter("odt")
+
+ assert isinstance(exporter, ODTExporter)
+
+ def test_export_via_registry(self, simple_markdown):
+ """Test export via registry lookup."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ exporter = ExporterRegistry.get_exporter("odt")
+ result = exporter.export(simple_markdown)
+
+ assert result.content[:2] == b"PK"
+ assert result.filename.endswith(".odt")
+
+
+class TestODTExporterFilenameTruncation:
+ """Tests for filename truncation with long titles."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create ODTExporter instance."""
+ from local_deep_research.exporters.odt_exporter import ODTExporter
+
+ return ODTExporter()
+
+ def test_filename_truncated_to_50_chars(self, exporter, simple_markdown):
+ """Test that filename is truncated when title exceeds 50 chars."""
+ from local_deep_research.exporters import ExportOptions
+
+ # Title with more than 50 characters
+ long_title = "A" * 60
+ options = ExportOptions(title=long_title)
+ result = exporter.export(simple_markdown, options)
+
+ # Filename should be truncated to 50 chars + extension
+ filename_without_ext = result.filename.rsplit(".", 1)[0]
+ assert len(filename_without_ext) == 50
+ assert result.filename.endswith(".odt")
+
+ def test_filename_not_truncated_under_50_chars(
+ self, exporter, simple_markdown
+ ):
+ """Test that filename is not truncated when under 50 chars."""
+ from local_deep_research.exporters import ExportOptions
+
+ title = "Short Title"
+ options = ExportOptions(title=title)
+ result = exporter.export(simple_markdown, options)
+
+ assert "Short_Title" in result.filename
+ assert result.filename.endswith(".odt")
+
+
+class TestODTExporterMetadataVariations:
+ """Tests for various metadata combinations."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create ODTExporter instance."""
+ from local_deep_research.exporters.odt_exporter import ODTExporter
+
+ return ODTExporter()
+
+ def test_title_only(self, exporter, simple_markdown):
+ """Test export with only title metadata."""
+ from local_deep_research.exporters import ExportOptions
+
+ options = ExportOptions(title="Title Only Test")
+ result = exporter.export(simple_markdown, options)
+
+ assert result.content[:2] == b"PK"
+ assert "Title_Only_Test" in result.filename
+
+ def test_author_only(self, exporter, simple_markdown):
+ """Test export with only author metadata."""
+ from local_deep_research.exporters import ExportOptions
+
+ options = ExportOptions(metadata={"author": "Test Author"})
+ result = exporter.export(simple_markdown, options)
+
+ assert result.content[:2] == b"PK"
+
+ def test_date_only(self, exporter, simple_markdown):
+ """Test export with only date metadata."""
+ from local_deep_research.exporters import ExportOptions
+
+ options = ExportOptions(metadata={"date": "2024-01-15"})
+ result = exporter.export(simple_markdown, options)
+
+ assert result.content[:2] == b"PK"
+
+ def test_all_metadata(self, exporter, simple_markdown):
+ """Test export with all metadata fields."""
+ from local_deep_research.exporters import ExportOptions
+
+ options = ExportOptions(
+ title="Full Test Document",
+ metadata={"author": "Test Author", "date": "2024-01-15"},
+ )
+ result = exporter.export(simple_markdown, options)
+
+ assert result.content[:2] == b"PK"
+ assert "Full_Test_Document" in result.filename
+
+ def test_unicode_in_title(self, exporter, simple_markdown):
+ """Test export with unicode characters in title."""
+ from local_deep_research.exporters import ExportOptions
+
+ options = ExportOptions(title="Café naïve 日本語")
+ result = exporter.export(simple_markdown, options)
+
+ assert result.content[:2] == b"PK"
+
+ def test_unicode_in_author(self, exporter, simple_markdown):
+ """Test export with unicode characters in author."""
+ from local_deep_research.exporters import ExportOptions
+
+ options = ExportOptions(metadata={"author": "José García 山田太郎"})
+ result = exporter.export(simple_markdown, options)
+
+ assert result.content[:2] == b"PK"
+
+
+class TestODTExporterContentSizeLimit:
+ """Tests for content size limit enforcement."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create ODTExporter instance."""
+ from local_deep_research.exporters.odt_exporter import ODTExporter
+
+ return ODTExporter()
+
+ def test_raises_error_for_oversized_content(self, exporter):
+ """Test that ValueError is raised for content exceeding size limit."""
+ from local_deep_research.exporters.odt_exporter import MAX_CONTENT_SIZE
+
+ # Create content that exceeds the limit
+ oversized_content = "x" * (MAX_CONTENT_SIZE + 1)
+
+ with pytest.raises(ValueError) as exc_info:
+ exporter.export(oversized_content)
+
+ assert "exceeds maximum size" in str(exc_info.value)
+
+ def test_accepts_content_at_limit(self, exporter):
+ """Test that content at exactly the limit is accepted (doesn't raise)."""
+ from local_deep_research.exporters.odt_exporter import MAX_CONTENT_SIZE
+ import zipfile
+ import io
+
+ # Create content at exactly the limit
+ content_at_limit = "x" * MAX_CONTENT_SIZE
+
+ # Create a minimal valid ODT file for mocking
+ odt_buffer = io.BytesIO()
+ with zipfile.ZipFile(odt_buffer, "w") as zf:
+ zf.writestr("mimetype", "application/vnd.oasis.opendocument.text")
+ zf.writestr("content.xml", "<office:document-content/>")
+ mock_odt_bytes = odt_buffer.getvalue()
+
+ # Mock subprocess.run to avoid actually processing 50MB
+ mock_result = type(
+ "Result", (), {"stdout": mock_odt_bytes, "stderr": b""}
+ )()
+
+ with patch(
+ "local_deep_research.exporters.odt_exporter.subprocess.run",
+ return_value=mock_result,
+ ):
+ # This should not raise ValueError for size limit
+ result = exporter.export(content_at_limit)
+ assert result.content[:2] == b"PK"
+
+ def test_accepts_content_under_limit(self, exporter, simple_markdown):
+ """Test that content under the limit is accepted."""
+ result = exporter.export(simple_markdown)
+
+ assert result.content[:2] == b"PK"
+
+
+class TestODTExporterMetadataSanitization:
+ """Tests for metadata sanitization to prevent injection."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create ODTExporter instance."""
+ from local_deep_research.exporters.odt_exporter import ODTExporter
+
+ return ODTExporter()
+
+ def test_sanitizes_title_with_dashes(self, exporter, simple_markdown):
+ """Test that double dashes are removed from title."""
+ from local_deep_research.exporters import ExportOptions
+
+ # Title with potential argument injection pattern
+ options = ExportOptions(title="Title --extract-media=/tmp")
+ result = exporter.export(simple_markdown, options)
+
+ # Should succeed and produce valid ODT
+ assert result.content[:2] == b"PK"
+
+ def test_sanitizes_author_with_newlines(self, exporter, simple_markdown):
+ """Test that newlines are removed from author metadata."""
+ from local_deep_research.exporters import ExportOptions
+
+ options = ExportOptions(metadata={"author": "Author\nWith\nNewlines"})
+ result = exporter.export(simple_markdown, options)
+
+ assert result.content[:2] == b"PK"
+
+ def test_sanitizes_date_with_special_chars(self, exporter, simple_markdown):
+ """Test that date with injection patterns is sanitized."""
+ from local_deep_research.exporters import ExportOptions
+
+ options = ExportOptions(metadata={"date": "2024--01--15 --verbose"})
+ result = exporter.export(simple_markdown, options)
+
+ assert result.content[:2] == b"PK"
+
+
+class TestODTExporterInMemoryConversion:
+ """Tests verifying ODT conversion happens entirely in memory."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create ODTExporter instance."""
+ from local_deep_research.exporters.odt_exporter import ODTExporter
+
+ return ODTExporter()
+
+ def test_no_temp_files_used(self, exporter, simple_markdown):
+ """Test that conversion uses subprocess stdin/stdout, not temp files."""
+ import subprocess
+
+ with patch(
+ "local_deep_research.exporters.odt_exporter.subprocess.run",
+ wraps=subprocess.run,
+ ) as mock_run:
+ exporter.export(simple_markdown)
+
+ # Verify subprocess was called with stdin input and stdout capture
+ call_kwargs = mock_run.call_args
+ assert call_kwargs.kwargs.get("input") is not None
+ assert call_kwargs.kwargs.get("capture_output") is True
+
+ # Verify -o - (stdout) is in the command
+ cmd = call_kwargs.args[0]
+ assert "-o" in cmd
+ assert "-" in cmd[cmd.index("-o") + 1]
+
+ def test_pandoc_error_propagates_without_cleanup_needed(self, exporter):
+ """Test that pandoc errors propagate cleanly (no temp cleanup needed)."""
+ import subprocess
+
+ with patch(
+ "local_deep_research.exporters.odt_exporter.subprocess.run",
+ side_effect=subprocess.CalledProcessError(
+ 1, "pandoc", stderr=b"Pandoc failed"
+ ),
+ ):
+ with pytest.raises(RuntimeError, match="Pandoc conversion failed"):
+ exporter.export("# Test content")
+
+
+class TestODTExporterFooter:
+ """Tests for LDR attribution footer in output."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create ODTExporter instance."""
+ from local_deep_research.exporters.odt_exporter import ODTExporter
+
+ return ODTExporter()
+
+ def test_footer_content_present_in_output(self, exporter, simple_markdown):
+ """Test that LDR attribution footer appears in the ODT output."""
+ import io
+ import zipfile
+
+ result = exporter.export(simple_markdown)
+
+ # ODT is a ZIP archive - extract content.xml
+ with zipfile.ZipFile(io.BytesIO(result.content), "r") as zf:
+ content_xml = zf.read("content.xml").decode("utf-8")
+
+ # Verify footer text is present in the content
+ assert "Local Deep Research" in content_xml
+ assert "Open Source AI Research Assistant" in content_xml
diff --git a/tests/exporters/test_pdf_exporter.py b/tests/exporters/test_pdf_exporter.py
new file mode 100644
index 0000000000..29594df43a
--- /dev/null
+++ b/tests/exporters/test_pdf_exporter.py
@@ -0,0 +1,288 @@
+"""Tests for PDFExporter (refactored version)."""
+
+import pytest
+from unittest.mock import patch
+
+
+class TestPDFExporterProperties:
+ """Tests for PDFExporter properties."""
+
+ def test_format_name_is_pdf(self):
+ """Test that format_name is 'pdf'."""
+ from local_deep_research.exporters.pdf_exporter import PDFExporter
+
+ exporter = PDFExporter()
+
+ assert exporter.format_name == "pdf"
+
+ def test_file_extension_is_pdf(self):
+ """Test that file_extension is '.pdf'."""
+ from local_deep_research.exporters.pdf_exporter import PDFExporter
+
+ exporter = PDFExporter()
+
+ assert exporter.file_extension == ".pdf"
+
+ def test_mimetype_is_correct(self):
+ """Test that mimetype is correct for PDF."""
+ from local_deep_research.exporters.pdf_exporter import PDFExporter
+
+ exporter = PDFExporter()
+
+ assert exporter.mimetype == "application/pdf"
+
+
+class TestPDFExporterExport:
+ """Tests for PDFExporter.export method."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create PDFExporter instance."""
+ from local_deep_research.exporters.pdf_exporter import PDFExporter
+
+ return PDFExporter()
+
+ def test_returns_export_result(self, exporter, simple_markdown):
+ """Test that export returns ExportResult."""
+ from local_deep_research.exporters import ExportResult
+
+ result = exporter.export(simple_markdown)
+
+ assert isinstance(result, ExportResult)
+
+ def test_result_content_is_bytes(self, exporter, simple_markdown):
+ """Test that result content is bytes."""
+ result = exporter.export(simple_markdown)
+
+ assert isinstance(result.content, bytes)
+
+ def test_result_is_valid_pdf(self, exporter, simple_markdown):
+ """Test that result is a valid PDF (starts with %PDF)."""
+ result = exporter.export(simple_markdown)
+
+ assert result.content.startswith(b"%PDF")
+
+ def test_result_has_reasonable_size(self, exporter, simple_markdown):
+ """Test that generated PDF has a reasonable size."""
+ result = exporter.export(simple_markdown)
+
+ # A simple PDF should be at least a few KB
+ assert len(result.content) > 1000
+
+ def test_result_filename_uses_title(self, exporter, simple_markdown):
+ """Test that filename uses provided title."""
+ from local_deep_research.exporters import ExportOptions
+
+ options = ExportOptions(title="My Research Report")
+ result = exporter.export(simple_markdown, options)
+
+ assert "My_Research_Report" in result.filename
+ assert result.filename.endswith(".pdf")
+
+ def test_result_filename_default_when_no_title(
+ self, exporter, simple_markdown
+ ):
+ """Test that filename uses default when no title."""
+ result = exporter.export(simple_markdown)
+
+ assert "research_report" in result.filename
+ assert result.filename.endswith(".pdf")
+
+ def test_result_mimetype_is_correct(self, exporter, simple_markdown):
+ """Test that result mimetype is correct."""
+ result = exporter.export(simple_markdown)
+
+ assert result.mimetype == "application/pdf"
+
+ def test_handles_empty_markdown(self, exporter):
+ """Test handling of empty markdown."""
+ result = exporter.export("")
+
+ assert result.content.startswith(b"%PDF")
+
+ def test_handles_markdown_with_all_features(
+ self, exporter, sample_markdown
+ ):
+ """Test handling of markdown with tables, code, lists."""
+ result = exporter.export(sample_markdown)
+
+ assert result.content.startswith(b"%PDF")
+
+ def test_handles_special_characters(
+ self, exporter, markdown_with_special_chars
+ ):
+ """Test handling of special characters."""
+ result = exporter.export(markdown_with_special_chars)
+
+ assert result.content.startswith(b"%PDF")
+
+ def test_handles_large_markdown(self, exporter):
+ """Test handling of large markdown content."""
+ large_content = "# Large Document\n\n"
+ large_content += ("This is a paragraph. " * 100 + "\n\n") * 50
+
+ result = exporter.export(large_content)
+
+ assert result.content.startswith(b"%PDF")
+ # Large content should produce larger PDF
+ assert len(result.content) > 10000
+
+ def test_applies_custom_css(self, exporter, simple_markdown):
+ """Test that custom CSS can be applied."""
+ from local_deep_research.exporters import ExportOptions
+
+ custom_css = "body { font-family: serif; }"
+ options = ExportOptions(custom_options={"custom_css": custom_css})
+ result = exporter.export(simple_markdown, options)
+
+ assert result.content.startswith(b"%PDF")
+
+ def test_logs_pdf_size(self, exporter, simple_markdown):
+ """Test that PDF size is logged."""
+ with patch(
+ "local_deep_research.exporters.pdf_exporter.logger"
+ ) as mock_logger:
+ exporter.export(simple_markdown)
+
+ mock_logger.info.assert_called_once()
+ call_args = mock_logger.info.call_args[0][0]
+ assert "Generated PDF" in call_args
+ assert "bytes" in call_args
+
+
+class TestPDFExporterIntegration:
+ """Integration tests for PDFExporter with ExporterRegistry."""
+
+ def test_registered_in_registry(self):
+ """Test that PDFExporter is registered in the registry."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ assert ExporterRegistry.is_format_supported("pdf")
+
+ def test_can_get_from_registry(self):
+ """Test that PDFExporter can be retrieved from registry."""
+ from local_deep_research.exporters import ExporterRegistry
+ from local_deep_research.exporters.pdf_exporter import PDFExporter
+
+ exporter = ExporterRegistry.get_exporter("pdf")
+
+ assert isinstance(exporter, PDFExporter)
+
+ def test_export_via_registry(self, simple_markdown):
+ """Test export via registry lookup."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ exporter = ExporterRegistry.get_exporter("pdf")
+ result = exporter.export(simple_markdown)
+
+ assert result.content.startswith(b"%PDF")
+ assert result.filename.endswith(".pdf")
+
+
+class TestPDFExporterContentSizeLimit:
+ """Tests for content size limit enforcement."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create PDFExporter instance."""
+ from local_deep_research.exporters.pdf_exporter import PDFExporter
+
+ return PDFExporter()
+
+ def test_raises_error_for_oversized_content(self, exporter):
+ """Test that ValueError is raised for content exceeding size limit."""
+ from local_deep_research.exporters.pdf_exporter import MAX_CONTENT_SIZE
+
+ # Create content that exceeds the limit
+ oversized_content = "x" * (MAX_CONTENT_SIZE + 1)
+
+ with pytest.raises(ValueError) as exc_info:
+ exporter.export(oversized_content)
+
+ assert "exceeds maximum size" in str(exc_info.value)
+
+ def test_accepts_content_at_limit(self, exporter):
+ """Test that content at exactly the limit is accepted."""
+ from local_deep_research.exporters.pdf_exporter import MAX_CONTENT_SIZE
+
+ # Create content at exactly the limit
+ content_at_limit = "x" * MAX_CONTENT_SIZE
+
+ # Mock the PDF service to avoid processing large content
+ with patch.object(
+ exporter._pdf_service,
+ "markdown_to_pdf",
+ return_value=b"%PDF-1.4 mock content",
+ ):
+ result = exporter.export(content_at_limit)
+ assert result.content.startswith(b"%PDF")
+
+ def test_accepts_content_under_limit(self, exporter, simple_markdown):
+ """Test that content under the limit is accepted."""
+ result = exporter.export(simple_markdown)
+
+ assert result.content.startswith(b"%PDF")
+
+
+class TestPDFExporterErrorHandling:
+ """Tests for error handling in PDFExporter."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create PDFExporter instance."""
+ from local_deep_research.exporters.pdf_exporter import PDFExporter
+
+ return PDFExporter()
+
+ def test_logs_exception_on_error(self, exporter):
+ """Test that exceptions are logged."""
+ with patch.object(
+ exporter._pdf_service,
+ "markdown_to_pdf",
+ side_effect=Exception("Test error"),
+ ):
+ with patch(
+ "local_deep_research.exporters.pdf_exporter.logger"
+ ) as mock_logger:
+ with pytest.raises(Exception):
+ exporter.export("test")
+
+ mock_logger.exception.assert_called_once()
+
+
+class TestPDFExporterFilenameTruncation:
+ """Tests for filename truncation with long titles."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create PDFExporter instance."""
+ from local_deep_research.exporters.pdf_exporter import PDFExporter
+
+ return PDFExporter()
+
+ def test_filename_truncated_to_50_chars(self, exporter, simple_markdown):
+ """Test that filename is truncated when title exceeds 50 chars."""
+ from local_deep_research.exporters import ExportOptions
+
+ # Title with more than 50 characters
+ long_title = "A" * 60
+ options = ExportOptions(title=long_title)
+ result = exporter.export(simple_markdown, options)
+
+ # Filename should be truncated to 50 chars + extension
+ filename_without_ext = result.filename.rsplit(".", 1)[0]
+ assert len(filename_without_ext) == 50
+ assert result.filename.endswith(".pdf")
+
+ def test_filename_not_truncated_under_50_chars(
+ self, exporter, simple_markdown
+ ):
+ """Test that filename is not truncated when under 50 chars."""
+ from local_deep_research.exporters import ExportOptions
+
+ title = "Short Title"
+ options = ExportOptions(title=title)
+ result = exporter.export(simple_markdown, options)
+
+ assert "Short_Title" in result.filename
+ assert result.filename.endswith(".pdf")
diff --git a/tests/exporters/test_quarto_exporter.py b/tests/exporters/test_quarto_exporter.py
new file mode 100644
index 0000000000..5758177a84
--- /dev/null
+++ b/tests/exporters/test_quarto_exporter.py
@@ -0,0 +1,389 @@
+"""Tests for QuartoExporter."""
+
+import io
+import zipfile
+
+import pytest
+from unittest.mock import patch
+
+
+class TestQuartoExporterProperties:
+ """Tests for QuartoExporter properties."""
+
+ def test_format_name_is_quarto(self):
+ """Test that format_name is 'quarto'."""
+ from local_deep_research.exporters.quarto_exporter import QuartoExporter
+
+ exporter = QuartoExporter()
+
+ assert exporter.format_name == "quarto"
+
+ def test_file_extension_is_zip(self):
+ """Test that file_extension is '.zip'."""
+ from local_deep_research.exporters.quarto_exporter import QuartoExporter
+
+ exporter = QuartoExporter()
+
+ assert exporter.file_extension == ".zip"
+
+ def test_mimetype_is_correct(self):
+ """Test that mimetype is correct for Quarto (ZIP)."""
+ from local_deep_research.exporters.quarto_exporter import QuartoExporter
+
+ exporter = QuartoExporter()
+
+ assert exporter.mimetype == "application/zip"
+
+
+class TestQuartoExporterExport:
+ """Tests for QuartoExporter.export method."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create QuartoExporter instance."""
+ from local_deep_research.exporters.quarto_exporter import QuartoExporter
+
+ return QuartoExporter()
+
+ def test_returns_export_result(self, exporter, simple_markdown):
+ """Test that export returns ExportResult."""
+ from local_deep_research.exporters import ExportResult
+
+ result = exporter.export(simple_markdown)
+
+ assert isinstance(result, ExportResult)
+
+ def test_result_content_is_bytes(self, exporter, simple_markdown):
+ """Test that result content is bytes."""
+ result = exporter.export(simple_markdown)
+
+ assert isinstance(result.content, bytes)
+
+ def test_result_is_valid_zip(self, exporter, simple_markdown):
+ """Test that result is a valid ZIP file."""
+ result = exporter.export(simple_markdown)
+
+ # ZIP files start with PK
+ assert result.content[:2] == b"PK"
+
+ def test_result_has_reasonable_size(self, exporter, simple_markdown):
+ """Test that generated ZIP has a reasonable size."""
+ result = exporter.export(simple_markdown)
+
+ # A simple Quarto ZIP should have some content
+ assert len(result.content) > 100
+
+ def test_result_filename_uses_title(self, exporter, simple_markdown):
+ """Test that filename uses provided title."""
+ from local_deep_research.exporters import ExportOptions
+
+ options = ExportOptions(title="My Research Report")
+ result = exporter.export(simple_markdown, options)
+
+ assert "My_Research_Report" in result.filename
+ assert result.filename.endswith(".zip")
+
+ def test_result_filename_default_when_no_title(
+ self, exporter, simple_markdown
+ ):
+ """Test that filename uses default when no title."""
+ result = exporter.export(simple_markdown)
+
+ # Should use title from markdown or default
+ assert result.filename.endswith(".zip")
+ assert "_quarto.zip" in result.filename
+
+ def test_result_mimetype_is_correct(self, exporter, simple_markdown):
+ """Test that result mimetype is correct."""
+ result = exporter.export(simple_markdown)
+
+ assert result.mimetype == "application/zip"
+
+ def test_handles_empty_markdown(self, exporter):
+ """Test handling of empty markdown."""
+ result = exporter.export("")
+
+ assert result.content[:2] == b"PK"
+
+ def test_handles_markdown_with_all_features(
+ self, exporter, sample_markdown
+ ):
+ """Test handling of markdown with tables, code, lists."""
+ result = exporter.export(sample_markdown)
+
+ assert result.content[:2] == b"PK"
+
+ def test_handles_special_characters(
+ self, exporter, markdown_with_special_chars
+ ):
+ """Test handling of special characters."""
+ result = exporter.export(markdown_with_special_chars)
+
+ assert result.content[:2] == b"PK"
+
+ def test_handles_large_markdown(self, exporter):
+ """Test handling of large markdown content."""
+ large_content = "# Large Document\n\n"
+ large_content += ("This is a paragraph. " * 100 + "\n\n") * 50
+
+ result = exporter.export(large_content)
+
+ assert result.content[:2] == b"PK"
+ assert len(result.content) > 500
+
+ def test_logs_quarto_size(self, exporter, simple_markdown):
+ """Test that Quarto size is logged."""
+ with patch(
+ "local_deep_research.exporters.quarto_exporter.logger"
+ ) as mock_logger:
+ exporter.export(simple_markdown)
+
+ mock_logger.info.assert_called_once()
+ call_args = mock_logger.info.call_args[0][0]
+ assert "Generated Quarto" in call_args
+ assert "bytes" in call_args
+
+
+class TestQuartoExporterZipContents:
+ """Tests for Quarto ZIP file contents."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create QuartoExporter instance."""
+ from local_deep_research.exporters.quarto_exporter import QuartoExporter
+
+ return QuartoExporter()
+
+ def test_zip_contains_qmd_file(self, exporter, simple_markdown):
+ """Test that ZIP contains a .qmd file."""
+ result = exporter.export(simple_markdown)
+
+ with zipfile.ZipFile(io.BytesIO(result.content), "r") as zf:
+ file_names = zf.namelist()
+
+ qmd_files = [f for f in file_names if f.endswith(".qmd")]
+ assert len(qmd_files) == 1
+
+ def test_zip_contains_bib_file(self, exporter, simple_markdown):
+ """Test that ZIP contains a references.bib file."""
+ result = exporter.export(simple_markdown)
+
+ with zipfile.ZipFile(io.BytesIO(result.content), "r") as zf:
+ file_names = zf.namelist()
+
+ assert "references.bib" in file_names
+
+ def test_qmd_file_has_content(self, exporter, simple_markdown):
+ """Test that .qmd file has content."""
+ result = exporter.export(simple_markdown)
+
+ with zipfile.ZipFile(io.BytesIO(result.content), "r") as zf:
+ file_names = zf.namelist()
+ qmd_files = [f for f in file_names if f.endswith(".qmd")]
+ qmd_content = zf.read(qmd_files[0]).decode("utf-8")
+
+ assert len(qmd_content) > 0
+
+ def test_qmd_file_contains_yaml_header(self, exporter, sample_markdown):
+ """Test that .qmd file contains YAML header."""
+ result = exporter.export(sample_markdown)
+
+ with zipfile.ZipFile(io.BytesIO(result.content), "r") as zf:
+ file_names = zf.namelist()
+ qmd_files = [f for f in file_names if f.endswith(".qmd")]
+ qmd_content = zf.read(qmd_files[0]).decode("utf-8")
+
+ # Quarto documents typically have YAML front matter
+ assert "---" in qmd_content
+
+
+class TestQuartoExporterContentSizeLimit:
+ """Tests for content size limit enforcement."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create QuartoExporter instance."""
+ from local_deep_research.exporters.quarto_exporter import QuartoExporter
+
+ return QuartoExporter()
+
+ def test_raises_error_for_oversized_content(self, exporter):
+ """Test that ValueError is raised for content exceeding size limit."""
+ from local_deep_research.exporters.quarto_exporter import (
+ MAX_CONTENT_SIZE,
+ )
+
+ # Create content that exceeds the limit
+ oversized_content = "x" * (MAX_CONTENT_SIZE + 1)
+
+ with pytest.raises(ValueError) as exc_info:
+ exporter.export(oversized_content)
+
+ assert "exceeds maximum size" in str(exc_info.value)
+
+ def test_accepts_content_at_limit(self, exporter):
+ """Test that content at exactly the limit is accepted."""
+ from local_deep_research.exporters.quarto_exporter import (
+ MAX_CONTENT_SIZE,
+ )
+
+ # Create content at exactly the limit
+ content_at_limit = "x" * MAX_CONTENT_SIZE
+
+ # Mock the legacy exporter to avoid processing large content
+ with patch.object(
+ exporter._legacy,
+ "export_to_quarto",
+ return_value="---\ntitle: Test\n---\n\nContent",
+ ):
+ with patch.object(
+ exporter._legacy, "_generate_bibliography", return_value=""
+ ):
+ result = exporter.export(content_at_limit)
+ assert result.content[:2] == b"PK"
+
+ def test_accepts_content_under_limit(self, exporter, simple_markdown):
+ """Test that content under the limit is accepted."""
+ result = exporter.export(simple_markdown)
+
+ assert result.content[:2] == b"PK"
+
+
+class TestQuartoExporterErrorHandling:
+ """Tests for error handling in QuartoExporter."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create QuartoExporter instance."""
+ from local_deep_research.exporters.quarto_exporter import QuartoExporter
+
+ return QuartoExporter()
+
+ def test_logs_exception_on_error(self, exporter):
+ """Test that exceptions are logged."""
+ with patch.object(
+ exporter._legacy,
+ "export_to_quarto",
+ side_effect=Exception("Test error"),
+ ):
+ with patch(
+ "local_deep_research.exporters.quarto_exporter.logger"
+ ) as mock_logger:
+ with pytest.raises(Exception):
+ exporter.export("test")
+
+ mock_logger.exception.assert_called_once()
+
+
+class TestQuartoExporterIntegration:
+ """Integration tests for QuartoExporter with ExporterRegistry."""
+
+ def test_registered_in_registry(self):
+ """Test that QuartoExporter is registered in the registry."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ assert ExporterRegistry.is_format_supported("quarto")
+
+ def test_can_get_from_registry(self):
+ """Test that QuartoExporter can be retrieved from registry."""
+ from local_deep_research.exporters import ExporterRegistry
+ from local_deep_research.exporters.quarto_exporter import QuartoExporter
+
+ exporter = ExporterRegistry.get_exporter("quarto")
+
+ assert isinstance(exporter, QuartoExporter)
+
+ def test_export_via_registry(self, simple_markdown):
+ """Test export via registry lookup."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ exporter = ExporterRegistry.get_exporter("quarto")
+ result = exporter.export(simple_markdown)
+
+ assert result.content[:2] == b"PK"
+ assert result.filename.endswith(".zip")
+
+
+class TestQuartoExporterFilenameTruncation:
+ """Tests for filename truncation with long titles."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create QuartoExporter instance."""
+ from local_deep_research.exporters.quarto_exporter import QuartoExporter
+
+ return QuartoExporter()
+
+ def test_filename_truncated_to_50_chars(self, exporter, simple_markdown):
+ """Test that filename is truncated when title exceeds 50 chars."""
+ from local_deep_research.exporters import ExportOptions
+
+ # Title with more than 50 characters
+ long_title = "A" * 60
+ options = ExportOptions(title=long_title)
+ result = exporter.export(simple_markdown, options)
+
+ # Filename should have truncated base + _quarto.zip suffix
+ assert result.filename.endswith("_quarto.zip")
+ # The base (without _quarto.zip) should be 50 chars
+ base_name = result.filename.replace("_quarto.zip", "")
+ assert len(base_name) == 50
+
+ def test_filename_not_truncated_under_50_chars(
+ self, exporter, simple_markdown
+ ):
+ """Test that filename is not truncated when under 50 chars."""
+ from local_deep_research.exporters import ExportOptions
+
+ title = "Short Title"
+ options = ExportOptions(title=title)
+ result = exporter.export(simple_markdown, options)
+
+ assert "Short_Title" in result.filename
+ assert result.filename.endswith("_quarto.zip")
+
+
+class TestQuartoExporterTitleExtraction:
+ """Tests for title extraction from markdown."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create QuartoExporter instance."""
+ from local_deep_research.exporters.quarto_exporter import QuartoExporter
+
+ return QuartoExporter()
+
+ def test_extracts_title_for_yaml_header(self, exporter):
+ """Test that title is extracted from markdown for YAML header.
+
+ When no title is provided in options, the exporter extracts it from
+ the first markdown heading for use in the YAML front matter.
+ The filename uses the default "research_report" when no title option
+ is provided.
+ """
+ markdown = "# My Document Title\n\nSome content here."
+
+ result = exporter.export(markdown)
+
+ # Filename uses default when no title in options
+ assert "research_report" in result.filename
+ assert result.filename.endswith("_quarto.zip")
+
+ # But the YAML header inside the qmd should contain the extracted title
+ with zipfile.ZipFile(io.BytesIO(result.content), "r") as zf:
+ file_names = zf.namelist()
+ qmd_files = [f for f in file_names if f.endswith(".qmd")]
+ qmd_content = zf.read(qmd_files[0]).decode("utf-8")
+
+ # The title should appear in the YAML front matter
+ assert "My Document Title" in qmd_content
+
+ def test_uses_default_title_when_no_heading(self, exporter):
+ """Test that default title is used when no heading present."""
+ markdown = "Just some content without a heading."
+
+ result = exporter.export(markdown)
+
+ # Should still create valid output
+ assert result.content[:2] == b"PK"
+ assert result.filename.endswith("_quarto.zip")
diff --git a/tests/exporters/test_registry.py b/tests/exporters/test_registry.py
new file mode 100644
index 0000000000..7f5e467d92
--- /dev/null
+++ b/tests/exporters/test_registry.py
@@ -0,0 +1,131 @@
+"""Tests for ExporterRegistry."""
+
+
+class TestExporterRegistryBasics:
+ """Basic tests for ExporterRegistry functionality."""
+
+ def test_registry_has_exporters_registered(self):
+ """Test that exporters are automatically registered on import."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ formats = ExporterRegistry.get_available_formats()
+
+ # Should have all core formats
+ assert "pdf" in formats
+ assert "odt" in formats
+ assert "latex" in formats
+ assert "quarto" in formats
+ assert "ris" in formats
+
+ def test_get_exporter_returns_instance(self):
+ """Test that get_exporter returns an exporter instance."""
+ from local_deep_research.exporters import ExporterRegistry, BaseExporter
+
+ exporter = ExporterRegistry.get_exporter("pdf")
+
+ assert exporter is not None
+ assert isinstance(exporter, BaseExporter)
+
+ def test_get_exporter_returns_none_for_unknown_format(self):
+ """Test that get_exporter returns None for unknown formats."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ exporter = ExporterRegistry.get_exporter("unknown_format")
+
+ assert exporter is None
+
+ def test_is_format_supported_returns_true_for_known_format(self):
+ """Test is_format_supported for known formats."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ assert ExporterRegistry.is_format_supported("pdf") is True
+ assert ExporterRegistry.is_format_supported("odt") is True
+ assert ExporterRegistry.is_format_supported("latex") is True
+
+ def test_is_format_supported_returns_false_for_unknown_format(self):
+ """Test is_format_supported for unknown formats."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ assert ExporterRegistry.is_format_supported("unknown") is False
+ assert ExporterRegistry.is_format_supported("xyz") is False
+
+ def test_format_names_are_case_insensitive(self):
+ """Test that format names are case insensitive."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ # Should work with different cases
+ assert ExporterRegistry.is_format_supported("PDF") is True
+ assert ExporterRegistry.is_format_supported("Pdf") is True
+ assert ExporterRegistry.is_format_supported("pdf") is True
+
+ # get_exporter should also be case insensitive
+ assert ExporterRegistry.get_exporter("PDF") is not None
+ assert ExporterRegistry.get_exporter("Pdf") is not None
+
+
+class TestExporterRegistrySingleton:
+ """Tests for singleton behavior of registered exporters."""
+
+ def test_get_exporter_returns_same_instance(self):
+ """Test that get_exporter returns the same instance."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ exporter1 = ExporterRegistry.get_exporter("pdf")
+ exporter2 = ExporterRegistry.get_exporter("pdf")
+
+ assert exporter1 is exporter2
+
+ def test_different_formats_return_different_instances(self):
+ """Test that different formats return different exporters."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ pdf_exporter = ExporterRegistry.get_exporter("pdf")
+ latex_exporter = ExporterRegistry.get_exporter("latex")
+
+ assert pdf_exporter is not latex_exporter
+
+
+class TestExporterRegistryCustomRegistration:
+ """Tests for custom exporter registration."""
+
+ def test_register_decorator_works(self):
+ """Test that @register decorator works for new exporters."""
+ from local_deep_research.exporters import (
+ ExporterRegistry,
+ BaseExporter,
+ ExportResult,
+ )
+
+ # Create a custom exporter
+ @ExporterRegistry.register
+ class TestExporter(BaseExporter):
+ @property
+ def format_name(self) -> str:
+ return "test_format"
+
+ @property
+ def file_extension(self) -> str:
+ return ".test"
+
+ @property
+ def mimetype(self) -> str:
+ return "application/x-test"
+
+ def export(self, markdown_content, options=None):
+ return ExportResult(
+ content=b"test",
+ filename="test.test",
+ mimetype=self.mimetype,
+ )
+
+ # Should be registered
+ assert ExporterRegistry.is_format_supported("test_format")
+ exporter = ExporterRegistry.get_exporter("test_format")
+ assert exporter is not None
+ assert exporter.format_name == "test_format"
+
+ # Clean up - remove from registry
+ if "test_format" in ExporterRegistry._exporters:
+ del ExporterRegistry._exporters["test_format"]
+ if "test_format" in ExporterRegistry._instances:
+ del ExporterRegistry._instances["test_format"]
diff --git a/tests/exporters/test_ris_exporter.py b/tests/exporters/test_ris_exporter.py
new file mode 100644
index 0000000000..e8c322d77e
--- /dev/null
+++ b/tests/exporters/test_ris_exporter.py
@@ -0,0 +1,320 @@
+"""Tests for RISExporter."""
+
+import pytest
+from unittest.mock import patch
+
+
+class TestRISExporterProperties:
+ """Tests for RISExporter properties."""
+
+ def test_format_name_is_ris(self):
+ """Test that format_name is 'ris'."""
+ from local_deep_research.exporters.ris_exporter import RISExporter
+
+ exporter = RISExporter()
+
+ assert exporter.format_name == "ris"
+
+ def test_file_extension_is_ris(self):
+ """Test that file_extension is '.ris'."""
+ from local_deep_research.exporters.ris_exporter import RISExporter
+
+ exporter = RISExporter()
+
+ assert exporter.file_extension == ".ris"
+
+ def test_mimetype_is_correct(self):
+ """Test that mimetype is correct for RIS."""
+ from local_deep_research.exporters.ris_exporter import RISExporter
+
+ exporter = RISExporter()
+
+ assert exporter.mimetype == "text/plain"
+
+
+class TestRISExporterExport:
+ """Tests for RISExporter.export method."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create RISExporter instance."""
+ from local_deep_research.exporters.ris_exporter import RISExporter
+
+ return RISExporter()
+
+ @pytest.fixture
+ def markdown_with_sources(self):
+ """Markdown content with sources for RIS export."""
+ return """# Research Report
+
+This is a test report with sources.
+
+## Sources
+
+[1] First Source Title
+URL: https://example.com/source1
+
+[2] Second Source Title
+URL: https://example.com/source2
+"""
+
+ def test_returns_export_result(self, exporter, markdown_with_sources):
+ """Test that export returns ExportResult."""
+ from local_deep_research.exporters import ExportResult
+
+ result = exporter.export(markdown_with_sources)
+
+ assert isinstance(result, ExportResult)
+
+ def test_result_content_is_bytes(self, exporter, markdown_with_sources):
+ """Test that result content is bytes."""
+ result = exporter.export(markdown_with_sources)
+
+ assert isinstance(result.content, bytes)
+
+ def test_result_filename_uses_title(self, exporter, markdown_with_sources):
+ """Test that filename uses provided title."""
+ from local_deep_research.exporters import ExportOptions
+
+ options = ExportOptions(title="My Research Report")
+ result = exporter.export(markdown_with_sources, options)
+
+ assert "My_Research_Report" in result.filename
+ assert result.filename.endswith(".ris")
+
+ def test_result_filename_default_when_no_title(
+ self, exporter, markdown_with_sources
+ ):
+ """Test that filename uses default when no title."""
+ result = exporter.export(markdown_with_sources)
+
+ assert "research_report" in result.filename
+ assert result.filename.endswith(".ris")
+
+ def test_result_mimetype_is_correct(self, exporter, markdown_with_sources):
+ """Test that result mimetype is correct."""
+ result = exporter.export(markdown_with_sources)
+
+ assert result.mimetype == "text/plain"
+
+ def test_handles_empty_markdown(self, exporter):
+ """Test handling of empty markdown."""
+ result = exporter.export("")
+
+ assert isinstance(result.content, bytes)
+
+ def test_handles_markdown_without_sources(self, exporter, simple_markdown):
+ """Test handling of markdown without sources section."""
+ result = exporter.export(simple_markdown)
+
+ assert isinstance(result.content, bytes)
+
+ def test_handles_special_characters(
+ self, exporter, markdown_with_special_chars
+ ):
+ """Test handling of special characters."""
+ result = exporter.export(markdown_with_special_chars)
+
+ assert isinstance(result.content, bytes)
+
+ def test_logs_ris_size(self, exporter, markdown_with_sources):
+ """Test that RIS size is logged."""
+ with patch(
+ "local_deep_research.exporters.ris_exporter.logger"
+ ) as mock_logger:
+ exporter.export(markdown_with_sources)
+
+ mock_logger.info.assert_called_once()
+ call_args = mock_logger.info.call_args[0][0]
+ assert "Generated RIS" in call_args
+ assert "bytes" in call_args
+
+
+class TestRISExporterOutput:
+ """Tests for RIS format output structure."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create RISExporter instance."""
+ from local_deep_research.exporters.ris_exporter import RISExporter
+
+ return RISExporter()
+
+ @pytest.fixture
+ def markdown_with_sources(self):
+ """Markdown content with sources for RIS export."""
+ return """# Research Report
+
+This is a test report with sources.
+
+## Sources
+
+[1] First Source Title
+URL: https://example.com/source1
+
+[2] Second Source Title
+URL: https://example.com/source2
+"""
+
+ def test_ris_contains_type_tag(self, exporter, markdown_with_sources):
+ """Test that RIS output contains TY (type) tag."""
+ result = exporter.export(markdown_with_sources)
+ content = result.content.decode("utf-8")
+
+ # RIS entries start with TY tag
+ assert "TY -" in content
+
+ def test_ris_contains_end_record(self, exporter, markdown_with_sources):
+ """Test that RIS output contains ER (end record) tag."""
+ result = exporter.export(markdown_with_sources)
+ content = result.content.decode("utf-8")
+
+ # RIS entries end with ER tag
+ assert "ER -" in content
+
+ def test_ris_contains_url_for_sources(
+ self, exporter, markdown_with_sources
+ ):
+ """Test that RIS output contains URL when sources have URLs."""
+ result = exporter.export(markdown_with_sources)
+ content = result.content.decode("utf-8")
+
+ # Check for URL tag (UR) or the actual URL
+ # Note: actual presence depends on the legacy exporter implementation
+ assert isinstance(content, str)
+
+
+class TestRISExporterContentSizeLimit:
+ """Tests for content size limit enforcement."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create RISExporter instance."""
+ from local_deep_research.exporters.ris_exporter import RISExporter
+
+ return RISExporter()
+
+ def test_raises_error_for_oversized_content(self, exporter):
+ """Test that ValueError is raised for content exceeding size limit."""
+ from local_deep_research.exporters.ris_exporter import MAX_CONTENT_SIZE
+
+ # Create content that exceeds the limit
+ oversized_content = "x" * (MAX_CONTENT_SIZE + 1)
+
+ with pytest.raises(ValueError) as exc_info:
+ exporter.export(oversized_content)
+
+ assert "exceeds maximum size" in str(exc_info.value)
+
+ def test_accepts_content_at_limit(self, exporter):
+ """Test that content at exactly the limit is accepted."""
+ from local_deep_research.exporters.ris_exporter import MAX_CONTENT_SIZE
+
+ # Create content at exactly the limit
+ content_at_limit = "x" * MAX_CONTENT_SIZE
+
+ # Mock the legacy exporter to avoid processing large content
+ with patch.object(
+ exporter._legacy, "export_to_ris", return_value="TY - WEB\nER -"
+ ):
+ result = exporter.export(content_at_limit)
+ assert isinstance(result.content, bytes)
+
+ def test_accepts_content_under_limit(self, exporter, simple_markdown):
+ """Test that content under the limit is accepted."""
+ result = exporter.export(simple_markdown)
+
+ assert isinstance(result.content, bytes)
+
+
+class TestRISExporterErrorHandling:
+ """Tests for error handling in RISExporter."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create RISExporter instance."""
+ from local_deep_research.exporters.ris_exporter import RISExporter
+
+ return RISExporter()
+
+ def test_logs_exception_on_error(self, exporter):
+ """Test that exceptions are logged."""
+ with patch.object(
+ exporter._legacy,
+ "export_to_ris",
+ side_effect=Exception("Test error"),
+ ):
+ with patch(
+ "local_deep_research.exporters.ris_exporter.logger"
+ ) as mock_logger:
+ with pytest.raises(Exception):
+ exporter.export("test")
+
+ mock_logger.exception.assert_called_once()
+
+
+class TestRISExporterIntegration:
+ """Integration tests for RISExporter with ExporterRegistry."""
+
+ def test_registered_in_registry(self):
+ """Test that RISExporter is registered in the registry."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ assert ExporterRegistry.is_format_supported("ris")
+
+ def test_can_get_from_registry(self):
+ """Test that RISExporter can be retrieved from registry."""
+ from local_deep_research.exporters import ExporterRegistry
+ from local_deep_research.exporters.ris_exporter import RISExporter
+
+ exporter = ExporterRegistry.get_exporter("ris")
+
+ assert isinstance(exporter, RISExporter)
+
+ def test_export_via_registry(self, simple_markdown):
+ """Test export via registry lookup."""
+ from local_deep_research.exporters import ExporterRegistry
+
+ exporter = ExporterRegistry.get_exporter("ris")
+ result = exporter.export(simple_markdown)
+
+ assert isinstance(result.content, bytes)
+ assert result.filename.endswith(".ris")
+
+
+class TestRISExporterFilenameTruncation:
+ """Tests for filename truncation with long titles."""
+
+ @pytest.fixture
+ def exporter(self):
+ """Create RISExporter instance."""
+ from local_deep_research.exporters.ris_exporter import RISExporter
+
+ return RISExporter()
+
+ def test_filename_truncated_to_50_chars(self, exporter, simple_markdown):
+ """Test that filename is truncated when title exceeds 50 chars."""
+ from local_deep_research.exporters import ExportOptions
+
+ # Title with more than 50 characters
+ long_title = "A" * 60
+ options = ExportOptions(title=long_title)
+ result = exporter.export(simple_markdown, options)
+
+ # Filename should be truncated to 50 chars + extension
+ filename_without_ext = result.filename.rsplit(".", 1)[0]
+ assert len(filename_without_ext) == 50
+ assert result.filename.endswith(".ris")
+
+ def test_filename_not_truncated_under_50_chars(
+ self, exporter, simple_markdown
+ ):
+ """Test that filename is not truncated when under 50 chars."""
+ from local_deep_research.exporters import ExportOptions
+
+ title = "Short Title"
+ options = ExportOptions(title=title)
+ result = exporter.export(simple_markdown, options)
+
+ assert "Short_Title" in result.filename
+ assert result.filename.endswith(".ris")
diff --git a/tests/mock_modules.py b/tests/mock_modules.py
index 040620a175..bf84b6d47e 100644
--- a/tests/mock_modules.py
+++ b/tests/mock_modules.py
@@ -42,13 +42,9 @@ def patch_module(monkeypatch, module_path: str, mock_module: types.ModuleType):
"""
monkeypatch.setitem(sys.modules, module_path, mock_module)
- # Also patch direct imports
- parts = module_path.split(".")
- if len(parts) > 1:
- parent_path = ".".join(parts[:-1])
- module_name = parts[-1]
- if parent_path in sys.modules:
- monkeypatch.setattr(f"{parent_path}.{module_name}", mock_module)
+ # Note: We only use sys.modules patching. The previous setattr approach
+ # could fail when the parent module doesn't have the attribute yet,
+ # causing AttributeError in parallel test execution.
def create_mock_llm_config(monkeypatch):
diff --git a/tests/report/test_report_generator_extended.py b/tests/report/test_report_generator_report_extended.py
similarity index 100%
rename from tests/report/test_report_generator_extended.py
rename to tests/report/test_report_generator_report_extended.py
diff --git a/tests/ui_tests/test_export_dropdown.js b/tests/ui_tests/test_export_dropdown.js
new file mode 100644
index 0000000000..4d9f9ce7a3
--- /dev/null
+++ b/tests/ui_tests/test_export_dropdown.js
@@ -0,0 +1,269 @@
+/**
+ * Export Dropdown UI Tests
+ *
+ * Tests for the export dropdown functionality on the results page.
+ * Verifies that:
+ * 1. PDF button is separate from dropdown
+ * 2. Export dropdown opens and shows all formats
+ * 3. All expected export options are present (Markdown, LaTeX, Quarto, ODT, RIS)
+ */
+
+const puppeteer = require('puppeteer');
+const AuthHelper = require('./auth_helper');
+const { getPuppeteerLaunchOptions } = require('./puppeteer_config');
+
+const BASE_URL = 'http://127.0.0.1:5000';
+
+const colors = {
+ reset: '\x1b[0m',
+ green: '\x1b[32m',
+ red: '\x1b[31m',
+ yellow: '\x1b[33m',
+ blue: '\x1b[34m',
+ cyan: '\x1b[36m'
+};
+
+function log(message, type = 'info') {
+ const timestamp = new Date().toISOString().split('T')[1].split('.')[0];
+ const typeColors = {
+ 'info': colors.cyan,
+ 'success': colors.green,
+ 'error': colors.red,
+ 'warning': colors.yellow,
+ 'section': colors.blue
+ };
+ const color = typeColors[type] || colors.reset;
+ console.log(`${color}[${timestamp}] ${message}${colors.reset}`);
+}
+
+async function delay(ms) {
+ return new Promise(resolve => setTimeout(resolve, ms));
+}
+
+async function testExportDropdown() {
+ const browser = await puppeteer.launch(getPuppeteerLaunchOptions());
+ const page = await browser.newPage();
+
+ // Track test results
+ const results = {
+ passed: 0,
+ failed: 0,
+ tests: []
+ };
+
+ function recordTest(name, passed, details = '') {
+ results.tests.push({ name, passed, details });
+ if (passed) {
+ results.passed++;
+ log(`✅ ${name}`, 'success');
+ } else {
+ results.failed++;
+ log(`❌ ${name}: ${details}`, 'error');
+ }
+ }
+
+ try {
+ // Authenticate
+ const authHelper = new AuthHelper(page, BASE_URL);
+ log('🔐 Authenticating...', 'info');
+ await authHelper.ensureAuthenticated();
+ log('✅ Authenticated', 'success');
+
+ // Navigate to history to find a completed research
+ log('\n=== FINDING COMPLETED RESEARCH ===', 'section');
+ await page.goto(`${BASE_URL}/history`, { waitUntil: 'domcontentloaded' });
+ await delay(2000);
+
+ // Look for a completed research item
+ const completedResearch = await page.evaluate(() => {
+ const items = document.querySelectorAll('.ldr-history-item, [data-research-id]');
+ for (const item of items) {
+ const status = item.querySelector('.ldr-status-badge, .status-badge');
+ if (status && status.textContent.toLowerCase().includes('completed')) {
+ const link = item.querySelector('a[href*="/results/"]');
+ return link ? link.href : null;
+ }
+ }
+ // If no completed research, return the first research link
+ const firstLink = document.querySelector('a[href*="/results/"]');
+ return firstLink ? firstLink.href : null;
+ });
+
+ if (!completedResearch) {
+ log('⚠️ No completed research found, creating mock results page test', 'warning');
+ // We can still test the HTML structure by navigating to a fake results URL
+ // and checking if the export elements exist in the template
+ await page.goto(`${BASE_URL}/results/test-123`, { waitUntil: 'domcontentloaded' });
+ } else {
+ log(`📍 Navigating to: ${completedResearch}`, 'info');
+ await page.goto(completedResearch, { waitUntil: 'domcontentloaded' });
+ }
+
+ await delay(2000);
+
+ log('\n=== TESTING EXPORT UI STRUCTURE ===', 'section');
+
+ // Test 1: PDF button exists and is separate from dropdown
+ const pdfButtonExists = await page.evaluate(() => {
+ const pdfBtn = document.getElementById('download-pdf-btn');
+ if (!pdfBtn) return { exists: false };
+
+ // Check it's not inside a dropdown
+ const isInDropdown = pdfBtn.closest('.dropdown-menu') !== null;
+ return {
+ exists: true,
+ isInDropdown,
+ text: pdfBtn.textContent.trim(),
+ hasIcon: !!pdfBtn.querySelector('i.fa-file-pdf')
+ };
+ });
+
+ recordTest(
+ 'PDF button exists and is separate from dropdown',
+ pdfButtonExists.exists && !pdfButtonExists.isInDropdown,
+ pdfButtonExists.exists ?
+ (pdfButtonExists.isInDropdown ? 'PDF button is inside dropdown' : '') :
+ 'PDF button not found'
+ );
+
+ // Test 2: Export dropdown button exists
+ const exportDropdownExists = await page.evaluate(() => {
+ const dropdownBtn = document.getElementById('export-dropdown-btn');
+ if (!dropdownBtn) return { exists: false };
+
+ return {
+ exists: true,
+ text: dropdownBtn.textContent.trim(),
+ hasToggle: dropdownBtn.classList.contains('dropdown-toggle'),
+ hasIcon: !!dropdownBtn.querySelector('i.fa-download')
+ };
+ });
+
+ recordTest(
+ 'Export dropdown button exists',
+ exportDropdownExists.exists && exportDropdownExists.hasToggle,
+ exportDropdownExists.exists ? '' : 'Export dropdown button not found'
+ );
+
+ // Test 3: Click dropdown and verify it opens
+ if (exportDropdownExists.exists) {
+ await page.click('#export-dropdown-btn');
+ await delay(500);
+
+ const dropdownOpened = await page.evaluate(() => {
+ const menu = document.querySelector('#export-dropdown-btn + .dropdown-menu, .dropdown-menu[aria-labelledby="export-dropdown-btn"]');
+ if (!menu) return { opened: false, reason: 'Menu not found' };
+
+ const isVisible = menu.classList.contains('show') ||
+ getComputedStyle(menu).display !== 'none';
+ return { opened: isVisible, reason: isVisible ? '' : 'Menu not visible' };
+ });
+
+ recordTest(
+ 'Export dropdown opens on click',
+ dropdownOpened.opened,
+ dropdownOpened.reason
+ );
+ }
+
+ // Test 4: Check all expected export options exist
+ const expectedFormats = [
+ { id: 'export-markdown-btn', name: 'Markdown', icon: 'fa-file-alt' },
+ { id: 'export-latex-btn', name: 'LaTeX', icon: 'fa-file-code' },
+ { id: 'export-quarto-btn', name: 'Quarto', icon: 'fa-file-code' },
+ { id: 'export-odt-btn', name: 'ODT (LibreOffice)', icon: 'fa-file-word' },
+ { id: 'export-ris-btn', name: 'RIS (Zotero)', icon: 'fa-file-export' }
+ ];
+
+ for (const format of expectedFormats) {
+ const formatExists = await page.evaluate((formatId) => {
+ const btn = document.getElementById(formatId);
+ if (!btn) return { exists: false };
+
+ return {
+ exists: true,
+ text: btn.textContent.trim(),
+ isInDropdown: btn.closest('.dropdown-menu') !== null,
+ isClickable: btn.tagName === 'A' || btn.tagName === 'BUTTON'
+ };
+ }, format.id);
+
+ recordTest(
+ `${format.name} export option exists in dropdown`,
+ formatExists.exists && formatExists.isInDropdown,
+ formatExists.exists ?
+ (formatExists.isInDropdown ? '' : 'Not in dropdown menu') :
+ `${format.id} not found`
+ );
+ }
+
+ // Test 5: Verify dropdown has proper structure (dividers)
+ const dropdownStructure = await page.evaluate(() => {
+ const menu = document.querySelector('.dropdown-menu[aria-labelledby="export-dropdown-btn"]');
+ if (!menu) return { valid: false, reason: 'Menu not found' };
+
+ const dividers = menu.querySelectorAll('.dropdown-divider, hr.dropdown-divider');
+ const items = menu.querySelectorAll('.dropdown-item');
+
+ return {
+ valid: true,
+ itemCount: items.length,
+ dividerCount: dividers.length,
+ hasProperStructure: items.length >= 5 && dividers.length >= 2
+ };
+ });
+
+ recordTest(
+ 'Dropdown has proper structure with dividers',
+ dropdownStructure.valid && dropdownStructure.hasProperStructure,
+ dropdownStructure.valid ?
+ `${dropdownStructure.itemCount} items, ${dropdownStructure.dividerCount} dividers` :
+ dropdownStructure.reason
+ );
+
+ // Test 6: Close dropdown by clicking elsewhere
+ await page.click('body');
+ await delay(300);
+
+ const dropdownClosed = await page.evaluate(() => {
+ const menu = document.querySelector('.dropdown-menu[aria-labelledby="export-dropdown-btn"]');
+ if (!menu) return { closed: true };
+
+ const isHidden = !menu.classList.contains('show') &&
+ getComputedStyle(menu).display === 'none';
+ return { closed: isHidden };
+ });
+
+ recordTest(
+ 'Dropdown closes when clicking elsewhere',
+ dropdownClosed.closed,
+ dropdownClosed.closed ? '' : 'Dropdown still visible'
+ );
+
+ // Print summary
+ log('\n=== TEST SUMMARY ===', 'section');
+ log(`Total: ${results.passed + results.failed} tests`, 'info');
+ log(`Passed: ${results.passed}`, 'success');
+ if (results.failed > 0) {
+ log(`Failed: ${results.failed}`, 'error');
+ }
+
+ if (results.failed > 0) {
+ throw new Error(`${results.failed} test(s) failed`);
+ }
+
+ log('\n✅ All export dropdown tests passed!', 'success');
+
+ } catch (error) {
+ log(`\n❌ Test failed: ${error.message}`, 'error');
+ throw error;
+ } finally {
+ await browser.close();
+ }
+}
+
+// Run tests
+testExportDropdown().catch(error => {
+ console.error('Test execution failed:', error);
+ process.exit(1);
+});
diff --git a/tests/web/services/test_research_service.py b/tests/web/services/test_research_service.py
index 5463124219..d7796f5029 100644
--- a/tests/web/services/test_research_service.py
+++ b/tests/web/services/test_research_service.py
@@ -139,17 +139,12 @@ class TestExportReportToMemory:
assert mimetype == "application/zip"
assert isinstance(content, bytes)
- @patch("local_deep_research.web.services.pdf_service.get_pdf_service")
- def test_export_pdf_format(self, mock_get_pdf):
+ def test_export_pdf_format(self):
"""export_report_to_memory generates PDF content."""
from local_deep_research.web.services.research_service import (
export_report_to_memory,
)
- mock_pdf_service = Mock()
- mock_pdf_service.markdown_to_pdf.return_value = b"PDF content"
- mock_get_pdf.return_value = mock_pdf_service
-
markdown_content = "# Test Report\n\nThis is test content."
content, filename, mimetype = export_report_to_memory(
@@ -158,7 +153,8 @@ class TestExportReportToMemory:
assert filename.endswith(".pdf")
assert mimetype == "application/pdf"
- assert content == b"PDF content"
+ # PDF files start with %PDF
+ assert content.startswith(b"%PDF")
class TestSaveResearchStrategy:
@@ -744,3 +740,172 @@ class TestResearchServiceExportFormats:
)
assert "Unsupported export format" in str(exc_info.value)
+
+
+class TestTitlePrepending:
+ """Test title prepending behavior for different export formats.
+
+ The export_report_to_memory function should prepend a markdown title
+ for formats that render markdown (PDF, ODT), but NOT for formats
+ where it would corrupt the output (RIS, LaTeX, Quarto).
+ """
+
+ def test_pdf_gets_title_prepended(self):
+ """PDF format should get markdown title prepended."""
+ from local_deep_research.web.services.research_service import (
+ export_report_to_memory,
+ )
+
+ # Content without a heading
+ markdown_content = "This is content without a title heading."
+ title = "My Report Title"
+
+ content, filename, mimetype = export_report_to_memory(
+ markdown_content, "pdf", title=title
+ )
+
+ # PDF should be valid and have the title (we can't easily inspect content,
+ # but we verify the export succeeded and returned valid PDF)
+ assert content.startswith(b"%PDF")
+ assert filename.endswith(".pdf")
+
+ def test_odt_gets_title_prepended(self):
+ """ODT format should get markdown title prepended."""
+ # Check if pandoc is available
+ try:
+ import pypandoc
+
+ pypandoc.get_pandoc_version()
+ except (ImportError, OSError):
+ import pytest
+
+ pytest.skip("Pandoc is not installed (required for ODT export)")
+
+ from local_deep_research.web.services.research_service import (
+ export_report_to_memory,
+ )
+
+ # Content without a heading
+ markdown_content = "This is content without a title heading."
+ title = "My Report Title"
+
+ content, filename, mimetype = export_report_to_memory(
+ markdown_content, "odt", title=title
+ )
+
+ # ODT should be valid ZIP and have the title
+ assert content[:2] == b"PK"
+ assert filename.endswith(".odt")
+
+ def test_ris_does_not_get_title_prepended(self):
+ """RIS format should NOT get title prepended (would corrupt output).
+
+ RIS is a bibliographic format with strict structure. Prepending
+ a markdown title would corrupt the output.
+ """
+ from local_deep_research.web.services.research_service import (
+ export_report_to_memory,
+ )
+
+ # Content with sources
+ markdown_content = """# Research Report
+
+Some content here.
+
+## Sources
+
+[1] First Source
+URL: https://example.com/1
+"""
+ title = "My Report Title"
+
+ content, filename, mimetype = export_report_to_memory(
+ markdown_content, "ris", title=title
+ )
+
+ # Decode the RIS content and verify it doesn't start with markdown title
+ ris_text = content.decode("utf-8")
+
+ # RIS should NOT have "# My Report Title" prepended
+ assert not ris_text.startswith("# My Report Title")
+ assert filename.endswith(".ris")
+
+ def test_latex_does_not_get_title_prepended(self):
+ """LaTeX format should NOT get title prepended.
+
+ LaTeX has its own document structure with \\documentclass, etc.
+ Prepending a markdown title would not be appropriate.
+ """
+ from local_deep_research.web.services.research_service import (
+ export_report_to_memory,
+ )
+
+ markdown_content = "Some content here."
+ title = "My Report Title"
+
+ content, filename, mimetype = export_report_to_memory(
+ markdown_content, "latex", title=title
+ )
+
+ # The function should NOT prepend "# My Report Title" to the content
+ # before passing to the LaTeX exporter
+ # We verify the export succeeded with proper LaTeX output
+ assert filename.endswith(".tex")
+ assert isinstance(content, bytes)
+ # Verify the content is valid (can be decoded)
+ assert content.decode("utf-8")
+
+ def test_quarto_does_not_get_title_prepended(self):
+ """Quarto format should NOT get title prepended.
+
+ Quarto uses YAML front matter for titles. Prepending a markdown
+ title would duplicate the title.
+ """
+ from local_deep_research.web.services.research_service import (
+ export_report_to_memory,
+ )
+
+ markdown_content = "Some content here."
+ title = "My Report Title"
+
+ content, filename, mimetype = export_report_to_memory(
+ markdown_content, "quarto", title=title
+ )
+
+ # Quarto produces a ZIP file
+ assert content[:2] == b"PK"
+ assert filename.endswith(".zip")
+
+ def test_title_not_duplicated_if_already_present(self):
+ """If content already starts with title heading, don't duplicate."""
+ from local_deep_research.web.services.research_service import (
+ export_report_to_memory,
+ )
+
+ # Content that already has the title as heading
+ title = "My Report Title"
+ markdown_content = f"# {title}\n\nThis content already has the title."
+
+ content, filename, mimetype = export_report_to_memory(
+ markdown_content, "pdf", title=title
+ )
+
+ # Should succeed without duplicating
+ assert content.startswith(b"%PDF")
+
+ def test_title_not_prepended_if_content_starts_with_heading(self):
+ """If content starts with any heading, don't prepend title."""
+ from local_deep_research.web.services.research_service import (
+ export_report_to_memory,
+ )
+
+ # Content that starts with a different heading
+ markdown_content = "# Different Heading\n\nSome content here."
+ title = "My Report Title"
+
+ content, filename, mimetype = export_report_to_memory(
+ markdown_content, "pdf", title=title
+ )
+
+ # Should succeed - PDF formats should not prepend if content starts with #
+ assert content.startswith(b"%PDF")