Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(ultrawiki): refuse a folder that isn't there instead of importing zero
Ruben Lütke0ce66825a6aa
diff --git a/jarvis/ultrawiki/connectors/local_folder.py b/jarvis/ultrawiki/connectors/local_folder.pyindex 5203c6272a..74d1012a4b 100644--- a/jarvis/ultrawiki/connectors/local_folder.py+++ b/jarvis/ultrawiki/connectors/local_folder.py@@ -54,6 +54,144 @@ log = logging.getLogger(__name__)#: Matches an H1 markdown heading ("# Title") at the start of a line._H1_RE = re.compile(r"^# +(.+?)\s*$", re.MULTILINE)+#: Shell-prompt decoration a pasted path arrives with. ``C:\\Users\\Someone>``+#: is what an interactive prompt PRINTS; the ``>`` is the prompt, not the+#: folder. Same for the POSIX ``$`` / ``#`` and PowerShell's ``PS `` prefix.+_PROMPT_PREFIX_RE = re.compile(r"^(?:PS|pwsh|bash|cmd)\s+", re.IGNORECASE)+_PROMPT_SUFFIX_RE = re.compile(r"\s*[>$#]+\s*$")+++class LocalFolderRootError(RuntimeError):+ """The configured folder cannot be walked — it is missing or not a folder.++ Raised instead of yielding nothing, so the run FAILS and the reason+ reaches the source card as ``last_error``. Returning empty here is what+ let a source pasted with a shell prompt still in the path ("...>") report+ a successful import of zero items, with the reason only ever reaching a+ log file nobody reads.+ """+++def normalize_root_path(raw: str) -> str:+ """Strip what a human's copy-paste brings along, never a real folder.++ Handles surrounding quotes, stray whitespace, and shell-prompt decoration+ (``PS C:\\Users\\Someone>``, ``/home/someone$``). Touches the filesystem:+ a path that EXISTS is returned untouched, so a directory legitimately+ named ``weird>`` (legal on POSIX) is never cleaned away. Blocking — call+ it from a worker thread on any async path.+ """+ text = str(raw).strip()+ if not text:+ return text+ for quote in ('"', "'"):+ if len(text) >= 2 and text.startswith(quote) and text.endswith(quote):+ text = text[1:-1].strip()+ if _path_exists(text):+ return text+ candidate = _PROMPT_PREFIX_RE.sub("", text).strip()+ candidate = _PROMPT_SUFFIX_RE.sub("", candidate).strip()+ return candidate or text+++def _path_exists(text: str) -> bool:+ """``True`` if something is at ``text``; never raises on a bogus path.++ A string carrying shell decoration can be invalid for the platform's path+ API (``ValueError``/``OSError`` on Windows for characters like ``>``),+ which must read as "not a path", not as a crash.+ """+ try:+ return Path(text).expanduser().exists()+ except (OSError, ValueError):+ return False++#: Directory names never walked, on top of every dot-prefixed one. These hold+#: machine output, not knowledge: dependency trees, byte-code caches, and the+#: per-OS application-data folders. Importing a home folder without this list+#: buries the user's own files under orders of magnitude of vendored text.+#: Deliberately per-OS-complete rather than Windows-shaped (charter §3):+#: ``AppData`` is Windows, ``Library`` is macOS, ``.cache`` (dot-prefixed) is+#: Linux, and the dependency names are the same everywhere.+NOISE_DIR_NAMES: frozenset[str] = frozenset(+ {+ "node_modules",+ "__pycache__",+ "site-packages",+ "dist-packages",+ "bower_components",+ "vendor",+ "venv",+ "AppData",+ "Library",+ "__MACOSX",+ "$RECYCLE.BIN",+ "System Volume Information",+ }+)++#: Text-shaped suffixes read as UTF-8. Deliberately an ALLOWLIST: a folder+#: full of photos, videos and installers must import as nothing rather than+#: as megabytes of replacement characters. Grouped for review, flattened+#: below — prose and notes, structured text, markup, then source code.+_PROSE_EXTENSIONS = (".md", ".markdown", ".txt", ".text", ".rst", ".org", ".tex")+_DATA_EXTENSIONS = (+ ".csv",+ ".tsv",+ ".json",+ ".jsonl",+ ".ndjson",+ ".yaml",+ ".yml",+ ".toml",+ ".ini",+ ".cfg",+ ".conf",+ ".env.example",+)+_MARKUP_EXTENSIONS = (".html", ".htm", ".xhtml", ".xml", ".svg", ".css", ".scss")+_CODE_EXTENSIONS = (+ ".py",+ ".pyi",+ ".js",+ ".mjs",+ ".cjs",+ ".jsx",+ ".ts",+ ".tsx",+ ".vue",+ ".svelte",+ ".java",+ ".kt",+ ".go",+ ".rs",+ ".rb",+ ".php",+ ".swift",+ ".c",+ ".h",+ ".cpp",+ ".hpp",+ ".cc",+ ".cs",+ ".m",+ ".r",+ ".lua",+ ".pl",+ ".sh",+ ".bash",+ ".zsh",+ ".ps1",+ ".psm1",+ ".bat",+ ".cmd",+ ".sql",+ ".graphql",+ ".proto",+ ".dockerfile",+ ".gradle",+)+#: Files stat'ed + read per worker-thread hop. Filesystem I/O must never run#: on the event loop (it also serves voice and chat), but one hop per file#: would pay the handoff thousands of times over a real vault — a small batch@@ -115,9 +253,14 @@ class LocalFolderConnector:deletes=True,)- DEFAULT_EXTENSIONS: tuple[str, ...] = (".md", ".txt")+ DEFAULT_EXTENSIONS: tuple[str, ...] = (+ *_PROSE_EXTENSIONS,+ *_DATA_EXTENSIONS,+ *_MARKUP_EXTENSIONS,+ *_CODE_EXTENSIONS,+ )#: Directory names skipped in addition to hidden (dot-prefixed) ones.- SKIP_DIR_NAMES: frozenset[str] = frozenset()+ SKIP_DIR_NAMES: frozenset[str] = NOISE_DIR_NAMESMAX_FILE_BYTES: int = 2 * 1024 * 1024# ------------------------------------------------------------------@@ -162,6 +305,14 @@ class LocalFolderConnector:# ------------------------------------------------------------------def _resolve_root(self, ctx: ConnectorContext) -> Path | None:+ """The folder to walk, or ``None`` when none is configured at all.++ A CONFIGURED path that cannot be walked raises+ :class:`LocalFolderRootError` rather than returning ``None``: the run+ must fail so the reason lands on the card. An ABSENT ``root`` stays a+ warning + empty walk — it cannot come from the UI (the field is+ required) and subclasses resolve their root elsewhere.+ """raw = ctx.config.get("root")if not raw:log.warning(@@ -170,15 +321,35 @@ class LocalFolderConnector:ctx.source_id,)return None- root = Path(str(raw)).expanduser()- if not root.is_dir():- log.warning(- "%s: configured root %s does not exist or is not a directory; yielding nothing",+ cleaned = normalize_root_path(str(raw))+ if cleaned != str(raw).strip():+ log.info(+ "%s: read the configured folder as %r (the pasted value %r "+ "carried shell-prompt decoration)",self.id,- root,+ cleaned,+ str(raw),)- return None- return root+ try:+ root = Path(cleaned).expanduser()+ is_dir = root.is_dir()+ exists = root.exists()+ except (OSError, ValueError) as exc:+ raise LocalFolderRootError(+ f"{cleaned!r} is not a usable folder path on this system "+ f"({type(exc).__name__}). Pick the folder again."+ ) from exc+ if is_dir:+ return root+ if exists:+ raise LocalFolderRootError(+ f"{root} is a file, not a folder. Point this source at the "+ f"folder that CONTAINS it."+ )+ raise LocalFolderRootError(+ f"There is no folder at {root}. Check the path: a value copied "+ f"from a terminal often carries the prompt with it."+ )def _extensions(self, ctx: ConnectorContext) -> tuple[str, ...]:raw = ctx.config.get("extensions")@@ -292,8 +463,11 @@ class LocalFolderConnector:__all__ = [+ "NOISE_DIR_NAMES","LocalFolderConnector",+ "LocalFolderRootError","first_h1_heading","iso_utc_from_timestamp",+ "normalize_root_path","parse_mtime_cursor",]diff --git a/jarvis/ultrawiki/connectors/obsidian_vault.py b/jarvis/ultrawiki/connectors/obsidian_vault.pyindex d0550c9c97..e275299316 100644--- a/jarvis/ultrawiki/connectors/obsidian_vault.py+++ b/jarvis/ultrawiki/connectors/obsidian_vault.py@@ -24,6 +24,7 @@ from __future__ import annotationsfrom pathlib import Pathfrom jarvis.ultrawiki.connectors.local_folder import (+ NOISE_DIR_NAMES,LocalFolderConnector,first_h1_heading,)@@ -38,7 +39,9 @@ class ObsidianVaultConnector(LocalFolderConnector):# auth / capabilities inherited: LOCAL_PATH, backfill + CURSOR + deletes.DEFAULT_EXTENSIONS = (".md",)- SKIP_DIR_NAMES = frozenset({".obsidian", ".trash"})+ # The vault's own internals ON TOP of the shared noise list — a vault kept+ # inside a project folder still must not import its node_modules.+ SKIP_DIR_NAMES = NOISE_DIR_NAMES | {".obsidian", ".trash"}def _extensions(self, ctx: ConnectorContext) -> tuple[str, ...]:# An Obsidian vault is markdown by definition; ignore anydiff --git a/jarvis/ultrawiki/service.py b/jarvis/ultrawiki/service.pyindex 87ae1bd9ae..686fce6904 100644--- a/jarvis/ultrawiki/service.py+++ b/jarvis/ultrawiki/service.py@@ -103,6 +103,23 @@ BRIDGE_ADAPTER_PENDING_NOTICE = (#: state is the only one that produces the notice above)._BRIDGE_CONNECTOR_ID = "plugin-bridge"+#: Connectors that walk a folder the user chose. A zero-item run on one of+#: these is never self-explanatory: the folder can be empty, hold only file+#: types this connector does not read, or contain nothing but skipped noise -+#: three very different situations that all render as a bare "0".+_FOLDER_CONNECTOR_IDS = frozenset({"local-folder", "obsidian-vault"})+++def _empty_folder_notice(source: dict[str, Any]) -> str:+ """Say which folder was read and why it produced nothing."""+ root = str((source.get("config") or {}).get("root") or "").strip()+ where = f" at {root}" if root else ""+ return (+ f"The folder{where} was read successfully, but it held no file this "+ "source can import. Text, documents and code are imported; images, "+ "video, archives and dependency folders are skipped."+ )+def _connector_identity(connector_id: str, integration_id: str) -> tuple[str, str]:"""``(brand asset key, connector kind)`` for one registered source.@@ -943,18 +960,54 @@ class UltraWikiService:f"unknown connector {connector_id!r} "f"(available: {', '.join(sorted(registry))})")+ resolved_config = await asyncio.to_thread(+ self._checked_folder_config, registry[connector_id](), dict(config or {})+ )source_id = f"{connector_id}-{uuid.uuid4().hex[:8]}"await store.upsert_source(source_id,connector=connector_id,- label=self._resolve_label(connector_id, label, config),- config=dict(config or {}),+ label=self._resolve_label(connector_id, label, resolved_config),+ config=resolved_config,areas=list(area_ids or []),)source = await store.get_source(source_id)assert source is not Nonereturn source+ @staticmethod+ def _checked_folder_config(+ connector: Any, config: dict[str, Any]+ ) -> dict[str, Any]:+ """Clean and CHECK a folder path while the user is still watching.++ A folder source is the one connector whose credential is a path the+ user typed, so it is the one that can be wrong in a way no later stage+ can recover from. Validating at registration turns "approved, synced,+ zero items, no reason" into a refusal the user can act on immediately;+ the cleaned value is what gets stored, so a path pasted with a shell+ prompt attached works on the first try instead of never.++ Blocking (it stats the path) — call it through ``asyncio.to_thread``.+ """+ from jarvis.ultrawiki.connectors.local_folder import ( # noqa: PLC0415+ LocalFolderRootError,+ normalize_root_path,+ )+ from jarvis.ultrawiki.types import AuthKind # noqa: PLC0415++ raw = config.get("root")+ if getattr(connector, "auth", None) is not AuthKind.LOCAL_PATH or not raw:+ return config+ checked = dict(config)+ checked["root"] = normalize_root_path(str(raw))+ ctx = ConnectorContext(source_id="(new source)", config=checked)+ try:+ connector._resolve_root(ctx) # noqa: SLF001 — the connector's own rule+ except LocalFolderRootError as exc:+ raise ValueError(str(exc)) from exc+ return checked+async def _heal_bridge_labels(self, store: Any) -> None:"""One-time self-heal: give pre-existing bridge sources their real name.@@ -1358,7 +1411,10 @@ class UltraWikiService:"""if job.items > 0:return None- if str(source.get("connector") or "") != _BRIDGE_CONNECTOR_ID:+ connector_id = str(source.get("connector") or "")+ if connector_id in _FOLDER_CONNECTOR_IDS:+ return _empty_folder_notice(source)+ if connector_id != _BRIDGE_CONNECTOR_ID:return Noneintegration_id = str((source.get("config") or {}).get("integration_id") or "")if not integration_id:diff --git a/tests/unit/ultrawiki/test_connectors.py b/tests/unit/ultrawiki/test_connectors.pyindex dc78e75d19..abd3b10618 100644--- a/tests/unit/ultrawiki/test_connectors.py+++ b/tests/unit/ultrawiki/test_connectors.py@@ -27,7 +27,11 @@ from jarvis.ultrawiki.connectors import plugin_bridge as plugin_bridge_modulefrom jarvis.ultrawiki.connectors.jarvis_conversations import (JarvisConversationsConnector,)-from jarvis.ultrawiki.connectors.local_folder import LocalFolderConnector+from jarvis.ultrawiki.connectors.local_folder import (+ LocalFolderConnector,+ LocalFolderRootError,+ normalize_root_path,+)from jarvis.ultrawiki.connectors.normal_wiki import NormalWikiConnectorfrom jarvis.ultrawiki.connectors.obsidian_vault import ObsidianVaultConnectorfrom jarvis.ultrawiki.connectors.plugin_bridge import (@@ -140,13 +144,20 @@ class TestObsidianVault:)assert [item.external_id for item in resumed] == ["b.md"]- async def test_missing_root_yields_nothing_and_logs(- self, tmp_path: Path, caplog: pytest.LogCaptureFixture+ async def test_missing_root_fails_the_run_instead_of_importing_nothing(+ self, tmp_path: Path):- ctx = _ctx({"root": str(tmp_path / "absent")})- with caplog.at_level(logging.WARNING):- assert await _collect(ObsidianVaultConnector().backfill(ctx)) == []- assert "does not exist" in caplog.text+ """Was: yields nothing + a log line. A log line is not a user surface.++ A vault path that is gone (external drive unplugged, folder renamed)+ used to sync "successfully" to zero items, which reads exactly like an+ empty vault. It now fails, so the reason reaches the card.+ """+ missing = tmp_path / "absent"+ ctx = _ctx({"root": str(missing)})+ with pytest.raises(LocalFolderRootError) as excinfo:+ await _collect(ObsidianVaultConnector().backfill(ctx))+ assert str(missing) in str(excinfo.value)async def test_unparsable_cursor_reyields_everything(self, tmp_path: Path, caplog: pytest.LogCaptureFixture@@ -207,6 +218,159 @@ class TestLocalFolder:assert "no 'root' configured" in caplog.text+class TestLocalFolderRootPath:+ """A folder path a human typed or pasted, and what it must not do silently.++ The maintainer pasted ``C:\\Users\\Administrator>`` — the trailing ``>``+ belongs to the shell PROMPT, not to the path. The source registered, the+ import reported "done", and the card showed zero items with no reason+ anywhere. Both halves are pinned here: clean what is obviously shell+ decoration, and REFUSE loudly for whatever is left.+ """++ @pytest.mark.parametrize(+ ("raw", "expected"),+ [+ ("C:/Users/Someone>", "C:/Users/Someone"),+ (" C:/Users/Someone ", "C:/Users/Someone"),+ ('"C:/Users/Someone"', "C:/Users/Someone"),+ ("'C:/Users/Someone'", "C:/Users/Someone"),+ ("PS C:/Users/Someone>", "C:/Users/Someone"),+ ("C:/Users/Someone> ", "C:/Users/Someone"),+ ("/home/someone$", "/home/someone"),+ ("/home/someone #", "/home/someone"),+ ],+ )+ def test_shell_prompt_decoration_is_stripped(self, raw: str, expected: str):+ assert normalize_root_path(raw) == expected++ def test_a_real_path_survives_untouched(self, tmp_path: Path):+ assert normalize_root_path(str(tmp_path)) == str(tmp_path)++ def test_a_folder_ending_in_a_prompt_character_is_kept_when_it_exists(+ self, tmp_path: Path+ ):+ """Cleaning must never eat a real folder. ``>`` is legal on POSIX."""+ odd = tmp_path / "weird>"+ try:+ odd.mkdir()+ except OSError:+ pytest.skip("this filesystem rejects '>' in a name")+ assert normalize_root_path(str(odd)) == str(odd)++ async def test_a_root_that_does_not_exist_raises_instead_of_yielding_nothing(+ self, tmp_path: Path+ ):+ missing = tmp_path / "nope"+ with pytest.raises(LocalFolderRootError) as excinfo:+ await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(missing)}))+ )+ assert str(missing) in str(excinfo.value)++ async def test_a_pasted_prompt_path_is_cleaned_and_then_imported(+ self, tmp_path: Path+ ):+ """The maintainer's exact case: the folder IS there behind the ``>``."""+ (tmp_path / "note.md").write_text("# Hello", encoding="utf-8")+ items = await _collect(+ LocalFolderConnector().backfill(_ctx({"root": f"{tmp_path}>"}))+ )+ assert [item.external_id for item in items] == ["note.md"]++ async def test_a_file_instead_of_a_folder_raises(self, tmp_path: Path):+ target = tmp_path / "notes.md"+ target.write_text("# Hello", encoding="utf-8")+ with pytest.raises(LocalFolderRootError):+ await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(target)}))+ )++ async def test_incremental_raises_for_a_missing_root_too(self, tmp_path: Path):+ missing = tmp_path / "gone"+ with pytest.raises(LocalFolderRootError):+ await _collect(+ LocalFolderConnector().incremental(_ctx({"root": str(missing)}))+ )+++class TestLocalFolderNoiseDirectories:+ """A real home folder is mostly machine noise; a knowledge base is not.++ Walking a Desktop pulled in dependency trees and caches, which are text+ but carry no knowledge — and on a developer machine they outnumber the+ user's own files by orders of magnitude.+ """++ async def test_dependency_and_cache_directories_are_skipped(+ self, tmp_path: Path+ ):+ (tmp_path / "mine.md").write_text("keep me", encoding="utf-8")+ for noisy in ("node_modules", "__pycache__", "site-packages", "AppData"):+ folder = tmp_path / noisy+ folder.mkdir()+ (folder / "junk.md").write_text("noise", encoding="utf-8")+ items = await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)}))+ )+ assert [item.external_id for item in items] == ["mine.md"]++ async def test_an_obsidian_vault_still_skips_its_own_internals(self):+ """Widening the shared skip list must not drop the vault's own rules."""+ assert {".obsidian", ".trash"} <= ObsidianVaultConnector.SKIP_DIR_NAMES++ async def test_the_skip_list_is_not_windows_only(self):+ """Charter §3: the same walk runs on macOS and Linux."""+ assert {"node_modules", "__pycache__"} <= LocalFolderConnector.SKIP_DIR_NAMES+ assert {"AppData", "Library"} <= LocalFolderConnector.SKIP_DIR_NAMES+++class TestLocalFolderFileTypes:+ """"Import my whole Desktop" means documents and code, not just notes.++ The connector read ``.md`` and ``.txt`` only, so a folder of PDFs, Office+ documents or source code imported as zero items — indistinguishable, from+ the card, from a folder that does not exist.+ """++ async def test_source_code_and_config_files_are_read(self, tmp_path: Path):+ (tmp_path / "app.py").write_text("print('hi')", encoding="utf-8")+ (tmp_path / "config.toml").write_text("[a]\nb = 1", encoding="utf-8")+ (tmp_path / "page.html").write_text("<h1>Title</h1>", encoding="utf-8")+ items = await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)}))+ )+ assert [item.external_id for item in items] == [+ "app.py",+ "config.toml",+ "page.html",+ ]++ async def test_binary_files_are_still_ignored(self, tmp_path: Path):+ (tmp_path / "photo.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 32)+ (tmp_path / "clip.mp4").write_bytes(b"\x00" * 64)+ (tmp_path / "note.md").write_text("keep", encoding="utf-8")+ items = await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)}))+ )+ assert [item.external_id for item in items] == ["note.md"]++ async def test_an_explicit_extensions_config_still_wins(self, tmp_path: Path):+ (tmp_path / "app.py").write_text("print('hi')", encoding="utf-8")+ (tmp_path / "note.md").write_text("keep", encoding="utf-8")+ ctx = _ctx({"root": str(tmp_path), "extensions": ["md"]})+ items = await _collect(LocalFolderConnector().backfill(ctx))+ assert [item.external_id for item in items] == ["note.md"]++ async def test_an_obsidian_vault_stays_markdown_only(self, tmp_path: Path):+ (tmp_path / "app.py").write_text("print('hi')", encoding="utf-8")+ (tmp_path / "note.md").write_text("# Note", encoding="utf-8")+ items = await _collect(+ ObsidianVaultConnector().backfill(_ctx({"root": str(tmp_path)}))+ )+ assert [item.external_id for item in items] == ["note.md"]++# ---------------------------------------------------------------------------# Jarvis conversations# ---------------------------------------------------------------------------diff --git a/tests/unit/web/test_ultrawiki_routes.py b/tests/unit/web/test_ultrawiki_routes.pyindex 059795609d..3c1d9d3a5d 100644--- a/tests/unit/web/test_ultrawiki_routes.py+++ b/tests/unit/web/test_ultrawiki_routes.py@@ -1535,3 +1535,96 @@ def test_export_preview_is_not_flagged_dangerous(env) -> None:assert upload["x-jarvis-dangerous"] is True# A multi-gigabyte transfer must outlive the CLI's default client timeout.assert upload["x-jarvis-timeout-seconds"] == 600+++# ---------------------------------------------------------------------------+# Folder sources: a path a human typed must be checked while they are looking+# ---------------------------------------------------------------------------+++def test_a_folder_source_with_a_missing_path_is_refused_at_creation(env) -> None:+ """The whole point: fail while the user is still in the dialog.++ A path pasted with the shell prompt still attached (``C:/Users/Someone>``)+ registered, imported "successfully", and showed zero items with the reason+ nowhere on screen.+ """+ _activate(env)+ missing = env.tmp / "not-a-real-folder"++ response = env.client.post(+ "/api/ultrawiki/sources",+ json={+ "connector": "local-folder",+ "label": "Desktop",+ "config": {"root": str(missing)},+ },+ )++ assert response.status_code == 400, response.text+ assert str(missing) in response.json()["detail"]+++def test_a_path_pasted_with_a_shell_prompt_is_cleaned_and_accepted(env) -> None:+ _activate(env)+ docs = env.tmp / "desk"+ docs.mkdir(exist_ok=True)++ response = env.client.post(+ "/api/ultrawiki/sources",+ json={+ "connector": "local-folder",+ "label": "Desktop",+ "config": {"root": f"{docs}>"},+ },+ )++ assert response.status_code == 201, response.text+ # Stored CLEANED, so every later run walks the real folder.+ assert response.json()["config"]["root"] == str(docs)+++def test_a_file_offered_as_a_folder_source_is_refused(env) -> None:+ _activate(env)+ target = env.tmp / "notes.md"+ target.write_text("# Notes", encoding="utf-8")++ response = env.client.post(+ "/api/ultrawiki/sources",+ json={+ "connector": "local-folder",+ "label": "Notes",+ "config": {"root": str(target)},+ },+ )++ assert response.status_code == 400, response.text+ assert "folder" in response.json()["detail"].lower()+++def test_a_folder_source_that_imported_nothing_says_why(env) -> None:+ """Zero items with a green card and no explanation is the defect itself."""+ _activate(env)+ empty = env.tmp / "empty-folder"+ empty.mkdir(exist_ok=True)++ created = env.client.post(+ "/api/ultrawiki/sources",+ json={+ "connector": "local-folder",+ "label": "Empty",+ "config": {"root": str(empty)},+ },+ )+ assert created.status_code == 201, created.text+ source_id = created.json()["id"]++ approved = env.client.post(f"/api/ultrawiki/sources/{source_id}/approve")+ assert approved.status_code == 200, approved.text+ _wait_for_job(env, approved.json()["job_id"])++ listing = env.client.get("/api/ultrawiki/sources")+ assert listing.status_code == 200, listing.text+ row = next(r for r in listing.json()["sources"] if r["id"] == source_id)+ assert row["last_notice"], "an empty import must explain itself"+ assert "folder" in row["last_notice"].lower()