Skip to content

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.

feat(ultrawiki): read the documents the cloud connectors were throwing away

Ruben Lütke0707f7e30eed
diff --git a/jarvis/ultrawiki/adapters/dropbox.py b/jarvis/ultrawiki/adapters/dropbox.py
index 5ec5d7a3bb..fb5dbdc5cb 100644
--- a/jarvis/ultrawiki/adapters/dropbox.py
+++ b/jarvis/ultrawiki/adapters/dropbox.py
@@ -1,13 +1,15 @@
-"""Dropbox pull adapter — the text files in the connected Dropbox.
+"""Dropbox pull adapter — the readable files in the connected Dropbox.
Of everything a Dropbox holds, this pulls the part that belongs in a *memory*:
-the text-like files — notes, documents, exports, configs — matched by the same
-extension-allowlist philosophy the local-folder connector uses (a curated
-default set, overridable per source via ``config["extensions"]``). Binaries
-are skipped honestly, by extension, before a single byte is downloaded: this
-adapter ships no OCR and no PDF/Office extraction, and pretending a JPEG is a
-memory would only pollute search. Dropbox Paper docs and other entries the API
-marks non-downloadable are excluded by the listing itself.
+the files with text inside — notes, exports, configs, and the documents a
+Dropbox is actually full of (PDF, Word, Excel, PowerPoint, OpenDocument,
+EPUB, RTF), read through the shared extraction service. Matching follows the
+same extension-allowlist philosophy the local-folder connector uses (a curated
+default set, overridable per source via ``config["extensions"]``). True blobs
+— pictures, video, archives — are skipped honestly, by extension, before a
+single byte is downloaded: this adapter ships no OCR, and pretending a JPEG is
+a memory would only pollute search. Dropbox Paper docs and other entries the
+API marks non-downloadable are excluded by the listing itself.
Scope, stated plainly:
@@ -15,10 +17,13 @@ Scope, stated plainly:
``recursive=true`` plus ``list_folder/continue`` cursor paging, so team
folders and deep trees are all reached. Only the extension allowlist and the
size caps narrow what is *imported*.
-* **Size caps:** files whose listed size exceeds 2 MiB are skipped with a log
- line (the local-folder connector's limit); a downloaded body is cut at 1 MiB
- with a visible truncation marker. A knowledge base wants the text, not a
- bulk mirror.
+* **Size caps:** a text file above 2 MiB (the local-folder connector's limit)
+ and a document above ``MAX_DOCUMENT_BYTES`` are not downloaded; a downloaded
+ text body is cut at 1 MiB with a visible truncation marker. Documents are
+ never cut — half a container parses as nothing — so for them the ceiling
+ refuses instead. **A file over any ceiling still becomes an item** carrying
+ the reason: silence is indistinguishable from a missing file, and one of
+ those two is a bug.
* **Incremental is client-side.** Dropbox's ``list_folder`` has no
modified-since filter, and its own delta cursor (``list_folder/continue``
across runs) is an opaque string that cannot ride the sync runner's NUMERIC
@@ -51,11 +56,17 @@ from urllib.parse import quote
import httpx
+from jarvis.ultrawiki.extract import (
+ DOCUMENT_EXTENSIONS,
+ MAX_DOCUMENT_BYTES,
+ extract_text,
+)
from jarvis.ultrawiki.types import ConnectorContext, RawItem
log = logging.getLogger(__name__)
__all__ = [
+ "INCLUDED_EXTENSIONS",
"INTEGRATION_ID",
"TEXT_EXTENSIONS",
"DropboxAdapterError",
@@ -116,6 +127,18 @@ TEXT_EXTENSIONS: tuple[str, ...] = (
".xml",
)
+#: What a walk actually looks at: the text shapes above PLUS every document
+#: the extraction service can read. The two are separated because they are
+#: fetched differently — a text file may be cut, a container may not.
+INCLUDED_EXTENSIONS: tuple[str, ...] = TEXT_EXTENSIONS + tuple(
+ sorted(DOCUMENT_EXTENSIONS)
+)
+
+
+def _is_document(path: str) -> bool:
+ """True when this name belongs to the extractor rather than a UTF-8 read."""
+ return PurePosixPath(path).suffix.lower() in DOCUMENT_EXTENSIONS
+
class DropboxAdapterError(RuntimeError):
"""A pull step failed. The message is safe to show and never holds the token."""
@@ -223,14 +246,14 @@ def _extensions(ctx: ConnectorContext) -> tuple[str, ...]:
"""
raw = ctx.config.get("extensions")
if not raw:
- return TEXT_EXTENSIONS
+ return INCLUDED_EXTENSIONS
normalized: list[str] = []
for entry in raw:
text = str(entry).strip().lower()
if not text:
continue
normalized.append(text if text.startswith(".") else f".{text}")
- return tuple(normalized) or TEXT_EXTENSIONS
+ return tuple(normalized) or INCLUDED_EXTENSIONS
async def _list_text_files(
@@ -283,10 +306,15 @@ async def _list_text_files(
return entries
-async def _download_text(
+async def _download_body(
client: httpx.AsyncClient, token: str, path_lower: str
-) -> str | None:
- """One file body as capped text; ``None`` skips the file, auth aborts.
+) -> tuple[str, str] | None:
+ """``(text, missing_reason)`` for one file; ``None`` skips it, auth aborts.
+
+ A document (PDF, Word, deck, …) is handed to the shared extraction service
+ instead of being decoded as UTF-8 — decoding a container produced a body of
+ replacement characters, which is why these files were excluded outright
+ and a Dropbox full of PDFs imported as the handful of notes beside them.
A single vanished or unreadable file (deleted between list and download,
a 409 path error) must not sink the other thousand — but a rejected token
@@ -305,10 +333,16 @@ async def _download_text(
)
return None
raw = response.content
+ name = PurePosixPath(path_lower).name
+ if _is_document(path_lower):
+ result = extract_text(raw, filename=name)
+ if result.ok:
+ return (result.text, "")
+ return ("", result.reason or "no text could be read from this file")
text = raw[:_MAX_BODY_BYTES].decode("utf-8", errors="replace")
if len(raw) > _MAX_BODY_BYTES:
text += _TRUNCATION_MARKER
- return text
+ return (text, "")
def _to_ns(iso: str) -> int:
@@ -354,8 +388,15 @@ def _preview_url(path_display: str) -> str:
return f"{base}?preview={quote(parts[-1])}"
-def item_from_entry(entry: dict[str, Any], body: str) -> RawItem | None:
- """One listed file plus its downloaded body as a ``RawItem``."""
+def item_from_entry(
+ entry: dict[str, Any], body: str, *, content_missing_reason: str = ""
+) -> RawItem | None:
+ """One listed file plus its downloaded body as a ``RawItem``.
+
+ ``content_missing_reason`` produces the item anyway, marked and explained:
+ a scanned contract or an oversized archive stays findable by name, folder
+ and date rather than disappearing without a trace.
+ """
path_lower = str(entry.get("path_lower") or "")
if not path_lower:
return None
@@ -363,6 +404,8 @@ def item_from_entry(entry: dict[str, Any], body: str) -> RawItem | None:
modified = str(entry.get("server_modified") or entry.get("client_modified") or "")
name = PurePosixPath(path_display)
parent = path_lower.rsplit("/", 1)[0] or "/"
+ if not body and content_missing_reason:
+ body = f"File: {name.name}\n[no text imported: {content_missing_reason}]"
return RawItem(
external_id=path_lower,
title=name.stem or name.name,
@@ -377,6 +420,14 @@ def item_from_entry(entry: dict[str, Any], body: str) -> RawItem | None:
"size_bytes": int(entry.get("size") or 0),
"path_display": path_display,
"rev": str(entry.get("rev") or ""),
+ **(
+ {
+ "content_missing": True,
+ "content_missing_reason": content_missing_reason,
+ }
+ if content_missing_reason
+ else {}
+ ),
},
)
@@ -413,18 +464,32 @@ async def dropbox_pull_adapter(
if _to_ns(modified) <= min_mtime_ns:
continue # unchanged since the cursor — never downloaded
size = int(entry.get("size") or 0)
- if size > _MAX_DOWNLOAD_BYTES:
- log.info(
- "dropbox adapter: skipping %s (%d bytes exceeds the %d-byte limit)",
- path_lower,
- size,
- _MAX_DOWNLOAD_BYTES,
+ ceiling = (
+ MAX_DOCUMENT_BYTES if _is_document(path_lower) else _MAX_DOWNLOAD_BYTES
+ )
+ if size > ceiling:
+ # Still an item. A file that vanishes from the knowledge base
+ # because it was large reads exactly like a file that was never
+ # there — and the second is a bug, so both must be visible.
+ oversized = item_from_entry(
+ entry,
+ "",
+ content_missing_reason=(
+ f"the file is {size // (1024 * 1024)} MB, above the "
+ f"{ceiling // (1024 * 1024)} MB import limit"
+ ),
)
+ if oversized is not None:
+ yielded += 1
+ yield oversized
continue
- body = await _download_text(client, token, path_lower)
- if body is None:
+ fetched = await _download_body(client, token, path_lower)
+ if fetched is None:
continue
- item = item_from_entry(entry, body)
+ body, missing_reason = fetched
+ item = item_from_entry(
+ entry, body, content_missing_reason=missing_reason
+ )
if item is not None:
yielded += 1
yield item
diff --git a/jarvis/ultrawiki/adapters/google_drive.py b/jarvis/ultrawiki/adapters/google_drive.py
index 11c1522d1c..c96f36fbdf 100644
--- a/jarvis/ultrawiki/adapters/google_drive.py
+++ b/jarvis/ultrawiki/adapters/google_drive.py
@@ -3,26 +3,35 @@
Of everything Drive holds, this pulls what belongs in a *memory*: the TEXT.
Google-native documents are exported to plain text (Docs → ``text/plain``,
Sheets → ``text/csv``, Slides → ``text/plain``); text-shaped regular files
-(``text/*``, JSON, XML, YAML, …) are downloaded directly. The walk lists the
-complete non-trashed corpus ordered by ``modifiedTime`` ascending, so an
-interrupted backfill resumes strictly after the last imported file id without
+(``text/*``, JSON, XML, YAML, …) are downloaded directly; uploaded documents
+(PDF, Word, Excel, PowerPoint, OpenDocument, EPUB, RTF) are downloaded whole
+and read by the shared extraction service. The walk lists the complete
+non-trashed corpus ordered by ``modifiedTime`` ascending, so an interrupted
+backfill resumes strictly after the last imported file id without
re-downloading anything before it.
Scope honesty — what the token allows vs. what is imported:
-- **Binaries are skipped, deliberately and visibly.** Images, videos,
- archives, PDFs and Office binaries have no text the Drive API can hand
- over as such (Drive exports only Google-native types), and a knowledge
- base must never swallow blobs. Skipped files are counted in one log line;
- they yield NO item.
+- **Only true blobs are skipped**: pictures, videos, audio and archives, plus
+ Drive's own structural types (folders, shortcuts, forms). They are counted
+ in one log line and yield NO item. Everything with text inside is imported,
+ including the formats Drive cannot export — that is the difference between
+ a knowledge base holding a Drive and holding the parts of it Google happens
+ to convert.
+- **A document whose text cannot be read is still imported**, marked
+ ``content_missing`` with the reason: a scanned PDF, an oversized upload or
+ a failed download stays findable by name, owner and date instead of
+ vanishing without trace.
- **Folders and shortcuts are skipped** — structure, not content; a
shortcut's target imports as itself.
-- **Bodies are capped at ~1 MB** with a visible truncation marker. Direct
- downloads are bounded at the source with an HTTP ``Range`` header, so an
- oversized file never crosses the wire whole; Google-native exports are
- additionally subject to Google's own ~10 MB export ceiling — a document
- whose export fails yields its metadata with an honest note instead of
- failing the sync.
+- **Bodies are capped at ~1 MB** with a visible truncation marker. A plain
+ text download is bounded at the source with an HTTP ``Range`` header, so an
+ oversized log file never crosses the wire whole. A document read by the
+ extractor cannot be bounded that way — half a PDF or half a ZIP parses as
+ nothing — so it is fetched whole below ``MAX_DOCUMENT_BYTES`` and refused
+ with a sentence above it. Google-native exports are additionally subject to
+ Google's own ~10 MB export ceiling; a document whose export fails yields
+ its metadata with an honest note instead of failing the sync.
- **Shared drives are not enumerated.** The walk covers the user corpus (My
Drive plus items shared with the user that surface in ``files.list``);
separate shared-drive corpora need a per-drive walk a later change can add.
@@ -39,11 +48,17 @@ from __future__ import annotations
import logging
from collections.abc import AsyncIterator
+from pathlib import PurePosixPath
from typing import Any
import httpx
from jarvis.ultrawiki.adapters import _google as g
+from jarvis.ultrawiki.extract import (
+ DOCUMENT_EXTENSIONS,
+ MAX_DOCUMENT_BYTES,
+ extract_text,
+)
from jarvis.ultrawiki.types import ConnectorContext, RawItem
log = logging.getLogger(__name__)
@@ -92,26 +107,69 @@ _TEXT_MIMES: frozenset[str] = frozenset(
}
)
+#: Uploaded documents that carry text no API hands over as such. Drive exports
+#: only its OWN formats, so every one of these used to leave as "no text
+#: form" — and they are the single largest category of real documents in a
+#: real Drive: the contract, the invoice, the deck someone sent by mail.
+#: The shared extraction service reads them from their bytes.
+_DOCUMENT_MIMES: frozenset[str] = frozenset(
+ {
+ "application/pdf",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ "application/msword",
+ "application/vnd.ms-excel",
+ "application/vnd.ms-powerpoint",
+ "application/vnd.oasis.opendocument.text",
+ "application/vnd.oasis.opendocument.spreadsheet",
+ "application/vnd.oasis.opendocument.presentation",
+ "application/epub+zip",
+ "application/rtf",
+ "text/rtf",
+ }
+)
+
-def _content_plan(mime: str) -> tuple[str, str] | None:
- """How to obtain a file's text: ``("export", target)``, ``("download", "")``,
- or ``None`` when the file has no text form and is skipped honestly."""
+def _content_plan(mime: str, name: str = "") -> tuple[str, str] | None:
+ """How to obtain a file's text: ``("export", target)``, ``("extract", "")``,
+ ``("download", "")``, or ``None`` when the file has no text form.
+
+ The name is consulted after the type because Drive's MIME is only as good
+ as whatever uploaded the file: a PDF dropped in by a scanner or a sync
+ client routinely arrives as ``application/octet-stream``, and judging it
+ by type alone would throw the document away.
+ """
if mime in _GOOGLE_EXPORTS:
return ("export", _GOOGLE_EXPORTS[mime])
if mime.startswith("application/vnd.google-apps."):
return None # folder, shortcut, form, drawing, … — no text export
+ suffix = PurePosixPath(name).suffix.lower()
+ # Documents are checked BEFORE the text shapes: RTF announces itself as
+ # `text/rtf` and would otherwise import as its own control words.
+ if mime in _DOCUMENT_MIMES or suffix in DOCUMENT_EXTENSIONS:
+ return ("extract", "")
if mime.startswith("text/") or mime in _TEXT_MIMES:
return ("download", "")
return None
def item_from_file(
- file: dict[str, Any], content: str, content_truncated: bool
+ file: dict[str, Any],
+ content: str,
+ content_truncated: bool,
+ *,
+ content_missing_reason: str = "",
) -> RawItem | None:
"""One listed file plus its fetched text as a ``RawItem``.
The body is composed rather than copied raw: bare file content loses its
own name, kind and owner — the handles a later question reaches for.
+
+ ``content_missing_reason`` marks a file whose text could not be read. The
+ item is still produced: a scanned contract that is findable by name, date
+ and owner, and that SAYS its text is missing, is worth incomparably more
+ than a document the knowledge base silently pretends it never saw.
"""
file_id = str(file.get("id") or "").strip()
if not file_id:
@@ -139,6 +197,8 @@ def item_from_file(
if content:
lines.append("")
lines.append(content)
+ elif content_missing_reason:
+ lines.append(f"[no text imported: {content_missing_reason}]")
body, capped = g.cap_body("\n".join(lines).strip())
truncated = capped or content_truncated
if content_truncated and not capped:
@@ -163,6 +223,14 @@ def item_from_file(
"mime_type": mime,
"size": size,
"truncated": truncated,
+ **(
+ {
+ "content_missing": True,
+ "content_missing_reason": content_missing_reason,
+ }
+ if content_missing_reason
+ else {}
+ ),
},
)
@@ -201,19 +269,64 @@ async def _all_files(
async def _file_text(
client: httpx.AsyncClient, token: str, file: dict[str, Any]
-) -> tuple[str, bool] | None:
- """``(text, truncated)`` for one file, or ``None`` when it has no text form.
+) -> tuple[str, bool, str] | None:
+ """``(text, truncated, missing_reason)``, or ``None`` when there is no text
+ form at all and the file is skipped.
+
+ A non-empty ``missing_reason`` is a FILE that exists and a CONTENT that
+ could not be read — a scanned PDF, an oversized upload. That is not the
+ same as having nothing to import: the item is still stored, so the
+ document is findable by its name and its absence is visible instead of
+ looking like it was never there.
A per-file fetch failure (export ceiling, permission quirk on one item)
degrades to an honest note — one stubborn file must never sink the whole
walk. Credential failures and exhausted rate budgets still raise, because
they concern the sync, not the file.
"""
- plan = _content_plan(str(file.get("mimeType") or ""))
+ mime = str(file.get("mimeType") or "")
+ name = str(file.get("name") or "")
+ plan = _content_plan(mime, name)
if plan is None:
return None
mode, target = plan
file_id = str(file.get("id") or "")
+ try:
+ declared = int(file.get("size") or 0)
+ except (TypeError, ValueError):
+ declared = 0
+
+ if mode == "extract":
+ # Whole file or nothing: a container cannot be range-truncated (see
+ # MAX_DOCUMENT_BYTES). So the ceiling REJECTS, with a sentence, rather
+ # than fetching a prefix that would parse as an empty document.
+ if declared > MAX_DOCUMENT_BYTES:
+ return (
+ "",
+ False,
+ f"the file is {declared // (1024 * 1024)} MB, above the "
+ f"{MAX_DOCUMENT_BYTES // (1024 * 1024)} MB import limit for "
+ "documents read whole",
+ )
+ response = await g.google_get(
+ client,
+ f"{_API}/files/{file_id}",
+ token,
+ _PRODUCT,
+ params={"alt": "media"},
+ tolerate=(403, 404),
+ )
+ if response.status_code >= 400:
+ return (
+ "",
+ False,
+ f"the download failed (HTTP {response.status_code}) — open the "
+ "link to view it",
+ )
+ result = extract_text(response.content, filename=name, mime=mime)
+ if result.ok:
+ return (result.text, False, "")
+ return ("", False, result.reason or "no text could be read from this file")
if mode == "export":
response = await g.google_get(
@@ -226,14 +339,16 @@ async def _file_text(
)
if response.status_code >= 400:
return (
- f"[content could not be exported (HTTP {response.status_code}) — "
- "open the link to view it]",
+ "",
False,
+ f"the export failed (HTTP {response.status_code}) — open the "
+ "link to view it",
)
- return response.text, False
+ return (response.text, False, "")
# Direct download, bounded at the source: the Range header caps what
- # crosses the wire, so an oversized file costs one capped request.
+ # crosses the wire, so an oversized file costs one capped request. Safe
+ # here and only here, because a text file cut mid-way is still text.
response = await g.google_get(
client,
f"{_API}/files/{file_id}",
@@ -244,19 +359,16 @@ async def _file_text(
tolerate=(403, 404, 416),
)
if response.status_code == 416: # empty file: the range has nothing to cover
- return "", False
+ return ("", False, "")
if response.status_code >= 400:
return (
- f"[content could not be downloaded (HTTP {response.status_code}) — "
- "open the link to view it]",
+ "",
False,
+ f"the download failed (HTTP {response.status_code}) — open the "
+ "link to view it",
)
- try:
- declared = int(file.get("size") or 0)
- except (TypeError, ValueError):
- declared = 0
truncated = response.status_code == 206 and declared > g.BODY_CAP
- return response.text, truncated
+ return (response.text, truncated, "")
async def google_drive_pull_adapter(
@@ -283,6 +395,7 @@ async def google_drive_pull_adapter(
resume_after = checkpoint if (checkpoint and cutoff is None) else None
yielded = 0
skipped = 0
+ unreadable = 0
async with httpx.AsyncClient(timeout=g.TIMEOUT, transport=transport) as client:
files = await _all_files(client, token, query)
@@ -304,8 +417,15 @@ async def google_drive_pull_adapter(
if fetched is None:
skipped += 1
continue
- content, content_truncated = fetched
- item = item_from_file(file, content, content_truncated)
+ content, content_truncated, missing_reason = fetched
+ if missing_reason:
+ unreadable += 1
+ item = item_from_file(
+ file,
+ content,
+ content_truncated,
+ content_missing_reason=missing_reason,
+ )
if item is not None:
yielded += 1
yield item
@@ -313,9 +433,15 @@ async def google_drive_pull_adapter(
if skipped:
log.info(
"Google Drive adapter: skipped %d file(s) with no text form "
- "(binaries are never imported)",
+ "(pictures, videos and archives are never imported)",
skipped,
)
+ if unreadable:
+ log.info(
+ "Google Drive adapter: %d file(s) were imported without their text "
+ "(scanned, oversized or unreadable); each item says why",
+ unreadable,
+ )
log.info(
"Google Drive adapter: yielded %d item(s) for %s (%s)",
yielded,
diff --git a/jarvis/ultrawiki/connectors/local_folder.py b/jarvis/ultrawiki/connectors/local_folder.py
index 94090e3280..8e24755d85 100644
--- a/jarvis/ultrawiki/connectors/local_folder.py
+++ b/jarvis/ultrawiki/connectors/local_folder.py
@@ -48,6 +48,7 @@ from jarvis.ultrawiki.extract import (
detect_kind,
extract_text,
)
+from jarvis.ultrawiki.extract import MAX_DOCUMENT_BYTES as _MAX_DOCUMENT_BYTES
from jarvis.ultrawiki.media import MediaRef
from jarvis.ultrawiki.types import (
AuthKind,
@@ -209,8 +210,10 @@ _LARGE_DOCUMENT_KINDS: frozenset[str] = frozenset(
)
#: Absolute ceiling for anything read as a whole document, media excluded.
-#: Far above the text limit, far below what could exhaust a small VPS.
-MAX_DOCUMENT_BYTES = 64 * 1024 * 1024
+#: Far above the text limit, far below what could exhaust a small VPS. Owned
+#: by the extraction service so a folder walk and a cloud adapter cannot drift
+#: apart on the same question; re-exported here for the callers that had it.
+MAX_DOCUMENT_BYTES = _MAX_DOCUMENT_BYTES
#: 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
diff --git a/jarvis/ultrawiki/extract.py b/jarvis/ultrawiki/extract.py
index bc1a0cc6c8..e172ae2caa 100644
--- a/jarvis/ultrawiki/extract.py
+++ b/jarvis/ultrawiki/extract.py
@@ -58,6 +58,7 @@ log = logging.getLogger(__name__)
__all__ = [
"DOCUMENT_EXTENSIONS",
"ExtractResult",
+ "MAX_DOCUMENT_BYTES",
"MEDIA_EXTENSIONS",
"MEDIA_KINDS",
"TEXT_EXTENSIONS",
@@ -74,6 +75,14 @@ _SNIFF_BYTES = 8192
#: about 30 000 pages; beyond it the file is a database, not a document.
_MAX_TEXT_CHARS = 64 * 1024 * 1024
+#: Ceiling for reading a file WHOLE, shared by every walker and adapter so the
+#: policy has one home. It rejects rather than truncates, and that is the
+#: point: a container format cannot be cut. Half a ZIP has no central
+#: directory and half a PDF has no cross-reference table — both read as
+#: nothing at all, so a range-limited download would turn a large document
+#: into a silent empty item instead of an honest oversized one.
+MAX_DOCUMENT_BYTES = 64 * 1024 * 1024
+
#: Leading magic → kind. Order matters: ZIP-based office formats share the
#: `PK` signature and are separated afterwards by their inner layout.
_MAGIC: tuple[tuple[bytes, str], ...] = (
diff --git a/tests/unit/ultrawiki/adapters/test_dropbox.py b/tests/unit/ultrawiki/adapters/test_dropbox.py
index 00d62e5b35..2366e3a73d 100644
--- a/tests/unit/ultrawiki/adapters/test_dropbox.py
+++ b/tests/unit/ultrawiki/adapters/test_dropbox.py
@@ -10,7 +10,9 @@ that never carry the token.
from __future__ import annotations
+import io
import json
+import zipfile
from typing import Any
import httpx
@@ -71,10 +73,13 @@ def _file(
def _transport(
pages: list[list[dict[str, Any]]],
- contents: dict[str, str],
+ contents: dict[str, str | bytes],
*,
seen: list[httpx.Request] | None = None,
) -> httpx.MockTransport:
+ """A fake Dropbox. ``contents`` accepts bytes for real binary documents —
+ the shape a PDF or a Word file actually arrives in."""
+
def handler(request: httpx.Request) -> httpx.Response:
if seen is not None:
seen.append(request)
@@ -85,6 +90,8 @@ def _transport(
if body is None:
# The file vanished between list and download.
return httpx.Response(409, json={"error_summary": "path/not_found/.."})
+ if isinstance(body, bytes):
+ return httpx.Response(200, content=body)
return httpx.Response(200, content=body.encode())
if path == "/2/files/list_folder":
index = 0
@@ -139,16 +146,59 @@ async def test_a_text_file_becomes_a_linkable_dated_item():
assert item.metadata["rev"] == "0123456789abcdef"
-async def test_binaries_are_never_downloaded():
+async def test_blobs_are_never_downloaded_but_documents_are():
"""The skip happens by extension BEFORE any byte moves — a photo library
- must not cost one request per photo just to be rejected."""
+ must not cost one request per photo just to be rejected.
+
+ A PDF is not in that category, and treating it as one is what made
+ "import my Dropbox" quietly mean "import the notes lying beside the
+ documents".
+ """
seen: list[httpx.Request] = []
pages = [[_file("/photo.jpg"), _file("/report.pdf"), _file("/notes.md")]]
items = await _collect(
- transport=_transport(pages, {"/notes.md": "text"}, seen=seen)
+ transport=_transport(
+ pages,
+ {"/notes.md": "text", "/report.pdf": "%PDF-1.4 not readable"},
+ seen=seen,
+ )
)
- assert [item.external_id for item in items] == ["/notes.md"]
- assert _downloaded_paths(seen) == ["/notes.md"]
+ assert [item.external_id for item in items] == ["/notes.md", "/report.pdf"]
+ assert _downloaded_paths(seen) == ["/notes.md", "/report.pdf"]
+ # The picture never moved a byte.
+ assert "/photo.jpg" not in _downloaded_paths(seen)
+
+
+async def test_a_word_document_is_imported_with_its_text():
+ """The point of the whole change: a container is not decoded as UTF-8 (that
+ produced a body of replacement characters, which is why these files were
+ excluded), it is handed to the extractor."""
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ archive.writestr(
+ "word/document.xml",
+ "<w:document xmlns:w='x'><w:body><w:p><w:r><w:t>"
+ "The quarterly ledger reconciliation"
+ "</w:t></w:r></w:p></w:body></w:document>",
+ )
+ docx = buffer.getvalue()
+ pages = [[_file("/ledger.docx", size=len(docx))]]
+ items = await _collect(transport=_transport(pages, {"/ledger.docx": docx}))
+ assert len(items) == 1
+ assert "The quarterly ledger reconciliation" in items[0].body
+ assert not items[0].metadata.get("content_missing")
+
+
+async def test_a_document_with_no_readable_text_is_still_imported():
+ """A scanned PDF is still a document that exists. It stays findable by
+ name, folder and date, and says plainly what is missing."""
+ pages = [[_file("/scan.pdf", size=40)]]
+ items = await _collect(
+ transport=_transport(pages, {"/scan.pdf": b"%PDF-1.4\nno text\n%%EOF"})
+ )
+ assert len(items) == 1
+ assert items[0].metadata["content_missing"] is True
+ assert "no text imported" in items[0].body
async def test_folders_deleted_and_non_downloadable_entries_are_ignored():
@@ -217,7 +267,12 @@ async def test_a_numeric_cursor_skips_unchanged_files_before_download():
assert _downloaded_paths(seen) == ["/new.md"]
-async def test_oversized_files_are_skipped_and_long_bodies_truncated():
+async def test_oversized_files_say_so_instead_of_vanishing():
+ """A file above the ceiling is not downloaded — but it IS recorded.
+
+ Dropping it silently makes "too big to read" look exactly like "never
+ existed", and only one of those two is the truth.
+ """
seen: list[httpx.Request] = []
pages = [
[
@@ -227,10 +282,12 @@ async def test_oversized_files_are_skipped_and_long_bodies_truncated():
]
contents = {"/long.md": "x" * (dbx._MAX_BODY_BYTES + 100_000)}
items = await _collect(transport=_transport(pages, contents, seen=seen))
- assert [item.external_id for item in items] == ["/long.md"]
- # The oversized file never cost a download.
+ assert [item.external_id for item in items] == ["/huge.md", "/long.md"]
+ # The oversized file still never cost a download.
assert _downloaded_paths(seen) == ["/long.md"]
- body = items[0].body
+ assert items[0].metadata["content_missing"] is True
+ assert "import limit" in items[0].metadata["content_missing_reason"]
+ body = items[1].body
assert body.endswith(dbx._TRUNCATION_MARKER)
assert len(body) == dbx._MAX_BODY_BYTES + len(dbx._TRUNCATION_MARKER)
diff --git a/tests/unit/ultrawiki/adapters/test_google_drive.py b/tests/unit/ultrawiki/adapters/test_google_drive.py
index 15f75aa024..a0648a3980 100644
--- a/tests/unit/ultrawiki/adapters/test_google_drive.py
+++ b/tests/unit/ultrawiki/adapters/test_google_drive.py
@@ -2,14 +2,17 @@
What makes this reader trustworthy rather than merely functional: Google-native
documents exported to text, text-shaped files downloaded with a source-side
-byte bound, binaries skipped honestly instead of swallowed, a deterministic
-oldest-modified-first walk so the checkpoint convention holds, per-file
-degradation instead of all-or-nothing failure, and refusals that never carry
-the token.
+byte bound, uploaded documents (PDF, Word, …) read through the shared
+extractor rather than thrown away, true blobs skipped honestly instead of
+swallowed, a deterministic oldest-modified-first walk so the checkpoint
+convention holds, per-file degradation instead of all-or-nothing failure, and
+refusals that never carry the token.
"""
from __future__ import annotations
+import io
+import zipfile
from datetime import UTC, datetime
from typing import Any
@@ -49,6 +52,26 @@ def _ctx() -> ConnectorContext:
_DOC = "application/vnd.google-apps.document"
_SHEET = "application/vnd.google-apps.spreadsheet"
_FOLDER = "application/vnd.google-apps.folder"
+_DOCX_MIME = (
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+)
+
+#: The inside of a Word file: paragraphs of runs of text.
+_WORD_XML = (
+ "<w:document xmlns:w='x'><w:body>"
+ "<w:p><w:r><w:t>The parties agree as follows.</w:t></w:r></w:p>"
+ "<w:p><w:r><w:t>Payment is due within 30 days.</w:t></w:r></w:p>"
+ "</w:body></w:document>"
+)
+
+
+def _zip(members: dict[str, str | bytes]) -> bytes:
+ """A real office archive, built in memory — the shape a Drive download has."""
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ for name, payload in members.items():
+ archive.writestr(name, payload)
+ return buffer.getvalue()
def _file(
@@ -84,9 +107,14 @@ def _transport(
contents: dict[str, str] | None = None,
export_status: dict[str, int] | None = None,
download_status: dict[str, int] | None = None,
+ blobs: dict[str, bytes] | None = None,
seen: list[httpx.Request] | None = None,
) -> httpx.MockTransport:
- """A fake Drive API: a paged listing plus per-file export/download."""
+ """A fake Drive API: a paged listing plus per-file export/download.
+
+ ``blobs`` serves the binary documents (a real PDF, a real DOCX) that only
+ exist as bytes — the shape a Range-bounded text download cannot represent.
+ """
def handler(request: httpx.Request) -> httpx.Response:
if seen is not None:
@@ -110,6 +138,8 @@ def _transport(
status = (download_status or {}).get(file_id, 200)
if status not in (200, 206):
return httpx.Response(status)
+ if blobs and file_id in blobs:
+ return httpx.Response(status, content=blobs[file_id])
return httpx.Response(status, text=(contents or {}).get(file_id, ""))
return httpx.Response(404)
@@ -165,26 +195,107 @@ async def test_a_spreadsheet_exports_as_csv_and_a_text_file_downloads_bounded():
assert download_call.headers.get("Range") == f"bytes=0-{g.BODY_CAP - 1}"
-async def test_binaries_folders_and_shortcuts_are_skipped_honestly():
+async def test_blobs_folders_and_shortcuts_are_skipped_honestly():
+ """Only what genuinely has no text inside is skipped.
+
+ A picture, a video and a plain archive have nothing to read; a folder is
+ structure. These cost NOTHING — the walk must not even request them.
+ """
listing = [
[
_file("f1", "photo.png", "image/png"),
_file("f2", "archive.zip", "application/zip"),
_file("f3", "Projects", _FOLDER),
- _file("f4", "scan.pdf", "application/pdf"),
- _file("f5", "notes.txt", "text/plain"),
+ _file("f4", "notes.txt", "text/plain"),
]
]
seen: list[httpx.Request] = []
items = await _collect(
- _transport(listing=listing, contents={"f5": "readable"}, seen=seen)
+ _transport(listing=listing, contents={"f4": "readable"}, seen=seen)
)
- # Only the text file becomes an item; nothing binary was even requested.
- assert [item.external_id for item in items] == ["f5"]
+ assert [item.external_id for item in items] == ["f4"]
fetched = {
r.url.path.rsplit("/", 1)[1] for r in seen if r.url.params.get("alt") == "media"
}
- assert fetched == {"f5"}
+ assert fetched == {"f4"}
+
+
+async def test_uploaded_documents_are_read_not_skipped():
+ """The regression this reader existed with: Drive exports only its OWN
+ formats, so every uploaded PDF, Word file and deck left as "no text form"
+ — the contract, the invoice, the deck someone mailed you. They are the
+ bulk of a real Drive, and they were the part that never arrived."""
+ docx = _zip({"word/document.xml": _WORD_XML})
+ listing = [
+ [
+ _file("f1", "Contract.docx", _DOCX_MIME, size=len(docx)),
+ _file("f2", "notes.txt", "text/plain"),
+ ]
+ ]
+ items = await _collect(
+ _transport(listing=listing, blobs={"f1": docx}, contents={"f2": "hello"})
+ )
+ assert [item.external_id for item in items] == ["f1", "f2"]
+ assert "The parties agree as follows." in items[0].body
+ assert not items[0].metadata.get("content_missing")
+
+
+async def test_a_document_is_recognised_by_its_name_when_the_type_lies():
+ """An upload's MIME is only as good as whatever produced it: scanners and
+ sync clients routinely say ``application/octet-stream``. Judging by type
+ alone threw the document away."""
+ docx = _zip({"word/document.xml": _WORD_XML})
+ mislabelled = _file("f1", "Contract.docx", "application/octet-stream", size=len(docx))
+ items = await _collect(_transport(listing=[[mislabelled]], blobs={"f1": docx}))
+ assert "The parties agree as follows." in items[0].body
+
+
+async def test_a_document_is_fetched_WHOLE_never_range_bounded():
+ """A container cannot be cut: half a ZIP has no central directory and half
+ a PDF has no cross-reference table. A Range header here would turn every
+ large document into a silently empty item."""
+ docx = _zip({"word/document.xml": _WORD_XML})
+ seen: list[httpx.Request] = []
+ await _collect(
+ _transport(
+ listing=[[_file("f1", "Contract.docx", _DOCX_MIME, size=len(docx))]],
+ blobs={"f1": docx},
+ seen=seen,
+ )
+ )
+ download = next(r for r in seen if r.url.params.get("alt") == "media")
+ assert "Range" not in download.headers
+
+
+async def test_a_document_with_no_readable_text_is_still_imported():
+ """A scanned PDF holds no text a parser can reach. Dropping it would make
+ the file invisible; importing it with the reason keeps it findable by
+ name, owner and date and says plainly what is missing."""
+ scan = b"%PDF-1.4\nnothing extractable here\n%%EOF"
+ items = await _collect(
+ _transport(
+ listing=[[_file("f1", "scan.pdf", "application/pdf", size=len(scan))]],
+ blobs={"f1": scan},
+ )
+ )
+ assert len(items) == 1
+ assert items[0].title == "scan.pdf"
+ assert items[0].metadata["content_missing"] is True
+ assert items[0].metadata["content_missing_reason"]
+ assert "no text imported" in items[0].body
+
+
+async def test_an_oversized_document_is_refused_with_a_sentence_not_fetched():
+ """Above the ceiling the file is refused rather than truncated — and the
+ refusal must happen BEFORE the download, or the ceiling protects nothing."""
+ huge = _file(
+ "f1", "archive.pdf", "application/pdf", size=gd.MAX_DOCUMENT_BYTES + 1
+ )
+ seen: list[httpx.Request] = []
+ items = await _collect(_transport(listing=[[huge]], seen=seen))
+ assert items[0].metadata["content_missing"] is True
+ assert "import limit" in items[0].metadata["content_missing_reason"]
+ assert not [r for r in seen if r.url.params.get("alt") == "media"]
async def test_listing_pages_are_walked_to_the_end():
@@ -269,7 +380,8 @@ async def test_a_failed_export_degrades_to_metadata_with_an_honest_note():
)
# One stubborn file must never sink the whole walk.
assert [item.external_id for item in items] == ["f1", "f2"]
- assert "[content could not be exported (HTTP 403)" in items[0].body
+ assert "the export failed (HTTP 403)" in items[0].body
+ assert items[0].metadata["content_missing"] is True
assert "still imported" in items[1].body