diff --git a/branding/smb/smb-ui.patch b/branding/smb/smb-ui.patch index b57d1c7..e27d29e 100644 --- a/branding/smb/smb-ui.patch +++ b/branding/smb/smb-ui.patch @@ -18,7 +18,7 @@ index 0f61ede9..2dcb8e7e 100644 : ccPairsIndexingStatus.last_status == "not_started" ? ConnectorCredentialPairStatus.SCHEDULED diff --git a/web/src/ee/sections/SearchCard.tsx b/web/src/ee/sections/SearchCard.tsx -index 42fb3bd8..b5244c75 100644 +index 42fb3bd8..a4b8926f 100644 --- a/web/src/ee/sections/SearchCard.tsx +++ b/web/src/ee/sections/SearchCard.tsx @@ -10,6 +10,7 @@ import { ValidSources } from "@/lib/types"; @@ -29,7 +29,7 @@ index 42fb3bd8..b5244c75 100644 import Truncated from "@/refresh-components/texts/Truncated"; import { timeAgo } from "@opal/time"; import { useMemo } from "react"; -@@ -37,6 +38,20 @@ export default function SearchCard({ +@@ -37,6 +38,25 @@ export default function SearchCard({ document.is_internet || document.source_type === ValidSources.Web; function handleClick() { @@ -38,7 +38,12 @@ index 42fb3bd8..b5244c75 100644 + // fail. Copy the logical path to the clipboard so the user can open the file + // directly on the share. Mirrors openDocument() used by the chat view. + if (document.source_type === ValidSources.IngestionApi) { -+ const path = document.semantic_identifier || document.document_id; ++ // The full network path is in `link` (file://\\server\share\...); the ++ // semantic_identifier is now just the file name, shown as the label. ++ const path = ++ document.link?.replace(/^file:\/\//, "") || ++ document.semantic_identifier || ++ document.document_id; + if (path) { + void navigator.clipboard + ?.writeText(path) @@ -51,7 +56,7 @@ index 42fb3bd8..b5244c75 100644 window.open(document.link, "_blank", "noopener,noreferrer"); return; diff --git a/web/src/lib/search/utils.ts b/web/src/lib/search/utils.ts -index ce7eab36..2711f0b6 100644 +index ce7eab36..2431a944 100644 --- a/web/src/lib/search/utils.ts +++ b/web/src/lib/search/utils.ts @@ -1,5 +1,6 @@ @@ -61,7 +66,7 @@ index ce7eab36..2711f0b6 100644 // If we have a link, open it in a new tab (including if it's a file) // If above fails and we have a file, update the presenting document -@@ -7,6 +8,20 @@ export const openDocument = ( +@@ -7,6 +8,25 @@ export const openDocument = ( document: OnyxDocument, updatePresentingDocument?: (document: MinimalOnyxDocument) => void ) => { @@ -70,7 +75,12 @@ index ce7eab36..2711f0b6 100644 + // just fail. Instead, surface the logical path by copying it to the clipboard + // so the user can open the file directly on the share. + if (document.source_type === ValidSources.IngestionApi) { -+ const path = document.semantic_identifier || document.document_id; ++ // The full network path is in `link` (file://\\server\share\...); the ++ // semantic_identifier is now just the file name, shown as the label. ++ const path = ++ document.link?.replace(/^file:\/\//, "") || ++ document.semantic_identifier || ++ document.document_id; + if (path) { + void navigator.clipboard + ?.writeText(path) diff --git a/smb-connector/README.md b/smb-connector/README.md index eaefb15..fa504d9 100644 --- a/smb-connector/README.md +++ b/smb-connector/README.md @@ -91,6 +91,7 @@ CIFS-mounted a second time — `_MOUNT` then just points at the bind-mounted pat | `INGESTION_INTERVAL_SECONDS` | Reconcile interval (default 300) | | `INCLUDE_EXTENSIONS` | File types to ingest (default pdf,docx,txt,md,csv,xlsx,html) | | `MAX_FILE_MB` | Skip files larger than this (default 50) | +| `SMB_WRITE_INDEX` | Write a per-source index (table-of-contents) document listing every file, so the assistant is aware of the full set (default on; `0`/`false` to disable) | State (manifest + cached key/cc_pair) lives in the mounted `/app/state` volume. diff --git a/smb-connector/app/config.py b/smb-connector/app/config.py index 48da467..819ceef 100644 --- a/smb-connector/app/config.py +++ b/smb-connector/app/config.py @@ -59,6 +59,9 @@ class Config: filename_encoding: str = "cp1252" connector_name_prefix: str = "AIDO SMB" http_timeout: int = 60 + # Write one table-of-contents (index) document per source, listing every + # file on the share so the assistant is aware of the full document set. + write_index: bool = True sources: list[SourceConfig] = field(default_factory=list) @@ -149,6 +152,9 @@ def load_config() -> Config: connector_name_prefix=os.environ.get("ONYX_CONNECTOR_NAME_PREFIX", "AIDO SMB"), # HTTP timeout for Onyx API calls; raise it for large embeddings/ingests. http_timeout=int(os.environ.get("ONYX_HTTP_TIMEOUT", "60")), + # Write a per-source index (table-of-contents) document. Set to 0/false to disable. + write_index=os.environ.get("SMB_WRITE_INDEX", "1").strip().lower() + not in ("0", "false", "no", "off"), sources=_load_sources(), ) if not cfg.sources: diff --git a/smb-connector/app/state.py b/smb-connector/app/state.py index b78c01d..1b9106e 100644 --- a/smb-connector/app/state.py +++ b/smb-connector/app/state.py @@ -24,6 +24,12 @@ class FileRecord: logical_path: str size: int mtime: float + # Ingestion payload format this file was last sent with. Bumping + # DOC_FORMAT_VERSION in sync.py forces a one-time re-upsert of every file + # when the document shape changes (e.g. the semantic_identifier), even + # though the file bytes are unchanged. Defaults to 1 for manifests written + # before this field existed. + doc_format_version: int = 1 @dataclass @@ -31,6 +37,10 @@ class SourceState: cc_pair_id: int | None = None # relative-path -> FileRecord files: dict[str, FileRecord] = field(default_factory=dict) + # Content hash of the last table-of-contents (index) document written for + # this source. Lets the engine re-upsert the index only when the file set + # changed. None until the first index is written. + index_hash: str | None = None class State: @@ -49,7 +59,7 @@ class State: raw = json.load(fh) state.api_key = raw.get("api_key") for name, s in (raw.get("sources") or {}).items(): - ss = SourceState(cc_pair_id=s.get("cc_pair_id")) + ss = SourceState(cc_pair_id=s.get("cc_pair_id"), index_hash=s.get("index_hash")) for rel, rec in (s.get("files") or {}).items(): ss.files[rel] = FileRecord(**rec) state.sources[name] = ss @@ -62,6 +72,7 @@ class State: "sources": { name: { "cc_pair_id": ss.cc_pair_id, + "index_hash": ss.index_hash, "files": {rel: vars(rec) for rel, rec in ss.files.items()}, } for name, ss in self.sources.items() diff --git a/smb-connector/app/sync.py b/smb-connector/app/sync.py index 2a8ae39..f854ca6 100644 --- a/smb-connector/app/sync.py +++ b/smb-connector/app/sync.py @@ -26,6 +26,11 @@ from .state import FileRecord, State logger = logging.getLogger("smb.sync") +# Bump this when the ingestion document shape changes (fields Onyx displays or +# indexes) so every already-synced file is re-upserted once, even though its +# bytes are unchanged. v2: semantic_identifier is the file name, not the path. +DOC_FORMAT_VERSION = 2 + def _source_slug(source_name: str) -> str: return re.sub(r"[^a-zA-Z0-9]+", "-", source_name).strip("-").lower() or "src" @@ -88,15 +93,18 @@ def _build_document( source: SourceConfig, rel_path: str, doc_id: str, text: str, mtime: float ) -> dict: logical = _logical_path(source, rel_path) + filename = os.path.basename(rel_path) updated = datetime.fromtimestamp(mtime, tz=timezone.utc).isoformat() return { "id": doc_id, "source": "ingestion_api", - # semantic_identifier is the main label Onyx shows in the citation view. - "semantic_identifier": logical, - "title": os.path.basename(rel_path), - # A link is kept for reference; smb:// won't open in a browser (Phase 2 - # replaces the broken preview with this path shown as copyable text). + # semantic_identifier is the label Onyx shows in the citation view. Use the + # file name so the citation stays short; the full network path is still in + # `link` and metadata, and the UI overlay copies it on click. + "semantic_identifier": filename, + "title": filename, + # The full logical network path. smb://Z:\... won't open in a browser; the + # Phase 2 UI overlay copies this to the clipboard on click instead. "link": f"file://{logical}", "sections": [{"text": text, "link": None}], "metadata": { @@ -108,6 +116,57 @@ def _build_document( } +def _index_document_id(source_name: str) -> str: + # Shares the source prefix so it is recognised as this connector's document, + # but has a fixed suffix so it is never treated as a file. The reconcile pass + # must whitelist this id (see sync_source) or it would be deleted as an orphan. + return f"{_source_id_prefix(source_name)}index" + + +def _build_index_text(source: SourceConfig, files: dict[str, "FileRecord"]) -> str: + """A human/LLM-readable table of contents: every file grouped by folder.""" + by_folder: dict[str, list[str]] = {} + for rel, rec in files.items(): + folder = os.path.dirname(rec.logical_path) or source.normalized_logical() + by_folder.setdefault(folder, []).append(rec.logical_path) + + lines = [ + f"Index of all documents synced from {source.name}.", + f"Total files: {len(files)}.", + "", + "This document lists every file available on this share, grouped by folder,", + "so the assistant knows the full set of documents even when a search only", + "returns some of them.", + "", + ] + for folder in sorted(by_folder): + lines.append(f"{folder}") + for path in sorted(by_folder[folder]): + lines.append(f" - {os.path.basename(path)}\t{path}") + lines.append("") + return "\n".join(lines) + + +def _build_index_document(source: SourceConfig, files: dict[str, "FileRecord"]) -> dict: + text = _build_index_text(source, files) + label = f"{source.name} — Index ({len(files)} Dateien)" + return { + "id": _index_document_id(source.name), + "source": "ingestion_api", + "semantic_identifier": label, + "title": label, + # No file:// link: the index is a generated document, not a file on the + # share, so clicking it should not try to copy a path. + "link": None, + "sections": [{"text": text, "link": None}], + "metadata": { + "smb_source": source.name, + "smb_index": "true", + }, + "doc_updated_at": datetime.now(tz=timezone.utc).isoformat(), + } + + def sync_source(client: OnyxClient, cfg: Config, source: SourceConfig, state: State) -> None: if not os.path.isdir(source.mount): logger.error("Source '%s': mount %s is not accessible — skipping", source.name, source.mount) @@ -141,7 +200,11 @@ def sync_source(client: OnyxClient, cfg: Config, source: SourceConfig, state: St content_hash = hashlib.sha256(data).hexdigest() prev = ss.files.get(rel) - if prev and prev.content_hash == content_hash: + if ( + prev + and prev.content_hash == content_hash + and prev.doc_format_version == DOC_FORMAT_VERSION + ): unchanged += 1 continue @@ -167,6 +230,7 @@ def sync_source(client: OnyxClient, cfg: Config, source: SourceConfig, state: St logical_path=_logical_path(source, rel), size=len(data), mtime=os.path.getmtime(abspath), + doc_format_version=DOC_FORMAT_VERSION, ) upserts += 1 logger.info("%s %s", "updated" if prev else "indexed", rel) @@ -186,10 +250,40 @@ def sync_source(client: OnyxClient, cfg: Config, source: SourceConfig, state: St state.save() + # Index (table-of-contents) document: one per source, re-upserted only when + # the file set changed. Written after deletes so it reflects the current set. + index_id = _index_document_id(source.name) + if cfg.write_index and ss.files: + index_doc = _build_index_document(source, ss.files) + index_hash = hashlib.sha256( + index_doc["sections"][0]["text"].encode("utf-8") + ).hexdigest() + if ss.index_hash != index_hash: + try: + client.upsert_document(index_doc, cc_pair_id) + ss.index_hash = index_hash + state.save() + logger.info("wrote index document (%d files)", len(ss.files)) + except OnyxError as exc: + logger.error("Index upsert failed for '%s': %s", source.name, exc) + elif not cfg.write_index and ss.index_hash is not None: + # Feature turned off after an index was written — remove it. + try: + client.delete_document(index_id) + ss.index_hash = None + state.save() + logger.info("removed index document (SMB_WRITE_INDEX disabled)") + except OnyxError as exc: + logger.warning("Index delete for '%s' skipped: %s", source.name, exc) + # Manifest-independent reconcile: remove Onyx docs for this cc_pair that we # no longer track (covers a lost manifest / externally-added docs). try: live_ids = {r.document_id for r in ss.files.values()} + # The index document shares the source prefix but is not a file, so it + # must be whitelisted here or the reconcile would delete it every cycle. + if cfg.write_index and ss.files: + live_ids.add(index_id) for doc in client.list_cc_pair_documents(cc_pair_id): did = doc.get("document_id") if did and did.startswith(_source_id_prefix(source.name)) and did not in live_ids: