Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

fix: remove setting the documents path on startup, set default langflow superuser (#2299)

Lucas Oliveira2765f9f4ff88
diff --git a/src/tui/cli.py b/src/tui/cli.py
index 54bdf5463..6dfdbec29 100644
--- a/src/tui/cli.py
+++ b/src/tui/cli.py
@@ -51,7 +51,6 @@ def run_cli():
pass # Non-critical bootstrap errors
env_manager = EnvManager()
- env_manager.ensure_openrag_version()
container_manager = ContainerManager()
docling_manager = DoclingManager()
@@ -349,11 +348,44 @@ def _start_services_cli(
env_manager = EnvManager()
env_manager.load_existing_env()
env_manager.setup_secure_defaults()
+
+ # Check for version mismatch before starting services / writing version
+ if hasattr(container_manager, "check_version_mismatch"):
+
+ async def _check_version():
+ return await container_manager.check_version_mismatch()
+
+ has_mismatch, container_version, cli_version = asyncio.run(_check_version())
+ if has_mismatch and container_version:
+ console.print()
+ console.print("[bold yellow]⚠ Version Mismatch Detected[/bold yellow]")
+ console.print(
+ f" Existing containers are running version [bold]{container_version}[/bold]"
+ )
+ console.print(f" Current version is [bold]{cli_version}[/bold]\n")
+ console.print(
+ f" Starting services will update containers to version [bold]{cli_version}[/bold]."
+ )
+ console.print(" This may cause compatibility issues with your flows.\n")
+ console.print(" [yellow]⚠️ Please backup your flows before continuing.[/yellow]")
+ console.print(
+ " Customizations to OpenRAG built-in flows are backed up in ~/.openrag/flows/backup/"
+ )
+ console.print(" Other user created flows are not backed up automatically.\n")
+ try:
+ proceed = input("Do you want to continue? [y/N]: ").strip().lower()
+ except (EOFError, KeyboardInterrupt):
+ console.print()
+ proceed = "n"
+ if proceed != "y":
+ console.print("[yellow]Start cancelled.[/yellow]")
+ return False
+
env_manager.ensure_openrag_version()
if not env_manager.config.langflow_superuser_password:
console.print("[red]✗ Error: Langflow password is required. Cannot start services.[/red]")
- return
+ return False
console.print()
console.print("Starting OpenRAG services...", style="bold")
diff --git a/src/tui/config_fields.py b/src/tui/config_fields.py
index 9b1948b2c..fc9139e39 100644
--- a/src/tui/config_fields.py
+++ b/src/tui/config_fields.py
@@ -149,8 +149,8 @@ CONFIG_SECTIONS: list[ConfigSection] = [
"langflow_superuser",
"LANGFLOW_SUPERUSER",
"Admin Username",
- placeholder="admin",
- default="admin",
+ placeholder="langflow",
+ default="langflow",
),
ConfigField(
"langflow_data_path",
diff --git a/src/tui/main.py b/src/tui/main.py
index 0bd1e37f0..8e551ff56 100644
--- a/src/tui/main.py
+++ b/src/tui/main.py
@@ -3,28 +3,28 @@
import os
import subprocess
import sys
+from collections.abc import Iterable
from pathlib import Path
-from typing import Iterable, Optional
-from textual.app import App, ComposeResult
-from utils.logging_config import get_logger
-try:
- from importlib.resources import files
-except ImportError:
- from importlib_resources import files
+from typing import Literal
-logger = get_logger(__name__)
+from textual.app import App
+
+from utils.logging_config import get_logger
-from .screens.welcome import WelcomeScreen
-from .screens.config import ConfigScreen
-from .screens.monitor import MonitorScreen
-from .screens.logs import LogsScreen
-from .screens.diagnostics import DiagnosticsScreen
-from .managers.env_manager import EnvManager
from .managers.container_manager import ContainerManager
from .managers.docling_manager import DoclingManager
+from .managers.env_manager import EnvManager
+from .screens.welcome import WelcomeScreen
from .utils.platform import PlatformDetector
from .widgets.diagnostics_notification import notify_with_diagnostics
+try:
+ from importlib.resources import files
+except ImportError:
+ from importlib_resources import files # type: ignore[no-redef]
+
+logger = get_logger(__name__)
+
class OpenRAGTUI(App):
"""OpenRAG Terminal User Interface application."""
@@ -373,7 +373,7 @@ class OpenRAGTUI(App):
message: str,
*,
title: str = "",
- severity: str = "information",
+ severity: Literal["information", "warning", "error"] = "information",
timeout: float | None = None,
markup: bool = True,
) -> None:
@@ -395,7 +395,7 @@ class OpenRAGTUI(App):
)
# Load existing config if available
- config_exists = self.env_manager.load_existing_env()
+ self.env_manager.load_existing_env()
# Start with welcome screen
self.push_screen(WelcomeScreen())
@@ -414,16 +414,20 @@ class OpenRAGTUI(App):
# Check Podman macOS memory if applicable
runtime_info = self.container_manager.get_runtime_info()
if runtime_info.runtime_type.value == "podman":
- is_sufficient, _, message = (
- self.platform_detector.check_podman_macos_memory()
- )
+ is_sufficient, _, message = self.platform_detector.check_podman_macos_memory()
if not is_sufficient:
return False, f"Podman VM memory insufficient:\n{message}"
return True, "Runtime requirements satisfied"
-def _copy_assets(resource_tree, destination: Path, allowed_suffixes: Optional[Iterable[str]] = None, *, force: bool = False) -> None:
+def _copy_assets(
+ resource_tree,
+ destination: Path,
+ allowed_suffixes: Iterable[str] | None = None,
+ *,
+ force: bool = False,
+) -> None:
"""Copy packaged assets into destination and optionally overwrite existing files.
When ``force`` is True, files are refreshed if the packaged bytes differ.
@@ -437,7 +441,9 @@ def _copy_assets(resource_tree, destination: Path, allowed_suffixes: Optional[It
_copy_assets(resource, target_path, allowed_suffixes, force=force)
continue
- if allowed_suffixes and not any(resource.name.endswith(suffix) for suffix in allowed_suffixes):
+ if allowed_suffixes and not any(
+ resource.name.endswith(suffix) for suffix in allowed_suffixes
+ ):
continue
resource_bytes = resource.read_bytes()
@@ -461,9 +467,10 @@ def copy_sample_documents(*, force: bool = False) -> None:
Uses the first path from OPENRAG_DOCUMENTS_PATHS env var.
Defaults to ~/.openrag/documents if not configured.
"""
- from .managers.env_manager import EnvManager
from pathlib import Path
+ from .managers.env_manager import EnvManager
+
# Get the configured documents path from env
env_manager = EnvManager()
env_manager.load_existing_env()
@@ -471,7 +478,7 @@ def copy_sample_documents(*, force: bool = False) -> None:
# Parse the first path from the documents paths config
documents_path_str = env_manager.config.openrag_documents_paths
if documents_path_str:
- first_path = documents_path_str.split(',')[0].strip()
+ first_path = documents_path_str.split(",")[0].strip()
# Expand $HOME and ~
first_path = first_path.replace("$HOME", str(Path.home()))
documents_dir = Path(first_path).expanduser()
@@ -488,19 +495,6 @@ def copy_sample_documents(*, force: bool = False) -> None:
logger.debug(f"Could not copy sample documents: {e}")
# This is not a critical error - the app can work without sample documents
- # Ensure OPENRAG_DOCUMENTS_PATH in .env points to the resolved documents directory.
- # Docker Compose uses this for the volume mount; if unset it defaults to ./openrag-documents
- # (CWD-relative), which may not contain the PDFs copied above.
- try:
- from dotenv import set_key
- resolved_path = str(documents_dir.resolve())
- current = env_manager.config.openrag_documents_path
- if not current or current in ("$HOME/.openrag/documents", "./openrag-documents", "./documents"):
- set_key(str(env_manager.env_file), "OPENRAG_DOCUMENTS_PATH", resolved_path)
- logger.debug(f"Set OPENRAG_DOCUMENTS_PATH={resolved_path} in {env_manager.env_file}")
- except Exception as e:
- logger.debug(f"Could not update OPENRAG_DOCUMENTS_PATH in .env: {e}")
-
def copy_sample_flows(*, force: bool = False) -> None:
"""Copy sample flows from package to host directory.
@@ -550,7 +544,9 @@ def copy_compose_files(*, force: bool = False) -> None:
if destination.read_bytes() == resource_bytes:
continue
except Exception as read_error:
- logger.debug(f"Failed to read existing compose file {destination}: {read_error}")
+ logger.debug(
+ f"Failed to read existing compose file {destination}: {read_error}"
+ )
destination.write_bytes(resource_bytes)
logger.info(f"Copied docker-compose template to {destination}")
@@ -598,7 +594,8 @@ def migrate_legacy_data_directories():
marker.touch()
# Still need to update .env with centralized paths
try:
- from managers.env_manager import EnvManager
+ from .managers.env_manager import EnvManager
+
env_manager = EnvManager()
env_manager.load_existing_env()
# Explicitly set centralized paths (overrides any old CWD-relative paths)
@@ -620,7 +617,7 @@ def migrate_legacy_data_directories():
print("\n" + "=" * 60)
print(" OpenRAG Data Migration Required")
print("=" * 60)
- print(f"\nStarting with this version, OpenRAG stores data in:")
+ print("\nStarting with this version, OpenRAG stores data in:")
print(f" {target_base}")
print("\nThe following will be copied from your current directory:")
for source, target, desc in sources_to_migrate:
@@ -677,7 +674,8 @@ def migrate_legacy_data_directories():
# Update .env file with centralized paths
try:
- from managers.env_manager import EnvManager
+ from .managers.env_manager import EnvManager
+
env_manager = EnvManager()
env_manager.load_existing_env()
# Explicitly set centralized paths (overrides any old CWD-relative paths)
@@ -723,11 +721,7 @@ def _reclaim_host_ownership(directories: list[Path]) -> None:
if not needs_reclaim:
return
- runtime = (
- "docker" if _shutil.which("docker")
- else "podman" if _shutil.which("podman")
- else None
- )
+ runtime = "docker" if _shutil.which("docker") else "podman" if _shutil.which("podman") else None
if not runtime:
logger.error("No container runtime found; cannot reclaim directory ownership")
return
@@ -736,9 +730,16 @@ def _reclaim_host_ownership(directories: list[Path]) -> None:
try:
subprocess.run(
[
- runtime, "run", "--rm",
- "-v", f"{directory}:/mnt/target",
- "alpine", "chown", "-R", f"{host_uid}:{host_gid}", "/mnt/target",
+ runtime,
+ "run",
+ "--rm",
+ "-v",
+ f"{directory}:/mnt/target",
+ "alpine",
+ "chown",
+ "-R",
+ f"{host_uid}:{host_gid}",
+ "/mnt/target",
],
check=True,
capture_output=True,
@@ -777,9 +778,11 @@ def generate_jwt_keys(keys_dir: Path):
[
"openssl",
"rsa",
- "-in", str(private_key_path),
+ "-in",
+ str(private_key_path),
"-pubout",
- "-out", str(public_key_path),
+ "-out",
+ str(public_key_path),
],
check=True,
capture_output=True,
@@ -789,7 +792,9 @@ def generate_jwt_keys(keys_dir: Path):
logger.info("Generated RSA keys for JWT signing")
except FileNotFoundError:
- logger.warning("openssl not found, skipping JWT key generation (will be generated in container)")
+ logger.warning(
+ "openssl not found, skipping JWT key generation (will be generated in container)"
+ )
except subprocess.CalledProcessError as e:
logger.error(f"Failed to generate RSA keys: {e}")
@@ -877,6 +882,7 @@ def _resolve_langflow_data_path(base_dir: Path) -> Path:
default = base_dir / "data" / "langflow-data"
try:
from .managers.env_manager import EnvManager
+
env_manager = EnvManager()
env_manager.load_existing_env()
raw = env_manager.config.langflow_data_path
@@ -925,7 +931,7 @@ def _run_tui_app():
logger.error("Error running OpenRAG TUI", error=str(e))
finally:
# Ensure cleanup happens even on exceptions
- if app and hasattr(app, 'docling_manager'):
+ if app and hasattr(app, "docling_manager"):
app.docling_manager.cleanup()
sys.exit(0)
@@ -947,6 +953,7 @@ def run_tui():
# Check for native Windows before launching anything
from .utils.platform import PlatformDetector
+
platform_detector = PlatformDetector()
if platform_detector.is_native_windows():
@@ -959,6 +966,7 @@ def run_tui():
# Run startup prerequisites (install runtime, health checks, etc.)
from .utils.startup_checks import run_startup_checks
+
if not run_startup_checks():
sys.exit(1)
@@ -966,6 +974,7 @@ def run_tui():
_run_tui_app()
else:
from .cli import run_cli
+
run_cli()
diff --git a/src/tui/managers/env_manager.py b/src/tui/managers/env_manager.py
index b537c866d..c5f4924bb 100644
--- a/src/tui/managers/env_manager.py
+++ b/src/tui/managers/env_manager.py
@@ -43,7 +43,7 @@ class EnvConfig:
langflow_port: str = "7860"
opensearch_index_name: str = "documents"
langflow_secret_key: str = ""
- langflow_superuser: str = "admin"
+ langflow_superuser: str = "langflow"
langflow_superuser_password: str = ""
langflow_chat_flow_id: str = "1098eea1-6649-4e1d-aed1-b77249fb8dd0"
langflow_ingest_flow_id: str = "5488df7c-b93f-4f87-a446-b67028bc0813"
@@ -481,7 +481,7 @@ class EnvManager:
f"LANGFLOW_SECRET_KEY={self._quote_env_value(self.config.langflow_secret_key)}\n"
)
f.write(
- f"LANGFLOW_SUPERUSER={self._quote_env_value(self.config.langflow_superuser or 'admin')}\n"
+ f"LANGFLOW_SUPERUSER={self._quote_env_value(self.config.langflow_superuser or 'langflow')}\n"
)
f.write(
f"LANGFLOW_SUPERUSER_PASSWORD={self._quote_env_value(self.config.langflow_superuser_password)}\n"
diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py
index 6e368a08f..6b82bf64c 100644
--- a/tests/unit/test_cli.py
+++ b/tests/unit/test_cli.py
@@ -118,3 +118,36 @@ def test_start_services_cli_ensures_openrag_version(tmp_path, monkeypatch):
assert env_file.exists()
assert "OPENRAG_VERSION='9.9.9'" in env_file.read_text()
+
+
+def test_start_services_cli_version_mismatch_warning(tmp_path, monkeypatch):
+ """CLI _start_services_cli surfaces version mismatch warning notice."""
+ env_file = tmp_path / ".env"
+ env_file.write_text("LANGFLOW_SUPERUSER_PASSWORD='secret'\n")
+
+ class MismatchContainerManager(StubContainerManager):
+ async def check_version_mismatch(self):
+ return True, "0.5.0", "0.7.0"
+
+ # Test user cancelling prompt ('n')
+ monkeypatch.setattr("builtins.input", lambda prompt="": "n")
+ with patch("utils.paths.get_tui_env_file", return_value=env_file):
+ fully_started, output = _run(
+ MismatchContainerManager(events=[(True, "Started", False)]),
+ StubDoclingManager(running=True),
+ )
+
+ assert fully_started is False
+ assert "Version Mismatch Detected" in output
+ assert "Start cancelled" in output
+
+ # Test user accepting prompt ('y')
+ monkeypatch.setattr("builtins.input", lambda prompt="": "y")
+ with patch("utils.paths.get_tui_env_file", return_value=env_file):
+ fully_started, output = _run(
+ MismatchContainerManager(events=[(True, "Started", False)]),
+ StubDoclingManager(running=True),
+ )
+
+ assert fully_started is True
+ assert "Version Mismatch Detected" in output
diff --git a/tests/unit/test_env_manager.py b/tests/unit/test_env_manager.py
index 5e7a0a70a..721883b88 100644
--- a/tests/unit/test_env_manager.py
+++ b/tests/unit/test_env_manager.py
@@ -240,7 +240,7 @@ class TestLangflowPasswordAndAutoLogin:
content = env_file.read_text()
assert "LANGFLOW_SUPERUSER_PASSWORD='LangflowPass123!'" in content
assert "LANGFLOW_AUTO_LOGIN='True'" in content
- assert "LANGFLOW_SUPERUSER='admin'" in content
+ assert "LANGFLOW_SUPERUSER='langflow'" in content
def test_validate_config_requires_langflow_password(self, env_manager):
env_manager.config.opensearch_password = "Pass123!"