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): import the attachments, not just their names

Ruben Lütkebaaaa0992b3e
diff --git a/jarvis/ultrawiki/adapters/_google.py b/jarvis/ultrawiki/adapters/_google.py
index e4fbdc4783..0fef3699c0 100644
--- a/jarvis/ultrawiki/adapters/_google.py
+++ b/jarvis/ultrawiki/adapters/_google.py
@@ -37,6 +37,7 @@ __all__ = [
"cap_body",
"cursor_cutoff",
"decode_base64url",
+ "decode_base64url_bytes",
"google_get",
"google_get_json",
"google_token",
@@ -289,13 +290,22 @@ def strip_html(markup: str) -> str:
return _BLANK_RE.sub("\n\n", "\n".join(lines)).strip()
-def decode_base64url(data: str) -> str:
- """Gmail's base64url body data → text; empty string on junk, never a crash."""
+def decode_base64url_bytes(data: str) -> bytes:
+ """Gmail's base64url payload → raw bytes; empty on junk, never a crash.
+
+ Attachments must stop here rather than at :func:`decode_base64url`: a PDF
+ or a Word file decoded as UTF-8 comes out as replacement characters, and
+ what the extractor needs is the bytes exactly as they were sent.
+ """
if not data:
- return ""
+ return b""
padded = data + "=" * (-len(data) % 4)
try:
- raw = base64.urlsafe_b64decode(padded.encode("ascii"))
+ return base64.urlsafe_b64decode(padded.encode("ascii"))
except (ValueError, binascii.Error):
- return ""
- return raw.decode("utf-8", errors="replace")
+ return b""
+
+
+def decode_base64url(data: str) -> str:
+ """Gmail's base64url body data → text; empty string on junk, never a crash."""
+ return decode_base64url_bytes(data).decode("utf-8", errors="replace")
diff --git a/jarvis/ultrawiki/adapters/discord.py b/jarvis/ultrawiki/adapters/discord.py
index 5808edbb68..ff8278b9d8 100644
--- a/jarvis/ultrawiki/adapters/discord.py
+++ b/jarvis/ultrawiki/adapters/discord.py
@@ -36,10 +36,17 @@ import asyncio
import logging
from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
+from pathlib import PurePosixPath
from typing import Any
import httpx
+from jarvis.ultrawiki.extract import (
+ DOCUMENT_EXTENSIONS,
+ MAX_DOCUMENT_BYTES,
+ TEXT_EXTENSIONS,
+ extract_text,
+)
from jarvis.ultrawiki.types import ConnectorContext, RawItem
log = logging.getLogger(__name__)
@@ -406,11 +413,113 @@ def _message_text(message: dict[str, Any]) -> str:
continue
name = str(attachment.get("filename") or "").strip()
if name:
- # By name only — binaries never enter the knowledge base.
+ # By name in the transcript; a readable one is pulled separately
+ # into an item of its own, so the conversation stays a conversation.
parts.append(f"[attachment: {name}]")
return " ".join(parts)
+def _readable_attachments(message: dict[str, Any]) -> list[dict[str, Any]]:
+ """The attachments of one message whose text is worth fetching.
+
+ Filtered by name and type BEFORE any request: a meme-heavy channel must
+ not cost one download per image to import nothing (no OCR ships here).
+ """
+ found: list[dict[str, Any]] = []
+ for attachment in message.get("attachments") or []:
+ if not isinstance(attachment, dict) or not attachment.get("url"):
+ continue
+ name = str(attachment.get("filename") or "").strip()
+ suffix = PurePosixPath(name).suffix.lower()
+ mime = str(attachment.get("content_type") or "").lower()
+ if (
+ suffix in DOCUMENT_EXTENSIONS
+ or suffix in TEXT_EXTENSIONS
+ or mime.startswith("text/")
+ ):
+ found.append(attachment)
+ return found
+
+
+async def _attachment_item(
+ client: httpx.AsyncClient,
+ guild: dict[str, Any],
+ channel: dict[str, Any],
+ message: dict[str, Any],
+ attachment: dict[str, Any],
+) -> RawItem | None:
+ """One posted file as its own item, tied to the channel it was posted in."""
+ guild_id = str(guild.get("id") or "")
+ channel_id = str(channel.get("id") or "")
+ message_id = str(message.get("id") or "")
+ attachment_id = str(attachment.get("id") or "")
+ name = str(attachment.get("filename") or "").strip()
+ if not message_id or not attachment_id or not name:
+ return None
+
+ reason = ""
+ text = ""
+ try:
+ size = int(attachment.get("size") or 0)
+ except (TypeError, ValueError):
+ size = 0
+ if size > MAX_DOCUMENT_BYTES:
+ reason = (
+ f"the file is {size // (1024 * 1024)} MB, above the "
+ f"{MAX_DOCUMENT_BYTES // (1024 * 1024)} MB import limit"
+ )
+ else:
+ # The CDN link carries its own signature; sending the bot token to a
+ # host that is not the API would leak the credential for no gain.
+ try:
+ response = await client.get(
+ str(attachment.get("url") or ""), follow_redirects=True
+ )
+ except httpx.HTTPError:
+ reason = "the download could not be reached"
+ else:
+ if response.status_code >= 400:
+ reason = f"the download failed (HTTP {response.status_code})"
+ else:
+ result = extract_text(
+ response.content,
+ filename=name,
+ mime=str(attachment.get("content_type") or ""),
+ )
+ if result.ok:
+ text = result.text
+ else:
+ reason = result.reason or "no text could be read from this file"
+
+ guild_name = str(guild.get("name") or "").strip() or f"server {guild_id}"
+ channel_name = str(channel.get("name") or "").strip() or f"channel {channel_id}"
+ author = _author_of(message)
+ header = f"{guild_name} · #{channel_name} · file posted by {author} · {name}"
+ body = f"{header}\n\n{text or f'[no text imported: {reason}]'}"
+ return RawItem(
+ external_id=f"discord:{guild_id}:{channel_id}:{message_id}#att-{attachment_id}",
+ title=name,
+ body=body[:_MAX_BODY_CHARS],
+ permalink=(
+ f"https://discord.com/channels/{guild_id}/{channel_id}/{message_id}"
+ ),
+ timestamp_utc=_iso_z(str(message.get("timestamp") or "")),
+ thread_key=f"{guild_id}/{channel_id}",
+ author_raw=author,
+ metadata={
+ "mtime_ns": _to_ns(str(message.get("timestamp") or "")),
+ "guild_id": guild_id,
+ "channel_id": channel_id,
+ "guild_name": guild_name,
+ "channel_name": channel_name,
+ "kind": "attachment",
+ "filename": name,
+ "parent_message_id": message_id,
+ **({"content_missing": True, "content_missing_reason": reason} if reason else {}),
+ },
+ )
+
+
def _chunk_item(
guild: dict[str, Any],
channel: dict[str, Any],
@@ -542,6 +651,16 @@ async def discord_pull_adapter(
for item in _day_items(guild, channel, messages):
yielded += 1
yield item
+ # After the transcript, never instead of it: a dead CDN link
+ # must cost that one file and nothing else.
+ for message in messages:
+ for attachment in _readable_attachments(message):
+ item = await _attachment_item(
+ client, guild, channel, message, attachment
+ )
+ if item is not None:
+ yielded += 1
+ yield item
log.info(
"Discord adapter: yielded %d item(s) for %s (%s)",
diff --git a/jarvis/ultrawiki/adapters/google_mail.py b/jarvis/ultrawiki/adapters/google_mail.py
index 22b87c0107..3fd6da8b63 100644
--- a/jarvis/ultrawiki/adapters/google_mail.py
+++ b/jarvis/ultrawiki/adapters/google_mail.py
@@ -7,11 +7,16 @@ an interrupted backfill resumes strictly after the last imported message id.
Scope honesty — what the token allows vs. what is imported:
-- **Message text only.** The plain-text part is preferred; an HTML-only
- message is stripped to readable text; a message with neither decodable part
- falls back to the API's snippet. Attachments are binaries and are NEVER
- downloaded — each item states how many it left behind, so the record never
- implies the body is the whole message.
+- **Message text.** The plain-text part is preferred; an HTML-only message is
+ stripped to readable text; a message with neither decodable part falls back
+ to the API's snippet.
+- **Readable attachments become their own items**, one per file, linked to
+ the message by ``thread_key`` and named ``<message-id>#att-<n>``. This is
+ where the invoice, the contract and the signed offer actually live: mail
+ bodies say "see attached", and a memory that stops at the body knows only
+ that something was attached. Blobs (photos, signature images, video) are
+ still never fetched — no OCR ships here — and the message body names every
+ attachment it carries either way, so the record never implies completeness.
- **Spam and trash are excluded** (the API's default listing). A memory keeps
what the user kept.
- **Bodies are capped at ~1 MB** with a visible truncation marker.
@@ -32,11 +37,18 @@ 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,
+ TEXT_EXTENSIONS,
+ extract_text,
+)
from jarvis.ultrawiki.types import ConnectorContext, RawItem
log = logging.getLogger(__name__)
@@ -46,6 +58,7 @@ __all__ = [
"GoogleAdapterError",
"gmail_pull_adapter",
"item_from_message",
+ "items_from_attachments",
]
#: Re-exported so callers can catch the family's error type from this module.
@@ -65,6 +78,29 @@ _LIST_PAGE_SIZE = 500
#: Defensive bound on MIME-part recursion; real messages nest a handful deep.
_MAX_PART_DEPTH = 20
+#: Attachment types worth fetching that are neither ``text/*`` nor named by a
+#: known extension. Everything else with a name is a blob (photo, signature
+#: image, video) — no OCR ships here, so fetching one would cost a request per
+#: message to import nothing.
+_READABLE_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",
+ "application/json",
+ "application/xml",
+ }
+)
+
def _header(headers: list[Any], name: str) -> str:
wanted = name.lower()
@@ -101,6 +137,31 @@ def _attachment_count(part: Any, depth: int = 0) -> int:
return count
+def _attachment_parts(part: Any, found: list[dict[str, Any]], depth: int = 0) -> None:
+ """Every named part of the MIME tree, in the order the message carries it."""
+ if depth > _MAX_PART_DEPTH or not isinstance(part, dict):
+ return
+ if str(part.get("filename") or "").strip():
+ found.append(part)
+ for sub in part.get("parts") or []:
+ _attachment_parts(sub, found, depth + 1)
+
+
+def _is_readable_attachment(filename: str, mime: str) -> bool:
+ """Whether this attachment holds text worth fetching.
+
+ A document or a text file does; a photo, a video and a signature image do
+ not, and must not cost one request each just to be discarded. The name is
+ checked as well as the type because mail clients label attachments with
+ ``application/octet-stream`` more often than they label them correctly.
+ """
+ suffix = PurePosixPath(filename).suffix.lower()
+ if suffix in DOCUMENT_EXTENSIONS or suffix in TEXT_EXTENSIONS:
+ return True
+ lowered = mime.lower()
+ return lowered.startswith("text/") or lowered in _READABLE_MIMES
+
+
def _body_text(payload: dict[str, Any], snippet: str) -> str:
plain: list[str] = []
html_parts: list[str] = []
@@ -137,14 +198,17 @@ def item_from_message(message: dict[str, Any]) -> RawItem | None:
descriptor.append(f"to {recipient}")
header_line = "email" + (f" {' · '.join(descriptor)}" if descriptor else "")
body_text = _body_text(payload, str(message.get("snippet") or ""))
- attachments = _attachment_count(payload)
+ parts: list[dict[str, Any]] = []
+ _attachment_parts(payload, parts)
+ attachments = len(parts)
if attachments:
- # Binaries are never imported (memory-shaped scope); the record must
- # say what it does not contain instead of implying completeness.
- body_text += (
- f"\n\n[{attachments} attachment(s) not imported — "
- "open the link to download them]"
+ # NAMES, not a count. "3 attachments" is unsearchable; "Invoice
+ # 2026-03.pdf" is how a person actually looks for the thing, and the
+ # readable ones are imported as their own items beside this message.
+ names = ", ".join(
+ str(part.get("filename") or "(unnamed)").strip() for part in parts
)
+ body_text += f"\n\nAttachments: {names}"
body, truncated = g.cap_body(f"{header_line}\n\n{body_text}".strip())
return RawItem(
@@ -168,6 +232,150 @@ def item_from_message(message: dict[str, Any]) -> RawItem | None:
)
+def _attachment_item(
+ message: dict[str, Any],
+ index: int,
+ filename: str,
+ text: str,
+ *,
+ content_missing_reason: str = "",
+) -> RawItem:
+ """One attachment as a child of its message.
+
+ It carries the message's ``thread_key`` and time, so the file and the
+ conversation it arrived in stay one story: a question about the offer
+ finds the PDF, and the PDF still knows who sent it and when.
+ """
+ message_id = str(message.get("id") or "")
+ headers = (message.get("payload") or {}).get("headers") or []
+ sender = _header(headers, "From")
+ subject = _header(headers, "Subject")
+ descriptor = f"attachment · {filename}"
+ if subject:
+ descriptor += f" · from the email “{subject}”"
+ if sender:
+ descriptor += f" · sent by {sender}"
+ content = text or f"[no text imported: {content_missing_reason}]"
+ body, truncated = g.cap_body(f"{descriptor}\n\n{content}".strip())
+ return RawItem(
+ external_id=f"{message_id}#att-{index}",
+ title=filename,
+ body=body,
+ permalink=f"https://mail.google.com/mail/u/0/#all/{message_id}",
+ timestamp_utc=g.iso_utc_from_ms(message.get("internalDate")),
+ thread_key=str(message.get("threadId") or "") or message_id,
+ author_raw=sender,
+ metadata={
+ "mtime_ns": g.ms_to_ns(message.get("internalDate")),
+ "parent_external_id": message_id,
+ "attachment_filename": filename,
+ "truncated": truncated,
+ **(
+ {
+ "content_missing": True,
+ "content_missing_reason": content_missing_reason,
+ }
+ if content_missing_reason
+ else {}
+ ),
+ },
+ )
+
+
+async def items_from_attachments(
+ client: httpx.AsyncClient, token: str, message: dict[str, Any]
+) -> list[RawItem]:
+ """Every readable attachment of one message, as child items.
+
+ A blob costs nothing: it is filtered by name and type BEFORE any request.
+ A fetch or parse that fails still yields an item saying why — an invoice
+ that silently disappears is indistinguishable from an invoice that was
+ never sent.
+ """
+ parts: list[dict[str, Any]] = []
+ _attachment_parts(message.get("payload") or {}, parts)
+ message_id = str(message.get("id") or "")
+ items: list[RawItem] = []
+
+ for index, part in enumerate(parts, start=1):
+ filename = str(part.get("filename") or "").strip()
+ mime = str(part.get("mimeType") or "")
+ if not _is_readable_attachment(filename, mime):
+ continue
+ body_meta = part.get("body") or {}
+ attachment_id = str(body_meta.get("attachmentId") or "")
+ try:
+ size = int(body_meta.get("size") or 0)
+ except (TypeError, ValueError):
+ size = 0
+ if size > MAX_DOCUMENT_BYTES:
+ items.append(
+ _attachment_item(
+ message,
+ index,
+ filename,
+ "",
+ content_missing_reason=(
+ f"the attachment is {size // (1024 * 1024)} MB, above "
+ f"the {MAX_DOCUMENT_BYTES // (1024 * 1024)} MB import "
+ "limit"
+ ),
+ )
+ )
+ continue
+
+ # A small part arrives inline with the message; only a large one needs
+ # its own request. Reading the inline copy first saves a round trip
+ # per attachment on exactly the mail a mailbox has most of.
+ data = str(body_meta.get("data") or "")
+ if not data and attachment_id:
+ # Tolerated per attachment: one file deleted between listing and
+ # fetch, or one the scope cannot reach, must never sink the sync.
+ # Credential and rate-limit failures still raise — they are about
+ # the whole run, not this file.
+ response = await g.google_get(
+ client,
+ f"{_API}/messages/{message_id}/attachments/{attachment_id}",
+ token,
+ _PRODUCT,
+ tolerate=(403, 404),
+ )
+ if response.status_code < 400:
+ try:
+ payload = response.json() or {}
+ except ValueError:
+ payload = {}
+ data = str(payload.get("data") or "")
+ if not data:
+ items.append(
+ _attachment_item(
+ message,
+ index,
+ filename,
+ "",
+ content_missing_reason="the attachment could not be fetched",
+ )
+ )
+ continue
+
+ raw = g.decode_base64url_bytes(data)
+ result = extract_text(raw, filename=filename, mime=mime)
+ items.append(
+ _attachment_item(
+ message,
+ index,
+ filename,
+ result.text if result.ok else "",
+ content_missing_reason=(
+ ""
+ if result.ok
+ else (result.reason or "no text could be read from this file")
+ ),
+ )
+ )
+ return items
+
+
async def _all_message_ids(
client: httpx.AsyncClient, token: str, query: str
) -> list[str]:
@@ -220,6 +428,7 @@ async def gmail_pull_adapter(
query = f"after:{int(cutoff.timestamp())}" if cutoff else ""
resume_after = checkpoint if (checkpoint and cutoff is None) else None
yielded = 0
+ attachments = 0
async with httpx.AsyncClient(timeout=g.TIMEOUT, transport=transport) as client:
ids = await _all_message_ids(client, token, query)
@@ -244,10 +453,17 @@ async def gmail_pull_adapter(
if item is not None:
yielded += 1
yield item
+ # After the message, never instead of it: a failure while reading
+ # an attachment must not cost the mail it belongs to.
+ for child in await items_from_attachments(client, token, payload):
+ attachments += 1
+ yielded += 1
+ yield child
log.info(
- "Gmail adapter: yielded %d item(s) for %s (%s)",
+ "Gmail adapter: yielded %d item(s) for %s (%s), %d of them attachments",
yielded,
ctx.source_id,
"incremental" if cutoff else "backfill",
+ attachments,
)
diff --git a/jarvis/ultrawiki/adapters/slack.py b/jarvis/ultrawiki/adapters/slack.py
index 7d6e8344c0..e455d31dea 100644
--- a/jarvis/ultrawiki/adapters/slack.py
+++ b/jarvis/ultrawiki/adapters/slack.py
@@ -59,10 +59,17 @@ import logging
import re
from collections.abc import AsyncIterator
from datetime import UTC, datetime
+from pathlib import PurePosixPath
from typing import Any
import httpx
+from jarvis.ultrawiki.extract import (
+ DOCUMENT_EXTENSIONS,
+ MAX_DOCUMENT_BYTES,
+ TEXT_EXTENSIONS,
+ extract_text,
+)
from jarvis.ultrawiki.types import ConnectorContext, RawItem
log = logging.getLogger(__name__)
@@ -465,11 +472,126 @@ def _author_of(message: dict[str, Any], names: dict[str, str]) -> str:
return str(message.get("username") or profile.get("name") or "app")
+def _file_name(file_info: dict[str, Any]) -> str:
+ """What a person would call this upload."""
+ return str(
+ file_info.get("name") or file_info.get("title") or "attachment"
+ ).strip()
+
+
+def _readable_files(message: dict[str, Any]) -> list[dict[str, Any]]:
+ """The uploads in one message whose text is worth fetching.
+
+ A picture or a video is filtered out here, before any request: no OCR
+ ships in this adapter, so downloading one would cost a request per
+ message and import nothing.
+ """
+ found: list[dict[str, Any]] = []
+ for file_info in message.get("files") or []:
+ if not isinstance(file_info, dict):
+ continue
+ if not str(file_info.get("url_private_download") or "").strip():
+ continue
+ name = _file_name(file_info)
+ suffix = PurePosixPath(name).suffix.lower()
+ mime = str(file_info.get("mimetype") or "").lower()
+ if (
+ suffix in DOCUMENT_EXTENSIONS
+ or suffix in TEXT_EXTENSIONS
+ or mime.startswith("text/")
+ ):
+ found.append(file_info)
+ return found
+
+
+async def _file_item(
+ client: httpx.AsyncClient,
+ token: str,
+ channel_id: str,
+ label: str,
+ message: dict[str, Any],
+ file_info: dict[str, Any],
+ names: dict[str, str],
+ team_url: str,
+) -> RawItem | None:
+ """One shared file as its own item, tied to the message that shared it.
+
+ Shared documents are where a channel's actual decisions live: the deck,
+ the spec, the spreadsheet. Recording only that "a file was shared" makes
+ the memory able to say a document exists and nothing about what it says.
+ """
+ name = _file_name(file_info)
+ file_id = str(file_info.get("id") or "").strip()
+ ts = str(message.get("ts") or "")
+ if not file_id or not ts:
+ return None
+
+ reason = ""
+ text = ""
+ try:
+ size = int(file_info.get("size") or 0)
+ except (TypeError, ValueError):
+ size = 0
+ if size > MAX_DOCUMENT_BYTES:
+ reason = (
+ f"the file is {size // (1024 * 1024)} MB, above the "
+ f"{MAX_DOCUMENT_BYTES // (1024 * 1024)} MB import limit"
+ )
+ else:
+ url = str(file_info.get("url_private_download") or "")
+ try:
+ response = await client.get(
+ url, headers=_headers(token), follow_redirects=True
+ )
+ except httpx.HTTPError:
+ # One unreachable upload is not the sync's problem to die of.
+ reason = "the download could not be reached"
+ else:
+ if response.status_code >= 400:
+ reason = f"the download failed (HTTP {response.status_code})"
+ else:
+ result = extract_text(
+ response.content,
+ filename=name,
+ mime=str(file_info.get("mimetype") or ""),
+ )
+ if result.ok:
+ text = result.text
+ else:
+ reason = result.reason or "no text could be read from this file"
+
+ author = _author_of(message, names)
+ header = f"{label} · file shared by {author} · {name}"
+ body = _cap_body(
+ "\n\n".join([header, text or f"[no text imported: {reason}]"]).strip()
+ )
+ return RawItem(
+ external_id=f"{channel_id}:{ts}#file-{file_id}",
+ title=name,
+ body=body,
+ permalink=str(file_info.get("permalink") or "")
+ or _permalink(team_url, channel_id, ts),
+ timestamp_utc=_ts_to_iso(ts),
+ thread_key=channel_id,
+ author_raw=author,
+ metadata={
+ "mtime_ns": _to_ns(ts),
+ "channel": channel_id,
+ "channel_label": label,
+ "kind": "file",
+ "file_id": file_id,
+ "filename": name,
+ **({"content_missing": True, "content_missing_reason": reason} if reason else {}),
+ },
+ )
+
+
def _line(message: dict[str, Any], names: dict[str, str]) -> str:
"""One ``author: text`` line; empty when the message carries no words.
- Files become ``[file: <name>]`` markers — the name is memory, the bytes
- are not (and never will be pulled).
+ Files become ``[file: <name>]`` markers in the conversation. The bytes of
+ a readable one are pulled separately, into an item of its own, so the
+ transcript stays a transcript.
"""
parts: list[str] = []
text = _clean_text(str(message.get("text") or ""), names)
@@ -612,6 +734,7 @@ async def _conversation_items(
by_day.setdefault(day, []).append(message)
items: list[RawItem] = []
+ shared: list[tuple[dict[str, Any], dict[str, Any]]] = []
for thread_ts in sorted(thread_parents, key=float):
messages = await _thread_messages(client, token, channel_id, thread_ts)
if not messages:
@@ -620,10 +743,28 @@ async def _conversation_items(
item = _thread_item(channel_id, label, messages, names, team_url)
if item is not None:
items.append(item)
+ shared.extend(
+ (message, file_info)
+ for message in messages
+ for file_info in _readable_files(message)
+ )
for day in sorted(by_day):
day_item = _day_item(channel_id, label, day, by_day[day], names, team_url)
if day_item is not None:
items.append(day_item)
+ shared.extend(
+ (message, file_info)
+ for message in by_day[day]
+ for file_info in _readable_files(message)
+ )
+ # Downloads happen after the conversation is assembled, so a slow or dead
+ # file server delays the uploads only — never the transcript itself.
+ for message, file_info in shared:
+ file_item = await _file_item(
+ client, token, channel_id, label, message, file_info, names, team_url
+ )
+ if file_item is not None:
+ items.append(file_item)
items.sort(key=lambda item: (item.timestamp_utc, item.external_id))
return items
diff --git a/tests/unit/ultrawiki/adapters/test_discord.py b/tests/unit/ultrawiki/adapters/test_discord.py
index da7d4d0766..45579ae8e0 100644
--- a/tests/unit/ultrawiki/adapters/test_discord.py
+++ b/tests/unit/ultrawiki/adapters/test_discord.py
@@ -79,6 +79,7 @@ def _transport(
guilds: list[dict[str, Any]] | None = None,
guild_channels: list[dict[str, Any]] | None = None,
forbidden: set[str] = frozenset(),
+ uploads: dict[str, bytes] | None = None,
seen: list[httpx.Request] | None = None,
ratelimit_first: int = 0,
) -> httpx.MockTransport:
@@ -89,6 +90,11 @@ def _transport(
if seen is not None:
seen.append(request)
path = request.url.path
+ if request.url.host == "cdn.discordapp.com":
+ raw = (uploads or {}).get(path.rsplit("/", 1)[1])
+ if raw is None:
+ return httpx.Response(404)
+ return httpx.Response(200, content=raw)
if path == "/api/v10/users/@me/guilds":
if request.url.params.get("after"):
return httpx.Response(200, json=[])
@@ -305,6 +311,55 @@ async def test_an_unconnected_plugin_refuses_before_any_request(monkeypatch):
await _collect(transport=_transport({}))
+def _attachment(
+ attachment_id: str, filename: str, content_type: str, size: int = 400
+) -> dict[str, Any]:
+ return {
+ "id": attachment_id,
+ "filename": filename,
+ "content_type": content_type,
+ "size": size,
+ "url": f"https://cdn.discordapp.com/attachments/{attachment_id}",
+ }
+
+
+async def test_a_posted_document_becomes_its_own_item():
+ """A posted spec is the substance of the conversation around it."""
+ message = _message("2026-03-01T10:00:00Z", "here is the spec")
+ message["attachments"] = [_attachment("A1", "spec.md", "text/markdown")]
+ items = await _collect(
+ transport=_transport(
+ {"222": [message]},
+ uploads={"A1": b"# Spec\n\nThe importer reads everything."},
+ )
+ )
+ files = [item for item in items if item.metadata.get("kind") == "attachment"]
+ assert len(files) == 1
+ assert "The importer reads everything." in files[0].body
+ assert files[0].external_id.endswith("#att-A1")
+ # The transcript still names it.
+ assert "[attachment: spec.md]" in items[0].body
+
+
+async def test_a_posted_image_is_never_downloaded():
+ """A meme-heavy channel must not cost one download per picture."""
+ message = _message("2026-03-01T10:00:00Z", "look")
+ message["attachments"] = [_attachment("A2", "cat.png", "image/png")]
+ seen: list[httpx.Request] = []
+ items = await _collect(transport=_transport({"222": [message]}, seen=seen))
+ assert not [item for item in items if item.metadata.get("kind") == "attachment"]
+ assert all(request.url.host != "cdn.discordapp.com" for request in seen)
+
+
+async def test_a_dead_link_costs_that_file_only():
+ message = _message("2026-03-01T10:00:00Z", "attached")
+ message["attachments"] = [_attachment("A3", "notes.md", "text/markdown")]
+ items = await _collect(transport=_transport({"222": [message]}, uploads={}))
+ # The day chunk survived; the file says why it is empty.
+ assert len(items) == 2
+ assert items[1].metadata["content_missing"] is True
+
+
def test_the_integration_id_matches_the_curated_roster():
from jarvis.ultrawiki import connector_catalog
from jarvis.ultrawiki.connectors import plugin_bridge
diff --git a/tests/unit/ultrawiki/adapters/test_google_mail.py b/tests/unit/ultrawiki/adapters/test_google_mail.py
index 7441344e41..07793bd306 100644
--- a/tests/unit/ultrawiki/adapters/test_google_mail.py
+++ b/tests/unit/ultrawiki/adapters/test_google_mail.py
@@ -10,6 +10,8 @@ downloaded, and failure messages a user can act on that never carry the token.
from __future__ import annotations
import base64
+import io
+import zipfile
from datetime import UTC, datetime
from typing import Any
@@ -109,14 +111,31 @@ def _transport(
*,
listing: list[list[dict[str, Any]]],
messages: dict[str, dict[str, Any]],
+ attachments: dict[str, bytes] | None = None,
seen: list[httpx.Request] | None = None,
) -> httpx.MockTransport:
- """A fake Gmail: a paged newest-first id listing plus per-id full fetches."""
+ """A fake Gmail: a paged newest-first id listing plus per-id full fetches.
+
+ ``attachments`` maps an attachment id to its RAW bytes; an id that is
+ absent answers 404, which is the "deleted between listing and fetch" case
+ every walk has to survive.
+ """
def handler(request: httpx.Request) -> httpx.Response:
if seen is not None:
seen.append(request)
path = request.url.path
+ if "/attachments/" in path:
+ raw = (attachments or {}).get(path.rsplit("/", 1)[1])
+ if raw is None:
+ return httpx.Response(404)
+ return httpx.Response(
+ 200,
+ json={
+ "data": base64.urlsafe_b64encode(raw).decode().rstrip("="),
+ "size": len(raw),
+ },
+ )
if path == "/gmail/v1/users/me/messages":
index = int(request.url.params.get("pageToken") or 0)
page = listing[index] if index < len(listing) else []
@@ -201,17 +220,79 @@ async def test_a_message_with_no_decodable_part_falls_back_to_the_snippet():
assert "the short preview" in items[0].body
-async def test_attachments_are_counted_never_downloaded():
+def _docx(text: str) -> bytes:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ archive.writestr(
+ "word/document.xml",
+ f"<w:document xmlns:w='x'><w:body><w:p><w:r><w:t>{text}"
+ "</w:t></w:r></w:p></w:body></w:document>",
+ )
+ return buffer.getvalue()
+
+
+async def test_the_message_names_its_attachments():
+ """A count is unsearchable. The name is how a person looks for the thing."""
message = _message("m1", "2026-03-01T10:00:00", attachments=2)
+ items = await _collect(
+ _transport(
+ listing=[[message]],
+ messages={"m1": message},
+ attachments={"att-0": _docx("first"), "att-1": _docx("second")},
+ )
+ )
+ assert "Attachments: report-0.pdf, report-1.pdf" in items[0].body
+ assert items[0].metadata["attachments"] == 2
+
+
+async def test_a_readable_attachment_becomes_its_own_item():
+ """Where the invoice actually lives. A mail body says "see attached", so a
+ memory that stops at the body knows only that something was attached."""
+ message = _message("m1", "2026-03-01T10:00:00", attachments=1)
+ message["payload"]["parts"][-1]["filename"] = "Invoice 2026-03.docx"
+ items = await _collect(
+ _transport(
+ listing=[[message]],
+ messages={"m1": message},
+ attachments={"att-0": _docx("Amount due: 1200 EUR")},
+ )
+ )
+ assert [item.external_id for item in items] == ["m1", "m1#att-1"]
+ child = items[1]
+ assert child.title == "Invoice 2026-03.docx"
+ assert "Amount due: 1200 EUR" in child.body
+ # It stays attached to the conversation it arrived in.
+ assert child.thread_key == items[0].thread_key
+ assert child.timestamp_utc == items[0].timestamp_utc
+ assert child.metadata["parent_external_id"] == "m1"
+
+
+async def test_a_photo_attachment_never_costs_a_request():
+ """No OCR ships here, so fetching an image would spend a request per
+ message to import nothing."""
+ message = _message("m1", "2026-03-01T10:00:00", attachments=1)
+ part = message["payload"]["parts"][-1]
+ part["filename"] = "signature.png"
+ part["mimeType"] = "image/png"
seen: list[httpx.Request] = []
items = await _collect(
_transport(listing=[[message]], messages={"m1": message}, seen=seen)
)
- body = items[0].body
- assert "[2 attachment(s) not imported" in body
- assert items[0].metadata["attachments"] == 2
- # No request beyond the listing and the message fetch: binaries never move.
- assert all("attachment" not in request.url.path for request in seen)
+ assert [item.external_id for item in items] == ["m1"]
+ assert all("/attachments/" not in request.url.path for request in seen)
+ # It is still NAMED in the message, so nothing is hidden.
+ assert "signature.png" in items[0].body
+
+
+async def test_an_attachment_that_cannot_be_fetched_does_not_sink_the_sync():
+ """One file deleted between listing and fetch must cost that file only —
+ and it still becomes an item saying so."""
+ message = _message("m1", "2026-03-01T10:00:00", attachments=1)
+ items = await _collect(
+ _transport(listing=[[message]], messages={"m1": message}, attachments={})
+ )
+ assert [item.external_id for item in items] == ["m1", "m1#att-1"]
+ assert items[1].metadata["content_missing"] is True
async def test_listing_pages_are_walked_to_the_end():
diff --git a/tests/unit/ultrawiki/adapters/test_slack.py b/tests/unit/ultrawiki/adapters/test_slack.py
index e9ae98698d..6cf7618adc 100644
--- a/tests/unit/ultrawiki/adapters/test_slack.py
+++ b/tests/unit/ultrawiki/adapters/test_slack.py
@@ -9,7 +9,9 @@ failure messages a user can act on that never carry the token.
from __future__ import annotations
+import io
import json
+import zipfile
from datetime import UTC, datetime
from typing import Any
@@ -19,6 +21,10 @@ import pytest
from jarvis.ultrawiki.adapters import slack as sl
from jarvis.ultrawiki.types import ConnectorContext
+_DOCX_MIME = (
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+)
+
@pytest.fixture(autouse=True)
def marketplace_token(monkeypatch):
@@ -86,6 +92,7 @@ def _transport(
missing_scope_types: frozenset[str] = frozenset(),
history_errors: dict[str, str] | None = None,
rate_limit_first_history: int = 0,
+ uploads: dict[str, bytes] | None = None,
seen: list[httpx.Request] | None = None,
) -> httpx.MockTransport:
"""A fake Slack workspace: dispatches by Web API method path."""
@@ -127,6 +134,11 @@ def _transport(
if path == "/api/conversations.replies":
key = (params.get("channel") or "", params.get("ts") or "")
return _json({"ok": True, "messages": (replies or {}).get(key, [])})
+ if path.startswith("/files/"):
+ raw = (uploads or {}).get(path.rsplit("/", 1)[1])
+ if raw is None:
+ return httpx.Response(404)
+ return httpx.Response(200, content=raw)
return _json({"ok": False, "error": "unknown_method"})
return httpx.MockTransport(handler)
@@ -385,6 +397,84 @@ async def test_a_dm_is_labelled_as_a_conversation_with_its_person():
assert items[0].thread_key == "D1"
+def _docx(text: str) -> bytes:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ archive.writestr(
+ "word/document.xml",
+ f"<w:document xmlns:w='x'><w:body><w:p><w:r><w:t>{text}"
+ "</w:t></w:r></w:p></w:body></w:document>",
+ )
+ return buffer.getvalue()
+
+
+def _upload(file_id: str, name: str, mimetype: str, size: int = 500) -> dict[str, Any]:
+ return {
+ "id": file_id,
+ "name": name,
+ "title": name,
+ "mimetype": mimetype,
+ "size": size,
+ "url_private_download": f"https://files.slack.com/files/{file_id}",
+ "permalink": f"https://acme.slack.com/files/{file_id}",
+ }
+
+
+async def test_a_shared_document_becomes_its_own_item():
+ """Shared files are where a channel's decisions live — the deck, the spec.
+ Recording only that "a file was shared" leaves the memory able to say a
+ document exists and nothing about what it says."""
+ upload = _upload("F1", "Roadmap.docx", _DOCX_MIME)
+ message = _msg("2026-03-01T10:00:00", text="here you go", files=[upload])
+ items = await _collect(
+ _transport(
+ channels={"public_channel": [_channel()]},
+ history={"C1": [[message]]},
+ uploads={"F1": _docx("Ship the importer in April")},
+ )
+ )
+ file_items = [item for item in items if item.metadata.get("kind") == "file"]
+ assert len(file_items) == 1
+ assert file_items[0].external_id.endswith("#file-F1")
+ assert "Ship the importer in April" in file_items[0].body
+ assert file_items[0].thread_key == "C1"
+ # The transcript still mentions it, so the conversation stays readable.
+ day = next(item for item in items if item.metadata.get("kind") == "day")
+ assert "[file: Roadmap.docx]" in day.body
+
+
+async def test_a_shared_photo_is_never_downloaded():
+ """No OCR ships here; one request per image would buy nothing."""
+ upload = _upload("F2", "team.png", "image/png")
+ message = _msg("2026-03-01T10:00:00", text="look", files=[upload])
+ seen: list[httpx.Request] = []
+ items = await _collect(
+ _transport(
+ channels={"public_channel": [_channel()]},
+ history={"C1": [[message]]},
+ seen=seen,
+ )
+ )
+ assert not [item for item in items if item.metadata.get("kind") == "file"]
+ assert all("/files/" not in request.url.path for request in seen)
+
+
+async def test_an_unreachable_upload_does_not_sink_the_conversation():
+ """The transcript must survive a dead file server; the file says why."""
+ upload = _upload("F3", "notes.docx", _DOCX_MIME)
+ message = _msg("2026-03-01T10:00:00", text="attached", files=[upload])
+ items = await _collect(
+ _transport(
+ channels={"public_channel": [_channel()]},
+ history={"C1": [[message]]},
+ uploads={},
+ )
+ )
+ assert any(item.metadata.get("kind") == "day" for item in items)
+ file_item = next(item for item in items if item.metadata.get("kind") == "file")
+ assert file_item.metadata["content_missing"] is True
+
+
def test_the_integration_id_matches_the_catalog_and_the_bridge():
from jarvis.ultrawiki import connector_catalog
from jarvis.ultrawiki.connectors import plugin_bridge