vector-inspector 0.3.7__py3-none-any.whl → 0.3.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,6 +5,8 @@ import json
5
5
  import psycopg2
6
6
  from psycopg2 import sql
7
7
 
8
+ from vector_inspector.core.logging import log_info
9
+
8
10
  ## No need to import register_vector; pgvector extension is enabled at table creation
9
11
  from vector_inspector.core.connections.base_connection import VectorDBConnection
10
12
  from vector_inspector.core.logging import log_error, log_info
@@ -1043,12 +1045,35 @@ class PgVectorConnection(VectorDBConnection):
1043
1045
  Returns:
1044
1046
  List of floats
1045
1047
  """
1048
+ log_info("[pgvector] _parse_vector raw value: %r (type: %s)", vector_str, type(vector_str))
1046
1049
  if isinstance(vector_str, list):
1050
+ log_info("[pgvector] _parse_vector: already list, len=%d", len(vector_str))
1047
1051
  return vector_str
1052
+ # Handle numpy arrays
1053
+ try:
1054
+ import numpy as np
1055
+
1056
+ if isinstance(vector_str, np.ndarray):
1057
+ log_info("[pgvector] _parse_vector: numpy array, shape=%s", vector_str.shape)
1058
+ return vector_str.tolist()
1059
+ except ImportError:
1060
+ pass
1048
1061
  if isinstance(vector_str, str):
1049
1062
  # Remove brackets and split by comma
1050
1063
  vector_str = vector_str.strip("[]")
1051
- return [float(x) for x in vector_str.split(",")]
1064
+ if not vector_str:
1065
+ log_info("[pgvector] _parse_vector: empty string after strip")
1066
+ return []
1067
+ try:
1068
+ parsed = [float(x) for x in vector_str.split(",")]
1069
+ log_info("[pgvector] _parse_vector: parsed list of len %d", len(parsed))
1070
+ return parsed
1071
+ except Exception as e:
1072
+ log_info(
1073
+ "[pgvector] _parse_vector: failed to parse '%s' with error: %s", vector_str, e
1074
+ )
1075
+ return []
1076
+ log_info("[pgvector] _parse_vector: unhandled type %s, returning []", type(vector_str))
1052
1077
  return []
1053
1078
 
1054
1079
  def compute_embeddings_for_documents(
@@ -0,0 +1,97 @@
1
+ """Factory for creating vector database connections from provider configs."""
2
+
3
+ from typing import Dict, Any
4
+ from vector_inspector.core.connections.base_connection import VectorDBConnection
5
+ from vector_inspector.core.connections.chroma_connection import ChromaDBConnection
6
+ from vector_inspector.core.connections.qdrant_connection import QdrantConnection
7
+ from vector_inspector.core.connections.pinecone_connection import PineconeConnection
8
+ from vector_inspector.core.connections.pgvector_connection import PgVectorConnection
9
+
10
+
11
+ class ProviderFactory:
12
+ """Factory for creating database connections from configuration."""
13
+
14
+ @staticmethod
15
+ def create(
16
+ provider: str, config: Dict[str, Any], credentials: Dict[str, Any] = None
17
+ ) -> VectorDBConnection:
18
+ """Create a connection object for the specified provider.
19
+
20
+ Args:
21
+ provider: Provider type (chromadb, qdrant, pinecone, pgvector)
22
+ config: Provider-specific configuration
23
+ credentials: Optional credentials (API keys, passwords, etc.)
24
+
25
+ Returns:
26
+ VectorDBConnection instance
27
+
28
+ Raises:
29
+ ValueError: If provider is unsupported or configuration is invalid
30
+ """
31
+ credentials = credentials or {}
32
+
33
+ if provider == "chromadb":
34
+ return ProviderFactory._create_chroma(config, credentials)
35
+ elif provider == "qdrant":
36
+ return ProviderFactory._create_qdrant(config, credentials)
37
+ elif provider == "pinecone":
38
+ return ProviderFactory._create_pinecone(config, credentials)
39
+ elif provider == "pgvector":
40
+ return ProviderFactory._create_pgvector(config, credentials)
41
+ else:
42
+ raise ValueError(f"Unsupported provider: {provider}")
43
+
44
+ @staticmethod
45
+ def _create_chroma(config: Dict[str, Any], credentials: Dict[str, Any]) -> ChromaDBConnection:
46
+ """Create a ChromaDB connection."""
47
+ conn_type = config.get("type")
48
+
49
+ if conn_type == "persistent":
50
+ return ChromaDBConnection(path=config.get("path"))
51
+ elif conn_type == "http":
52
+ return ChromaDBConnection(host=config.get("host"), port=config.get("port"))
53
+ else: # ephemeral
54
+ return ChromaDBConnection()
55
+
56
+ @staticmethod
57
+ def _create_qdrant(config: Dict[str, Any], credentials: Dict[str, Any]) -> QdrantConnection:
58
+ """Create a Qdrant connection."""
59
+ conn_type = config.get("type")
60
+ api_key = credentials.get("api_key")
61
+
62
+ if conn_type == "persistent":
63
+ return QdrantConnection(path=config.get("path"))
64
+ elif conn_type == "http":
65
+ return QdrantConnection(
66
+ host=config.get("host"), port=config.get("port"), api_key=api_key
67
+ )
68
+ else: # ephemeral
69
+ return QdrantConnection()
70
+
71
+ @staticmethod
72
+ def _create_pinecone(config: Dict[str, Any], credentials: Dict[str, Any]) -> PineconeConnection:
73
+ """Create a Pinecone connection."""
74
+ api_key = credentials.get("api_key")
75
+ if not api_key:
76
+ raise ValueError("Pinecone requires an API key")
77
+
78
+ return PineconeConnection(api_key=api_key)
79
+
80
+ @staticmethod
81
+ def _create_pgvector(config: Dict[str, Any], credentials: Dict[str, Any]) -> PgVectorConnection:
82
+ """Create a PgVector/Postgres connection."""
83
+ conn_type = config.get("type")
84
+
85
+ if conn_type == "http":
86
+ host = config.get("host", "localhost")
87
+ port = int(config.get("port", 5432))
88
+ database = config.get("database")
89
+ user = config.get("user")
90
+ # Prefer password from credentials
91
+ password = credentials.get("password")
92
+
93
+ return PgVectorConnection(
94
+ host=host, port=port, database=database, user=user, password=password
95
+ )
96
+
97
+ raise ValueError("Unsupported connection type for PgVector profile")
@@ -0,0 +1,105 @@
1
+ """Extension points for Vector Inspector.
2
+
3
+ This module provides hooks and callbacks that allow pro versions
4
+ or plugins to extend core functionality without modifying the base code.
5
+ """
6
+
7
+ from typing import Any, ClassVar
8
+ from collections.abc import Callable
9
+ from PySide6.QtWidgets import QMenu, QTableWidget
10
+
11
+
12
+ class TableContextMenuHook:
13
+ """Hook for adding custom context menu items to table widgets."""
14
+
15
+ _handlers: ClassVar[list[Callable]] = []
16
+
17
+ @classmethod
18
+ def register(cls, handler: Callable):
19
+ """Register a context menu handler.
20
+
21
+ Args:
22
+ handler: Callable that takes (menu: QMenu, table: QTableWidget, row: int, data: Dict)
23
+ and adds menu items to the menu.
24
+ """
25
+ if handler not in cls._handlers:
26
+ cls._handlers.append(handler)
27
+
28
+ @classmethod
29
+ def unregister(cls, handler: Callable):
30
+ """Unregister a context menu handler."""
31
+ if handler in cls._handlers:
32
+ cls._handlers.remove(handler)
33
+
34
+ @classmethod
35
+ def trigger(
36
+ cls,
37
+ menu: QMenu,
38
+ table: QTableWidget,
39
+ row: int,
40
+ data: dict[str, Any] | None = None,
41
+ ):
42
+ """Trigger all registered handlers.
43
+
44
+ Args:
45
+ menu: The QMenu to add items to
46
+ table: The QTableWidget that was right-clicked
47
+ row: The row number that was clicked
48
+ data: Optional data dictionary with context (ids, documents, metadatas, etc.)
49
+ """
50
+ for handler in cls._handlers:
51
+ try:
52
+ handler(menu, table, row, data)
53
+ except Exception as e:
54
+ # Log but don't break if a handler fails
55
+ from vector_inspector.core.logging import log_error
56
+
57
+ log_error("Context menu handler error: %s", e)
58
+
59
+ @classmethod
60
+ def clear(cls):
61
+ """Clear all registered handlers."""
62
+ cls._handlers.clear()
63
+
64
+
65
+ # Global singleton instance
66
+ table_context_menu_hook = TableContextMenuHook()
67
+
68
+
69
+ class SettingsPanelHook:
70
+ """Hook for adding custom sections to the Settings/Preferences dialog."""
71
+
72
+ _handlers: ClassVar[list[Callable]] = []
73
+
74
+ @classmethod
75
+ def register(cls, handler: Callable):
76
+ """Register a settings panel provider.
77
+
78
+ Handler signature: (parent_layout, settings_service, dialog)
79
+ where `parent_layout` is a QLayout the handler can add widgets to.
80
+ """
81
+ if handler not in cls._handlers:
82
+ cls._handlers.append(handler)
83
+
84
+ @classmethod
85
+ def unregister(cls, handler: Callable):
86
+ if handler in cls._handlers:
87
+ cls._handlers.remove(handler)
88
+
89
+ @classmethod
90
+ def trigger(cls, parent_layout, settings_service, dialog=None):
91
+ for handler in cls._handlers:
92
+ try:
93
+ handler(parent_layout, settings_service, dialog)
94
+ except Exception as e:
95
+ from vector_inspector.core.logging import log_error
96
+
97
+ log_error("Settings panel handler error: %s", e)
98
+
99
+ @classmethod
100
+ def clear(cls):
101
+ cls._handlers.clear()
102
+
103
+
104
+ # Global singleton instance
105
+ settings_panel_hook = SettingsPanelHook()
@@ -1,6 +1,8 @@
1
1
  """Service for persisting application settings."""
2
2
 
3
3
  import json
4
+ import base64
5
+ from PySide6.QtCore import QObject, Signal
4
6
  from pathlib import Path
5
7
  from typing import Dict, Any, Optional, List
6
8
  from vector_inspector.core.cache_manager import invalidate_cache_on_settings_change
@@ -12,6 +14,18 @@ class SettingsService:
12
14
 
13
15
  def __init__(self):
14
16
  """Initialize settings service."""
17
+
18
+ # Expose a shared QObject-based signal emitter so UI can react to
19
+ # settings changes without polling.
20
+ class _Signals(QObject):
21
+ setting_changed = Signal(str, object)
22
+
23
+ # singleton-like per-process signals instance
24
+ try:
25
+ self.signals
26
+ except Exception:
27
+ self.signals = _Signals()
28
+
15
29
  self.settings_dir = Path.home() / ".vector-inspector"
16
30
  self.settings_file = self.settings_dir / "settings.json"
17
31
  self.settings: Dict[str, Any] = {}
@@ -51,6 +65,62 @@ class SettingsService:
51
65
  """Get a setting value."""
52
66
  return self.settings.get(key, default)
53
67
 
68
+ # Convenience accessors for common settings
69
+ def get_breadcrumb_enabled(self) -> bool:
70
+ return bool(self.settings.get("breadcrumb.enabled", True))
71
+
72
+ def set_breadcrumb_enabled(self, enabled: bool):
73
+ self.set("breadcrumb.enabled", bool(enabled))
74
+
75
+ def get_breadcrumb_elide_mode(self) -> str:
76
+ return str(self.settings.get("breadcrumb.elide_mode", "left"))
77
+
78
+ def set_breadcrumb_elide_mode(self, mode: str):
79
+ if mode not in ("left", "middle"):
80
+ mode = "left"
81
+ self.set("breadcrumb.elide_mode", mode)
82
+
83
+ def get_default_n_results(self) -> int:
84
+ return int(self.settings.get("search.default_n_results", 10))
85
+
86
+ def set_default_n_results(self, n: int):
87
+ self.set("search.default_n_results", int(n))
88
+
89
+ def get_auto_generate_embeddings(self) -> bool:
90
+ return bool(self.settings.get("embeddings.auto_generate", True))
91
+
92
+ def set_auto_generate_embeddings(self, enabled: bool):
93
+ self.set("embeddings.auto_generate", bool(enabled))
94
+
95
+ def get_window_restore_geometry(self) -> bool:
96
+ return bool(self.settings.get("window.restore_geometry", True))
97
+
98
+ def set_window_restore_geometry(self, enabled: bool):
99
+ self.set("window.restore_geometry", bool(enabled))
100
+
101
+ def set_window_geometry(self, geometry_bytes: bytes):
102
+ """Save window geometry as base64 string."""
103
+ try:
104
+ if isinstance(geometry_bytes, str):
105
+ # assume base64 already
106
+ b64 = geometry_bytes
107
+ else:
108
+ b64 = base64.b64encode(bytes(geometry_bytes)).decode("ascii")
109
+ self.set("window.geometry", b64)
110
+ except Exception as e:
111
+ log_error("Failed to set window geometry: %s", e)
112
+
113
+ def get_window_geometry(self) -> Optional[bytes]:
114
+ """Return geometry bytes or None."""
115
+ try:
116
+ b64 = self.settings.get("window.geometry")
117
+ if not b64:
118
+ return None
119
+ return base64.b64decode(b64)
120
+ except Exception as e:
121
+ log_error("Failed to get window geometry: %s", e)
122
+ return None
123
+
54
124
  def get_cache_enabled(self) -> bool:
55
125
  """Get whether caching is enabled (default: True)."""
56
126
  return self.settings.get("cache_enabled", True)
@@ -74,6 +144,12 @@ class SettingsService:
74
144
  # Invalidate cache when settings change (only if cache is enabled)
75
145
  if key != "cache_enabled": # Don't invalidate when toggling cache itself
76
146
  invalidate_cache_on_settings_change()
147
+ # Emit change signal for UI/reactive components
148
+ try:
149
+ # Emit the raw python object (value) for convenience
150
+ self.signals.setting_changed.emit(key, value)
151
+ except Exception:
152
+ pass
77
153
 
78
154
  def clear(self):
79
155
  """Clear all settings."""
@@ -34,10 +34,22 @@ class SplashWindow(QDialog):
34
34
  layout.addWidget(github)
35
35
 
36
36
  # About info (reuse About dialog text)
37
- from vector_inspector.ui.main_window import get_about_html
37
+ from vector_inspector.utils.version import get_app_version
38
38
 
39
39
  about = QTextBrowser()
40
- about.setHtml(get_about_html())
40
+ version = get_app_version()
41
+ version_html = (
42
+ f"<h2>Vector Inspector {version}</h2>" if version else "<h2>Vector Inspector</h2>"
43
+ )
44
+ about_text = (
45
+ version_html + "<p>A comprehensive desktop application for visualizing, "
46
+ "querying, and managing multiple vector databases simultaneously.</p>"
47
+ '<p><a href="https://github.com/anthonypdawson/vector-inspector" style="color:#2980b9;">GitHub Project Page</a></p>'
48
+ "<hr />"
49
+ "<p>Built with PySide6</p>"
50
+ "<p><b>New:</b> Pinecone support!</p>"
51
+ )
52
+ about.setHtml(about_text)
41
53
  about.setOpenExternalLinks(True)
42
54
  about.setMaximumHeight(160)
43
55
  layout.addWidget(about)
@@ -0,0 +1 @@
1
+ """UI controllers for managing application logic."""
@@ -0,0 +1,177 @@
1
+ """Controller for managing connection lifecycle and threading."""
2
+
3
+ from typing import Dict, Optional
4
+ from PySide6.QtCore import QObject, Signal, QThread
5
+ from PySide6.QtWidgets import QMessageBox, QWidget
6
+
7
+ from vector_inspector.core.connection_manager import ConnectionManager, ConnectionState
8
+ from vector_inspector.core.connections.base_connection import VectorDBConnection
9
+ from vector_inspector.core.provider_factory import ProviderFactory
10
+ from vector_inspector.services.profile_service import ProfileService
11
+ from vector_inspector.ui.components.loading_dialog import LoadingDialog
12
+
13
+
14
+ class ConnectionThread(QThread):
15
+ """Background thread for connecting to database."""
16
+
17
+ finished = Signal(bool, list, str) # success, collections, error_message
18
+
19
+ def __init__(self, connection: VectorDBConnection):
20
+ super().__init__()
21
+ self.connection = connection
22
+
23
+ def run(self):
24
+ """Connect to database and get collections."""
25
+ try:
26
+ success = self.connection.connect()
27
+ if success:
28
+ collections = self.connection.list_collections()
29
+ self.finished.emit(True, collections, "")
30
+ else:
31
+ self.finished.emit(False, [], "Connection failed")
32
+ except Exception as e:
33
+ self.finished.emit(False, [], str(e))
34
+
35
+
36
+ class ConnectionController(QObject):
37
+ """Controller for managing connection operations and lifecycle.
38
+
39
+ This handles:
40
+ - Creating connections from profiles
41
+ - Starting connection threads
42
+ - Handling connection results
43
+ - Managing loading dialogs
44
+ - Emitting signals for UI updates
45
+ """
46
+
47
+ connection_completed = Signal(
48
+ str, bool, list, str
49
+ ) # connection_id, success, collections, error
50
+
51
+ def __init__(
52
+ self,
53
+ connection_manager: ConnectionManager,
54
+ profile_service: ProfileService,
55
+ parent: Optional[QWidget] = None,
56
+ ):
57
+ super().__init__(parent)
58
+ self.connection_manager = connection_manager
59
+ self.profile_service = profile_service
60
+ self.parent_widget = parent
61
+
62
+ # State
63
+ self._connection_threads: Dict[str, ConnectionThread] = {}
64
+ self.loading_dialog = LoadingDialog("Loading...", parent)
65
+
66
+ def connect_to_profile(self, profile_id: str) -> bool:
67
+ """Connect to a profile.
68
+
69
+ Args:
70
+ profile_id: ID of the profile to connect to
71
+
72
+ Returns:
73
+ True if connection initiated successfully, False otherwise
74
+ """
75
+ profile_data = self.profile_service.get_profile_with_credentials(profile_id)
76
+ if not profile_data:
77
+ QMessageBox.warning(self.parent_widget, "Error", "Profile not found.")
78
+ return False
79
+
80
+ # Check connection limit
81
+ if self.connection_manager.get_connection_count() >= ConnectionManager.MAX_CONNECTIONS:
82
+ QMessageBox.warning(
83
+ self.parent_widget,
84
+ "Connection Limit",
85
+ f"Maximum number of connections ({ConnectionManager.MAX_CONNECTIONS}) reached. "
86
+ "Please close a connection first.",
87
+ )
88
+ return False
89
+
90
+ # Create connection
91
+ provider = profile_data["provider"]
92
+ config = profile_data["config"]
93
+ credentials = profile_data.get("credentials", {})
94
+
95
+ try:
96
+ # Create connection object using factory
97
+ connection = ProviderFactory.create(provider, config, credentials)
98
+
99
+ # Register with connection manager, using profile_id as connection_id for persistence
100
+ connection_id = self.connection_manager.create_connection(
101
+ name=profile_data["name"],
102
+ provider=provider,
103
+ connection=connection,
104
+ config=config,
105
+ connection_id=profile_data["id"],
106
+ )
107
+
108
+ # Update state to connecting
109
+ self.connection_manager.update_connection_state(
110
+ connection_id, ConnectionState.CONNECTING
111
+ )
112
+
113
+ # Connect in background thread
114
+ thread = ConnectionThread(connection)
115
+ thread.finished.connect(
116
+ lambda success, collections, error: self._on_connection_finished(
117
+ connection_id, success, collections, error
118
+ )
119
+ )
120
+ self._connection_threads[connection_id] = thread
121
+ thread.start()
122
+
123
+ # Show loading dialog
124
+ self.loading_dialog.show_loading(f"Connecting to {profile_data['name']}...")
125
+ return True
126
+
127
+ except Exception as e:
128
+ QMessageBox.critical(
129
+ self.parent_widget, "Connection Error", f"Failed to create connection: {e}"
130
+ )
131
+ return False
132
+
133
+ def _on_connection_finished(
134
+ self, connection_id: str, success: bool, collections: list, error: str
135
+ ):
136
+ """Handle connection thread completion."""
137
+ self.loading_dialog.hide_loading()
138
+
139
+ # Clean up thread
140
+ thread = self._connection_threads.pop(connection_id, None)
141
+ if thread:
142
+ thread.wait() # Wait for thread to fully finish
143
+ thread.deleteLater()
144
+
145
+ if success:
146
+ # Update state to connected
147
+ self.connection_manager.update_connection_state(
148
+ connection_id, ConnectionState.CONNECTED
149
+ )
150
+
151
+ # Mark connection as opened first (will show in UI)
152
+ self.connection_manager.mark_connection_opened(connection_id)
153
+
154
+ # Then update collections (UI item now exists to receive them)
155
+ self.connection_manager.update_collections(connection_id, collections)
156
+ else:
157
+ # Update state to error
158
+ self.connection_manager.update_connection_state(
159
+ connection_id, ConnectionState.ERROR, error
160
+ )
161
+
162
+ QMessageBox.warning(
163
+ self.parent_widget, "Connection Failed", f"Failed to connect: {error}"
164
+ )
165
+
166
+ # Remove the failed connection
167
+ self.connection_manager.close_connection(connection_id)
168
+
169
+ # Emit signal for UI updates
170
+ self.connection_completed.emit(connection_id, success, collections, error)
171
+
172
+ def cleanup(self):
173
+ """Clean up connection threads on shutdown."""
174
+ for thread in list(self._connection_threads.values()):
175
+ if thread.isRunning():
176
+ thread.quit()
177
+ thread.wait(1000) # Wait up to 1 second
@@ -0,0 +1,124 @@
1
+ from PySide6.QtWidgets import (
2
+ QDialog,
3
+ QVBoxLayout,
4
+ QHBoxLayout,
5
+ QLabel,
6
+ QCheckBox,
7
+ QComboBox,
8
+ QSpinBox,
9
+ QPushButton,
10
+ )
11
+ from PySide6.QtCore import Qt
12
+
13
+ from vector_inspector.services.settings_service import SettingsService
14
+ from vector_inspector.extensions import settings_panel_hook
15
+
16
+
17
+ class SettingsDialog(QDialog):
18
+ """Modal settings dialog backed by SettingsService."""
19
+
20
+ def __init__(self, settings_service: SettingsService = None, parent=None):
21
+ super().__init__(parent)
22
+ self.setWindowTitle("Preferences")
23
+ self.settings = settings_service or SettingsService()
24
+ self._init_ui()
25
+ self._load_values()
26
+
27
+ def _init_ui(self):
28
+ layout = QVBoxLayout(self)
29
+
30
+ # Breadcrumb controls are provided by pro extensions (vector-studio)
31
+ # via the settings_panel_hook. Core does not add breadcrumb options.
32
+
33
+ # Search defaults
34
+ search_layout = QHBoxLayout()
35
+ search_layout.addWidget(QLabel("Default results:"))
36
+ self.default_results = QSpinBox()
37
+ self.default_results.setMinimum(1)
38
+ self.default_results.setMaximum(1000)
39
+ search_layout.addWidget(self.default_results)
40
+ layout.addLayout(search_layout)
41
+
42
+ # Embeddings
43
+ self.auto_embed_checkbox = QCheckBox("Auto-generate embeddings for new text")
44
+ layout.addWidget(self.auto_embed_checkbox)
45
+
46
+ # Window geometry
47
+ self.restore_geometry_checkbox = QCheckBox("Restore window size/position on startup")
48
+ layout.addWidget(self.restore_geometry_checkbox)
49
+
50
+ # Buttons
51
+ btn_layout = QHBoxLayout()
52
+ self.apply_btn = QPushButton("Apply")
53
+ self.ok_btn = QPushButton("OK")
54
+ self.cancel_btn = QPushButton("Cancel")
55
+ self.reset_btn = QPushButton("Reset to defaults")
56
+ btn_layout.addWidget(self.reset_btn)
57
+ btn_layout.addStretch()
58
+ btn_layout.addWidget(self.apply_btn)
59
+ btn_layout.addWidget(self.ok_btn)
60
+ btn_layout.addWidget(self.cancel_btn)
61
+ # Allow external extensions to add sections before the buttons
62
+ try:
63
+ # Handlers receive (parent_layout, settings_service, dialog)
64
+ settings_panel_hook.trigger(layout, self.settings, self)
65
+ except Exception:
66
+ pass
67
+
68
+ layout.addLayout(btn_layout)
69
+
70
+ # Signals
71
+ self.apply_btn.clicked.connect(self._apply)
72
+ self.ok_btn.clicked.connect(self._ok)
73
+ self.cancel_btn.clicked.connect(self.reject)
74
+ self.reset_btn.clicked.connect(self._reset_defaults)
75
+
76
+ # Immediate apply on change for some controls
77
+ self.default_results.valueChanged.connect(lambda v: self.settings.set_default_n_results(v))
78
+ self.auto_embed_checkbox.stateChanged.connect(
79
+ lambda s: self.settings.set_auto_generate_embeddings(bool(s))
80
+ )
81
+ self.restore_geometry_checkbox.stateChanged.connect(
82
+ lambda s: self.settings.set_window_restore_geometry(bool(s))
83
+ )
84
+
85
+ # Container for programmatic sections
86
+ self._extra_sections = []
87
+
88
+ def add_section(self, widget_or_layout):
89
+ """Programmatically add a section (widget or layout) to the dialog.
90
+
91
+ `widget_or_layout` can be a QWidget or QLayout. It will be added
92
+ immediately to the dialog's main layout.
93
+ """
94
+ try:
95
+ if hasattr(widget_or_layout, "setParent"):
96
+ # QWidget
97
+ self.layout().addWidget(widget_or_layout)
98
+ else:
99
+ # Assume QLayout
100
+ self.layout().addLayout(widget_or_layout)
101
+ self._extra_sections.append(widget_or_layout)
102
+ except Exception:
103
+ pass
104
+
105
+ def _load_values(self):
106
+ # Breadcrumb controls are not present in core dialog.
107
+ self.default_results.setValue(self.settings.get_default_n_results())
108
+ self.auto_embed_checkbox.setChecked(self.settings.get_auto_generate_embeddings())
109
+ self.restore_geometry_checkbox.setChecked(self.settings.get_window_restore_geometry())
110
+
111
+ def _apply(self):
112
+ # Values are already applied on change; ensure persistence and close
113
+ self.settings._save_settings()
114
+
115
+ def _ok(self):
116
+ self._apply()
117
+ self.accept()
118
+
119
+ def _reset_defaults(self):
120
+ # Reset to recommended defaults
121
+ self.default_results.setValue(10)
122
+ self.auto_embed_checkbox.setChecked(True)
123
+ self.restore_geometry_checkbox.setChecked(True)
124
+ self._apply()