Skip to content

Self-hosted AI workspace.

Python

merge: reconcile PR 40 with current lab

Alexandre Teixeiraf74a262f731a
diff --cc ACKNOWLEDGMENTS.md
index 46a347d45,46a347d45..61aaad287
--- a/ACKNOWLEDGMENTS.md
+++ b/ACKNOWLEDGMENTS.md
@@@ -47,7 -47,7 +47,7 @@@ just composed
| Service | Image | Purpose | License |
|---|---|---|---|
--| [SearXNG](https://github.com/searxng/searxng) | `searxng/searxng:2026.5.31-7159b8aed` (pinned tag; see compose) | Default metasearch backend | AGPL-3.0 |
++| [SearXNG](https://github.com/searxng/searxng) | `searxng/searxng:2026.9.25-12f8b6515` (pinned tag; see compose) | Default metasearch backend | AGPL-3.0 |
| [ChromaDB](https://github.com/chroma-core/chroma) | `chromadb/chroma:latest` | Vector store for memory / RAG | Apache-2.0 |
| [ntfy](https://github.com/binwiederhier/ntfy) | `binwiederhier/ntfy` | Push notifications (self-hosted reminders) | Apache-2.0 / GPL-2.0 |
diff --cc docker-compose.gpu-amd.yml
index ce7e2d96d,ce7e2d96d..a2e86eda6
--- a/docker-compose.gpu-amd.yml
+++ b/docker-compose.gpu-amd.yml
@@@ -133,7 -133,7 +133,7 @@@ services
# tag blocks the whole app from starting. 2026.6.2 crashes on boot with
# `KeyError: 'default_doi_resolver'`, failing the healthcheck (issue #1414).
# Bump this deliberately after verifying a newer tag boots clean.
-- image: docker.io/searxng/searxng:2026.5.31-7159b8aed
++ image: docker.io/searxng/searxng:2026.9.25-12f8b6515@sha256:5286edb35782454ab8a102c5eff6b54bff745853191b46aeead95f225aa6dfb6
entrypoint:
- /bin/sh
- -c
diff --cc docker-compose.gpu-nvidia.yml
index 08a9638b4,08a9638b4..2578c6644
--- a/docker-compose.gpu-nvidia.yml
+++ b/docker-compose.gpu-nvidia.yml
@@@ -136,7 -136,7 +136,7 @@@ services
# tag blocks the whole app from starting. 2026.6.2 crashes on boot with
# `KeyError: 'default_doi_resolver'`, failing the healthcheck (issue #1414).
# Bump this deliberately after verifying a newer tag boots clean.
-- image: docker.io/searxng/searxng:2026.5.31-7159b8aed
++ image: docker.io/searxng/searxng:2026.9.25-12f8b6515@sha256:5286edb35782454ab8a102c5eff6b54bff745853191b46aeead95f225aa6dfb6
entrypoint:
- /bin/sh
- -c
diff --cc routes/email/email_helpers.py
index 000000000,59b3b4800..26ef3aa50
mode 000000,100644..100644
--- a/routes/email/email_helpers.py
+++ b/routes/email/email_helpers.py
@@@ -1,0 -1,2025 +1,2024 @@@
+ """
+ email_helpers.py
+
+ Lower-level helpers used by both `email_routes.py` (the FastAPI route file)
+ and `email_pollers.py` (the background loops):
+
+ - auth dependencies (require_owner / require_user / _assert_owns_account)
+ - account config + settings persistence (`_get_email_config`, `_list_email_accounts`)
+ - IMAP connection helpers (`_imap_connect`, `_imap`, folder detection)
+ - message parsing (`_decode_header`, `_extract_html/text`, attachment helpers)
+ - sender context retrieval for the AI-summary / AI-reply pipelines
+ - Pydantic models, shared constants, scheduled-DB bootstrap
+ """
+
+ import os
+ import base64
+ import time
+ import imaplib
+ import smtplib
+ import email as email_mod
+ import email.header
+ import email.utils
+ import json
+ import re
+ import html
+ import logging
+ from email.mime.multipart import MIMEMultipart
+ from email.mime.base import MIMEBase
+ from email import encoders
+ import mimetypes
+ from pathlib import Path
+
+ from fastapi import Query, HTTPException, Request
+ from pydantic import BaseModel
+ from typing import Optional, List
+
+ from src.auth_helpers import _auth_disabled, get_current_user
+ from src.secret_storage import decrypt as _decrypt
+
+ logger = logging.getLogger(__name__)
+
+
+ class EmailNotConfiguredError(RuntimeError):
+ """Raised when an IMAP operation is attempted on an account that has no
+ inbox configured (e.g. a send-only / SMTP-only account).
+
+ Subclasses RuntimeError so existing broad ``except Exception`` handlers
+ keep working; callers that want to treat "no inbox" as an empty result
+ rather than a failure can catch this type specifically.
+ """
+
+
+ def _xoauth2_raw(user: str, access_token: str) -> str:
+ """The SASL XOAUTH2 initial-response string (unencoded).
+
+ Both smtplib.SMTP.auth() and imaplib.IMAP4.authenticate() base64-encode
+ the value their callback returns, so callers pass this raw form — never
+ pre-encoded — to avoid double base64.
+ """
+ return f"user={user}\x01auth=Bearer {access_token}\x01\x01"
+
+
+ def _xoauth2_bytes(user: str, access_token: str) -> bytes:
+ """Raw XOAUTH2 bytes for imaplib's authenticate() callback."""
+ return _xoauth2_raw(user, access_token).encode()
+
+
+ def make_oauth_state(account_id: str, owner: str) -> str:
+ """Return an HMAC-signed, base64-encoded OAuth state token.
+
+ Encodes account_id + owner + a random nonce, signed with the app secret
+ so the callback can validate that the flow was initiated by an
+ authenticated, owning user (CSRF / state-forgery protection).
+ """
+ import hmac as _hmac, hashlib as _hl, secrets as _sec
+ from src.secret_storage import _load_or_create_key
+ nonce = _sec.token_hex(16)
+ payload = json.dumps({"a": account_id, "o": owner, "n": nonce}, separators=(",", ":"))
+ sig = _hmac.new(_load_or_create_key(), payload.encode(), _hl.sha256).hexdigest()
+ return base64.urlsafe_b64encode(f"{payload}|{sig}".encode()).decode()
+
+
+ def verify_oauth_state(state: str) -> dict | None:
+ """Verify an OAuth state token's HMAC signature.
+
+ Returns the decoded payload dict ({"a", "o", "n"}) on success, or None if
+ the token is malformed, tampered, or signed with a different key.
+ """
+ import hmac as _hmac, hashlib as _hl
+ from src.secret_storage import _load_or_create_key
+ try:
+ decoded = base64.urlsafe_b64decode(state.encode()).decode()
+ payload, sig = decoded.rsplit("|", 1)
+ expected = _hmac.new(_load_or_create_key(), payload.encode(), _hl.sha256).hexdigest()
+ if not _hmac.compare_digest(sig, expected):
+ return None
+ return json.loads(payload)
+ except Exception:
+ return None
+
+
+ def _refresh_google_token(account_id: str) -> str | None:
+ """Exchange the stored refresh token for a new access token and persist it."""
+ import httpx
+ from core.database import SessionLocal as _SL, EmailAccount as _EA
+ from src.secret_storage import encrypt as _enc, decrypt as _dec
+ client_id = os.environ.get("GOOGLE_OAUTH_CLIENT_ID", "")
+ client_secret = os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET", "")
+ if not client_id or not client_secret:
+ return None
+ db = _SL()
+ try:
+ row = db.get(_EA, account_id)
+ if not row or not row.oauth_refresh_token:
+ return None
+ refresh_token = _dec(row.oauth_refresh_token or "")
+ if not refresh_token:
+ return None
+ resp = httpx.post("https://oauth2.googleapis.com/token", data={
+ "client_id": client_id,
+ "client_secret": client_secret,
+ "refresh_token": refresh_token,
+ "grant_type": "refresh_token",
+ }, timeout=10)
+ resp.raise_for_status()
+ data = resp.json()
+ access_token = data["access_token"]
+ row.oauth_access_token = _enc(access_token)
+ row.oauth_token_expiry = str(int(time.time()) + data.get("expires_in", 3600))
+ db.commit()
+ return access_token
+ except Exception:
+ logger.warning(f"Google token refresh failed for account {account_id}")
+ return None
+ finally:
+ db.close()
+
+
+ def _get_valid_google_token(account_id: str, cfg: dict) -> str | None:
+ """Return a valid Google access token, refreshing if expired or missing."""
+ from src.secret_storage import decrypt as _dec
+ access_token = _dec(cfg.get("oauth_access_token") or "")
+ expiry_str = cfg.get("oauth_token_expiry") or ""
+ if access_token and expiry_str:
+ try:
+ if int(expiry_str) - 60 > time.time():
+ return access_token
+ except (ValueError, TypeError):
+ pass
+ return _refresh_google_token(account_id)
+
+
+ def _smtp_security_mode(cfg: dict) -> str:
+ raw = str(cfg.get("smtp_security") or "").strip().lower()
+ if raw in {"ssl", "starttls", "none"}:
+ return raw
+ port = int(cfg.get("smtp_port") or 465)
+ if port == 587:
+ return "starttls"
+ return "ssl"
+
+
+ def _send_smtp_message(cfg: dict, from_addr: str, recipients: list[str], message: str | bytes, timeout: int = 30) -> None:
+ """Send through SMTP using the configured transport security mode."""
+ host = cfg["smtp_host"]
+ port = int(cfg.get("smtp_port") or 465)
+ user = cfg.get("smtp_user") or ""
+ password = cfg.get("smtp_password") or ""
+
+ def _auth_smtp(smtp):
+ if cfg.get("oauth_provider") == "google":
+ token = _get_valid_google_token(cfg.get("account_id"), cfg)
+ if not token:
+ raise RuntimeError("Google OAuth token unavailable — reconnect the account")
+ smtp.ehlo()
+ smtp.auth("XOAUTH2", lambda challenge=None: _xoauth2_raw(user, token), initial_response_ok=True)
+ elif user and password:
+ smtp.login(user, password)
+
+ security = _smtp_security_mode(cfg)
+
+ if security == "ssl":
+ with smtplib.SMTP_SSL(host, port, timeout=timeout) as smtp:
+ _auth_smtp(smtp)
+ smtp.sendmail(from_addr, recipients, message)
+ return
+
+ with smtplib.SMTP(host, port, timeout=timeout) as smtp:
+ if security == "starttls":
+ smtp.starttls()
+ _auth_smtp(smtp)
+ smtp.sendmail(from_addr, recipients, message)
+
+
+ def _friendly_email_auth_error(protocol: str, host: str, error: object) -> str:
+ """Return a clearer setup error for known provider auth policies."""
+ raw = str(error or "")
+ lower = raw.lower()
+ host_lower = (host or "").lower()
+ microsoft_host = any(
+ marker in host_lower
+ for marker in (
+ "outlook.office365.com",
+ "smtp.office365.com",
+ "office365.com",
+ "outlook.com",
+ "hotmail.com",
+ "live.com",
+ )
+ )
+ microsoft_basic_auth_failure = (
+ "5.7.139" in lower
+ or "basic authentication is disabled" in lower
+ or ("authenticate failed" in lower and microsoft_host)
+ or ("authentication unsuccessful" in lower and microsoft_host)
+ )
+ if microsoft_basic_auth_failure:
+ return (
+ "Microsoft no longer accepts normal mailbox passwords for "
+ "Outlook/Office 365 IMAP/SMTP in most accounts. Odysseus "
+ "does not support Microsoft OAuth/Graph mail yet, so Outlook "
+ "accounts cannot be added with this password form."
+ )
+ return raw[:200]
+
+
+ def _strip_think(text: str) -> str:
+ """Email-flavored think strip — thin wrapper over the central helper.
+
+ Email AI features get the prose-strip extension because their outputs
+ are short LLM-only generations (replies, summaries, calendar extraction,
+ urgency, classification, writing-style) where untagged reasoning leaks
+ are common. The central helper only runs the prose-strip when an actual
+ `<think>` tag was present in the input, so legit user content is safe.
+ """
+ if not text:
+ return ""
+ from src.text_helpers import strip_think as _central, _THINK_TAG_RE
+ # Single linear tag check; the old closed/open `.search()` calls could ReDoS.
+ had_think = bool(_THINK_TAG_RE.search(text))
+ return _central(text, prose=had_think, prompt_echo=True)
+
+
+ import re as _re_reply
+ # Accept REPLY / SUMMARY / OUTPUT as the opening fence so the same extractor
+ # serves replies and summaries (any fenced final-output block).
+ _REPLY_OPEN_RE = _re_reply.compile(r"<<<\s*(?:REPLY|SUMMARY|OUTPUT)\s*>>+", _re_reply.I)
+ _REPLY_CLOSE_RE = _re_reply.compile(r"<<<\s*END\s*>>+", _re_reply.I)
+ _REPLY_ROLE_MARKER_RE = _re_reply.compile(r"</?\|(?:assistant|assistan|user|system|tool)\|>?|</\|end\|>?", _re_reply.I)
+ _SUMMARY_BULLET_RE = _re_reply.compile(r"^(?:[-*\u2022]\s+|\d+[.)]\s+)")
+
+
+ def _extract_reply(text: str) -> str:
+ """Pull the final email reply out of a model response.
+
+ Positive extraction beats blocklist stripping: the model is asked to fence
+ its reply in <<<REPLY>>> ... <<<END>>> markers, so we keep ONLY that region
+ and ignore whatever reasoning came before/after it. Deterministic, and it
+ can never clip a legit reply that merely opens reflectively.
+
+ Fallbacks when the markers are absent (older/weaker models): we just run the
+ usual think-strip on the whole text — strictly no worse than before. A
+ second think-strip pass always runs on the extracted body too, in case the
+ model also reasoned *inside* the markers.
+ """
+ if not text:
+ return ""
+ t = text
+ m = _REPLY_OPEN_RE.search(t)
+ if m:
+ rest = t[m.end():]
+ c = _REPLY_CLOSE_RE.search(rest)
+ t = rest[:c.start()] if c else rest
+ # Drop any stray/duplicate marker tokens, then strip think markup.
+ t = _REPLY_OPEN_RE.sub("", t)
+ t = _REPLY_CLOSE_RE.sub("", t)
+ t = _REPLY_ROLE_MARKER_RE.sub("", t)
+ return _strip_think(t).strip()
+
+
+ def _build_email_summary_messages(sender: str, subject: str, body_for_llm: str) -> list[dict[str, str]]:
+ return [
+ {
+ "role": "system",
+ "content": (
+ "You are an email summarizer. Format: 1-3 short bullet points "
+ "(use '- '). Cover: main point, action items, deadlines. If the "
+ "email has attachments (marked '--- ATTACHMENTS ---'), USE THEIR "
+ "CONTENTS - pull invoice totals, deadlines, key clauses, concrete "
+ "numbers/dates from PDFs/docs into the bullets. Be terse.\n\n"
+ "OUTPUT FORMAT: Put ONLY the bullet points between these exact "
+ "markers, each on its own line:\n"
+ "<<<SUMMARY>>>\n"
+ "- ...\n"
+ "<<<END>>>\n"
+ "Any reasoning must come BEFORE <<<SUMMARY>>> (ideally inside "
+ "<think>...</think>). Only the text between the markers is kept."
+ ),
+ },
+ {
+ "role": "user",
+ "content": (
+ f"From: {sender}\nSubject: {subject}\n\n{body_for_llm[:12000]}"
+ "\n\n---\n\nSummarize the email. Output the bullets between "
+ "<<<SUMMARY>>> and <<<END>>>."
+ ),
+ },
+ ]
+
+
+ async def _generate_email_summary(
+ url: str,
+ model: str,
+ sender: str,
+ subject: str,
+ body_for_llm: str,
+ *,
+ headers: dict | None = None,
+ max_tokens: int = 8192,
+ timeout: int = 180,
+ ) -> str:
+ """Generate an interactive email summary through the shared LLM adapter."""
+ from src.llm_core import llm_call_async
+
+ raw = await llm_call_async(
+ url=url,
+ model=model,
+ messages=_build_email_summary_messages(sender, subject, body_for_llm),
+ temperature=0.3,
+ max_tokens=max_tokens,
+ headers=headers,
+ timeout=timeout,
+ workload="foreground",
+ )
+ return _normalize_email_summary(raw)
+
+
+ async def _generate_scheduled_email_summary(
+ url: str,
+ model: str,
+ sender: str,
+ subject: str,
+ body_for_llm: str,
+ *,
+ headers: dict | None = None,
+ owner: str | None = None,
+ max_tokens: int = 8192,
+ timeout: int = 180,
+ ) -> str:
+ """Generate a scheduled summary through the background task candidate chain."""
+ from src.task_endpoint import task_llm_call_async
+
+ raw = await task_llm_call_async(
+ messages=_build_email_summary_messages(sender, subject, body_for_llm),
+ fallback_url=url,
+ fallback_model=model,
+ fallback_headers=headers,
+ owner=owner,
+ temperature=0.3,
+ max_tokens=max_tokens,
+ timeout=timeout,
+ )
+ return _normalize_email_summary(raw)
+
+
+ def _normalize_email_summary(raw) -> str:
+ """Extract a stable cache/UI summary from provider output."""
+ raw_text = raw or ""
+ if _REPLY_OPEN_RE.search(raw_text):
+ summary = _extract_reply(raw_text)
+ if summary:
+ return summary
+
+ cleaned = _strip_think(raw_text).strip()
+ bullets = [
+ line.strip()
+ for line in cleaned.splitlines()
+ if _SUMMARY_BULLET_RE.match(line.strip())
+ ]
+ if bullets:
+ return "\n".join(bullets)
+ return cleaned.strip()
+
+
+ EMAIL_SUMMARY_ERROR_CODE = "email_summary_unavailable"
+ EMAIL_SUMMARY_ERROR_MESSAGE = "Failed to summarize"
+
+
+ def _email_summary_failure_log_detail(exc: BaseException) -> str:
+ """Return useful provider-failure metadata without echoing exception text."""
+ detail = f"type={type(exc).__name__}"
+ status = getattr(exc, "status_code", None)
+ if status is None:
+ status = getattr(getattr(exc, "response", None), "status_code", None)
+ if isinstance(status, int):
+ detail += f" status={status}"
+ return detail
+
+
+ def _apply_email_style_mechanics(text: str) -> str:
+ """Enforce deterministic writing-style mechanics that models often miss."""
+ if not text:
+ return ""
+ return (
+ text.replace("—", "--")
+ .replace("–", "--")
+ .replace("’", "'")
+ .replace("‘", "'")
+ )
+
+
+ def _require_auth(request: Request) -> str:
+ """Defense-in-depth: reject unauthenticated callers even if upstream
+ middleware was bypassed (e.g. localhost-bypass, SSRF from a sibling
+ service). Mirrors core.middleware.require_admin's resolution path.
+
+ v2 review HIGH-13: previously fell open whenever auth_manager wasn't
+ `is_configured`, exposing IMAP creds and SMTP send to any network
+ caller on a half-configured deploy. Now: anonymous callers in
+ unconfigured mode are only honoured if they're coming from
+ localhost; everyone else gets 401.
+ """
+ u = get_current_user(request)
+ if u:
+ return u
+ if _auth_disabled():
+ return ""
+ auth_mgr = getattr(request.app.state, "auth_manager", None)
+ if auth_mgr is not None and getattr(auth_mgr, "is_configured", False):
+ raise HTTPException(401, "Not authenticated")
+ # Unconfigured / first-run mode: only allow loopback callers. Public
+ # network traffic must authenticate even before auth is set up.
+ client = getattr(request, "client", None)
+ host = (client.host if client else "") or ""
+ if host in ("127.0.0.1", "::1", "localhost"):
+ return ""
+ raise HTTPException(401, "Not authenticated")
+
+
+ def require_owner(request: Request, account_id: str | None = Query(None)) -> str:
+ """FastAPI dependency: authenticate the caller and, if `account_id` is in
+ the query string, assert ownership. Returns the resolved owner ("" in
+ unconfigured single-user mode). Routes whose `account_id` lives in the
+ request body or path must still call `_assert_owns_account(body_id, owner)`
+ explicitly. Use `require_user` (no Query read) for path-param routes."""
+ owner = _require_auth(request)
+ if account_id:
+ _assert_owns_account(account_id, owner)
+ return owner
+
+
+ def require_user(request: Request) -> str:
+ """Auth-only dependency for routes where `account_id` is a path param
+ or absent. Avoids `require_owner`'s Query collision with path params."""
+ return _require_auth(request)
+
+
+ def _assert_owns_account(account_id: str, owner: str) -> None:
+ """Reject requests that name an `account_id` belonging to another user.
+ Previously the account lookup in `_get_email_config` filtered only on
+ `id == account_id`, letting a multi-user deploy enumerate / operate
+ against any other user's IMAP/SMTP mailbox. Call this *before* opening
+ the IMAP connection or reading creds. `owner == ""` is the unconfigured /
+ single-user case — accept any account."""
+ if not account_id or not owner:
+ return
+ try:
+ from core.database import SessionLocal as _SL, EmailAccount as _EA
+ db = _SL()
+ try:
+ row = db.query(_EA).filter(_EA.id == account_id).first()
+ if row is None:
+ raise HTTPException(404, "Account not found")
+ if not _account_visible_to_owner(row, owner):
+ # Treat as 404 (not 403) so we don't leak existence.
+ raise HTTPException(404, "Account not found")
+ finally:
+ db.close()
+ except HTTPException:
+ raise
+ except Exception as e:
+ # Fail closed — a DB hiccup must not let cross-tenant access slip
+ # through. 503 tells the caller to retry; logs preserve detail.
+ logger.error(f"Account-owner check failed: {e}")
+ raise HTTPException(503, "Account check failed")
+
+
+ def _account_visible_to_owner(row, owner: str) -> bool:
+ """Whether an authenticated `owner` may act on this EmailAccount row.
+
+ Mirrors the SQL predicate in `_get_email_config`'s
+ `_owner_or_matching_legacy_account`: a caller sees an account they own, or a
+ legacy owner-less account (owner NULL/"") only when its own mailbox
+ (`imap_user` / `from_address`) is the caller's. `email_accounts` is the one
+ owner-scoped table deliberately left out of the legacy-owner migration
+ backfill, so ownerless rows persist on multi-user deploys — making this the
+ gate that keeps one tenant off another's imported mailbox and its decrypted
+ IMAP/SMTP credentials."""
+ row_owner = getattr(row, "owner", None) or ""
+ if row_owner:
+ return row_owner == owner
+ return owner in {
+ getattr(row, "imap_user", None) or "",
+ getattr(row, "from_address", None) or "",
+ }
+
+ def _q(name: str) -> str:
+ """Quote an IMAP mailbox name. Defensive: escapes `\\` and `"` and wraps
+ in double quotes so user-supplied folder names with spaces or quotes can't
+ confuse `SELECT` / `COPY`. imaplib already rejects CRLF, but quoting also
+ handles `[Gmail]/Sent Mail`-style names that need wrapping anyway."""
+ return '"' + (name or "").replace("\\", "\\\\").replace('"', '\\"') + '"'
+
+
+ def _attach_compose_uploads(outer: MIMEMultipart, tokens) -> None:
+ """Read each staged upload token, build a MIMEBase part, and attach to
+ `outer`. Tokens are sanitized via Path(token).name to prevent traversal.
+ Missing files are skipped silently. Used by /send, scheduled delivery,
+ and the agent send pipeline."""
+ if not tokens:
+ return
+ for token in tokens:
+ safe_token = Path(token).name
+ path = COMPOSE_UPLOADS_DIR / safe_token
+ if not path.exists():
+ logger.warning(f"Attachment token not found: {safe_token}")
+ continue
+ ctype, encoding = mimetypes.guess_type(str(path))
+ if ctype is None or encoding is not None:
+ ctype = "application/octet-stream"
+ maintype, subtype = ctype.split("/", 1)
+ with open(path, "rb") as f:
+ part = MIMEBase(maintype, subtype)
+ part.set_payload(f.read())
+ encoders.encode_base64(part)
+ # Token format: "<uuid>_<original_name>"
+ original_name = safe_token.split("_", 1)[1] if "_" in safe_token else safe_token
+ part.add_header("Content-Disposition", "attachment", filename=original_name)
+ outer.attach(part)
+
+
+ def _cleanup_compose_uploads(tokens) -> None:
+ """Best-effort unlink of staged uploads after delivery (or failure)."""
+ if not tokens:
+ return
+ for token in tokens:
+ try:
+ (COMPOSE_UPLOADS_DIR / Path(token).name).unlink(missing_ok=True)
+ except Exception:
+ pass
+
+
+ from src.constants import DATA_DIR as _DATA_DIR, MAIL_ATTACHMENTS_DIR, SETTINGS_FILE as _SETTINGS_FILE, SCHEDULED_EMAILS_DB
+ DATA_DIR = Path(_DATA_DIR)
+ SETTINGS_FILE = Path(_SETTINGS_FILE)
+ # Override at deploy time via ODYSSEUS_MAIL_ATTACHMENTS_DIR. Defaults to a
+ # subdir of the install's data/ tree so the app works out-of-the-box without
+ # a hardcoded /home/<user>/ path.
+ ATTACHMENTS_DIR = Path(MAIL_ATTACHMENTS_DIR)
+ ATTACHMENTS_DIR.mkdir(parents=True, exist_ok=True)
+ COMPOSE_UPLOADS_DIR = ATTACHMENTS_DIR / "_compose"
+ COMPOSE_UPLOADS_DIR.mkdir(parents=True, exist_ok=True)
+ SCHEDULED_DB = Path(SCHEDULED_EMAILS_DB)
+
+
+ OWNER_SCOPED_EMAIL_CACHE_TABLES = {
+ "email_summaries",
+ "email_ai_replies",
+ "email_translations",
+ "email_calendar_extractions",
+ "email_urgency_alerts",
+ "sender_signatures",
+ }
+
+
+ def email_translation_body_hash(body: str) -> str:
+ import hashlib as _hashlib
+ normalized = (body or "").strip()
+ return _hashlib.sha256(normalized.encode("utf-8", errors="ignore")).hexdigest()
+
+
+ def _email_cache_owner_clause(owner: str = "") -> tuple[str, tuple[str, ...]]:
+ owner = (owner or "").strip()
+ if owner:
+ return "owner = ?", (owner,)
+ return "(owner = '' OR owner IS NULL)", ()
+
+
+ def _ensure_owner_scoped_email_cache_table(
+ conn,
+ table: str,
+ create_sql: str,
+ columns: list[str],
+ pk_columns: list[str] | None = None,
+ ):
+ """Rebuild legacy Message-ID-only cache tables with owner in the PK."""
+ desired_pk_cols = pk_columns or ["message_id", "owner"]
+ conn.execute(create_sql)
+ try:
+ info = conn.execute(f"PRAGMA table_info({table})").fetchall()
+ cols = [r[1] for r in info]
+ pk_cols = [r[1] for r in sorted((r for r in info if r[5]), key=lambda r: r[5])]
+ for col in columns:
+ if col not in cols:
+ if col == "owner":
+ conn.execute(f"ALTER TABLE {table} ADD COLUMN owner TEXT DEFAULT ''")
+ elif col in {"event_uids"}:
+ conn.execute(f"ALTER TABLE {table} ADD COLUMN {col} TEXT DEFAULT '[]'")
+ elif col.startswith("has_") or col.endswith("_created") or col.endswith("_count"):
+ conn.execute(f"ALTER TABLE {table} ADD COLUMN {col} INTEGER DEFAULT 0")
+ elif col == "created_at":
+ conn.execute(f"ALTER TABLE {table} ADD COLUMN {col} TEXT DEFAULT ''")
+ else:
+ conn.execute(f"ALTER TABLE {table} ADD COLUMN {col} TEXT")
+ cols.append(col)
+ if "owner" in cols and pk_cols == desired_pk_cols:
+ return
+
+ conn.execute(f"ALTER TABLE {table} RENAME TO {table}__old")
+ conn.execute(create_sql)
+ old_cols = [r[1] for r in conn.execute(f"PRAGMA table_info({table}__old)").fetchall()]
+ copy_cols = [c for c in columns if c != "owner" and c in old_cols]
+ source_owner = "COALESCE(owner, '')" if "owner" in old_cols else "''"
+ target_cols = ["owner", *copy_cols]
+ select_exprs = [source_owner, *copy_cols]
+ conn.execute(
+ f"INSERT OR IGNORE INTO {table} ({', '.join(target_cols)}) "
+ f"SELECT {', '.join(select_exprs)} FROM {table}__old"
+ )
+ conn.execute(f"DROP TABLE {table}__old")
+ except Exception as _mig_e:
+ import logging as _lg
+ _lg.getLogger(__name__).warning(f"{table} owner-migration skipped: {_mig_e}")
+
+
+ def _ensure_sender_signatures_table(conn):
+ """Create/migrate learned sender signatures to an owner-scoped cache."""
+ create_sql = """
+ CREATE TABLE IF NOT EXISTS sender_signatures (
+ from_address TEXT,
+ owner TEXT DEFAULT '',
+ signature_text TEXT,
+ sample_count INTEGER,
+ last_built_at TEXT NOT NULL,
+ model_used TEXT,
+ source TEXT,
+ PRIMARY KEY (from_address, owner)
+ )
+ """
+ conn.execute(create_sql)
+ try:
+ info = conn.execute("PRAGMA table_info(sender_signatures)").fetchall()
+ cols = [r[1] for r in info]
+ pk_cols = [r[1] for r in sorted((r for r in info if r[5]), key=lambda r: r[5])]
+ if "owner" in cols and pk_cols == ["from_address", "owner"]:
+ return
+
+ conn.execute("ALTER TABLE sender_signatures RENAME TO sender_signatures__old")
+ conn.execute(create_sql)
+ old_cols = [r[1] for r in conn.execute("PRAGMA table_info(sender_signatures__old)").fetchall()]
+ copy_cols = [
+ c for c in (
+ "from_address",
+ "signature_text",
+ "sample_count",
+ "last_built_at",
+ "model_used",
+ "source",
+ )
+ if c in old_cols
+ ]
+ source_owner = "COALESCE(owner, '')" if "owner" in old_cols else "''"
+ conn.execute(
+ f"INSERT OR IGNORE INTO sender_signatures "
+ f"({', '.join([*copy_cols, 'owner'])}) "
+ f"SELECT {', '.join([*copy_cols, source_owner])} "
+ f"FROM sender_signatures__old"
+ )
+ conn.execute("DROP TABLE sender_signatures__old")
+ except Exception as _mig_e:
+ import logging as _lg
+ _lg.getLogger(__name__).warning(f"sender_signatures owner-migration skipped: {_mig_e}")
+
+
+ def attachment_extract_dir(folder: str, uid: str) -> Path:
+ """Containment-safe extraction directory for an attachment.
+
+ `folder` and `uid` are user-controlled (query/path params). Flatten them to
+ a single safe path segment so a value like folder='../../tmp' can't escape
+ ATTACHMENTS_DIR, then assert containment as belt-and-suspenders."""
+ key = re.sub(r"[^A-Za-z0-9._-]", "_", f"{folder}_{uid}") or "_"
+ target = (ATTACHMENTS_DIR / key).resolve()
+ base = ATTACHMENTS_DIR.resolve()
+ if target != base and base not in target.parents:
+ raise HTTPException(400, "Invalid attachment location")
+ return target
+
+
+ def _init_scheduled_db():
+ import sqlite3
+ conn = sqlite3.connect(SCHEDULED_DB)
+ conn.execute("""
+ CREATE TABLE IF NOT EXISTS scheduled_emails (
+ id TEXT PRIMARY KEY,
+ to_addr TEXT NOT NULL,
+ cc TEXT,
+ bcc TEXT,
+ subject TEXT,
+ body TEXT NOT NULL,
+ in_reply_to TEXT,
+ references_hdr TEXT,
+ attachments TEXT,
+ send_at TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'pending',
+ error TEXT,
+ owner TEXT DEFAULT ''
+ )
+ """)
+ # Email summary cache. SECURITY: Message-IDs are global, so AI-derived
+ # cache rows must be owner-scoped just like email_tags.
+ _ensure_owner_scoped_email_cache_table(conn, "email_summaries", """
+ CREATE TABLE IF NOT EXISTS email_summaries (
+ message_id TEXT,
+ owner TEXT DEFAULT '',
+ uid TEXT,
+ folder TEXT,
+ subject TEXT,
+ sender TEXT,
+ summary TEXT NOT NULL,
+ model_used TEXT,
+ created_at TEXT NOT NULL,
+ PRIMARY KEY (message_id, owner)
+ )
+ """, ["message_id", "owner", "uid", "folder", "subject", "sender", "summary", "model_used", "created_at"])
+ # Email AI reply cache (pre-generated draft replies)
+ _ensure_owner_scoped_email_cache_table(conn, "email_ai_replies", """
+ CREATE TABLE IF NOT EXISTS email_ai_replies (
+ message_id TEXT,
+ owner TEXT DEFAULT '',
+ uid TEXT,
+ folder TEXT,
+ reply TEXT NOT NULL,
+ model_used TEXT,
+ created_at TEXT NOT NULL,
+ PRIMARY KEY (message_id, owner)
+ )
+ """, ["message_id", "owner", "uid", "folder", "reply", "model_used", "created_at"])
+ _ensure_owner_scoped_email_cache_table(conn, "email_translations", """
+ CREATE TABLE IF NOT EXISTS email_translations (
+ body_hash TEXT,
+ owner TEXT DEFAULT '',
+ target_language TEXT DEFAULT 'English',
+ uid TEXT,
+ folder TEXT,
+ subject TEXT,
+ sender TEXT,
+ translation TEXT,
+ same_language INTEGER DEFAULT 0,
+ model_used TEXT,
+ created_at TEXT NOT NULL,
+ PRIMARY KEY (body_hash, owner, target_language)
+ )
+ """, [
+ "body_hash", "owner", "target_language", "uid", "folder", "subject", "sender",
+ "translation", "same_language", "model_used", "created_at",
+ ], ["body_hash", "owner", "target_language"])
+ # Email tags / spam classification cache. SECURITY: keyed by
+ # (message_id, owner) because Message-IDs are GLOBAL (a newsletter goes
+ # to many users with the same Message-ID). Without owner-scoping, a
+ # tag-write for user A's row clobbered user B's row and surfaced A's
+ # UID in B's `tag:urgent` IMAP filter (review C2).
+ conn.execute("""
+ CREATE TABLE IF NOT EXISTS email_tags (
+ message_id TEXT,
+ owner TEXT DEFAULT '',
+ account_id TEXT DEFAULT '',
+ uid TEXT,
+ folder TEXT,
+ subject TEXT,
+ sender TEXT,
+ tags TEXT,
+ spam_verdict INTEGER DEFAULT 0,
+ spam_reason TEXT,
+ moved_to TEXT,
+ model_used TEXT,
+ created_at TEXT NOT NULL,
+ PRIMARY KEY (message_id, owner, account_id)
+ )
+ """)
+ # Backfill migration: older installs created the table with
+ # message_id as a bare PK and no owner column. Add the column +
+ # promote it into the PK by rebuild-copy-swap (SQLite can't ALTER PK).
+ try:
+ _cols = [r[1] for r in conn.execute("PRAGMA table_info(email_tags)")]
+ _pk_cols = [r[1] for r in sorted(conn.execute("PRAGMA table_info(email_tags)").fetchall(), key=lambda row: row[5] or 99) if r[5]]
+ if "owner" not in _cols:
+ conn.execute("ALTER TABLE email_tags ADD COLUMN owner TEXT DEFAULT ''")
+ _cols.append("owner")
+ if "account_id" not in _cols:
+ conn.execute("ALTER TABLE email_tags ADD COLUMN account_id TEXT DEFAULT ''")
+ _cols.append("account_id")
+ if _pk_cols != ["message_id", "owner", "account_id"]:
+ # Rebuild with account-aware composite PK. Existing rows get
+ # account_id='' and are still readable as legacy fallback rows;
+ # fresh task runs write exact account ids and no longer block each
+ # other when two accounts share a Message-ID.
+ conn.execute("""
+ CREATE TABLE IF NOT EXISTS email_tags__new (
+ message_id TEXT,
+ owner TEXT DEFAULT '',
+ account_id TEXT DEFAULT '',
+ uid TEXT, folder TEXT, subject TEXT, sender TEXT,
+ tags TEXT, spam_verdict INTEGER DEFAULT 0,
+ spam_reason TEXT, moved_to TEXT, model_used TEXT,
+ created_at TEXT NOT NULL,
+ PRIMARY KEY (message_id, owner, account_id)
+ )
+ """)
+ conn.execute("""
+ INSERT OR IGNORE INTO email_tags__new
+ (message_id, owner, account_id, uid, folder, subject, sender, tags,
+ spam_verdict, spam_reason, moved_to, model_used, created_at)
+ SELECT message_id, COALESCE(owner, ''), COALESCE(account_id, ''), uid, folder, subject,
+ sender, tags, spam_verdict, spam_reason, moved_to,
+ model_used, created_at
+ FROM email_tags
+ """)
+ conn.execute("DROP TABLE email_tags")
+ conn.execute("ALTER TABLE email_tags__new RENAME TO email_tags")
+ except Exception as _mig_e:
+ # Best-effort — log via the module logger if available
+ import logging as _lg
+ _lg.getLogger(__name__).warning(f"email_tags owner-migration skipped: {_mig_e}")
+ _ensure_owner_scoped_email_cache_table(conn, "email_calendar_extractions", """
+ CREATE TABLE IF NOT EXISTS email_calendar_extractions (
+ message_id TEXT,
+ owner TEXT DEFAULT '',
+ uid TEXT,
+ event_uids TEXT DEFAULT '[]',
+ events_created INTEGER DEFAULT 0,
+ created_at TEXT NOT NULL,
+ PRIMARY KEY (message_id, owner)
+ )
+ """, ["message_id", "owner", "uid", "event_uids", "events_created", "created_at"])
+ _ensure_owner_scoped_email_cache_table(conn, "email_urgency_alerts", """
+ CREATE TABLE IF NOT EXISTS email_urgency_alerts (
+ message_id TEXT,
+ owner TEXT DEFAULT '',
+ uid TEXT,
+ folder TEXT,
+ subject TEXT,
+ sender TEXT,
+ urgency TEXT,
+ reason TEXT,
+ alerted INTEGER DEFAULT 0,
+ created_at TEXT NOT NULL,
+ PRIMARY KEY (message_id, owner)
+ )
+ """, ["message_id", "owner", "uid", "folder", "subject", "sender", "urgency", "reason", "alerted", "created_at"])
+ conn.execute("""
+ CREATE TABLE IF NOT EXISTS email_event_seen (
+ owner TEXT NOT NULL,
+ account_key TEXT NOT NULL,
+ folder TEXT NOT NULL,
+ message_key TEXT NOT NULL,
+ first_seen_at TEXT NOT NULL,
+ PRIMARY KEY (owner, account_key, folder, message_key)
+ )
+ """)
+ conn.execute("""
+ CREATE TABLE IF NOT EXISTS email_message_index (
+ owner TEXT NOT NULL DEFAULT '',
+ account_key TEXT NOT NULL DEFAULT '',
+ folder TEXT NOT NULL,
+ uid TEXT NOT NULL,
+ message_id TEXT,
+ subject TEXT,
+ from_name TEXT,
+ from_address TEXT,
+ to_text TEXT,
+ cc_text TEXT,
+ date_iso TEXT,
+ date_display TEXT,
+ date_epoch REAL DEFAULT 0,
+ size INTEGER DEFAULT 0,
+ flags TEXT DEFAULT '',
+ has_attachments INTEGER DEFAULT 0,
+ attachment_names TEXT DEFAULT '',
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (owner, account_key, folder, uid)
+ )
+ """)
+ _message_index_cols = {
+ row[1] for row in conn.execute("PRAGMA table_info(email_message_index)").fetchall()
+ }
+ if "attachment_names" not in _message_index_cols:
+ conn.execute("ALTER TABLE email_message_index ADD COLUMN attachment_names TEXT DEFAULT ''")
+ conn.execute("""
+ CREATE INDEX IF NOT EXISTS ix_email_message_index_folder_date
+ ON email_message_index(owner, account_key, folder, date_epoch DESC)
+ """)
+ conn.execute("""
+ CREATE INDEX IF NOT EXISTS ix_email_message_index_message_id
+ ON email_message_index(owner, account_key, message_id)
+ """)
+ conn.execute("""
+ CREATE TABLE IF NOT EXISTS email_body_preview_cache (
+ owner TEXT NOT NULL DEFAULT '',
+ account_key TEXT NOT NULL DEFAULT '',
+ folder TEXT NOT NULL,
+ uid TEXT NOT NULL,
+ message_id TEXT,
+ payload_json TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (owner, account_key, folder, uid)
+ )
+ """)
+ conn.execute("""
+ CREATE INDEX IF NOT EXISTS ix_email_body_preview_message_id
+ ON email_body_preview_cache(owner, account_key, message_id)
+ """)
+ conn.execute("""
+ CREATE TABLE IF NOT EXISTS email_attachment_metadata_cache (
+ owner TEXT NOT NULL DEFAULT '',
+ account_key TEXT NOT NULL DEFAULT '',
+ folder TEXT NOT NULL,
+ uid TEXT NOT NULL,
+ message_id TEXT,
+ attachments_json TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (owner, account_key, folder, uid)
+ )
+ """)
+ # Boundary cache — LLM-detected sig/quote start positions in the body.
+ # Stored as char offsets (-1 = no boundary found). Once cached, the
+ # client uses these to fold without ever re-calling the LLM.
+ conn.execute("""
+ CREATE TABLE IF NOT EXISTS email_boundaries (
+ message_id TEXT PRIMARY KEY,
+ uid TEXT,
+ folder TEXT,
+ sig_start INTEGER,
+ quote_start INTEGER,
+ model_used TEXT,
+ created_at TEXT NOT NULL
+ )
+ """)
+ # Lazy migration: add account_id column to scheduled_emails if missing
+ try:
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(scheduled_emails)").fetchall()]
+ if "account_id" not in cols:
+ conn.execute("ALTER TABLE scheduled_emails ADD COLUMN account_id TEXT")
+ if "odysseus_kind" not in cols:
+ conn.execute("ALTER TABLE scheduled_emails ADD COLUMN odysseus_kind TEXT")
+ if "owner" not in cols:
+ conn.execute("ALTER TABLE scheduled_emails ADD COLUMN owner TEXT DEFAULT ''")
+ conn.execute("CREATE INDEX IF NOT EXISTS ix_scheduled_emails_owner_status ON scheduled_emails(owner, status)")
+ # Backfill owner on legacy rows from the owning email account so the
+ # owner-scoped list/cancel routes surface pre-migration scheduled
+ # sends to the right user (the poller already resolves these by
+ # account at send time; this aligns the UI with that).
+ legacy_accounts = conn.execute(
+ "SELECT DISTINCT account_id FROM scheduled_emails "
+ "WHERE (owner IS NULL OR owner = '') AND account_id IS NOT NULL AND account_id != ''"
+ ).fetchall()
+ if legacy_accounts:
+ try:
+ from core.database import SessionLocal as _SL, EmailAccount as _EA
+ _db = _SL()
+ try:
+ for (acct_id,) in legacy_accounts:
+ row = _db.query(_EA.owner).filter(_EA.id == acct_id).first()
+ acct_owner = (row[0] or "") if row else ""
+ if acct_owner:
+ conn.execute(
+ "UPDATE scheduled_emails SET owner = ? "
+ "WHERE account_id = ? AND (owner IS NULL OR owner = '')",
+ (acct_owner, acct_id),
+ )
+ finally:
+ _db.close()
+ except Exception:
+ pass
+ except Exception:
+ pass
+ # Lazy migration: add turns_json to email_boundaries for server-side
+ # thread parsing cache (talon-style precomputed reply chain).
+ try:
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(email_boundaries)").fetchall()]
+ if "turns_json" not in cols:
+ conn.execute("ALTER TABLE email_boundaries ADD COLUMN turns_json TEXT")
+ except Exception:
+ pass
+ # Per-sender signature cache. Populated by `learn_sender_signatures`.
+ # Message sender addresses are global, so signatures must be scoped to the
+ # mailbox owner before `/read` returns them to the renderer.
+ _ensure_sender_signatures_table(conn)
+ conn.commit()
+ conn.close()
+
+
+ _init_scheduled_db()
+
+
+ def _load_settings():
+ if SETTINGS_FILE.exists():
+ return json.loads(SETTINGS_FILE.read_text(encoding="utf-8"))
+ return {}
+
+
+ def _save_settings(settings):
+ from core.atomic_io import atomic_write_json
+ atomic_write_json(str(SETTINGS_FILE), settings, indent=2)
+
+
+ def _get_email_config(account_id: str | None = None, owner: str = "") -> dict:
+ """Return IMAP/SMTP config as a dict.
+
+ Resolution order:
+ 1. If account_id given → that specific EmailAccount row.
+ 2. Else → the row with is_default=True (scoped to `owner` when given).
+ 3. Else → the first enabled row (scoped to `owner` when given).
+ 4. Else → legacy flat keys in data/settings.json (kept for envs
+ where the migration hasn't run yet or accounts table is empty).
+ 5. Else → env vars (SMTP_HOST / IMAP_HOST / ...).
+
+ Returned dict always has the same shape as before; an `account_id` key is
+ added so callers can stamp derivative records (email_ai_replies etc.).
+
+ SECURITY: without `owner`, the fallback queries (is_default, first-enabled)
+ don't filter by user — so on a multi-user deploy a brand-new account would
+ inherit whoever else's IMAP/SMTP creds happened to be the default. Pass
+ `owner` from the route's auth dependency to scope the lookup.
+ """
+ import os
+ from core.database import SessionLocal as _SL, EmailAccount as _EA
+
+ def _owner_or_matching_legacy_account(query):
+ if not owner:
+ return query
+ from sqlalchemy import and_, or_
+ unowned = or_(_EA.owner == None, _EA.owner == "") # noqa: E711
+ same_mailbox = or_(_EA.imap_user == owner, _EA.from_address == owner)
+ return query.filter(or_(_EA.owner == owner, and_(unowned, same_mailbox)))
+
+ resolved_id = None
+ row = None
+ try:
+ db = _SL()
+ try:
+ if account_id:
+ row = db.query(_EA).filter(_EA.id == account_id, _EA.enabled == True).first() # noqa: E712
+ # If the resolved row isn't visible to this owner, treat as
+ # not-found rather than silently serving it. This is a defense
+ # in depth — `require_owner` already calls `_assert_owns_account`
+ # for query-param account_ids, but other callers (cookbook
+ # rules, scheduled poller) may not. Ownerless legacy rows are
+ # only visible on a mailbox match, same as the fallback below.
+ if row is not None and owner and not _account_visible_to_owner(row, owner):
+ row = None
+ # Fallback path — restrict to this owner's accounts so we don't
+ # leak another user's default mailbox to an unconfigured user.
+ if row is None:
+ q = db.query(_EA).filter(_EA.is_default == True, _EA.enabled == True) # noqa: E712
+ q = _owner_or_matching_legacy_account(q)
+ row = q.first()
+ if row is None:
+ q = db.query(_EA).filter(_EA.enabled == True) # noqa: E712
+ q = _owner_or_matching_legacy_account(q)
+ row = q.order_by(_EA.created_at.asc()).first()
+ if row is not None:
+ resolved_id = row.id
+ cfg = {
+ "account_id": row.id,
+ "account_name": row.name,
+ "smtp_host": row.smtp_host or "",
+ "smtp_port": int(row.smtp_port or 465),
+ "smtp_security": _smtp_security_mode({"smtp_security": getattr(row, "smtp_security", ""), "smtp_port": row.smtp_port}),
+ "smtp_user": row.smtp_user or "",
+ "smtp_password": _decrypt(row.smtp_password or ""),
+ "imap_host": row.imap_host or "",
+ "imap_port": int(row.imap_port or 993),
+ "imap_user": row.imap_user or "",
+ "imap_password": _decrypt(row.imap_password or ""),
+ "imap_starttls": bool(row.imap_starttls),
+ "from_address": row.from_address or row.imap_user or "",
+ "oauth_provider": row.oauth_provider or "",
+ "oauth_access_token": row.oauth_access_token or "",
+ "oauth_refresh_token": row.oauth_refresh_token or "",
+ "oauth_token_expiry": row.oauth_token_expiry or "",
+ "display_name": row.display_name or "",
+ }
+ is_oauth = bool(cfg.get("oauth_provider"))
+ if not is_oauth and not (cfg["smtp_host"] and cfg["smtp_user"] and cfg["smtp_password"]):
+ logger.warning(f"SMTP not configured for account {row.name!r}")
+ if not is_oauth and not (cfg["imap_host"] and cfg["imap_user"] and cfg["imap_password"]):
+ logger.warning(f"IMAP not configured for account {row.name!r}")
+ return cfg
+ finally:
+ db.close()
+ except Exception as e:
+ logger.debug(f"email_accounts lookup failed, falling back to settings.json: {e}")
+
+ # Legacy fallback — flat keys in settings.json / env vars
+ settings = _load_settings()
+ cfg = {
+ "account_id": resolved_id,
+ "account_name": "legacy",
+ "smtp_host": settings.get("smtp_host", os.environ.get("SMTP_HOST", "")),
+ "smtp_port": int(settings.get("smtp_port", os.environ.get("SMTP_PORT", "465")) or 465),
+ "smtp_security": _smtp_security_mode({
+ "smtp_security": settings.get("smtp_security", os.environ.get("SMTP_SECURITY", "")),
+ "smtp_port": settings.get("smtp_port", os.environ.get("SMTP_PORT", "465")),
+ }),
+ "smtp_user": settings.get("smtp_user", os.environ.get("SMTP_USER", "")),
+ "smtp_password": settings.get("smtp_password", os.environ.get("SMTP_PASSWORD", "")),
+ "imap_host": settings.get("imap_host", os.environ.get("IMAP_HOST", "")),
+ "imap_port": int(settings.get("imap_port", os.environ.get("IMAP_PORT", "993")) or 993),
+ "imap_user": settings.get("imap_user", os.environ.get("IMAP_USER", "")),
+ "imap_password": settings.get("imap_password", os.environ.get("IMAP_PASSWORD", "")),
+ "imap_starttls": settings.get("imap_starttls", True),
+ "from_address": settings.get("email_from", os.environ.get("EMAIL_FROM", "")),
+ }
+ if not (cfg["smtp_host"] and cfg["smtp_user"] and cfg["smtp_password"]):
+ logger.warning("SMTP not configured — add an Email Account in Settings or set env vars")
+ if not (cfg["imap_host"] and cfg["imap_user"] and cfg["imap_password"]):
+ logger.warning("IMAP not configured — add an Email Account in Settings or set env vars")
+ return cfg
+
+
+ def _list_email_accounts() -> list[dict]:
+ """Return all enabled accounts in creation order. Used by background loops
+ that iterate over every account (auto-summarize, urgency, etc.)."""
+ from core.database import SessionLocal as _SL, EmailAccount as _EA
+ try:
+ db = _SL()
+ try:
+ rows = (
+ db.query(_EA)
+ .filter(_EA.enabled == True) # noqa: E712
+ .order_by(_EA.is_default.desc(), _EA.created_at.asc())
+ .all()
+ )
+ return [_get_email_config(r.id) for r in rows]
+ finally:
+ db.close()
+ except Exception as e:
+ logger.debug(f"_list_email_accounts failed, returning [default]: {e}")
+ return [_get_email_config()]
+
+
+ # ── IMAP helpers ──
+
+ def _coerce_imap_timeout_seconds(raw: str | None) -> int:
+ try:
+ value = int(raw or "30")
+ except (TypeError, ValueError):
+ value = 30
+ return max(5, min(value, 300))
+
+
+ _IMAP_TIMEOUT_SECONDS = _coerce_imap_timeout_seconds(os.environ.get("ODYSSEUS_IMAP_TIMEOUT_SECONDS"))
+
+
+ def _open_imap_connection(
+ host: str,
+ port: int,
+ *,
+ starttls: bool,
+ timeout: int = _IMAP_TIMEOUT_SECONDS,
+ ssl_context=None,
+ ):
+ """Open an IMAP connection using the configured security mode."""
+ port = int(port or 993)
+ if starttls:
+ conn = imaplib.IMAP4(host, port, timeout=timeout)
+ try:
+ if ssl_context:
+ conn.starttls(ssl_context=ssl_context)
+ else:
+ conn.starttls()
+ except Exception:
+ # Don't leak the open plain socket if the STARTTLS upgrade is
+ # rejected; close it before propagating. (#3174)
+ try:
+ conn.shutdown()
+ except Exception:
+ pass
+ raise
+ elif port == 993:
+ kwargs = {"ssl_context": ssl_context} if ssl_context else {}
+ conn = imaplib.IMAP4_SSL(host, port, timeout=timeout, **kwargs)
+ else:
+ conn = imaplib.IMAP4(host, port, timeout=timeout)
+ try:
+ conn.sock.settimeout(timeout)
+ except Exception:
+ pass
+ # Raise the IMAP line-length limit from the default 1 MB to 50 MB so that
+ # large mailboxes (tens of thousands of messages) don't crash with
+ # "got more than 1000000 bytes" on UID SEARCH ALL. (#2883)
+ imaplib._MAXLINE = 50_000_000
+ return conn
+
+ def _imap_connect(account_id: str | None = None, owner: str = "",
+ timeout: int = _IMAP_TIMEOUT_SECONDS):
+ # SECURITY: passing `owner` scopes the fallback config lookup so a brand
+ # new user doesn't get connected against another user's default mailbox
+ # when they have no account configured.
+ #
+ # `timeout` is overridable so short-lived callers (e.g. the service-health
+ # probe) can impose a tighter budget than the default IMAP timeout.
+ cfg = _get_email_config(account_id, owner=owner)
+ # Send-only (SMTP-only) account: no IMAP host means there is no inbox to
+ # read. Bail out with a clear, typed error instead of handing an empty
+ # host to imaplib — IMAP4("", 993) silently dials localhost:993 and fails
+ # with a confusing "[Errno 111] Connection refused" on every inbox poll.
+ if not cfg.get("imap_host"):
+ raise EmailNotConfiguredError(
+ f"IMAP is not configured for account {cfg.get('account_name') or 'default'!r}"
+ )
+ # Connection mode:
+ # STARTTLS on → plain + upgrade
+ # STARTTLS off + port 993 → implicit SSL (IMAPS)
+ # STARTTLS off + any other port → plain (local Dovecot, custom ports)
+ # The last branch is critical: previously this fell into IMAP4_SSL
+ # for any non-STARTTLS port, which would fail the TLS handshake on
+ # plain local servers (Dovecot on 31143, etc.).
+ conn = _open_imap_connection(
+ cfg["imap_host"],
+ cfg["imap_port"],
+ starttls=bool(cfg.get("imap_starttls")),
+ timeout=timeout,
+ )
+ try:
+ if cfg.get("oauth_provider") == "google":
+ token = _get_valid_google_token(cfg.get("account_id"), cfg)
+ if not token:
+ raise RuntimeError("Google OAuth token unavailable — reconnect the account in Settings → Integrations")
+ conn.authenticate("XOAUTH2", lambda x: _xoauth2_bytes(cfg["imap_user"], token))
+ else:
+ conn.login(cfg["imap_user"], cfg["imap_password"])
+ except Exception:
+ # A failed AUTHENTICATE (e.g. an Office 365 app password on an
+ # MFA-enabled tenant, #3174, or an expired/revoked OAuth token)
+ # otherwise orphans the already-connected socket; close it before
+ # propagating so a misconfigured account can't leak one descriptor
+ # per retry / background poller pass.
+ try:
+ conn.shutdown()
+ except Exception:
+ pass
+ raise
+ return conn
+
+
+ from contextlib import contextmanager
+
+
+ # Filled in by setup_email_routes() once its closure-scoped pool helpers are
+ # defined. Keyed so we can swap them out in tests.
+ _POOL_HOOKS: dict = {"connect": None, "release": None}
+
+
+ @contextmanager
+ def _imap(account_id: str | None = None, owner: str = ""):
+ """IMAP connection scoped to a `with` block.
+
+ Uses the connection pool when available so we don't pay the
+ TCP+TLS+LOGIN handshake (~30-100ms with Dovecot) on every request.
+ Falls back to a fresh connect+logout pair before `setup_email_routes()`
+ has run (e.g. background pollers spinning up early).
+
+ SECURITY: `owner` flows through `_imap_connect` → `_get_email_config`
+ so the fallback config lookup (when `account_id` is missing) is scoped
+ to this user's accounts.
+ """
+ pool_connect = _POOL_HOOKS.get("connect")
+ pool_release = _POOL_HOOKS.get("release")
+ if pool_connect and pool_release:
+ # SECURITY: forward owner so the pool slot is per-user and the
+ # fresh-connection fallback runs through a scoped config lookup.
+ try:
+ conn, _reused = pool_connect(account_id, owner=owner)
+ except TypeError:
+ # Older hook signature without owner — fall back transparently.
+ conn, _reused = pool_connect(account_id)
+ ok = True
+ try:
+ yield conn
+ except Exception:
+ ok = False
+ raise
+ finally:
+ try:
+ try:
+ pool_release(account_id, conn, ok=ok, owner=owner)
+ except TypeError:
+ pool_release(account_id, conn, ok=ok)
+ except Exception:
+ pass
+ return
+ # Fallback: plain connect+logout. Used pre-setup or in tests.
+ conn = _imap_connect(account_id, owner=owner)
+ try:
+ yield conn
+ finally:
+ try:
+ conn.logout()
+ except Exception:
+ pass
+
+
+ def _decode_header(raw):
+ if not raw:
+ return ""
+ try:
+ # make_header concatenates per RFC 2047: no spurious space between an
+ # encoded-word and adjacent plain text (plain runs keep their own
+ # whitespace), and the whitespace between two adjacent encoded-words is
+ # dropped. The old " ".join produced "Re: Jose"-style double spaces on
+ # every non-ASCII subject or sender.
+ return str(email.header.make_header(email.header.decode_header(raw)))
+ except Exception:
+ # Malformed header or unknown/invalid MIME charset (e.g. a spam header
+ # like =?x-unknown-charset?B?...?=) makes make_header raise LookupError;
+ # fall back to a lossy per-part decode. errors="replace" only covers
+ # byte-decode errors, not codec lookup, hence the explicit utf-8 retry.
+ decoded = []
+ for data, charset in email.header.decode_header(raw):
+ if isinstance(data, bytes):
+ try:
+ decoded.append(data.decode(charset or "utf-8", errors="replace"))
+ except (LookupError, ValueError):
+ decoded.append(data.decode("utf-8", errors="replace"))
+ else:
+ decoded.append(data)
+ return "".join(decoded)
+
+
+ def _detect_sent_folder(conn):
+ """Find the server's Sent folder name. Returns 'Sent' if nothing matches.
+
+ Different IMAP servers expose the sent folder under different names:
+ Dovecot/typical: "Sent"
+ Gmail: "[Gmail]/Sent Mail"
+ Outlook/EWS: "Sent Items"
+ Some hosts: "INBOX.Sent"
+ """
+ candidates = ("Sent", "[Gmail]/Sent Mail", "Sent Mail", "Sent Items", "INBOX.Sent")
+ try:
+ status, folders = conn.list()
+ if status != "OK" or not folders:
+ return "Sent"
+ names = []
+ for f in folders:
+ decoded = f.decode() if isinstance(f, bytes) else str(f)
+ m = re.search(r'"([^"]*)"\s*$|(\S+)\s*$', decoded)
+ if m:
+ names.append(m.group(1) or m.group(2))
+ # Prefer \Sent flag in LIST response if present.
+ for f in folders:
+ decoded = f.decode() if isinstance(f, bytes) else str(f)
+ if r"\Sent" in decoded:
+ m = re.search(r'"([^"]*)"\s*$|(\S+)\s*$', decoded)
+ if m:
+ return m.group(1) or m.group(2)
+ for c in candidates:
+ if c in names:
+ return c
+ except Exception:
+ pass
+ return "Sent"
+
+
+ def _detect_drafts_folder(conn):
+ """Find the server's Drafts folder name. Gmail usually exposes
+ "[Gmail]/Drafts"; other servers often use "Drafts"."""
+ candidates = ("Drafts", "[Gmail]/Drafts", "Draft", "INBOX.Drafts")
+ try:
+ status, folders = conn.list()
+ if status != "OK" or not folders:
+ return "Drafts"
+ names = []
+ for f in folders:
+ decoded = f.decode() if isinstance(f, bytes) else str(f)
+ m = re.search(r'"([^"]*)"\s*$|(\S+)\s*$', decoded)
+ if m:
+ names.append(m.group(1) or m.group(2))
+ for f in folders:
+ decoded = f.decode() if isinstance(f, bytes) else str(f)
+ if r"\Drafts" in decoded or r"\Draft" in decoded:
+ m = re.search(r'"([^"]*)"\s*$|(\S+)\s*$', decoded)
+ if m:
+ return m.group(1) or m.group(2)
+ for c in candidates:
+ if c in names:
+ return c
+ except Exception:
+ pass
+ return "Drafts"
+
+
+ def _detect_spam_folder(conn):
+ """Find the server's Junk/Spam folder name, if any."""
+ try:
+ status, folders = conn.list()
+ if status != "OK" or not folders:
+ return None
+ preferred = None
+ fallback = None
+ for f in folders:
+ decoded = f.decode() if isinstance(f, bytes) else str(f)
+ m = re.search(r'"([^"]*)"\s*$|(\S+)\s*$', decoded)
+ if not m:
+ continue
+ name = m.group(1) or m.group(2)
+ if r"\Junk" in decoded:
+ preferred = name
+ break
+ low = name.lower()
+ if low in ("junk", "spam", "junk mail", "junk e-mail") or low.endswith("/junk") or low.endswith("/spam"):
+ fallback = fallback or name
+ return preferred or fallback
+ except Exception:
+ return None
+
+
+ def _imap_move(uid, dest, src="INBOX", account_id: str | None = None, owner: str = ""):
+ """Move a single IMAP UID from src folder to dest. Returns True on success."""
+ c = None
+ try:
+ c = _imap_connect(account_id, owner=owner)
+ c.select(_q(src))
+ # Callers pass a real IMAP UID (from conn.uid("SEARCH", ...)). copy()
+ # and store() operate on message SEQUENCE NUMBERS, so addressing them
+ # with a UID moved/deleted the wrong message (or silently no-oped when
+ # the UID exceeded the message count). Use the UID commands, matching
+ # the move/delete path in email_routes.py.
+ status, _ = c.uid("COPY", uid, _q(dest))
+ if status != "OK":
+ return False
+ c.uid("STORE", uid, "+FLAGS", "\\Deleted")
+ c.expunge()
+ return True
+ except Exception as e:
+ logger.warning(f"IMAP move {uid} → {dest} failed: {e}")
+ return False
+ finally:
+ if c:
+ try:
+ c.logout()
+ except Exception:
+ pass
+
+
+ def _extract_attachment_text(msg, max_chars: int = 6000) -> str:
+ """Pull readable text out of an email's attachments — PDF (via PyMuPDF),
+ plain text, markdown, csv, log. Caps total at `max_chars`. Returns a
+ formatted string with `[Attachment: filename]\\n<content>` blocks
+ separated by `---`. Empty string if there's nothing useful.
+
+ Used by the summarize/reply pipeline so an email like "see attached
+ invoice" produces a summary that actually references the invoice.
+ """
+ if not msg or not msg.is_multipart():
+ return ""
+ out_parts: list[str] = []
+ total = 0
+ import os as _os
+ import tempfile as _tempfile
+ for part in msg.walk():
+ if part.is_multipart():
+ continue
+ cd = str(part.get("Content-Disposition", ""))
+ ct = (part.get_content_type() or "").lower()
+ if ct in ("text/plain", "text/html") and "attachment" not in cd.lower():
+ continue
+ filename = part.get_filename() or ""
+ if filename:
+ try:
+ filename = _decode_header(filename)
+ except Exception:
+ pass
+ fname_lower = (filename or "").lower()
+ payload = part.get_payload(decode=True)
+ if not payload:
+ continue
+ # Cap per-attachment size to avoid huge PDFs blowing the budget.
+ if len(payload) > 2_000_000:
+ continue
+ text = ""
+ try:
+ if ct == "application/pdf" or fname_lower.endswith(".pdf"):
+ tmp = _tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
+ try:
+ tmp.write(payload)
+ tmp.close()
+ from src.personal_docs import extract_pdf_text
+ text = extract_pdf_text(tmp.name) or ""
+ finally:
+ try:
+ _os.unlink(tmp.name)
+ except Exception:
+ pass
+ elif ct.startswith("text/") or fname_lower.endswith((".txt", ".md", ".csv", ".log", ".json")):
+ text = payload.decode("utf-8", errors="replace")
+ except Exception as e:
+ logger.debug(f"attachment-text extract failed for {filename}: {e}")
+ continue
+ text = (text or "").strip()
+ if not text:
+ continue
+ remaining = max_chars - total
+ if remaining <= 0:
+ break
+ snippet = text[:remaining]
+ out_parts.append(f"[Attachment: {filename or 'file'}]\n{snippet}")
+ total += len(snippet)
+ if total >= max_chars:
+ break
+ return "\n\n---\n\n".join(out_parts)
+
+
+ def _list_attachments_from_msg(msg):
+ """Return a list of attachment metadata from an email message."""
+ attachments = []
+ if not msg.is_multipart():
+ return attachments
+ idx = 0
+ for part in msg.walk():
+ cd = str(part.get("Content-Disposition", ""))
+ ct = part.get_content_type()
+ is_attached_email = ct == "message/rfc822" and ("attachment" in cd.lower() or part.get_filename())
+ if part.is_multipart() and not is_attached_email:
+ continue
+ # Skip text/html body parts (only consider real attachments)
+ if ct in ("text/plain", "text/html") and "attachment" not in cd:
+ continue
+ filename = part.get_filename()
+ if filename:
+ filename = _decode_header(filename)
+ if ct == "message/rfc822" and not re.search(r"\.[A-Za-z0-9]{1,8}$", filename):
+ filename = f"{filename}.eml"
+ else:
+ # Inline images, etc. - generate a name
+ ext = "eml" if ct == "message/rfc822" else (ct.split("/")[-1] if "/" in ct else "bin")
+ filename = f"attachment_{idx}.{ext}"
+ payload = part.get_payload(decode=True)
+ if payload is None and ct == "message/rfc822":
+ try:
+ payload = part.as_bytes()
+ except Exception:
+ payload = b""
+ size = len(payload) if payload is not None else 0
+ content_id = (part.get("Content-ID") or "").strip().strip("<>")
+ attachments.append({
+ "index": idx,
+ "filename": filename,
+ "content_type": ct,
+ "size": size,
+ "is_inline": "inline" in cd.lower(),
+ "content_id": content_id,
+ })
+ idx += 1
+ return attachments
+
+
+ def _is_likely_signature_image_attachment(att: dict) -> bool:
+ """Match the reader's inline signature/logo image filter."""
+ filename = str((att or {}).get("filename") or "").lower()
+ if not re.search(r"\.(png|jpe?g|gif|bmp|svg|webp)$", filename):
+ return False
+ size = int((att or {}).get("size") or 0)
+ if re.search(r"^image\d{3,}\.(png|jpe?g|gif)$", filename):
+ return True
+ if re.search(r"^(signature|logo|sig|footer|banner)[-_\d]*\.(png|jpe?g|gif|svg)$", filename):
+ return True
+ return 0 < size < 30 * 1024
+
+
+ def _has_visible_attachments(msg) -> bool:
+ """Return True only for attachments the reader will render as chips."""
+ return any(
+ not _is_likely_signature_image_attachment(att)
+ for att in _list_attachments_from_msg(msg)
+ )
+
+
+ def _extract_attachment_to_disk(msg, index, target_dir):
+ """Extract a specific attachment to disk and return the file path."""
+ if not msg.is_multipart():
+ return None
+ idx = 0
+ for part in msg.walk():
+ cd = str(part.get("Content-Disposition", ""))
+ ct = part.get_content_type()
+ is_attached_email = ct == "message/rfc822" and ("attachment" in cd.lower() or part.get_filename())
+ if part.is_multipart() and not is_attached_email:
+ continue
+ if ct in ("text/plain", "text/html") and "attachment" not in cd:
+ continue
+ if idx == index:
+ filename = part.get_filename()
+ if filename:
+ filename = _decode_header(filename)
+ if ct == "message/rfc822" and not re.search(r"\.[A-Za-z0-9]{1,8}$", filename):
+ filename = f"{filename}.eml"
+ else:
+ ext = "eml" if ct == "message/rfc822" else (ct.split("/")[-1] if "/" in ct else "bin")
+ filename = f"attachment_{idx}.{ext}"
+ # Sanitize
+ safe_name = re.sub(r"[^\w\s\-.]", "_", filename).strip()
+ payload = part.get_payload(decode=True)
+ if payload is None and ct == "message/rfc822":
+ try:
+ payload = part.as_bytes()
+ except Exception:
+ payload = b""
+ if payload is None:
+ return None
+ target_dir.mkdir(parents=True, exist_ok=True)
+ filepath = target_dir / safe_name
+ with open(filepath, "wb") as f:
+ f.write(payload)
+ return filepath
+ idx += 1
+ return None
+
+
+ def _extract_html(msg):
+ """Extract raw HTML body from an email message, if present."""
+ if msg.is_multipart():
+ for part in msg.walk():
+ ct = part.get_content_type()
+ cd = str(part.get("Content-Disposition", ""))
+ if ct == "text/html" and "attachment" not in cd:
+ payload = part.get_payload(decode=True)
+ if payload:
+ charset = part.get_content_charset() or "utf-8"
+ return payload.decode(charset, errors="replace")
+ elif msg.get_content_type() == "text/html":
+ payload = msg.get_payload(decode=True)
+ if payload:
+ charset = msg.get_content_charset() or "utf-8"
+ return payload.decode(charset, errors="replace")
+ return None
+
+
+ def _extract_text(msg):
+ if msg.is_multipart():
+ text_parts = []
+ for part in msg.walk():
+ ct = part.get_content_type()
+ cd = str(part.get("Content-Disposition", ""))
+ if ct == "text/plain" and "attachment" not in cd:
+ payload = part.get_payload(decode=True)
+ if payload:
+ charset = part.get_content_charset() or "utf-8"
+ text_parts.append(payload.decode(charset, errors="replace"))
+ elif ct == "text/html" and not text_parts and "attachment" not in cd:
+ payload = part.get_payload(decode=True)
+ if payload:
+ charset = part.get_content_charset() or "utf-8"
+ raw_html = payload.decode(charset, errors="replace")
+ text = re.sub(r"<br\s*/?>", "\n", raw_html, flags=re.I)
+ text = re.sub(r"<[^>]+>", "", text)
+ text = html.unescape(text)
+ text_parts.append(text.strip())
+ return "\n".join(text_parts)
+ else:
+ payload = msg.get_payload(decode=True)
+ if payload:
+ charset = msg.get_content_charset() or "utf-8"
+ text = payload.decode(charset, errors="replace")
+ if msg.get_content_type() == "text/html":
+ text = re.sub(r"<br\s*/?>", "\n", text, flags=re.I)
+ text = re.sub(r"</(?:p|div|li|tr|h[1-6])\s*>", "\n", text, flags=re.I)
+ text = re.sub(r"<[^>]+>", "", text)
+ text = html.unescape(text)
+ text = re.sub(r"[ \t]+\n", "\n", text)
+ text = re.sub(r"\n{3,}", "\n\n", text)
+ return text.strip()
+ return ""
+
+
+ def _fetch_sender_thread_context(sender_addr: str,
+ exclude_uid: str = "",
+ exclude_folder: str = "INBOX",
+ limit: int = 3,
+ max_chars_per_email: int = 1500,
+ max_attachment_chars: int = 4000,
+ account_id: str | None = None,
+ owner: str = "") -> str:
+ """Pull the last N emails from `sender_addr` (across common folders),
+ extract their body snippets + attachment text, and return one formatted
+ block ready to be glued into an LLM system prompt as "REFERENCED MATERIAL".
+
+ Returns empty string if nothing useful was found. Never raises.
+
+ Used by the AI reply path so a follow-up like "regarding question 3 of the
+ document you sent" can actually quote that document instead of pretending.
+ """
+ if not sender_addr:
+ return ""
+ sender_addr = sender_addr.strip().lower()
+ if not sender_addr:
+ return ""
+
+ blocks: list[str] = []
+ seen_uids: set[tuple[str, str]] = set() # (folder, uid)
+ if exclude_uid:
+ seen_uids.add((exclude_folder or "INBOX", str(exclude_uid)))
+
+ conn = None
+ try:
+ conn = _imap_connect(account_id, owner=owner)
+ for folder in ["INBOX", "Sent", "Archive", "Drafts"]:
+ if len(blocks) >= limit:
+ break
+ try:
+ st_sel, _ = conn.select(_q(folder), readonly=True)
+ if st_sel != "OK":
+ continue
+ except Exception:
+ continue
+ try:
+ addr_escaped = sender_addr.replace('"', '\\"')
+ status, sdata = conn.search(None, f'(FROM "{addr_escaped}")')
+ if status != "OK" or not sdata or not sdata[0]:
+ continue
+ uids = sdata[0].split()
+ # Most recent first.
+ uids = list(reversed(uids))
+ except Exception:
+ continue
+
+ for raw_uid in uids:
+ if len(blocks) >= limit:
+ break
+ uid = raw_uid.decode() if isinstance(raw_uid, bytes) else str(raw_uid)
+ key = (folder, uid)
+ if key in seen_uids:
+ continue
+ seen_uids.add(key)
+
+ try:
+ st_f, msg_data = conn.fetch(raw_uid, "(RFC822)")
+ if st_f != "OK" or not msg_data:
+ continue
+ raw_bytes = None
+ for part in msg_data:
+ if isinstance(part, tuple) and len(part) >= 2 and part[1]:
+ raw_bytes = part[1]
+ break
+ if not raw_bytes:
+ continue
+ msg = email_mod.message_from_bytes(raw_bytes)
+ except Exception as e:
+ logger.debug(f"sender-thread-context fetch fail uid={uid}: {e}")
+ continue
+
+ try:
+ subj = _decode_header(msg.get("Subject", "(no subject)"))
+ date_hdr = msg.get("Date", "")
+ body_text = (_extract_text(msg) or "").strip()
+ body_text = re.sub(r"\n{3,}", "\n\n", body_text)
+ if len(body_text) > max_chars_per_email:
+ body_text = body_text[:max_chars_per_email].rstrip() + "…"
+ atts_text = _extract_attachment_text(msg, max_chars=max_attachment_chars)
+ except Exception as e:
+ logger.debug(f"sender-thread-context parse fail uid={uid}: {e}")
+ continue
+
+ if not body_text and not atts_text:
+ continue
+
+ lines = [f"— {folder} · {date_hdr} · Subject: {subj}"]
+ if body_text:
+ lines.append(body_text)
+ if atts_text:
+ lines.append(atts_text)
+ blocks.append("\n".join(lines))
+ except Exception as e:
+ logger.warning(f"sender-thread-context: imap failed: {e}")
+ finally:
+ if conn:
+ try: conn.close()
+ except Exception: pass
+ try: conn.logout()
+ except Exception: pass
+
+ if not blocks:
+ return ""
+ return "\n\n=====\n\n".join(blocks)
+
+
+ def _pre_retrieve_context(
+ body: str,
+ sender: str,
+ account_id: str | None = None,
+ owner: str = "",
+ ) -> tuple:
+ """Extract key terms from an incoming email and search past emails + contacts.
+
+ Returns (context_snippets, terms_list). Best-effort; never raises.
+
+ Sec note: this is called from the auto-reply path. An attacker who can
+ craft an inbound email's content to contain Capitalized words matching
+ private context (legal/medical names, project codenames) can coerce the
+ LLM reply to quote that context back in the auto-reply. To narrow the
+ blast radius:
+ - require terms ≥ 5 chars (was 4),
+ - require multiword for an unknown sender,
+ - cap to 3 terms (was 4),
+ - skip entirely for senders with no prior contact / no past mail.
+ """
+ STOPWORDS = {"dear", "hello", "hi", "hey", "thanks", "thank", "regards",
+ "best", "kind", "sincerely", "cheers", "the", "this", "that",
+ "from", "subject", "re", "fwd", "yours", "my", "our", "your"}
+ context_snippets = []
+ terms_list = []
+ try:
+ # ── Known-sender check: only retrieve context for senders we already
+ # have a relationship with. New / cold senders get an empty context.
+ sender_addr = email.utils.parseaddr(sender or "")[1].lower()
+ # The CardDAV address book is global admin data backed by a single
+ # Radicale instance, so only fold it into reply context for an admin /
+ # single-user owner. Non-admin owners still get their own (owner-scoped)
+ # IMAP history below, just not the shared contacts.
+ try:
+ from src.tool_security import owner_is_admin_or_single_user
+ contacts_allowed = owner_is_admin_or_single_user(owner or None)
+ except Exception:
+ contacts_allowed = not bool(owner)
+ is_known = False
+ if contacts_allowed:
+ try:
+ from routes.contacts_routes import _fetch_contacts
+ for c in _fetch_contacts() or []:
+ # Contacts are normalized to plural `emails` lists, but
+ # keep the legacy singular key fallback for older data.
+ contact_emails = []
+ raw_emails = c.get("emails")
+ if isinstance(raw_emails, list):
+ contact_emails.extend(str(e or "") for e in raw_emails)
+ legacy_email = c.get("email")
+ if legacy_email:
+ contact_emails.append(str(legacy_email))
+ if any((addr or "").strip().lower() == sender_addr for addr in contact_emails):
+ is_known = True
+ break
+ except Exception:
+ pass
+ if not is_known and sender_addr:
+ try:
+ with _imap(account_id, owner=owner) as _ck:
+ _ck.select("INBOX", readonly=True)
+ st_known, dk = _ck.search(None, f'(FROM "{sender_addr}")')
+ if st_known == "OK" and dk and dk[0]:
+ is_known = True
+ except Exception:
+ pass
+ if not is_known:
+ logger.info(f"Pre-retrieval skipped — unknown sender {sender_addr}")
+ return [], []
+
+ seen = set()
+ multiword = []
+ singleword = []
+ for m in re.finditer(r"\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+){0,2})\b", body or ""):
+ term = m.group(1).strip()
+ key = term.lower()
+ if key in seen:
+ continue
+ first = term.split()[0].lower()
+ if first in STOPWORDS:
+ continue
+ if len(term) < 5:
+ continue
+ seen.add(key)
+ (multiword if " " in term else singleword).append(term)
+ sender_name_clean = _decode_header(sender or "").split("<")[0].strip().lower()
+ # Multiword terms are far less likely to collide with unrelated context
+ # than single capitalized words. Prefer them; only fall back to
+ # singletons when we don't have enough multiwords.
+ ranked = [t for t in (multiword + singleword) if t.lower() != sender_name_clean]
+ terms_list = ranked[:3]
+ logger.info(f"Pre-retrieval terms={terms_list}")
+
+ if not terms_list:
+ return context_snippets, terms_list
+
+ ctx_conn = None
+ try:
+ ctx_conn = _imap_connect(account_id, owner=owner)
+ for folder in ["INBOX", "Sent", "Archive", "Drafts"]:
+ try:
+ st_sel, _sd = ctx_conn.select(_q(folder), readonly=True)
+ if st_sel != "OK":
+ continue
+ except Exception:
+ continue
+ for term in terms_list:
+ try:
+ safe_term = term.replace('"', '').replace('\\', '')
+ st, data2 = ctx_conn.search(None, "TEXT", f'"{safe_term}"')
+ if st != "OK" or not data2 or not data2[0]:
+ continue
+ all_hits = data2[0].split()
+ hit_uids = all_hits[-2:]
+ logger.info(f" [{folder}] term={term!r} hits={len(all_hits)}")
+ for huid in hit_uids:
+ try:
+ st2, hd = ctx_conn.fetch(huid, "(RFC822)")
+ if st2 != "OK" or not hd or not hd[0]:
+ continue
+ hmsg = email_mod.message_from_bytes(hd[0][1])
+ hsubj = _decode_header(hmsg.get("Subject", ""))
+ hfrom = _decode_header(hmsg.get("From", ""))
+ hdate = hmsg.get("Date", "")
+ hbody = _extract_text(hmsg)[:600]
+ context_snippets.append(
+ f"[{folder} match for \"{term}\"]\nFrom: {hfrom}\nDate: {hdate}\nSubject: {hsubj}\n{hbody}"
+ )
+ except Exception:
+ continue
+ except Exception as _e:
+ logger.warning(f" search {folder} {term!r} failed: {_e}")
+ continue
+ except Exception as _e:
+ logger.warning(f"IMAP context search failed: {_e}")
+ finally:
+ if ctx_conn:
+ try: ctx_conn.logout()
+ except Exception: pass
+
+ try:
+ from routes.contacts_routes import _fetch_contacts
+ all_contacts = _fetch_contacts() if contacts_allowed else []
+ for term in terms_list:
+ t_lower = term.lower()
+ matches = [c for c in all_contacts
+ if t_lower in (c.get("name") or "").lower()
+ or any(t_lower in (e or "").lower() for e in (c.get("emails") or []))]
+ for c in matches[:2]:
+ parts = [f"Name: {c.get('name','')}"]
+ if c.get("emails"):
+ parts.append(f"Email: {', '.join(c['emails'])}")
+ if c.get("phones"):
+ parts.append(f"Phone: {', '.join(c['phones'])}")
+ context_snippets.append(f"[Contact match for \"{term}\"] " + ", ".join(parts))
+ except Exception:
+ pass
+ except Exception as e:
+ logger.warning(f"Pre-retrieval failed: {e}")
+ logger.info(f"Pre-retrieval snippets={len(context_snippets)}")
+ return context_snippets, terms_list
+
+
+ _EMAIL_REPLY_SYS_PROMPT_BASE = (
+ "You are drafting an email reply. Write only the reply body, no subject line, "
+ "and no extra commentary. The saved WRITING STYLE below outranks generic tone guidance. "
+ "If the saved style says to use a greeting/sign-off, include them. For English replies, "
+ "default to 'Hi [Name]' rather than 'Hey'. Be direct and concise. Match the tone of the "
+ "original email without violating the saved style.\n\n"
+ "MECHANICAL STYLE RULES — CRITICAL: Never use an em dash or en dash; use -- instead. "
+ "Never use curly apostrophes; write I'm, don't, we'll with straight '. Do not start "
+ "with 'Hey' unless the saved style explicitly requests it.\n\n"
+ "IDENTITY RULE — CRITICAL: write as the user/mailbox owner only. NEVER sign as, "
+ "speak as, or imply you are the recipient, original sender, quoted sender, spouse, "
+ "assistant, company, or any third party. Do not copy a name from the quoted thread "
+ "into the sign-off. If a writing style below names a signature, use only that "
+ "signature; otherwise omit the sign-off.\n\n"
+ "CRITICAL RULE: NEVER invent facts, names, dates, phone numbers, emails, addresses, "
+ "or any specifics not explicitly present in the RELEVANT CONTEXT section below or "
+ "the original email itself. If the sender asks for information you don't have in "
+ "the context, say plainly that you don't have it on hand — do NOT guess or fabricate. "
+ "Do not promise to 'look it up' or 'get back to you soon' as a way to pad the reply. "
+ "If you have no real information to offer, write a short honest reply (2-4 sentences max).\n\n"
+ "OUTPUT FORMAT — IMPORTANT: Put ONLY the final email reply between these exact markers, "
+ "each on its own line:\n"
+ "<<<REPLY>>>\n"
+ "(the reply body goes here)\n"
+ "<<<END>>>\n"
- "Any reasoning, planning, or notes-to-self must come BEFORE the <<<REPLY>>> marker "
- "(ideally wrapped in <think>...</think>). Only the text between <<<REPLY>>> and <<<END>>> "
- "is sent as the email — nothing else is shown to anyone."
++ "Start with <<<REPLY>>> immediately. Do not output reasoning, planning, or notes-to-self. "
++ "Only the final reply belongs between <<<REPLY>>> and <<<END>>>."
+ )
+
+
+ # ── Request models ──
+
+ class SendEmailRequest(BaseModel):
+ to: str
+ cc: Optional[str] = None
+ bcc: Optional[str] = None
+ subject: str
+ body: str
+ # WYSIWYG compose sends the rendered HTML here; the server sanitizes it and
+ # uses it for the text/html part (body stays the plain-text fallback). When
+ # absent, the server renders markdown from `body` instead.
+ body_html: Optional[str] = None
+ in_reply_to: Optional[str] = None
+ references: Optional[str] = None
+ # List of uploaded attachment tokens (filenames in COMPOSE_UPLOADS_DIR)
+ attachments: Optional[List[str]] = None
+ # Which account to send from. None = default account.
+ account_id: Optional[str] = None
+ # Source message for replies. When present, /send marks this exact message
+ # answered after successful delivery so it leaves undone/reply-soon views.
+ source_uid: Optional[str] = None
+ source_folder: Optional[str] = None
+ # Exact IMAP draft to remove after successful delivery.
+ draft_uid: Optional[str] = None
+ draft_folder: Optional[str] = None
+ # Internal marker for Odysseus-generated mail (e.g. reminder, scheduled).
+ odysseus_kind: Optional[str] = None
+ # If true, /send waits for SMTP + Sent append and returns the sent UID.
+ wait_for_delivery: bool = False
+
+
+ class ExtractStyleRequest(BaseModel):
+ sample_count: Optional[int] = 20
diff --cc routes/email/email_routes.py
index 000000000,f58de5d5b..9422221dc
mode 000000,100644..100644
--- a/routes/email/email_routes.py
+++ b/routes/email/email_routes.py
@@@ -1,0 -1,7194 +1,7231 @@@
+ """
+ email_routes.py
+
+ FastAPI route handlers for the email feature. All non-route logic
+ (IMAP connection helpers, message parsing, account config, the
+ auto-summarize + scheduled-email pollers, Pydantic models) lives in:
+
+ routes/email_helpers.py — synchronous helpers + models + constants
+ routes/email_pollers.py — background loops, started by `_start_poller`
+
+ Importing from the helpers module brings in everything those route
+ handlers need. The split is mechanical — no behavior change.
+ """
+
+ import asyncio
+ import os
+ import sqlite3 as _sql3
+ import time
+ import email as email_mod
+ import email.header
+ import email.utils
+ import smtplib
+ import ssl
+ import json
+ import re
+ import html
+ import io
+ import zipfile
+ from urllib.parse import parse_qs, unquote, urlparse
+ from html.parser import HTMLParser as _HTMLParser
+ import logging
+ import uuid
+ from datetime import datetime
+ from pathlib import Path
+
+ from email.mime.text import MIMEText
+ from email.mime.multipart import MIMEMultipart
+
+ from fastapi import APIRouter, Query, UploadFile, File, BackgroundTasks, HTTPException, Depends, Request
+ from fastapi.responses import FileResponse, StreamingResponse
+ from src.constants import DATA_DIR
+
+ from src.llm_core import llm_call_async
+ from src.upload_limits import read_upload_limited, EMAIL_COMPOSE_UPLOAD_MAX_BYTES
+
+ from .email_helpers import (
+ _strip_think, _extract_reply, _apply_email_style_mechanics, require_owner, require_user, _assert_owns_account,
+ _account_visible_to_owner,
+ _q, _attach_compose_uploads, _cleanup_compose_uploads,
+ _load_settings, _save_settings, _get_email_config,
+ _send_smtp_message, _smtp_security_mode,
+ _IMAP_TIMEOUT_SECONDS, _open_imap_connection,
+ _get_valid_google_token, _xoauth2_bytes, _xoauth2_raw,
+ make_oauth_state, verify_oauth_state,
+ EmailNotConfiguredError,
+ _imap_connect, _imap, _decode_header, _detect_sent_folder, _detect_drafts_folder,
+ _extract_attachment_text, _list_attachments_from_msg, _has_visible_attachments, _is_likely_signature_image_attachment,
+ _extract_attachment_to_disk, _extract_html, _extract_text,
+ _fetch_sender_thread_context, _pre_retrieve_context,
+ _EMAIL_REPLY_SYS_PROMPT_BASE, _POOL_HOOKS,
+ _friendly_email_auth_error, _email_summary_failure_log_detail,
+ _generate_email_summary, EMAIL_SUMMARY_ERROR_CODE, EMAIL_SUMMARY_ERROR_MESSAGE,
+ SendEmailRequest, ExtractStyleRequest,
+ ATTACHMENTS_DIR, COMPOSE_UPLOADS_DIR, SCHEDULED_DB,
+ attachment_extract_dir, _email_cache_owner_clause, email_translation_body_hash,
+ )
+ from .email_pollers import _start_poller
+
+ logger = logging.getLogger(__name__)
+
+ ODYSSEUS_MAIL_ORIGIN = "odysseus-ui"
+ EMAIL_READ_ATTACHMENT_VERSION = 2
+ _GOOGLE_OAUTH_IMAP_HOST = "imap.gmail.com"
+ _GOOGLE_OAUTH_SMTP_HOST = "smtp.gmail.com"
+ _SERVER_OWNED_OAUTH_FIELDS = {
+ "oauth_provider",
+ "oauth_access_token",
+ "oauth_refresh_token",
+ "oauth_token_expiry",
+ }
+
+
+ def _normalized_mail_host(value) -> str:
+ """Normalize a mail hostname for exact provider-bound comparisons."""
+ return str(value or "").strip().lower().rstrip(".")
+
+
+ def _google_oauth_imap_transport_allowed(port: int, starttls: bool) -> bool:
+ return (port == 993 and not starttls) or (port == 143 and starttls)
+
+
+ def _google_oauth_smtp_transport_allowed(port: int, security: str) -> bool:
+ return (port == 465 and security == "ssl") or (port == 587 and security == "starttls")
+
+ def _email_style_key(account_id: str | None) -> str:
+ return str(account_id or "").strip()
+
+
+ def _get_email_writing_style_for_account(settings: dict, account_id: str | None = None) -> str:
+ key = _email_style_key(account_id)
+ by_account = settings.get("email_writing_styles_by_account") or {}
+ if key and isinstance(by_account, dict):
+ val = by_account.get(key)
+ if isinstance(val, str) and val.strip():
+ return val
+ return str(settings.get("email_writing_style") or "")
+
+
+ def _set_email_writing_style_for_account(settings: dict, style: str, account_id: str | None = None) -> None:
+ key = _email_style_key(account_id)
+ style = str(style or "")
+ if key:
+ by_account = settings.get("email_writing_styles_by_account")
+ if not isinstance(by_account, dict):
+ by_account = {}
+ by_account[key] = style
+ settings["email_writing_styles_by_account"] = by_account
+ return
+ settings["email_writing_style"] = style
+
+
+ def _get_email_view_inline_images(settings: dict, account_id: str | None = None) -> bool:
+ """Return the mailbox preference for automatically showing embedded images."""
+ key = _email_style_key(account_id)
+ by_account = settings.get("email_view_inline_images_by_account") or {}
+ if key and isinstance(by_account, dict) and key in by_account:
+ return bool(by_account[key])
+ # Keep a possible legacy/global value useful during the transition. A
+ # missing preference deliberately defaults to enabled.
+ return bool(settings.get("email_view_inline_images", True))
+
+
+ def _set_email_view_inline_images(settings: dict, enabled: bool, account_id: str | None = None) -> None:
+ key = _email_style_key(account_id)
+ if key:
+ by_account = settings.get("email_view_inline_images_by_account")
+ if not isinstance(by_account, dict):
+ by_account = {}
+ by_account[key] = bool(enabled)
+ settings["email_view_inline_images_by_account"] = by_account
+ else:
+ settings["email_view_inline_images"] = bool(enabled)
+
+
+ _AUTO_REPLY_BOOL_KEYS = {
+ "email_auto_reply",
+ "email_auto_reply_exclude_automated",
+ "email_auto_reply_pause_notifications",
+ }
+ _AUTO_REPLY_TEXT_KEYS = {
+ "email_auto_reply_start",
+ "email_auto_reply_end",
+ "email_auto_reply_subject",
+ "email_auto_reply_message",
+ "email_auto_reply_cooldown",
+ "email_auto_reply_scope",
+ "email_auto_reply_account_id",
+ "email_auto_reply_enabled_at",
+ }
+ _AUTO_REPLY_KEYS = _AUTO_REPLY_BOOL_KEYS | _AUTO_REPLY_TEXT_KEYS
+
+
+ def _get_auto_reply_settings_for_account(settings: dict, account_id: str | None = None) -> dict:
+ key = _email_style_key(account_id)
+ out = {k: settings.get(k) for k in _AUTO_REPLY_KEYS if k in settings}
+ by_account = settings.get("email_auto_reply_by_account") or {}
+ if key and isinstance(by_account, dict) and isinstance(by_account.get(key), dict):
+ out.update({k: v for k, v in by_account[key].items() if k in _AUTO_REPLY_KEYS})
+ return out
+
+
+ def _set_auto_reply_settings_for_account(settings: dict, data: dict, account_id: str | None = None) -> tuple[bool, bool]:
+ key = _email_style_key(account_id)
+ target = _get_auto_reply_settings_for_account(settings, account_id) if key else settings
+ prev_auto_reply = bool(target.get("email_auto_reply", False))
+ for name in _AUTO_REPLY_BOOL_KEYS:
+ if name in data:
+ target[name] = bool(data[name])
+ for name in _AUTO_REPLY_TEXT_KEYS - {"email_auto_reply_enabled_at"}:
+ if name in data:
+ target[name] = str(data.get(name) or "").strip()
+ if "email_auto_reply" in data:
+ next_auto_reply = bool(target.get("email_auto_reply", False))
+ if next_auto_reply and (not prev_auto_reply or not str(target.get("email_auto_reply_enabled_at") or "").strip()):
+ target["email_auto_reply_enabled_at"] = datetime.utcnow().isoformat()
+ elif not next_auto_reply:
+ target.pop("email_auto_reply_enabled_at", None)
+ if key:
+ by_account = settings.get("email_auto_reply_by_account")
+ if not isinstance(by_account, dict):
+ by_account = {}
+ by_account[key] = {k: target.get(k) for k in _AUTO_REPLY_KEYS if k in target}
+ by_account[key]["email_auto_reply_account_id"] = key
+ by_account[key]["email_auto_reply_scope"] = "account"
+ settings["email_auto_reply_by_account"] = by_account
+ return prev_auto_reply, bool(target.get("email_auto_reply", False))
+
+
+ def _safe_attachment_zip_name(name: str, fallback: str) -> str:
+ """Return a zip entry filename without path traversal or empty names."""
+ base = Path(str(name or "")).name.strip() or fallback
+ base = re.sub(r"[\x00-\x1f\x7f]+", "_", base)
+ base = base.replace("/", "_").replace("\\", "_").strip(". ") or fallback
+ return base[:180] or fallback
+
+
+ def _coerce_port(value, default):
+ """Coerce a user-supplied port to int.
+
+ Returns ``(port, error)``. A missing or blank value yields ``default``; a
+ non-numeric value yields ``(None, message)`` so callers can return a clean
+ error instead of letting ``int()`` raise and surface as an HTTP 500.
+ """
+ if value in (None, ""):
+ return default, None
+ try:
+ return int(value), None
+ except (TypeError, ValueError):
+ return None, f"Invalid port {value!r}; must be a whole number"
+
+
+ def _lock_email_account_owner_mutation(db, *owners: str) -> None:
+ """Delegate account/default serialization to the shared DB primitive."""
+ from core.database import lock_email_account_owner_mutations
+
+ lock_email_account_owner_mutations(db, *owners)
+
+
+ def _email_account_owner_scope(query, owner: str):
+ """Restrict a query to one normalized EmailAccount owner partition."""
+ from core.database import EmailAccount
+ from sqlalchemy import or_
+
+ if owner:
+ return query.filter(EmailAccount.owner == owner)
+ return query.filter(or_(EmailAccount.owner == None, EmailAccount.owner == "")) # noqa: E711
+
+
+ def _discover_email_account_mutation_scope(account_id: str, owner: str) -> str:
+ """Read the initial lock key and fail closed before a mutation session."""
+ from core.database import EmailAccount, SessionLocal
+
+ db = SessionLocal()
+ try:
+ row = db.get(EmailAccount, account_id)
+ if row is None or (owner and not _account_visible_to_owner(row, owner)):
+ raise HTTPException(404, "Account not found")
+ return row.owner or ""
+ except HTTPException:
+ raise
+ except Exception as exc:
+ logger.error("Account-owner mutation check failed: %s", exc)
+ raise HTTPException(503, "Account check failed")
+ finally:
+ db.close()
+
+
+ def _lock_and_reload_email_account(db, account_id: str, owner: str, scope: str):
+ """Lock, reload, and revalidate an account, retrying if its owner moved."""
+ from core.database import EmailAccount
+
+ owner_scopes = {scope or ""}
+ while True:
+ _lock_email_account_owner_mutation(db, *owner_scopes)
+ row = db.get(EmailAccount, account_id, populate_existing=True)
+ if row is None or (owner and not _account_visible_to_owner(row, owner)):
+ raise HTTPException(404, "Account not found")
+
+ current_scope = row.owner or ""
+ if current_scope in owner_scopes or db.get_bind().dialect.name == "sqlite":
+ return row
+
+ # The account changed owner after discovery but before lock acquisition.
+ # Release the partial lock set and reacquire all observed scopes in the
+ # shared helper's canonical order, then validate from the database again.
+ db.rollback()
+ owner_scopes.add(current_scope)
+
+
+ def _email_tag_owner_aliases(account_id: str | None, owner: str = "") -> list[str]:
+ aliases = [owner or ""]
+ try:
+ from core.database import SessionLocal as _SL, EmailAccount as _EA
+ db = _SL()
+ try:
+ resolved_account_id = account_id
+ if not resolved_account_id:
+ try:
+ cfg = _get_email_config(None, owner=owner)
+ resolved_account_id = cfg.get("account_id") or None
+ aliases.extend([
+ cfg.get("imap_user") or "",
+ cfg.get("smtp_user") or "",
+ cfg.get("from_address") or "",
+ ])
+ except Exception as _e:
+ logger.warning("Failed to resolve email account alias", exc_info=_e)
+ resolved_account_id = None
+ row = db.get(_EA, resolved_account_id) if resolved_account_id else None
+ if row:
+ aliases.extend([row.owner or "", row.imap_user or "", row.from_address or ""])
+ finally:
+ db.close()
+ except Exception as _e:
+ logger.warning("Failed to load email aliases", exc_info=_e)
+ out = []
+ for a in aliases:
+ a = (a or "").strip()
+ if a not in out:
+ out.append(a)
+ return out or [""]
+
+
+ def _email_tag_owner_clause(account_id: str | None, owner: str = "") -> tuple[str, list[str]]:
+ aliases = _email_tag_owner_aliases(account_id, owner)
+ placeholders = ",".join("?" * len(aliases))
+ # In configured multi-user mode, do not treat legacy owner='' rows as
+ # visible to everyone. Single-user/unconfigured mode keeps legacy rows.
+ if owner:
+ return f"owner IN ({placeholders})", aliases
+ return f"(owner IN ({placeholders}) OR owner IS NULL)", aliases
+
+
+ def _email_tag_account_clause(account_id: str | None) -> tuple[str, list[str]]:
+ account = (account_id or "").strip()
+ if account:
+ return "(account_id=? OR account_id='' OR account_id IS NULL)", [account]
+ # No explicit account means the caller is using the default/all-account
+ # view. Keep the owner clause as the boundary, but do not hide tags that
+ # were written under a concrete account id for the same message.
+ return "1=1", []
+
+
+ _VISIBLE_EMAIL_TAGS = {"urgent", "reply-soon", "action-needed", "calendar", "bills", "receipt", "travel"}
+ _DONE_RESPONSE_TAGS = {"urgent", "reply-soon", "action-needed"}
+
+
+ def _sanitize_visible_email_tags(tags, *, is_answered: bool = False) -> list[str]:
+ out = []
+ for tag in tags if isinstance(tags, list) else []:
+ tag = str(tag or "").strip().lower().replace("_", "-")
+ if tag == "promo":
+ tag = "marketing"
+ if tag not in _VISIBLE_EMAIL_TAGS:
+ continue
+ if is_answered and tag in _DONE_RESPONSE_TAGS:
+ continue
+ if tag not in out:
+ out.append(tag)
+ return out
+
+
+ def _hide_unlinked_calendar_tags(emails: list[dict]) -> None:
+ for e in emails or []:
+ if not isinstance(e.get("tags"), list):
+ continue
+ if "calendar" in e.get("tags", []) and not e.get("calendar_event_uids"):
+ e["tags"] = [t for t in e.get("tags", []) if t != "calendar"]
+
+
+ def _clear_done_response_tags(owner: str, account_id: str | None, folder: str, uid: str) -> None:
+ try:
+ conn = _sql3.connect(SCHEDULED_DB)
+ owner_clause, owner_params = _email_tag_owner_clause(account_id, owner)
+ account_clause, account_params = _email_tag_account_clause(account_id)
+ rows = conn.execute(
+ f"SELECT rowid, tags FROM email_tags WHERE folder=? AND uid=? AND {owner_clause} AND {account_clause}",
+ [folder, str(uid), *owner_params, *account_params],
+ ).fetchall()
+ for rowid, tags_raw in rows:
+ try:
+ tags = json.loads(tags_raw or "[]")
+ except Exception:
+ tags = []
+ if not isinstance(tags, list):
+ tags = []
+ kept = [
+ t for t in tags
+ if str(t).strip().lower().replace("_", "-") not in _DONE_RESPONSE_TAGS
+ ]
+ if kept != tags:
+ conn.execute("UPDATE email_tags SET tags=? WHERE rowid=?", (json.dumps(kept), rowid))
+ conn.commit()
+ conn.close()
+ except Exception as e:
+ logger.debug(f"clear done response tags skipped: {e}")
+
+
+ def _record_email_received_events(owner: str, account_id: str | None, folder: str, emails: list[dict]):
+ """Baseline inbox messages, then fire `email_received` for new arrivals."""
+ # AUTH_ENABLED=false single-user deployments intentionally have no owner;
+ # the concrete mailbox account still provides the required scope.
+ if not account_id or (folder or "INBOX").upper() != "INBOX" or not emails:
+ return
+ try:
+ from src.event_bus import fire_event
+ account_key = (account_id or "default").strip() or "default"
+ now = datetime.utcnow().isoformat() + "Z"
+ keys = []
+ for e in emails:
+ key = (e.get("message_id") or e.get("uid") or "").strip()
+ if key and key not in keys:
+ keys.append(key)
+ if not keys:
+ return
+
+ conn = _sql3.connect(SCHEDULED_DB)
+ try:
+ conn.execute(
+ "CREATE TABLE IF NOT EXISTS email_event_seen ("
+ "owner TEXT NOT NULL, account_key TEXT NOT NULL, folder TEXT NOT NULL, "
+ "message_key TEXT NOT NULL, first_seen_at TEXT NOT NULL, "
+ "PRIMARY KEY (owner, account_key, folder, message_key))"
+ )
+ count = conn.execute(
+ "SELECT COUNT(*) FROM email_event_seen WHERE owner=? AND account_key=? AND folder=?",
+ (owner, account_key, folder),
+ ).fetchone()[0]
+ existing = set()
+ if count:
+ placeholders = ",".join("?" * len(keys))
+ rows = conn.execute(
+ f"SELECT message_key FROM email_event_seen "
+ f"WHERE owner=? AND account_key=? AND folder=? AND message_key IN ({placeholders})",
+ (owner, account_key, folder, *keys),
+ ).fetchall()
+ existing = {r[0] for r in rows}
+ new_keys = [k for k in keys if k not in existing]
+ conn.executemany(
+ "INSERT OR IGNORE INTO email_event_seen "
+ "(owner, account_key, folder, message_key, first_seen_at) VALUES (?, ?, ?, ?, ?)",
+ [(owner, account_key, folder, k, now) for k in keys],
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+ if count and new_keys:
+ for _ in new_keys[:50]:
+ fire_event("email_received", owner)
+ logger.info("Fired email_received for %d new message(s)", min(len(new_keys), 50))
+ try:
+ loop = asyncio.get_running_loop()
+
+ async def _run_away_reply_check():
+ try:
+ from .email_pollers import _auto_summarize_pass
+ result = await _auto_summarize_pass(
+ days_back=1,
+ account_id=account_id,
+ max_process=min(max(len(new_keys), 1), 5),
+ away_only=True,
+ )
+ logger.info("Auto away-reply pass after email_received account=%s: %s", account_id, result)
+ except Exception:
+ logger.warning("Auto away-reply pass after email_received failed", exc_info=True)
+
+ loop.create_task(_run_away_reply_check())
+ except RuntimeError:
+ logger.debug("No running event loop for immediate away-reply check")
+ except Exception:
+ logger.debug("email_received event detection skipped", exc_info=True)
+
+
+ def _folder_name_from_list_line(line) -> str | None:
+ decoded = line.decode() if isinstance(line, bytes) else str(line)
+ match = re.search(r'"([^"]*)"\s*$|(\S+)\s*$', decoded)
+ if not match:
+ return None
+ return match.group(1) or match.group(2)
+
+
+ def _list_imap_folders(conn) -> tuple[list, list[str]]:
+ try:
+ status, folders = conn.list()
+ if status != "OK" or not folders:
+ return [], []
+ names = [name for name in (_folder_name_from_list_line(f) for f in folders) if name]
+ return folders, names
+ except Exception:
+ return [], []
+
+
+ def _resolve_mail_folder(conn, preferred: str, role: str = "") -> str:
+ """Resolve provider-specific names such as Gmail's [Gmail]/Bin/Spam."""
+ folders, names = _list_imap_folders(conn)
+ if preferred and preferred in names:
+ return preferred
+ role_flags = {
+ "trash": ("\\Trash",),
+ "archive": ("\\Archive", "\\All"),
+ "junk": ("\\Junk",),
+ "sent": ("\\Sent",),
+ "drafts": ("\\Drafts",),
+ "starred": ("\\Flagged",),
+ }.get(role, ())
+ for f in folders:
+ decoded = f.decode() if isinstance(f, bytes) else str(f)
+ if any(flag in decoded for flag in role_flags):
+ name = _folder_name_from_list_line(f)
+ if name:
+ return name
+ candidates = {
+ "trash": ("Trash", "[Gmail]/Trash", "[Google Mail]/Trash", "Bin", "[Gmail]/Bin", "Deleted Messages", "Deleted Items"),
+ "archive": ("Archive", "Archives", "[Gmail]/All Mail", "[Google Mail]/All Mail", "All Mail"),
+ "junk": ("Junk", "Spam", "[Gmail]/Spam", "[Google Mail]/Spam"),
+ "sent": ("Sent", "[Gmail]/Sent Mail", "[Google Mail]/Sent Mail", "Sent Mail", "Sent Items", "INBOX.Sent"),
+ "drafts": ("Drafts", "[Gmail]/Drafts", "[Google Mail]/Drafts", "Draft", "INBOX.Drafts"),
+ "starred": ("Starred", "[Gmail]/Starred", "[Google Mail]/Starred", "Flagged"),
+ }.get(role, ())
+ lower_map = {n.lower(): n for n in names}
+ for candidate in candidates:
+ found = lower_map.get(candidate.lower())
+ if found:
+ return found
+ return preferred
+
+
+ def _mail_folder_role_hint(name: str) -> str:
+ lower = (name or "").strip().lower()
+ if lower in {"archive", "archives", "all mail", "archive / all mail"}:
+ return "archive"
+ if lower in {"sent", "sent mail", "sent items", "outbox"}:
+ return "sent"
+ if lower in {"draft", "drafts"}:
+ return "drafts"
+ if lower in {"starred", "favorites", "flagged"}:
+ return "starred"
+ if lower in {"junk", "spam"}:
+ return "junk"
+ if lower in {"trash", "bin", "deleted", "deleted items", "deleted messages"}:
+ return "trash"
+ return ""
+
+
+ def _folder_role_from_name(name: str) -> str:
+ lower = (name or "").lower()
+ if "trash" in lower or "bin" in lower or "deleted" in lower:
+ return "trash"
+ if "spam" in lower or "junk" in lower:
+ return "junk"
+ if "archive" in lower or "all mail" in lower:
+ return "archive"
+ return ""
+
+
+ def _uid_bytes(uid: str | bytes) -> bytes:
+ return uid if isinstance(uid, bytes) else str(uid).encode()
+
+
+ def _uid_exists(conn, uid: str, *, strict: bool = False) -> bool:
+ try:
+ status, data = conn.uid("FETCH", _uid_bytes(uid), "(UID)")
+ if status == "OK":
+ for part in data or []:
+ meta = part[0] if isinstance(part, tuple) else part
+ meta_b = meta if isinstance(meta, bytes) else str(meta).encode()
+ if re.search(rb"\bUID\s+\d+\b", meta_b):
+ return True
+ # A few IMAP servers do not return UID metadata for a FETCH probe,
+ # while their UID SEARCH implementation is reliable.
+ status, data = conn.uid("SEARCH", None, f"UID {uid}")
+ if strict and status != "OK":
+ raise RuntimeError("Email UID lookup failed")
+ return status == "OK" and bool(data and data[0] and _uid_bytes(uid) in data[0].split())
+ except Exception:
+ if strict:
+ raise
+ return False
+
+
+ def _resolve_current_email_uid(conn, uid: str, message_id: str | None = None) -> str:
+ """Resolve a stale cached UID by the message's stable RFC Message-ID."""
+ uid = str(uid or "").strip()
+ if uid and _uid_exists(conn, uid, strict=True):
+ return uid
+ message_id = str(message_id or "").strip()
+ if not message_id:
+ return ""
+ try:
+ status, data = _imap_uid_search(conn, f"(HEADER Message-ID {_imap_search_quote(message_id)})")
+ if status != "OK":
+ raise RuntimeError("Email Message-ID lookup failed")
+ if status == "OK" and data and data[0]:
+ matches = data[0].split()
+ if matches:
+ return matches[-1].decode(errors="ignore") if isinstance(matches[-1], bytes) else str(matches[-1])
+ except Exception:
+ logger.debug("Could not resolve stale email UID by Message-ID", exc_info=True)
+ raise
+ return ""
+
+
+ def _imap_uid_search(conn, criteria: str):
+ return conn.uid("SEARCH", None, criteria)
+
+
+ def _imap_uid_fetch(conn, uid_set: str | bytes, query: str):
+ return conn.uid("FETCH", _uid_bytes(uid_set), query)
+
+
+ def _imap_search_quote(value: str) -> str:
+ return '"' + str(value or "").replace("\\", "\\\\").replace('"', '\\"') + '"'
+
+
+ def _message_id_chain(*values: str) -> list[str]:
+ seen = set()
+ out = []
+ for value in values:
+ for mid in re.findall(r"<[^>]+>", value or ""):
+ if mid not in seen:
+ seen.add(mid)
+ out.append(mid)
+ return out
+
+
+ def _uid_from_fetch_meta(meta_b: bytes) -> str:
+ m = re.search(rb"\bUID\s+(\d+)\b", meta_b)
+ return m.group(1).decode() if m else ""
+
+
+ def _parse_list_unsubscribe_header(value: str | None) -> list[dict]:
+ """Parse RFC List-Unsubscribe entries into safe reviewable actions.
+
+ We return mailto/http entries but only the mailto kind is executable by the
+ first-pass Odysseus flow. HTTP unsubscribe links are useful evidence but
+ often contain tracking tokens and should be opened manually unless/until we
+ add a browser-confirmed flow.
+ """
+ raw = str(value or "").strip()
+ if not raw:
+ return []
+ pieces = re.findall(r"<([^>]+)>", raw)
+ if not pieces:
+ pieces = [p.strip() for p in raw.split(",") if p.strip()]
+ out: list[dict] = []
+ seen = set()
+ for piece in pieces:
+ target = piece.strip().strip("<>").strip()
+ if not target:
+ continue
+ parsed = urlparse(target)
+ scheme = parsed.scheme.lower()
+ key = target.lower()
+ if key in seen:
+ continue
+ seen.add(key)
+ if scheme == "mailto":
+ addr = unquote(parsed.path or "").strip()
+ if not addr or "\r" in addr or "\n" in addr:
+ continue
+ query = parse_qs(parsed.query or "", keep_blank_values=True)
+ subject = unquote((query.get("subject") or ["unsubscribe"])[0] or "unsubscribe")
+ body = unquote((query.get("body") or ["unsubscribe"])[0] or "unsubscribe")
+ subject = re.sub(r"[\r\n]+", " ", subject).strip() or "unsubscribe"
+ body = re.sub(r"[\r\n]+", "\n", body).strip() or "unsubscribe"
+ out.append({
+ "kind": "mailto",
+ "target": addr,
+ "subject": subject[:200],
+ "body": body[:1000],
+ "executable": True,
+ })
+ elif scheme in {"http", "https"}:
+ out.append({
+ "kind": "url",
+ "target": target,
+ "executable": False,
+ })
+ return out
+
+
+ def _email_unsubscribe_candidate_from_msg(msg, uid: str, folder: str, *, spam_cached: dict | None = None) -> dict | None:
+ sender = _decode_header(msg.get("From", ""))
+ sender_name, sender_addr = email.utils.parseaddr(sender)
+ subject = _decode_header(msg.get("Subject", "(no subject)"))
+ list_id = _decode_header(msg.get("List-Id", ""))
+ precedence = (msg.get("Precedence") or "").strip().lower()
+ auto_submitted = (msg.get("Auto-Submitted") or "").strip().lower()
+ methods = _parse_list_unsubscribe_header(msg.get("List-Unsubscribe"))
+ has_unsub = bool(methods)
+ reasons: list[str] = []
+ score = 0
+ if has_unsub:
+ score += 45
+ reasons.append("has unsubscribe header")
+ if list_id:
+ score += 20
+ reasons.append("mailing-list header")
+ if precedence in {"bulk", "junk", "list"}:
+ score += 20
+ reasons.append(f"precedence={precedence}")
+ if auto_submitted and auto_submitted != "no":
+ score += 10
+ reasons.append(f"auto-submitted={auto_submitted}")
+ if spam_cached and spam_cached.get("spam"):
+ score += 35
+ if spam_cached.get("reason"):
+ reasons.append(str(spam_cached.get("reason")))
+ else:
+ reasons.append("previously classified as spam")
+ subj_l = (subject or "").lower()
+ if re.search(r"\b(unsubscribe|newsletter|sale|discount|offer|promo|limited time)\b", subj_l):
+ score += 10
+ reasons.append("promotional subject")
+ executable = [m for m in methods if m.get("executable")]
+ if score < 45 or not has_unsub:
+ return None
+ return {
+ "uid": str(uid),
+ "folder": folder,
+ "message_id": (msg.get("Message-ID") or "").strip(),
+ "subject": subject,
+ "from_name": sender_name or sender_addr,
+ "from_address": sender_addr,
+ "list_id": list_id,
+ "score": min(score, 100),
+ "reasons": reasons[:5],
+ "methods": methods,
+ "can_execute": bool(executable),
+ "recommended_method": executable[0] if executable else (methods[0] if methods else None),
+ "spam_reason": (spam_cached or {}).get("reason") or "",
+ }
+
+
+ def _unsubscribe_candidate_dedupe_key(candidate: dict) -> tuple[str, str, str]:
+ list_id = str(candidate.get("list_id") or "").strip().lower()
+ method = candidate.get("recommended_method") or {}
+ method_kind = str(method.get("kind") or "").strip().lower()
+ method_target = str(method.get("target") or "").strip().lower()
+ sender = str(candidate.get("from_address") or "").strip().lower()
+ # A sender address is the actionable identity here. Newsletter links are
+ # often tokenized per message, so list/url keys would show the same sender
+ # repeatedly and cause repeated unsubscribe attempts.
+ if sender:
+ return ("sender", sender, "")
+ if list_id:
+ return ("list", list_id, method_target)
+ if method_target:
+ return ("method", method_kind, method_target)
+ return ("sender", "", str(candidate.get("subject") or "").strip().lower())
+
+
+ def _dedupe_unsubscribe_candidates(candidates: list[dict]) -> list[dict]:
+ deduped: dict[tuple[str, str, str], dict] = {}
+ for candidate in candidates or []:
+ key = _unsubscribe_candidate_dedupe_key(candidate)
+ existing = deduped.get(key)
+ if not existing:
+ copy = dict(candidate)
+ copy["duplicate_count"] = 1
+ copy["duplicate_uids"] = [str(candidate.get("uid") or "")]
+ deduped[key] = copy
+ continue
+ existing["duplicate_count"] = int(existing.get("duplicate_count") or 1) + 1
+ uid = str(candidate.get("uid") or "")
+ if uid:
+ existing.setdefault("duplicate_uids", []).append(uid)
+ if int(candidate.get("score") or 0) > int(existing.get("score") or 0):
+ keep_count = existing.get("duplicate_count")
+ keep_uids = existing.get("duplicate_uids")
+ replacement = dict(candidate)
+ replacement["duplicate_count"] = keep_count
+ replacement["duplicate_uids"] = keep_uids
+ deduped[key] = replacement
+ return list(deduped.values())
+
+
+ _FETCH_SEQ_RE = re.compile(rb"^(\d+)\s+\(")
+
+
+ def _group_uid_fetch_records(msg_data) -> list:
+ """Group an imaplib UID FETCH response into per-message (meta, payload).
+
+ imaplib yields an interleaved list: ``(meta, literal)`` tuples for
+ attributes that carry a literal (``RFC822.HEADER {n}`` etc.) plus bare
+ ``bytes`` elements for everything the server sends outside a literal.
+ Where each attribute lands is server-specific: Dovecot sends FLAGS
+ *before* the header literal (so it ends up inside the tuple meta), while
+ Gmail sends FLAGS *after* it, arriving as a bare ``b' FLAGS (\\Seen))'``
+ element. Dropping bare elements therefore silently loses FLAGS on Gmail
+ and every message renders as unread/unflagged.
+
+ A tuple whose meta starts with a sequence number opens a new record;
+ every other part — continuation tuple or bare bytes — is folded into the
+ current record's meta so attribute regexes see the full meta text.
+ Plain ``b')'`` terminators get folded in too, which is harmless.
+ """
+ grouped: list = [] # list of (meta_bytes, payload_bytes_or_None)
+ for part in (msg_data or []):
+ if isinstance(part, tuple):
+ meta_b = part[0] if isinstance(part[0], (bytes, bytearray)) else str(part[0]).encode()
+ if _FETCH_SEQ_RE.match(meta_b):
+ grouped.append((meta_b, part[1]))
+ elif grouped:
+ cur_meta, cur_payload = grouped[-1]
+ grouped[-1] = (cur_meta + b" " + meta_b, cur_payload or part[1])
+ elif isinstance(part, (bytes, bytearray)) and grouped:
+ cur_meta, cur_payload = grouped[-1]
+ grouped[-1] = (cur_meta + b" " + bytes(part), cur_payload)
+ return grouped
+
+
+ def _account_cache_key(account_id: str | None, owner: str = "") -> str:
+ return (account_id or "default").strip() or f"default:{owner or ''}"
+
+
+ def _parse_email_list_record(meta_b: bytes, raw_header: bytes | None) -> dict | None:
+ try:
+ meta = meta_b.decode(errors="replace")
+ uid_num = _uid_from_fetch_meta(meta_b)
+ if not uid_num or not raw_header:
+ return None
+ flag_m = re.search(r'FLAGS \(([^)]*)\)', meta)
+ flags = flag_m.group(1) if flag_m else ""
+ size_m = re.search(r'RFC822\.SIZE (\d+)', meta)
+ size = int(size_m.group(1)) if size_m else 0
+ msg = email_mod.message_from_bytes(raw_header)
+ subject = _decode_header(msg.get("Subject", "(no subject)"))
+ sender = _decode_header(msg.get("From", "unknown"))
+ date_str = msg.get("Date", "")
+ message_id = (msg.get("Message-ID", "") or "").strip()
+ sender_name, sender_addr = email.utils.parseaddr(sender)
+ to_str = _decode_header(msg.get("To", ""))
+ cc_str = _decode_header(msg.get("Cc", ""))
+ parsed_date = email.utils.parsedate_to_datetime(date_str) if date_str else None
+ if parsed_date and parsed_date.tzinfo is None:
+ from datetime import timezone as _tz
+ parsed_date = parsed_date.replace(tzinfo=_tz.utc)
+ iso_date = parsed_date.isoformat() if parsed_date else ""
+ date_epoch = parsed_date.timestamp() if parsed_date else 0.0
+ ct = msg.get("Content-Type", "")
+ # multipart/related usually means HTML + inline signature/logo assets,
+ # not a user attachment. Real file attachments conventionally use a
+ # multipart/mixed top-level container. A later MIME metadata fetch
+ # replaces this conservative header-only estimate with an exact value.
+ has_attachments = "multipart/mixed" in ct.lower()
+ return {
+ "uid": uid_num,
+ "message_id": message_id,
+ "subject": subject,
+ "from_name": sender_name or sender_addr,
+ "from_address": sender_addr,
+ "to": to_str,
+ "cc": cc_str,
+ "date": iso_date,
+ "date_display": date_str,
+ "date_epoch": date_epoch,
+ "size": size,
+ "is_read": "\\Seen" in flags,
+ "is_answered": "\\Answered" in flags,
+ "is_flagged": "\\Flagged" in flags,
+ "flags": flags,
+ "has_attachments": has_attachments,
+ }
+ except Exception as e:
+ logger.warning(f"Error parsing email index entry: {e}")
+ return None
+
+
+ def _email_index_rows(owner: str, account_id: str | None, folder: str, uids: list[str]) -> dict[str, dict]:
+ if not uids:
+ return {}
+ try:
+ conn = _sql3.connect(SCHEDULED_DB)
+ try:
+ placeholders = ",".join("?" * len(uids))
+ rows = conn.execute(
+ f"""
+ SELECT uid, message_id, subject, from_name, from_address, to_text, cc_text,
+ date_iso, date_display, date_epoch, size, flags, has_attachments
+ FROM email_message_index
+ WHERE owner=? AND account_key=? AND folder=? AND uid IN ({placeholders})
+ """,
+ [owner or "", _account_cache_key(account_id, owner), folder, *uids],
+ ).fetchall()
+ finally:
+ conn.close()
+ except Exception as e:
+ logger.debug(f"email index read skipped: {e}")
+ return {}
+ out: dict[str, dict] = {}
+ for row in rows:
+ uid, message_id, subject, from_name, from_address, to_text, cc_text, date_iso, date_display, date_epoch, size, flags, has_attachments = row
+ flags = flags or ""
+ out[str(uid)] = {
+ "uid": str(uid),
+ "message_id": (message_id or "").strip(),
+ "subject": subject or "(no subject)",
+ "from_name": from_name or from_address or "",
+ "from_address": from_address or "",
+ "to": to_text or "",
+ "cc": cc_text or "",
+ "date": date_iso or "",
+ "date_display": date_display or "",
+ "date_epoch": float(date_epoch or 0),
+ "size": int(size or 0),
+ "is_read": "\\Seen" in flags,
+ "is_answered": "\\Answered" in flags,
+ "is_flagged": "\\Flagged" in flags,
+ "flags": flags,
+ "has_attachments": bool(has_attachments),
+ }
+ return out
+
+
+ def _email_index_list(owner: str, account_id: str | None, folder: str, filter_: str, limit: int, offset: int, has_attachments: bool = False) -> tuple[list[dict], int, str | None]:
+ """Return a newest-first page from the durable local email index.
+
+ This is intentionally a paint-fast cache path for the UI, not the source of
+ truth. The normal IMAP list still runs after this in the browser to refresh
+ flags/new mail.
+ """
+ limit = max(1, min(int(limit or 50), 200))
+ offset = max(0, int(offset or 0))
+ account_key = _account_cache_key(account_id, owner)
+ clauses = ["owner=?", "account_key=?", "folder=?"]
+ params: list = [owner or "", account_key, folder]
+ if filter_ == "unread":
+ clauses.append("(flags IS NULL OR instr(flags, '\\Seen') = 0)")
+ elif filter_ in {"unanswered", "undone"}:
+ clauses.append("(flags IS NULL OR instr(flags, '\\Answered') = 0)")
+ elif filter_ == "favorites":
+ clauses.append("instr(COALESCE(flags, ''), '\\Flagged') > 0")
+ elif filter_ not in {"all", "", None}:
+ return [], 0, None
+ if has_attachments:
+ clauses.append("has_attachments=1")
+ where = " AND ".join(clauses)
+ try:
+ conn = _sql3.connect(SCHEDULED_DB)
+ try:
+ total_row = conn.execute(
+ f"SELECT COUNT(*), MAX(updated_at) FROM email_message_index WHERE {where}",
+ params,
+ ).fetchone()
+ total = int((total_row or [0])[0] or 0)
+ if not total:
+ return [], 0, (total_row or [None, None])[1]
+ rows = conn.execute(
+ f"""
+ SELECT uid, message_id, subject, from_name, from_address, to_text, cc_text,
+ date_iso, date_display, date_epoch, size, flags, has_attachments
+ FROM email_message_index
+ WHERE {where}
+ ORDER BY date_epoch DESC
+ LIMIT ? OFFSET ?
+ """,
+ [*params, limit, offset],
+ ).fetchall()
+ finally:
+ conn.close()
+ except Exception:
+ logger.debug("email index list skipped", exc_info=True)
+ return [], 0, None
+
+ emails: list[dict] = []
+ for row in rows:
+ uid, message_id, subject, from_name, from_address, to_text, cc_text, date_iso, date_display, date_epoch, size, flags, has_attachments_raw = row
+ flags = flags or ""
+ emails.append({
+ "uid": str(uid),
+ "message_id": (message_id or "").strip(),
+ "subject": subject or "(no subject)",
+ "from_name": from_name or from_address or "",
+ "from_address": from_address or "",
+ "to": to_text or "",
+ "cc": cc_text or "",
+ "date": date_iso or "",
+ "date_display": date_display or "",
+ "date_epoch": float(date_epoch or 0),
+ "size": int(size or 0),
+ "is_read": "\\Seen" in flags,
+ "is_answered": "\\Answered" in flags,
+ "is_flagged": "\\Flagged" in flags,
+ "flags": flags,
+ "has_attachments": bool(has_attachments_raw),
+ "folder": folder,
+ })
+ return emails, total, (total_row or [None, None])[1]
+
+
+ def _email_index_search(owner: str, account_id: str | None, folder: str, query: str, limit: int, global_search: bool = True) -> tuple[list[dict], int, str | None]:
+ q = (query or "").strip()
+ if not q:
+ return [], 0, None
+ limit = max(1, min(int(limit or 50), 200))
+ account_key = _account_cache_key(account_id, owner)
+ folder_clause = ""
+ params: list = [owner or "", account_key]
+ # Searching from INBOX should feel global for Gmail-style accounts,
+ # because users expect archived/labelled mail to show up too. The
+ # local index only contains folders that have been warmed/listed, so
+ # this remains a best-effort fast path; IMAP is still the fallback.
+ if not global_search or (folder or "").upper() != "INBOX":
+ folder_clause = "AND folder=?"
+ params.append(folder)
+ terms = _email_search_terms(q)
+ if not terms:
+ return [], 0, None
+ term_clause = " AND ".join([
+ """(
+ subject LIKE ? ESCAPE '\\' OR
+ from_name LIKE ? ESCAPE '\\' OR
+ from_address LIKE ? ESCAPE '\\' OR
+ to_text LIKE ? ESCAPE '\\' OR
+ cc_text LIKE ? ESCAPE '\\' OR
+ attachment_names LIKE ? ESCAPE '\\'
+ )"""
+ for _ in terms
+ ])
+ for term in terms:
+ like = "%" + term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
+ params.extend([like, like, like, like, like, like])
+ try:
+ conn = _sql3.connect(SCHEDULED_DB)
+ try:
+ total_row = conn.execute(
+ f"""
+ SELECT COUNT(*), MAX(updated_at)
+ FROM email_message_index
+ WHERE owner=? AND account_key=? {folder_clause}
+ AND {term_clause}
+ """,
+ params,
+ ).fetchone()
+ total = int((total_row or [0])[0] or 0)
+ if not total:
+ return [], 0, (total_row or [None, None])[1]
+ rows = conn.execute(
+ f"""
+ SELECT uid, message_id, subject, from_name, from_address, to_text, cc_text,
+ date_iso, date_display, date_epoch, size, flags, has_attachments,
+ folder
+ FROM email_message_index
+ WHERE owner=? AND account_key=? {folder_clause}
+ AND {term_clause}
+ ORDER BY date_epoch DESC
+ LIMIT ?
+ """,
+ [*params, limit],
+ ).fetchall()
+ finally:
+ conn.close()
+ except Exception:
+ logger.debug("email index search skipped", exc_info=True)
+ return [], 0, None
+
+ emails: list[dict] = []
+ for row in rows:
+ uid, message_id, subject, from_name, from_address, to_text, cc_text, date_iso, date_display, date_epoch, size, flags, has_attachments, row_folder = row
+ flags = flags or ""
+ emails.append({
+ "uid": str(uid),
+ "message_id": (message_id or "").strip(),
+ "subject": subject or "(no subject)",
+ "from_name": from_name or from_address or "",
+ "from_address": from_address or "",
+ "to": to_text or "",
+ "cc": cc_text or "",
+ "date": date_iso or "",
+ "date_display": date_display or "",
+ "date_epoch": float(date_epoch or 0),
+ "size": int(size or 0),
+ "is_read": "\\Seen" in flags,
+ "is_answered": "\\Answered" in flags,
+ "is_flagged": "\\Flagged" in flags,
+ "flags": flags,
+ "has_attachments": bool(has_attachments),
+ "folder": row_folder or folder,
+ })
+ return emails, total, (total_row or [None, None])[1]
+
+
+ def _email_search_terms(query: str) -> list[str]:
+ q = (query or "").strip()
+ if not q:
+ return []
+ # Preserve quoted phrases, then split the rest. This makes:
+ # honda insurance -> honda AND insurance
+ # "Yoko Honda" insurance -> "Yoko Honda" AND insurance
+ # The cap avoids creating huge IMAP expressions from pasted paragraphs.
+ parts = []
+ consumed = []
+ for m in re.finditer(r'"([^"]{1,120})"', q):
+ phrase = m.group(1).strip()
+ if phrase:
+ parts.append(phrase)
+ consumed.append((m.start(), m.end()))
+ remainder = q
+ for start, end in reversed(consumed):
+ remainder = remainder[:start] + " " + remainder[end:]
+ parts.extend(re.findall(r"[^\s,;]+", remainder))
+ out = []
+ seen = set()
+ for p in parts:
+ p = p.strip().strip('"').strip()
+ if len(p) < 2:
+ continue
+ key = p.lower()
+ if key in seen:
+ continue
+ seen.add(key)
+ out.append(p)
+ if len(out) >= 6:
+ break
+ return out
+
+
+ def _imap_or_many(keys: list[str]) -> str:
+ if not keys:
+ return "ALL"
+ expr = keys[0]
+ for key in keys[1:]:
+ expr = f"OR ({expr}) ({key})"
+ return expr
+
+
+ def _email_imap_search_criteria(query: str) -> str:
+ terms = _email_search_terms(query)
+ if not terms:
+ return "ALL"
+ term_exprs = []
+ for term in terms:
+ q = _imap_search_quote(term)
+ # Search both sides of the conversation, plus subject and body. The
+ # older route only searched FROM/SUBJECT/TEXT, so recipient searches
+ # and many sent-message searches felt broken.
+ # Some providers do not include MIME part headers in TEXT searches.
+ # Explicitly search both standard filename-bearing MIME headers so
+ # attachment-name lookup works even when the body does not mention it.
+ term_exprs.append(f"({_imap_or_many([f'FROM {q}', f'TO {q}', f'CC {q}', f'SUBJECT {q}', f'TEXT {q}', f'HEADER Content-Disposition {q}', f'HEADER Content-Type {q}'])})")
+ return "(" + " ".join(term_exprs) + ")"
+
+
+ def _email_index_upsert(owner: str, account_id: str | None, folder: str, emails: list[dict]):
+ if not emails:
+ return
+ now = datetime.utcnow().isoformat() + "Z"
+ rows = []
+ for e in emails:
+ uid = str(e.get("uid") or "").strip()
+ if not uid:
+ continue
+ rows.append((
+ owner or "",
+ _account_cache_key(account_id, owner),
+ folder,
+ uid,
+ (e.get("message_id") or "").strip(),
+ e.get("subject") or "",
+ e.get("from_name") or "",
+ e.get("from_address") or "",
+ e.get("to") or "",
+ e.get("cc") or "",
+ e.get("date") or "",
+ e.get("date_display") or "",
+ float(e.get("date_epoch") or 0),
+ int(e.get("size") or 0),
+ e.get("flags") or "",
+ 1 if e.get("has_attachments") else 0,
+ now,
+ ))
+ if not rows:
+ return
+ try:
+ conn = _sql3.connect(SCHEDULED_DB)
+ try:
+ conn.executemany(
+ """
+ INSERT INTO email_message_index
+ (owner, account_key, folder, uid, message_id, subject, from_name,
+ from_address, to_text, cc_text, date_iso, date_display, date_epoch,
+ size, flags, has_attachments, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(owner, account_key, folder, uid) DO UPDATE SET
+ message_id=excluded.message_id,
+ subject=excluded.subject,
+ from_name=excluded.from_name,
+ from_address=excluded.from_address,
+ to_text=excluded.to_text,
+ cc_text=excluded.cc_text,
+ date_iso=excluded.date_iso,
+ date_display=excluded.date_display,
+ date_epoch=excluded.date_epoch,
+ size=excluded.size,
+ flags=excluded.flags,
+ has_attachments=excluded.has_attachments,
+ updated_at=excluded.updated_at
+ """,
+ rows,
+ )
+ conn.commit()
+ finally:
+ conn.close()
+ except Exception as e:
+ logger.debug(f"email index write skipped: {e}")
+
+
+ def _email_index_update_flags(owner: str, account_id: str | None, folder: str, uid: str, flag: str, add: bool):
+ try:
+ conn = _sql3.connect(SCHEDULED_DB)
+ try:
+ row = conn.execute(
+ "SELECT flags FROM email_message_index WHERE owner=? AND account_key=? AND folder=? AND uid=?",
+ (owner or "", _account_cache_key(account_id, owner), folder, str(uid)),
+ ).fetchone()
+ if not row:
+ return
+ parts = {p for p in (row[0] or "").split() if p}
+ if add:
+ parts.add(flag)
+ else:
+ parts.discard(flag)
+ conn.execute(
+ "UPDATE email_message_index SET flags=?, updated_at=? WHERE owner=? AND account_key=? AND folder=? AND uid=?",
+ (" ".join(sorted(parts)), datetime.utcnow().isoformat() + "Z", owner or "", _account_cache_key(account_id, owner), folder, str(uid)),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+ except Exception:
+ logger.debug("email index flag update skipped", exc_info=True)
+
+
+ def _email_index_delete(owner: str, account_id: str | None, folder: str | None, uid: str):
+ try:
+ conn = _sql3.connect(SCHEDULED_DB)
+ try:
+ if folder:
+ conn.execute(
+ "DELETE FROM email_message_index WHERE owner=? AND account_key=? AND folder=? AND uid=?",
+ (owner or "", _account_cache_key(account_id, owner), folder, str(uid)),
+ )
+ else:
+ conn.execute(
+ "DELETE FROM email_message_index WHERE owner=? AND account_key=? AND uid=?",
+ (owner or "", _account_cache_key(account_id, owner), str(uid)),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+ except Exception:
+ logger.debug("email index delete skipped", exc_info=True)
+
+
+ def _email_preview_cache_get(owner: str, account_id: str | None, folder: str, uid: str) -> dict | None:
+ try:
+ conn = _sql3.connect(SCHEDULED_DB)
+ try:
+ row = conn.execute(
+ """
+ SELECT payload_json, updated_at
+ FROM email_body_preview_cache
+ WHERE owner=? AND account_key=? AND folder=? AND uid=?
+ """,
+ (owner or "", _account_cache_key(account_id, owner), folder, str(uid)),
+ ).fetchone()
+ finally:
+ conn.close()
+ if not row:
+ return None
+ payload = json.loads(row[0] or "{}")
+ if isinstance(payload, dict):
+ payload.setdefault("sync", {})
+ payload["sync"].update({"source": "preview_cache", "updated_at": row[1]})
+ return payload
+ except Exception:
+ logger.debug("email preview cache read skipped", exc_info=True)
+ return None
+
+
+ def _email_preview_cache_put(owner: str, account_id: str | None, folder: str, uid: str, payload: dict):
+ if not payload:
+ return
+ try:
+ now = datetime.utcnow().isoformat() + "Z"
+ message_id = (payload.get("message_id") or "").strip()
+ stored = dict(payload)
+ stored["sync"] = {"source": "preview_cache", "updated_at": now}
+ conn = _sql3.connect(SCHEDULED_DB)
+ try:
+ conn.execute(
+ """
+ INSERT INTO email_body_preview_cache
+ (owner, account_key, folder, uid, message_id, payload_json, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(owner, account_key, folder, uid) DO UPDATE SET
+ message_id=excluded.message_id,
+ payload_json=excluded.payload_json,
+ updated_at=excluded.updated_at
+ """,
+ (
+ owner or "",
+ _account_cache_key(account_id, owner),
+ folder,
+ str(uid),
+ message_id,
+ json.dumps(stored, ensure_ascii=False),
+ now,
+ ),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+ except Exception:
+ logger.debug("email preview cache write skipped", exc_info=True)
+
+
+ def _email_attachment_meta_cache_get(owner: str, account_id: str | None, folder: str, uid: str) -> list[dict] | None:
+ try:
+ conn = _sql3.connect(SCHEDULED_DB)
+ try:
+ row = conn.execute(
+ """
+ SELECT attachments_json
+ FROM email_attachment_metadata_cache
+ WHERE owner=? AND account_key=? AND folder=? AND uid=?
+ """,
+ (owner or "", _account_cache_key(account_id, owner), folder, str(uid)),
+ ).fetchone()
+ if not row:
+ row = conn.execute(
+ """
+ SELECT attachments_json
+ FROM email_attachment_metadata_cache
+ WHERE owner=? AND folder=? AND uid=?
+ ORDER BY updated_at DESC
+ LIMIT 1
+ """,
+ (owner or "", folder, str(uid)),
+ ).fetchone()
+ finally:
+ conn.close()
+ if not row:
+ return None
+ data = json.loads(row[0] or "[]")
+ return data if isinstance(data, list) else []
+ except Exception:
+ logger.debug("email attachment metadata cache read skipped", exc_info=True)
+ return None
+
+
+ def _email_attachment_meta_cache_put(owner: str, account_id: str | None, folder: str, uid: str, message_id: str, attachments: list[dict]):
+ try:
+ conn = _sql3.connect(SCHEDULED_DB)
+ try:
+ conn.execute(
+ """
+ INSERT INTO email_attachment_metadata_cache
+ (owner, account_key, folder, uid, message_id, attachments_json, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(owner, account_key, folder, uid) DO UPDATE SET
+ message_id=CASE
+ WHEN excluded.message_id != '' THEN excluded.message_id
+ ELSE email_attachment_metadata_cache.message_id
+ END,
+ attachments_json=excluded.attachments_json,
+ updated_at=excluded.updated_at
+ """,
+ (
+ owner or "",
+ _account_cache_key(account_id, owner),
+ folder,
+ str(uid),
+ (message_id or "").strip(),
+ json.dumps(attachments or [], ensure_ascii=False),
+ datetime.utcnow().isoformat() + "Z",
+ ),
+ )
+ visible = [
+ att for att in (attachments or [])
+ if not _is_likely_signature_image_attachment(att)
+ ]
+ attachment_names = "\n".join(
+ str(att.get("filename") or "") for att in visible
+ )
+ conn.execute(
+ """
+ UPDATE email_message_index
+ SET has_attachments=?, attachment_names=?, updated_at=?
+ WHERE owner=? AND account_key=? AND folder=? AND uid=?
+ """,
+ (
+ 1 if visible else 0,
+ attachment_names,
+ datetime.utcnow().isoformat() + "Z",
+ owner or "",
+ _account_cache_key(account_id, owner),
+ folder,
+ str(uid),
+ ),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+ except Exception:
+ logger.debug("email attachment metadata cache write skipped", exc_info=True)
+
+
+ def _smtp_ready(cfg: dict) -> bool:
+ if not cfg.get("smtp_host") or not cfg.get("smtp_user"):
+ return False
+ return bool(cfg.get("smtp_password") or cfg.get("oauth_provider"))
+
+
+ def _resolve_send_config(account_id: str | None = None, owner: str = "") -> dict:
+ """Resolve an account for outbound SMTP.
+
+ If the caller explicitly picked an account, use only that account and
+ return a clear error when it cannot send. If no account was picked and
+ the default is receive-only, fall back to the first SMTP-capable account
+ owned by the same user.
+ """
+ cfg = _get_email_config(account_id, owner=owner)
+ if _smtp_ready(cfg):
+ return cfg
+ if account_id:
+ raise ValueError(f"Email account {cfg.get('account_name') or account_id} has no SMTP configured")
+ try:
+ from core.database import SessionLocal as _SL, EmailAccount as _EA
+ from sqlalchemy import and_, or_
+ db = _SL()
+ try:
+ q = db.query(_EA).filter(_EA.enabled == True) # noqa: E712
+ if owner:
+ unowned = or_(_EA.owner == None, _EA.owner == "") # noqa: E711
+ same_mailbox = or_(_EA.imap_user == owner, _EA.from_address == owner)
+ q = q.filter(or_(_EA.owner == owner, and_(unowned, same_mailbox)))
+ for row in q.order_by(_EA.is_default.desc(), _EA.created_at.asc()).all():
+ trial = _get_email_config(account_id=row.id, owner=owner)
+ if _smtp_ready(trial):
+ return trial
+ finally:
+ db.close()
+ except Exception as e:
+ logger.debug(f"SMTP-capable account fallback failed: {e}")
+ raise ValueError("No SMTP-capable email account configured")
+
+
+ def _store_email_flag(conn, uid: str, flag: str, add: bool = True) -> bool:
+ # imaplib's plain store() takes a message SEQUENCE NUMBER, not a UID, so the
+ # old `else` fallback flagged whichever message happened to occupy sequence
+ # position == the UID value. When the UID isn't present, fail safe (callers
+ # surface "Email not found") rather than touch an unrelated message.
+ if not _uid_exists(conn, uid):
+ return False
+ op = "+FLAGS" if add else "-FLAGS"
+ status, _ = conn.uid("STORE", _uid_bytes(uid), op, flag)
+ return status == "OK"
+
+
+ def _move_email_message(conn, uid: str, dest: str, role: str = "") -> bool:
+ dest = _resolve_mail_folder(conn, dest, role or _folder_role_from_name(dest))
+ # copy()/store() are SEQUENCE-NUMBER commands; using them with a UID (the old
+ # `else` branch) copied + \Deleted-flagged the wrong message and then
+ # expunge() permanently removed it. There is no valid case where treating a
+ # UID as a sequence number is correct, so fail safe when the UID is absent.
+ if not _uid_exists(conn, uid):
+ return False
+ status, _ = conn.uid("MOVE", _uid_bytes(uid), _q(dest))
+ if status == "OK":
+ return True
+ status, _ = conn.uid("COPY", _uid_bytes(uid), _q(dest))
+ if status != "OK":
+ return False
+ status, _ = conn.uid("STORE", _uid_bytes(uid), "+FLAGS", "\\Deleted")
+ if status == "OK":
+ conn.expunge()
+ return True
+ return False
+
+
+ def _copy_and_delete_email_message(conn, uid: str, dest: str, role: str = "") -> bool:
+ """Keep a Junk copy while removing the original from the current folder."""
+ dest = _resolve_mail_folder(conn, dest, role or _folder_role_from_name(dest))
+ if not _uid_exists(conn, uid):
+ return False
+ status, _ = conn.uid("COPY", _uid_bytes(uid), _q(dest))
+ if status != "OK":
+ return False
+ status, _ = conn.uid("STORE", _uid_bytes(uid), "+FLAGS", "\\Deleted")
+ if status == "OK":
+ conn.expunge()
+ return True
+ return False
+
+
+ def _apply_odysseus_headers(msg, kind: str | None = None, ref_id: str | None = None):
+ msg["X-Odysseus-Origin"] = ODYSSEUS_MAIL_ORIGIN
+ if kind:
+ msg["X-Odysseus-Kind"] = re.sub(r"[^A-Za-z0-9_.-]", "-", kind)[:64]
+ if ref_id:
+ msg["X-Odysseus-Ref"] = re.sub(r"[^A-Za-z0-9_.:-]", "-", ref_id)[:128]
+
+
+ def _normalize_addr_field(field: str) -> str:
+ """Strip the malformed-but-common trailing/leading commas and stray
+ whitespace from a To/Cc/Bcc string before it lands in the MIME header
+ or the SMTP envelope. Users often paste a single address with a
+ trailing comma, which most MTAs reject as a syntax error. Collapse
+ any run of separator junk between addresses too."""
+ if not field:
+ return field
+ # Split on commas, drop empty tokens, rejoin with a single ', '.
+ parts = [p.strip() for p in field.split(",")]
+ parts = [p for p in parts if p]
+ return ", ".join(parts)
+
+
+ def _envelope_recipients(*fields: str) -> list:
+ """Extract bare SMTP envelope addresses from one or more To/Cc/Bcc header
+ strings. A naive `field.split(",")` corrupts display names that contain a
+ comma (e.g. `"Smith, John" <[email protected]>`, the canonical Outlook form):
+ it splits into `"Smith` and `John" <[email protected]>`, breaking delivery.
+ email.utils.getaddresses parses the address grammar correctly."""
+ out = []
+ for _name, addr in email.utils.getaddresses([f for f in fields if f]):
+ addr = (addr or "").strip()
+ if addr:
+ out.append(addr)
+ return out
+
+
+ def _md_to_email_html(text: str) -> str:
+ """Render the compose markdown body to a SAFE HTML fragment for the email's
+ text/html part. Everything is HTML-escaped FIRST (so a pasted <script> /
+ <img onerror=...> can never become live HTML in the recipient's client),
+ then the toolbar's formatting is layered on with controlled regex: bold,
+ italic, strike, inline code, http(s) links, headings, and bullet/numbered
+ lists. Plain-text readers still get the raw markdown via the text/plain part.
+ """
+ def _inline(s: str) -> str:
+ s = html.escape(s) # escape BEFORE formatting
+ s = re.sub(r"\*\*([^*]+)\*\*", r"<strong>\1</strong>", s)
+ s = re.sub(r"\*([^*]+)\*", r"<em>\1</em>", s)
+ s = re.sub(r"~~([^~]+)~~", r"<del>\1</del>", s)
+ s = re.sub(r"`([^`]+)`", r"<code>\1</code>", s)
+ # links: text + http(s) url only (escape() already neutralised quotes)
+ s = re.sub(r"\[([^\]]+)\]\((https?://[^)\s]+)\)", r'<a href="\2">\1</a>', s)
+ return s
+
+ parts: list[str] = []
+ in_ul = in_ol = False
+ for ln in (text or "").split("\n"):
+ m_h = re.match(r"^(#{1,3})\s+(.*)$", ln)
+ m_ul = re.match(r"^\s*[-*]\s+(.*)$", ln)
+ m_ol = re.match(r"^\s*\d+\.\s+(.*)$", ln)
+ if m_h:
+ if in_ul: parts.append("</ul>"); in_ul = False
+ if in_ol: parts.append("</ol>"); in_ol = False
+ lvl = len(m_h.group(1))
+ parts.append(f"<h{lvl}>{_inline(m_h.group(2))}</h{lvl}>")
+ elif m_ul:
+ if in_ol: parts.append("</ol>"); in_ol = False
+ if not in_ul: parts.append("<ul>"); in_ul = True
+ parts.append(f"<li>{_inline(m_ul.group(1))}</li>")
+ elif m_ol:
+ if in_ul: parts.append("</ul>"); in_ul = False
+ if not in_ol: parts.append("<ol>"); in_ol = True
+ parts.append(f"<li>{_inline(m_ol.group(1))}</li>")
+ else:
+ if in_ul: parts.append("</ul>"); in_ul = False
+ if in_ol: parts.append("</ol>"); in_ol = False
+ parts.append(_inline(ln) + "<br>")
+ if in_ul: parts.append("</ul>")
+ if in_ol: parts.append("</ol>")
+ return "<html><body>" + "\n".join(parts) + "</body></html>"
+
+
+ # Tags the WYSIWYG email composer may legitimately produce.
+ _EMAIL_ALLOWED_TAGS = {
+ "b", "strong", "i", "em", "u", "s", "strike", "del", "a", "br", "p", "div",
+ "ul", "ol", "li", "blockquote", "span", "h1", "h2", "h3", "code", "pre",
+ }
+
+
+ class _EmailHtmlSanitizer(_HTMLParser):
+ """Allowlist sanitizer for WYSIWYG-composed email HTML. Emits only known
+ formatting tags (all attributes dropped except a safe href on <a>), escapes
+ all text, and discards <script>/<style> content entirely — so client-sent
+ HTML can never carry live script/handlers into the recipient's client."""
+
+ def __init__(self):
+ super().__init__(convert_charrefs=True)
+ self.out = []
+ self._skip = 0 # depth inside <script>/<style>
+
+ def handle_starttag(self, tag, attrs):
+ if tag in ("script", "style"):
+ self._skip += 1
+ return
+ if tag == "br":
+ self.out.append("<br>")
+ return
+ if tag not in _EMAIL_ALLOWED_TAGS:
+ return
+ if tag == "a":
+ href = ""
+ for k, v in attrs:
+ if k.lower() == "href" and v and re.match(r"^(https?:|mailto:)", v.strip(), re.I):
+ href = v.strip()
+ self.out.append(
+ f'<a href="{html.escape(href, quote=True)}" target="_blank" rel="noopener noreferrer">'
+ if href else "<a>")
+ else:
+ self.out.append(f"<{tag}>")
+
+ def handle_startendtag(self, tag, attrs):
+ if tag == "br":
+ self.out.append("<br>")
+
+ def handle_endtag(self, tag):
+ if tag in ("script", "style"):
+ if self._skip:
+ self._skip -= 1
+ return
+ if tag == "br" or tag not in _EMAIL_ALLOWED_TAGS:
+ return
+ self.out.append(f"</{tag}>")
+
+ def handle_data(self, data):
+ if self._skip:
+ return
+ self.out.append(html.escape(data))
+
+
+ def _sanitize_email_html(raw: str) -> str:
+ """Return a safe <html><body>…</body></html> from client-supplied compose
+ HTML, or None if it can't be parsed."""
+ p = _EmailHtmlSanitizer()
+ try:
+ p.feed(raw or "")
+ p.close()
+ except Exception:
+ return None
+ inner = "".join(p.out).strip()
+ if not inner:
+ return None
+ return f"<html><body>{inner}</body></html>"
+
+
+ def setup_email_routes():
+ _start_poller()
+ router = APIRouter(prefix="/api/email", tags=["email"])
+
+ # ── In-memory cache + prefetch + IMAP connection pool ──
+ # Three layers stacked because every cold click was hitting Dovecot
+ # over a fresh TCP+TLS+LOGIN handshake plus a full RFC822 fetch.
+ # 1. _LIST_CACHE: list-emails responses keyed by (account, folder, filter,
+ # limit, offset). 8s TTL — short enough that flag changes show up
+ # quickly but long enough to absorb burst polls and tab switches.
+ # 2. _READ_CACHE: per-(account, folder, uid) parsed email bodies.
+ # 60s TTL — bodies don't change.
+ # 3. _IMAP_POOL: per-account live IMAP connection reused across
+ # requests. Recycled if NOOP fails or it's been idle >60s.
+ # 4. Prefetch task: after a list load, kick off background reads of
+ # the top-N visible UIDs so clicks land in the read cache.
+ import asyncio as _asyncio
+ import time as _time
+ import threading as _threading
+
+ _LIST_CACHE = {} # key → (expires_at, response_dict)
+ _LIST_TTL = 45.0
+ _FOLDER_CACHE = {} # (account_id, owner) -> (expires_at, response_dict)
+ _FOLDER_TTL = 5 * 60.0
+ _READ_CACHE = {} # key → (expires_at, response_dict)
+ _READ_TTL = 30 * 60.0
+ _IMAP_POOL = {} # account_id → (conn, last_used_at)
+ _IMAP_IDLE_MAX = 60.0
+ _WARMING_READS = set()
+ _WARM_READ_LIMIT = 6
+ _WARM_MAX_BYTES = 192 * 1024
+ _WARM_RECENT_SECONDS = 7 * 24 * 60 * 60
+ _pool_lock = _threading.Lock()
+
+ def _pooled_connect(account_id, owner=""):
+ """Reuse a live IMAP connection if one is in the pool and still
+ responsive. Otherwise open fresh and store it. Caller must release
+ via _pooled_release after use (not strictly required — the pool
+ holds the same conn handle, and we lock to serialize access).
+
+ SECURITY: `owner` is forwarded to `_imap_connect` so the fallback
+ config lookup (when `account_id` is None) is scoped to this user's
+ accounts only. The pool key is (account_id, owner) so two users
+ with `account_id=None` don't share a pooled connection.
+ """
+ pool_key = (account_id, owner)
+ now = _time.monotonic()
+ with _pool_lock:
+ entry = _IMAP_POOL.get(pool_key)
+ if entry:
+ conn, last_used = entry
+ if (now - last_used) < _IMAP_IDLE_MAX:
+ try:
+ conn.noop()
+ # Pop it out of the pool while we use it (serialize)
+ del _IMAP_POOL[pool_key]
+ return conn, True # reused
+ except Exception:
+ try: conn.logout()
+ except Exception: pass
+ del _IMAP_POOL[pool_key]
+ else:
+ try: conn.logout()
+ except Exception: pass
+ del _IMAP_POOL[pool_key]
+ # Fresh connection
+ return _imap_connect(account_id, owner=owner), False
+
+ def _pooled_release(account_id, conn, ok=True, owner=""):
+ # SECURITY: match the (account_id, owner) key used by _pooled_connect
+ # so a pooled handle is returned to the same per-user slot.
+ if not ok:
+ try: conn.logout()
+ except Exception: pass
+ return
+ with _pool_lock:
+ _IMAP_POOL[(account_id, owner)] = (conn, _time.monotonic())
+
+ def _invalidate_imap_pool(account_id=None, owner=""):
+ """Close pooled IMAP handles for a manual refresh.
+
+ The list route's cache-buster already bypasses the short response
+ cache, but a user-visible refresh should also make a fresh IMAP
+ connection instead of reusing a selected mailbox handle that may be
+ behind the provider's latest state.
+ """
+ with _pool_lock:
+ for key, (conn, _last_used) in list(_IMAP_POOL.items()):
+ key_account, key_owner = key if isinstance(key, tuple) and len(key) == 2 else (key, "")
+ if account_id is not None and key_account != (account_id or ""):
+ continue
+ if owner and key_owner != owner:
+ continue
+ _IMAP_POOL.pop(key, None)
+ try:
+ conn.logout()
+ except Exception:
+ pass
+
+ def _list_cache_key(account_id, folder, filter_, limit, offset, from_addr=""):
+ return (account_id or "", folder, filter_, int(limit), int(offset), from_addr or "")
+
+ def _read_cache_key(account_id, folder, uid, owner=""):
+ # SECURITY: include owner so two users with `account_id == ""` /
+ # None (i.e. resolved through the per-user default) don't share
+ # a cached message body.
+ return (account_id or "", folder, str(uid), owner)
+
+ def _list_cache_get(key):
+ v = _LIST_CACHE.get(key)
+ if not v: return None
+ if v[0] < _time.monotonic():
+ _LIST_CACHE.pop(key, None)
+ return None
+ return v[1]
+
+ def _list_cache_put(key, value):
+ _LIST_CACHE[key] = (_time.monotonic() + _LIST_TTL, value)
+ # Cap size
+ if len(_LIST_CACHE) > 64:
+ for k in list(_LIST_CACHE.keys())[:-32]:
+ _LIST_CACHE.pop(k, None)
+
+ def _folder_cache_get(account_id, owner):
+ key = (account_id or "", owner or "")
+ v = _FOLDER_CACHE.get(key)
+ if not v:
+ return None
+ if v[0] < _time.monotonic():
+ _FOLDER_CACHE.pop(key, None)
+ return None
+ return v[1]
+
+ def _folder_cache_get_stale(account_id, owner):
+ v = _FOLDER_CACHE.get((account_id or "", owner or ""))
+ return v[1] if v else None
+
+ def _folder_cache_put(account_id, owner, value):
+ _FOLDER_CACHE[(account_id or "", owner or "")] = (_time.monotonic() + _FOLDER_TTL, value)
+ if len(_FOLDER_CACHE) > 32:
+ for k in list(_FOLDER_CACHE.keys())[:-16]:
+ _FOLDER_CACHE.pop(k, None)
+
+ def _invalidate_list_cache(account_id=None, folder=None):
+ """Drop list cache entries that the caller's mutation may have stale-ed.
+
+ Called from flag-mutating endpoints (mark-read/unread/answered, archive,
+ delete, move) so the UI doesn't show stale read/unread counts for up to
+ the 8s TTL after a manual flag change. With no args, clears everything.
+ """
+ if account_id is None and folder is None:
+ _LIST_CACHE.clear()
+ return
+ for k in list(_LIST_CACHE.keys()):
+ k_acct = k[0] if len(k) > 0 else ""
+ k_folder = k[1] if len(k) > 1 else ""
+ if (account_id is None or k_acct == (account_id or "")) and \
+ (folder is None or k_folder == folder):
+ _LIST_CACHE.pop(k, None)
+
+ def _update_list_cache_seen(account_id, folder, uid, seen: bool):
+ uid_s = str(uid)
+ for key, (expires_at, value) in list(_LIST_CACHE.items()):
+ if key[0] != (account_id or "") or key[1] != folder:
+ continue
+ emails = list((value or {}).get("emails") or [])
+ changed = False
+ if seen and key[2] == "unread":
+ kept = [e for e in emails if str((e or {}).get("uid") or "") != uid_s]
+ if len(kept) != len(emails):
+ value = dict(value)
+ value["emails"] = kept
+ value["total"] = max(0, int(value.get("total") or 0) - (len(emails) - len(kept)))
+ changed = True
+ else:
+ for e in emails:
+ if str((e or {}).get("uid") or "") == uid_s:
+ e["is_read"] = bool(seen)
+ changed = True
+ if changed:
+ _LIST_CACHE[key] = (expires_at, value)
+
+ def _read_cache_get(key):
+ v = _READ_CACHE.get(key)
+ if not v: return None
+ if v[0] < _time.monotonic():
+ _READ_CACHE.pop(key, None)
+ return None
+ return v[1]
+
+ def _read_cache_put(key, value):
+ _READ_CACHE[key] = (_time.monotonic() + _READ_TTL, value)
+ if len(_READ_CACHE) > 256:
+ for k in list(_READ_CACHE.keys())[:-128]:
+ _READ_CACHE.pop(k, None)
+
+ # Expose helpers in the closure to be used by handlers below
+ router._email_pool = {
+ "connect": _pooled_connect,
+ "release": _pooled_release,
+ "list_cache_get": _list_cache_get,
+ "list_cache_put": _list_cache_put,
+ "list_cache_key": _list_cache_key,
+ "read_cache_get": _read_cache_get,
+ "read_cache_put": _read_cache_put,
+ "read_cache_key": _read_cache_key,
+ }
+ # Wire the module-level _imap() context manager into the pool so every
+ # `with _imap(account_id, owner=owner) as conn:` reuses an existing connection
+ # instead of paying TCP+TLS+LOGIN per request.
+ _POOL_HOOKS["connect"] = _pooled_connect
+ _POOL_HOOKS["release"] = _pooled_release
+
+ def _fixture_email_file() -> Path:
+ return Path(DATA_DIR) / "fixture_email_messages.json"
+
+ def _fixture_email_enabled() -> bool:
+ return os.environ.get("ODYSSEUS_EMAIL_FIXTURE") == "1" and _fixture_email_file().exists()
+
+ def _fixture_folder_key(folder: str | None) -> str:
+ value = str(folder or "INBOX").strip().lower()
+ if value in {"", "inbox"}:
+ return "inbox"
+ if value in {"archive", "archived", "[gmail]/all mail", "all mail"}:
+ return "archive"
+ if value == "all":
+ return "all"
+ if value in {"trash", "deleted", "bin"}:
+ return "trash"
+ return value
+
+ def _fixture_folder_matches(row_folder: str | None, requested: str | None) -> bool:
+ req = _fixture_folder_key(requested)
+ actual = _fixture_folder_key(row_folder or "INBOX")
+ if req == "all":
+ return actual != "trash"
+ return actual == req
+
+ def _fixture_attachment_meta(raw_attachments: list[dict]) -> list[dict]:
+ out = []
+ for idx, att in enumerate(raw_attachments):
+ if not isinstance(att, dict):
+ continue
+ filename = str(att.get("filename") or f"attachment-{idx}.txt")
+ content = str(att.get("content") or "")
+ content_type = str(att.get("content_type") or "application/octet-stream")
+ out.append({
+ "index": int(att.get("index", idx) or idx),
+ "filename": filename,
+ "content_type": content_type,
+ "size": len(content.encode("utf-8")),
+ })
+ return out
+
+ def _fixture_attachment_source(uid: str, index: int, owner: str, folder: str = "INBOX") -> tuple[dict, dict] | None:
+ if not _fixture_email_enabled():
+ return None
+ if not _fixture_owner_has_rows(owner):
+ return None
+ path = _fixture_email_file()
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ logger.debug("fixture email attachment load failed", exc_info=True)
+ return None
+ rows = payload.get("messages") if isinstance(payload, dict) else payload
+ for i, row in enumerate(rows if isinstance(rows, list) else [], start=1):
+ if not isinstance(row, dict):
+ continue
+ row_owner = str(row.get("owner") or "").strip()
+ if owner and row_owner and row_owner != owner:
+ continue
+ if str(row.get("uid") or i) != str(uid):
+ continue
+ if not _fixture_folder_matches(row.get("folder") or "INBOX", folder):
+ continue
+ attachments = row.get("attachments") if isinstance(row.get("attachments"), list) else []
+ for att_i, att in enumerate(attachments):
+ if int(att.get("index", att_i) or att_i) == int(index):
+ return row, att
+ return None
+
+ def _fixture_email_rows(owner: str) -> list[dict]:
+ path = _fixture_email_file()
+ if not path.exists():
+ return []
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ logger.debug("fixture email load failed", exc_info=True)
+ return []
+ rows = raw.get("messages") if isinstance(raw, dict) else raw
+ out = []
+ for i, row in enumerate(rows if isinstance(rows, list) else [], start=1):
+ if not isinstance(row, dict):
+ continue
+ row_owner = str(row.get("owner") or "").strip()
+ if owner and row_owner and row_owner != owner:
+ continue
+ out.append(_fixture_email_record(row, i, owner))
+ out.sort(key=lambda e: e.get("date_epoch") or 0, reverse=True)
+ return out
+
+ def _fixture_owner_has_rows(owner: str) -> bool:
+ owner = str(owner or "").strip()
+ if not owner:
+ return True
+ path = _fixture_email_file()
+ if not path.exists():
+ return False
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ logger.debug("fixture email owner probe failed", exc_info=True)
+ return False
+ rows = raw.get("messages") if isinstance(raw, dict) else raw
+ return any(
+ isinstance(row, dict) and str(row.get("owner") or "").strip() == owner
+ for row in (rows if isinstance(rows, list) else [])
+ )
+
+ def _fixture_email_record(row: dict, uid_num: int, owner: str) -> dict:
+ sender = str(row.get("from") or "Inbox Sender <[email protected]>")
+ sender_name, sender_addr = email.utils.parseaddr(sender)
+ raw_date = str(row.get("date") or "")
+ parsed_date = None
+ if raw_date:
+ try:
+ parsed_date = datetime.fromisoformat(raw_date.replace("Z", "+00:00"))
+ except Exception:
+ try:
+ parsed_date = email.utils.parsedate_to_datetime(raw_date)
+ except Exception:
+ parsed_date = None
+ iso_date = parsed_date.isoformat() if parsed_date else raw_date
+ date_epoch = parsed_date.timestamp() if parsed_date else 0.0
+ subject = str(row.get("subject") or "(no subject)")
+ body = str(row.get("body") or "")
+ uid = str(row.get("uid") or uid_num)
+ owner_key = re.sub(r"[^A-Za-z0-9_.-]", "-", owner or "default")
+ message_id = str(row.get("message_id") or "").strip()
+ folder = str(row.get("folder") or "INBOX").strip() or "INBOX"
+ attachments = _fixture_attachment_meta(row.get("attachments") if isinstance(row.get("attachments"), list) else [])
+ is_answered = bool(row.get("done") or row.get("answered"))
+ is_flagged = bool(row.get("favorite") or row.get("flagged") or row.get("starred"))
+ flags = []
+ if row.get("read"):
+ flags.append("\\Seen")
+ if is_answered:
+ flags.append("\\Answered")
+ if is_flagged:
+ flags.append("\\Flagged")
+ tags = _sanitize_visible_email_tags(row.get("tags") or row.get("category_tags") or [], is_answered=is_answered)
+ spam_verdict = bool(row.get("spam") or row.get("is_spam_verdict") or row.get("spam_verdict"))
+ return {
+ "uid": uid,
+ "message_id": message_id or f"<inbox-{uid}-{owner_key}@mail.local>",
+ "subject": subject,
+ "from_name": sender_name or sender_addr or sender,
+ "from_address": sender_addr,
+ "to": str(row.get("to") or owner or ""),
+ "cc": "",
+ "date": iso_date,
+ "date_display": raw_date,
+ "date_epoch": date_epoch,
+ "size": len(body.encode("utf-8")),
+ "is_read": bool(row.get("read")),
+ "is_answered": is_answered,
+ "is_done": is_answered,
+ "is_flagged": is_flagged,
+ "flags": " ".join(flags),
+ "has_attachments": bool(attachments),
+ "folder": folder,
+ "account": str(row.get("account") or "Primary Inbox"),
+ "account_email": str(row.get("account_email") or row.get("to") or owner or ""),
+ "account_id": str(row.get("account_id") or "primary-inbox"),
+ "tags": tags,
+ "is_spam_verdict": spam_verdict,
+ "spam_reason": str(row.get("spam_reason") or row.get("spam_label") or ""),
+ "_fixture_body": body,
+ "_fixture_attachments": attachments,
+ }
+
+ def _fixture_email_matches(row: dict, query: str) -> bool:
+ terms = [term for term in re.split(r"\W+", str(query or "").lower()) if term]
+ if not terms:
+ return True
+ attachment_text = "\n".join(
+ f"{att.get('filename') or ''}\n{att.get('content') or ''}"
+ for att in (row.get("attachments") if isinstance(row.get("attachments"), list) else [])
+ if isinstance(att, dict)
+ )
+ haystack = "\n".join(
+ str(row.get(key) or "")
+ for key in ("subject", "from", "to", "body", "summary", "date")
+ ) + "\n" + attachment_text
+ haystack = haystack.lower()
+ return all(term in haystack for term in terms)
+
+ def _fixture_email_list(folder: str, limit: int, offset: int, filter_: str, from_addr: str | None, owner: str, has_attachments_only: bool = False, query: str = "") -> dict | None:
+ if not _fixture_email_enabled():
+ return None
+ if not _fixture_owner_has_rows(owner):
+ return None
+ rows = [
+ e for e in _fixture_email_rows(owner)
+ if _fixture_folder_matches(e.get("folder"), folder)
+ ]
+ if query:
+ raw = []
+ path = _fixture_email_file()
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ raw = payload.get("messages") if isinstance(payload, dict) else payload
+ except Exception:
+ raw = []
+ matching_uids = {
+ str(row.get("uid") or i)
+ for i, row in enumerate(raw if isinstance(raw, list) else [], start=1)
+ if isinstance(row, dict)
+ and (not owner or not row.get("owner") or row.get("owner") == owner)
+ and _fixture_email_matches(row, query)
+ }
+ rows = [e for e in rows if str(e.get("uid")) in matching_uids]
+ if from_addr:
+ needle = from_addr.strip().lower()
+ rows = [
+ e for e in rows
+ if needle in (e.get("from_address") or "").lower()
+ or needle in (e.get("from_name") or "").lower()
+ ]
+ if filter_ == "unread":
+ rows = [e for e in rows if not e.get("is_read")]
+ elif filter_ in {"unanswered", "undone"}:
+ rows = [e for e in rows if not e.get("is_answered")]
+ elif filter_ == "favorites":
+ rows = [e for e in rows if e.get("is_flagged")]
+ elif filter_ in {"all", "", None}:
+ pass
+ elif str(filter_).startswith("tag:"):
+ tag_name = str(filter_)[len("tag:"):].strip().lower().replace("_", "-")
+ if tag_name == "spam":
+ rows = [e for e in rows if e.get("is_spam_verdict")]
+ else:
+ rows = [e for e in rows if tag_name in (e.get("tags") or [])]
+ elif filter_ == "reminders":
+ rows = []
+ else:
+ pass
+ if has_attachments_only:
+ rows = [e for e in rows if e.get("has_attachments")]
+ total = len(rows)
+ start = max(0, int(offset or 0))
+ stop = start + max(1, min(int(limit or 50), 200))
+ visible = []
+ for e in rows[start:stop]:
+ item = dict(e)
+ item.pop("_fixture_body", None)
+ item.pop("_fixture_attachments", None)
+ visible.append(item)
+ return {
+ "emails": visible,
+ "total": total,
+ "folder": folder,
+ "sync": {"source": "local", "updated_at": datetime.utcnow().isoformat() + "Z"},
+ }
+
+ def _fixture_email_read(uid: str, folder: str, owner: str) -> dict | None:
+ if not _fixture_email_enabled():
+ return None
+ if not _fixture_owner_has_rows(owner):
+ return None
+ for e in _fixture_email_rows(owner):
+ if not _fixture_folder_matches(e.get("folder"), folder):
+ continue
+ if str(e.get("uid")) != str(uid):
+ continue
+ body = e.get("_fixture_body") or ""
+ body_html = "<html><body><p>" + html.escape(body).replace("\n", "<br>") + "</p></body></html>"
+ return {
+ "uid": str(uid),
+ "folder": folder,
+ "message_id": e.get("message_id") or "",
+ "subject": e.get("subject") or "",
+ "from_name": e.get("from_name") or "",
+ "from_address": e.get("from_address") or "",
+ "to": e.get("to") or owner or "",
+ "cc": "",
+ "date": e.get("date") or "",
+ "in_reply_to": "",
+ "references": "",
+ "body": body,
+ "body_html": body_html,
+ "is_read": bool(e.get("is_read")),
+ "is_answered": bool(e.get("is_answered") or e.get("is_done")),
+ "is_done": bool(e.get("is_answered") or e.get("is_done")),
+ "is_flagged": bool(e.get("is_flagged")),
+ "flags": e.get("flags") or "",
+ "attachments": e.get("_fixture_attachments") or [],
+ "attachments_deferred": False,
+ "related_attachments": [],
+ "attachment_version": EMAIL_READ_ATTACHMENT_VERSION,
+ "cached_summary": None,
+ "cached_ai_reply": None,
+ "boundaries": None,
+ "thread_turns": None,
+ "sender_signature": None,
+ "sync": {"source": "local"},
+ }
+ return {"error": f"Email UID {uid} not found"}
+
+ def _fixture_email_update(uid: str, owner: str, source_folder: str = "INBOX", **updates) -> bool | None:
+ if not _fixture_email_enabled():
+ return None
+ path = _fixture_email_file()
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ logger.debug("fixture email update load failed", exc_info=True)
+ return False
+ rows = payload.get("messages") if isinstance(payload, dict) else payload
+ if not isinstance(rows, list):
+ return None
+ for i, row in enumerate(rows, start=1):
+ if not isinstance(row, dict):
+ continue
+ row_owner = str(row.get("owner") or "").strip()
+ if owner and row_owner and row_owner != owner:
+ continue
+ row_uid = str(row.get("uid") or i)
+ if str(row_uid) != str(uid):
+ continue
+ if not _fixture_folder_matches(row.get("folder") or "INBOX", source_folder):
+ continue
+ for key, value in updates.items():
+ if value is None:
+ row.pop(key, None)
+ else:
+ row[key] = value
+ path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ return True
+ # Fixture mode may be enabled for a small set of synthetic messages
+ # while the visible mailbox is still backed by IMAP. Do not turn a
+ # live UID that is absent from the fixture into a false “not found”;
+ # callers must fall through to the real mailbox operation.
+ return None
+
+ def _list_emails_sync(folder, limit, offset, filter_, account_id, from_addr=None, has_attachments_only=False, owner="", refresh=False, date_from="", date_to=""):
+ """Sync IMAP work — call from async handler via asyncio.to_thread so
+ it doesn't block the event loop.
+
+ When `has_attachments_only` is True, IMAP doesn't have a portable
+ HASATTACH keyword, so we widen the fetch (up to ~400 most-recent
+ UIDs in the folder slice) and post-filter by Content-Type. Total
+ count then reflects matches in that scanned window, not the whole
+ folder.
+
+ SECURITY: `owner` is propagated so when `account_id` is missing,
+ the fallback config lookup is scoped to this user's accounts only.
+ """
+ conn = None
+ conn_ok = False
+ try:
+ conn, _reused_conn = _pooled_connect(account_id, owner=owner)
+ conn_ok = True
+ select_status, _ = conn.select(_q(folder), readonly=True)
+ if select_status != "OK":
+ resolved_folder = _resolve_mail_folder(conn, folder, role=_mail_folder_role_hint(folder))
+ if resolved_folder != folder:
+ retry_status, _ = conn.select(_q(resolved_folder), readonly=True)
+ if retry_status == "OK":
+ folder = resolved_folder
+ select_status = retry_status
+ if select_status != "OK":
+ return {"emails": [], "total": 0, "folder": folder, "error": f"Folder not found: {folder}"}
+
+ from_clause = ""
+ if from_addr:
+ # Escape quotes/backslashes for IMAP SEARCH FROM
+ _safe = from_addr.replace("\\", "\\\\").replace('"', '\\"')
+ from_clause = f' FROM "{_safe}"'
+
+ if filter_ == "unread":
+ status, data = _imap_uid_search(conn, f"(UNSEEN{from_clause})")
+ elif filter_ == "favorites":
+ # Flagged/favorited emails (the star toggle sets the \Flagged flag).
+ status, data = _imap_uid_search(conn, f"(FLAGGED{from_clause})")
+ elif filter_ == "unanswered":
+ status, data = _imap_uid_search(conn, f"(UNSEEN UNANSWERED{from_clause})")
+ elif filter_ == "undone":
+ # All emails NOT marked as answered/done (read or unread).
+ status, data = _imap_uid_search(conn, f"(UNANSWERED{from_clause})")
+ elif filter_ == "reminders":
+ # Prefer the Odysseus marker header, but include the subject
+ # fallback too. The fallback uses a distinct Odysseus prefix
+ # so ordinary emails containing "Reminder" don't get mixed in.
+ status, data = _imap_uid_search(
+ conn,
+ f'(OR HEADER X-Odysseus-Kind "reminder" SUBJECT "Reminder (Odysseus):"{from_clause})',
+ )
+ elif filter_ == "pending_30d":
+ # "What's pending in the last month" — UNANSWERED + delivered
+ # within the last 30 days. SINCE takes a DD-Mon-YYYY date.
+ from datetime import datetime as _dt, timedelta as _td
+ _since = (_dt.utcnow() - _td(days=30)).strftime("%d-%b-%Y")
+ status, data = _imap_uid_search(conn, f'(UNANSWERED SINCE "{_since}"{from_clause})')
+ elif filter_ == "stale_30d":
+ # "What's been sitting too long" — UNANSWERED + delivered
+ # MORE than 30 days ago. BEFORE excludes the cutoff date itself.
+ from datetime import datetime as _dt, timedelta as _td
+ _before = (_dt.utcnow() - _td(days=30)).strftime("%d-%b-%Y")
+ status, data = _imap_uid_search(conn, f'(UNANSWERED BEFORE "{_before}"{from_clause})')
+ elif filter_ and filter_.startswith("tag:"):
+ # Tag-based filter — resolve UIDs from email_tags first, then
+ # ask IMAP for those messages by Message-ID. `tag:spam` reads
+ # spam_verdict=1; any other tag matches JSON-array membership
+ # in `tags`.
+ _tag_name = filter_[len("tag:"):].strip().lower()
+ _tag_message_ids = []
+ _tag_seq_fallback = []
+ try:
+ import sqlite3 as _sql3t
+ _ct = _sql3t.connect(SCHEDULED_DB)
+ _owner_clause, _owner_params = _email_tag_owner_clause(account_id, owner)
+ _account_clause, _account_params = _email_tag_account_clause(account_id)
+ # SECURITY: owner-scope the lookup (review C2/H8). Without
+ # this, user A's `tag:urgent` filter would surface UIDs
+ # written by user B and IMAP would return whatever
+ # happens to live at those UIDs in A's mailbox. Account
+ # mailbox aliases are included because the background
+ # urgency task may be owned by the mailbox address while
+ # the UI is owned by the app user.
+ if _tag_name == "spam":
+ rows_t = _ct.execute(
+ "SELECT message_id, uid FROM email_tags "
+ "WHERE folder=? AND spam_verdict=1 "
+ f"AND {_owner_clause} AND {_account_clause}",
+ (folder, *_owner_params, *_account_params),
+ ).fetchall()
+ for mid, uid in rows_t:
+ if uid:
+ _tag_seq_fallback.append(str(uid).strip())
+ elif mid:
+ _tag_message_ids.append(str(mid).strip())
+ else:
+ rows_t = _ct.execute(
+ "SELECT message_id, uid, tags FROM email_tags "
+ "WHERE folder=? AND tags IS NOT NULL AND tags != '' "
+ f"AND {_owner_clause} AND {_account_clause}",
+ (folder, *_owner_params, *_account_params),
+ ).fetchall()
+ _idx_flags_by_uid = {}
+ _idx_flags_by_mid = {}
+ try:
+ _uid_vals = [str(r[1]).strip() for r in rows_t if r[1]]
+ _mid_vals = [str(r[0]).strip() for r in rows_t if r[0]]
+ _idx_clauses = []
+ _idx_params = [owner or "", _account_cache_key(account_id, owner), folder]
+ if _uid_vals:
+ _idx_clauses.append("uid IN (" + ",".join("?" * len(_uid_vals)) + ")")
+ _idx_params.extend(_uid_vals)
+ if _mid_vals:
+ _idx_clauses.append("message_id IN (" + ",".join("?" * len(_mid_vals)) + ")")
+ _idx_params.extend(_mid_vals)
+ if _idx_clauses:
+ for _uid_i, _mid_i, _flags_i in _ct.execute(
+ "SELECT uid, message_id, flags FROM email_message_index "
+ "WHERE owner=? AND account_key=? AND folder=? AND (" + " OR ".join(_idx_clauses) + ")",
+ _idx_params,
+ ).fetchall():
+ if _uid_i:
+ _idx_flags_by_uid[str(_uid_i)] = _flags_i or ""
+ if _mid_i:
+ _idx_flags_by_mid[str(_mid_i).strip()] = _flags_i or ""
+ except Exception as _idx_e:
+ logger.debug(f"tag filter index flag lookup skipped: {_idx_e}")
+ for r in rows_t:
+ try:
+ tg = json.loads(r[2] or "[]")
+ flags = _idx_flags_by_mid.get(str(r[0] or "").strip()) or _idx_flags_by_uid.get(str(r[1] or "").strip()) or ""
+ row_tags = set(_sanitize_visible_email_tags(tg, is_answered="\\Answered" in flags))
+ if _tag_name in row_tags:
+ if r[1]:
+ _tag_seq_fallback.append(str(r[1]).strip())
+ elif r[0]:
+ _tag_message_ids.append(str(r[0]).strip())
+ except Exception:
+ continue
+ _ct.close()
+ except Exception as _te:
+ logger.warning(f"tag filter lookup failed: {_te}")
+ if not _tag_message_ids and not _tag_seq_fallback:
+ return {"emails": [], "total": 0, "folder": folder}
+ # Exact account/folder-scoped UIDs avoid one remote IMAP search
+ # per tagged message (especially costly on Gmail). Message-ID
+ # lookup is retained only for legacy rows that have no UID.
+ def _imap_search_quote(value: str) -> str:
+ return '"' + str(value or "").replace("\\", "\\\\").replace('"', '\\"') + '"'
+ _uids = set()
+ for _mid in dict.fromkeys(_tag_message_ids):
+ if not _mid:
+ continue
+ st_m, data_m = _imap_uid_search(conn, f'(HEADER Message-ID {_imap_search_quote(_mid)}{from_clause})')
+ if st_m == "OK" and data_m and data_m[0]:
+ _uids.update(data_m[0].split())
+ for _uid in _tag_seq_fallback:
+ if _uid:
+ _uids.add(str(_uid).encode())
+ if not _uids:
+ return {"emails": [], "total": 0, "folder": folder}
+ data = [b" ".join(sorted(_uids, key=lambda x: int(x) if str(x, "ascii", "ignore").isdigit() else 0))]
+ status = "OK"
+ elif from_clause:
+ status, data = _imap_uid_search(conn, f"({from_clause.strip()})")
+ else:
+ status, data = _imap_uid_search(conn, "ALL")
+
+ # Intersect the selected filter with an IMAP-native date range.
+ # Search dates separately rather than sending the entire mailbox's
+ # UID set back to IMAP (large Gmail inboxes can exceed command limits).
+ if status == "OK" and data and data[0] and (date_from or date_to):
+ current_uids = set(data[0].split())
+ for value, keyword, add_day in ((date_from, "SINCE", False), (date_to, "BEFORE", True)):
+ if not value:
+ continue
+ try:
+ parsed_date = datetime.strptime(value, "%Y-%m-%d")
+ if add_day:
+ from datetime import timedelta as _date_delta
+ parsed_date += _date_delta(days=1)
+ date_status, date_data = _imap_uid_search(
+ conn, f'{keyword} {parsed_date.strftime("%d-%b-%Y")}'
+ )
+ if date_status != "OK":
+ status, data = date_status, date_data
+ break
+ dated_uids = set(date_data[0].split()) if date_data and date_data[0] else set()
+ current_uids &= dated_uids
+ except ValueError:
+ continue
+ if status == "OK":
+ data = [b" ".join(sorted(current_uids, key=lambda value: int(value)))]
+
+ if status != "OK" or not data[0]:
+ return {"emails": [], "total": 0, "folder": folder}
+
+ uid_list = data[0].split()
+ total = len(uid_list)
+ # Reverse for newest first, apply pagination
+ uid_list = list(reversed(uid_list))
+ if has_attachments_only:
+ # Can't filter via IMAP — widen the window so post-filter
+ # still yields enough rows to fill `limit` after dropping
+ # rows without attachments.
+ scan_window = max(400, offset + limit * 8)
+ uid_list = uid_list[:scan_window]
+ else:
+ uid_list = uid_list[offset:offset + limit]
+
+ # Preload tag rows once — keyed by uid (as str) for the emails we'll render
+ _tag_by_uid = {}
+ try:
+ import sqlite3 as _sql3
+ _c = _sql3.connect(SCHEDULED_DB)
+ _uid_strs = [u.decode() for u in uid_list]
+ if _uid_strs:
+ placeholders = ",".join("?" * len(_uid_strs))
+ _owner_clause, _owner_params = _email_tag_owner_clause(account_id, owner)
+ _account_clause, _account_params = _email_tag_account_clause(account_id)
+ rows = _c.execute(
+ f"SELECT uid, tags, spam_verdict FROM email_tags "
+ f"WHERE folder=? AND {_owner_clause} AND {_account_clause} AND uid IN ({placeholders})",
+ [folder, *_owner_params, *_account_params, *_uid_strs],
+ ).fetchall()
+ for r in rows:
+ try:
+ tg = json.loads(r[1] or "[]")
+ except Exception:
+ tg = []
+ if isinstance(tg, list):
+ tg = _sanitize_visible_email_tags(tg)
+ _tag_by_uid[r[0]] = {"tags": tg, "spam": bool(r[2])}
+ _c.close()
+ except Exception as e:
+ logger.warning(f"Tag preload failed: {e}")
+
+ # Batch fetch ALL requested UIDs in a single IMAP round-trip.
+ # Per-UID fetch was the dominant cost — N round-trips × (~5-20ms
+ # each on localhost) made 50-message lists take 250ms-1s+. The
+ # batched form trades a slightly bigger response for one round-trip.
+ emails = []
+ if uid_list:
+ uid_order = [u.decode(errors="ignore") if isinstance(u, bytes) else str(u) for u in uid_list]
+ cached_rows = {} if refresh else _email_index_rows(owner, account_id, folder, uid_order)
+ missing_uids = [u for u in uid_order if u and u not in cached_rows]
+ fetched_emails = []
+ status, msg_data = "OK", []
+ if missing_uids:
+ fetch_set = ",".join(missing_uids).encode()
+ try:
+ status, msg_data = _imap_uid_fetch(conn, fetch_set, "(UID FLAGS RFC822.HEADER RFC822.SIZE)")
+ except Exception as e:
+ logger.warning(f"Batch fetch failed, falling back to per-UID: {e}")
+ status, msg_data = "NO", []
+ # Group the batched response into per-message (meta, payload)
+ # records. Bare bytes parts must be kept: Gmail returns FLAGS
+ # after the header literal as a bare element, and dropping it
+ # rendered every Gmail message as unread/unflagged.
+ grouped = _group_uid_fetch_records(msg_data)
+
+ if status != "OK" and not grouped:
+ return {"emails": [], "total": total, "folder": folder, "offset": offset}
+
+ _tag_by_message_id = {}
+ try:
+ header_ids = []
+ for _, raw_header in grouped:
+ if not raw_header:
+ continue
+ mid = (email_mod.message_from_bytes(raw_header).get("Message-ID", "") or "").strip()
+ if mid:
+ header_ids.append(mid)
+ if header_ids:
+ import sqlite3 as _sql3m
+ _cm = _sql3m.connect(SCHEDULED_DB)
+ _owner_clause_m, _owner_params_m = _email_tag_owner_clause(account_id, owner)
+ _account_clause_m, _account_params_m = _email_tag_account_clause(account_id)
+ _mid_ph = ",".join("?" * len(header_ids))
+ rows_m = _cm.execute(
+ f"SELECT message_id, tags, spam_verdict FROM email_tags "
+ f"WHERE folder=? AND {_owner_clause_m} AND {_account_clause_m} "
+ f"AND message_id IN ({_mid_ph})",
+ [folder, *_owner_params_m, *_account_params_m, *header_ids],
+ ).fetchall()
+ _cm.close()
+ for mid, tags_raw, spam_raw in rows_m:
+ try:
+ tags = json.loads(tags_raw or "[]")
+ except Exception:
+ tags = []
+ if isinstance(tags, list):
+ tags = _sanitize_visible_email_tags(tags)
+ _tag_by_message_id[(mid or "").strip()] = {
+ "tags": tags if isinstance(tags, list) else [],
+ "spam": bool(spam_raw),
+ }
+ except Exception as e:
+ logger.warning(f"Message-ID tag preload failed: {e}")
+
+ for meta_b, raw_header in grouped:
+ parsed = _parse_email_list_record(meta_b, raw_header)
+ if parsed:
+ fetched_emails.append(parsed)
+ cached_rows[parsed["uid"]] = parsed
+ _email_index_upsert(owner, account_id, folder, fetched_emails)
+ for uid_num in uid_order:
+ row = cached_rows.get(uid_num)
+ if not row:
+ continue
+ tag_entry = _tag_by_message_id.get((row.get("message_id") or "").strip()) or _tag_by_uid.get(uid_num, {})
+ item = dict(row)
+ item["tags"] = _sanitize_visible_email_tags(tag_entry.get("tags", []), is_answered=bool(item.get("is_answered")))
+ item["is_spam_verdict"] = tag_entry.get("spam", False)
+ emails.append(item)
+ # IMAP returns batched results in seq-set order, not the
+ # newest-first order we want. Sort by the parsed UTC epoch
+ # so cross-timezone dates compare chronologically (ISO-string
+ # sort had `+02:00` beating `+00:00` at the same local time).
+ emails.sort(key=lambda x: x.get("date_epoch") or 0.0, reverse=True)
+
+ if emails:
+ try:
+ import sqlite3 as _sql3i
+ _ci = _sql3i.connect(SCHEDULED_DB)
+ _owner_clause_i, _owner_params_i = _email_tag_owner_clause(account_id, owner)
+ _account_clause_i, _account_params_i = _email_tag_account_clause(account_id)
+ uid_vals = [str(e.get("uid") or "") for e in emails if e.get("uid")]
+ mid_vals = [(e.get("message_id") or "").strip() for e in emails if e.get("message_id")]
+ clauses = []
+ params = [folder, *_owner_params_i, *_account_params_i]
+ if uid_vals:
+ clauses.append("uid IN (" + ",".join("?" * len(uid_vals)) + ")")
+ params.extend(uid_vals)
+ if mid_vals:
+ clauses.append("message_id IN (" + ",".join("?" * len(mid_vals)) + ")")
+ params.extend(mid_vals)
+ tag_by_uid = {}
+ tag_by_mid = {}
+ if clauses:
+ rows_i = _ci.execute(
+ f"SELECT uid, message_id, tags, spam_verdict FROM email_tags "
+ f"WHERE folder=? AND {_owner_clause_i} AND {_account_clause_i} AND ({' OR '.join(clauses)})",
+ params,
+ ).fetchall()
+ for uid_i, mid_i, tags_raw_i, spam_i in rows_i:
+ try:
+ tags_i = json.loads(tags_raw_i or "[]")
+ except Exception:
+ tags_i = []
+ if isinstance(tags_i, list):
+ tags_i = _sanitize_visible_email_tags(tags_i)
+ entry_i = {"tags": tags_i if isinstance(tags_i, list) else [], "spam": bool(spam_i)}
+ if uid_i:
+ tag_by_uid[str(uid_i)] = entry_i
+ if mid_i:
+ tag_by_mid[str(mid_i).strip()] = entry_i
+ _ci.close()
+ for e in emails:
+ tag_entry = tag_by_mid.get((e.get("message_id") or "").strip()) or tag_by_uid.get(str(e.get("uid") or ""))
+ if tag_entry:
+ e["tags"] = _sanitize_visible_email_tags(tag_entry.get("tags", []), is_answered=bool(e.get("is_answered")))
+ e["is_spam_verdict"] = tag_entry.get("spam", False)
+ except Exception as e:
+ logger.debug(f"email index tag merge skipped: {e}")
+
+ try:
+ import sqlite3 as _sql3c
+ ids = [(e.get("message_id") or "").strip() for e in emails if e.get("message_id")]
+ if ids:
+ _ccal = _sql3c.connect(SCHEDULED_DB)
+ owner_clause, owner_params = _email_cache_owner_clause(owner)
+ ph = ",".join("?" * len(ids))
+ cal_rows = _ccal.execute(
+ f"SELECT message_id, event_uids FROM email_calendar_extractions "
+ f"WHERE message_id IN ({ph}) AND {owner_clause}",
+ (*ids, *owner_params),
+ ).fetchall()
+ _ccal.close()
+ by_mid = {}
+ for mid, raw_uids in cal_rows:
+ try:
+ uids = json.loads(raw_uids or "[]")
+ except Exception:
+ uids = []
+ if isinstance(uids, list):
+ by_mid[(mid or "").strip()] = [str(u).strip() for u in uids if str(u).strip()]
+ for e in emails:
+ event_uids = by_mid.get((e.get("message_id") or "").strip()) or []
+ if event_uids:
+ e["calendar_event_uids"] = event_uids
+ except Exception as e:
+ logger.debug(f"email calendar event link attach skipped: {e}")
+
+ _hide_unlinked_calendar_tags(emails)
+ if filter_ and filter_.startswith("tag:") and filter_ != "tag:spam":
+ _final_tag = filter_[len("tag:"):].strip().lower().replace("_", "-")
+ emails = [e for e in emails if _final_tag in (e.get("tags") or [])]
+ total = len(emails)
+
+ if has_attachments_only:
+ emails = [e for e in emails if e.get("has_attachments")]
+ # Total now reflects matches inside the scanned window, not
+ # the whole folder — see scan_window above.
+ total = len(emails)
+ emails = emails[offset:offset + limit]
+
+ # Bulk-attach cached AI summaries by Message-ID so the frontend
+ # can show them on hover (avoids a per-card round-trip).
+ try:
+ ids = [e.get("message_id", "") for e in emails if e.get("message_id")]
+ if ids:
+ import sqlite3 as _sql3
+ _c = _sql3.connect(SCHEDULED_DB)
+ placeholders = ",".join("?" * len(ids))
+ owner_clause, owner_params = _email_cache_owner_clause(owner)
+ rows = _c.execute(
+ f"SELECT message_id, summary FROM email_summaries "
+ f"WHERE message_id IN ({placeholders}) AND {owner_clause}",
+ (*ids, *owner_params),
+ ).fetchall()
+ _c.close()
+ by_id = {r[0]: r[1] for r in rows}
+ for e in emails:
+ s = by_id.get(e.get("message_id", ""))
+ if s:
+ e["cached_summary"] = s
+ except Exception as _summary_err:
+ logger.debug(f"Bulk summary attach skipped: {_summary_err}")
+
+ return {
+ "emails": emails,
+ "total": total,
+ "folder": folder,
+ "offset": offset,
+ "sync": {
+ "source": "imap",
+ "indexed": len(cached_rows) if uid_list else 0,
+ "updated_at": datetime.utcnow().isoformat() + "Z",
+ },
+ }
+ except EmailNotConfiguredError:
+ # Send-only (SMTP-only) account: there is no inbox to read, so the
+ # poll returns an empty list instead of a per-minute error. SMTP
+ # send is unaffected.
+ return {"emails": [], "total": 0, "folder": folder, "offset": offset}
+ except Exception as e:
+ conn_ok = False
+ logger.error(f"Failed to list emails: {e}")
+ detail = str(e).strip()
+ return {"emails": [], "total": 0, "error": f"Mail operation failed: {detail[:180]}" if detail else "Mail operation failed"}
+ finally:
+ if conn:
+ _pooled_release(account_id, conn, ok=conn_ok, owner=owner)
+
+ def _related_thread_attachments_sync(
+ folder: str,
+ account_id: str | None,
+ owner: str,
+ current_uid: str,
+ current_message_id: str,
+ in_reply_to: str,
+ references: str,
+ limit: int = 12,
+ ) -> list[dict]:
+ """Return visible attachments from referenced messages in this folder."""
+ wanted_ids = _message_id_chain(references, in_reply_to)
+ current_mid = (current_message_id or "").strip()
+ wanted_ids = [mid for mid in wanted_ids if mid and mid != current_mid]
+ if not wanted_ids:
+ return []
+
+ related: list[dict] = []
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder), readonly=True)
+ # Search newest referenced messages first; cap work so opening
+ # a long thread stays bounded.
+ for mid in reversed(wanted_ids[-10:]):
+ if len(related) >= limit:
+ break
+ status, data = _imap_uid_search(conn, f'(HEADER Message-ID {_imap_search_quote(mid)})')
+ if status != "OK" or not data or not data[0]:
+ continue
+ for uid_b in reversed(data[0].split()[-3:]):
+ source_uid = uid_b.decode(errors="ignore")
+ if not source_uid or source_uid == str(current_uid):
+ continue
+ st2, msg_data = _imap_uid_fetch(conn, source_uid, "(BODY.PEEK[])")
+ if st2 != "OK" or not msg_data or not isinstance(msg_data[0], tuple):
+ continue
+ msg = email_mod.message_from_bytes(msg_data[0][1])
+ source_from = _decode_header(msg.get("From", ""))
+ source_subject = _decode_header(msg.get("Subject", ""))
+ source_date = msg.get("Date", "")
+ for att in _list_attachments_from_msg(msg):
+ if _is_likely_signature_image_attachment(att):
+ continue
+ enriched = dict(att)
+ enriched.update({
+ "source_uid": source_uid,
+ "source_folder": folder,
+ "source_message_id": (msg.get("Message-ID") or "").strip(),
+ "source_from": source_from,
+ "source_subject": source_subject,
+ "source_date": source_date,
+ })
+ related.append(enriched)
+ if len(related) >= limit:
+ break
+ except Exception as e:
+ logger.debug(f"related thread attachment lookup failed uid={current_uid}: {e}")
+ return related
+
+ @router.get("/list")
+ async def list_emails(
+ folder: str = Query("INBOX"),
+ limit: int = Query(50),
+ offset: int = Query(0),
+ filter: str = Query("all"), # all, unread, unanswered
+ from_addr: str | None = Query(None, alias="from"),
+ account_id: str | None = Query(None),
+ has_attachments: int = Query(0),
+ date_from: str | None = Query(None),
+ date_to: str | None = Query(None),
+ cached_only: int = Query(0),
+ cache_bust: str | None = Query(None, alias="_"),
+ refresh: int = Query(0),
+ owner: str = Depends(require_owner),
+ ):
+ """List emails. Uses an 8s in-memory cache + offloads blocking IMAP
+ calls to a worker thread so the event loop never stalls."""
+ started_at = _time.monotonic()
+ for field_name, value in (("date_from", date_from), ("date_to", date_to)):
+ if value:
+ try:
+ datetime.strptime(value, "%Y-%m-%d")
+ except ValueError:
+ raise HTTPException(status_code=400, detail=f"Invalid {field_name}")
+ if date_from and date_to and date_from > date_to:
+ raise HTTPException(status_code=400, detail="date_from must not be after date_to")
+ fixture_result = _fixture_email_list(folder, limit, offset, filter, from_addr, owner, bool(has_attachments))
+ if fixture_result is not None:
+ return fixture_result
+ manual_refresh = bool(refresh)
+ if cached_only and not from_addr:
+ indexed_emails, indexed_total, indexed_at = _email_index_list(
+ owner, account_id, folder, filter, limit, offset, bool(has_attachments),
+ )
+ if indexed_total:
+ _hide_unlinked_calendar_tags(indexed_emails)
+ return {
+ "emails": indexed_emails,
+ "total": indexed_total,
+ "folder": folder,
+ "offset": offset,
+ "sync": {
+ "source": "index",
+ "indexed": indexed_total,
+ "updated_at": indexed_at,
+ "cached_only": True,
+ },
+ }
+ return {
+ "emails": [],
+ "total": 0,
+ "folder": folder,
+ "offset": offset,
+ "sync": {"source": "index", "cached_only": True},
+ }
+ _deferred = getattr(_start_poller, '_deferred', None)
+ if _deferred:
+ await _deferred()
+ # SECURITY: include `owner` in the cache key so two users with
+ # different account scopes don't share a cached list.
+ ck = _list_cache_key(account_id, folder, filter, limit, offset, from_addr or "") + (int(bool(has_attachments)), date_from or "", date_to or "", owner)
+ if manual_refresh:
+ _invalidate_list_cache(account_id, folder)
+ _invalidate_imap_pool(account_id, owner)
+ if not cache_bust and not manual_refresh:
+ cached = _list_cache_get(ck)
+ if cached is not None:
+ _schedule_recent_email_warm(cached.get("emails") or [], folder, account_id, owner)
+ cached = dict(cached)
+ sync_meta = dict(cached.get("sync") or {})
+ sync_meta["source"] = "memory_cache"
+ cached["sync"] = sync_meta
+ elapsed_ms = int((_time.monotonic() - started_at) * 1000)
+ if elapsed_ms > 500:
+ logger.info(
+ "email list cache hit slow owner=%s account=%s folder=%s filter=%s limit=%s offset=%s total=%sms",
+ owner, account_id or "", folder, filter, limit, offset, elapsed_ms,
+ )
+ return cached
+ result = await _asyncio.to_thread(
+ _list_emails_sync, folder, limit, offset, filter, account_id, from_addr,
+ bool(has_attachments), owner, manual_refresh, date_from or "", date_to or "",
+ )
+ if result and not result.get("error"):
+ if offset == 0 and not from_addr and not has_attachments and filter in ("all", "unread", "unanswered", "undone"):
+ _record_email_received_events(owner, account_id, folder, result.get("emails") or [])
+ _schedule_recent_email_warm(result.get("emails") or [], folder, account_id, owner)
+ _list_cache_put(ck, result)
+ elapsed_ms = int((_time.monotonic() - started_at) * 1000)
+ if elapsed_ms > 1500:
+ logger.warning(
+ "Slow email list owner=%s account=%s folder=%s filter=%s limit=%s offset=%s cache_bust=%s emails=%s total=%s elapsed=%sms",
+ owner, account_id or "", folder, filter, limit, offset, bool(cache_bust),
+ len((result or {}).get("emails") or []), (result or {}).get("total"), elapsed_ms,
+ )
+ return result
+
+ @router.get("/unread-state")
+ async def unread_state(
+ folder: str = Query("INBOX"),
+ account_id: str | None = Query(None),
+ owner: str = Depends(require_owner),
+ ):
+ """Cheap unread summary for notification dots.
+
+ Reads the local message index first so periodic UI polling does not
+ trigger Gmail SEARCH/LIST round-trips. If no local index exists for the
+ account/folder yet, do one tiny IMAP fallback and then cache naturally
+ through the list path.
+ """
+ fixture_result = _fixture_email_list(folder, 1, 0, "unread", None, owner)
+ if fixture_result is not None:
+ return {
+ "unread_count": int(fixture_result.get("total") or 0),
+ "max_uid": max([int(e.get("uid") or 0) for e in _fixture_email_rows(owner)] or [0]),
+ "folder": folder,
+ "sync": {"source": "local"},
+ }
+ try:
+ account_key = _account_cache_key(account_id, owner)
+ conn = _sql3.connect(SCHEDULED_DB)
+ try:
+ row = conn.execute(
+ """
+ SELECT COUNT(*),
+ MAX(CASE WHEN uid GLOB '[0-9]*' THEN CAST(uid AS INTEGER) ELSE 0 END),
+ MAX(updated_at)
+ FROM email_message_index
+ WHERE owner=? AND account_key=? AND folder=?
+ AND (flags IS NULL OR instr(flags, '\\Seen') = 0)
+ """,
+ (owner or "", account_key, folder),
+ ).fetchone()
+ total_row = conn.execute(
+ "SELECT COUNT(*), MAX(updated_at) FROM email_message_index WHERE owner=? AND account_key=? AND folder=?",
+ (owner or "", account_key, folder),
+ ).fetchone()
+ finally:
+ conn.close()
+ indexed_total = int((total_row or [0])[0] or 0)
+ if indexed_total:
+ return {
+ "unread_count": int((row or [0])[0] or 0),
+ "max_uid": int((row or [0, 0])[1] or 0),
+ "folder": folder,
+ "sync": {
+ "source": "index",
+ "indexed": indexed_total,
+ "updated_at": (total_row or [None, None])[1],
+ },
+ }
+ except Exception:
+ logger.debug("unread-state index lookup skipped", exc_info=True)
+
+ result = await _asyncio.to_thread(
+ _list_emails_sync, folder, 1, 0, "unread", account_id, None, False, owner,
+ )
+ emails = (result or {}).get("emails") or []
+ max_uid = 0
+ if emails:
+ try:
+ max_uid = max(int(e.get("uid") or 0) for e in emails)
+ except Exception:
+ max_uid = 0
+ return {
+ "unread_count": int((result or {}).get("total") or len(emails) or 0),
+ "max_uid": max_uid,
+ "folder": folder,
+ "sync": {"source": "imap_fallback"},
+ }
+
+ @router.post("/{uid}/unflag-spam")
+ async def unflag_spam(uid: str, owner: str = Depends(require_owner)):
+ """User override — mark email as not spam."""
+ try:
+ owner_clause, owner_params = _email_tag_owner_clause(None, owner)
+ _c = _sql3.connect(SCHEDULED_DB)
+ _c.execute(
+ f"UPDATE email_tags SET spam_verdict=0, spam_reason='' WHERE uid=? AND {owner_clause}",
+ [uid, *owner_params],
+ )
+ _c.commit()
+ _c.close()
+ return {"ok": True}
+ except Exception as e:
+ logger.error(f"unflag-spam failed: {e}")
+ return {"ok": False, "error": "Mail operation failed"}
+
+ def _unsubscribe_spam_cache(owner: str, account_id: str | None, folder: str) -> dict[str, dict]:
+ out: dict[str, dict] = {}
+ try:
+ conn = _sql3.connect(SCHEDULED_DB)
+ try:
+ owner_clause, owner_params = _email_tag_owner_clause(account_id, owner)
+ account_clause, account_params = _email_tag_account_clause(account_id)
+ rows = conn.execute(
+ "SELECT uid, message_id, spam_verdict, spam_reason FROM email_tags "
+ "WHERE folder=? AND "
+ f"{owner_clause} AND {account_clause}",
+ (folder, *owner_params, *account_params),
+ ).fetchall()
+ finally:
+ conn.close()
+ for uid, message_id, spam_verdict, spam_reason in rows:
+ payload = {"spam": bool(spam_verdict), "reason": spam_reason or ""}
+ if uid:
+ out[str(uid)] = payload
+ if message_id:
+ out[str(message_id).strip()] = payload
+ except Exception:
+ logger.debug("unsubscribe spam cache lookup skipped", exc_info=True)
+ return out
+
+ def _scan_unsubscribe_candidates_sync(folder: str, account_id: str | None, owner: str, limit: int, max_scan: int) -> dict:
+ folder = folder or "INBOX"
+ limit = max(1, min(int(limit or 25), 500))
+ requested_max_scan = int(max_scan or 0)
+ # A synchronous request cannot safely inspect an unbounded mailbox:
+ # Gmail, in particular, can take minutes to search/fetch old headers.
+ # Keep the normal review responsive while allowing callers to request
+ # a larger bounded page explicitly.
+ max_scan = max(limit, min(requested_max_scan or 500, 500))
+ spam_cache = _unsubscribe_spam_cache(owner, account_id, folder)
+ candidates: list[dict] = []
+ with _imap(account_id, owner=owner) as conn:
+ st, _ = conn.select(_q(folder), readonly=True)
+ if st != "OK":
+ return {"success": False, "error": f"Folder not found: {folder}", "candidates": []}
+ st, data = _imap_uid_search(conn, "ALL")
+ if st != "OK":
+ return {"success": False, "error": "Failed to search email headers", "candidates": []}
+ if not data or not data[0]:
+ return {"success": True, "candidates": [], "total": 0, "scanned": 0, "folder": folder}
+ uids = []
+ for raw_uid in data[0].split():
+ try:
+ uids.append(int(raw_uid))
+ except Exception:
+ continue
+ uids = sorted(uids, reverse=True)
+ if max_scan is not None:
+ uids = uids[:max_scan]
+ if not uids:
+ return {"success": True, "candidates": [], "total": 0, "scanned": 0, "folder": folder}
+ msg_data = []
+ fetched_any = False
+ for start in range(0, len(uids), 100):
+ batch_uids = uids[start:start + 100]
+ fetch_set = ",".join(str(u) for u in batch_uids)
+ try:
+ st, batch = _imap_uid_fetch(conn, fetch_set, "(UID RFC822.HEADER)")
+ except Exception:
+ st, batch = "NO", []
+ if st == "OK":
+ fetched_any = True
+ msg_data.extend(batch or [])
+ continue
+ # Some providers reject multi-UID FETCH even though a
+ # single-UID FETCH works. Keep the bounded scan useful instead
+ # of turning that provider quirk into a total error.
+ for uid in batch_uids:
+ try:
+ single_status, single = _imap_uid_fetch(conn, str(uid), "(UID RFC822.HEADER)")
+ except Exception:
+ single_status, single = "NO", []
+ if single_status == "OK":
+ fetched_any = True
+ msg_data.extend(single or [])
+ if not fetched_any:
+ return {"success": False, "error": "Failed to fetch email headers", "candidates": []}
+ fetch_records = _group_uid_fetch_records(msg_data)
+ for meta_b, raw_header in fetch_records:
+ uid = _uid_from_fetch_meta(meta_b)
+ if not uid:
+ continue
+ try:
+ msg = email_mod.message_from_bytes(raw_header or b"")
+ except Exception:
+ continue
+ mid = (msg.get("Message-ID") or "").strip()
+ spam_info = spam_cache.get(uid) or (spam_cache.get(mid) if mid else None) or {}
+ candidate = _email_unsubscribe_candidate_from_msg(msg, uid, folder, spam_cached=spam_info)
+ if candidate:
+ candidates.append(candidate)
+ def _uid_sort_value(candidate: dict) -> int:
+ try:
+ return int(candidate.get("uid") or 0)
+ except Exception:
+ return 0
+ raw_total = len(candidates)
+ candidates = _dedupe_unsubscribe_candidates(candidates)
+ candidates.sort(key=lambda c: (int(c.get("score") or 0), int(c.get("duplicate_count") or 1), _uid_sort_value(c)), reverse=True)
+ return {
+ "success": True,
+ "candidates": candidates[:limit],
+ "total": len(candidates),
+ "raw_total": raw_total,
+ "scanned": len(uids),
+ "scan_mode": "bounded",
+ "has_more": bool(len(uids) >= max_scan),
+ "folder": folder,
+ "account_id": account_id or "",
+ }
+
+ def _unsubscribe_sender_uids_sync(
+ folder: str,
+ account_id: str | None,
+ owner: str,
+ sender: str,
+ ) -> list[str]:
+ """Find every source-folder message from a sender with List-Unsubscribe.
+
+ This is deliberately stricter than a sender-only cleanup: a normal
+ message from the same address must not be moved just because one
+ newsletter from that sender was unsubscribed.
+ """
+ _, sender_addr = email.utils.parseaddr(str(sender or ""))
+ sender_key = (sender_addr or str(sender or "")).strip().lower()
+ if not sender_key:
+ return []
+ found: list[str] = []
+ with _imap(account_id, owner=owner) as conn:
+ st, _ = conn.select(_q(folder), readonly=True)
+ if st != "OK":
+ return []
+ # Restrict the server-side search to this sender before fetching
+ # headers. Searching ALL and then fetching the whole mailbox made
+ # sender cleanup unnecessarily slow for large inboxes.
+ st, data = _imap_uid_search(conn, f'FROM {_imap_search_quote(sender_key)}')
+ if st != "OK" or not data or not data[0]:
+ return []
+ raw_uids = []
+ for raw_uid in data[0].split():
+ try:
+ raw_uids.append(int(raw_uid))
+ except Exception:
+ continue
+ # Keep each FETCH reasonably sized for IMAP servers with strict
+ # command-line limits while still scanning the whole folder.
+ for start in range(0, len(raw_uids), 200):
+ fetch_set = ",".join(str(uid) for uid in raw_uids[start:start + 200])
+ st, msg_data = _imap_uid_fetch(conn, fetch_set, "(UID RFC822.HEADER)")
+ if st != "OK":
+ continue
+ for meta_b, raw_header in _group_uid_fetch_records(msg_data):
+ uid = _uid_from_fetch_meta(meta_b)
+ if not uid or not raw_header:
+ continue
+ try:
+ msg = email_mod.message_from_bytes(raw_header)
+ except Exception:
+ continue
+ candidate = _email_unsubscribe_candidate_from_msg(msg, uid, folder)
+ if candidate and str(candidate.get("from_address") or "").strip().lower() == sender_key:
+ found.append(uid)
+ return found
+
+ @router.get("/unsubscribe/scan")
+ async def scan_unsubscribe_candidates(
+ folder: str = Query("INBOX"),
+ account_id: str | None = Query(None),
+ limit: int = Query(25),
+ max_scan: int = Query(500),
+ owner: str = Depends(require_owner),
+ ):
+ """Review-only scan for spam/newsletter unsubscribe candidates."""
+ if account_id:
+ _assert_owns_account(account_id, owner)
+ if _fixture_email_enabled():
+ return {"success": True, "candidates": [], "total": 0, "scanned": 0, "folder": folder, "sync": {"source": "local"}}
+ try:
+ return await _asyncio.to_thread(_scan_unsubscribe_candidates_sync, folder, account_id, owner, limit, max_scan)
+ except Exception as e:
+ logger.error(f"unsubscribe scan failed: {e}")
+ return {"success": False, "error": "Mail operation failed", "candidates": []}
+
+ @router.post("/unsubscribe/execute")
+ def execute_unsubscribe(data: dict, owner: str = Depends(require_owner)):
+ """Execute an approved unsubscribe action.
+
+ First implementation supports mailto List-Unsubscribe only. The message
+ header is re-read server-side; client-supplied addresses are not trusted.
+ """
+ uid = str((data or {}).get("uid") or "").strip()
+ folder = str((data or {}).get("folder") or "INBOX").strip() or "INBOX"
+ account_id = (data or {}).get("account_id") or None
+ method_index = int((data or {}).get("method_index") or 0)
+ move_to_spam = bool((data or {}).get("move_to_spam"))
+ if not uid:
+ raise HTTPException(400, "Missing uid")
+ if account_id:
+ _assert_owns_account(account_id, owner)
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ st, _ = conn.select(_q(folder), readonly=True)
+ if st != "OK":
+ return {"success": False, "error": f"Folder not found: {folder}"}
+ st, msg_data = _imap_uid_fetch(conn, uid, "(UID RFC822.HEADER)")
+ if st != "OK" or not msg_data:
+ return {"success": False, "error": "Email not found"}
+ raw_header = b""
+ for item in msg_data or []:
+ if isinstance(item, tuple) and len(item) >= 2:
+ raw_header = item[1] or b""
+ break
+ msg = email_mod.message_from_bytes(raw_header)
+ candidate = _email_unsubscribe_candidate_from_msg(msg, uid, folder)
+ if not candidate:
+ return {"success": False, "error": "No unsubscribe header found for this email"}
+ methods = [m for m in (candidate.get("methods") or []) if m.get("kind") == "mailto" and m.get("executable")]
+ if not methods:
+ return {"success": False, "error": "This email only has web unsubscribe links; open manually for now", "candidate": candidate}
+ method = methods[method_index] if 0 <= method_index < len(methods) else methods[0]
+ target = str(method.get("target") or "").strip()
+ if not target or "\r" in target or "\n" in target:
+ return {"success": False, "error": "Invalid unsubscribe address"}
+ cfg = _resolve_send_config(account_id, owner=owner)
+ subject = str(method.get("subject") or "unsubscribe")[:200]
+ body = str(method.get("body") or "unsubscribe")[:1000]
+ msg_out = MIMEText(body or "unsubscribe", "plain", "utf-8")
+ msg_out["From"] = email.utils.formataddr((cfg.get("display_name") or "", cfg["from_address"]))
+ msg_out["To"] = target
+ msg_out["Subject"] = subject
+ msg_out["Message-ID"] = email.utils.make_msgid(domain="odysseus.local")
+ _apply_odysseus_headers(msg_out, "unsubscribe", uid)
+ _send_smtp_message(cfg, cfg["from_address"], [target], msg_out.as_string())
+ moved = False
+ deleted = False
+ delete_error = ""
+ if move_to_spam:
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder))
+ moved = _move_email_message(conn, uid, "Junk", role="junk")
+ if moved:
+ _email_index_delete(owner, account_id, folder, uid)
+ _invalidate_list_cache(account_id)
+ except Exception:
+ logger.debug("unsubscribe move-to-spam skipped", exc_info=True)
+ else:
+ # A successful unsubscribe should not be rediscovered on the
+ # next scan. Keep the message in Trash when possible, with the
+ # same permanent-delete fallback used by the normal delete API.
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder))
+ deleted = _move_email_message(conn, uid, "Trash", role="trash")
+ if not deleted:
+ deleted = _store_email_flag(conn, uid, "\\Deleted", add=True)
+ if deleted:
+ conn.expunge()
+ if deleted:
+ _email_index_delete(owner, account_id, folder, uid)
+ _invalidate_list_cache(account_id)
+ except Exception as exc:
+ delete_error = "Email was unsubscribed but could not be moved to Trash"
+ logger.debug("unsubscribe delete skipped uid=%s: %s", uid, exc, exc_info=True)
+ return {
+ "success": True,
+ "method": method,
+ "candidate": candidate,
+ "moved_to_spam": moved,
+ "deleted": deleted,
+ **({"delete_error": delete_error} if delete_error else {}),
+ }
+ except ValueError as e:
+ return {"success": False, "error": str(e)}
+ except Exception as e:
+ logger.error(f"unsubscribe execute failed uid={uid}: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.post("/unsubscribe/cleanup")
+ def cleanup_unsubscribe_candidates(data: dict, owner: str = Depends(require_owner)):
+ """Move reviewed unsubscribe candidates to Junk, Trash, or both."""
+ folder = str((data or {}).get("folder") or "INBOX").strip() or "INBOX"
+ account_id = (data or {}).get("account_id") or None
+ action = str((data or {}).get("action") or "").strip().lower()
+ raw_uids = (data or {}).get("uids") or []
+ scope = str((data or {}).get("scope") or "").strip().lower()
+ sender = str((data or {}).get("sender") or "").strip()
+ if action not in {"junk", "delete", "junk_delete"}:
+ raise HTTPException(400, "Unsupported cleanup action")
+ if account_id:
+ _assert_owns_account(account_id, owner)
+ uids: list[str] = []
+ seen = set()
+ for raw_uid in raw_uids:
+ uid = str(raw_uid or "").strip()
+ if not uid or uid in seen:
+ continue
+ if not uid.isdigit():
+ continue
+ seen.add(uid)
+ uids.append(uid)
+ if scope == "sender_unsubscribe":
+ if not sender:
+ raise HTTPException(400, "Missing sender for sender unsubscribe cleanup")
+ try:
+ sender_uids = _unsubscribe_sender_uids_sync(folder, account_id, owner, sender)
+ except Exception:
+ logger.debug("sender unsubscribe scan failed", exc_info=True)
+ sender_uids = []
+ for uid in sender_uids:
+ if uid not in seen:
+ seen.add(uid)
+ uids.append(uid)
+ if not uids:
+ if scope == "sender_unsubscribe":
+ return {
+ "success": True,
+ "action": action,
+ "changed": 0,
+ "failed": 0,
+ "cleaned_uids": [],
+ }
+ return {"success": False, "error": "No email UIDs provided", "changed": 0, "failed": 0}
+ role = "junk" if action in {"junk", "junk_delete"} else "trash"
+ target = "Junk" if action in {"junk", "junk_delete"} else "Trash"
+ changed = 0
+ failed = 0
+ cleaned_uids: list[str] = []
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder))
+ for uid in uids:
+ try:
+ moved = (
+ _copy_and_delete_email_message(conn, uid, target, role=role)
+ if action == "junk_delete"
+ else _move_email_message(conn, uid, target, role=role)
+ )
+ if moved:
+ changed += 1
+ cleaned_uids.append(uid)
+ _email_index_delete(owner, account_id, folder, uid)
+ else:
+ failed += 1
+ except Exception:
+ failed += 1
+ logger.debug("unsubscribe cleanup failed for uid=%s", uid, exc_info=True)
+ if changed:
+ _invalidate_list_cache(account_id)
+ return {
+ "success": True,
+ "action": action,
+ "changed": changed,
+ "failed": failed,
+ "cleaned_uids": cleaned_uids,
+ }
+ except Exception as e:
+ logger.error(f"unsubscribe cleanup failed: {e}")
+ return {
+ "success": False,
+ "error": "Mail operation failed",
+ "changed": changed,
+ "failed": failed,
+ "cleaned_uids": cleaned_uids,
+ }
+
+ @router.get("/contacts")
+ async def list_contacts(
+ q: str = Query(""),
+ limit: int = Query(20),
+ owner: str = Depends(require_owner),
+ ):
+ """Distinct name/address pairs aggregated from the email_tags table
+ — used by the from-sender sidebar's autocomplete to convert typed
+ names into chips. Backed by the AI-classification cache so it's a
+ cheap SQL read; people you've never received a tagged email from
+ won't appear yet."""
+ ql = (q or "").strip().lower()
+ try:
+ conn = _sql3.connect(SCHEDULED_DB)
+ owner_clause, owner_params = _email_tag_owner_clause(None, owner)
+ rows = conn.execute(
+ f"SELECT sender FROM email_tags WHERE sender IS NOT NULL AND sender != '' AND {owner_clause}",
+ owner_params,
+ ).fetchall()
+ conn.close()
+ seen = {}
+ for (s,) in rows:
+ try:
+ name, addr = email.utils.parseaddr(s or "")
+ except Exception:
+ continue
+ if not addr:
+ continue
+ addr_l = addr.lower()
+ if ql and ql not in (name or "").lower() and ql not in addr_l:
+ continue
+ if addr_l in seen:
+ continue
+ seen[addr_l] = {"name": (name or addr).strip(), "address": addr}
+ items = list(seen.values())
+ # Prefer entries whose name starts with the query, then alphabetical.
+ items.sort(key=lambda c: (
+ 0 if ql and (c["name"] or "").lower().startswith(ql) else 1,
+ (c["name"] or c["address"]).lower(),
+ ))
+ return {"contacts": items[: max(1, int(limit))]}
+ except Exception as e:
+ logger.error(f"contacts list failed: {e}")
+ return {"contacts": [], "error": "Mail operation failed"}
+
+ @router.get("/search")
+ # Sync def: the body is blocking IMAP I/O with no awaits. As `async def` it ran
+ # directly on the event loop and stalled the whole app during a search; as a sync
+ # def FastAPI runs it in a threadpool, keeping the loop responsive.
+ def search_emails(
+ q: str = Query(""),
+ folder: str = Query("INBOX"),
+ limit: int = Query(50),
+ account_id: str | None = Query(None),
+ local_only: bool = Query(False),
+ scope: str = Query("all"),
+ owner: str = Depends(require_owner),
+ ):
+ """Search emails server-side via IMAP SEARCH. Matches subject, from, or body text.
+
+ When the caller asks for INBOX and the account has an "All Mail"
+ folder (Gmail does), we transparently swap to All Mail so the
+ search surfaces archived / labelled emails too. Plain IMAP
+ accounts fall back to whatever folder the caller specified."""
+ if not q or len(q) < 2:
+ return {"emails": [], "total": 0, "query": q}
+ # CRLF in q would terminate the IMAP command early — reject defensively.
+ if "\r" in q or "\n" in q:
+ raise HTTPException(400, "Invalid query")
+ global_search = (scope or "all").lower() != "folder"
+ fixture_result = _fixture_email_list(
+ "all" if global_search else folder,
+ limit,
+ 0,
+ "all",
+ None,
+ owner,
+ False,
+ query=q,
+ )
+ if fixture_result is not None:
+ return {
+ "emails": fixture_result.get("emails") or [],
+ "total": fixture_result.get("total") or 0,
+ "query": q,
+ "folder": folder,
+ "source": "local",
+ "sync": fixture_result.get("sync") or {"source": "local"},
+ }
+ indexed_response = None
+ try:
+ indexed_emails, indexed_total, indexed_at = _email_index_search(owner, account_id, folder, q, limit, global_search=global_search)
+ indexed_response = {
+ "emails": indexed_emails,
+ "total": indexed_total,
+ "query": q,
+ "folder": folder,
+ "source": "index",
+ "sync": {
+ "source": "index",
+ "updated_at": indexed_at,
+ },
+ }
+ if local_only:
+ return indexed_response
+
+ with _imap(account_id, owner=owner) as conn:
+ # If the user asked for INBOX, try to upgrade to All Mail —
+ # one folder == every email on Gmail-class servers.
+ effective_folder = folder
+ if global_search and (folder or "").upper() == "INBOX":
+ try:
+ status, folder_lines = conn.list()
+ if status == "OK" and folder_lines:
+ for raw in folder_lines:
+ if isinstance(raw, bytes):
+ raw = raw.decode("utf-8", errors="replace")
+ m = re.match(r"\((?P<flags>[^)]*)\)\s+\"[^\"]*\"\s+(?P<name>.+)", raw)
+ if not m:
+ continue
+ flags = (m.group("flags") or "").lower()
+ name = m.group("name").strip().strip('"')
+ if "\\all" in flags or "all mail" in name.lower():
+ effective_folder = name
+ break
+ except Exception:
+ pass
+ select_status, _ = conn.select(_q(effective_folder), readonly=True)
+ if select_status != "OK":
+ resolved_folder = _resolve_mail_folder(conn, effective_folder, role=_mail_folder_role_hint(effective_folder))
+ if resolved_folder != effective_folder:
+ retry_status, _ = conn.select(_q(resolved_folder), readonly=True)
+ if retry_status == "OK":
+ effective_folder = resolved_folder
+ select_status = retry_status
+ if select_status != "OK":
+ return {"emails": [], "total": 0, "query": q, "folder": effective_folder, "error": f"Folder not found: {effective_folder}"}
+
+ search_cmd = _email_imap_search_criteria(q)
+
+ status, data = _imap_uid_search(conn, search_cmd)
+ if status != "OK" or not data[0]:
+ if indexed_response and indexed_response.get("emails"):
+ indexed_response["fallback"] = True
+ indexed_response["source"] = "index"
+ indexed_response["sync"] = {
+ **(indexed_response.get("sync") or {}),
+ "fallback_reason": "imap_empty" if status == "OK" else "imap_search_failed",
+ }
+ return indexed_response
+ return {
+ "emails": [],
+ "total": 0,
+ "query": q,
+ "folder": effective_folder,
+ "source": "imap",
+ "sync": {
+ "source": "imap",
+ "updated_at": datetime.utcnow().isoformat() + "Z",
+ },
+ }
+
+ uid_list = data[0].split()
+ total = len(uid_list)
+ uid_list = list(reversed(uid_list))[:limit]
+
+ uid_order = [uid.decode(errors="ignore") if isinstance(uid, bytes) else str(uid) for uid in uid_list]
+ cached_rows = _email_index_rows(owner, account_id, effective_folder, uid_order)
+ emails = []
+ fetched_emails = []
+ for uid in uid_order:
+ cached = cached_rows.get(uid)
+ if cached:
+ item = dict(cached)
+ item["folder"] = effective_folder
+ emails.append(item)
+ continue
+ try:
+ status, msg_data = _imap_uid_fetch(conn, uid, "(UID FLAGS RFC822.HEADER)")
+ if status != "OK":
+ continue
+ raw_header = None
+ flags = ""
+ # Same Gmail caveat as the list route: FLAGS may
+ # arrive after the header literal, so group bare
+ # parts back into the message meta before scanning.
+ for meta_b, payload in _group_uid_fetch_records(msg_data):
+ if payload and b"RFC822.HEADER" in meta_b:
+ raw_header = payload
+ flag_match = re.search(rb'FLAGS \(([^)]*)\)', meta_b)
+ if flag_match:
+ flags = flag_match.group(1).decode(errors="replace")
+ if not raw_header:
+ continue
+ parsed = None
+ for meta_b, payload in _group_uid_fetch_records(msg_data):
+ parsed = _parse_email_list_record(meta_b, payload)
+ if parsed:
+ break
+ if not parsed:
+ continue
+ parsed["folder"] = effective_folder
+ emails.append(parsed)
+ fetched_emails.append(parsed)
+ except Exception as e:
+ logger.warning(f"Error parsing search result {uid}: {e}")
+ continue
+ _email_index_upsert(owner, account_id, effective_folder, fetched_emails)
+
+ return {
+ "emails": emails,
+ "total": total,
+ "query": q,
+ "folder": effective_folder,
+ "source": "imap",
+ "sync": {
+ "source": "imap",
+ "updated_at": datetime.utcnow().isoformat() + "Z",
+ },
+ }
+ except Exception as e:
+ logger.error(f"Search failed: {e}")
+ if indexed_response and indexed_response.get("emails"):
+ indexed_response["fallback"] = True
+ return indexed_response
+ return {"emails": [], "total": 0, "error": "Mail operation failed"}
+
+ def _read_email_sync(uid, folder, account_id, owner, mark_seen=False, full=False):
+ """Sync IMAP read — wrapped in to_thread by the async handler.
+
+ The normal reader path fetches the headers plus a bounded body prefix.
+ That avoids downloading multi-megabyte attachments just to open a
+ message. Full-message fetch remains available for flows that need
+ attachment metadata immediately, such as forwarding.
+
+ `mark_seen` defaults to False because it mutates provider state: it
+ selects the mailbox read-write and issues a STORE. Only a foreground
+ open should ask for it, and it has to ask explicitly.
+
+ A failed \\Seen transition is reported as `mark_seen_failed` on an
+ otherwise normal response, never as an error. The body has already been
+ fetched at that point, so refusing to return it would turn a cosmetic
+ flag failure into an unreadable message.
+ """
+ import time as _t
+ _t0 = _t.monotonic()
+ raw = None
+ preview_bytes = 384 * 1024
+ _t_select = 0.0
+ _t_fetch = 0.0
+ mark_seen_failed = False
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ # A foreground open owns both the body fetch and the \Seen
+ # transition. Keep them on one read-write IMAP selection so the
+ # route never schedules a second connection that can race the
+ # response. Prefetch/read-only callers retain BODY.PEEK and a
+ # read-only mailbox selection.
+ try:
+ select_status, _ = conn.select(_q(folder), readonly=not mark_seen)
+ if select_status != "OK":
+ resolved_folder = _resolve_mail_folder(
+ conn, folder, role=_mail_folder_role_hint(folder)
+ )
+ if resolved_folder != folder:
+ select_status, _ = conn.select(
+ _q(resolved_folder), readonly=not mark_seen
+ )
+ if select_status != "OK":
+ return {"error": f"Could not open email folder: {folder}"}
+ except Exception as select_exc:
+ if not mark_seen:
+ raise
+ # Read-only mailboxes (shared archives, some provider
+ # folders) reject a read-write SELECT. Serve the message
+ # read-only and report the flag failure.
+ logger.warning(
+ f"read-write SELECT rejected for {folder!r}; "
+ f"serving read-only without \\Seen: {select_exc}"
+ )
+ select_status, _ = conn.select(_q(folder), readonly=True)
+ if select_status != "OK":
+ return {"error": f"Could not open email folder: {folder}"}
+ mark_seen_failed = True
+ _t_select = _t.monotonic() - _t0
+ fetch_query = "(BODY.PEEK[])" if full else f"(BODY.PEEK[HEADER] BODY.PEEK[TEXT]<0.{preview_bytes}>)"
+ status, msg_data = _imap_uid_fetch(conn, uid, fetch_query)
+ _t_fetch = _t.monotonic() - _t0
+ if status != "OK":
+ return {"error": f"Email UID {uid} not found"}
+ if full:
+ raw = msg_data[0][1]
+ else:
+ header_part = b""
+ text_part = b""
+ for item in msg_data or []:
+ if not isinstance(item, tuple) or len(item) < 2:
+ continue
+ meta_b = item[0] if isinstance(item[0], bytes) else str(item[0]).encode()
+ payload = item[1] or b""
+ meta_up = meta_b.upper()
+ if b"BODY[HEADER]" in meta_up:
+ header_part = payload
+ elif b"BODY[TEXT]" in meta_up:
+ text_part = payload
+ if not header_part and msg_data and isinstance(msg_data[0], tuple):
+ header_part = msg_data[0][1] or b""
+ raw = header_part + b"\r\n" + text_part
+
+ # Parse the fetched payload before mutating provider state. If
+ # the message is malformed enough that the reader cannot build
+ # a response, the caller gets an error while the message stays
+ # unread instead of receiving a false optimistic rollback.
+ msg = email_mod.message_from_bytes(raw)
+
+ subject = _decode_header(msg.get("Subject", "(no subject)"))
+ sender = _decode_header(msg.get("From", "unknown"))
+ to = _decode_header(msg.get("To", ""))
+ cc = _decode_header(msg.get("Cc", ""))
+ date_str = msg.get("Date", "")
+ message_id = msg.get("Message-ID", "")
+ in_reply_to = msg.get("In-Reply-To", "")
+ references = msg.get("References", "")
+ body = _extract_text(msg)
+ body_html = _extract_html(msg)
+
+ sender_name, sender_addr = email.utils.parseaddr(sender)
+ parsed_date = email.utils.parsedate_to_datetime(date_str) if date_str else None
+ attachments = _list_attachments_from_msg(msg) if full else (_email_attachment_meta_cache_get(owner, account_id, folder, uid) or [])
+
+ if mark_seen and not mark_seen_failed:
+ seen_status, _ = conn.uid("STORE", _uid_bytes(uid), "+FLAGS", "(\\Seen)")
+ if seen_status != "OK":
+ # Report, don't raise. The parsed body below is still a
+ # valid response; only the flag claim is untrue.
+ logger.warning(
+ f"IMAP STORE \\Seen failed for UID {uid} in {folder!r}: {seen_status}"
+ )
+ mark_seen_failed = True
+
+ # Only record the local flag transition when the provider actually
+ # accepted it, so the index and list cache cannot drift ahead of
+ # the mailbox.
+ if mark_seen and not mark_seen_failed:
+ _email_index_update_flags(owner, account_id, folder, uid, "\\Seen", True)
+ _update_list_cache_seen(account_id, folder, uid, True)
+
+ related_attachments = []
+ if full and not _has_visible_attachments(msg):
+ related_attachments = _related_thread_attachments_sync(
+ folder,
+ account_id,
+ owner,
+ uid,
+ message_id,
+ in_reply_to,
+ references,
+ )
+ if attachments:
+ _email_attachment_meta_cache_put(owner, account_id, folder, uid, message_id, attachments)
+
+ _t_total = _t.monotonic() - _t0
+ if _t_total > 2.0:
+ logger.warning(
+ f"Slow email read uid={uid} folder={folder} "
+ f"select={_t_select*1000:.0f}ms fetch={_t_fetch*1000:.0f}ms "
+ f"size={len(raw)} full={full} total={_t_total*1000:.0f}ms"
+ )
+
+ # Look up cached summary, AI reply, and LLM-detected boundaries
+ # by Message-ID
+ cached_summary = None
+ cached_ai_reply = None
+ cached_boundaries = None
+ try:
+ import sqlite3 as _sql3
+ _c = _sql3.connect(SCHEDULED_DB)
+ owner_clause, owner_params = _email_cache_owner_clause(owner)
+ _row = _c.execute(
+ f"SELECT summary FROM email_summaries WHERE message_id = ? AND {owner_clause}",
+ (message_id.strip(), *owner_params),
+ ).fetchone()
+ if _row:
+ cached_summary = _row[0]
+ _row2 = _c.execute(
+ f"SELECT reply FROM email_ai_replies WHERE message_id = ? AND {owner_clause}",
+ (message_id.strip(), *owner_params),
+ ).fetchone()
+ if _row2:
+ cached_ai_reply = _apply_email_style_mechanics(_extract_reply(_row2[0] or ""))
+ _row3 = _c.execute(
+ "SELECT sig_start, quote_start, turns_json FROM email_boundaries WHERE message_id = ?",
+ (message_id.strip(),),
+ ).fetchone()
+ cached_turns = None
+ cached_sender_sig = None
+ # Look up a per-sender cached signature (built by the
+ # `learn_sender_signatures` action). Used by the renderer
+ # to fold sigs consistently from the same address.
+ try:
+ if sender_addr:
+ _rs = _c.execute(
+ f"SELECT signature_text FROM sender_signatures "
+ f"WHERE from_address = ? AND {owner_clause}",
+ (sender_addr.lower().strip(), *owner_params),
+ ).fetchone()
+ if _rs and _rs[0]:
+ cached_sender_sig = _rs[0]
+ except Exception:
+ pass
+ if _row3:
+ cached_boundaries = {"sig_start": _row3[0], "quote_start": _row3[1]}
+ if _row3[2]:
+ try:
+ from src.email_thread_parser import THREAD_PARSER_VERSION
+ _parsed = json.loads(_row3[2])
+ # Versioned envelope: {"v": N, "turns": [...]}.
+ # Anything else (bare list from older code, wrong
+ # version) is treated as a cache miss so the
+ # on-the-fly parser re-runs and the next write
+ # warms the cache with the current shape.
+ if (
+ isinstance(_parsed, dict)
+ and _parsed.get("v") == THREAD_PARSER_VERSION
+ and isinstance(_parsed.get("turns"), list)
+ ):
+ cached_turns = _parsed["turns"]
+ except Exception:
+ cached_turns = None
+ _c.close()
+ except Exception:
+ pass
+
+ # If no cached turns, parse on-the-fly so the client never has
+ # to do the heavy lifting. Cheap on a 50KB body, free for short
+ # ones. The background task warms the cache for next reads.
+ if cached_turns is None:
+ try:
+ from src.email_thread_parser import parse_thread
+ cached_turns = parse_thread(body_html, body)
+ except Exception as _pe:
+ logger.debug(f"thread parse on read failed: {_pe}")
+ cached_turns = None
+
+ return {
+ "uid": uid,
+ "folder": folder,
+ "message_id": message_id.strip(),
+ "subject": subject,
+ "from_name": sender_name or sender_addr,
+ "from_address": sender_addr,
+ "to": to,
+ "cc": cc,
+ "date": parsed_date.isoformat() if parsed_date else "",
+ "in_reply_to": in_reply_to.strip(),
+ "references": references.strip(),
+ "body": body,
+ "body_html": body_html,
+ "attachments": attachments,
+ "attachments_deferred": not full and not attachments,
+ "related_attachments": related_attachments,
+ "attachment_version": EMAIL_READ_ATTACHMENT_VERSION,
+ "cached_summary": cached_summary,
+ "cached_ai_reply": cached_ai_reply,
+ "boundaries": cached_boundaries,
+ "thread_turns": cached_turns,
+ "sender_signature": cached_sender_sig,
+ # Per-request, not part of the message: the route strips this
+ # before caching so a one-off flag failure is never replayed to
+ # later readers.
+ "mark_seen_failed": mark_seen_failed,
+ }
+ except Exception as e:
+ logger.error(f"Failed to read email {uid}: {e}")
+ return {"error": "Mail operation failed"}
+
+ def _mark_email_seen_sync(uid, folder, account_id, owner):
+ """Synchronously mark a cached email seen and report success."""
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder), readonly=False)
+ status, _ = conn.uid("STORE", _uid_bytes(uid), "+FLAGS", "(\\Seen)")
+ if status != "OK":
+ return False
+ _email_index_update_flags(owner, account_id, folder, uid, "\\Seen", True)
+ _update_list_cache_seen(account_id, folder, uid, True)
+ return True
+ except Exception as e:
+ logger.warning(f"mark-seen after cached read failed uid={uid}: {e}")
+ return False
+
+ @router.get("/read/{uid}")
+ async def read_email_by_uid(
+ uid: str,
+ folder: str = Query("INBOX"),
+ account_id: str | None = Query(None),
+ mark_seen: bool = Query(True),
+ full: bool = Query(False),
+ owner: str = Depends(require_owner),
+ ):
+ """Read email body. Cached for 30m, sync IMAP work runs in a thread."""
+ mark_seen = True if mark_seen is True or str(mark_seen).lower() == "true" else False
+ full = True if full is True or str(full).lower() == "true" else False
+ fixture_result = _fixture_email_read(uid, folder, owner)
+ if fixture_result is not None:
++ # require_owner validated the selected account. Fixture row labels
++ # are not configured account IDs; keep the selection for AI Reply
++ # and other subsequent account-scoped operations.
++ if account_id and not fixture_result.get("error"):
++ fixture_result = {**fixture_result, "account_id": account_id}
+ return fixture_result
+ ck = _read_cache_key(account_id, folder, uid, owner=owner) + (int(bool(full)),)
+ cached = _read_cache_get(ck)
+ if cached is not None:
+ # Older cached read responses lack the thread-attachment fallback.
+ # Fetch once so replies that reference prior attachments can show
+ # those files without waiting for cache expiry.
+ if cached.get("attachment_version") != EMAIL_READ_ATTACHMENT_VERSION:
+ cached = None
+ if cached is not None:
+ # A cache hit already holds a complete, valid message. Await the
+ # STORE so the response reports the real flag state, but never let
+ # a failed STORE withhold a body we are holding in memory.
+ if mark_seen and not await _asyncio.to_thread(
+ _mark_email_seen_sync, uid, folder, account_id, owner
+ ):
+ return {**cached, "mark_seen_failed": True}
+ return cached
+ if not full:
+ persisted = _email_preview_cache_get(owner, account_id, folder, uid)
+ if persisted and persisted.get("attachment_version") == EMAIL_READ_ATTACHMENT_VERSION:
+ _read_cache_put(ck, persisted)
+ if mark_seen and not await _asyncio.to_thread(
+ _mark_email_seen_sync, uid, folder, account_id, owner
+ ):
+ return {**persisted, "mark_seen_failed": True}
+ return persisted
+ result = await _asyncio.to_thread(_read_email_sync, uid, folder, account_id, owner, mark_seen, full)
+ if result and not result.get("error"):
+ # `mark_seen_failed` describes this request, not the message, so it
+ # must not enter either cache — a later reader would otherwise be
+ # told a STORE failed that it never issued.
+ cacheable = {k: v for k, v in result.items() if k != "mark_seen_failed"}
+ _read_cache_put(ck, cacheable)
+ if not full:
+ _email_preview_cache_put(owner, account_id, folder, uid, cacheable)
+ return result
+
+ def _schedule_recent_email_warm(emails: list, folder: str, account_id: str | None, owner: str):
+ if not emails or folder == "__scheduled__":
+ return
+ now = _time.time()
+ selected = []
+ for em in emails:
+ uid = str((em or {}).get("uid") or "").strip()
+ if not uid:
+ continue
+ try:
+ epoch = float((em or {}).get("date_epoch") or 0)
+ except Exception:
+ epoch = 0
+ if epoch and now - epoch > _WARM_RECENT_SECONDS:
+ continue
+ try:
+ size = int((em or {}).get("size") or 0)
+ except Exception:
+ size = 0
+ if size > _WARM_MAX_BYTES:
+ continue
+ ck = _read_cache_key(account_id, folder, uid, owner=owner) + (0,)
+ if _read_cache_get(ck) is not None or ck in _WARMING_READS:
+ continue
+ _WARMING_READS.add(ck)
+ selected.append((uid, ck))
+ if len(selected) >= _WARM_READ_LIMIT:
+ break
+ if not selected:
+ return
+
+ async def _warm():
+ await _asyncio.sleep(0.25)
+ for uid, ck in selected:
+ if _read_cache_get(ck) is not None:
+ _WARMING_READS.discard(ck)
+ continue
+ try:
+ result = await _asyncio.to_thread(_read_email_sync, uid, folder, account_id, owner, False, False)
+ if result and not result.get("error"):
+ _read_cache_put(ck, result)
+ except Exception as e:
+ logger.debug(f"email read warm skipped uid={uid}: {e}")
+ finally:
+ _WARMING_READS.discard(ck)
+ await _asyncio.sleep(0.35)
+
+ try:
+ _asyncio.create_task(_warm())
+ except RuntimeError:
+ pass
+
+ @router.get("/attachments/{uid}")
+ async def list_attachments(uid: str, folder: str = Query("INBOX"), account_id: str | None = Query(None), owner: str = Depends(require_owner)):
+ """List attachments for an email."""
+ fixture = _fixture_email_read(uid, folder, owner)
+ if fixture is not None and not fixture.get("error"):
+ return {"attachments": fixture.get("attachments") or [], "uid": uid, "sync": {"source": "local"}}
+ cached = _email_attachment_meta_cache_get(owner, account_id, folder, uid)
+ if cached is not None:
+ # Older cache rows predate exact attachment-name/visibility
+ # indexing. Re-saving the metadata repairs stale card icons and
+ # warms filename search without another IMAP download.
+ _email_attachment_meta_cache_put(owner, account_id, folder, uid, "", cached)
+ return {"attachments": cached, "uid": uid, "sync": {"source": "attachment_metadata_cache"}}
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder), readonly=True)
+ status, msg_data = _imap_uid_fetch(conn, uid, "(RFC822)")
+ if status != "OK":
+ return {"attachments": [], "error": "Email not found"}
+ raw = msg_data[0][1]
+ msg = email_mod.message_from_bytes(raw)
+ attachments = _list_attachments_from_msg(msg)
+ _email_attachment_meta_cache_put(owner, account_id, folder, uid, msg.get("Message-ID", ""), attachments)
+ return {"attachments": attachments, "uid": uid}
+ except Exception as e:
+ logger.error(f"Failed to list attachments for {uid}: {e}")
+ return {"attachments": [], "error": "Mail operation failed"}
+
+ @router.get("/attachment/{uid}/{index}")
+ async def download_attachment(uid: str, index: int, folder: str = Query("INBOX"), account_id: str | None = Query(None), owner: str = Depends(require_owner)):
+ """Download a specific attachment by email UID and attachment index. Saves to local disk and returns the file."""
+ fixture_att = _fixture_attachment_source(uid, index, owner, folder)
+ if fixture_att is not None:
+ _row, att = fixture_att
+ filename = str(att.get("filename") or f"attachment-{index}.txt")
+ safe_name = re.sub(r"[^\w\s\-.]", "_", filename).strip() or f"attachment-{index}.txt"
+ target_dir = attachment_extract_dir(folder, uid)
+ target_dir.mkdir(parents=True, exist_ok=True)
+ filepath = target_dir / safe_name
+ filepath.write_bytes(str(att.get("content") or "").encode("utf-8"))
+ return FileResponse(
+ path=str(filepath),
+ filename=filepath.name,
+ media_type=str(att.get("content_type") or "application/octet-stream"),
+ )
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder), readonly=True)
+ status, msg_data = _imap_uid_fetch(conn, uid, "(RFC822)")
+ if status != "OK":
+ return {"error": "Email not found"}
+ raw = msg_data[0][1]
+ msg = email_mod.message_from_bytes(raw)
+
+ # Extract to a per-email folder
+ target_dir = attachment_extract_dir(folder, uid)
+ filepath = _extract_attachment_to_disk(msg, index, target_dir)
+ if not filepath:
+ return {"error": f"Attachment index {index} not found"}
+
+ return FileResponse(
+ path=str(filepath),
+ filename=filepath.name,
+ media_type="application/octet-stream",
+ )
+ except Exception as e:
+ logger.error(f"Failed to download attachment {uid}/{index}: {e}")
+ return {"error": "Mail operation failed"}
+
+ @router.get("/attachments-download/{uid}")
+ async def download_all_attachments(uid: str, folder: str = Query("INBOX"), account_id: str | None = Query(None), owner: str = Depends(require_owner)):
+ """Download all visible attachments for an email as a zip archive."""
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder), readonly=True)
+ status, msg_data = _imap_uid_fetch(conn, uid, "(RFC822)")
+ if status != "OK":
+ raise HTTPException(status_code=404, detail="Email not found")
+ raw = msg_data[0][1]
+ msg = email_mod.message_from_bytes(raw)
+ attachments = [
+ att for att in _list_attachments_from_msg(msg)
+ if not _is_likely_signature_image_attachment(att)
+ ]
+ if not attachments:
+ raise HTTPException(status_code=404, detail="No downloadable attachments")
+
+ target_dir = attachment_extract_dir(folder, uid)
+ zip_buf = io.BytesIO()
+ used_names: dict[str, int] = {}
+ with zipfile.ZipFile(zip_buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
+ for att in attachments:
+ idx = att.get("index")
+ if idx is None:
+ continue
+ filepath = _extract_attachment_to_disk(msg, int(idx), target_dir)
+ if not filepath or not Path(filepath).exists():
+ continue
+ fallback = f"attachment-{idx}"
+ arcname = _safe_attachment_zip_name(att.get("filename") or Path(filepath).name, fallback)
+ stem = Path(arcname).stem
+ suffix = Path(arcname).suffix
+ seen = used_names.get(arcname, 0)
+ used_names[arcname] = seen + 1
+ if seen:
+ arcname = f"{stem}-{seen + 1}{suffix}"
+ zf.write(str(filepath), arcname)
+ zip_buf.seek(0)
+ if not zip_buf.getbuffer().nbytes:
+ raise HTTPException(status_code=404, detail="No downloadable attachments")
+ zip_name = _safe_attachment_zip_name(f"email-{uid}-attachments.zip", "attachments.zip")
+ return StreamingResponse(
+ zip_buf,
+ media_type="application/zip",
+ headers={"Content-Disposition": f'attachment; filename="{zip_name}"'},
+ )
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.error(f"Failed to download attachments zip {uid}: {e}")
+ raise HTTPException(status_code=500, detail="Mail operation failed")
+
+ @router.post("/attachments-download-bulk")
+ async def download_bulk_attachments(request: Request, owner: str = Depends(require_owner)):
+ """Download visible attachments from selected emails as one zip archive."""
+ try:
+ payload = await request.json()
+ except Exception:
+ raise HTTPException(status_code=400, detail="Invalid JSON body")
+ messages = payload.get("messages") if isinstance(payload, dict) else None
+ if not isinstance(messages, list) or not messages:
+ raise HTTPException(status_code=400, detail="No emails selected")
+ if len(messages) > 250:
+ raise HTTPException(status_code=400, detail="Too many emails selected")
+
+ category = str(payload.get("category") or "").strip().lower()
+ category = re.sub(r"[^a-z0-9_-]+", "-", category).strip("-")
+ if category == "receipt":
+ category = "receipts"
+ category = category or "selected"
+ selected_dates = sorted({
+ str(row.get("date") or "").strip()
+ for row in messages if isinstance(row, dict)
+ and re.fullmatch(r"\d{4}-\d{2}-\d{2}", str(row.get("date") or "").strip())
+ })
+ date_span = ""
+ if selected_dates:
+ date_span = selected_dates[0] if len(selected_dates) == 1 else f"{selected_dates[0]} - {selected_dates[-1]}"
+ export_folder = f"email-attachments-{category}" + (f" ({date_span})" if date_span else "")
+
+ zip_buf = io.BytesIO()
+ used_names: dict[str, int] = {}
+ added = 0
+ skipped = 0
+
+ def _add_bytes(zf: zipfile.ZipFile, folder_name: str, filename: str, data: bytes) -> None:
+ nonlocal added
+ clean_folder = _safe_attachment_zip_name(folder_name, "email")
+ clean_file = _safe_attachment_zip_name(filename, "attachment")
+ arcname = f"{export_folder}/{clean_folder}/{clean_file}"
+ stem = Path(clean_file).stem
+ suffix = Path(clean_file).suffix
+ seen = used_names.get(arcname, 0)
+ used_names[arcname] = seen + 1
+ if seen:
+ arcname = f"{export_folder}/{clean_folder}/{stem}-{seen + 1}{suffix}"
+ zf.writestr(arcname, data)
+ added += 1
+
+ remote_groups: dict[tuple[str | None, str], list[tuple[str, str]]] = {}
+ with zipfile.ZipFile(zip_buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
+ for raw in messages:
+ if not isinstance(raw, dict):
+ continue
+ uid = str(raw.get("uid") or "").strip()
+ if not uid:
+ continue
+ folder = str(raw.get("folder") or "INBOX").strip() or "INBOX"
+ acct = str(raw.get("account_id") or raw.get("account") or "").strip() or None
+ subject = str(raw.get("subject") or f"email-{uid}").strip() or f"email-{uid}"
+ email_folder_name = f"{uid}-{subject}"[:120]
+
+ fixture = _fixture_email_read(uid, folder, owner)
+ if fixture is not None and not fixture.get("error"):
+ for att_meta in fixture.get("attachments") or []:
+ idx = att_meta.get("index")
+ if idx is None:
+ continue
+ fixture_att = _fixture_attachment_source(uid, int(idx), owner, folder)
+ if fixture_att is None:
+ continue
+ _row, att = fixture_att
+ filename = str(att.get("filename") or att_meta.get("filename") or f"attachment-{idx}.txt")
+ content = str(att.get("content") or "").encode("utf-8")
+ _add_bytes(zf, email_folder_name, filename, content)
+ continue
+
+ remote_groups.setdefault((acct, folder), []).append((uid, email_folder_name))
+
+ # Reuse one authenticated IMAP connection per mailbox/folder and
+ # fetch message bodies in bounded batches. Opening a fresh Gmail
+ # connection for every selected email made larger exports exceed
+ # the reverse proxy timeout before any ZIP bytes were returned.
+ for (acct, folder), rows in remote_groups.items():
+ try:
+ with _imap(acct, owner=owner) as conn:
+ conn.select(_q(folder), readonly=True)
+ for batch_start in range(0, len(rows), 20):
+ batch = rows[batch_start:batch_start + 20]
+ names_by_uid = {uid: folder_name for uid, folder_name in batch}
+ uid_set = ",".join(uid for uid, _ in batch).encode()
+ status, msg_data = _imap_uid_fetch(conn, uid_set, "(UID RFC822)")
+ if status != "OK" or not msg_data:
+ skipped += len(batch)
+ continue
+ seen_uids = set()
+ for meta_b, raw_msg in _group_uid_fetch_records(msg_data):
+ uid_num = _uid_from_fetch_meta(meta_b)
+ if not uid_num or not raw_msg:
+ continue
+ uid = str(uid_num)
+ seen_uids.add(uid)
+ msg = email_mod.message_from_bytes(raw_msg)
+ attachments = [
+ att for att in _list_attachments_from_msg(msg)
+ if not _is_likely_signature_image_attachment(att)
+ ]
+ target_dir = attachment_extract_dir(folder, uid)
+ for att in attachments:
+ idx = att.get("index")
+ if idx is None:
+ continue
+ filepath = _extract_attachment_to_disk(msg, int(idx), target_dir)
+ if not filepath or not Path(filepath).exists():
+ continue
+ _add_bytes(
+ zf,
+ names_by_uid.get(uid, f"email-{uid}"),
+ att.get("filename") or Path(filepath).name,
+ Path(filepath).read_bytes(),
+ )
+ skipped += len(batch) - len(seen_uids)
+ except Exception as exc:
+ skipped += len(rows)
+ logger.warning("Bulk attachment export skipped mailbox folder=%s account=%s count=%s: %s", folder, acct, len(rows), exc)
+
+ zip_buf.seek(0)
+ if added <= 0 or not zip_buf.getbuffer().nbytes:
+ raise HTTPException(status_code=404, detail="No downloadable attachments in selected emails")
+ logger.info("Bulk attachment export complete owner=%s messages=%s attachments=%s skipped=%s", owner, len(messages), added, skipped)
+ zip_name = _safe_attachment_zip_name(f"{export_folder}.zip", "email-attachments.zip")
+ return StreamingResponse(
+ zip_buf,
+ media_type="application/zip",
+ headers={"Content-Disposition": f'attachment; filename="{zip_name}"'},
+ )
+
+ @router.get("/inline-image/{uid}")
+ async def inline_image(
+ uid: str,
+ cid: str = Query(...),
+ folder: str = Query("INBOX"),
+ account_id: str | None = Query(None),
+ owner: str = Depends(require_owner),
+ ):
+ """Serve an inline MIME image by Content-ID for the email reader."""
+ want = (cid or "").strip().strip("<>")
+ if not want:
+ raise HTTPException(status_code=400, detail="Missing image Content-ID")
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder), readonly=True)
+ status, msg_data = _imap_uid_fetch(conn, uid, "(RFC822)")
+ if status != "OK":
+ raise HTTPException(status_code=404, detail="Email not found")
+ raw = msg_data[0][1]
+ msg = email_mod.message_from_bytes(raw)
+ idx = 0
+ for part in msg.walk():
+ cd = str(part.get("Content-Disposition", ""))
+ ct = part.get_content_type()
+ is_attached_email = ct == "message/rfc822" and ("attachment" in cd.lower() or part.get_filename())
+ if part.is_multipart() and not is_attached_email:
+ continue
+ if ct in ("text/plain", "text/html") and "attachment" not in cd:
+ continue
+ content_id = (part.get("Content-ID") or "").strip().strip("<>")
+ if content_id != want:
+ idx += 1
+ continue
+ if not ct.lower().startswith("image/"):
+ raise HTTPException(status_code=415, detail="Content-ID is not an image")
+ target_dir = attachment_extract_dir(folder, uid)
+ filepath = _extract_attachment_to_disk(msg, idx, target_dir)
+ if not filepath:
+ raise HTTPException(status_code=404, detail="Inline image not found")
+ return FileResponse(
+ path=str(filepath),
+ media_type=ct,
+ headers={"Content-Disposition": f'inline; filename="{filepath.name}"'},
+ )
+ raise HTTPException(status_code=404, detail="Inline image not found")
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.error(f"Failed to load inline image {uid}/{want}: {e}")
+ return {"error": "Mail operation failed"}
+
+ @router.post("/attachment-as-doc/{uid}/{index}")
+ def attachment_as_doc(uid: str, index: int, request: Request, folder: str = Query("INBOX"), account_id: str | None = Query(None), owner: str = Depends(require_owner)):
+ """Extract an email attachment and open it in the document editor.
+
+ Supported extensions:
+ - .pdf → rendered as PDF Document (existing flow)
+ - .docx → rendered as signable PDF Document when conversion is available,
+ otherwise text extracted to markdown Document
+ - .txt / .md → loaded directly as a markdown Document
+
+ Returns {doc_id} so the frontend can open it as a tab in the doc panel.
+ Other types are rejected — caller should fall back to download.
+ """
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder), readonly=True)
+ status, msg_data = _imap_uid_fetch(conn, uid, "(RFC822)")
+ if status != "OK":
+ return {"error": "Email not found"}
+ raw = msg_data[0][1]
+ msg = email_mod.message_from_bytes(raw)
+
+ target_dir = attachment_extract_dir(folder, uid)
+ filepath = _extract_attachment_to_disk(msg, index, target_dir)
+ if not filepath:
+ return {"error": f"Attachment index {index} not found"}
+
+ from pathlib import Path as _Path
+ target_root = os.path.abspath(str(target_dir))
+ filepath_str = os.path.abspath(str(filepath))
+ if os.path.commonpath([target_root, filepath_str]) != target_root:
+ logger.warning("Rejected attachment path outside extraction dir: %s", filepath)
+ return {"error": "Invalid attachment path"}
+ filepath = _Path(filepath_str)
+ base = _Path(filepath).name
+ if base.startswith("."):
+ return {"error": "Invalid filename", "filename": base}
+ ext = _Path(base).suffix.lower()
+
+ import os as _os
+ title = _os.path.splitext(filepath.name)[0]
+
+ # Capture the source email's identity so the doc can later be used
+ # to thread a signed-reply back to the original sender.
+ src_message_id = (msg.get("Message-ID") or "").strip()
+ def _tag_doc_with_source(doc_id_to_tag: str):
+ if not doc_id_to_tag:
+ return
+ try:
+ from src.database import SessionLocal as _SL, Document as _Doc
+ _db = _SL()
+ try:
+ d = _db.query(_Doc).filter(_Doc.id == doc_id_to_tag).first()
+ if d:
+ d.source_email_uid = str(uid)
+ d.source_email_folder = folder
+ d.source_email_account_id = account_id or ""
+ d.source_email_message_id = src_message_id
+ _db.commit()
+ finally:
+ _db.close()
+ except Exception as _e:
+ logger.warning(f"tag doc source-email failed: {_e}")
+
+ # Extracted docs MUST belong to a session the caller owns — a
+ # session-less ("orphan") doc is rejected by get_document's owner
+ # check (404), so the frontend's loadDocument() throws and nothing
+ # opens (the "open in document didn't open" bug). Attach it to the
+ # user's most-recent session so it's fetchable + ownable.
+ from src.auth_helpers import get_current_user as _gcu
+ _doc_user = _gcu(request)
+ def _resolve_doc_session():
+ try:
+ from src.database import SessionLocal as _SL, Session as _Sess
+ _db = _SL()
+ try:
+ _q2 = _db.query(_Sess)
+ if _doc_user:
+ _q2 = _q2.filter(_Sess.owner == _doc_user)
+ s = _q2.order_by(_Sess.updated_at.desc()).first()
+ return s.id if s else None
+ finally:
+ _db.close()
+ except Exception as _e:
+ logger.warning(f"resolve doc session failed: {_e}")
+ return None
+ doc_session_id = _resolve_doc_session()
+
+ def _create_markdown_doc(content: str, summary: str):
+ from src.database import SessionLocal as _SL, Document as _Doc, DocumentVersion as _DV
+ doc_id = str(uuid.uuid4())
+ ver_id = str(uuid.uuid4())
+ _db = _SL()
+ try:
+ _db.query(_Doc).filter(_Doc.is_active == True).update({"is_active": False})
+ _db.add(_Doc(
+ id=doc_id, session_id=doc_session_id, title=title,
+ language="markdown", current_content=content,
+ version_count=1, is_active=True,
+ ))
+ _db.add(_DV(
+ id=ver_id, document_id=doc_id, version_number=1,
+ content=content, summary=summary, source="upload",
+ ))
+ _db.commit()
+ finally:
+ _db.close()
+ _tag_doc_with_source(doc_id)
+ return doc_id
+
+ def _attached_email_markdown(raw_bytes: bytes):
+ if not raw_bytes:
+ return f"# Attached email: {base}\n\n_(empty email attachment)_"
+ try:
+ attached_msg = email_mod.message_from_bytes(raw_bytes)
+ except Exception:
+ logger.exception("Failed to parse attached email %s", base)
+ return f"# Attached email: {base}\n\nCould not parse this email attachment."
+
+ attached_subject = _decode_header(attached_msg.get("Subject", "")) or base
+ attached_from = _decode_header(attached_msg.get("From", ""))
+ attached_to = _decode_header(attached_msg.get("To", ""))
+ attached_cc = _decode_header(attached_msg.get("Cc", ""))
+ attached_date = attached_msg.get("Date", "")
+ attached_body = _extract_text(attached_msg).strip()
+ attached_atts = _list_attachments_from_msg(attached_msg)
+
+ lines = [f"# Attached email: {attached_subject}", ""]
+ if attached_from:
+ lines.append(f"**From:** {attached_from}")
+ if attached_to:
+ lines.append(f"**To:** {attached_to}")
+ if attached_cc:
+ lines.append(f"**Cc:** {attached_cc}")
+ if attached_date:
+ lines.append(f"**Date:** {attached_date}")
+ lines.extend(["", "## Body", "", attached_body or "_(no readable body)_"])
+ if attached_atts:
+ lines.extend(["", "## Attachments", ""])
+ for att in attached_atts:
+ size = int(att.get("size") or 0)
+ size_label = f"{size} B" if size < 1024 else f"{round(size / 1024)} KB"
+ name = att.get("filename") or f"attachment_{att.get('index', '')}"
+ ctype = att.get("content_type") or "application/octet-stream"
+ lines.append(f"- {name} ({ctype}, {size_label})")
+ return "\n".join(lines).strip()
+
+ def _store_pdf_upload(src_pdf: _Path, original_name: str):
+ import hashlib as _hashlib
+ import json as _json
+ import shutil as _shutil
+ from src.constants import UPLOAD_DIR
+
+ upload_id = f"{uuid.uuid4().hex}.pdf"
+ today = datetime.utcnow().strftime("%Y/%m/%d")
+ dated_dir = _os.path.join(UPLOAD_DIR, today)
+ _os.makedirs(dated_dir, exist_ok=True)
+ dest_path = _os.path.join(dated_dir, upload_id)
+ _shutil.copyfile(str(src_pdf), dest_path)
+
+ file_size = _os.path.getsize(dest_path)
+ h = _hashlib.sha256()
+ with open(dest_path, "rb") as f:
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
+ h.update(chunk)
+ file_hash = h.hexdigest()
+ created_at = datetime.utcnow().isoformat()
+ safe_original = _Path(original_name or src_pdf.name).name or f"{title}.pdf"
+ metadata = {
+ "id": upload_id,
+ "path": dest_path,
+ "mime": "application/pdf",
+ "size": file_size,
+ "name": safe_original,
+ "hash": file_hash,
+ "checksum_sha256": file_hash,
+ "original_name": safe_original,
+ "uploaded_at": created_at,
+ "created_at": created_at,
+ "last_accessed": created_at,
+ "client_ip": request.client.host if request.client else "email",
+ "owner": _doc_user,
+ }
+ uploads_db_path = _os.path.join(UPLOAD_DIR, "uploads.json")
+ try:
+ if _os.path.exists(uploads_db_path):
+ with open(uploads_db_path, "r", encoding="utf-8") as f:
+ current = _json.load(f) or {}
+ else:
+ current = {}
+ storage_key = f"{_doc_user}:{file_hash}" if _doc_user else file_hash
+ current[storage_key] = metadata
+ tmp_path = uploads_db_path + ".tmp"
+ with open(tmp_path, "w", encoding="utf-8") as f:
+ _json.dump(current, f, indent=2)
+ _os.replace(tmp_path, uploads_db_path)
+ except Exception as e:
+ logger.warning("Failed to index email attachment PDF upload %s: %s", upload_id, e)
+ return upload_id, dest_path
+
+ def _create_pdf_document_from_path(pdf_path: _Path, original_name: str, body_text: str | None = None):
+ from src.constants import UPLOAD_DIR
+ from src.pdf_forms import has_form_fields, extract_fields
+ from src.pdf_form_doc import (
+ save_field_sidecar,
+ create_form_markdown_document,
+ create_plain_pdf_document,
+ )
+
+ upload_id, dest_path = _store_pdf_upload(pdf_path, original_name)
+
+ is_form = False
+ try:
+ is_form = has_form_fields(dest_path)
+ except Exception as e:
+ logger.warning(f"has_form_fields failed for attachment PDF: {e}")
+
+ if is_form:
+ fields = extract_fields(dest_path)
+ save_field_sidecar(dest_path, fields)
+ doc_id = create_form_markdown_document(
+ session_id=doc_session_id,
+ fields=fields,
+ upload_id=upload_id,
+ title=title,
+ intro_text=None,
+ )
+ else:
+ doc_id = create_plain_pdf_document(
+ session_id=doc_session_id,
+ upload_id=upload_id,
+ title=title,
+ body_text=body_text,
+ )
+
+ if not doc_id:
+ return {"error": "Failed to create document"}
+ _tag_doc_with_source(doc_id)
+ return {"doc_id": doc_id, "filename": original_name}
+
+ def _convert_docx_to_pdf(src_docx: _Path) -> _Path | None:
+ import shutil as _shutil
+ import subprocess as _subprocess
+ import tempfile as _tempfile
+
+ soffice = _shutil.which("soffice") or _shutil.which("libreoffice")
+ if not soffice:
+ return None
+ tmp_dir = _tempfile.mkdtemp(prefix="odysseus-docx-pdf-")
+ try:
+ proc = _subprocess.run(
+ [
+ soffice,
+ "--headless",
+ "--convert-to",
+ "pdf",
+ "--outdir",
+ tmp_dir,
+ str(src_docx),
+ ],
+ stdout=_subprocess.PIPE,
+ stderr=_subprocess.PIPE,
+ text=True,
+ timeout=60,
+ check=False,
+ )
+ if proc.returncode != 0:
+ logger.info(
+ "DOCX preview conversion failed for %s: %s%s",
+ src_docx.name,
+ proc.stdout[-500:],
+ proc.stderr[-500:],
+ )
+ return None
+ out_pdf = _Path(tmp_dir) / (src_docx.stem + ".pdf")
+ if out_pdf.exists() and out_pdf.stat().st_size > 0:
+ return out_pdf
+ found = list(_Path(tmp_dir).glob("*.pdf"))
+ return found[0] if found else None
+ except Exception as e:
+ logger.info("DOCX preview conversion unavailable for %s: %s", src_docx.name, e)
+ return None
+
+ # ── PDF path (existing) ────────────────────────────────────
+ if ext == ".pdf":
+ return _create_pdf_document_from_path(filepath, filepath.name)
+
+ # ── Attached email (.eml / message/rfc822) ────────────────
+ if ext == ".eml":
+ def _attachment_bytes_from_msg():
+ if not msg.is_multipart():
+ return b""
+ idx = 0
+ for part in msg.walk():
+ cd = str(part.get("Content-Disposition", ""))
+ ct = part.get_content_type()
+ is_attached_email = ct == "message/rfc822" and ("attachment" in cd.lower() or part.get_filename())
+ if part.is_multipart() and not is_attached_email:
+ continue
+ if ct in ("text/plain", "text/html") and "attachment" not in cd:
+ continue
+ if idx == index:
+ payload = part.get_payload(decode=True)
+ if payload is None and ct == "message/rfc822":
+ try:
+ payload = part.as_bytes()
+ except Exception:
+ payload = b""
+ return payload or b""
+ idx += 1
+ return b""
+
+ try:
+ content = _attached_email_markdown(_attachment_bytes_from_msg())
+ except Exception:
+ logger.exception("Failed to read email attachment %s", base)
+ return {"error": "Failed to read email attachment", "filename": base}
+ doc_id = _create_markdown_doc(content, "Imported attached email")
+ return {"doc_id": doc_id, "filename": filepath.name}
+
+ # ── DOCX path: prefer signable PDF preview, fallback to markdown ─
+ if ext == ".docx":
+ try:
+ from src.markitdown_runtime import convert_to_markdown
+
+ content = (convert_to_markdown(str(filepath)) or "").strip()
+ except Exception as e:
+ logger.warning("Failed to extract docx attachment %s: %s", base, e)
+ content = ""
+ if not content:
+ return {
+ "error": "Could not extract DOCX text. Install Office document dependencies in Cookbook Dependencies.",
+ "filename": base,
+ }
+
+ preview_pdf = _convert_docx_to_pdf(filepath)
+ if preview_pdf:
+ return _create_pdf_document_from_path(preview_pdf, f"{title}.pdf", content)
+
+ doc_id = _create_markdown_doc(content, "Imported from DOCX")
+ return {"doc_id": doc_id, "filename": filepath.name}
+
+ # ── Plain text / markdown ────────────────────────────────
+ if ext in (".txt", ".md", ".markdown"):
+ try:
+ content = filepath.read_text(encoding="utf-8", errors="replace")
+ except Exception as e:
+ return {"error": f"Failed to read text file: {e}", "filename": base}
+ doc_id = _create_markdown_doc(content, "Imported from email attachment")
+ return {"doc_id": doc_id, "filename": filepath.name}
+
+ return {"error": f"Unsupported attachment type: {ext}", "filename": base}
+ except Exception as e:
+ logger.error(f"attachment-as-doc {uid}/{index} failed: {e}")
+ return {"error": "Mail operation failed"}
+
+ @router.post("/attachment-path/{uid}/{index}")
+ async def get_attachment_path(uid: str, index: int, folder: str = Query("INBOX"), account_id: str | None = Query(None), owner: str = Depends(require_owner)):
+ """Extract attachment to local disk and return the path (for AI to read via read_file)."""
+ fixture_att = _fixture_attachment_source(uid, index, owner, folder)
+ if fixture_att is not None:
+ _row, att = fixture_att
+ filename = str(att.get("filename") or f"attachment-{index}.txt")
+ safe_name = re.sub(r"[^\w\s\-.]", "_", filename).strip() or f"attachment-{index}.txt"
+ target_dir = attachment_extract_dir(folder, uid)
+ target_dir.mkdir(parents=True, exist_ok=True)
+ filepath = target_dir / safe_name
+ filepath.write_bytes(str(att.get("content") or "").encode("utf-8"))
+ return {"path": str(filepath), "filename": filepath.name, "size": filepath.stat().st_size}
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder), readonly=True)
+ status, msg_data = _imap_uid_fetch(conn, uid, "(RFC822)")
+ if status != "OK":
+ return {"error": "Email not found"}
+ raw = msg_data[0][1]
+ msg = email_mod.message_from_bytes(raw)
+
+ target_dir = attachment_extract_dir(folder, uid)
+ filepath = _extract_attachment_to_disk(msg, index, target_dir)
+ if not filepath:
+ return {"error": f"Attachment index {index} not found"}
+
+ return {"path": str(filepath), "filename": filepath.name, "size": filepath.stat().st_size}
+ except Exception as e:
+ logger.error(f"Failed to get attachment path {uid}/{index}: {e}")
+ return {"error": "Mail operation failed"}
+
+ @router.post("/mark-unread/{uid}")
+ async def mark_unread(uid: str, folder: str = Query("INBOX"), account_id: str | None = Query(None), owner: str = Depends(require_owner)):
+ """Mark an email as unread (clear \\Seen flag)."""
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder))
+ if not _store_email_flag(conn, uid, "\\Seen", add=False):
+ return {"success": False, "error": "Email not found"}
+ _email_index_update_flags(owner, account_id, folder, uid, "\\Seen", False)
+ _invalidate_list_cache(account_id, folder)
+ return {"success": True}
+ except Exception as e:
+ logger.error(f"Failed to mark unread {uid}: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.post("/flag/{uid}")
+ async def flag_email(uid: str, folder: str = Query("INBOX"), account_id: str | None = Query(None),
+ on: bool = Query(True), owner: str = Depends(require_owner)):
+ """Toggle the \\Flagged flag (a.k.a. favorite / star) on an email.
+ Pass `on=true` to favorite, `on=false` to unfavorite."""
+ fixture_ok = _fixture_email_update(uid, owner, source_folder=folder, favorite=bool(on))
+ if fixture_ok is not None:
+ return {"success": bool(fixture_ok), "flagged": bool(on), **({} if fixture_ok else {"error": "Email not found"})}
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder))
+ if not _store_email_flag(conn, uid, "\\Flagged", add=bool(on)):
+ return {"success": False, "error": "Email not found"}
+ _email_index_update_flags(owner, account_id, folder, uid, "\\Flagged", bool(on))
+ _invalidate_list_cache(account_id, folder)
+ return {"success": True, "flagged": bool(on)}
+ except Exception as e:
+ logger.error(f"Failed to flag {uid}: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.post("/mark-read/{uid}")
+ async def mark_read(uid: str, folder: str = Query("INBOX"), account_id: str | None = Query(None), owner: str = Depends(require_owner)):
+ """Mark an email as read (set \\Seen flag)."""
+ fixture_ok = _fixture_email_update(uid, owner, source_folder=folder, read=True)
+ if fixture_ok is not None:
+ return {"success": bool(fixture_ok), **({} if fixture_ok else {"error": "Email not found"})}
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder))
+ if not _store_email_flag(conn, uid, "\\Seen", add=True):
+ return {"success": False, "error": "Email not found"}
+ _email_index_update_flags(owner, account_id, folder, uid, "\\Seen", True)
+ _invalidate_list_cache(account_id, folder)
+ return {"success": True}
+ except Exception as e:
+ logger.error(f"Failed to mark read {uid}: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.post("/archive/{uid}")
+ # Sync def: blocking IMAP I/O with no awaits — see search_emails above. Runs in a
+ # threadpool instead of blocking the event loop.
+ def archive_email(uid: str, folder: str = Query("INBOX"), account_id: str | None = Query(None), owner: str = Depends(require_owner)):
+ """Move email to Archive folder."""
+ fixture_ok = _fixture_email_update(uid, owner, source_folder=folder, folder="Archive")
+ if fixture_ok is not None:
+ return {"success": bool(fixture_ok), **({} if fixture_ok else {"error": "Email not found"})}
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder))
+ if not _move_email_message(conn, uid, "Archive", role="archive"):
+ return {"success": False, "error": "Email not found"}
+ _email_index_delete(owner, account_id, folder, uid)
+ _invalidate_list_cache(account_id)
+ return {"success": True}
+ except Exception as e:
+ logger.error(f"Failed to archive email {uid}: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.delete("/delete/{uid}")
+ async def delete_email(uid: str, folder: str = Query("INBOX"), account_id: str | None = Query(None), message_id: str | None = Query(None), owner: str = Depends(require_owner)):
+ """Move email to Trash."""
+ logger.info(
+ "Email delete requested uid=%s folder=%s account=%s message_id=%s fixture=%s",
+ uid, folder, account_id or "default", bool(message_id), bool(_fixture_email_enabled()),
+ )
+ fixture_ok = _fixture_email_update(uid, owner, source_folder=folder, folder="Trash")
+ if fixture_ok is not None:
+ logger.info("Email delete fixture result uid=%s success=%s", uid, fixture_ok)
+ return {"success": bool(fixture_ok), **({} if fixture_ok else {"error": "Email not found"})}
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ select_status, _ = conn.select(_q(folder), readonly=False)
+ if select_status != "OK":
+ return {"success": False, "error": "Could not open email folder"}
+ resolved_uid = _resolve_current_email_uid(conn, uid, message_id)
+ if not resolved_uid:
+ logger.info("Email delete already absent uid=%s folder=%s message_id=%s", uid, folder, bool(message_id))
+ # Delete is intentionally idempotent. A stale library row
+ # can point at a UID that was already moved by a previous
+ # click or by another mailbox client; it is already gone
+ # from the requested folder, so do not trap the UI on a
+ # permanent “Email not found” error.
+ _email_index_delete(owner, account_id, folder, str(uid))
+ _invalidate_list_cache(account_id, folder)
+ return {"success": True, "already_deleted": True}
+ trash_folder = _resolve_mail_folder(conn, "Trash", "trash")
+ # A few providers expose no special-use Trash mailbox. Create
+ # the conventional folder before attempting the move so the
+ # kebab action still means “move to Trash”, never “delete
+ # permanently as a fallback”.
+ _, folder_names = _list_imap_folders(conn)
+ if trash_folder not in folder_names:
+ try:
+ if conn.create(_q("Trash"))[0] == "OK":
+ trash_folder = "Trash"
+ except Exception:
+ pass
+ if not _move_email_message(conn, resolved_uid, trash_folder, role="trash"):
+ logger.warning("Email delete Trash move failed uid=%s resolved_uid=%s folder=%s trash=%s", uid, resolved_uid, folder, trash_folder)
+ return {"success": False, "error": "Could not move email to Trash"}
+ _email_index_delete(owner, account_id, folder, resolved_uid)
+ if resolved_uid != str(uid):
+ _email_index_delete(owner, account_id, folder, str(uid))
+ _invalidate_list_cache(account_id)
+ return {"success": True}
+ except Exception as e:
+ logger.error(f"Failed to delete email {uid}: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.delete("/delete-permanent/{uid}")
+ async def delete_email_permanent(uid: str, folder: str = Query("INBOX"), account_id: str | None = Query(None), owner: str = Depends(require_owner)):
+ """Permanently delete an email (no Trash)."""
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder))
+ if not _store_email_flag(conn, uid, "\\Deleted", add=True):
+ return {"success": False, "error": "Email not found"}
+ conn.expunge()
+ _email_index_delete(owner, account_id, folder, uid)
+ _invalidate_list_cache(account_id, folder)
+ return {"success": True}
+ except Exception as e:
+ logger.error(f"Failed to permanently delete email {uid}: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.post("/delete-bulk")
+ def delete_email_bulk(data: dict, owner: str = Depends(require_owner)):
+ """Move a selected batch to Trash using one IMAP connection."""
+ payload = data or {}
+ folder = str(payload.get("folder") or "INBOX").strip() or "INBOX"
+ account_id = payload.get("account_id") or None
+ if account_id:
+ _assert_owns_account(account_id, owner)
+ uids = []
+ seen = set()
+ for raw_uid in payload.get("uids") or []:
+ uid = str(raw_uid or "").strip()
+ if uid and uid not in seen and uid.isdigit():
+ seen.add(uid)
+ uids.append(uid)
+ if not uids:
+ return {"success": False, "error": "No email UIDs provided", "deleted_uids": [], "failed_uids": []}
+ deleted_uids = []
+ failed_uids = []
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ select_status, _ = conn.select(_q(folder), readonly=False)
+ if select_status != "OK":
+ return {"success": False, "error": "Could not open email folder", "deleted_uids": [], "failed_uids": uids}
+ trash_folder = _resolve_mail_folder(conn, "Trash", "trash")
+ # Some accounts have no special-use Trash mailbox. Create a
+ # normal Trash folder when the provider permits it.
+ _, folder_names = _list_imap_folders(conn)
+ if trash_folder not in folder_names:
+ try:
+ if conn.create(_q("Trash"))[0] == "OK":
+ trash_folder = "Trash"
+ except Exception:
+ pass
+ pending_expunge = False
+ for uid in uids:
+ try:
+ if not _uid_exists(conn, uid):
+ failed_uids.append(uid)
+ continue
+ status, _ = conn.uid("MOVE", _uid_bytes(uid), _q(trash_folder))
+ if status != "OK":
+ copy_status, _ = conn.uid("COPY", _uid_bytes(uid), _q(trash_folder))
+ if copy_status != "OK":
+ # Keep deletion reliable even when this IMAP
+ # server has no writable Trash folder.
+ store_status, _ = conn.uid("STORE", _uid_bytes(uid), "+FLAGS", "\\Deleted")
+ if store_status != "OK":
+ failed_uids.append(uid)
+ continue
+ pending_expunge = True
+ else:
+ store_status, _ = conn.uid("STORE", _uid_bytes(uid), "+FLAGS", "\\Deleted")
+ if store_status != "OK":
+ failed_uids.append(uid)
+ continue
+ pending_expunge = True
+ deleted_uids.append(uid)
+ _email_index_delete(owner, account_id, folder, uid)
+ except Exception:
+ failed_uids.append(uid)
+ logger.debug("Bulk email delete failed for uid=%s", uid, exc_info=True)
+ if pending_expunge:
+ conn.expunge()
+ if deleted_uids:
+ _invalidate_list_cache(account_id, folder)
+ return {"success": True, "deleted_uids": deleted_uids, "failed_uids": failed_uids}
+ except Exception as e:
+ logger.error(f"Failed to bulk delete emails: {e}")
+ return {"success": False, "error": "Mail operation failed", "deleted_uids": deleted_uids, "failed_uids": [u for u in uids if u not in deleted_uids]}
+
+ @router.delete("/odysseus/reminders")
+ async def delete_odysseus_reminder_emails(
+ account_id: str | None = Query(None),
+ permanent: bool = Query(False),
+ owner: str = Depends(require_owner),
+ ):
+ """Delete email messages stamped as Odysseus reminders."""
+ if account_id:
+ _assert_owns_account(account_id, owner)
+ deleted = 0
+ folders_checked = []
+ try:
+ cfg = _get_email_config(account_id, owner=owner)
+ own_addrs = [
+ (cfg.get("from_address") or "").strip(),
+ (cfg.get("smtp_user") or "").strip(),
+ (cfg.get("imap_user") or "").strip(),
+ ]
+ own_addrs = [a for i, a in enumerate(own_addrs) if a and a not in own_addrs[:i]]
+
+ def _search_quote(value: str) -> str:
+ return '"' + (value or "").replace("\\", "\\\\").replace('"', '\\"') + '"'
+
+ def _search_uids(conn, criteria: str):
+ st, data = conn.uid("SEARCH", None, criteria)
+ return set(data[0].split()) if st == "OK" and data and data[0] else set()
+
+ with _imap(account_id, owner=owner) as conn:
+ sent_folder = _detect_sent_folder(conn)
+ candidates = ["INBOX", sent_folder, "All Mail", "[Gmail]/All Mail"]
+ seen = set()
+ for folder_name in candidates:
+ if not folder_name or folder_name in seen:
+ continue
+ seen.add(folder_name)
+ try:
+ st, _ = conn.select(_q(folder_name))
+ if st != "OK":
+ continue
+ folders_checked.append(folder_name)
+ uids = set()
+ # Match the Reminders filter: new messages have the
+ # explicit kind header, and subject fallback catches
+ # clients/providers that stripped custom headers.
+ uids.update(_search_uids(conn, f'(HEADER X-Odysseus-Kind {_search_quote("reminder")})'))
+ uids.update(_search_uids(conn, f'(SUBJECT {_search_quote("Reminder (Odysseus):")})'))
+ for addr in own_addrs:
+ addr_q = _search_quote(addr)
+ uids.update(_search_uids(conn, f'(FROM {addr_q} SUBJECT {_search_quote("Reminder (Odysseus):")})'))
+ # Legacy reminders created before the Odysseus
+ # prefix still came from this mailbox as
+ # "Reminder: ..."; include them in Clear without
+ # sweeping unrelated external reminder emails.
+ uids.update(_search_uids(conn, f'(FROM {addr_q} SUBJECT {_search_quote("Reminder:")})'))
+ if not uids:
+ continue
+ for uid in sorted(uids, key=lambda b: int(b)):
+ if permanent:
+ conn.uid("STORE", uid, "+FLAGS", "\\Deleted")
+ else:
+ copy_st, _ = conn.uid("COPY", uid, _q("Trash"))
+ if copy_st == "OK":
+ conn.uid("STORE", uid, "+FLAGS", "\\Deleted")
+ else:
+ conn.uid("STORE", uid, "+FLAGS", "\\Deleted")
+ deleted += 1
+ conn.expunge()
+ except Exception as e:
+ logger.warning(f"Skipped reminder cleanup in {folder_name!r}: {e}")
+ _invalidate_list_cache(account_id)
+ return {"success": True, "deleted": deleted, "folders_checked": folders_checked}
+ except Exception as e:
+ logger.error(f"delete_odysseus_reminder_emails failed: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.post("/move/{uid}")
+ async def move_email(uid: str, folder: str = Query("INBOX"), dest: str = Query(...), account_id: str | None = Query(None), owner: str = Depends(require_owner)):
+ """Move an email to another folder."""
+ fixture_ok = _fixture_email_update(uid, owner, source_folder=folder, folder=dest)
+ if fixture_ok is not None:
+ return {"success": bool(fixture_ok), **({} if fixture_ok else {"error": f"Failed to move to {dest}"})}
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder))
+ if not _move_email_message(conn, uid, dest):
+ return {"success": False, "error": f"Failed to move to {dest}"}
+ _email_index_delete(owner, account_id, folder, uid)
+ _invalidate_list_cache(account_id)
+ return {"success": True}
+ except Exception as e:
+ logger.error(f"Failed to move email {uid} to {dest}: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.get("/folders")
+ async def list_folders(
+ account_id: str | None = Query(None),
+ cached_only: int = Query(0),
+ owner: str = Depends(require_owner),
+ ):
+ """List IMAP folders."""
+ if _fixture_email_enabled():
+ return {"folders": ["INBOX", "Archive", "Sent"], "sync": {"source": "local"}}
+ cached = _folder_cache_get(account_id, owner)
+ if cached is not None:
+ payload = dict(cached)
+ sync_meta = dict(payload.get("sync") or {})
+ sync_meta["source"] = "folder_cache"
+ payload["sync"] = sync_meta
+ return payload
+ if cached_only:
+ stale = _folder_cache_get_stale(account_id, owner)
+ if stale:
+ payload = dict(stale)
+ sync_meta = dict(payload.get("sync") or {})
+ sync_meta["source"] = "folder_cache_stale"
+ payload["sync"] = sync_meta
+ return payload
+ return {
+ "folders": ["INBOX", "Sent", "Archive"],
+ "sync": {"source": "folder_cached_only_fallback"},
+ }
+
+ def _list_folders_sync():
+ with _imap(account_id, owner=owner) as conn:
+ status, folders = conn.list()
+ result = []
+ for f in folders or []:
+ decoded = f.decode() if isinstance(f, bytes) else f
+ match = re.search(r'"([^"]*)"$|(\S+)$', decoded)
+ if match:
+ name = match.group(1) or match.group(2)
+ result.append(name)
+ return {
+ "folders": result,
+ "sync": {
+ "source": "imap",
+ "updated_at": datetime.utcnow().isoformat() + "Z",
+ "status": status.decode() if isinstance(status, bytes) else status,
+ },
+ }
+
+ try:
+ payload = await _asyncio.wait_for(_asyncio.to_thread(_list_folders_sync), timeout=8.0)
+ _folder_cache_put(account_id, owner, payload)
+ return payload
+ except _asyncio.TimeoutError:
+ logger.warning(f"list_folders timed out for account={account_id or 'default'} owner={owner}")
+ stale = _folder_cache_get_stale(account_id, owner)
+ if stale:
+ payload = dict(stale)
+ sync_meta = dict(payload.get("sync") or {})
+ sync_meta["source"] = "folder_cache_stale"
+ sync_meta["warning"] = "Folder list timed out"
+ payload["sync"] = sync_meta
+ return payload
+ return {
+ "folders": ["INBOX", "Sent", "Archive"],
+ "error": "Folder list timed out",
+ "sync": {"source": "folder_timeout_fallback"},
+ }
+ except Exception as e:
+ logger.error(f"list_folders failed: {e}")
+ return {"folders": [], "error": "Mail operation failed"}
+
+ @router.post("/mark-answered/{uid}")
+ async def mark_answered(uid: str, folder: str = Query("INBOX"), account_id: str | None = Query(None), owner: str = Depends(require_owner)):
+ """Mark an email as answered (set \\Answered flag)."""
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder))
+ if not _store_email_flag(conn, uid, "\\Answered", add=True):
+ return {"success": False, "error": "Email not found"}
+ _email_index_update_flags(owner, account_id, folder, uid, "\\Answered", True)
+ _clear_done_response_tags(owner, account_id, folder, uid)
+ _invalidate_list_cache(account_id, folder)
+ return {"success": True}
+ except Exception as e:
+ logger.error(f"Failed to mark answered {uid}: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.post("/clear-answered/{uid}")
+ async def clear_answered(uid: str, folder: str = Query("INBOX"), account_id: str | None = Query(None), owner: str = Depends(require_owner)):
+ """Clear the \\Answered flag from an email."""
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder))
+ if not _store_email_flag(conn, uid, "\\Answered", add=False):
+ return {"success": False, "error": "Email not found"}
+ _email_index_update_flags(owner, account_id, folder, uid, "\\Answered", False)
+ _invalidate_list_cache(account_id, folder)
+ return {"success": True}
+ except Exception as e:
+ logger.error(f"Failed to clear answered {uid}: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.post("/compose-upload")
+ async def compose_upload(file: UploadFile = File(...), owner: str = Depends(require_owner)):
+ """Upload a file for attaching to a compose email. Returns a token."""
+ try:
+ # Sanitize filename and generate a unique token
+ safe_name = re.sub(r"[^\w\s\-.]", "_", file.filename or "file").strip()
+ token = f"{uuid.uuid4().hex}_{safe_name}"
+ filepath = COMPOSE_UPLOADS_DIR / token
+ content = await read_upload_limited(file, EMAIL_COMPOSE_UPLOAD_MAX_BYTES, "Attachment")
+ with open(filepath, "wb") as f:
+ f.write(content)
+ return {
+ "success": True,
+ "token": token,
+ "filename": safe_name,
+ "size": len(content),
+ }
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.error(f"Failed to upload attachment: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ def _safe_compose_filename(name: str, fallback: str = "attachment") -> str:
+ safe_name = re.sub(r"[^\w\s\-.]", "_", Path(str(name or fallback)).name).strip(". ")[:180]
+ return safe_name or fallback
+
+ def _stage_compose_bytes(filename: str, content: bytes) -> dict:
+ if len(content) > EMAIL_COMPOSE_UPLOAD_MAX_BYTES:
+ raise HTTPException(status_code=413, detail="Attachment too large")
+ safe_name = _safe_compose_filename(filename)
+ token = f"{uuid.uuid4().hex}_{safe_name}"
+ filepath = COMPOSE_UPLOADS_DIR / token
+ with open(filepath, "wb") as f:
+ f.write(content)
+ return {"success": True, "token": token, "filename": safe_name, "size": len(content)}
+
+ def _stage_compose_file(filename: str, src: Path) -> dict:
+ if not src.exists() or not src.is_file():
+ raise HTTPException(status_code=404, detail="File not found")
+ size = src.stat().st_size
+ if size > EMAIL_COMPOSE_UPLOAD_MAX_BYTES:
+ raise HTTPException(status_code=413, detail="Attachment too large")
+ safe_name = _safe_compose_filename(filename)
+ token = f"{uuid.uuid4().hex}_{safe_name}"
+ dest = COMPOSE_UPLOADS_DIR / token
+ import shutil as _shutil
+ _shutil.copyfile(str(src), str(dest))
+ return {"success": True, "token": token, "filename": safe_name, "size": size}
+
+ def _load_odysseus_attachment_source(db, kind: str, item_id: str, owner: str):
+ from core.database import Document as _Doc, GalleryImage as _GI
+ from core.database import Session as _Sess
+
+ if kind == "document":
+ doc = db.query(_Doc).filter(_Doc.id == item_id, _Doc.is_active == True).first()
+ if not doc:
+ raise HTTPException(status_code=404, detail="Document not found")
+ if owner:
+ if doc.owner and doc.owner != owner:
+ raise HTTPException(status_code=404, detail="Document not found")
+ if not doc.owner and doc.session_id:
+ sess = db.query(_Sess).filter(_Sess.id == doc.session_id).first()
+ if sess and sess.owner and sess.owner != owner:
+ raise HTTPException(status_code=404, detail="Document not found")
+ lang = (doc.language or "text").strip().lower()
+ ext = {
+ "markdown": "md",
+ "email": "eml",
+ "json": "json",
+ "yaml": "yaml",
+ "yml": "yml",
+ "html": "html",
+ "csv": "csv",
+ "xml": "xml",
+ "text": "txt",
+ }.get(lang, "txt")
+ base = _safe_compose_filename(doc.title or "document", "document")
+ if not base.lower().endswith(f".{ext}"):
+ base = f"{base}.{ext}"
+ return {"filename": base, "content": (doc.current_content or "").encode("utf-8")}
+
+ if kind == "gallery":
+ img = db.query(_GI).filter(_GI.id == item_id, _GI.is_active == True).first()
+ if not img:
+ raise HTTPException(status_code=404, detail="Image not found")
+ if owner and img.owner and img.owner != owner:
+ raise HTTPException(status_code=404, detail="Image not found")
+ from routes.gallery.gallery_routes import _gallery_image_path
+ src = _gallery_image_path(img.filename)
+ if not src.exists() or not src.is_file():
+ raise HTTPException(status_code=404, detail="Image file not found")
+ return {"filename": _safe_compose_filename(img.filename or "gallery-image.png"), "path": src}
+
+ raise HTTPException(status_code=400, detail="Unknown attachment kind")
+
+ @router.post("/compose-from-odysseus")
+ async def compose_from_odysseus(data: dict, owner: str = Depends(require_owner)):
+ """Stage an Odysseus document or gallery image as a compose upload."""
+ kind = str(data.get("kind") or "").strip().lower()
+ item_id = str(data.get("id") or "").strip()
+ if kind not in {"document", "gallery"} or not item_id:
+ raise HTTPException(status_code=400, detail="Expected kind and id")
+ try:
+ from core.database import SessionLocal as _SL
+
+ db = _SL()
+ try:
+ src = _load_odysseus_attachment_source(db, kind, item_id, owner)
+ if "path" in src:
+ return _stage_compose_file(src["filename"], src["path"])
+ return _stage_compose_bytes(src["filename"], src["content"])
+ finally:
+ db.close()
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.error(f"Failed to stage Odysseus attachment {kind}/{item_id}: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.post("/compose-from-odysseus-zip")
+ async def compose_from_odysseus_zip(data: dict, owner: str = Depends(require_owner)):
+ """Stage several Odysseus documents/gallery images as one zip attachment."""
+ raw_items = data.get("items") or []
+ if not isinstance(raw_items, list) or not raw_items:
+ raise HTTPException(status_code=400, detail="Expected items")
+ if len(raw_items) > 100:
+ raise HTTPException(status_code=400, detail="Too many attachments")
+ try:
+ from core.database import SessionLocal as _SL
+
+ db = _SL()
+ try:
+ buf = io.BytesIO()
+ used_names: dict[str, int] = {}
+
+ def unique_name(name: str) -> str:
+ safe = _safe_attachment_zip_name(name, "attachment")
+ stem = Path(safe).stem or "attachment"
+ suffix = Path(safe).suffix
+ idx = used_names.get(safe, 0)
+ used_names[safe] = idx + 1
+ if idx == 0:
+ return safe
+ return f"{stem}-{idx + 1}{suffix}"
+
+ with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
+ for item in raw_items:
+ if not isinstance(item, dict):
+ continue
+ kind = str(item.get("kind") or "").strip().lower()
+ item_id = str(item.get("id") or "").strip()
+ if kind not in {"document", "gallery"} or not item_id:
+ continue
+ src = _load_odysseus_attachment_source(db, kind, item_id, owner)
+ zname = unique_name(src["filename"])
+ if "path" in src:
+ zf.write(src["path"], arcname=zname)
+ else:
+ zf.writestr(zname, src["content"])
+ content = buf.getvalue()
+ if not content:
+ raise HTTPException(status_code=400, detail="No valid attachments")
+ return _stage_compose_bytes("odysseus-attachments.zip", content)
+ finally:
+ db.close()
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.error(f"Failed to stage Odysseus zip attachment: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.post("/compose-from-attachment/{uid}/{index}")
+ async def compose_from_attachment(
+ uid: str,
+ index: int,
+ folder: str = Query("INBOX"),
+ account_id: str | None = Query(None),
+ owner: str = Depends(require_owner),
+ ):
+ """Stage an existing email attachment as a compose upload.
+
+ Used by Forward so original attachments are sent as real attachments,
+ not just shown as source-email chips.
+ """
+ try:
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder), readonly=True)
+ status, msg_data = _imap_uid_fetch(conn, uid, "(RFC822)")
+ if status != "OK":
+ return {"success": False, "error": "Email not found"}
+ raw = msg_data[0][1]
+ msg = email_mod.message_from_bytes(raw)
+ target_dir = attachment_extract_dir(folder, uid)
+ filepath = _extract_attachment_to_disk(msg, index, target_dir)
+ if not filepath:
+ return {"success": False, "error": f"Attachment index {index} not found"}
+ safe_name = re.sub(r"[^\w\s\-.]", "_", filepath.name or "attachment").strip() or "attachment"
+ token = f"{uuid.uuid4().hex}_{safe_name}"
+ dest = COMPOSE_UPLOADS_DIR / token
+ import shutil as _shutil
+ _shutil.copyfile(str(filepath), str(dest))
+ return {
+ "success": True,
+ "token": token,
+ "filename": safe_name,
+ "size": dest.stat().st_size,
+ }
+ except Exception as e:
+ logger.error(f"Failed to stage forwarded attachment {uid}/{index}: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.delete("/compose-upload/{token}")
+ async def delete_compose_upload(token: str, owner: str = Depends(require_owner)):
+ """Delete a staged compose upload."""
+ try:
+ # Prevent path traversal
+ safe_token = Path(token).name
+ filepath = COMPOSE_UPLOADS_DIR / safe_token
+ if filepath.exists():
+ filepath.unlink()
+ return {"success": True}
+ except Exception as e:
+ logger.error(f"delete_compose_upload {token!r} failed: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ async def _send_email_sync(
+ to, cc, bcc, subject, body, in_reply_to, references, attachments,
+ account_id=None, owner="", odysseus_kind=None, odysseus_ref=None,
+ ):
+ """Shared send logic used by both /send and scheduled delivery.
+
+ SECURITY: callers MUST pass `owner` (the authed user) so the config
+ lookup is scoped — otherwise the fallback picks whichever account
+ happens to be is_default globally and the message ships through
+ someone else's SMTP creds + From-address.
+ """
+ cfg = _resolve_send_config(account_id, owner=owner)
+ has_atts = bool(attachments)
+ if has_atts:
+ outer = MIMEMultipart("mixed")
+ body_container = MIMEMultipart("alternative")
+ else:
+ outer = MIMEMultipart("alternative")
+ body_container = outer
+
+ to = _normalize_addr_field(to or "")
+ cc = _normalize_addr_field(cc or "")
+ bcc = _normalize_addr_field(bcc or "")
+ outer["From"] = email.utils.formataddr((cfg.get("display_name") or "", cfg["from_address"]))
+ outer["To"] = to
+ if cc:
+ outer["Cc"] = cc
+ outer["Subject"] = subject or ""
+ outer["Date"] = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S +0000")
+ _apply_odysseus_headers(outer, odysseus_kind or "scheduled", odysseus_ref)
+ if in_reply_to:
+ outer["In-Reply-To"] = in_reply_to
+ if references:
+ outer["References"] = references
+
+ body_container.attach(MIMEText(body or "", "plain", "utf-8"))
+ body_container.attach(MIMEText(_md_to_email_html(body or ""), "html", "utf-8"))
+
+ if has_atts:
+ outer.attach(body_container)
+ _attach_compose_uploads(outer, attachments)
+
+ recipients = _envelope_recipients(to, cc, bcc)
+
+ _send_smtp_message(cfg, cfg["from_address"], recipients, outer.as_string())
+
+ _cleanup_compose_uploads(attachments)
+
+ @router.post("/schedule")
+ async def schedule_email(req: dict, owner: str = Depends(require_owner)):
+ """Schedule an email to be sent at a specific time. ISO8601 UTC."""
+ import sqlite3
+ import uuid as _uuid
+ try:
+ send_at = req.get("send_at")
+ if not send_at:
+ return {"success": False, "error": "send_at required (ISO8601 UTC)"}
+ # Body-based account_id — dep can't see it, check here.
+ _acct = req.get("account_id")
+ if _acct:
+ _assert_owns_account(_acct, owner)
+ # Validate parseable + reject past times (the poller fires
+ # anything in the past immediately on the next tick — a
+ # 1970-dated schedule would deliver right now).
+ from datetime import datetime as _dt, timezone as _tz
+ try:
+ parsed_at = _dt.fromisoformat(send_at.replace("Z", "+00:00"))
+ except ValueError:
+ return {"success": False, "error": "send_at must be ISO8601"}
+ now_utc = _dt.now(_tz.utc) if parsed_at.tzinfo else _dt.utcnow()
+ # Tiny 30s grace so a user clicking Send right at the chosen
+ # minute doesn't trip the past-time guard.
+ if parsed_at < now_utc:
+ return {"success": False, "error": "send_at must be in the future"}
+ # Normalize to naive UTC before storing: the poller selects due
+ # rows with a lexicographic string compare against a naive
+ # datetime.utcnow().isoformat(), so storing the raw client string
+ # makes "+02:00" schedules fire hours late, negative offsets fire
+ # hours early, and a "Z" suffix compares after the fractional
+ # seconds of the poller timestamp.
+ if parsed_at.tzinfo:
+ parsed_at = parsed_at.astimezone(_tz.utc).replace(tzinfo=None)
+ send_at = parsed_at.isoformat()
+
+ sid = _uuid.uuid4().hex[:16]
+ conn = sqlite3.connect(SCHEDULED_DB)
+ conn.execute("""
+ INSERT INTO scheduled_emails
+ (id, to_addr, cc, bcc, subject, body, in_reply_to, references_hdr, attachments, send_at, created_at, status, account_id, odysseus_kind, owner)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?)
+ """, (
+ sid,
+ req.get("to", ""),
+ req.get("cc") or None,
+ req.get("bcc") or None,
+ req.get("subject") or "",
+ req.get("body") or "",
+ req.get("in_reply_to") or None,
+ req.get("references") or None,
+ json.dumps(req.get("attachments") or []),
+ send_at,
+ datetime.utcnow().isoformat(),
+ req.get("account_id") or None,
+ req.get("odysseus_kind") or "scheduled",
+ owner or "",
+ ))
+ conn.commit()
+ conn.close()
+ logger.info(f"Scheduled email {sid} for {send_at}")
+ return {"success": True, "id": sid, "send_at": send_at}
+ except Exception as e:
+ logger.error(f"Failed to schedule email: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.get("/scheduled")
+ async def list_scheduled(owner: str = Depends(require_owner)):
+ """List all scheduled (pending) emails."""
+ import sqlite3
+ try:
+ conn = sqlite3.connect(SCHEDULED_DB)
+ rows = conn.execute("""
+ SELECT id, to_addr, cc, subject, send_at, created_at, status, error
+ FROM scheduled_emails
+ WHERE status IN ('pending', 'failed') AND owner = ?
+ ORDER BY send_at ASC
+ """, (owner or "",)).fetchall()
+ conn.close()
+ return {"scheduled": [
+ {
+ "id": r[0], "to": r[1], "cc": r[2], "subject": r[3],
+ "send_at": r[4], "created_at": r[5], "status": r[6], "error": r[7],
+ } for r in rows
+ ]}
+ except Exception as e:
+ logger.error(f"list_scheduled failed: {e}")
+ return {"scheduled": [], "error": "Mail operation failed"}
+
+ @router.delete("/scheduled/{sid}")
+ async def cancel_scheduled(sid: str, owner: str = Depends(require_owner)):
+ """Cancel a scheduled email."""
+ import sqlite3
+ try:
+ conn = sqlite3.connect(SCHEDULED_DB)
+ conn.execute(
+ "DELETE FROM scheduled_emails WHERE id = ? AND status = 'pending' AND owner = ?",
+ (sid, owner or ""),
+ )
+ conn.commit()
+ conn.close()
+ return {"success": True}
+ except Exception as e:
+ logger.error(f"cancel_scheduled {sid!r} failed: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ # ── Agent send-confirm: list/approve/cancel ──────────────────────────
+ # When `agent_email_confirm` is on, the MCP send_email tool drops the
+ # composed email into scheduled_emails with status='agent_draft' (a
+ # far-future send_at so the poller never picks it up). These endpoints
+ # let the chat UI surface them for the user and either approve (flip
+ # to status='pending' with send_at=now so the poller delivers it) or
+ # cancel (status='cancelled').
+ @router.get("/pending")
+ async def list_pending_agent_drafts(owner: str = Depends(require_owner)):
+ import sqlite3
+ try:
+ conn = sqlite3.connect(SCHEDULED_DB)
+ conn.row_factory = sqlite3.Row
+ rows = conn.execute(
+ """SELECT id, to_addr, subject, body, created_at, account_id
+ FROM scheduled_emails
+ WHERE status = 'agent_draft' AND owner = ?
+ ORDER BY created_at DESC""",
+ (owner or "",),
+ ).fetchall()
+ conn.close()
+ return {"pending": [dict(r) for r in rows]}
+ except Exception as e:
+ logger.error(f"list_pending_agent_drafts failed: {e}")
+ return {"pending": [], "error": "Mail operation failed"}
+
+ @router.post("/pending/{sid}/approve")
+ async def approve_agent_draft(sid: str, owner: str = Depends(require_owner)):
+ """Approve a draft staged by the agent: flip status → pending and
+ backdate send_at so the scheduled-send poller picks it up
+ immediately."""
+ import sqlite3
+ try:
+ conn = sqlite3.connect(SCHEDULED_DB)
+ cur = conn.execute(
+ """UPDATE scheduled_emails
+ SET status = 'pending', send_at = ?
+ WHERE id = ? AND status = 'agent_draft' AND owner = ?""",
+ (datetime.utcnow().isoformat(), sid, owner or ""),
+ )
+ conn.commit()
+ affected = cur.rowcount
+ conn.close()
+ if not affected:
+ return {"success": False, "error": "Draft not found or already handled"}
+ return {"success": True}
+ except Exception as e:
+ logger.error(f"approve_agent_draft {sid!r} failed: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.delete("/pending/{sid}")
+ async def cancel_agent_draft(sid: str, owner: str = Depends(require_owner)):
+ """Discard a draft the agent staged for approval."""
+ import sqlite3
+ try:
+ conn = sqlite3.connect(SCHEDULED_DB)
+ cur = conn.execute(
+ """UPDATE scheduled_emails SET status = 'cancelled'
+ WHERE id = ? AND status = 'agent_draft' AND owner = ?""",
+ (sid, owner or ""),
+ )
+ conn.commit()
+ affected = cur.rowcount
+ conn.close()
+ if not affected:
+ return {"success": False, "error": "Draft not found or already handled"}
+ return {"success": True}
+ except Exception as e:
+ logger.error(f"cancel_agent_draft {sid!r} failed: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.get("/resolve-contact")
+ async def resolve_contact(name: str = Query(..., description="Name to search for"), owner: str = Depends(require_owner)):
+ """Search Sent folder for a contact by name. Returns matching email addresses."""
+ try:
+ with _imap(owner=owner) as conn:
+ matches = {}
+ for folder in ["Sent", "INBOX", "Drafts"]:
+ try:
+ st, _ = conn.select(_q(folder), readonly=True)
+ if st != "OK":
+ continue
+ st, data = conn.search(None, "ALL")
+ if st != "OK" or not data[0]:
+ continue
+ uids = data[0].split()[-200:]
+ for uid in reversed(uids):
+ try:
+ st2, msg_data = conn.fetch(uid, "(BODY.PEEK[HEADER.FIELDS (FROM TO CC)])")
+ if st2 != "OK":
+ continue
+ raw = msg_data[0][1] if msg_data[0] and len(msg_data[0]) > 1 else b""
+ hdr = email_mod.message_from_bytes(raw)
+ for field in ["From", "To", "Cc"]:
+ val = _decode_header(hdr.get(field, ""))
+ if not val:
+ continue
+ for part in val.split(","):
+ part = part.strip()
+ if name.lower() in part.lower():
+ addr_match = re.search(r'<([^>]+)>', part)
+ addr = addr_match.group(1) if addr_match else part
+ addr = addr.strip().lower()
+ if addr and "@" in addr:
+ display = part.split("<")[0].strip().strip('"') or addr
+ if addr not in matches:
+ matches[addr] = display
+ except Exception:
+ continue
+ except Exception:
+ continue
+ if len(matches) >= 10:
+ break
+ results = [{"email": addr, "name": display} for addr, display in matches.items()]
+ return {"contacts": results[:10], "query": name}
+ except Exception as e:
+ logger.error(f"resolve_contact {name!r} failed: {e}")
+ return {"contacts": [], "error": "Mail operation failed"}
+
+ @router.post("/send")
+ async def send_email(req: SendEmailRequest, background_tasks: BackgroundTasks, owner: str = Depends(require_owner)):
+ """Queue an email for SMTP delivery. Returns immediately; send runs in background.
+
+ Uses req.account_id to pick the sending account (falls back to default)."""
+ # Body-based account_id — dep can't see it, check here.
+ if req.account_id:
+ _assert_owns_account(req.account_id, owner)
+
+ try:
+ cfg = _resolve_send_config(req.account_id, owner=owner)
+ except Exception as e:
+ logger.warning(f"No SMTP-capable account resolved: {e}")
+ return {"success": False, "error": str(e) or "No SMTP-capable email account configured"}
+
+ # Use 'mixed' if we have attachments, 'alternative' otherwise
+ has_attachments = bool(req.attachments)
+ logger.info(
+ "Sending email account=%s from=%s via=%s to=%s: subject=%r, attachments=%s",
+ cfg.get("account_id") or req.account_id or "default",
+ cfg.get("from_address") or cfg.get("smtp_user") or "",
+ cfg.get("smtp_host") or "",
+ req.to,
+ req.subject,
+ req.attachments,
+ )
+ if has_attachments:
+ outer = MIMEMultipart("mixed")
+ body_container = MIMEMultipart("alternative")
+ else:
+ outer = MIMEMultipart("alternative")
+ body_container = outer
+
+ req.to = _normalize_addr_field(req.to or "")
+ req.cc = _normalize_addr_field(req.cc or "")
+ req.bcc = _normalize_addr_field(req.bcc or "")
+ outer["From"] = email.utils.formataddr((cfg.get("display_name") or "", cfg["from_address"]))
+ outer["To"] = req.to
+ if req.cc:
+ outer["Cc"] = req.cc
+ outer["Subject"] = req.subject
+ outer["Date"] = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S +0000")
+ # Use a real domain in the Message-ID. Some receiving providers accept
+ # SMTP delivery but silently discard messages carrying the local-only
+ # ``odysseus.local`` domain.
+ from_domain = (cfg.get("from_address") or "").rsplit("@", 1)[-1].strip()
+ outer["Message-ID"] = email.utils.make_msgid(domain=from_domain or None)
+
+ if req.in_reply_to:
+ outer["In-Reply-To"] = req.in_reply_to
+ if req.references:
+ outer["References"] = req.references
+ if req.odysseus_kind:
+ _apply_odysseus_headers(outer, req.odysseus_kind)
+
+ # Plain + HTML body. Escape user content so a `<script>` or
+ # `<img onerror=...>` paste in compose doesn't end up as live HTML
+ # in the recipient's MUA.
+ body_container.attach(MIMEText(req.body, "plain", "utf-8"))
+ # HTML part: prefer the WYSIWYG composer's HTML (sanitized via allowlist);
+ # otherwise render the markdown body. Both routes escape untrusted text,
+ # so neither can introduce live script/handlers.
+ _html_part = (_sanitize_email_html(req.body_html) if req.body_html else None) \
+ or _md_to_email_html(req.body)
+ body_container.attach(MIMEText(_html_part, "html", "utf-8"))
+
+ if has_attachments:
+ outer.attach(body_container)
+ _attach_compose_uploads(outer, req.attachments)
+
+ # Build recipient list (parse the address grammar so display names with
+ # commas don't get split into broken envelope addresses)
+ recipients = _envelope_recipients(req.to, req.cc, req.bcc)
+
+ # Serialize what the background task needs so the request object can be GC'd
+ outer_bytes = outer.as_bytes()
+ outer_str = outer.as_string()
+ _from = cfg["from_address"]
+ _smtp_host = cfg["smtp_host"]
+ _smtp_port = cfg["smtp_port"]
+ _smtp_security = cfg.get("smtp_security")
+ _smtp_user = cfg["smtp_user"]
+ _smtp_pw = cfg["smtp_password"]
+ _recipients = list(recipients)
+ _to_label = req.to
+ _subject = req.subject
+ _atts = list(req.attachments or [])
+ _message_id = outer["Message-ID"]
+
+ _account_id = cfg.get("account_id") or req.account_id # capture for the IMAP append in the closure
+ _in_reply_to = (req.in_reply_to or "").strip()
+ _source_uid = (req.source_uid or "").strip()
+ _source_folder = (req.source_folder or "INBOX").strip() or "INBOX"
+ _draft_uid = (req.draft_uid or "").strip()
+ _draft_folder = (req.draft_folder or "").strip()
+ _oauth_provider = cfg.get("oauth_provider") or ""
+ _oauth_access_token = cfg.get("oauth_access_token") or ""
+ _oauth_refresh_token = cfg.get("oauth_refresh_token") or ""
+ _oauth_token_expiry = cfg.get("oauth_token_expiry") or ""
+
+ def _deliver():
+ try:
+ _send_smtp_message(
+ {
+ "smtp_host": _smtp_host,
+ "smtp_port": _smtp_port,
+ "smtp_security": _smtp_security,
+ "smtp_user": _smtp_user,
+ "smtp_password": _smtp_pw,
+ "account_id": _account_id,
+ "oauth_provider": _oauth_provider,
+ "oauth_access_token": _oauth_access_token,
+ "oauth_refresh_token": _oauth_refresh_token,
+ "oauth_token_expiry": _oauth_token_expiry,
+ },
+ _from,
+ _recipients,
+ outer_str,
+ )
+ logger.info(
+ "Email sent account=%s from=%s via=%s to=%s: %s",
+ _account_id or "default",
+ _from,
+ _smtp_host,
+ _to_label,
+ _subject,
+ )
+ delivery_result = {
+ "success": True,
+ "account_id": cfg.get("account_id") or _account_id,
+ "sent_folder": None,
+ "sent_uid": None,
+ "message_id": _message_id,
+ }
+ try:
+ with _imap(_account_id, owner=owner) as imap:
+ sent_folder = _detect_sent_folder(imap)
+ sent_uid = None
+ sent_append_ok = False
+ append_st, append_data = imap.append(sent_folder, "\\Seen", None, outer_bytes)
+ sent_append_ok = append_st == "OK"
+ if append_st == "OK" and append_data:
+ m = re.search(rb"APPENDUID\s+\d+\s+(\d+)", append_data[0] or b"")
+ if m:
+ sent_uid = m.group(1).decode("ascii", errors="ignore")
+ if not sent_uid:
+ try:
+ st_sel, _ = imap.select(_q(sent_folder), readonly=True)
+ if st_sel == "OK":
+ mid = (_message_id or "").strip().lstrip("<").rstrip(">").replace('"', '\\"')
+ st_uid, uid_data = imap.uid("SEARCH", None, f'HEADER Message-ID "{mid}"')
+ if st_uid == "OK" and uid_data and uid_data[0]:
+ sent_uid = uid_data[0].split()[-1].decode("ascii", errors="ignore")
+ except Exception:
+ pass
+ # Auto-mark the source email as Answered/done so it
+ # disappears from "undone" filters.
+ if _source_uid:
+ try:
+ st, _sel = imap.select(_q(_source_folder), readonly=False)
+ if st == "OK" and _store_email_flag(imap, _source_uid, "\\Answered", add=True):
+ _email_index_update_flags(owner, _account_id, _source_folder, _source_uid, "\\Answered", True)
+ _clear_done_response_tags(owner, _account_id, _source_folder, _source_uid)
+ _invalidate_list_cache(_account_id, _source_folder)
+ logger.info(f"Marked source UID {_source_uid} as \\Answered in {_source_folder}")
+ else:
+ logger.warning(f"Failed to mark source UID {_source_uid} as answered in {_source_folder}")
+ except Exception as e:
+ logger.warning(f"Failed to mark exact source UID as answered: {e}")
+ if _in_reply_to:
+ try:
+ # Strip any angle brackets and quote for IMAP
+ mid = _in_reply_to.strip().lstrip("<").rstrip(">").replace('"', '\\"')
+ # Search common folders for the source message.
+ folder_candidates = (
+ "INBOX",
+ sent_folder,
+ "Sent",
+ "[Gmail]/Sent Mail",
+ "Archive",
+ "All Mail",
+ "[Gmail]/All Mail",
+ )
+ for folder_name in dict.fromkeys(folder_candidates):
+ try:
+ st, _sel = imap.select(_q(folder_name), readonly=False)
+ if st != "OK":
+ continue
+ st2, sd = imap.search(None, f'HEADER Message-ID "{mid}"')
+ if st2 == "OK" and sd and sd[0]:
+ for u in sd[0].split():
+ imap.store(u, "+FLAGS", "\\Answered")
+ logger.info(f"Marked source {mid[:60]!r} as \\Answered in {folder_name}")
+ break
+ except Exception:
+ continue
+ except Exception as e:
+ logger.warning(f"Failed to auto-mark source as answered: {e}")
+ if _draft_uid and _draft_folder and sent_append_ok:
+ try:
+ st_draft, _ = imap.select(_q(_draft_folder), readonly=False)
+ if st_draft == "OK" and _store_email_flag(imap, _draft_uid, "\\Deleted", add=True):
+ imap.expunge()
+ logger.info(f"Removed sent draft UID {_draft_uid} from {_draft_folder}")
+ else:
+ logger.warning(f"Failed to remove sent draft UID {_draft_uid} from {_draft_folder}")
+ except Exception as e:
+ logger.warning(f"Failed to remove sent draft UID {_draft_uid}: {e}")
+ delivery_result = {
+ "success": True,
+ "account_id": cfg.get("account_id") or _account_id,
+ "sent_folder": sent_folder,
+ "sent_uid": sent_uid,
+ "message_id": _message_id,
+ }
+ except Exception as e:
+ logger.warning(f"Failed to append to Sent: {e}")
+ _cleanup_compose_uploads(_atts)
+ return delivery_result
+ except Exception as e:
+ logger.error(f"Failed to send email to {_to_label}: {e}")
+ return {"success": False, "error": str(e) or "Failed to send email"}
+
+ if req.wait_for_delivery:
+ result = await asyncio.to_thread(_deliver)
+ if result.get("success"):
+ return {"success": True, "queued": False, "message": f"Email sent to {req.to}", **result}
+ return result
+
+ background_tasks.add_task(_deliver)
+ return {
+ "success": True,
+ "queued": True,
+ "account_id": cfg.get("account_id") or req.account_id,
+ "message": f"Email queued for {req.to}",
+ }
+
+ @router.post("/draft")
+ async def save_draft(req: SendEmailRequest, owner: str = Depends(require_owner)):
+ """Save email as draft in IMAP Drafts folder.
+
+ IMAP append is sync; offload via asyncio.to_thread so the event loop
+ stays responsive on slow remote IMAP servers.
+ """
+ if req.account_id:
+ _assert_owns_account(req.account_id, owner)
+ cfg = _get_email_config(req.account_id, owner=owner)
+
+ # Multipart plain+HTML when the WYSIWYG composer supplied HTML, so a
+ # reopened draft keeps its formatting; plain MIMEText otherwise.
+ # Wrap that alternative part in mixed when staged attachments are
+ # present so recovery does not silently lose the files.
+ _draft_html = _sanitize_email_html(req.body_html) if req.body_html else None
+ _draft_has_attachments = bool(req.attachments)
+ if _draft_html:
+ body_container = MIMEMultipart("alternative")
+ body_container.attach(MIMEText(req.body, "plain", "utf-8"))
+ body_container.attach(MIMEText(_draft_html, "html", "utf-8"))
+ else:
+ body_container = MIMEText(req.body, "plain", "utf-8")
+ msg = MIMEMultipart("mixed") if _draft_has_attachments else body_container
+ if _draft_has_attachments:
+ msg.attach(body_container)
+ _attach_compose_uploads(msg, req.attachments)
+ msg["From"] = email.utils.formataddr((cfg.get("display_name") or "", cfg["from_address"]))
+ msg["To"] = req.to
+ if req.cc:
+ msg["Cc"] = req.cc
+ if req.bcc:
+ msg["Bcc"] = req.bcc
+ msg["Subject"] = req.subject
+ msg["Date"] = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S +0000")
+
+ if req.in_reply_to:
+ msg["In-Reply-To"] = req.in_reply_to
+ if req.references:
+ msg["References"] = req.references
+
+ _draft_acct = req.account_id
+
+ def _do_append():
+ try:
+ with _imap(_draft_acct, owner=owner) as imap:
+ drafts_folder = _detect_drafts_folder(imap)
+ append_st, append_data = imap.append(drafts_folder, "\\Draft", None, msg.as_bytes())
+ if append_st != "OK":
+ return (f"IMAP APPEND failed: {append_st}", None, None)
+ draft_uid = None
+ if append_data:
+ m = re.search(rb"APPENDUID\s+\d+\s+(\d+)", append_data[0] or b"")
+ if m:
+ draft_uid = m.group(1).decode("ascii", errors="ignore")
+ # Resaving an already-open draft creates a new IMAP
+ # message. Remove the previous copy only after the new
+ # append succeeded, so a transient IMAP failure cannot
+ # destroy the user's recovery copy.
+ old_uid = (req.draft_uid or "").strip()
+ old_folder = (req.draft_folder or "").strip()
+ if old_uid and old_folder and old_uid != (draft_uid or ""):
+ try:
+ st_old, _ = imap.select(_q(old_folder), readonly=False)
+ if st_old == "OK" and _store_email_flag(imap, old_uid, "\\Deleted", add=True):
+ imap.expunge()
+ else:
+ logger.warning(f"Failed to replace previous draft UID {old_uid} in {old_folder}")
+ except Exception as e:
+ logger.warning(f"Failed to replace previous draft UID {old_uid}: {e}")
+ return (None, drafts_folder, draft_uid)
+ except Exception as e:
+ return (str(e), None, None)
+
+ err, draft_folder, draft_uid = await asyncio.to_thread(_do_append)
+ if err:
+ logger.error(f"Failed to save draft: {err}")
+ return {"success": False, "error": err}
+ logger.info(f"Draft saved: {req.subject}")
+ return {"success": True, "message": "Draft saved", "draft_folder": draft_folder, "draft_uid": draft_uid}
+
+ @router.post("/extract-style")
+ async def extract_writing_style(
+ req: ExtractStyleRequest,
+ account_id: str | None = Query(None),
+ owner: str = Depends(require_owner),
+ ):
+ """Extract writing style from sent emails using LLM.
+
+ IMAP fetch is offloaded to a worker thread; the LLM call uses the
+ async client. Otherwise this handler froze the event loop for ~5s
+ on the IMAP step alone with a remote server.
+ """
+ if account_id:
+ _assert_owns_account(account_id, owner)
+
+ def _gather_samples() -> tuple[list[str], str | None]:
+ try:
+ with _imap(account_id, owner=owner) as imap:
+ imap.select(_q(_detect_sent_folder(imap)), readonly=True)
+ status, data = imap.search(None, "ALL")
+ if status != "OK" or not data[0]:
+ return [], "No sent emails found"
+ uid_list = data[0].split()[-req.sample_count:]
+
+ out = []
+ for uid in uid_list:
+ try:
+ status, msg_data = imap.fetch(uid, "(RFC822)")
+ if status != "OK":
+ continue
+ raw = msg_data[0][1]
+ msg = email_mod.message_from_bytes(raw)
+ body = ""
+ if msg.is_multipart():
+ for part in msg.walk():
+ if part.get_content_type() == "text/plain":
+ payload = part.get_payload(decode=True)
+ if payload:
+ charset = part.get_content_charset() or "utf-8"
+ body = payload.decode(charset, errors="replace")
+ break
+ else:
+ payload = msg.get_payload(decode=True)
+ if payload:
+ charset = msg.get_content_charset() or "utf-8"
+ body = payload.decode(charset, errors="replace")
+ if body.strip() and len(body) > 20:
+ out.append(body[:1000])
+ except Exception:
+ continue
+ return out, None
+ except Exception as e:
+ return [], str(e)
+
+ try:
+ samples, err = await asyncio.to_thread(_gather_samples)
+ if err and not samples:
+ return {"success": False, "error": err}
+
+ if len(samples) < 3:
+ return {"success": False, "error": f"Only found {len(samples)} usable sent emails, need at least 3"}
+
+ # Call LLM to analyze writing style. Prefer the utility model;
+ # fall back to the default chat model when utility isn't set
+ # (matches how the background email tasks behave).
+ from src.endpoint_resolver import resolve_endpoint
+
+ url, model, headers = resolve_endpoint("utility", owner=owner)
+ if not url or not model:
+ url, model, headers = resolve_endpoint("default", owner=owner)
+ if not url or not model:
+ return {"success": False, "error": "No LLM endpoint configured — set a Utility or Default Chat model in Settings → AI Defaults."}
+
+ sample_text = "\n\n---EMAIL---\n\n".join(samples[:15])
+ messages = [
+ {
+ "role": "system",
+ "content": (
+ "You are analyzing a user's email writing style. Based on the sample emails below, "
+ "describe their writing style in 3-5 concise sentences. Cover: tone (formal/informal), "
+ "typical greeting and sign-off patterns, sentence structure (short/long), "
+ "any distinctive phrases or habits, and overall communication approach. "
+ "Write this as instructions for an AI to mimic this style. "
+ "Start with 'Write emails in this style:'"
+ ),
+ },
+ {
+ "role": "user",
+ "content": f"Here are {len(samples)} recently sent emails:\n\n{sample_text}",
+ },
+ ]
+
+ style = await llm_call_async(url, model, messages, headers=headers, max_tokens=2048)
+ style = _strip_think(style or "")
+ if not style:
+ return {"success": False, "error": "LLM failed to generate style description"}
+
+ # Save to settings
+ settings = _load_settings()
+ _set_email_writing_style_for_account(settings, style, account_id)
+ _save_settings(settings)
+
+ logger.info("Writing style extracted and saved")
+ return {"success": True, "style": style}
+
+ except Exception as e:
+ logger.error(f"Failed to extract writing style: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.post("/summarize")
+ async def summarize_email(data: dict, owner: str = Depends(require_owner)):
+ """Generate a quick AI summary of an email body."""
+ try:
+ from src.endpoint_resolver import resolve_endpoint
+
+ body = data.get("body", "")
+ subject = data.get("subject", "")
+ sender = data.get("from", "")
+ uid = data.get("uid", "")
+ folder = data.get("folder", "INBOX") or "INBOX"
+ account_id = data.get("account_id")
+ if account_id:
+ _assert_owns_account(account_id, owner)
+ if not body:
+ return {
+ "success": False,
+ "error": "No body provided",
+ "error_code": "email_summary_missing_body",
+ }
+
+ # If we know which UID this is, fetch the raw message and pull
+ # attachment text so the summary can reference invoice totals,
+ # contract clauses, etc. — not just the body.
+ att_text = ""
+ if uid:
+ try:
+ def _fetch_atts():
+ with _imap(account_id, owner=owner) as conn:
+ conn.select(_q(folder), readonly=True)
+ status, msg_data = _imap_uid_fetch(conn, str(uid), "(BODY.PEEK[])")
+ if status != "OK" or not msg_data or not msg_data[0]:
+ return ""
+ raw = msg_data[0][1]
+ msg_obj = email_mod.message_from_bytes(raw)
+ return _extract_attachment_text(msg_obj, max_chars=6000)
+ att_text = await asyncio.to_thread(_fetch_atts)
+ except Exception as _ae:
+ logger.debug(f"on-demand summarize attachment fetch failed for uid={uid}: {_ae}")
+
+ body_for_llm = body
+ if att_text:
+ body_for_llm = body + "\n\n--- ATTACHMENTS ---\n\n" + att_text
+
+ url, model, headers = resolve_endpoint("utility", owner=owner)
+ if not url:
+ url, model, headers = resolve_endpoint("default", owner=owner)
+ if not url or not model:
+ return {
+ "success": False,
+ "error": "No model configured for email summaries",
+ "error_code": "email_summary_not_configured",
+ }
+
+ req_headers = {"Content-Type": "application/json"}
+ if headers:
+ req_headers.update(headers)
+ try:
+ content = await _generate_email_summary(
+ url=url,
+ model=model,
+ sender=sender,
+ subject=subject,
+ body_for_llm=body_for_llm,
+ headers=req_headers,
+ max_tokens=8192,
+ timeout=180,
+ )
+ except Exception as e:
+ logger.warning(
+ "Email summary LLM call failed %s",
+ _email_summary_failure_log_detail(e),
+ )
+ return {
+ "success": False,
+ "error": EMAIL_SUMMARY_ERROR_MESSAGE,
+ "error_code": EMAIL_SUMMARY_ERROR_CODE,
+ }
+
+ if not content:
+ return {
+ "success": False,
+ "error": "The model returned an empty summary",
+ "error_code": "email_summary_empty",
+ }
+
+ # Cache the summary if we have a message_id
+ mid = data.get("message_id", "")
+ if mid:
+ try:
+ import sqlite3 as _sql3
+ _c = _sql3.connect(SCHEDULED_DB)
+ _c.execute("""
+ INSERT OR REPLACE INTO email_summaries
+ (message_id, owner, uid, folder, subject, sender, summary, model_used, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """, (
+ mid, owner, data.get("uid", ""), data.get("folder", ""),
+ subject, sender, content, model, datetime.utcnow().isoformat(),
+ ))
+ _c.commit()
+ _c.close()
+ except Exception as e:
+ logger.warning(f"Failed to cache summary: {e}")
+
+ return {"success": True, "summary": content, "model_used": model}
+ except Exception as e:
+ logger.error(
+ "Email summary route failed %s",
+ _email_summary_failure_log_detail(e),
+ )
+ return {
+ "success": False,
+ "error": EMAIL_SUMMARY_ERROR_MESSAGE,
+ "error_code": EMAIL_SUMMARY_ERROR_CODE,
+ }
+
+ @router.post("/translate")
+ async def translate_email(data: dict, owner: str = Depends(require_owner)):
+ """Translate an email body into a target language."""
+ try:
+ from src.endpoint_resolver import (
+ resolve_endpoint,
+ resolve_utility_fallback_candidates,
+ )
+ from src.llm_core import llm_call_async_with_fallback
+
+ body = (data.get("body") or "").strip()
+ subject = (data.get("subject") or "").strip()
+ sender = (data.get("from") or "").strip()
+ target_language = (data.get("target_language") or "English").strip() or "English"
+ auto = bool(data.get("auto", False))
+ if not body:
+ return {"success": False, "error": "No body provided"}
+
+ body_hash = email_translation_body_hash(body)
+ try:
+ _c = _sql3.connect(SCHEDULED_DB)
+ owner_clause, owner_params = _email_cache_owner_clause(owner)
+ row = _c.execute(
+ f"SELECT translation, same_language, model_used FROM email_translations "
+ f"WHERE body_hash = ? AND target_language = ? AND {owner_clause}",
+ (body_hash, target_language, *owner_params),
+ ).fetchone()
+ _c.close()
+ if row:
+ if int(row[1] or 0):
+ return {
+ "success": True,
+ "same_language": True,
+ "language": target_language,
+ "model_used": row[2] or "cached",
+ "cached": True,
+ }
+ if row[0]:
+ return {
+ "success": True,
+ "translation": row[0],
+ "language": target_language,
+ "model_used": row[2] or "cached",
+ "cached": True,
+ }
+ except Exception as e:
+ logger.warning(f"Failed to read email translation cache: {e}")
+
+ candidates = []
+ seen = set()
+
+ def _add(url, model, headers):
+ key = (url or "", model or "")
+ if not url or not model or key in seen:
+ return
+ seen.add(key)
+ candidates.append((url, model, headers))
+
+ try:
+ _add(*resolve_endpoint("utility", owner=owner))
+ except Exception:
+ pass
+ try:
+ _add(*resolve_endpoint("default", owner=owner))
+ except Exception:
+ pass
+ for cand in resolve_utility_fallback_candidates(owner=owner) or []:
+ _add(*cand)
+ if not candidates:
+ return {"success": False, "error": "No LLM endpoint configured"}
+
+ content = await llm_call_async_with_fallback(
+ candidates,
+ messages=[
+ {
+ "role": "system",
+ "content": (
+ "You translate emails faithfully. Preserve meaning, names, dates, money, addresses, "
+ "bullet structure, and tone. Do not summarize or answer the email. "
+ "Output only the translation between <<<TRANSLATION>>> and <<<END>>>. "
+ "If AUTO mode is enabled and the email is already primarily in the target language, "
+ "output exactly <<<SAME_LANGUAGE>>>."
+ ),
+ },
+ {
+ "role": "user",
+ "content": (
+ f"AUTO mode: {'enabled' if auto else 'disabled'}\n"
+ f"Target language: {target_language}\n\n"
+ f"From: {sender}\nSubject: {subject}\n\n{body[:16000]}\n\n"
+ "Translate the email unless AUTO mode is enabled and it is already primarily in the target language.\n"
+ "Return only:\n<<<TRANSLATION>>>\ntranslated text\n<<<END>>>"
+ ),
+ },
+ ],
+ temperature=0.2,
+ max_tokens=8192,
+ timeout=180,
+ )
+ model = candidates[0][1] if candidates else ""
+ content = (content or "").strip()
+ content = _extract_reply(content)
+ if "<<<SAME_LANGUAGE>>>" in content:
+ try:
+ _c = _sql3.connect(SCHEDULED_DB)
+ _c.execute("""
+ INSERT OR REPLACE INTO email_translations
+ (body_hash, owner, target_language, uid, folder, subject, sender,
+ translation, same_language, model_used, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """, (
+ body_hash, owner, target_language, data.get("uid", ""), data.get("folder", ""),
+ subject, sender, "", 1, model, datetime.utcnow().isoformat(),
+ ))
+ _c.commit()
+ _c.close()
+ except Exception as e:
+ logger.warning(f"Failed to cache same-language email translation: {e}")
+ return {"success": True, "same_language": True, "language": target_language, "model_used": model}
+ marker = re.search(r"<<<TRANSLATION>>>\s*(.*?)\s*<<<END>>>", content, re.S | re.I)
+ if marker:
+ content = marker.group(1).strip()
+ else:
+ content = re.sub(r"^\s*<<<TRANSLATION>>>\s*", "", content, flags=re.I).strip()
+ content = re.sub(r"\s*<<<END>>>\s*$", "", content, flags=re.I).strip()
+ if not content:
+ return {"success": False, "error": "Empty response from model"}
+ try:
+ _c = _sql3.connect(SCHEDULED_DB)
+ _c.execute("""
+ INSERT OR REPLACE INTO email_translations
+ (body_hash, owner, target_language, uid, folder, subject, sender,
+ translation, same_language, model_used, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """, (
+ body_hash, owner, target_language, data.get("uid", ""), data.get("folder", ""),
+ subject, sender, content, 0, model, datetime.utcnow().isoformat(),
+ ))
+ _c.commit()
+ _c.close()
+ except Exception as e:
+ logger.warning(f"Failed to cache email translation: {e}")
+ return {"success": True, "translation": content, "language": target_language, "model_used": model}
+ except Exception as e:
+ logger.error(f"Failed to translate email: {e}")
+ return {"success": False, "error": "Mail operation failed"}
+
+ @router.post("/ai-reply")
+ async def ai_reply(data: dict, owner: str = Depends(require_owner)):
+ """Generate an AI-drafted reply to an email using the user's writing style."""
++ if data.get('stream'):
++ async def events():
++ queue = asyncio.Queue()
++ async def run():
++ result = await ai_reply({**data, 'stream': False, '_emit': queue.put}, owner)
++ await queue.put({'type': 'result', **result})
++ task = asyncio.create_task(run())
++ try:
++ while True:
++ item = await queue.get()
++ yield 'data: ' + json.dumps(item) + '\n\n'
++ if item.get('type') == 'result':
++ break
++ finally:
++ task.cancel()
++ await asyncio.gather(task, return_exceptions=True)
++ return StreamingResponse(events(), media_type='text/event-stream', headers={'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'})
+ try:
+ from src.endpoint_resolver import resolve_endpoint
+
+ to = data.get("to", "")
+ subject = data.get("subject", "")
+ original_body = data.get("original_body", "")
+ requested_model = str(data.get("model") or "").strip()
+ session_id = str(data.get("session_id") or "").strip()
+ message_id = (data.get("message_id") or "").strip()
+ source_uid = (data.get("uid") or "").strip()
+ source_folder = (data.get("folder") or "INBOX").strip()
+ account_id = (data.get("account_id") or "").strip() or None
+ fast_reply = bool(data.get("fast", False))
+ user_hint = (data.get("user_hint") or "").strip()
+ if account_id:
+ _assert_owns_account(account_id, owner)
+
+ if not original_body:
+ return {"success": False, "error": "No email body provided"}
+
+ # Skip cache lookup when the caller supplied a user_hint — the
+ # cached generic reply doesn't reflect the instructions and
+ # would silently override them.
- if message_id and not user_hint and not account_id:
++ if message_id and not user_hint and not account_id and not callable(data.get('_emit')):
+ try:
+ _c = _sql3.connect(SCHEDULED_DB)
+ owner_clause, owner_params = _email_cache_owner_clause(owner)
+ _row = _c.execute(
+ f"SELECT reply, model_used FROM email_ai_replies WHERE message_id = ? AND {owner_clause}",
+ (message_id, *owner_params),
+ ).fetchone()
+ _c.close()
+ if _row and _row[0]:
+ cached_reply = _apply_email_style_mechanics(_extract_reply(_row[0] or ""))
+ # Older failures could be cached as a one-word
+ # fragment (for example "and"). Never surface that
+ # as a finished draft; let the current model generate
+ # a fresh reply instead.
+ cached_reply_is_usable = (
+ len(cached_reply.split()) >= 4
+ or len(original_body.split()) <= 3
+ )
+ if cached_reply and cached_reply_is_usable:
+ return {
+ "success": True,
+ "reply": cached_reply,
+ "model_used": _row[1] or "cached",
+ "cached": True,
+ }
+ if cached_reply:
+ logger.warning(
+ "Ignoring unusable cached AI reply message_id=%s words=%s",
+ message_id,
+ len(cached_reply.split()),
+ )
+ except Exception as e:
+ logger.warning(f"AI reply cache lookup failed: {e}")
+
+ settings = _load_settings()
+ style = _get_email_writing_style_for_account(settings, account_id)
+ general_style = str(settings.get("document_writing_style") or "").strip()
+
+ # Try session's endpoint first if session_id provided
+ url = None
+ model = requested_model
+ headers = None
+ if session_id:
+ try:
+ # The chat-session ORM model is `Session`, not `ChatSession`
+ # — the old import threw ImportError, was swallowed by the
+ # except, and left url=None so EVERY reply silently fell back
+ # to the "default" endpoint (wrong model). Its auth lives in
+ # `headers` (JSON), and `endpoint_url` is already the full
+ # chat-completions URL the chat path uses verbatim — so use
+ # those directly rather than rebuilding via a nonexistent
+ # `api_key` field.
+ from core.database import SessionLocal as _SL, Session as _CS
+ _db = _SL()
+ sess = _db.query(_CS).filter(_CS.id == session_id, _CS.owner == owner).first()
+ if sess and sess.endpoint_url:
+ url = sess.endpoint_url
+ # Some sessions stored headers double-encoded (a JSON
+ # string inside the JSON column), so the ORM hands back
+ # a str, not a dict — and llm_call_async's h.update()
+ # then throws "dictionary update sequence element…".
+ # Unwrap until we have a dict (or give up → no headers).
+ _h = sess.headers
+ for _ in range(3):
+ if isinstance(_h, str):
+ try:
+ _h = json.loads(_h)
+ except Exception:
+ _h = None
+ break
+ else:
+ break
+ headers = _h if isinstance(_h, dict) and _h else None
+ if not requested_model:
+ model = sess.model
+ _db.close()
+ except Exception as e:
+ logger.warning(f"Failed to read session endpoint: {e}")
+
+ if not url:
+ # Match the rest of email AI: prefer the caller's Utility
+ # model, then fall back to their Default chat model. Using the
+ # global default here could hit a stale provider/key even when
+ # chat and summaries worked for the current user.
+ url, fallback_model, headers = resolve_endpoint("utility", owner=owner)
+ if not url:
+ url, fallback_model, headers = resolve_endpoint("default", owner=owner)
+ if not model:
+ model = fallback_model
+
+ if not url or not model:
+ return {"success": False, "error": "No LLM endpoint configured"}
+
+ # Resolve the model against what the endpoint actually serves. A
+ # stored session model can drift from the server's
+ # --served-model-name, giving a 404 "model does not exist". Match
+ # by exact id, then basename; fall back to the first served model.
+ try:
+ from src.llm_core import list_model_ids
- _avail = list_model_ids(url, headers=headers)
++ _avail = await asyncio.to_thread(list_model_ids, url, headers=headers)
+ if _avail and model not in _avail:
+ import os as _os
+ _base = _os.path.basename((model or "").rstrip("/"))
+ _match = next((a for a in _avail if _os.path.basename(a.rstrip("/")) == _base), None)
+ model = _match or _avail[0]
+ except Exception as _e:
+ logger.warning(f"AI reply model resolve failed: {_e}")
+
+ logger.info(f"AI reply using model={model} url={url}")
+
+ # Manual AI Reply should feel immediate. The heavier context mining
+ # can involve multiple IMAP folder searches and attachment parsing;
+ # reserve that for callers that explicitly opt out of fast mode.
+ # Owner-scoped so pre-retrieval never crosses tenants.
+ context_snippets, _terms = ([], [])
+ if not fast_reply:
- context_snippets, _terms = _pre_retrieve_context(original_body, to, owner=owner)
++ context_snippets, _terms = await asyncio.to_thread(_pre_retrieve_context, original_body, to, owner=owner)
+
+ # NEW: also pull the last few emails from the original sender +
+ # their attachments. The "to" field on this endpoint is the
+ # recipient of the *outgoing* reply — that is, the original
+ # sender we're answering. So `to` doubles as the address we want
+ # the thread context for.
+ referenced = ""
+ if not fast_reply:
+ try:
+ from_addr_for_ctx = email.utils.parseaddr(to or "")[1]
- referenced = _fetch_sender_thread_context(
++ referenced = await asyncio.to_thread(_fetch_sender_thread_context,
+ sender_addr=from_addr_for_ctx,
+ exclude_uid=source_uid,
+ exclude_folder=source_folder,
+ limit=3,
+ owner=owner,
+ )
+ except Exception as _e:
+ logger.warning(f"sender-thread-context failed: {_e}")
+
+ system_prompt = _EMAIL_REPLY_SYS_PROMPT_BASE
++ config = await asyncio.to_thread(_get_email_config, account_id, owner=owner)
++ mailbox = config.get('from_address') or config.get('imap_user') or ''
++ system_prompt += (
++ f'\n\nYou are writing FROM this mailbox: {mailbox}. '
++ 'The recipient is the person being replied to, not your identity. '
++ 'Quoted participants are third parties. Do not adopt their signatures or commitments. '
++ 'Return the final reply immediately inside <<<REPLY>>> and <<<END>>>; no analysis.'
++ )
+ if general_style:
+ system_prompt += f"\n\nGENERAL WRITING STYLE:\n{general_style}"
+ if style:
+ system_prompt += f"\n\nEMAIL CONVENTIONS:\n{style}"
+ if context_snippets:
+ system_prompt += "\n\nRELEVANT CONTEXT FROM PAST EMAILS AND CONTACTS:\n" + "\n\n---\n\n".join(context_snippets[:5])
+ if referenced:
+ system_prompt += (
+ "\n\nREFERENCED MATERIAL — the last few emails from this sender, "
+ "plus any text extracted from their attachments. Use this to "
+ "answer numbered questions or refer to documents they previously "
+ "sent. Do NOT cite this material verbatim unless the sender "
+ "directly asked about something in it.\n\n" + referenced[:18000]
+ )
+
+ user_msg = (
+ f"Recipient: {to}\nSubject: {subject}\n\n"
- f"Original email and any current draft:\n{original_body[:6000]}\n\n"
++ f"Received email and quoted conversation (not your draft):\n{original_body[:6000]}\n\n"
+ )
+ if user_hint:
+ user_msg += (
+ "User guidance for THIS reply. Treat this as intent/context to fold "
+ "into a normal polished email reply in the user's writing style. "
+ "Do not answer with only this guidance unless the user explicitly "
+ "asked for a one-word reply:\n"
+ f"{user_hint[:2000]}\n\n"
+ )
+ user_msg += "Draft a reply. Return only the reply body text."
+
+ # Build a candidate chain so a stale session-stored API key
+ # (the most common cause of "authentication failed" here)
+ # doesn't kill AI Reply outright — fall through to the
+ # user's Utility / Default endpoints and active Utility fallback
+ # chain. Dedupe by url+model so we don't retry the same endpoint.
+ from src.llm_core import llm_call_async_with_fallback
+ from src.endpoint_resolver import (
+ resolve_utility_fallback_candidates,
+ )
+ _seen = set()
+ _candidates = []
+ def _add(_url, _model, _headers):
+ key = (_url or "", _model or "")
+ if not _url or not _model or key in _seen:
+ return
+ _seen.add(key)
+ _candidates.append((_url, _model, _headers))
+ # Session endpoint first (may be the broken one).
+ _add(url, model, headers)
+ # Primary utility endpoint — this is what the user has actually
+ # configured as their background-task model, with fresh creds.
+ try:
+ _u_url, _u_model, _u_headers = resolve_endpoint("utility", owner=owner)
+ _add(_u_url, _u_model, _u_headers)
+ except Exception:
+ pass
+ # Primary default chat endpoint — last working chat config.
+ try:
+ _d_url, _d_model, _d_headers = resolve_endpoint("default", owner=owner)
+ _add(_d_url, _d_model, _d_headers)
+ except Exception:
+ pass
+ # Active Utility fallbacks last.
+ for cand in resolve_utility_fallback_candidates(owner=owner) or []:
+ _add(*cand)
+ _messages = [
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": user_msg},
+ ]
+ try:
- reply_raw = await llm_call_async_with_fallback(
- _candidates,
- messages=_messages,
- temperature=0.7,
- max_tokens=1536 if fast_reply else 6144,
- timeout=120 if fast_reply else 180,
- )
++ if callable(data.get('_emit')):
++ from src.email_reply_stream import stream_reply
++ reply_raw, model = await stream_reply(_candidates, _messages, data['_emit'], max_tokens=1536)
++ else:
++ reply_raw = await llm_call_async_with_fallback(
++ _candidates,
++ messages=_messages,
++ temperature=0.7,
++ max_tokens=1536 if fast_reply else 6144,
++ timeout=120 if fast_reply else 180,
++ thinking_mode='off',
++ )
+ except Exception as e:
+ detail = getattr(e, "detail", None) or str(e)
+ _attempted = ", ".join(f"{m}@{u.split('/')[2] if '/' in u else u}" for u, m, _ in _candidates) or "no candidates"
- return {"success": False, "error": f"All endpoints failed ({_attempted}): {detail}. Check your API keys in Settings → Services."}
++ return {"success": False, "error": f"AI reply failed ({_attempted}): {detail}"}
+
- reply = _apply_email_style_mechanics(_extract_reply(reply_raw or ""))
++ from src.email_reply_stream import reply_body
++ reply = _apply_email_style_mechanics(reply_body(reply_raw or "", complete=True))
+ # Small/local models sometimes satisfy the format request with a
+ # one-word acknowledgement ("Thanks.") even though the email
+ # needs an actual draft. Treat that as an unusable result and
+ # give the retry prompt a chance to produce a complete reply.
+ reply_is_too_short = bool(reply) and len(reply.split()) < 4
+ if not reply or reply_is_too_short:
+ allow_short_reply = reply_is_too_short and len(original_body.split()) <= 3
+ logger.warning(
+ "AI reply returned %s usable text on first pass model=%s raw_len=%s; retrying candidates",
+ "too-short" if reply_is_too_short else "empty",
+ model,
+ len(reply_raw or ""),
+ )
+ retry_system = (
+ system_prompt
+ + "\n\nRETRY BECAUSE THE PREVIOUS OUTPUT WAS NOT USABLE: You MUST return a complete email reply body of at least 2 sentences (unless the original email itself is only a greeting). "
+ "Use the saved writing style and write a short, honest reply using only the facts in the original email and user instructions. "
+ "Still use the exact <<<REPLY>>> and <<<END>>> markers."
+ )
+ retry_user = user_msg + "\n\nReturn a complete usable reply now. Do not return a one-word acknowledgement or an empty marker block."
+ retry_messages = [
+ {"role": "system", "content": retry_system},
+ {"role": "user", "content": retry_user},
+ ]
+ for cand_url, cand_model, cand_headers in _candidates:
+ try:
+ raw_retry = await llm_call_async(
+ cand_url,
+ cand_model,
+ retry_messages,
+ headers=cand_headers,
+ temperature=0.3,
+ max_tokens=2048 if fast_reply else 4096,
+ timeout=90 if fast_reply else 120,
+ max_retries=1,
++ thinking_mode='off',
+ )
- retry_reply = _apply_email_style_mechanics(_extract_reply(raw_retry or ""))
++ retry_reply = _apply_email_style_mechanics(reply_body(raw_retry or "", complete=True))
+ if retry_reply and (len(retry_reply.split()) >= 4 or allow_short_reply):
+ reply = retry_reply
+ model = cand_model
+ break
+ logger.warning(
+ "AI reply retry still empty model=%s raw_len=%s",
+ cand_model,
+ len(raw_retry or ""),
+ )
+ except Exception as retry_exc:
+ logger.warning("AI reply retry failed model=%s: %s", cand_model, retry_exc)
+ if reply_is_too_short and not allow_short_reply and len(reply.split()) < 4:
+ reply = ""
+ if not reply:
+ _attempted = ", ".join(f"{m}@{u.split('/')[2] if '/' in u else u}" for u, m, _ in _candidates) or "no candidates"
+ return {"success": False, "error": f"AI reply returned blank text after retrying: {_attempted}"}
+
+ # Cache so next click is instant
+ if message_id:
+ try:
+ _c = _sql3.connect(SCHEDULED_DB)
+ _c.execute("""
+ INSERT OR REPLACE INTO email_ai_replies
+ (message_id, owner, uid, folder, reply, model_used, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ """, (message_id, owner, source_uid, source_folder, reply, model, datetime.utcnow().isoformat()))
+ _c.commit()
+ _c.close()
+ except Exception as e:
+ logger.warning(f"Failed to cache ai_reply: {e}")
+
+ return {"success": True, "reply": reply, "model_used": model}
+ except Exception as e:
+ # Keep the browser error actionable. Do not return a raw traceback
+ # or unbounded provider response, but do preserve the exception
+ # class/message so configuration and response-shape failures can
+ # be distinguished from an empty model reply.
+ detail = str(e or "").strip()
+ detail = re.sub(r"(?i)(api[_ -]?key|authorization|token)\s*[=:]\s*[^\s,;]+", r"\1=[redacted]", detail)
+ detail = detail[:320] if detail else type(e).__name__
+ logger.exception("Failed to generate AI reply: %s", detail)
+ return {"success": False, "error": f"AI reply failed ({type(e).__name__}): {detail}"}
+
+ @router.get("/style")
+ async def get_writing_style(
+ account_id: str | None = Query(None),
+ owner: str = Depends(require_user),
+ ):
+ """Get the current writing style prompt."""
+ if account_id:
+ _assert_owns_account(account_id, owner)
+ settings = _load_settings()
+ return {"style": _get_email_writing_style_for_account(settings, account_id)}
+
+ @router.put("/style")
+ async def update_writing_style(
+ data: dict,
+ account_id: str | None = Query(None),
+ owner: str = Depends(require_user),
+ ):
+ """Manually update the writing style prompt."""
+ if account_id:
+ _assert_owns_account(account_id, owner)
+ settings = _load_settings()
+ _set_email_writing_style_for_account(settings, data.get("style", ""), account_id)
+ _save_settings(settings)
+ return {"success": True}
+
+ @router.get("/config")
+ async def get_email_config(
+ account_id: str | None = Query(None),
+ owner: str = Depends(require_user),
+ ):
+ """Get email configuration (passwords masked)."""
+ if account_id is not None and not isinstance(account_id, str):
+ account_id = None
+ if account_id:
+ _assert_owns_account(account_id, owner)
+ cfg = _get_email_config(account_id, owner=owner)
+ cfg["smtp_password"] = "***" if cfg["smtp_password"] else ""
+ cfg["imap_password"] = "***" if cfg["imap_password"] else ""
+ # `_get_email_config` includes encrypted OAuth fields for the server's
+ # IMAP/SMTP helpers. They are implementation secrets, not client
+ # configuration, so keep them out of this browser-facing response just
+ # as the account-list endpoint does.
+ cfg.pop("oauth_access_token", None)
+ cfg.pop("oauth_refresh_token", None)
+ cfg.pop("oauth_token_expiry", None)
+ # Include preferences from settings.json
+ settings = _load_settings()
+ auto_reply_settings = _get_auto_reply_settings_for_account(settings, account_id)
+ cfg["email_auto_summarize"] = bool(settings.get("email_auto_summarize", False))
+ cfg["email_auto_reply"] = bool(auto_reply_settings.get("email_auto_reply", False))
+ cfg["email_auto_tag"] = bool(settings.get("email_auto_tag", False))
+ cfg["email_auto_spam"] = bool(settings.get("email_auto_spam", False))
+ cfg["email_auto_calendar"] = bool(settings.get("email_auto_calendar", False))
+ cfg["email_auto_reply_start"] = auto_reply_settings.get("email_auto_reply_start", "")
+ cfg["email_auto_reply_end"] = auto_reply_settings.get("email_auto_reply_end", "")
+ cfg["email_auto_reply_subject"] = auto_reply_settings.get("email_auto_reply_subject", "(Away) {subject}")
+ cfg["email_auto_reply_message"] = auto_reply_settings.get("email_auto_reply_message", "")
+ cfg["email_auto_reply_cooldown"] = auto_reply_settings.get("email_auto_reply_cooldown", "period")
+ cfg["email_auto_reply_scope"] = auto_reply_settings.get("email_auto_reply_scope", "account" if account_id else "all")
+ cfg["email_auto_reply_account_id"] = auto_reply_settings.get("email_auto_reply_account_id", account_id or "")
+ cfg["email_auto_reply_exclude_automated"] = bool(auto_reply_settings.get("email_auto_reply_exclude_automated", True))
+ cfg["email_auto_reply_pause_notifications"] = bool(auto_reply_settings.get("email_auto_reply_pause_notifications", False))
+ cfg["email_view_inline_images"] = _get_email_view_inline_images(settings, account_id)
+ # Email translation is owned by the background task now; opening an email
+ # should not trigger reader-side auto-translation from Settings.
+ cfg["email_auto_translate"] = False
+ cfg["email_translate_language"] = settings.get("email_translate_language", "English")
+ return cfg
+
+ @router.put("/config")
+ async def update_email_config(
+ data: dict,
+ account_id: str | None = Query(None),
+ owner: str = Depends(require_owner),
+ ):
+ """Update email configuration.
+
+ Automation flags (email_auto_*) still live in settings.json. Credentials
+ are written to the default EmailAccount row. Passwords are only
+ overwritten when a non-empty value is provided, so saving the form
+ without retyping the password no longer wipes it.
+ """
+ if account_id:
+ _assert_owns_account(account_id, owner)
+
+ # Non-reply automation flags stay global. Away/auto-reply settings are
+ # account-scoped when an account_id is supplied by the Email Settings UI.
+ settings = _load_settings()
+ bool_keys = [
+ "email_auto_summarize", "email_auto_tag", "email_auto_spam", "email_auto_calendar",
+ ]
+ for key in bool_keys:
+ if key in data:
+ settings[key] = bool(data[key])
+ if "email_view_inline_images" in data:
+ _set_email_view_inline_images(settings, bool(data["email_view_inline_images"]), account_id)
+ _set_auto_reply_settings_for_account(settings, data, account_id)
+ _save_settings(settings)
+
+ # Credentials go into the default account row
+ from core.database import SessionLocal, EmailAccount
+ import uuid as _uuid
+ db = SessionLocal()
+ try:
+ _lock_email_account_owner_mutation(db, owner)
+ q = db.query(EmailAccount).filter(EmailAccount.is_default == True) # noqa: E712
+ q = _email_account_owner_scope(q, owner)
+ row = q.first()
+ if row is None:
+ row = EmailAccount(id=_uuid.uuid4().hex, owner=owner, name="Default", is_default=True, enabled=True)
+ db.add(row)
+ field_map = {
+ "smtp_host": "smtp_host", "smtp_port": "smtp_port", "smtp_user": "smtp_user",
+ "smtp_security": "smtp_security", "imap_host": "imap_host", "imap_port": "imap_port", "imap_user": "imap_user",
+ "imap_starttls": "imap_starttls", "email_from": "from_address",
+ }
+ for in_key, col_name in field_map.items():
+ if in_key in data:
+ val = data[in_key]
+ if col_name.endswith("_port") and val in (None, ""):
+ continue
+ if col_name.endswith("_port"):
+ val = int(val)
+ setattr(row, col_name, val)
+ # Passwords: only update when a non-empty value is given.
+ # Stored encrypted; see src/secret_storage.py.
+ from src.secret_storage import encrypt as _enc
+ if data.get("imap_password"):
+ row.imap_password = _enc(data["imap_password"])
+ if data.get("smtp_password"):
+ row.smtp_password = _enc(data["smtp_password"])
+ clear_q = db.query(EmailAccount).filter(EmailAccount.id != row.id)
+ clear_q = _email_account_owner_scope(clear_q, owner)
+ clear_q.update({EmailAccount.is_default: False})
+ db.commit()
+ finally:
+ db.close()
+ return {"success": True}
+
+ # ═══════════════ Urgency state ═══════════════
+ # Read-only state file written by `action_check_email_urgency`. The UI
+ # uses this to color the unread email dot by urgency tier (3=red,
+ # 2=orange, otherwise default blue) and per-row dots in the inbox list.
+
+ @router.get("/urgency-state")
+ async def get_email_urgency_state(owner: str = Depends(require_user)):
+ from pathlib import Path as _P
+ import json as _json
+ _slug = "".join(c if (c.isalnum() or c in "-_.@") else "_" for c in (owner or "default"))
+ path = _P(DATA_DIR) / f"email_urgency_state_{_slug}.json"
+ if not path.exists():
+ return {"total_unread": 0, "total_urgent": 0, "max_score": 0, "per_uid": {}}
+ try:
+ data = _json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ return {"total_unread": 0, "total_urgent": 0, "max_score": 0, "per_uid": {}}
+ # Drop `notified_uids` from the payload — it's an internal scheduler
+ # debounce, not UI-relevant.
+ data.pop("notified_uids", None)
+ return data
+
+ # ═══════════════ Email Accounts CRUD ═══════════════
+ # Multi-account support. Each row is an independent IMAP/SMTP config.
+ # Exactly one row has is_default=True; that account is used when callers
+ # don't specify an account_id.
+
+ @router.get("/accounts")
+ async def list_email_accounts(owner: str = Depends(require_user)):
+ """List all email accounts with credentials masked."""
+ from core.database import SessionLocal, EmailAccount
+ from sqlalchemy import and_, or_
+ db = SessionLocal()
+ try:
+ out = []
+ # SECURITY: scope to this user's accounts. Previously returned
+ # every row in the EmailAccount table, leaking IMAP/SMTP hosts +
+ # usernames across users. Also show legacy unowned rows that match
+ # the logged-in mailbox; _get_email_config already accepts those,
+ # so Settings should not hide the active account.
+ q = db.query(EmailAccount)
+ if owner:
+ unowned = or_(EmailAccount.owner == None, EmailAccount.owner == "") # noqa: E711
+ same_mailbox = or_(EmailAccount.imap_user == owner, EmailAccount.from_address == owner)
+ q = q.filter(or_(EmailAccount.owner == owner, and_(unowned, same_mailbox)))
+ for r in q.order_by(
+ EmailAccount.is_default.desc(), EmailAccount.created_at.asc()
+ ).all():
+ out.append({
+ "id": r.id,
+ "name": r.name,
+ "is_default": bool(r.is_default),
+ "enabled": bool(r.enabled),
+ "imap_host": r.imap_host or "",
+ "imap_port": int(r.imap_port or 993),
+ "imap_user": r.imap_user or "",
+ "imap_starttls": bool(r.imap_starttls),
+ "smtp_host": r.smtp_host or "",
+ "smtp_port": int(r.smtp_port or 465),
+ "smtp_security": _smtp_security_mode({"smtp_security": getattr(r, "smtp_security", ""), "smtp_port": r.smtp_port}),
+ "smtp_user": r.smtp_user or "",
+ "from_address": r.from_address or "",
+ "has_imap_password": bool(r.imap_password),
+ "has_smtp_password": bool(r.smtp_password),
+ "oauth_provider": r.oauth_provider or "",
+ "display_name": r.display_name or "",
+ })
+ return {"accounts": out}
+ finally:
+ db.close()
+
+ @router.post("/accounts")
+ async def create_email_account(data: dict, owner: str = Depends(require_owner)):
+ """Create a new email account."""
+ from core.database import SessionLocal, EmailAccount
+ from src.secret_storage import encrypt as _enc
+ import uuid as _uuid
+ name = (data.get("name") or "").strip()
+ if not name:
+ return {"ok": False, "error": "name required"}
+ imap_port, port_err = _coerce_port(data.get("imap_port"), 993)
+ if port_err:
+ return {"ok": False, "error": port_err}
+ smtp_port, port_err = _coerce_port(data.get("smtp_port"), 465)
+ if port_err:
+ return {"ok": False, "error": port_err}
+ db = SessionLocal()
+ try:
+ _lock_email_account_owner_mutation(db, owner)
+ row = EmailAccount(
+ id=_uuid.uuid4().hex,
+ name=name,
+ is_default=bool(data.get("is_default", False)),
+ enabled=bool(data.get("enabled", True)),
+ imap_host=(data.get("imap_host") or "").strip(),
+ imap_port=imap_port,
+ imap_user=(data.get("imap_user") or "").strip(),
+ imap_password=_enc(data.get("imap_password") or ""),
+ imap_starttls=bool(data.get("imap_starttls", True)),
+ smtp_host=(data.get("smtp_host") or "").strip(),
+ smtp_port=smtp_port,
+ smtp_security=_smtp_security_mode({"smtp_security": data.get("smtp_security"), "smtp_port": smtp_port}),
+ smtp_user=(data.get("smtp_user") or "").strip(),
+ smtp_password=_enc(data.get("smtp_password") or ""),
+ from_address=(data.get("from_address") or "").strip(),
+ display_name=(data.get("display_name") or "").strip(),
+ # SECURITY: stamp the creator so all subsequent reads / mutations
+ # can filter by user. Without this every new account leaks to
+ # every other user.
+ owner=owner,
+ )
+ # If there are no accounts yet OR caller asked for default, enforce
+ # the one-default invariant — but scope it to THIS user's accounts,
+ # otherwise creating a default would clear every other user's
+ # default flag too.
+ scope_q = _email_account_owner_scope(db.query(EmailAccount), owner)
+ existing_count = scope_q.count()
+ if row.is_default or existing_count == 0:
+ scope_q.update({EmailAccount.is_default: False})
+ row.is_default = True
+ db.add(row)
+ db.commit()
+ return {"ok": True, "id": row.id}
+ finally:
+ db.close()
+
+ @router.put("/accounts/{account_id}")
+ async def update_email_account(account_id: str, data: dict, owner: str = Depends(require_user)):
+ """Update an email account. Passwords only overwrite if non-empty."""
+ # Path param account_id — dep validated via Query, re-check the path-param value.
+ _assert_owns_account(account_id, owner)
+ from core.database import SessionLocal, EmailAccount
+ db = SessionLocal()
+ try:
+ row = db.get(EmailAccount, account_id)
+ if not row:
+ return {"ok": False, "error": "Account not found"}
+ # Simple fields
+ for key in ("name", "imap_host", "imap_user", "smtp_host", "smtp_user", "from_address", "display_name"):
+ if key in data:
+ setattr(row, key, (data[key] or "").strip())
+ for key in ("imap_port", "smtp_port"):
+ if data.get(key) not in (None, ""):
+ port, port_err = _coerce_port(data.get(key), None)
+ if port_err:
+ return {"ok": False, "error": port_err}
+ setattr(row, key, port)
+ if "smtp_security" in data:
+ row.smtp_security = _smtp_security_mode({"smtp_security": data.get("smtp_security"), "smtp_port": data.get("smtp_port") or row.smtp_port})
+ for key in ("imap_starttls", "enabled"):
+ if key in data:
+ setattr(row, key, bool(data[key]))
+ # Passwords — only overwrite when a non-empty value is
+ # provided. Stored encrypted; see src/secret_storage.py.
+ from src.secret_storage import encrypt as _enc
+ if data.get("imap_password"):
+ row.imap_password = _enc(data["imap_password"])
+ if data.get("smtp_password"):
+ row.smtp_password = _enc(data["smtp_password"])
+ db.commit()
+ return {"ok": True, "id": row.id}
+ finally:
+ db.close()
+
+ @router.delete("/accounts/{account_id}")
+ async def delete_email_account(account_id: str, owner: str = Depends(require_user)):
+ initial_scope = _discover_email_account_mutation_scope(account_id, owner)
+ from core.database import SessionLocal, EmailAccount
+ db = SessionLocal()
+ try:
+ row = _lock_and_reload_email_account(
+ db, account_id, owner, initial_scope
+ )
+ row_scope = row.owner or ""
+ was_default = bool(row.is_default)
+ db.delete(row)
+ # Flush the removal before staging a replacement default. The
+ # partial unique index is checked statement-by-statement, and the
+ # ORM is otherwise free to UPDATE the promoted row before DELETE.
+ db.flush()
+ # If the deleted row was default, promote the next-oldest enabled
+ # row owned by THIS user. Without the owner filter we'd promote
+ # another user's account and the deleter would silently inherit
+ # it as their default.
+ if was_default:
+ promote_q = db.query(EmailAccount).filter(
+ EmailAccount.id != account_id,
+ EmailAccount.enabled == True, # noqa: E712
+ )
+ promote_q = _email_account_owner_scope(promote_q, row_scope)
+ promote = promote_q.order_by(
+ EmailAccount.created_at.asc(), EmailAccount.id.asc()
+ ).first()
+ if promote:
+ promote.is_default = True
+ # Deletion and any replacement promotion are one durable state
+ # transition, so another worker can never observe or race the old
+ # split-commit gap.
+ db.commit()
+ return {"ok": True}
+ finally:
+ db.close()
+
+ @router.post("/accounts/test")
+ async def test_account_config(req: Request, owner: str = Depends(require_user)):
+ """Try to actually connect to the provided IMAP (and optionally SMTP)
+ server with the given credentials. Lets the user verify a config
+ BEFORE saving it. Returns per-protocol status so the UI can show
+ which half failed.
+
+ If `account_id` is provided (instead of inline credentials), load
+ the saved row's stored creds and test those — used by the
+ clickable test-dot in the integrations list, where the form has
+ no live values."""
+ try:
+ body = await req.json()
+ except Exception:
+ return {"ok": False, "imap": {"ok": False, "error": "invalid request body"}}
+
+ # Saved-account shortcut — hydrate missing credentials from the DB row,
+ # while keeping any edited form fields from the request. This lets the UI
+ # test unsaved host/port changes without forcing the user to retype the
+ # stored password.
+ # `imap_password` / `smtp_password` are Fernet-encrypted at rest
+ # (see _migrate_encrypt_email_passwords); decrypt before use so
+ # the test actually sends the real password to the server.
+ acc_id = body.get("account_id")
+ if acc_id:
+ _assert_owns_account(acc_id, owner)
+ from core.database import SessionLocal, EmailAccount
+ from src.secret_storage import decrypt as _decrypt
+ db = SessionLocal()
+ try:
+ row = db.get(EmailAccount, acc_id)
+ if not row:
+ return {"ok": False, "imap": {"ok": False, "error": "Account not found"}}
+ saved_body = {
+ "imap_host": row.imap_host or "",
+ "imap_port": row.imap_port or 993,
+ "imap_user": row.imap_user or "",
+ "imap_password": _decrypt(row.imap_password or ""),
+ "imap_starttls": bool(row.imap_starttls),
+ "smtp_host": row.smtp_host or "",
+ "smtp_port": row.smtp_port or 465,
+ "smtp_security": _smtp_security_mode({"smtp_security": getattr(row, "smtp_security", ""), "smtp_port": row.smtp_port}),
+ "smtp_user": row.smtp_user or "",
+ "smtp_password": _decrypt(row.smtp_password or ""),
+ "oauth_provider": row.oauth_provider or "",
+ "oauth_access_token": row.oauth_access_token or "",
+ "oauth_refresh_token": row.oauth_refresh_token or "",
+ "oauth_token_expiry": row.oauth_token_expiry or "",
+ "account_id": acc_id,
+ }
+ for key, value in body.items():
+ if key == "account_id" or key in _SERVER_OWNED_OAUTH_FIELDS:
+ continue
+ if value not in (None, ""):
+ saved_body[key] = value
+ body = saved_body
+ finally:
+ db.close()
+ else:
+ # OAuth state belongs to a saved, owner-checked account. Do not let
+ # inline test payloads select the OAuth branch or supply token data.
+ body = {key: value for key, value in body.items() if key not in _SERVER_OWNED_OAUTH_FIELDS}
+
+ imap_result = {"ok": False}
+ smtp_result = None
+
+ imap_host = (body.get("imap_host") or "").strip()
+ imap_port, imap_port_err = _coerce_port(body.get("imap_port"), 993)
+ imap_user = (body.get("imap_user") or "").strip()
+ imap_pass = body.get("imap_password") or ""
+ imap_starttls = bool(body.get("imap_starttls"))
+ oauth_provider = body.get("oauth_provider") or ""
+
+ google_token = None
+ google_token_loaded = False
+ google_ssl_context = (
+ ssl.create_default_context()
+ if oauth_provider == "google"
+ else None
+ )
+
+ def _google_token():
+ nonlocal google_token, google_token_loaded
+ if not google_token_loaded:
+ google_token = _get_valid_google_token(body.get("account_id"), body)
+ google_token_loaded = True
+ if not google_token:
+ raise RuntimeError("Google OAuth token unavailable — reconnect the account")
+ return google_token
+
+ if imap_port_err:
+ imap_result = {"ok": False, "error": imap_port_err}
+ elif not (imap_host and imap_user and (imap_pass or oauth_provider == "google")):
+ imap_result = {"ok": False, "error": "Need IMAP host, username, and password"}
+ elif oauth_provider == "google" and _normalized_mail_host(imap_host) != _GOOGLE_OAUTH_IMAP_HOST:
+ imap_result = {"ok": False, "error": "Google OAuth IMAP requires imap.gmail.com"}
+ elif oauth_provider == "google" and not _google_oauth_imap_transport_allowed(imap_port, imap_starttls):
+ imap_result = {"ok": False, "error": "Google OAuth IMAP requires TLS on port 993 or STARTTLS on port 143"}
+ else:
+ # Connection mode resolution:
+ # STARTTLS on → plain IMAP4 + .starttls() (upgrade)
+ # STARTTLS off + port 993 → IMAP4_SSL (implicit SSL, "IMAPS")
+ # STARTTLS off + any other port → plain IMAP4 (no encryption)
+ # Without the last branch, local servers exposed on a non-993
+ # port (Dovecot on 31143, etc.) would always fail the SSL
+ # handshake because they're not actually wrapped in TLS.
+ try:
+ imap_kwargs = {
+ "starttls": imap_starttls,
+ "timeout": _IMAP_TIMEOUT_SECONDS,
+ }
+ if google_ssl_context:
+ imap_kwargs["ssl_context"] = google_ssl_context
+ conn = _open_imap_connection(
+ imap_host,
+ imap_port,
+ **imap_kwargs,
+ )
+ try:
+ if oauth_provider == "google":
+ token = _google_token()
+ conn.authenticate("XOAUTH2", lambda x: _xoauth2_bytes(imap_user, token))
+ else:
+ conn.login(imap_user, imap_pass)
+ imap_result = {"ok": True}
+ finally:
+ try: conn.logout()
+ except Exception: pass
+ except Exception as e:
+ imap_result = {"ok": False, "error": _friendly_email_auth_error("IMAP", imap_host, e)}
+
+ smtp_host = (body.get("smtp_host") or "").strip()
+ smtp_port, smtp_port_err = _coerce_port(body.get("smtp_port"), 465)
+ if smtp_host and smtp_port_err:
+ smtp_result = {"ok": False, "error": smtp_port_err}
+ elif oauth_provider == "google" and smtp_host and _normalized_mail_host(smtp_host) != _GOOGLE_OAUTH_SMTP_HOST:
+ smtp_result = {"ok": False, "error": "Google OAuth SMTP requires smtp.gmail.com"}
+ elif (
+ oauth_provider == "google"
+ and smtp_host
+ and not _google_oauth_smtp_transport_allowed(
+ smtp_port,
+ _smtp_security_mode({"smtp_security": body.get("smtp_security"), "smtp_port": smtp_port}),
+ )
+ ):
+ smtp_result = {"ok": False, "error": "Google OAuth SMTP requires TLS on port 465 or STARTTLS on port 587"}
+ elif smtp_host:
+ smtp_security = _smtp_security_mode({"smtp_security": body.get("smtp_security"), "smtp_port": smtp_port})
+ smtp_user = (body.get("smtp_user") or imap_user).strip()
+ smtp_pass = body.get("smtp_password") or imap_pass
+ smtp = None
+ try:
+ if smtp_security == "ssl":
+ smtp_kwargs = (
+ {"context": google_ssl_context}
+ if google_ssl_context
+ else {}
+ )
+ smtp = smtplib.SMTP_SSL(
+ smtp_host,
+ smtp_port,
+ timeout=10,
+ **smtp_kwargs,
+ )
+ else:
+ smtp = smtplib.SMTP(smtp_host, smtp_port, timeout=10)
+ if smtp_security == "starttls":
+ try:
+ if google_ssl_context:
+ smtp.starttls(context=google_ssl_context)
+ else:
+ smtp.starttls()
+ except Exception:
+ # STARTTLS failed before the auth cleanup block.
+ # Close the still-open plaintext socket explicitly.
+ try:
+ smtp.close()
+ except Exception:
+ pass
+ smtp = None
+ raise
+ if oauth_provider == "google":
+ token = _google_token()
+ smtp.ehlo()
+ smtp.auth("XOAUTH2", lambda challenge=None: _xoauth2_raw(smtp_user, token), initial_response_ok=True)
+ else:
+ smtp.login(smtp_user, smtp_pass)
+ smtp_result = {"ok": True}
+ except Exception as e:
+ smtp_result = {"ok": False, "error": _friendly_email_auth_error("SMTP", smtp_host, e)}
+ finally:
+ if smtp is not None:
+ try:
+ smtp.quit()
+ except Exception:
+ try:
+ smtp.close()
+ except Exception:
+ pass
+
+ return {
+ "ok": imap_result["ok"] and (smtp_result is None or smtp_result["ok"]),
+ "imap": imap_result,
+ "smtp": smtp_result,
+ }
+
+ @router.post("/accounts/{account_id}/set-default")
+ async def set_default_account(account_id: str, owner: str = Depends(require_user)):
+ initial_scope = _discover_email_account_mutation_scope(account_id, owner)
+ from core.database import SessionLocal, EmailAccount
+ db = SessionLocal()
+ try:
+ row = _lock_and_reload_email_account(
+ db, account_id, owner, initial_scope
+ )
+ # Scope the sweep to the target row's normalized owner partition;
+ # this also handles visible legacy NULL/empty-owner accounts.
+ clear_q = _email_account_owner_scope(
+ db.query(EmailAccount), row.owner or ""
+ )
+ clear_q.update({EmailAccount.is_default: False})
+ row.is_default = True
+ db.commit()
+ return {"ok": True}
+ finally:
+ db.close()
+
+ # ── Google OAuth2 routes ──
+
+ @router.get("/oauth/google/authorize")
+ async def google_oauth_authorize(account_id: str = Query(...), request: Request = None, owner: str = Depends(require_user)):
+ import urllib.parse
+ _assert_owns_account(account_id, owner)
+ client_id = os.environ.get("GOOGLE_OAUTH_CLIENT_ID", "")
+ if not client_id:
+ raise HTTPException(400, "GOOGLE_OAUTH_CLIENT_ID not set — add it to .env")
+ redirect_uri = (
+ os.environ.get("GOOGLE_OAUTH_REDIRECT_URI")
+ or f"{request.url.scheme}://{request.headers.get('host', 'localhost:7000')}/api/email/oauth/google/callback"
+ )
+ state = make_oauth_state(account_id, owner)
+ params = urllib.parse.urlencode({
+ "client_id": client_id,
+ "redirect_uri": redirect_uri,
+ "response_type": "code",
+ "scope": "https://mail.google.com/ email",
+ "access_type": "offline",
+ "prompt": "consent",
+ "state": state,
+ })
+ from fastapi.responses import RedirectResponse as _RR
+ return _RR(f"https://accounts.google.com/o/oauth2/v2/auth?{params}")
+
+ @router.get("/oauth/google/callback")
+ async def google_oauth_callback(
+ code: str = Query(None),
+ state: str = Query(None),
+ error: str = Query(None),
+ request: Request = None,
+ ):
+ import urllib.parse
+ from fastapi.responses import RedirectResponse as _RR
+ if error:
+ return _RR("/?section=integrations&email_oauth_error=google_error")
+ if not code or not state:
+ return _RR("/?section=integrations&email_oauth_error=missing_code")
+ state_data = verify_oauth_state(state)
+ if not state_data:
+ return _RR("/?section=integrations&email_oauth_error=invalid_state")
+ account_id = state_data.get("a", "")
+ owner = state_data.get("o", "")
+ client_id = os.environ.get("GOOGLE_OAUTH_CLIENT_ID", "")
+ client_secret = os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET", "")
+ redirect_uri = (
+ os.environ.get("GOOGLE_OAUTH_REDIRECT_URI")
+ or f"{request.url.scheme}://{request.headers.get('host', 'localhost:7000')}/api/email/oauth/google/callback"
+ )
+ import httpx as _httpx
+ try:
+ resp = _httpx.post("https://oauth2.googleapis.com/token", data={
+ "code": code,
+ "client_id": client_id,
+ "client_secret": client_secret,
+ "redirect_uri": redirect_uri,
+ "grant_type": "authorization_code",
+ }, timeout=10)
+ resp.raise_for_status()
+ data = resp.json()
+ except Exception:
+ logger.warning("Google token exchange failed")
+ return _RR("/?section=integrations&email_oauth_error=token_exchange_failed")
+ access_token = data.get("access_token", "")
+ refresh_token = data.get("refresh_token", "")
+ if not access_token or not refresh_token:
+ logger.warning("Google token exchange omitted required offline credentials")
+ return _RR("/?section=integrations&email_oauth_error=token_exchange_failed")
+ expiry = str(int(time.time()) + data.get("expires_in", 3600))
+ # Fetch the email address from userinfo so we can auto-fill imap_user.
+ email_addr = ""
+ display_name = ""
+ try:
+ ui = _httpx.get("https://www.googleapis.com/oauth2/v1/userinfo",
+ headers={"Authorization": f"Bearer {access_token}"}, timeout=10)
+ if ui.is_success:
+ ui_data = ui.json()
+ email_addr = ui_data.get("email", "")
+ display_name = ui_data.get("name", "")
+ except Exception:
+ pass
+ from core.database import SessionLocal, EmailAccount
+ from src.secret_storage import encrypt as _enc
+ db = SessionLocal()
+ try:
+ row = db.query(EmailAccount).filter(EmailAccount.id == account_id).first()
+ if not row:
+ return _RR("/?section=integrations&email_oauth_error=account_not_found")
+ # SECURITY: verify the account belongs to the initiating user.
+ if owner and row.owner and row.owner != owner:
+ logger.warning("OAuth callback owner mismatch — rejecting token write")
+ return _RR("/?section=integrations&email_oauth_error=ownership_error")
+
+ # A reconnect must prove that the token belongs to the mailbox
+ # already configured on this row. Otherwise authenticating a
+ # different Google account leaves the saved IMAP/SMTP usernames
+ # paired with credentials for another identity.
+ verified_email = (
+ email_addr.strip().casefold()
+ if isinstance(email_addr, str)
+ else ""
+ )
+ configured_logins = {
+ value.strip().casefold()
+ for value in (row.imap_user or "", row.smtp_user or "")
+ if value.strip()
+ }
+ if not verified_email or any(
+ login != verified_email for login in configured_logins
+ ):
+ logger.warning(
+ "Google OAuth mailbox identity verification failed for account %s",
+ account_id,
+ )
+ return _RR("/?section=integrations&email_oauth_error=identity_verification_failed")
+
+ row.oauth_provider = "google"
+ row.oauth_access_token = _enc(access_token)
+ row.oauth_refresh_token = _enc(refresh_token)
+ row.oauth_token_expiry = expiry
+ # Auto-fill Google IMAP/SMTP settings if not already configured.
+ if not row.imap_host:
+ row.imap_host = "imap.gmail.com"
+ row.imap_port = 993
+ row.imap_starttls = False
+ if not row.smtp_host:
+ row.smtp_host = "smtp.gmail.com"
+ row.smtp_port = 587
+ if email_addr:
+ if not row.imap_user:
+ row.imap_user = email_addr
+ if not row.smtp_user:
+ row.smtp_user = email_addr
+ if not row.from_address:
+ row.from_address = email_addr
+ if not row.name or row.name == row.id:
+ row.name = email_addr
+ if display_name and not row.display_name:
+ row.display_name = display_name
+ db.commit()
+ finally:
+ db.close()
+ return _RR("/?section=integrations&email_oauth_success=1")
+
+ return router
diff --cc scripts/generate_env_reference.py
index 000000000,766cb244e..c00131574
mode 000000,100644..100644
--- a/scripts/generate_env_reference.py
+++ b/scripts/generate_env_reference.py
@@@ -1,0 -1,1084 +1,1132 @@@
+ #!/usr/bin/env python3
+ """Generate the ODYSSEUS_* configuration reference from the source tree.
+
+ The page at website/configuration-reference.md is generated, never hand-edited.
+ This script walks the Python sources, collects every ODYSSEUS_* environment read
+ with the default it falls back to and the file it is read in, merges the
+ hand-written area/audience notes in VARIABLE_NOTES, and writes the Markdown.
+
+ python3 scripts/generate_env_reference.py # rewrite the page
+ python3 scripts/generate_env_reference.py --check # fail if it is stale
+ python3 scripts/generate_env_reference.py --stdout # print, write nothing
+ python3 scripts/generate_env_reference.py --list # one name per line
+
+ Reads are found three ways, because one pattern is not enough:
+
+ 1. Direct reads: `os.getenv(...)`, and any `.get` / `.setdefault` / `.pop` call
+ or subscript load keyed by an `ODYSSEUS_*` literal. The receiver is
+ deliberately not required to be `os.environ` - `src/tool_index.py` reads
+ through `source = os.environ if environ is None else environ`, and
+ `src/agent_tools/web_tools.py` reads from an env mapping passed in as an
+ argument. The `ODYSSEUS_` prefix is specific enough that keying anything else
+ by one of these names would itself be the bug.
+ 2. Calls to env-reader helpers - any function that passes one of its own
+ parameters to an environment read. This is detected, not hardcoded, so a new
+ helper is picked up without editing this script. It is what finds the
+ read_byte_limit_env family in src/upload_limits.py and the media-ingress
+ overrides in src/media_ingress.py, both of which a grep for `os.environ.get(`
+ misses entirely.
+ 3. A regex sweep of the raw file text, to catch reads that the AST cannot see -
+ notably a read inside a Python snippet that is itself a string literal
+ (routes/cookbook_helpers.py builds an Ollama probe script that way).
+ """
+ import argparse
+ import ast
+ import re
+ import sys
+ from collections import defaultdict
+ from dataclasses import dataclass, field
+ from pathlib import Path
+
+ REPO_ROOT = Path(__file__).resolve().parents[1]
+ OUTPUT_PATH = REPO_ROOT / "website" / "configuration-reference.md"
+ PREFIX = "ODYSSEUS_"
+
+ # Source roots walked for reads. Order is irrelevant; results are sorted.
+ SOURCE_ROOTS = (
+ "app.py",
+ "launcher.py",
+ "setup.py",
+ "companion",
+ "config",
+ "core",
+ "integrations",
+ "mcp_servers",
+ "routes",
+ "scripts",
+ "services",
+ "src",
+ "tests",
+ )
+
+ # Mapping methods that read a variable out of an environment-like mapping.
+ ENVIRON_READERS = ("get", "setdefault", "pop")
+
+ # Files whose ODYSSEUS_* text is deliberately not a real read. The generator's
+ # own test builds a synthetic source tree out of string literals, and the text
+ # sweep below would otherwise document its fixtures as configuration.
+ EXCLUDED_FILES = ("tests/test_env_reference.py",)
+
+ # Reads the AST walk cannot reach (strings holding generated code) are found by
+ # this. It allows any quoting and any whitespace, and the lookahead keeps a
+ # subscript ASSIGNMENT - `os.environ["ODYSSEUS_X"] = "1"` - from counting as a
+ # read, which the AST pass already excludes by checking the expression context.
+ TEXT_READ_RE = re.compile(
+ r"""(?:os\.)?(?:environ\.(?:get|setdefault|pop)|getenv)\(\s*['"](ODYSSEUS_[A-Z0-9_]+)['"]"""
+ r"""|environ\[\s*['"](ODYSSEUS_[A-Z0-9_]+)['"]\s*\](?!\s*=[^=])"""
+ )
+
+ # Markdown table order. A variable whose area is missing from here is a bug in
+ # VARIABLE_NOTES, and check_notes() reports it.
+ AREA_ORDER = (
+ "Deployment and first run",
+ "Data directories and paths",
+ "Model routing and providers",
+ "Agent loop and tool execution",
+ "Browser automation",
+ "Container and workspace mounts",
+ "Email",
+ "Calendar, notes and single-user mode",
+ "Upload and media limits",
+ "Search",
+ "Memory and skills",
+ "Speech and vision models",
+ "Auth and internal API",
+ "Integrations (Claude, Codex)",
+ "Testing, capture and development tooling",
+ "Build and release metadata",
+ )
+
+ USER = "user"
+ INTERNAL = "internal"
+
+
+ @dataclass
+ class Read:
+ """One place a variable is read."""
+
+ path: str
+ lineno: int
+ how: str
+ default: str | None
+
+ @property
+ def location(self) -> str:
+ return f"{self.path}:{self.lineno}"
+
+
+ @dataclass
+ class Variable:
+ name: str
+ reads: list[Read] = field(default_factory=list)
+
+ @property
+ def primary(self) -> Read:
+ """The read to quote: prefer application code over tooling and tests."""
+ return min(self.reads, key=_read_rank)
+
+ @property
+ def defaults(self) -> list[str]:
+ seen = []
+ for read in sorted(self.reads, key=_read_rank):
+ shown = read.default if read.default is not None else "unset"
+ if shown not in seen:
+ seen.append(shown)
+ return seen
+
+ @property
+ def test_only(self) -> bool:
+ return all(read.path.startswith("tests/") for read in self.reads)
+
+
+ def _read_rank(read: "Read") -> tuple[int, int, str, int]:
+ """Sort key picking the most informative read first.
+
+ Application code beats tooling beats tests, and within one tier a read that
+ carries an explicit default beats one that does not - otherwise the Default
+ column quotes a call site that simply has no fallback to report.
+ """
+ if read.path.startswith("tests/"):
+ tier = 3
+ elif read.path.startswith("scripts/"):
+ tier = 2
+ elif read.path.startswith("integrations/"):
+ tier = 1
+ else:
+ tier = 0
+ return (tier, 0 if read.default is not None else 1, read.path, read.lineno)
+
+
+ def iter_source_files(repo_root: Path):
+ for entry in SOURCE_ROOTS:
+ target = repo_root / entry
+ if target.is_file():
+ candidates = [target]
+ elif target.is_dir():
+ candidates = sorted(target.rglob("*.py"))
+ else:
+ continue
+ for path in candidates:
+ if "__pycache__" in path.parts:
+ continue
+ if path.relative_to(repo_root).as_posix() in EXCLUDED_FILES:
+ continue
+ yield path
+
+
+ def _fold(node: ast.AST, constants: dict[str, ast.AST]) -> str:
+ """Render a default expression, resolving one level of indirection.
+
+ Names bound to a module-level literal and attributes of a locally
+ constructed dataclass are resolved to the literal in the source. Anything
+ else is rendered as written, which keeps the table honest about defaults
+ that are computed at import time.
+ """
+ if isinstance(node, ast.Name) and node.id in constants:
+ return ast.unparse(constants[node.id])
+ if isinstance(node, ast.Attribute):
+ resolved = constants.get(f".{node.attr}")
+ if resolved is not None:
+ return ast.unparse(resolved)
+ return ast.unparse(node)
+
+
+ def _collect_constants(tree: ast.Module) -> dict[str, ast.AST]:
+ """Module-level `NAME = <expr>` bindings, plus dataclass field defaults.
+
+ Dataclass fields are keyed as `.field_name` so an attribute read on any
+ local instance resolves. That is loose, but every collision would have to be
+ two dataclasses in one module using one field name with different defaults,
+ and check_notes() makes a wrong default visible rather than silent.
+ """
+ constants: dict[str, ast.AST] = {}
+ for node in tree.body:
+ if isinstance(node, ast.Assign):
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ constants[target.id] = node.value
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
+ if node.value is not None:
+ constants[node.target.id] = node.value
+ elif isinstance(node, ast.ClassDef):
+ for stmt in node.body:
+ if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):
+ if stmt.value is not None:
+ constants.setdefault(f".{stmt.target.id}", stmt.value)
+ return constants
+
+
+ def _env_name(node: ast.AST, constants: dict[str, ast.AST]) -> str | None:
+ """The variable name a call/subscript argument refers to, if any."""
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
+ return node.value
+ if isinstance(node, ast.Name):
+ bound = constants.get(node.id)
+ if isinstance(bound, ast.Constant) and isinstance(bound.value, str):
+ return bound.value
+ return None
+
+
+ def find_env_reader_helpers(tree: ast.Module) -> dict[str, int]:
+ """Functions in this module that read `os.environ` from a parameter.
+
+ Returns helper name -> index of the parameter holding the variable name.
+ Nested functions count: src/media_ingress.py defines its reader inside
+ limits_from_env().
+ """
+ helpers: dict[str, int] = {}
+ for func in ast.walk(tree):
+ if not isinstance(func, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ params = [arg.arg for arg in func.args.posonlyargs + func.args.args]
+ if not params:
+ continue
+ for node in ast.walk(func):
+ arg = None
+ if isinstance(node, ast.Call):
+ attr = getattr(node.func, "attr", None)
+ base = getattr(node.func, "value", None)
+ if node.args and (attr in ENVIRON_READERS or attr == "getenv"):
+ arg = node.args[0]
+ elif isinstance(node, ast.Subscript) and isinstance(node.ctx, ast.Load):
+ arg = node.slice
+ if isinstance(arg, ast.Name) and arg.id in params:
+ helpers[func.name] = params.index(arg.id)
+ break
+ return helpers
+
+
+ def scan_file(path: Path, repo_root: Path) -> list[tuple[str, Read]]:
+ """Every ODYSSEUS_* read in one file."""
+ rel = path.relative_to(repo_root).as_posix()
+ text = path.read_text(encoding="utf-8", errors="replace")
+ if PREFIX not in text:
+ return []
+ try:
+ tree = ast.parse(text)
+ except SyntaxError:
+ return []
+
+ constants = _collect_constants(tree)
+ helpers = find_env_reader_helpers(tree)
+ results: list[tuple[str, Read]] = []
+ seen_by_ast: set[str] = set()
+
+ for node in ast.walk(tree):
+ name = None
+ how = None
+ default_node = None
+
+ if isinstance(node, ast.Call):
+ func = node.func
+ attr = getattr(func, "attr", None)
+ base = getattr(func, "value", None)
+ if node.args and attr in ENVIRON_READERS and base is not None:
+ name = _env_name(node.args[0], constants)
+ how = f"environ.{attr}"
+ default_node = node.args[1] if len(node.args) > 1 else None
+ elif node.args and attr == "getenv" and base is not None:
+ name = _env_name(node.args[0], constants)
+ how = "os.getenv"
+ default_node = node.args[1] if len(node.args) > 1 else None
+ elif isinstance(func, ast.Name) and func.id in helpers:
+ index = helpers[func.id]
+ if len(node.args) > index:
+ name = _env_name(node.args[index], constants)
+ how = f"{func.id}()"
+ if len(node.args) > index + 1:
+ default_node = node.args[index + 1]
+ elif isinstance(func, ast.Name) and func.id == "getenv" and node.args:
+ name = _env_name(node.args[0], constants)
+ how = "os.getenv"
+ default_node = node.args[1] if len(node.args) > 1 else None
+ elif isinstance(node, ast.Subscript) and isinstance(node.ctx, ast.Load):
+ name = _env_name(node.slice, constants)
+ how = "environ[...]"
+
+ if not name or not name.startswith(PREFIX):
+ continue
+ default = _fold(default_node, constants) if default_node is not None else None
+ results.append((name, Read(rel, node.lineno, how, default)))
+ seen_by_ast.add(name)
+
+ # Pass 3: reads the AST cannot reach, e.g. inside generated-code strings.
+ for lineno, line in enumerate(text.splitlines(), start=1):
+ for match in TEXT_READ_RE.finditer(line):
+ name = match.group(1) or match.group(2)
+ if name in seen_by_ast:
+ continue
+ results.append((name, Read(rel, lineno, "read in generated code", None)))
+ return results
+
+
+ def collect(repo_root: Path = REPO_ROOT) -> dict[str, Variable]:
+ variables: dict[str, Variable] = {}
+ for path in iter_source_files(repo_root):
+ for name, read in scan_file(path, repo_root):
+ variables.setdefault(name, Variable(name)).reads.append(read)
+ for variable in variables.values():
+ variable.reads.sort(key=_read_rank)
+ return dict(sorted(variables.items()))
+
+
+ # Hand-written notes, one entry per variable: (area, audience, summary).
+ #
+ # This is the only part of the page that is not derived from the source, and it
+ # is why the test is worth having: check_notes() fails when a variable is read
+ # without an entry here, so a new ODYSSEUS_* knob cannot land undocumented.
+ # Every default in the table comes from the source, not from this table.
+ #
+ # audience is USER for something an operator may reasonably set on a real
+ # install, and INTERNAL for sentinels, fixture switches, capture hooks and
+ # development tooling. Internal variables are listed on the page too, in their
+ # own section, rather than hidden.
+ VARIABLE_NOTES: dict[str, tuple[str, str, str]] = {
+ # -- Deployment and first run ------------------------------------------
+ "ODYSSEUS_ADMIN_USER": (
+ "Deployment and first run", USER,
+ "Username for the admin account created on first run. Setup uses env vars "
+ "first, then an interactive prompt, then a random password.",
+ ),
+ "ODYSSEUS_ADMIN_PASSWORD": (
+ "Deployment and first run", USER,
+ "Password for the admin account created on first run. Setup refuses a value "
+ "shorter than its minimum length rather than silently falling back.",
+ ),
+ "ODYSSEUS_SKIP_ADMIN_PROMPT": (
+ "Deployment and first run", USER,
+ "Any non-empty value suppresses the interactive admin-credential prompt even "
+ "on a TTY, for unattended installs.",
+ ),
+ "ODYSSEUS_INPROCESS_TASKS": (
+ "Deployment and first run", USER,
+ "Set to 0, false, no or off to stop the in-process scheduled-task runner, for "
+ "deployments where an external worker drives task firing.",
+ ),
+ "ODYSSEUS_INPROCESS_POLLERS": (
+ "Deployment and first run", USER,
+ "The same off switch for the in-process email pollers, when "
+ "`odysseus-mail poll-scheduled` is the sole external driver.",
+ ),
+ "ODYSSEUS_STARTUP_WARMUPS": (
+ "Deployment and first run", USER,
+ "Opt-in startup pings of the configured model endpoints. Off by default "
+ "because they compete with the first seconds of UI use.",
+ ),
+ "ODYSSEUS_MODEL_KEEPALIVE": (
+ "Deployment and first run", USER,
+ "Opt-in periodic model keep-alive pings. Off by default: the ping path runs "
+ "model discovery, so stale LAN endpoints add background pressure.",
+ ),
+ "ODYSSEUS_SLOW_REQUEST_LOG_SECONDS": (
+ "Deployment and first run", USER,
+ "Request duration in seconds above which the middleware logs a slow-request "
+ "warning.",
+ ),
+ "ODYSSEUS_REQUIRE_TOOL_INDEX_READY": (
+ "Deployment and first run", USER,
+ "Set truthy to make semantic tool-index readiness gate startup. Off by "
+ "default so an install stays available on deterministic tool selection.",
+ ),
+ "ODYSSEUS_TOOL_INDEX_PREWARM": (
+ "Deployment and first run", USER,
+ "Set to 0, false, no or off to skip background initialization of semantic "
+ "tool retrieval at startup.",
+ ),
+ "ODYSSEUS_ENABLE_HOST_DOCKER": (
+ "Deployment and first run", USER,
+ "Security-relevant. Must be exactly `true` before tools may use a mounted "
+ "host Docker socket, and the socket itself must exist.",
+ ),
+ "ODYSSEUS_CONTAINER_NETWORK_MODE": (
+ "Deployment and first run", USER,
+ "Declares the container's Docker network mode. Set to `host` to skip "
+ "host-gateway probing when discovering local model endpoints.",
+ ),
+ "ODYSSEUS_ALLOW_OLLAMA_CLI_SCAN": (
+ "Deployment and first run", USER,
+ "On Windows only, set truthy to let the Cookbook dependency probe shell out "
+ "to `ollama list`. Ignored on other platforms, where the scan always runs.",
+ ),
+
+ # -- Data directories and paths ----------------------------------------
+ "ODYSSEUS_DATA_DIR": (
+ "Data directories and paths", USER,
+ "Root directory for every persisted file. Prefer this over the per-path "
+ "overrides; the rest of `src/constants.py` derives from it.",
+ ),
+ "ODYSSEUS_MAIL_ATTACHMENTS_DIR": (
+ "Data directories and paths", USER,
+ "Dedicated override for the mail attachment store, which otherwise lives "
+ "under the data directory.",
+ ),
+ "ODYSSEUS_INTERNAL_BASE": (
+ "Auth and internal API", USER,
+ "Base URL the in-app tool layer uses for loopback HTTP calls. Set it when "
+ "the app is not reachable at the port it thinks it is bound to.",
+ ),
+
+ # -- Model routing and providers ---------------------------------------
+ "ODYSSEUS_LOCAL_MODEL_GATE": (
+ "Model routing and providers", USER,
+ "On by default. Set 0, false, no or off to drop the gate that checks a local "
+ "endpoint before routing a request to it.",
+ ),
+ "ODYSSEUS_FIRST_TOKEN_TIMEOUT": (
+ "Model routing and providers", USER,
+ "Seconds to wait for the first streamed token from a local endpoint before "
+ "failing. Unset keeps the generous read timeout, which makes a stalled "
+ "backend look like a hung agent.",
+ ),
+ "ODYSSEUS_MISTRAL_REASONING_EFFORT": (
+ "Model routing and providers", USER,
+ "Reasoning effort sent to Mistral thinking-capable models. The API accepts "
+ "high, medium, low and none.",
+ ),
+ "ODYSSEUS_DEEPSEEK_REASONING_EFFORT": (
+ "Model routing and providers", USER,
+ "Reasoning effort for DeepSeek. Only `high` and `max` are accepted; any "
+ "other value falls back to the default.",
+ ),
+ "ODYSSEUS_QWEN_ROUTE_THINKING": (
+ "Model routing and providers", USER,
+ "Thinking policy for the Qwen routing step. An unrecognized value falls back "
+ "to `auto`.",
+ ),
+ "ODYSSEUS_COPILOT_CLIENT_ID": (
+ "Model routing and providers", USER,
+ "GitHub OAuth client id for the Copilot device flow. The default is the "
+ "public VS Code client id; override it only with your own allow-listed app.",
+ ),
+ "ODYSSEUS_COPILOT_API_VERSION": (
+ "Model routing and providers", USER,
+ "Dated API-version header the Copilot models and chat endpoints require.",
+ ),
+ "ODYSSEUS_MLX_IMAGE_VLM_MODEL": (
+ "Model routing and providers", USER,
+ "Vision-language model id for the MLX image server script. Required unless "
+ "`--vlm-model` is passed on the command line.",
+ ),
+ "ODYSSEUS_COPILOT_USER_AGENT": (
+ "Model routing and providers", INTERNAL,
+ "Editor-like User-Agent presented to the Copilot API. Kept stable on purpose.",
+ ),
+ "ODYSSEUS_COPILOT_INTEGRATION_ID": (
+ "Model routing and providers", INTERNAL,
+ "Integration id presented to the Copilot API. Kept stable on purpose.",
+ ),
+ "ODYSSEUS_COPILOT_EDITOR_VERSION": (
+ "Model routing and providers", INTERNAL,
+ "Editor-version header presented to the Copilot API. Kept stable on purpose.",
+ ),
+ "ODYSSEUS_DEBUG_LLM_SHAPE": (
+ "Model routing and providers", INTERNAL,
+ "Truthy logs the shape of streamed provider chunks. Debugging aid for "
+ "provider response parsing.",
+ ),
+
+ # -- Agent loop and tool execution -------------------------------------
+ "ODYSSEUS_TOOL_APPROVAL_GATE": (
+ "Agent loop and tool execution", USER,
+ "Security-relevant. Truthy makes tool calls pass through the approval gate. "
+ "Off by default.",
+ ),
+ "ODYSSEUS_MCP_ALLOWED_COMMANDS": (
+ "Agent loop and tool execution", USER,
+ "Security-relevant. Comma-separated allowlist of MCP launcher basenames the "
+ "agent may start. Empty by default, and the deny list still wins.",
+ ),
+ "ODYSSEUS_PYTHON_TOOL_SITE_PACKAGES": (
+ "Agent loop and tool execution", USER,
+ "Security-relevant. Absolute package roots, separated by the platform path "
+ "separator, exposed to the sandboxed Python tool. Empty exposes none.",
+ ),
+ "ODYSSEUS_DISABLE_MCP": (
+ "Agent loop and tool execution", USER,
+ "Truthy disables MCP entirely, as an escape hatch for compatibility "
+ "problems with a server.",
+ ),
+ "ODYSSEUS_SCRIPT_HOST": (
+ "Agent loop and tool execution", USER,
+ "Default host for the run-script action. `localhost`, `127.0.0.1`, `local` "
+ "and empty run locally; any other value runs over SSH.",
+ ),
+ "ODYSSEUS_MAX_VISUAL_EVIDENCE_IMAGES": (
+ "Agent loop and tool execution", USER,
+ "How many images one tool result may contribute to the model turn. Clamped "
+ "to 1-8.",
+ ),
+ "ODYSSEUS_MAX_VISUAL_EVIDENCE_FRAMES": (
+ "Agent loop and tool execution", USER,
+ "How many video frames one tool result may contribute. Clamped to 1-8.",
+ ),
+ "ODYSSEUS_CAPTURE_MODEL_REQUESTS": (
+ "Agent loop and tool execution", INTERNAL,
+ "Truthy writes model-request snapshots for local debugging. The marker file "
+ "`/tmp/odysseus_capture_model_requests` enables the same thing.",
+ ),
+ "ODYSSEUS_EXPOSE_RAW_BROWSER_MCP": (
+ "Agent loop and tool execution", INTERNAL,
+ "Truthy stops hiding the raw Playwright MCP tools from agent prompts when "
+ "the private-browser tool is available.",
+ ),
+ "ODYSSEUS_TOOL_CONTRACT_ROOT": (
+ "Agent loop and tool execution", INTERNAL,
+ "Directory holding the tool-contract scripts the clean-agent preview loads. "
+ "The default is a path on the maintainer's own machine.",
+ ),
+
+ # -- Browser automation -------------------------------------------------
+ "ODYSSEUS_BROWSER_EXECUTABLE": (
+ "Browser automation", USER,
+ "Absolute path to the Chrome or Chromium binary. Empty searches the usual "
+ "names, then lets Playwright MCP pick its own browser.",
+ ),
+ "ODYSSEUS_BROWSER_ISOLATED": (
+ "Browser automation", USER,
+ "Security-relevant. On by default, adding `--isolated` so each browser "
+ "session starts clean. Set 0, false or no to keep a persistent profile.",
+ ),
+ "ODYSSEUS_BROWSER_NO_SANDBOX": (
+ "Browser automation", USER,
+ "Security-relevant. On by default, adding `--no-sandbox` because the Docker "
+ "image cannot use the Chromium sandbox. Set 0, false or no to keep it.",
+ ),
+ "ODYSSEUS_BROWSER_MCP_CACHE": (
+ "Browser automation", USER,
+ "Cache directory handed to the browser MCP server, so its npm download "
+ "survives a container rebuild.",
+ ),
+ "ODYSSEUS_BROWSER_MCP_REQUIRE_CACHE": (
+ "Browser automation", USER,
+ "Truthy refuses to start the browser MCP server unless its npm package is "
+ "already in the npx cache, instead of installing it at startup.",
+ ),
+ "ODYSSEUS_BROWSER_NAMESPACE": (
+ "Browser automation", USER,
+ "Namespace for the detached agent-browser daemon's pid files, so two "
+ "runtimes on one machine do not terminate each other's browsers.",
+ ),
+ "ODYSSEUS_BROWSER_SCREENSHOT_DIR": (
+ "Browser automation", USER,
+ "Where private-browser screenshots are written. Falls back to the container "
+ "path, then the system temp directory.",
+ ),
+
+ # -- Container and workspace mounts ------------------------------------
+ "ODYSSEUS_WORKSPACE_MOUNTS": (
+ "Container and workspace mounts", USER,
+ "`host=container` path pairs separated by commas or semicolons, so the agent "
+ "can translate a container path back to the host path a user typed.",
+ ),
+ "ODYSSEUS_WORKSPACE_HOST_ROOT": (
+ "Container and workspace mounts", USER,
+ "Single host-side root, paired with the container root below. Simpler than "
+ "the explicit mount list when there is only one mount.",
+ ),
+ "ODYSSEUS_WORKSPACE_CONTAINER_ROOT": (
+ "Container and workspace mounts", USER,
+ "Container-side root that the host root maps onto. An `or` fallback, not a "
+ "read default, supplies `/workspace` when it is unset.",
+ ),
+ "ODYSSEUS_WORKSPACE_DEFAULT": (
+ "Container and workspace mounts", USER,
+ "Default workspace path the admin-only workspace route reports. Empty means "
+ "no default is configured.",
+ ),
+
+ # -- Email --------------------------------------------------------------
+ "ODYSSEUS_IMAP_TIMEOUT_SECONDS": (
+ "Email", USER,
+ "IMAP socket timeout in seconds, clamped to 5-300. A non-numeric value falls "
+ "back to 30 rather than failing.",
+ ),
+ "ODYSSEUS_DOCUMENT_OWNER": (
+ "Email", USER,
+ "Owner stamped on documents the email MCP server creates. Stdio MCP tools "
+ "get no authenticated user, so without this a draft is invisible.",
+ ),
+ "ODYSSEUS_EMAIL_FIXTURE": (
+ "Email", INTERNAL,
+ "Exactly `1`, plus a fixture file on disk, makes the email MCP server serve "
+ "fixtures instead of a real mailbox.",
+ ),
+
+ # -- Calendar, notes and single-user mode -------------------------------
+ "ODYSSEUS_SINGLE_USER": (
+ "Calendar, notes and single-user mode", USER,
+ "Security-relevant. On by default. Set to 0 on a real multi-user install so "
+ "unauthenticated calendar writes are rejected rather than absorbed.",
+ ),
+ "ODYSSEUS_FALLBACK_OWNER": (
+ "Calendar, notes and single-user mode", USER,
+ "Owner address that single-user mode attributes an unauthenticated request "
+ "to. Only reachable while single-user mode is on.",
+ ),
+ "ODYSSEUS_ALLOW_PRIVATE_CALDAV": (
+ "Calendar, notes and single-user mode", USER,
+ "Security-relevant. Truthy lets CalDAV sync reach private and link-local "
+ "addresses. Off by default; this is an SSRF guard.",
+ ),
+
+ # -- Upload and media limits -------------------------------------------
+ "ODYSSEUS_CHAT_UPLOAD_MAX_BYTES": (
+ "Upload and media limits", USER, "Maximum bytes accepted for a chat attachment.",
+ ),
+ "ODYSSEUS_GALLERY_UPLOAD_MAX_BYTES": (
+ "Upload and media limits", USER, "Maximum bytes accepted for a gallery upload.",
+ ),
+ "ODYSSEUS_GALLERY_TRANSFORM_UPLOAD_MAX_BYTES": (
+ "Upload and media limits", USER,
+ "Maximum bytes accepted for an image handed to a gallery transform.",
+ ),
+ "ODYSSEUS_EDITOR_DRAFT_MAX_BYTES": (
+ "Upload and media limits", USER, "Maximum bytes accepted for a saved editor draft.",
+ ),
+ "ODYSSEUS_MEMORY_IMPORT_MAX_BYTES": (
+ "Upload and media limits", USER, "Maximum bytes accepted for a memory import file.",
+ ),
+ "ODYSSEUS_PERSONAL_UPLOAD_MAX_BYTES": (
+ "Upload and media limits", USER,
+ "Maximum bytes accepted for a personal-documents upload.",
+ ),
+ "ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES": (
+ "Upload and media limits", USER,
+ "Maximum bytes accepted for an attachment added while composing mail.",
+ ),
+ "ODYSSEUS_STT_MAX_AUDIO_BYTES": (
+ "Upload and media limits", USER,
+ "Maximum bytes accepted for an audio file submitted for transcription.",
+ ),
+ "ODYSSEUS_ICS_MAX_BYTES": (
+ "Upload and media limits", USER, "Maximum bytes accepted for an imported ICS file.",
+ ),
+ "ODYSSEUS_MEDIA_MAX_FILES": (
+ "Upload and media limits", USER,
+ "How many local media files one agent turn may ingest.",
+ ),
+ "ODYSSEUS_MEDIA_MAX_IMAGE_BYTES": (
+ "Upload and media limits", USER, "Largest source image the media pipeline will read.",
+ ),
+ "ODYSSEUS_MEDIA_MAX_VIDEO_BYTES": (
+ "Upload and media limits", USER, "Largest source video the media pipeline will read.",
+ ),
+ "ODYSSEUS_MEDIA_MAX_DOCUMENT_BYTES": (
+ "Upload and media limits", USER, "Largest source document the media pipeline will read.",
+ ),
+ "ODYSSEUS_MEDIA_MAX_AUDIO_BYTES": (
+ "Upload and media limits", USER, "Largest source audio file the media pipeline will read.",
+ ),
+ "ODYSSEUS_MEDIA_MAX_ENCODED_BYTES": (
+ "Upload and media limits", USER,
+ "Budget for the encoded payload handed to the model, counted cumulatively "
+ "across one turn's attachments rather than per file.",
+ ),
+ "ODYSSEUS_MEDIA_MAX_DOCUMENT_CHARS": (
+ "Upload and media limits", USER,
+ "How many characters of an ingested document are inlined into the turn.",
+ ),
+ "ODYSSEUS_MEDIA_MAX_DIMENSION": (
+ "Upload and media limits", USER,
+ "Longest edge in pixels an image is resized down to before encoding.",
+ ),
+ "ODYSSEUS_MEDIA_MAX_PIXELS": (
+ "Upload and media limits", USER,
+ "Total pixel budget for a source image, as a decompression-bomb guard.",
+ ),
+ "ODYSSEUS_MEDIA_MAX_VIDEO_FRAMES": (
+ "Upload and media limits", USER, "How many frames are sampled from a video.",
+ ),
+ "ODYSSEUS_MEDIA_PROBE_TIMEOUT": (
+ "Upload and media limits", USER,
+ "Seconds allowed for probing a video's metadata before giving up.",
+ ),
+ "ODYSSEUS_MEDIA_FRAME_TIMEOUT": (
+ "Upload and media limits", USER,
+ "Seconds allowed for extracting frames from a video before giving up.",
+ ),
+
+ # -- Search -------------------------------------------------------------
+ "ODYSSEUS_SEARCH_PROVIDER": (
+ "Search", USER,
+ "Forces the search provider, overriding the Settings value. Empty keeps the "
+ "UI authoritative, which is what a normal install wants.",
+ ),
+
+ # -- Memory and skills --------------------------------------------------
+ "ODYSSEUS_SKILL_SEMANTIC_RETRIEVAL": (
+ "Memory and skills", USER,
+ "On by default. Set 0, false, no or off to fall back to keyword-only skill "
+ "retrieval when no vector store is reachable.",
+ ),
+ "ODYSSEUS_SKILL_SEMANTIC_THRESHOLD": (
+ "Memory and skills", USER,
+ "Minimum semantic score a skill needs to be retrieved. A non-numeric value "
+ "falls back to the default.",
+ ),
+
+ # -- Speech and vision models -------------------------------------------
+ "ODYSSEUS_STT_MODEL": (
+ "Speech and vision models", USER,
+ "Default speech-to-text model for media transcription when the tool call "
+ "does not name one.",
+ ),
+ "ODYSSEUS_TTS_CACHE_MAX_BYTES": (
+ "Speech and vision models", USER,
+ "Cap on the synthesized-speech cache. A non-numeric value falls back to the "
+ "default.",
+ ),
+ "ODYSSEUS_SAM_MODEL": (
+ "Speech and vision models", USER,
+ "Segmentation model id the gallery loads for subject selection.",
+ ),
+ "ODYSSEUS_GROUNDING_MODEL": (
+ "Speech and vision models", USER,
+ "Object-grounding model id the gallery loads for text-driven selection.",
+ ),
+
+ # -- Auth and internal API ----------------------------------------------
+ "ODYSSEUS_INTERNAL_TOKEN": (
+ "Auth and internal API", USER,
+ "Security-relevant. Token that lets the in-app tool layer reach admin-gated "
+ "routes over loopback. Unset generates a fresh per-process token, which is "
+ "what you want unless something outside the process needs the same value.",
+ ),
+
+ # -- Integrations (Claude, Codex) ---------------------------------------
+ "ODYSSEUS_URL": (
+ "Integrations (Claude, Codex)", USER,
+ "Base URL of the Odysseus instance the bundled integration scripts call.",
+ ),
+ "ODYSSEUS_API_TOKEN": (
+ "Integrations (Claude, Codex)", USER,
+ "API token those scripts authenticate with. Both this and the URL are "
+ "required; the scripts name whichever is missing.",
+ ),
+
+ # -- Testing, capture and development tooling ---------------------------
+ "ODYSSEUS_SKIP_RUN_HINT": (
+ "Testing, capture and development tooling", INTERNAL,
+ "Any non-empty value suppresses the `start the server with` hint at the end "
+ "of setup. `start-macos.sh` sets it because it starts the server itself.",
+ ),
+ "ODYSSEUS_TEST_STATIC_ORIGIN": (
+ "Testing, capture and development tooling", INTERNAL,
+ "Origin an already-running static server is serving the repository from, so "
+ "snapshot tooling reuses it instead of starting its own.",
+ ),
+ "ODYSSEUS_TEST_STATIC_PORT": (
+ "Testing, capture and development tooling", INTERNAL,
+ "Fixed port for the test suite's static server. Unset takes an ephemeral "
+ "port, which is what keeps parallel runs from colliding.",
+ ),
+ "ODYSSEUS_SFT_TRACE_CAPTURE": (
+ "Testing, capture and development tooling", INTERNAL,
+ "On by default, but only for owners whose name starts with `sft_`. Set 0, "
+ "false, no or off to stop writing training traces.",
+ ),
+ "ODYSSEUS_SFT_TRACE_DIR": (
+ "Testing, capture and development tooling", INTERNAL,
+ "Directory the SFT trace JSONL files are written to. Defaults to "
+ "`sft_traces` under the data directory.",
+ ),
+ "ODYSSEUS_SFT_FORCE_UTC_TIMEZONE": (
+ "Testing, capture and development tooling", INTERNAL,
+ "Truthy forces `sft_` accounts to UTC for deterministic batch generation. "
+ "Interactive accounts still follow the browser timezone.",
+ ),
+ "ODYSSEUS_SFT_DISABLE_WORKSPACE_TOOLS": (
+ "Testing, capture and development tooling", INTERNAL,
+ "On by default. Keeps synthetic personal-assistant fixtures out of workspace "
+ "mode; set 0, false, no or off to let them through.",
+ ),
++ "ODYSSEUS_AJAX_TEST_URL": (
++ "Testing, capture and development tooling", INTERNAL,
++ "Chat-completions URL of a live Ajax endpoint. Unset skips the opt-in live "
++ "Ajax email tests.",
++ ),
++ "ODYSSEUS_EDITOR_TEST_ENDPOINT": (
++ "Testing, capture and development tooling", INTERNAL,
++ "Chat-completions URL the opt-in editor-writing and organizer smoke tools "
++ "drive. Both tools require it.",
++ ),
++ "ODYSSEUS_EDITOR_ACTIONS": (
++ "Testing, capture and development tooling", INTERNAL,
++ "Comma-separated writing actions the editor-writing smoke tool runs. Unset "
++ "runs every action plus edit and update.",
++ ),
++ "ODYSSEUS_EDITOR_MAX_TOKENS": (
++ "Testing, capture and development tooling", INTERNAL,
++ "Completion token limit for each editor-writing smoke request.",
++ ),
++ "ODYSSEUS_EDITOR_RICH_FIXTURE": (
++ "Testing, capture and development tooling", INTERNAL,
++ "Set to 1 to run the editor-writing smoke tool against a rich-text document "
++ "fixture instead of Markdown.",
++ ),
++ "ODYSSEUS_EDITOR_TRACE": (
++ "Testing, capture and development tooling", INTERNAL,
++ "Any non-empty value prints every stream event after each editor-writing "
++ "smoke action.",
++ ),
++ "ODYSSEUS_ORGANIZER_TRACE": (
++ "Testing, capture and development tooling", INTERNAL,
++ "Any non-empty value prints each provider request the organizer smoke tool "
++ "sends.",
++ ),
++ "ODYSSEUS_ORGANIZER_AUTO_CHOICE": (
++ "Testing, capture and development tooling", INTERNAL,
++ "With organizer tracing on, any non-empty value replaces forced tool choice "
++ "with auto on traced requests.",
++ ),
++ "ODYSSEUS_ORGANIZER_TRACE_MESSAGES": (
++ "Testing, capture and development tooling", INTERNAL,
++ "With organizer tracing on, any non-empty value also prints the request "
++ "messages.",
++ ),
++ "ODYSSEUS_ORGANIZER_CASES": (
++ "Testing, capture and development tooling", INTERNAL,
++ "Comma-separated organizer smoke case names to run. Unset runs every case.",
++ ),
+ "ODYSSEUS_RUNTIME_REVISION": (
+ "Testing, capture and development tooling", INTERNAL,
+ "Revision string stamped into each captured SFT trace record, so a trace can "
+ "be tied back to the build that produced it.",
+ ),
+ "ODYSSEUS_QA_TEACHER_ATTEMPTS": (
+ "Testing, capture and development tooling", INTERNAL,
+ "Retry budget for the conversation-QA teacher model call. Clamped to 1-3.",
+ ),
+ "ODYSSEUS_QA_TEACHER_TIMEOUT": (
+ "Testing, capture and development tooling", INTERNAL,
+ "Timeout in seconds for that call. Clamped to 15-120.",
+ ),
+
+ # -- Build and release metadata ----------------------------------------
+ "ODYSSEUS_BUILD_VERSION": (
+ "Build and release metadata", INTERNAL,
+ "Overrides the build-version string the API and UI report, without touching "
+ "the public application version.",
+ ),
+ "ODYSSEUS_SOURCE_COMMIT": (
+ "Build and release metadata", INTERNAL,
+ "Overrides the source commit reported for runtime provenance, for builds "
+ "that ship without a git directory.",
+ ),
+ }
+
+
+ GENERATED_WARNING = (
+ "This page is generated from the source tree by "
+ "`scripts/generate_env_reference.py`. Do not edit it by hand: run the script "
+ "instead. `tests/test_env_reference.py` fails when the committed page and the "
+ "source disagree, or when a variable is read without an entry in the script's "
+ "notes table."
+ )
+
+ INTRO = """Odysseus reads its runtime configuration from the Settings UI. The
+ environment variables below are the deployment-level escape hatches underneath
+ that: they are read directly from the process environment, mostly at import or
+ startup, and most installs never need any of them.
+
+ `.env.example` stays a short, deployment-level example on purpose - `APP_BIND`,
+ `APP_PORT`, `AUTH_ENABLED`, `DATABASE_URL` and a pre-seeded admin password. This
+ page is the complete list, which is a different job.
+
+ Truthiness is not uniform across the codebase. Where a variable is described as
+ "truthy" the read accepts `1`, `true`, `yes` and usually `on`; where it is
+ described as a switch that turns something off, the read rejects `0`, `false`,
+ `no` and `off` and treats everything else as on. The `Default` column is the
+ value the code falls back to when the variable is unset, quoted from the source."""
+
+ HOW_SECTION = """The generator walks the Python sources under {roots} and finds
+ reads three ways, because no single pattern covers the codebase:
+
+ - Direct reads: `os.getenv(...)`, and any `.get` / `.setdefault` / `.pop` call or
+ subscript keyed by an `ODYSSEUS_*` literal, including names held in a
+ module-level constant. The receiver is not required to be `os.environ`, because
+ several call sites read through a mapping passed in as an argument
+ (`src/tool_index.py`, `src/host_docker_access.py`).
+ - Calls to env-reader helpers - any function that forwards one of its own
+ parameters to an environment read. This is detected rather than hardcoded, so a
+ new helper needs no change here. It is what finds the upload caps in
+ `src/upload_limits.py` and the media-ingress overrides in
+ `src/media_ingress.py`.
+ - A regex sweep of the raw file text, for reads the AST cannot see.
+ `routes/cookbook_helpers.py` builds an Ollama probe script as a list of source
+ lines, so one read lives inside a string literal.
+
+ The three passes are not redundancy. A line-based grep for a direct
+ `os.environ.get("ODYSSEUS_...` call finds {naive} of the {total} variables on this
+ page. What it misses is reads through an env-reader helper, reads whose call
+ spans more than one line, reads whose variable name is held in a module
+ constant, and reads through a mapping passed in as an argument - which is the
+ whole reason this page is generated rather than maintained.
+
+ The `Default` column shows the expression as written, with one level of
+ indirection resolved: a module-level constant and a dataclass field default are
+ replaced by the literal they hold, so `defaults.max_media_files` shows as `4`.
+ Anything computed at import time - `get_default_data_dir()` - is shown as
+ written, because that is the honest answer. A few call sites supply their
+ fallback with `or` rather than a default argument; those show as *unset* and say
+ so in the last column."""
+
+
+ def naive_line_scan(repo_root: Path = REPO_ROOT) -> set[str]:
+ """What a line-based grep for the direct call pattern would find.
+
+ Reported on the page so the gap between this and the real inventory stays
+ true as the code changes, instead of being a number somebody wrote down once.
+ """
+ pattern = re.compile(
+ r"""(?:os\.environ\.get|os\.getenv|environ\.get|getenv)\(\s*['"](ODYSSEUS_[A-Z0-9_]+)['"]"""
+ r"""|environ\[\s*['"](ODYSSEUS_[A-Z0-9_]+)['"]"""
+ )
+ found = set()
+ for path in iter_source_files(repo_root):
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
+ for match in pattern.finditer(line):
+ found.add(match.group(1) or match.group(2))
+ return found
+
+
+ def check_notes(variables: dict[str, Variable]) -> list[str]:
+ """Problems that make the page wrong. Empty means the notes table is sound."""
+ problems = []
+ for name in variables:
+ if name not in VARIABLE_NOTES:
+ location = variables[name].primary.location
+ problems.append(
+ f"{name} is read at {location} but has no entry in VARIABLE_NOTES "
+ f"in scripts/generate_env_reference.py - add one, with the area, "
+ f"whether an operator would ever set it, and one sentence on what "
+ f"it does"
+ )
+ for name, (area, audience, summary) in VARIABLE_NOTES.items():
+ if name not in variables:
+ problems.append(
+ f"{name} has a VARIABLE_NOTES entry but is no longer read anywhere "
+ f"- remove the entry"
+ )
+ if area not in AREA_ORDER:
+ problems.append(f"{name} has area {area!r}, which is not in AREA_ORDER")
+ if audience not in (USER, INTERNAL):
+ problems.append(f"{name} has audience {audience!r}")
+ if not summary.endswith("."):
+ problems.append(f"{name} summary should end with a full stop")
+ return problems
+
+
+ def _cell(text: str) -> str:
+ return text.replace("|", "\\|")
+
+
+ def _read_cell(variable: Variable) -> str:
+ primary = f"`{variable.primary.location}`"
+ extra = len(variable.reads) - 1
+ return primary if extra <= 0 else f"{primary} (+{extra} more)"
+
+
+ def _default_cell(variable: Variable) -> str:
+ default = variable.primary.default
+ return "*unset*" if default is None else f"`{_cell(default)}`"
+
+
+ def _table(rows: list[Variable]) -> list[str]:
+ lines = ["| Variable | Default | Read in | What it does |", "|---|---|---|---|"]
+ for variable in rows:
+ summary = VARIABLE_NOTES[variable.name][2]
+ lines.append(
+ f"| `{variable.name}` | {_default_cell(variable)} | "
+ f"{_read_cell(variable)} | {_cell(summary)} |"
+ )
+ return lines
+
+
+ def _sections(variables: dict[str, Variable], audience: str) -> list[str]:
+ by_area: dict[str, list[Variable]] = defaultdict(list)
+ for variable in variables.values():
+ area, own_audience, _ = VARIABLE_NOTES[variable.name]
+ if own_audience == audience:
+ by_area[area].append(variable)
+ lines = []
+ for area in AREA_ORDER:
+ rows = by_area.get(area)
+ if not rows:
+ continue
+ lines += ["", f"### {area}", ""]
+ lines += _table(sorted(rows, key=lambda item: item.name))
+ return lines
+
+
+ def render(variables: dict[str, Variable], naive: set[str]) -> str:
+ operator = [n for n, (_, aud, _) in VARIABLE_NOTES.items() if aud == USER and n in variables]
+ internal = [n for n, (_, aud, _) in VARIABLE_NOTES.items() if aud == INTERNAL and n in variables]
+ lines = [
+ "---",
+ "layout: default",
+ "---",
+ "",
+ "# Configuration reference: ODYSSEUS_* environment variables",
+ "",
+ f"<!-- {GENERATED_WARNING} -->",
+ "",
+ INTRO,
+ "",
+ f"The source tree reads **{len(variables)}** `ODYSSEUS_*` variables: "
+ f"{len(operator)} an operator may want to set, and {len(internal)} that are "
+ f"internal - sentinels, fixture switches, capture hooks and development "
+ f"tooling. The internal ones are listed too, in their own section, so this "
+ f"page can be checked against the source mechanically.",
+ "",
+ "> This page is generated. Edit `scripts/generate_env_reference.py` and",
+ "> re-run it; `tests/test_env_reference.py` enforces that the committed page",
+ "> matches the source.",
+ "",
+ "## Variables you can set",
+ ]
+ lines += _sections(variables, USER)
+ lines += ["", "## Internal and development-only variables", "",
+ "Listed for completeness. Setting one of these on a real install is "
+ "either a no-op or a way to break something quietly."]
+ lines += _sections(variables, INTERNAL)
+ lines += [
+ "",
+ "## How this page is generated",
+ "",
+ HOW_SECTION.format(
+ roots="`" + "`, `".join(SOURCE_ROOTS) + "`",
+ naive=len(naive & set(variables)),
+ total=len(variables),
+ ),
+ "",
+ "Regenerate it with:",
+ "",
+ "```bash",
+ "python3 scripts/generate_env_reference.py",
+ "```",
+ "",
+ ]
+ return "\n".join(lines)
+
+
+ def build(repo_root: Path = REPO_ROOT) -> tuple[str, dict[str, Variable], list[str]]:
+ """The page text, the inventory behind it, and any notes-table problems."""
+ variables = collect(repo_root)
+ problems = check_notes(variables)
+ if problems:
+ # Rendering an undocumented variable would raise a KeyError and bury the
+ # message that actually tells a contributor what to do.
+ return "", variables, problems
+ return render(variables, naive_line_scan(repo_root)), variables, problems
+
+
+ def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--check", action="store_true",
+ help="exit non-zero if the committed page is stale")
+ parser.add_argument("--stdout", action="store_true",
+ help="print the page instead of writing it")
+ parser.add_argument("--list", action="store_true",
+ help="print one variable name per line and nothing else")
+ args = parser.parse_args(argv)
+
+ page, variables, problems = build()
+
+ if args.list:
+ for name in variables:
+ print(name)
+ return 0
+
+ for problem in problems:
+ print(f"error: {problem}", file=sys.stderr)
+ if problems:
+ return 1
+
+ if args.stdout:
+ print(page, end="")
+ return 0
+
+ try:
+ relative = OUTPUT_PATH.relative_to(REPO_ROOT).as_posix()
+ except ValueError: # an output path outside the repo, as the tests use
+ relative = str(OUTPUT_PATH)
+ current = OUTPUT_PATH.read_text(encoding="utf-8") if OUTPUT_PATH.exists() else None
+ if args.check:
+ if current == page:
+ print(f"{relative} is up to date ({len(variables)} variables)")
+ return 0
+ print(f"error: {relative} is stale; run "
+ f"python3 scripts/generate_env_reference.py", file=sys.stderr)
+ return 1
+
+ if current == page:
+ print(f"{relative} unchanged ({len(variables)} variables)")
+ return 0
+ OUTPUT_PATH.write_text(page, encoding="utf-8")
+ print(f"wrote {relative} ({len(variables)} variables)")
+ return 0
+
+
+ if __name__ == "__main__":
+ raise SystemExit(main())
diff --cc src/browser_observation.py
index 82e680489,000000000..9eb2c547a
mode 100644,000000..100644
--- a/src/browser_observation.py
+++ b/src/browser_observation.py
@@@ -1,64 -1,0 +1,66 @@@
+"""Readable, bounded browser evidence without duplicate reference dictionaries."""
+import json
+import re
+
+
+def compact_browser_observation(value, budget=8000):
+ notices, pages = [], []
+
+ def visit(item):
+ if isinstance(item, list):
+ for child in item:
+ visit(child)
+ elif isinstance(item, dict):
+ if item.get('error'):
+ notices.append('Error: ' + str(item['error'])[:1000])
+ if item.get('exit_code') not in (None, 0):
+ notices.append('Exit code: ' + str(item['exit_code']))
+ if item.get('success') is False:
+ notices.append('Browser command failed.')
- snapshot = item.get('snapshot')
++ snapshot = item.get('snapshot') or item.get('text')
++ if item.get('title'):
++ notices.append('Title: ' + str(item['title']))
+ url = item.get('url') or item.get('origin')
+ if isinstance(snapshot, str) and snapshot.strip():
+ # Snapshot text already contains labels and refs in DOM order.
+ # The refs mapping repeats them and buries menus in raw JSON.
+ lines = [line for line in snapshot.splitlines()
+ if not re.fullmatch(r'\s*-?\s*generic(?:\s+\[ref=e\d+\])?:?\s*', line)]
+ pages.append(('URL: ' + str(url) + '\n' if url else '') + '\n'.join(lines))
+ elif url:
+ notices.append('URL: ' + str(url))
+ for key in ('result', 'output'):
+ if key in item:
+ visit(item[key])
+ elif isinstance(item, str):
+ try:
+ parsed = json.loads(item)
+ except (ValueError, TypeError):
+ # CLI status text precedes the JSON post-interaction state.
+ parts = re.split(r'\n\n\[(?:post-[^\]]+|page state after failed [^\]]+)\]\n', item)
+ if len(parts) > 1:
+ for part in parts:
+ visit(part)
+ elif item.strip():
+ notices.append(item.strip())
+ else:
+ if isinstance(parsed, (dict, list)):
+ visit(parsed)
+ else:
+ notices.append(str(parsed))
+
+ visit(value)
+ if not notices and not pages:
+ notices.append(json.dumps(value, ensure_ascii=False))
+ prefix = '\n'.join(dict.fromkeys(notices))[:2000]
+ body = pages[-1] if pages else ''
+ if not pages:
+ prefix = '\n'.join(dict.fromkeys(notices))
+ text = (prefix + '\n\n' + body).strip()
+ if len(text) <= budget:
+ return text
+ hint = '\n[Page observation shortened at line boundaries. Use a focused snapshot/read to inspect omitted content; do not guess refs.]\n'
+ room = budget - len(hint)
+ head = text[:room * 2 // 3].rsplit('\n', 1)[0]
+ tail = text[-room // 3:].split('\n', 1)[-1]
+ return head + hint + tail
diff --cc src/clean_agent_preview.py
index 9c6892014,0420b740b..83a448db1
--- a/src/clean_agent_preview.py
+++ b/src/clean_agent_preview.py
@@@ -2294,42 -1993,12 +2294,42 @@@ def compact_schemas(schemas, *, model=N
properties['message_id']['description'] = 'Exact RFC Message-ID header value, not a UID or result position.'
if 'folder' in properties:
properties['folder']['description'] = 'Folder from the selected result; omitting this reads INBOX, not other folders.'
+ elif function.get('name') == 'manage_calendar':
+ function['description'] = (
+ 'Calendar events. create_event requires summary and local_start={date,time} in the SAME call; '
+ 'omit uid (the server generates it). Copy the original date and clock time; '
+ 'the backend handles timezone conversion. Resolve dates from current local '
+ 'context; ask for a missing date rather than inventing one. '
+ 'update_event/delete_event use an existing uid. list_events uses start/end. '
+ 'reminder_minutes sets the event reminder; do not create a separate note. '
+ 'Set rrule only for explicit recurrence. Preserve tags on update unless requested. '
+ 'Use local_end={date,time} for the end. For all_day=true, omit time. '
+ 'When a timezone is stated, put it in timezone. Do not calculate UTC yourself.'
+ )
+ properties.pop('dtstart', None)
+ properties.pop('dtend', None)
+ for field in ('local_start', 'local_end'):
+ properties[field]['description'] = 'Original stated date and clock time. Do not convert timezones.'
+ properties[field]['properties']['date']['description'] = 'YYYY-MM-DD'
+ properties[field]['properties']['time']['description'] = 'HH:MM, original clock time; omit for all_day=true.'
+ properties['uid']['description'] = 'Existing event ID for update/delete only. Omit when creating.'
+ properties['timezone'] = {'type': 'string', 'description': 'Original stated zone: UTC, signed HH:MM offset or IANA name. Omit for user-local times or all-day dates.'}
elif function.get('name') == 'manage_notes':
- function['description'] = (function.get('description') or '') + ' add creates a new note; use update with id to change an existing note.'
+ function['description'] = (
+ 'Saved notes. Create a todo in ONE add call: note_type="checklist", '
+ 'checklist_items=[{text,done:false}], title only if requested (otherwise auto-dated). '
+ 'Keep tasks and stated times in item text, never title. No time conversion. '
- 'Freeform body: content. Existing note: update+id, never add. '
++ 'Freeform body: content. add creates a new note; update with id edits an existing note, never add. '
+ 'list supports label/archived; search by topic; view by id. Delete only on request. '
+ 'due_date sets a reminder, not an item time.'
+ )
if 'done' in properties:
properties['done']['description'] = 'For toggle_item: target checked state; omit to toggle.'
+ if 'index' in properties:
+ properties['index']['description'] = 'Required for toggle_item: 0-based item index. Use view if unknown.'
if 'checklist_items' in properties:
properties['checklist_items']['description'] = (
+ 'Required for to-do/checklist creation: one {text, done:false} per task. '
'For update, replaces the whole checklist; include unchanged items and their done state.'
)
elif function.get('name') == 'manage_skills':
@@@ -5339,6 -4626,6 +5339,8 @@@ async def stream_preview(*, endpoint_ur
required_artifacts = runtime_required_artifacts(
direct_user_text, client_runtime_context,
) if native_workspace_enabled else tuple()
++ if required_artifacts:
++ web_briefing_target = False
yield event({'type': 'turn_contract', **turn_contract.audit(), 'schema_mode': 'compact_contract_v5',
'native_workspace': native_workspace_enabled,
'required_artifacts': list(required_artifacts),
@@@ -7186,7 -6090,7 +7188,7 @@@
browser_access_blocked = (
canonical(actual_tool) == 'private_browser'
and not failed
-- and browser_observation_access_blocked(output)
++ and browser_observation_access_blocked(result.get('output') or result)
)
browser_page_missing = (
canonical(actual_tool) == 'private_browser'
diff --cc src/tool_capabilities.py
index 999e536e4,999e536e4..8fc6efefd
--- a/src/tool_capabilities.py
+++ b/src/tool_capabilities.py
@@@ -101,7 -101,7 +101,7 @@@ _register
result_integrity=ResultIntegrity.WORKSPACE_UNTRUSTED,
)
_register(
-- {"private_browser", "web_search", "youtube_tool"},
++ {"get_weather", "private_browser", "web_search", "youtube_tool"},
ToolEffect.BROKERED_NETWORK_READ,
result_integrity=ResultIntegrity.EXTERNAL_UNTRUSTED,
)
diff --cc src/turn_contract.py
index 17b333965,8682e259a..b04c58f17
--- a/src/turn_contract.py
+++ b/src/turn_contract.py
@@@ -955,7 -784,15 +955,16 @@@ def selected_tools_for_request(message
# Content words such as "reviews", "which", "highlights", or
# "final" must not become a public-Web lookup operation.
return None
+ if re.fullmatch(
+ _REQUEST_PREFIX + r"(?:which\s+search\s+(?:backend|provider)\s+am\s+i\s+on"
+ r"(?:\s+right\s+now)?|what\s+(?:default\s+)?time\s+filter\s+is\s+"
+ r"my\s+search\s+set\s+to(?:\s+by\s+default)?|show\s+me\s+the\s+whole\s+"
+ r"search\s+(?:settings?\s+)?group)[?!.]*",
+ text,
+ re.I,
+ ):
+ return frozenset({"manage_settings"})
+ web_lookup_fallback = False
if (
re.search(r"\b(?:look\s*up|search|find)\b", text, re.I)
and re.search(
diff --cc static/css/01-agent-chat.css
index 000000000,f06f3b050..7db3115a6
mode 000000,100644..100644
--- a/static/css/01-agent-chat.css
+++ b/static/css/01-agent-chat.css
@@@ -1,0 -1,7807 +1,7842 @@@
+ /* 01-agent-chat - part of the former static/style.css.
+ *
+ * The stylesheet is split by area, but the split is mechanical: rules were
+ * moved verbatim and NOT regrouped. The numeric prefix is the load order, and
+ * that order is what preserves the cascade. A rule sits in the file its
+ * original position fell into, so an area's rules are not all in its file and
+ * a file is not only that area's rules.
+ *
+ * Do not reorder the <link> tags in static/index.html, and do not move a rule
+ * between files: with 1,151 redeclarations and 1,886 !important in this
+ * cascade, either can change which declaration wins.
+ *
+ * static/index.html and the PRECACHE list in static/sw.js must agree on this
+ * order. tests/test_static_stylesheet_manifest.py and
+ * tests/test_css_computed_style_snapshot.py fail if that drifts.
+ */
+ #cookbook-modal .modal-content { height: 94vh; max-height: 94vh; }
+ .pdf-export-overlay .modal-content { max-height: 86vh; }
+
+ /* ── Background Patterns ── */
+
+ :root { --bg-effect-intensity: 1; }
+
+ /* Canvas-based effects — single source of truth for intensity */
+ #synapse-canvas, #rain-canvas, #constellations-canvas,
+ #perlin-flow-canvas, #petals-canvas, #sparkles-canvas,
+ #embers-canvas, #starfield-depth-canvas, #ascii-fireflies-background {
+ opacity: var(--bg-effect-intensity, 1);
+ }
+
+ body.bg-pattern-dots {
+ background-image: radial-gradient(color-mix(in srgb, var(--bg-effect-color, var(--fg)) calc(5% * var(--bg-effect-intensity, 1)), transparent) 1px, transparent 1px);
+ background-size: 20px 20px; background-attachment: fixed;
+ }
+ body.bg-pattern-synapse {
+ /* CSS grid as base, canvas pulses overlay */
+ background-image: linear-gradient(color-mix(in srgb, var(--bg-effect-color, var(--fg)) calc(3.5% * var(--bg-effect-intensity, 1)), transparent) 1px, transparent 1px),
+ linear-gradient(90deg, color-mix(in srgb, var(--bg-effect-color, var(--fg)) calc(3.5% * var(--bg-effect-intensity, 1)), transparent) 1px, transparent 1px);
+ background-size: 24px 24px; background-attachment: fixed;
+ }
+ body.memory-disabled.bg-pattern-synapse {
+ background-image: none;
+ }
+ body.memory-disabled #synapse-canvas {
+ display: none;
+ }
+ body.bg-pattern-perlin-flow,
+ body.bg-pattern-petals,
+ body.bg-pattern-sparkles {
+ /* canvas-only backgrounds */
+ }
+ body.bg-pattern-starfield-depth,
+ body.bg-pattern-ascii-fireflies {
+ /* rendered by their fixed background layer */
+ }
+ #ascii-fireflies-background {
+ position: fixed;
+ inset: 0;
+ z-index: 0;
+ box-sizing: border-box;
+ margin: 0;
+ padding: 14px 16px;
+ overflow: hidden;
+ pointer-events: none;
+ white-space: pre;
+ color: var(--bg-effect-color, var(--fg));
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+ font-size: 12px;
+ line-height: 1;
+ letter-spacing: 0;
+ }
+
+
+ /* ── Layout ── */
+
+ /* Top bar — session meta + incognito, single row */
+ .chat-top-bar {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ position: relative;
+ z-index: 2;
+ padding: 5px 0 0;
+ min-height: 25px;
+ box-sizing: border-box;
+ }
+ .chat-top-bar::after {
+ content: none;
+ }
+ body.sidebar-collapsed.hamburger-left .chat-top-bar {
+ padding-left: 38px;
+ }
+ body.sidebar-collapsed.hamburger-right .chat-top-bar {
+ padding-right: 38px;
+ }
+ .incognito-indicator {
+ position: absolute;
+ left: 12px;
+ top: 50%;
+ transform: translateY(-50%);
+ background: color-mix(in srgb, var(--accent) 12%, transparent);
+ border: 1px solid var(--accent);
+ color: var(--accent);
+ cursor: pointer;
+ padding: 4px;
+ width: 26px;
+ height: 26px;
+ box-sizing: border-box;
+ border-radius: 6px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ transition: opacity 0.15s, background 0.15s, left 0.15s;
+ z-index: 1;
+ opacity: 0.7;
+ }
+ body.sidebar-collapsed.hamburger-left .incognito-indicator {
+ left: 12px;
+ }
+ .incognito-indicator:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--accent) 20%, transparent);
+ }
+
+ .chat-new-btn {
+ position: absolute;
+ right: 7px;
+ top: 50%;
+ transform: translateY(-50%);
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.6;
+ cursor: pointer;
+ padding: 4px;
+ border-radius: 6px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ transition: opacity 0.08s, background 0.08s, left 0.15s, right 0.15s;
+ flex-shrink: 0;
+ z-index: 1;
+ }
+ .chat-new-btn:hover {
+ opacity: 1;
+ color: var(--accent);
+ }
+ /* Flip new-chat and incognito when sidebar is on the right */
+ body:has(.sidebar.right-side) .chat-new-btn {
+ right: auto;
+ left: 12px;
+ }
+ body:has(.sidebar.right-side) .incognito-indicator {
+ left: auto;
+ right: 12px;
+ }
+ body.sidebar-collapsed.hamburger-right .incognito-indicator {
+ right: 42px;
+ }
+
+ /* Session meta — sits at top of chat area, scrolls with content */
+ .chat-meta-overlay {
+ position: absolute;
+ left: 44px;
+ right: 44px;
+ top: 50%;
+ transform: translateY(calc(-50% - 2px));
+ font-size: 0.75em;
+ line-height: 1;
+ /* 70% mix keeps the chat title clearly above the WCAG AA 4.5:1
+ contrast threshold (40% only reached ~2.8:1). */
+ color: color-mix(in srgb, var(--fg) 70%, transparent);
+ white-space: nowrap;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 2px;
+ pointer-events: none;
+ min-width: 0;
+ max-width: calc(100% - 88px);
+ overflow: hidden;
+ }
+ .chat-meta-overlay > * {
+ pointer-events: auto;
+ flex-shrink: 0;
+ }
+ .chat-meta-overlay #current-meta {
+ display: inline-block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ cursor: pointer;
+ min-width: 0;
+ flex: 0 1 auto;
+ max-width: min(56vw, 520px);
+ line-height: 1.25;
+ }
+ .chat-top-bar:has(.incognito-indicator:not([style*="display:none"]):not([style*="display: none"])) .chat-meta-overlay {
+ left: 54px;
+ right: 44px;
+ max-width: calc(100% - 98px);
+ }
+ body:has(.sidebar.right-side) .chat-top-bar:has(.incognito-indicator:not([style*="display:none"]):not([style*="display: none"])) .chat-meta-overlay {
+ left: 44px;
+ right: 54px;
+ }
+ .chat-meta-overlay:hover {
+ color: color-mix(in srgb, var(--fg) 75%, transparent);
+ }
+ /* Offline model rows */
+ .models-row-offline {
+ opacity: 0.4;
+ pointer-events: none;
+ }
+ .models-row-offline .model-chat-btn {
+ pointer-events: auto;
+ }
+ /* Offline badge next to endpoint name */
+ .endpoint-offline-badge {
+ color: var(--danger, #f44);
+ font-size: 0.8em;
+ margin-left: 4px;
+ opacity: 0.7;
+ }
+ .chat-meta-overlay:empty,
+ .chat-meta-overlay:not(:has(#current-meta:not(:empty))) {
+ display: none;
+ }
+ .export-dropdown-wrap {
+ position: relative;
+ display: inline-flex;
+ flex-shrink: 0;
+ margin-left: -4px;
+ margin-right: -20px;
+ }
+ .export-dl-btn {
+ background: none; border: none;
+ color: inherit;
+ cursor: pointer;
+ padding: 4px 5px; border-radius: 4px;
+ display: flex; align-items: center;
+ transition: color 0.08s, background 0.08s;
+ }
+ .export-dl-btn > svg { color: var(--accent, var(--red)); }
+ .export-dl-btn:hover {
+ color: var(--accent);
+ background: color-mix(in srgb, var(--accent) 12%, transparent);
+ }
+ .export-dropdown-menu {
+ display: none;
+ position: fixed;
+ background: var(--panel); border: 1px solid var(--border);
+ border-radius: 8px; padding: 4px; min-width: 120px;
+ box-shadow: 0 4px 16px rgba(0,0,0,0.4);
+ z-index: 300;
+ color: var(--fg);
+ }
+ .export-dropdown-menu.open { display: block; }
+ .export-dropdown-item {
+ padding: 6px 8px; font-size: 11px; cursor: pointer;
+ border-radius: 6px; color: var(--fg); white-space: nowrap;
+ display: flex; align-items: center; gap: 10px;
+ transition: background 0.1s;
+ }
+ .export-dropdown-item:hover { background: color-mix(in srgb, var(--accent) 10%, transparent); }
+ .export-settings-text-only .dropdown-icon { display: none; }
+ #export-compact-btn {
+ display: none !important;
+ }
+ #export-compact-btn .dropdown-icon {
+ display: none;
+ }
+ .export-compact-pill {
+ display: inline;
+ padding: 0;
+ border: 0;
+ border-radius: 0;
+ background: transparent;
+ color: inherit;
+ line-height: inherit;
+ }
+ .export-dropdown-item .dropdown-icon {
+ width: 14px; height: 14px;
+ display: flex; align-items: center; justify-content: center;
+ flex-shrink: 0; opacity: 0.5;
+ }
+ /* On mobile the chat-header export dropdown was cramped — items
+ were 11px font with 6px padding. Bump to readable touch targets:
+ larger min-width, taller rows, bigger icons + text. */
+ @media (max-width: 768px) {
+ .export-dropdown-menu {
+ min-width: 200px;
+ padding: 6px;
+ border-radius: 10px;
+ }
+ .export-dropdown-item {
+ padding: 12px 14px;
+ font-size: 14px;
+ gap: 12px;
+ min-height: 44px;
+ }
+ #export-compact-btn {
+ margin: 5px 6px 7px;
+ min-height: 38px;
+ padding: 9px 14px;
+ }
+ .export-dropdown-item .dropdown-icon {
+ width: 18px; height: 18px; opacity: 0.7;
+ }
+ .export-dropdown-item .dropdown-icon svg {
+ width: 18px; height: 18px;
+ }
+ }
+ .sidebar {
+ width: 240px;
+ background: var(--sidebar-bg, var(--panel));
+ border-right: 1px solid var(--border);
+ transition: width 0.25s ease, opacity 0.2s ease, padding 0.25s ease;
+ display: flex;
+ flex-direction: column;
+ flex-shrink: 0;
+ overflow: hidden;
+ min-height: 0;
+ margin: 0;
+ padding: 0;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+ backdrop-filter: blur(10px);
+ border: 1px solid color-mix(in srgb, var(--fg) 11%, transparent);
+ position: relative;
+ }
+ .sidebar-resize-handle {
+ position: absolute;
+ top: 0;
+ right: -3px;
+ width: 6px;
+ height: 100%;
+ cursor: col-resize;
+ z-index: 10;
+ background: transparent;
+ }
+ .sidebar-resize-handle:hover,
+ .sidebar-resize-handle.dragging {
+ background: var(--accent);
+ opacity: 0.6;
+ }
+ .sidebar.right-side .sidebar-resize-handle {
+ right: auto;
+ left: -3px;
+ }
+ .sidebar.resizing {
+ transition: none;
+ user-select: none;
+ }
+ .sidebar.right-side {
+ order: 2;
+ margin: 0;
+ border-right: none;
+ border-left: 1px solid var(--border);
+ }
+ .sidebar.hidden {
+ /* !important so it beats the inline width init.js restores from storage —
+ otherwise the width never changes and only opacity animates, making the
+ collapse look instant. With this, width animates from the inline value
+ down to 0 via the .sidebar width transition. */
+ width: 0 !important;
+ padding: 0 !important;
+ border: none;
+ overflow: hidden;
+ opacity: 0;
+ }
+ /* ===== Sidebar User Bar ===== */
+ .sidebar-user-bar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 12px 12px;
+ flex-shrink: 0;
+ gap: 4px;
+ min-height: 48px;
+ }
+
+ .user-bar-left {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex: 1;
+ min-width: 0;
+ cursor: pointer;
+ padding: 6px 8px;
+ border-radius: 8px;
+ transition: background 0.15s;
+ }
+
+ .user-bar-left:hover {
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ }
+
+ .user-bar-avatar {
+ width: 24px;
+ height: 24px;
+ border-radius: 50%;
+ background: color-mix(in srgb, var(--fg) 12%, transparent);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 10px;
+ font-weight: 600;
+ color: var(--fg);
+ opacity: 0.7;
+ flex-shrink: 0;
+ text-transform: uppercase;
+ }
+
+ #user-bar-avatar { position: relative; left: -4px; }
+
+ .user-bar-name {
+ font-size: 9.75px;
+ font-weight: 500;
+ color: var(--fg);
+ opacity: 0.8;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .user-bar-actions {
+ display: flex;
+ gap: 1px;
+ flex-shrink: 0;
+ }
+
+ .user-bar-btn {
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.35;
+ cursor: pointer;
+ padding: 6px;
+ border-radius: 6px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ transition: opacity 0.12s, background 0.12s;
+ }
+
+ .user-bar-btn:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
+
+
+ .sidebar.hidden .sidebar-user-bar {
+ display: none;
+ }
+
+ /* Sticky sidebar header — logo, never scrolls */
+ .sidebar-header {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end; /* right-align when sidebar is on left */
+ gap: 8px;
+ padding: 15px 10px 0 40px; /* top padding aligns logo with fixed hamburger */
+ flex-shrink: 0;
+ min-height: 40px;
+ border: none !important;
+ box-shadow: none !important;
+ position: relative;
+ z-index: 3;
+ background: var(--sidebar-bg, var(--panel));
+ }
+ .sidebar-hamburger {
+ display: none !important; /* external #hamburger-btn is the only toggle */
+ }
+ .sidebar-inner {
+ flex: 1;
+ overflow-y: auto;
+ overflow-x: hidden;
+ overscroll-behavior-y: none;
+ scrollbar-width: none;
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+ padding: 10px 8px 8px;
+ min-height: 0;
+ transition: transform 0.3s cubic-bezier(0.25, 1, 0.5, 1);
+ }
+ .sidebar-brand {
+ display: flex;
+ align-items: center;
+ flex-shrink: 0;
+ min-height: 24px;
+ }
+ .sidebar-brand-title {
+ font-size: 1rem;
+ font-weight: 600;
+ line-height: 1.35;
+ color: var(--brand-color, var(--red));
+ white-space: nowrap;
+ user-select: none;
+ position: relative;
+ top: 0;
+ left: -10px;
+ }
+ .sidebar-sep {
+ display: none;
+ }
+ #sidebar-search-btn,
+ #sidebar-new-chat-btn {
+ margin: 0;
+ padding: 8px 8px;
+ }
+ #sessions-section {
+ margin-top: -1px;
+ min-height: 0;
+ flex: 0 0 auto;
+ }
+ /* Keep a large chat history from pushing the rest of the sidebar below
+ the fold. The chat rows scroll independently; the sections beneath
+ them stay reachable in the main sidebar scroll area. */
+ #sessions-section #session-list {
+ max-height: min(42vh, 420px);
+ flex: 0 0 auto;
+ overflow-y: auto;
+ overflow-x: hidden;
+ scrollbar-width: thin;
+ min-height: 0;
+ }
+ #tools-section {
+ margin-top: 1px;
+ }
+
+ @media (max-width: 768px) {
+ #sessions-section {
+ flex: 0 0 auto !important;
+ overflow: visible !important;
+ }
+ #sessions-section #session-list {
+ max-height: min(34vh, 300px) !important;
+ flex: 0 0 auto !important;
+ overflow-y: auto !important;
+ overflow-x: hidden !important;
+ }
+ }
+ #tools-section .list-item {
+ padding: 8px 8px;
+ }
+ .sidebar.right-side .sidebar-header {
+ justify-content: flex-start;
+ padding-left: 10px;
+ padding-right: 40px;
+ }
+ .sidebar.right-side .sidebar-inner {
+ padding: 8px;
+ }
+ .sidebar.right-side .sidebar-brand {
+ justify-content: flex-start;
+ padding: 2px 30px 4px 4px;
+ }
+ .sidebar.right-side .sidebar-brand-title {
+ margin-left: 10px;
+ }
+ /* Fixed hamburger — always visible, toggles sidebar */
+ .hamburger-btn {
+ position: fixed;
+ top: 12px;
+ left: 9px;
+ right: auto;
+ z-index: 210;
+ width: 30px;
+ height: 30px;
+ align-items: center;
+ justify-content: center;
+ background: none;
+ border: none;
+ color: var(--hamburger-color, var(--fg));
+ cursor: pointer;
+ opacity: 0.5;
+ -webkit-tap-highlight-color: transparent;
+ outline: none;
+ transition: opacity 0.15s;
+ padding: 0;
+ display: flex;
+ }
+ body.hamburger-right .hamburger-btn {
+ left: auto;
+ right: 9px;
+ }
+ .mobile-new-chat-btn {
+ display: none;
+ }
+ .hamburger-btn:hover {
+ opacity: 1;
+ }
+ /* Icon rail — mini sidebar that replaces the wide .sidebar when it's
+ hidden (mutually exclusive — see sidebar-layout.js:57). Fullscreen
+ panels reserve this strip of width via `left: var(--icon-rail-w)`
+ so the rail stays visible without needing a z-index hack (which
+ used to cover the fixed-position hamburger button). */
+ .icon-rail {
+ width: 48px;
+ flex-shrink: 0;
+ background: var(--panel);
+ border-right: 1px solid var(--border);
+ display: none;
+ flex-direction: column;
+ align-items: center;
+ padding: 48px 4px 8px 4px;
+ gap: 4px;
+ margin: 0;
+ position: relative;
+ box-sizing: border-box;
+ /* Allow hover labels (e.g. the rail-new-chat "New" tooltip) to extend
+ outside the 48px column. overflow:hidden was clipping them. */
+ overflow: visible;
+ }
+ body.sidebar-collapsed:not(.hamburger-only) .icon-rail,
+ html.ody-sidebar-mini .icon-rail {
+ display: flex;
+ }
+ html.ody-sidebar-mini .sidebar,
+ html.ody-sidebar-off .sidebar {
+ width: 0 !important;
+ min-width: 0 !important;
+ opacity: 0;
+ overflow: hidden;
+ pointer-events: none;
+ padding: 0 !important;
+ border: 0 !important;
+ }
+ html.ody-sidebar-off .icon-rail {
+ display: none !important;
+ }
+ .rail-resize-handle {
+ position: absolute;
+ top: 0;
+ right: -3px;
+ width: 6px;
+ height: 100%;
+ cursor: col-resize;
+ z-index: 10;
+ background: transparent;
+ }
+ .rail-resize-handle:hover,
+ .rail-resize-handle.dragging {
+ background: var(--accent);
+ opacity: 0.6;
+ }
+ .icon-rail.right-side .rail-resize-handle {
+ right: auto;
+ left: -3px;
+ }
+ .icon-rail.right-side {
+ order: 2;
+ margin: 0;
+ border-right: none;
+ border-left: 1px solid var(--border);
+ }
+ .icon-rail-divider {
+ width: 24px;
+ height: 1px;
+ background: var(--border);
+ margin: 4px 0;
+ }
+ .icon-rail-btn {
+ position: relative;
+ width: 34px;
+ height: 34px;
+ border: none;
+ background: transparent;
+ color: var(--accent, var(--red));
+ font-size: 16px;
+ border-radius: 6px;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0.5;
+ transition: opacity 0.08s, background 0.08s;
+ }
+ .rail-notes-badge {
+ position: absolute;
+ top: 1px;
+ right: 1px;
+ min-width: 14px;
+ height: 14px;
+ padding: 0 3px;
+ border-radius: 7px;
+ background: color-mix(in srgb, var(--accent) 85%, var(--bg));
+ color: var(--bg);
+ font-size: 9px;
+ font-weight: 700;
+ line-height: 14px;
+ text-align: center;
+ box-sizing: border-box;
+ pointer-events: none;
+ box-shadow: 0 0 0 1px var(--bg);
+ }
+ .rail-notes-badge.fired {
+ background: var(--red);
+ animation: rail-notes-pulse 1.6s ease-in-out infinite;
+ }
+ @keyframes rail-notes-pulse {
+ 0%, 100% { box-shadow: 0 0 0 1px var(--bg), 0 0 0 0 color-mix(in srgb, var(--red) 50%, transparent); }
+ 50% { box-shadow: 0 0 0 1px var(--bg), 0 0 0 4px color-mix(in srgb, var(--red) 15%, transparent); }
+ }
+ /* Main sidebar notes button — dot when a reminder has fired */
+ .tool-notes-dot {
+ display: inline-block;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--red);
+ /* Match the Deep Research badge: right-aligned (auto) with the same
+ 4px left nudge, so both sidebar buttons' dots line up identically. */
+ margin-left: auto;
+ position: relative;
+ left: -4px;
+ flex-shrink: 0;
+ align-self: center;
+ animation: rail-notes-pulse 1.6s ease-in-out infinite;
+ pointer-events: none;
+ }
+ /* Individual card — subtle accent border tint when a reminder has fired */
+ .note-card.note-card-reminder-due .note-card-reminder {
+ background: color-mix(in srgb, var(--red) 22%, transparent);
+ color: var(--red);
+ font-weight: 600;
+ }
+ .icon-rail-btn:hover { opacity: 1; background: color-mix(in srgb, var(--accent) 12%, transparent); }
+ .icon-rail-btn.active-section { opacity: 1; background: color-mix(in srgb, var(--color-accent) 15%, transparent); }
+ /* Unified "minimized" indicator for any rail/sidebar button whose modal is held open */
+ .rail-minimized { position: relative; }
+ .rail-minimized::after {
+ content: ''; position: absolute;
+ /* Default for inline spans like #email-section-title — sit just to the
+ right of the element so it never overlaps the icon. */
+ top: 50%; right: -10px; transform: translateY(-50%);
+ width: 6px; height: 6px; border-radius: 50%;
+ background: var(--accent, var(--red));
+ box-shadow: 0 0 0 2px var(--bg);
+ pointer-events: none;
+ animation: rail-min-pulse 2s ease-in-out infinite;
+ }
+ /* Compact icon-rail buttons: top-right corner of the icon */
+ .icon-rail-btn.rail-minimized::after { top: 4px; right: 4px; transform: none; }
+ /* Sidebar list-items are wider — anchor right-aligned vertically centered */
+ .list-item.rail-minimized::after { top: 50%; right: 8px; transform: translateY(-50%); }
+ #tool-memory-btn.rail-minimized::after { right: 12px; }
+ /* Per-user nudge: the listed tools' minimized dot sits 2px further
+ in from the right edge so it doesn't look glued to the border. */
+ #tool-theme-btn.rail-minimized::after,
+ #tool-tasks-btn.rail-minimized::after,
+ #tool-notes-btn.rail-minimized::after,
+ #tool-library-btn.rail-minimized::after,
+ #tool-gallery-btn.rail-minimized::after,
+ #tool-compare-btn.rail-minimized::after,
+ #tool-calendar-btn.rail-minimized::after { right: 12px; }
+ @media (max-width: 768px) {
+ /* On mobile the list-items are taller (touch-sized), so the tabbed-down
+ pulsing dot reads a hair low and right. Email uses its own dot and is
+ already aligned — only the tool list-item dots need the nudge:
+ 4px left (right 8 → 12) and 2px up. */
+ .list-item.rail-minimized::after {
+ right: 13px;
+ transform: translateY(calc(-50% - 2px));
+ }
+ #tool-memory-btn.rail-minimized::after { right: 17px; }
+ }
+ @keyframes rail-min-pulse {
+ 0%,100% { opacity: 1; }
+ 50% { opacity: 0.4; }
+ }
+ /* Compact minimize button for modal headers — matches the close
+ button's round control so the two read as a paired set. The
+ header's h4 carries margin-right:auto, which groups minimize + close
+ on the right; this button just needs a small gap before close. */
+ .modal-minimize-btn {
+ background: transparent;
+ color: color-mix(in srgb, var(--fg) 58%, transparent);
+ border: 1px solid transparent;
+ cursor: pointer;
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ margin-left: 0;
+ margin-right: 4px;
+ line-height: 1;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 999px;
+ flex-shrink: 0;
+ transition: background 0.15s, color 0.15s;
+ }
+ .modal-minimize-btn:hover {
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ border-color: color-mix(in srgb, var(--fg) 12%, transparent);
+ color: var(--fg);
+ }
+ .modal-minimize-btn svg {
+ transform: translateY(2px);
+ }
+ .modal.modal-minimized { display: none !important; }
+ /* Window tile snap ghost (desktop only) */
+ #tile-ghost {
+ position: fixed; pointer-events: none; z-index: 9000;
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ border: 2px solid color-mix(in srgb, var(--accent, var(--red)) 55%, transparent);
+ border-radius: 8px;
+ opacity: 0; transform: scale(0.96);
+ transition: left 0.12s ease, top 0.12s ease, width 0.12s ease, height 0.12s ease, opacity 0.12s, transform 0.12s;
+ }
+ #tile-ghost.visible { opacity: 1; transform: scale(1); }
+ /* Bottom dock — chip per minimized modal */
+ #minimized-dock {
+ position: fixed; bottom: var(--composer-clearance, 12px); left: 50%; transform: translateX(-50%);
+ display: flex; gap: 6px; flex-wrap: wrap;
+ max-width: calc(100vw - 24px);
+ padding: 4px;
+ z-index: 100;
+ pointer-events: none;
+ }
+ .minimized-dock-chip {
+ pointer-events: auto;
+ display: inline-flex; align-items: center; gap: 6px;
+ padding: 6px 8px 6px 10px;
+ background: var(--panel, var(--bg));
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ color: var(--fg); font-family: inherit; font-size: 12px;
+ cursor: grab; touch-action: none; user-select: none;
+ box-shadow: 0 4px 14px rgba(0,0,0,0.35);
+ transition: transform 0.28s cubic-bezier(0.34, 1.56, 0.64, 1), background 0.15s, border-color 0.15s;
+ animation: dock-chip-in 0.25s cubic-bezier(0.34, 1.56, 0.64, 1) both;
+ }
+ .minimized-dock-chip:hover {
+ background: color-mix(in srgb, var(--accent, var(--red)) 12%, var(--panel, var(--bg)));
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 40%, var(--border));
+ }
+ .minimized-dock-chip:active { cursor: grabbing; }
+ .minimized-dock-chip.dragging {
+ cursor: grabbing; z-index: 1000;
+ box-shadow: 0 8px 24px rgba(0,0,0,0.55);
+ transition: none;
+ opacity: 0.95;
+ }
+ /* Whole-dock drag (grabbed an edge chip) */
+ #minimized-dock.dock-dragging { cursor: grabbing; }
+ #minimized-dock.dock-dragging .minimized-dock-chip {
+ transition: none;
+ box-shadow: 0 8px 24px rgba(0,0,0,0.45);
+ }
+ /* Subtle visual cue that edge chips drag the whole dock */
+ #minimized-dock .minimized-dock-chip:first-child:not(:only-child),
+ #minimized-dock .minimized-dock-chip:last-child:not(:only-child) {
+ box-shadow: 0 4px 14px rgba(0,0,0,0.35),
+ inset 0 0 0 1px color-mix(in srgb, var(--accent, var(--red)) 25%, transparent);
+ }
+ .minimized-dock-chip svg { opacity: 0.7; flex-shrink: 0; }
+ .minimized-dock-label { white-space: nowrap; }
+
+ /* Mobile: chips are icon-only round pills. Tap to restore, drag toward
+ the trash zone at top-center to close. touch-action:none lets the
+ pointermove listener claim the gesture instead of the page scroll. */
+ @media (max-width: 768px) {
+ .minimized-dock-chip {
+ width: 40px; height: 40px;
+ padding: 0 !important;
+ border-radius: 50% !important;
+ justify-content: center;
+ position: relative;
+ overflow: visible;
+ touch-action: none;
+ }
+ .minimized-dock-chip svg { width: 18px; height: 18px; opacity: 0.9; }
+ .minimized-dock-label,
+ .minimized-dock-x { display: none !important; }
+ .minimized-dock-chip.chip-free-drag {
+ box-shadow: 0 8px 22px rgba(0,0,0,0.55),
+ 0 0 0 2px color-mix(in srgb, var(--accent, var(--red)) 50%, transparent) !important;
+ }
+ /* Long-press hint — chip swells and settles while the detach timer
+ counts down so the user feels feedback before the bubble peels out
+ of the chain. Returns to scale(1) at the end so there's no visual
+ jump when the timer fires and the chip becomes a free-drag puck. */
+ .minimized-dock-chip.chip-long-press {
+ background:
+ radial-gradient(circle at 30% 25%, color-mix(in srgb, #fff 28%, transparent), transparent 36%),
+ linear-gradient(135deg,
+ color-mix(in srgb, var(--accent, var(--red)) 34%, var(--panel, var(--bg))),
+ color-mix(in srgb, #7dd3fc 26%, var(--panel, var(--bg))) 52%,
+ color-mix(in srgb, #f0abfc 22%, var(--panel, var(--bg))));
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 72%, #fff 12%) !important;
+ animation: chip-long-press-pulse 0.82s ease-in-out infinite;
+ z-index: 10030;
+ }
+ .minimized-dock-chip.chip-long-press::before {
+ content: '';
+ position: absolute;
+ inset: -96px;
+ border-radius: inherit;
+ background:
+ radial-gradient(circle,
+ color-mix(in srgb, var(--accent, var(--red)) 42%, transparent) 0 18%,
+ color-mix(in srgb, #7dd3fc 34%, transparent) 34%,
+ color-mix(in srgb, #f0abfc 30%, transparent) 50%,
+ transparent 72%);
+ pointer-events: none;
+ z-index: -1;
+ animation: chip-long-press-ripple 0.82s ease-out infinite;
+ }
+ @keyframes chip-long-press-pulse {
+ 0%, 100% { transform: scale(1); }
+ 50% { transform: scale(1.42);
+ box-shadow: 0 14px 42px rgba(0,0,0,0.66),
+ 0 0 0 16px color-mix(in srgb, var(--accent, var(--red)) 42%, transparent),
+ 0 0 72px color-mix(in srgb, #7dd3fc 44%, transparent),
+ 0 0 118px color-mix(in srgb, #f0abfc 32%, transparent); }
+ }
+ @keyframes chip-long-press-ripple {
+ 0% { opacity: 0.92; transform: scale(0.08); }
+ 72% { opacity: 0.28; transform: scale(3.6); }
+ 100% { opacity: 0; transform: scale(5.4); }
+ }
+ /* Chip whose modal is currently open — accent ring so the user can
+ tell at a glance which floating bubble belongs to the visible
+ modal. Tap it to minimize. */
+ .minimized-dock-chip.chip-active {
+ border-color: var(--accent, var(--red)) !important;
+ box-shadow: 0 4px 14px rgba(0,0,0,0.35),
+ 0 0 0 2px color-mix(in srgb, var(--accent, var(--red)) 35%, transparent);
+ }
+ .minimized-dock-chip.chip-active svg { opacity: 1; }
+ }
+ /* Magnetic close zone — slides in from the side opposite the chip's
+ starting position so it never overlaps the dock. Always accent
+ color, larger than the chips, snappy spring transition. */
+ #dock-trash-zone {
+ position: fixed;
+ left: 50%;
+ width: 88px; height: 88px;
+ border-radius: 50%;
+ --trash-zone-color: var(--accent, var(--red, #e53935));
+ background: var(--trash-zone-color);
+ color: #fff;
+ display: flex; align-items: center; justify-content: center;
+ pointer-events: none;
+ opacity: 0;
+ z-index: 9000;
+ box-shadow: 0 8px 28px color-mix(in srgb, var(--trash-zone-color) 55%, transparent);
+ transition: opacity 0.18s ease,
+ transform 0.26s cubic-bezier(0.34, 1.56, 0.64, 1),
+ box-shadow 0.18s ease;
+ }
+ /* Off-screen start position depends on which side the chip is on so
+ the X slides in from the opposite edge with a snappy overshoot. */
+ #dock-trash-zone[data-side="top"] { transform: translateX(-50%) translateY(-180%) scale(0.7); }
+ #dock-trash-zone[data-side="bottom"] { transform: translateX(-50%) translateY(180%) scale(0.7); }
+ #dock-trash-zone.visible {
+ opacity: 1;
+ transform: translateX(-50%) translateY(0) scale(1);
+ }
+ #dock-trash-zone.engaged {
+ transform: translateX(-50%) translateY(0) scale(var(--trash-zone-scale, 1.22));
+ box-shadow: 0 0 0 14px color-mix(in srgb, var(--trash-zone-color) 22%, transparent),
+ 0 12px 36px color-mix(in srgb, var(--trash-zone-color) 60%, transparent);
+ animation: trash-zone-breathe 1.35s ease-in-out infinite;
+ }
+ /* Whirlpool ring — fades in when chip is in capture range and spins
+ continuously, then bursts on drop. */
+ #dock-trash-zone .whirlpool {
+ position: absolute; inset: -8px;
+ border-radius: 50%;
+ border: 2px solid transparent;
+ border-top-color: color-mix(in srgb, var(--trash-zone-color) 95%, transparent);
+ border-right-color: color-mix(in srgb, var(--trash-zone-color) 65%, transparent);
+ border-bottom-color: color-mix(in srgb, var(--trash-zone-color) 30%, transparent);
+ opacity: 0;
+ pointer-events: none;
+ animation: whirlpool-spin 0.85s linear infinite;
+ transition: opacity 0.15s ease;
+ }
+ #dock-trash-zone.engaged .whirlpool { opacity: 1; }
+ #dock-trash-zone.dropping .whirlpool {
+ opacity: 1;
+ animation: whirlpool-burst 0.36s cubic-bezier(0.4, 0, 0.2, 1) forwards;
+ }
+ /* When a chip is swirling into the trash X, its inline `rotate(720deg)`
+ drags every child + ::after badge along with it — the count/dot pill
+ spinning looks chaotic. Fade those out fast at the start of the close
+ so visually only the icon glyph rotates. */
+ .minimized-dock-chip.chip-trashing > :not(svg),
+ .minimized-dock-chip.chip-trashing::after,
+ .minimized-dock-chip.chip-trashing::before {
+ opacity: 0 !important;
+ transition: opacity 0.16s ease-out !important;
+ }
+ @keyframes whirlpool-spin { to { transform: rotate(360deg); } }
+ @keyframes trash-zone-breathe {
+ 0%, 100% { box-shadow: 0 0 0 10px color-mix(in srgb, var(--trash-zone-color) 16%, transparent), 0 10px 30px color-mix(in srgb, var(--trash-zone-color) 48%, transparent); }
+ 50% { box-shadow: 0 0 0 16px color-mix(in srgb, var(--trash-zone-color) 25%, transparent), 0 14px 38px color-mix(in srgb, var(--trash-zone-color) 68%, transparent); }
+ }
+ @keyframes whirlpool-burst {
+ 0% { transform: rotate(0deg) scale(1); opacity: 1; }
+ 60% { transform: rotate(540deg) scale(1.5); opacity: 0.6; }
+ 100% { transform: rotate(900deg) scale(2.2); opacity: 0; }
+ }
+
+ /* Email chip badges:
+ - email-lib-modal chip: "1" badge when an email is expanded
+ inside (JS sets data-has-expanded).
+ - email-reader-* chips: auto-numbered 1, 2, 3 … via CSS counter,
+ so multiple opened-email windows are visually distinguishable. */
+ .minimized-dock-chip[data-modal-id="email-lib-modal"],
+ .minimized-dock-chip[data-modal-id^="email-reader-"] {
+ position: relative;
+ }
+ .minimized-dock-chip[data-modal-id^="email-reader-"][data-tab-num]::after {
+ content: attr(data-tab-num);
+ position: absolute;
+ top: -4px;
+ right: -4px;
+ min-width: 16px;
+ height: 16px;
+ padding: 0 4px;
+ background: var(--accent, var(--red));
+ color: #fff;
+ font-size: 9px;
+ font-weight: 700;
+ line-height: 16px;
+ text-align: center;
+ border-radius: 8px;
+ box-shadow: 0 0 0 2px var(--bg);
+ pointer-events: none;
+ }
+ .minimized-dock-chip[data-modal-id="email-lib-modal"][data-email-unread-label]::after {
+ content: attr(data-email-unread-label);
+ position: absolute;
+ top: -6px;
+ right: 10px;
+ height: 16px;
+ padding: 0 6px;
+ background: var(--accent, var(--red));
+ color: #fff;
+ font-size: 9px;
+ font-weight: 700;
+ line-height: 16px;
+ white-space: nowrap;
+ border-radius: 8px;
+ box-shadow: 0 0 0 2px var(--bg);
+ pointer-events: none;
+ }
+
+ .minimized-dock-x {
+ display: inline-flex; align-items: center; justify-content: center;
+ width: 16px; height: 16px; border-radius: 50%;
+ font-size: 14px; line-height: 1; opacity: 0.4;
+ margin-left: 3px;
+ }
+ .minimized-dock-x:hover { opacity: 1; background: color-mix(in srgb, var(--fg) 12%, transparent); }
+ @keyframes dock-chip-in {
+ from { opacity: 0; transform: translateY(20px) scale(0.85); }
+ to { opacity: 1; transform: translateY(0) scale(1); }
+ }
+ .rail-new-chat svg { transition: transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1); }
+ .rail-new-chat:hover svg { transform: rotate(90deg); }
+ /* Sleek hover labels for the mini sidebar. Use a real child span instead
+ of ::before/::after so status dots and minimized indicators keep working. */
+ .rail-hover-label {
+ position: absolute;
+ left: 100%;
+ top: 50%;
+ margin-left: 6px;
+ transform: translateY(-50%) translateX(-6px);
+ opacity: 0;
+ pointer-events: none;
+ white-space: nowrap;
+ font-size: 10px;
+ font-weight: 600;
+ color: var(--fg);
+ background: var(--panel);
+ padding: 2px 6px;
+ border-radius: 4px;
+ box-shadow: 0 2px 6px rgba(0,0,0,0.25);
+ z-index: 20;
+ transition: opacity 0.25s ease, transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ .icon-rail-btn:hover .rail-hover-label {
+ opacity: 1;
+ transform: translateY(-50%) translateX(0);
+ }
+ #rail-admin,
+ #rail-settings { color: var(--fg); }
+ .rail-separator { width: 20px; height: 1px; background: var(--border); margin: 4px auto; }
+ .rail-dynamic {
+ position: relative;
+ }
+ .rail-dynamic::after {
+ content: '';
+ position: absolute;
+ bottom: 2px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 4px;
+ height: 4px;
+ border-radius: 50%;
+ background: var(--accent, var(--red));
+ opacity: 0.7;
+ }
+ /* ── Sidebar sections (flat layout) ── */
+ .section { padding: 0; border: none; background: none; border-radius: 0; box-shadow: none; margin: 0; }
+
+ /* Section header row — identical sizing to .list-item */
+ .section-header-flex {
+ display: flex; align-items: center; gap: 6px;
+ padding: 8px 8px; margin: 1px 0; border-radius: 4px;
+ background: transparent; cursor: pointer;
+ transition: background 0.08s;
+ height: 29px;
+ box-sizing: border-box;
+ }
+ .section-header-flex:hover { background: color-mix(in srgb, var(--red) 8%, transparent); }
+ .section-header-flex::after { content: none; }
+ .section-header-flex h4::before { content: none; }
+
+ /* Section title text — same font as .list-item .grow */
+ .section-header-flex h4,
+ .section-header-flex .section-title {
+ flex: 1; cursor: pointer; user-select: none;
+ display: flex; align-items: center; gap: 6px;
+ margin: 0; padding: 0; border: none;
+ font-size: 10px; font-weight: 400; font-family: inherit;
+ /* 1.3 (not 1) so Fira Code's tall glyph box isn't vertically clipped in
+ Chromium/Edge — mirrors the .list-item fix. The title is flex-centred
+ in a fixed-height (29px) header, so this adds headroom without reflow. */
+ line-height: 1.3; letter-spacing: 0; text-transform: none;
+ color: var(--fg);
+ }
+ .section-icon,
+ .sidebar-action-icon {
+ flex-shrink: 0;
+ stroke: var(--accent, var(--red));
+ position: relative;
+ left: -1px;
+ color: var(--accent, var(--red));
+ }
+ /* Shared notification dot for sidebar section titles. Single source of
+ truth so chats / email / assistant / future-section dots all sit at
+ the same offset from their label. */
+ .sidebar-notif-dot {
+ display: inline-block;
+ width: 6px;
+ height: 6px;
+ /* Push to the right edge of the flex section-title so chats / email
+ / assistant dots all line up vertically in the same column
+ instead of trailing right after each (differently-sized) label. */
+ margin-left: auto;
+ border-radius: 50%;
+ background: var(--accent, var(--red));
+ flex-shrink: 0;
+ vertical-align: middle;
+ }
+ /* The email notification gets a soft breathing glow so new-mail catches
+ the eye without being shouty. Vertical alignment stays with the
+ inherited .sidebar-notif-dot rule so it lines up with chats/assistant. */
+ #email-unread-dot.sidebar-notif-dot {
+ animation: email-notif-breathe 2.2s ease-in-out infinite;
+ /* Nudge in from the far-right edge so it doesn't crowd the corner. */
+ margin-right: 4px;
+ /* Tiny vertical nudge to center with the email label. */
+ position: relative;
+ top: 0.1px;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ #email-unread-dot.sidebar-notif-dot { animation: none; }
+ }
+ @media (max-width: 768px) {
+ /* Nudge the sidebar notification dot up 1px on mobile so it lines
+ up with the bigger section titles. vertical-align:middle drifts
+ a hair low against the larger touch-friendly text. */
+ .sidebar-notif-dot {
+ position: relative;
+ top: -1px;
+ }
+ /* Cookbook's sidebar status dot carries an inline top:-1px, so override
+ with the ID + !important to nudge it 2px left / 1px up on mobile. */
+ #cookbook-notif-dot {
+ left: -1px !important;
+ top: -2px !important;
+ }
+ }
+ #sidebar-new-chat-btn svg {
+ transition: transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ #sidebar-new-chat-btn:hover svg {
+ transform: rotate(90deg);
+ }
+
+ /* Sort/select buttons in header — compact */
+ .section-header-flex > div { display: flex; align-items: center; gap: 2px; }
+ .section-header-btn {
+ all: unset;
+ cursor: pointer; opacity: 0.4; padding: 1px 3px; border-radius: 4px;
+ display: inline-flex; align-items: center; justify-content: center;
+ transition: opacity 0.08s, background 0.08s;
+ }
+ .section-header-btn:hover { opacity: 1; background: color-mix(in srgb, var(--fg) 7%, transparent); }
+ .section-header-btn.active { opacity: 0.9; color: var(--accent); }
+ .section-header-btn svg { width: 12px; height: 12px; }
+ #session-sort-btn { transform: translateX(2px); }
+
+ /* Chats library — grid icon, hover-reveal so the header only toggles
+ collapse. Uses !important to win over .list-item-plus-btn's
+ opacity:1!important (the email-style plus button forces always-on,
+ which we don't want here — the manage button should fade until the
+ user actually hovers the section). */
+ #sessions-section .chats-manage-btn {
+ opacity: 0.4 !important;
+ transition: opacity 0.12s, background 0.08s;
+ }
+ #sessions-section .section-header-flex:hover .chats-manage-btn,
+ #sessions-section .chats-manage-btn:hover,
+ #sessions-section .chats-manage-btn:focus-visible {
+ opacity: 0.85 !important;
+ }
+ #sessions-section .chats-manage-btn:hover,
+ #sessions-section .chats-manage-btn:focus-visible {
+ opacity: 1 !important;
+ }
+ /* No hover background on the Chats manage button — the inherited
+ section-header-btn rule was painting a tinted box behind the
+ 'manage' label as it slid in. */
+ #sessions-section .chats-manage-btn,
+ #sessions-section .chats-manage-btn:hover,
+ #sessions-section .chats-manage-btn:focus-visible {
+ background: transparent !important;
+ }
+ @media (hover: none) {
+ #sessions-section .chats-manage-btn { opacity: 0.35 !important; }
+ #sessions-section .chats-manage-btn:active { opacity: 1 !important; }
+ }
+ /* Pull the 'manage' label out of email's absolute-positioning trick
+ so it sits in the flex flow and expands the button's clickable
+ area as it slides in. Otherwise hovering the visible 'manage'
+ text would actually be outside the button's bounding box. */
+ #sessions-section .chats-manage-btn .list-item-plus-label {
+ position: static;
+ transform: none;
+ max-width: 0;
+ overflow: hidden;
+ padding-right: 0;
+ transition: max-width 0.2s ease, opacity 0.18s ease, padding-right 0.18s ease;
+ }
+ #sessions-section .chats-manage-btn:hover .list-item-plus-label,
+ #sessions-section .chats-manage-btn:focus-visible .list-item-plus-label,
+ #sessions-section .section-header-flex:hover .chats-manage-btn .list-item-plus-label {
+ max-width: 80px;
+ padding-right: 4px;
+ }
+
+ /* Collapse chevron */
+ .section-collapse-btn {
+ all: unset;
+ cursor: pointer; display: inline-flex; align-items: center; padding: 0 2px; border-radius: 4px;
+ }
+ .section-collapse-btn:hover { background: color-mix(in srgb, var(--fg) 8%, transparent); }
+ .section-collapse-chevron { display: inline-flex; opacity: 0.4; transition: transform 0.2s, opacity 0.15s; }
+ .section-collapse-btn:hover .section-collapse-chevron { opacity: 0.6; }
+ .section.collapsed .section-collapse-chevron { transform: rotate(-90deg); opacity: 0.4; }
+ .section-header-flex:has(.section-header-btn) .section-collapse-btn { display: none; }
+ .section.collapsed .section-collapse-btn { display: inline-flex !important; }
+
+ /* Collapsed state */
+ .section.collapsed > *:not(h4):not(.section-title):not(.section-header-flex) { display: none !important; }
+ .section.collapsed .section-header-flex { margin-bottom: 0; }
+ .section.collapsed .section-header-btn { display: none; }
+ .section.collapsed { cursor: pointer; }
+
+ /* Domino expand: every time a section goes from .collapsed → open
+ (toggleCollapse in section-management.js adds .section-just-expanded
+ for ~700ms), the .list-item children cascade in one after another,
+ same feel as the chat input's tools menu. Each row springs in
+ from a tiny offset below + scaled-down, staggered by nth-child. */
+ .section.section-just-expanded :is(.list-item, .models-row, .date-section-header) {
+ animation: section-domino-in 0.36s cubic-bezier(0.22, 1.61, 0.36, 1) backwards;
+ }
+ .section.section-just-expanded :is(.list-item, .models-row, .date-section-header):nth-child(1) { animation-delay: 0.04s; }
+ .section.section-just-expanded :is(.list-item, .models-row, .date-section-header):nth-child(2) { animation-delay: 0.08s; }
+ .section.section-just-expanded :is(.list-item, .models-row, .date-section-header):nth-child(3) { animation-delay: 0.12s; }
+ .section.section-just-expanded :is(.list-item, .models-row, .date-section-header):nth-child(4) { animation-delay: 0.16s; }
+ .section.section-just-expanded :is(.list-item, .models-row, .date-section-header):nth-child(5) { animation-delay: 0.20s; }
+ .section.section-just-expanded :is(.list-item, .models-row, .date-section-header):nth-child(6) { animation-delay: 0.24s; }
+ .section.section-just-expanded :is(.list-item, .models-row, .date-section-header):nth-child(7) { animation-delay: 0.28s; }
+ .section.section-just-expanded :is(.list-item, .models-row, .date-section-header):nth-child(8) { animation-delay: 0.32s; }
+ .section.section-just-expanded :is(.list-item, .models-row, .date-section-header):nth-child(9) { animation-delay: 0.36s; }
+ .section.section-just-expanded :is(.list-item, .models-row, .date-section-header):nth-child(10) { animation-delay: 0.40s; }
+ .section.section-just-expanded :is(.list-item, .models-row, .date-section-header):nth-child(11) { animation-delay: 0.44s; }
+ .section.section-just-expanded :is(.list-item, .models-row, .date-section-header):nth-child(12) { animation-delay: 0.48s; }
+ @keyframes section-domino-in {
+ 0% { opacity: 0; transform: translateY(8px) translateX(-4px) scale(0.92); }
+ 60% { opacity: 1; }
+ 100% { opacity: 1; transform: translateY(0) translateX(0) scale(1); }
+ }
+
+ /* Domino collapse: when toggleCollapse goes open → closed, JS adds
+ .section-just-collapsing for ~530ms before flipping in .collapsed.
+ During that window the items fade/slide DOWN one after another so
+ you see them peel off instead of vanishing as a block. Uses
+ nth-last-child so the BOTTOM item leaves first and the cascade
+ rolls upward — mirrors the "stacked deck" feeling of the open
+ animation reversed. */
+ .section.section-just-collapsing :is(.list-item, .models-row, .date-section-header) {
+ animation: section-domino-out 0.22s ease-in forwards;
+ }
+ .section.section-just-collapsing :is(.list-item, .models-row, .date-section-header):nth-last-child(1) { animation-delay: 0.00s; }
+ .section.section-just-collapsing :is(.list-item, .models-row, .date-section-header):nth-last-child(2) { animation-delay: 0.025s; }
+ .section.section-just-collapsing :is(.list-item, .models-row, .date-section-header):nth-last-child(3) { animation-delay: 0.05s; }
+ .section.section-just-collapsing :is(.list-item, .models-row, .date-section-header):nth-last-child(4) { animation-delay: 0.075s; }
+ .section.section-just-collapsing :is(.list-item, .models-row, .date-section-header):nth-last-child(5) { animation-delay: 0.10s; }
+ .section.section-just-collapsing :is(.list-item, .models-row, .date-section-header):nth-last-child(6) { animation-delay: 0.125s; }
+ .section.section-just-collapsing :is(.list-item, .models-row, .date-section-header):nth-last-child(7) { animation-delay: 0.15s; }
+ .section.section-just-collapsing :is(.list-item, .models-row, .date-section-header):nth-last-child(8) { animation-delay: 0.175s; }
+ .section.section-just-collapsing :is(.list-item, .models-row, .date-section-header):nth-last-child(9) { animation-delay: 0.20s; }
+ .section.section-just-collapsing :is(.list-item, .models-row, .date-section-header):nth-last-child(10) { animation-delay: 0.225s; }
+ .section.section-just-collapsing :is(.list-item, .models-row, .date-section-header):nth-last-child(11) { animation-delay: 0.25s; }
+ .section.section-just-collapsing :is(.list-item, .models-row, .date-section-header):nth-last-child(12) { animation-delay: 0.275s; }
+ @keyframes section-domino-out {
+ 0% { opacity: 1; transform: translateY(0) translateX(0) scale(1); }
+ 100% { opacity: 0; transform: translateY(6px) translateX(-3px) scale(0.94); }
+ }
+
+ .row { display:flex; gap:6px; align-items:center; }
+ .list-item:hover,
+ .models-row:hover {
+ background: color-mix(in srgb, var(--red) 8%, transparent);
+ border-color: var(--red);
+ }
+ #models.models-refreshing {
+ opacity: 0.72;
+ transition: opacity 0.16s ease;
+ }
+ /* Disabled tool — dimmed to signal its feature is turned off globally */
+ .list-item.tool-disabled {
+ opacity: 0.4;
+ }
+ .list-item.tool-disabled:hover {
+ opacity: 0.7;
+ }
+ /* Session bulk select mode */
+ .session-bulk-bar {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 8px;
+ border-bottom: 1px solid var(--border);
+ background: var(--sidebar-bg, var(--panel));
+ position: sticky;
+ top: 0;
+ z-index: 3;
+ font-size: 11px;
+ }
+ .session-bulk-bar.hidden { display: none; }
+ #session-select-all-dot {
+ display: inline-block;
+ position: relative;
+ top: -2px;
+ }
+ .session-bulk-btn {
+ background: none;
+ border: none;
+ border-radius: 4px;
+ color: var(--fg);
+ padding: 4px;
+ font-family: inherit;
+ cursor: pointer;
+ opacity: 0.4;
+ transition: opacity 0.1s;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .session-bulk-btn:hover { opacity: 1; }
+ .session-bulk-btn-danger { color: var(--red); opacity: 0.5; }
+ .session-bulk-btn-danger:hover { opacity: 1; }
+ /* Checkbox in select mode */
+ .session-select-cb {
+ accent-color: var(--accent, var(--red));
+ margin: 0 4px 0 0;
+ flex-shrink: 0;
+ cursor: pointer;
+ }
+
+ .session-icon,
+ .model-icon {
+ flex-shrink: 0;
+ opacity: 0.35;
+ display: inline-flex;
+ align-items: center;
+ }
+ .session-icon.has-docs {
+ color: inherit;
+ opacity: 0.5;
+ }
+ .session-star {
+ width: 10px; height: 10px;
+ border-radius: 50%;
+ border: 1.5px solid color-mix(in srgb, var(--fg) 22%, transparent);
+ flex-shrink: 0;
+ position: relative;
+ }
+ .session-star.processing {
+ animation: none;
+ }
+ .session-star.provider-logo.processing svg {
+ animation: none;
+ }
+ .session-star.notify {
+ animation: none;
+ opacity: 1;
+ /* Completed runs keep the provider slot but turn it into a compact
+ success check, so the logo does not simply appear to vanish. */
+ width: 14px; height: 14px;
- background: var(--color-success, #4caf50);
- border-color: var(--color-success, #4caf50);
- color: #fff;
++ background: transparent;
++ border-color: transparent;
++ color: var(--accent, var(--red));
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ }
+ /* The dot doubles as the provider-logo holder; hide that logo in the
+ done state so the solid notif dot doesn't collide with the SVG behind it. */
+ .session-star.notify svg { display: none; }
+ .session-star.notify::after {
- content: '\2713';
- font-family: system-ui, sans-serif;
- font-size: 10px;
- font-weight: 700;
- line-height: 1;
- transform: translateY(-0.5px);
++ content: '';
++ width: 14px;
++ height: 14px;
++ background: currentColor;
++ mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpolyline points='20 6 9 17 4 12' fill='none' stroke='black' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / contain no-repeat;
+ }
+ .session-fav {
+ flex-shrink: 0;
+ cursor: pointer;
+ color: var(--red);
+ opacity: 0.6;
+ display: inline-flex;
+ align-items: center;
+ transition: opacity 0.1s;
+ }
+ .session-fav:hover {
+ opacity: 1;
+ }
+ .list-item.active-session {
+ background: color-mix(in srgb, var(--red) 10%, transparent);
+ border-color: var(--red);
+ border-left-color: var(--red);
+ }
+ .list-item .provider-logo { opacity: 0.4 !important; }
+ .list-item:has(.session-star.processing) .provider-logo { opacity: 1 !important; }
+ .list-item.stream-complete .provider-logo { opacity: 1 !important; }
+ .list-item.active {
+ background: color-mix(in srgb, var(--red) 10%, transparent);
+ border-color: var(--red);
+ border-left-color: var(--red);
+ }
+ /* Only show the red focus ring for keyboard navigation (Tab). Mouse
+ clicks shouldn't leave a sticky red outline on a sidebar item. */
+ .list-item:focus { outline: none; }
+ .list-item:focus-visible {
+ outline: none;
+ border-color: var(--red, var(--color-error));
+ box-shadow: 0 0 0 1px var(--red, var(--color-error));
+ }
+ /* Drag handles hidden by default, shown via body.rearrange-mode */
+ .drag-handle, .item-drag-handle, .folder-drag-handle { display: none; }
+ body.rearrange-mode .drag-handle,
+ body.rearrange-mode .item-drag-handle,
+ body.rearrange-mode .folder-drag-handle { display: inline; }
+
+ /* Drag sorting styles for list items */
+ .item-drag-handle {
+ cursor: grab;
+ opacity: 0.4;
+ font-size: 10px;
+ padding: 0 4px;
+ user-select: none;
+ letter-spacing: -2px;
+ transition: opacity 0.15s;
+ }
+ .item-drag-handle:hover {
+ opacity: 1;
+ color: var(--red);
+ }
+ .item-drag-handle:active {
+ cursor: grabbing;
+ }
+ .list-item.dragging,
+ .models-row.dragging,
+ .session-folder.dragging {
+ opacity: 0.95;
+ box-shadow: 0 8px 24px color-mix(in srgb, var(--red) 30%, transparent);
+ border-color: var(--red);
+ background: var(--panel);
+ cursor: grabbing;
+ }
+ .session-item.dragging-to-folder {
+ opacity: 0.55;
+ border-color: var(--red);
+ box-shadow: 0 4px 14px color-mix(in srgb, var(--red) 22%, transparent);
+ }
+ .list-item.dragging .item-drag-handle,
+ .models-row.dragging .item-drag-handle,
+ .session-folder.dragging .folder-drag-handle {
+ opacity: 1;
+ color: var(--red);
+ }
+ /* ── Model category grouping ── */
+ .models-category-header {
+ display: flex; align-items: center; gap: 6px;
+ padding: 4px 8px; cursor: pointer;
+ font-size: 0.85em; font-weight: 600;
+ color: color-mix(in srgb, var(--fg) 55%, transparent);
+ border-radius: 4px; user-select: none;
+ margin-top: 4px;
+ transition: opacity 0.08s, background 0.08s, color 0.08s;
+ }
+ .models-category-header:hover { color: var(--fg); background: color-mix(in srgb, var(--fg) 4%, transparent); }
+ .models-category-header .folder-count { font-weight: 400; opacity: 0.5; font-size: 0.9em; }
+ .models-endpoint-label {
+ display: flex; align-items: center; gap: 6px;
+ padding: 4px 8px; cursor: pointer;
+ font-size: 0.85em; font-weight: 600;
+ color: color-mix(in srgb, var(--fg) 55%, transparent);
+ border-radius: 4px; user-select: none;
+ transition: opacity 0.08s, background 0.08s;
+ }
+ .models-endpoint-label:hover { color: var(--fg); background: color-mix(in srgb, var(--fg) 4%, transparent); }
+ .models-endpoint-label .folder-count { font-weight: 400; opacity: 0.5; }
+ .models-group-content.indented {
+ padding-left: 4px;
+ }
+ .models-group-content.indented .models-row { border-bottom: 1px solid color-mix(in srgb, var(--fg) 7%, transparent); }
+ .models-group-content.indented .models-row:last-child { border-bottom: none; }
+ /* ── Session folders ── */
+ .session-folder { margin: 2px 0; }
+ .session-folder-header {
+ display: flex; align-items: center; gap: 6px;
+ padding: 4px 8px; cursor: pointer;
+ font-size: 0.88em; font-weight: 600;
+ color: color-mix(in srgb, var(--fg) 55%, transparent);
+ border-radius: 4px; user-select: none;
+ transition: opacity 0.08s, background 0.08s;
+ }
+ .session-folder-header:hover { color: var(--fg); background: color-mix(in srgb, var(--fg) 4%, transparent); }
+ .session-folder-header .folder-count { font-weight: 400; opacity: 0.5; }
+ .session-folder-header.drag-over {
+ outline: 2px dashed var(--red); background: color-mix(in srgb, var(--red) 13%, transparent); opacity: 1;
+ }
+ .session-folder.dragging-folder { opacity: 0.4; }
+ .folder-toggle { font-size: 0.7em; width: 10px; text-align: center; }
+ .folder-name { font-weight: inherit; flex: 1; }
+ .folder-count { font-size: 0.85em; opacity: 0.5; }
+ .folder-drag-handle {
+ cursor: grab; opacity: 0.3; font-size: 0.8em; padding: 0 2px;
+ transition: opacity 0.08s;
+ }
+ .session-folder-header:hover .folder-drag-handle { opacity: 0.7; }
+ .folder-delete-btn {
+ background: none; border: none; color: var(--fg); opacity: 0;
+ cursor: pointer; font-size: 1.1em; padding: 0 2px; line-height: 1;
+ min-height: 0; height: auto;
+ transition: opacity 0.08s, color 0.08s;
+ }
+ .session-folder-header:hover .folder-delete-btn { opacity: 0.5; }
+ .folder-delete-btn:hover { opacity: 1 !important; color: var(--color-error); }
+ .session-folder-content { padding-left: 4px; }
+ .session-folder-content .list-item { border-bottom: 1px solid color-mix(in srgb, var(--fg) 7%, transparent); }
+ .session-folder-content .list-item:last-child { border-bottom: none; }
+ .session-show-more-btn {
+ display: block;
+ width: 100%;
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.4;
+ font-size: 0.8em;
+ padding: 6px 8px;
+ cursor: pointer;
+ text-align: center;
+ transition: opacity 0.15s;
+ }
+ .session-show-more-btn:hover { opacity: 0.8; }
+ .drag-folder-placeholder {
+ height: 4px; margin: 2px 0; border-radius: 2px;
+ background: var(--red); opacity: 0.6;
+ }
+ .unfiled-drop-zone {
+ min-height: 8px; border-radius: 4px; transition: all 0.15s;
+ }
+ .unfiled-drop-zone.drag-over {
+ min-height: 24px; outline: 2px dashed var(--red);
+ background: color-mix(in srgb, var(--red) 9%, transparent);
+ }
+
+ /* Mobile swipe-to-delete */
+ .swipe-delete-action {
+ position: absolute;
+ right: 0;
+ top: 0;
+ bottom: 0;
+ width: 60px;
+ background: color-mix(in srgb, var(--color-error) 12%, transparent);
+ color: var(--color-error);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 0 4px 4px 0;
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.15s;
+ cursor: pointer;
+ z-index: 1;
+ }
+ .swipe-delete-action::before {
+ content: '';
+ display: block;
+ width: 18px;
+ height: 18px;
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='18' height='18' viewBox='0 0 24 24' fill='none' stroke='%23ff4444' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='3 6 5 6 21 6'/%3E%3Cpath d='M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2'/%3E%3C/svg%3E");
+ background-size: contain;
+ background-repeat: no-repeat;
+ }
+ .swipe-delete-action:active {
+ background: color-mix(in srgb, var(--color-error) 22%, transparent);
+ }
+ .drag-placeholder {
+ background: color-mix(in srgb, var(--red) 10%, transparent);
+ border: 2px dashed color-mix(in srgb, var(--color-accent) 40%, transparent);
+ border-radius: 6px;
+ margin: 4px 0;
+ transition: height 0.15s ease;
+ }
+ .list-item,
+ .models-row {
+ display: flex;
+ gap: 6px;
+ align-items: center;
+ padding: 3px 8px;
+ margin: 0;
+ border-radius: 4px;
+ border: none;
+ line-height: 1.3;
+ font-size: 13px;
+ background: transparent;
+ transition: background 0.08s;
+ cursor: pointer;
+ touch-action: pan-y;
+ }
+ .list-item button {
+ margin: 0;
+ height: 24px;
+ padding: 0 8px;
+ font-size: 9px;
+ }
+ /* Inline "+" action on a tool/section row (Library → new document,
+ Email → compose). Sizing forced + min-* zeroed so the mobile
+ touch-target rule (44px) can't inflate it. Selector intentionally
+ NOT scoped to `.list-item` so the same class also styles buttons
+ sitting in `.section-header-flex` (e.g. #email-compose-btn). */
+ .list-item-plus-btn {
+ all: unset;
+ box-sizing: border-box;
+ flex-shrink: 0;
+ position: relative;
+ left: 4px;
+ display: inline-flex !important;
+ align-items: center;
+ justify-content: center;
+ height: 14px !important;
+ min-height: 0 !important;
+ width: auto !important;
+ min-width: 0 !important;
+ padding: 0 5px !important;
+ border-radius: 4px;
+ color: var(--fg);
+ /* Always visible at rest. On hover (devices that have it) the + spins
+ 90° and "new" reveals to its right — neat expand affordance. */
+ opacity: 1 !important;
+ cursor: pointer;
+ gap: 0;
+ overflow: visible;
+ z-index: 1;
+ transition: background 0.12s, color 0.12s, gap 0.18s ease;
+ }
+ .list-item-plus-btn svg.list-item-plus-icon {
+ width: 13px; height: 13px;
+ transition: transform 0.22s ease;
+ }
+ /* Legacy fallback for plus-btns without the `.list-item-plus-icon` class. */
+ .list-item-plus-btn svg:not(.list-item-plus-icon) { width: 13px; height: 13px; }
+ /* Label is absolutely positioned to the LEFT of the icon so the + stays
+ put — it just appears beside it on hover instead of pushing it. The
+ button's intrinsic width remains the icon, so neighbours don't shift. */
+ .list-item-plus-label {
+ position: absolute;
+ right: 100%;
+ top: 50%;
+ transform: translateY(-50%);
+ padding-right: 5px;
+ opacity: 0;
+ pointer-events: none;
+ white-space: nowrap;
+ font-size: 9.5px;
+ line-height: 1;
+ letter-spacing: 0.02em;
+ transition: opacity 0.18s ease, transform 0.22s ease;
+ }
+ @media (hover: hover) {
+ .list-item-plus-btn:hover .list-item-plus-icon {
+ transform: rotate(90deg);
+ }
+ .list-item-plus-btn:hover .list-item-plus-label {
+ opacity: 1;
+ transform: translateY(-50%) translateX(0);
+ pointer-events: auto;
+ }
+ .list-item-plus-btn .list-item-plus-label {
+ transform: translateY(-50%) translateX(6px);
+ }
+ }
+ .list-item-plus-btn:hover {
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ color: var(--accent, var(--red));
+ }
+ .list-item span {
+ color: var(--fg);
+ font-size: 9.75px;
+ }
+ .grow {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: clip;
+ white-space: nowrap;
+ }
+ input, textarea, button, select {
+ background:var(--bg);
+ color:var(--fg);
+ border:1px solid var(--border);
+ font-family:inherit;
+ padding:6.9px;
+ border-radius: 4px;
+ transition: background 0.08s, border-color 0.08s, color 0.08s, opacity 0.08s;
+ }
+ input:hover, textarea:hover, button:hover, select:hover {
+ border-color: var(--fg);
+ background-color: var(--panel);
+ }
+ :root.light input,
+ :root.light textarea,
+ :root.light button,
+ :root.light select {
+ background:#eaeaea;
+ color-scheme: light;
+ }
+ input[type="text"] { height:32px; width:100%; }
+ textarea { width:100%; min-height:32px; height:auto; max-height:30lh; overflow-y:auto; resize:none; }
+ button { height:32px; padding:0 10px; }
+ #chat-form button[type="submit"] { height:38px; }
+ select {
+ height:32px;
+ color-scheme: dark;
+ background-color: var(--select-bg);
+ color: var(--select-fg);
+ }
+ select option,
+ select optgroup {
+ background-color: var(--select-option-bg);
+ color: var(--select-option-fg);
+ }
+ select option:checked {
+ background-color: var(--select-option-active-bg);
+ color: var(--select-option-fg);
+ }
+ :root.light select { color-scheme: light; }
+ .chat-container {
+ flex:1;
+ display:flex;
+ flex-direction:column;
+ padding:0 16px;
+ overflow:hidden;
+ position:relative;
+ min-height:0;
+ min-width:0;
+ margin-top:8px;
+ margin-bottom: 0;
+ transition: margin-left 160ms cubic-bezier(0.22, 0.61, 0.36, 1),
+ margin-right 160ms cubic-bezier(0.22, 0.61, 0.36, 1);
+ }
+ .chat-meta { font-size:12px; color:color-mix(in srgb, var(--fg) 60%, transparent); margin-bottom:6px; }
+ .chat-history {
+ display:flex;
+ flex-direction:column;
+ flex:1;
+ overflow-y:auto;
+ overflow-x:hidden;
+ overscroll-behavior-y: none;
+ margin-bottom:8px;
+ white-space:normal;
+ min-height:0;
+ /* Streaming completion replaces the live turn with its persisted DOM.
+ We preserve the scroll position explicitly; native anchoring would
+ otherwise fight that replacement and create a visible bounce. */
+ overflow-anchor: none;
+ --chat-max: 800px;
+ padding-left: max(0px, calc((100% - var(--chat-max)) / 2));
+ padding-right: max(12px, calc((100% - var(--chat-max)) / 2 + 12px));
+ }
+ .chat-history > * {
+ flex: 0 0 auto;
+ }
+ .chat-pull-refresh {
+ --pull-refresh-y: 0px;
+ --pull-refresh-progress: 0;
+ position: absolute;
+ top: 8px;
+ left: 50%;
+ z-index: 48;
+ width: 34px;
+ height: 34px;
+ display: none;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid color-mix(in srgb, var(--border) 75%, transparent);
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--panel) 94%, transparent);
+ box-shadow: 0 8px 20px color-mix(in srgb, #000 16%, transparent);
+ opacity: calc(0.25 + (var(--pull-refresh-progress) * 0.75));
+ pointer-events: none;
+ transform: translate(-50%, calc(-42px + var(--pull-refresh-y))) scale(calc(0.82 + (var(--pull-refresh-progress) * 0.18)));
+ transition: opacity 0.16s ease, transform 0.18s cubic-bezier(0.2, 0.8, 0.2, 1), border-color 0.16s ease;
+ }
+ .chat-pull-refresh.is-visible,
+ .chat-pull-refresh.is-refreshing {
+ display: inline-flex;
+ }
+ .chat-pull-refresh.is-ready,
+ .chat-pull-refresh.is-refreshing {
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 58%, transparent);
+ color: var(--accent, var(--red));
+ }
+ .chat-pull-refresh .spinner-whirlpool {
+ margin: 0 !important;
+ width: 18px !important;
+ height: 18px !important;
+ }
+ .chat-pull-refresh canvas {
+ display: block;
+ }
+ #email-lib-modal .email-pull-refresh {
+ top: 112px;
+ z-index: 4;
+ }
+ /* Sortable Cookbook column headers had no visual cue, so users couldn't tell
+ a header was clickable (the Newest sort on the Model column was invisible).
+ Show a pointer + hover highlight, and underline the active sort column. */
+ .hwfit-header .hwfit-sortable { cursor: pointer; transition: color .12s; }
+ .hwfit-header .hwfit-sortable:hover { color: var(--fg); text-decoration: underline dotted; }
+ .hwfit-header .hwfit-sort-active { color: var(--fg); font-weight: 600; }
+ /* Welcome screen — centered in available space above input bar */
+ #welcome-screen {
+ position:absolute;
+ top:40%;
+ left:50%;
+ transform:translate(-50%,-50%);
+ display:flex;
+ flex-direction:column;
+ align-items:center;
+ text-align:center;
+ pointer-events:none;
+ animation: welcome-enter 0.4s ease-out both;
+ transition: top 0.35s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.3s ease, transform 0.3s ease;
+ }
+ #welcome-screen .welcome-tip,
+ #welcome-screen .welcome-sub,
+ #welcome-screen .welcome-version {
+ transition: opacity 0.25s ease, max-height 0.25s ease, margin 0.25s ease;
+ max-height: 60px;
+ overflow: hidden;
+ }
+ /* The tip is a full sentence that wraps to 4-5 lines on narrow phones,
+ where the welcome block shrink-wraps small; the shared 60px ceiling
+ (sized for the one-line sub/version) clipped its last line. Give the tip
+ a taller ceiling so it isn't truncated. Kept above the max-height:650px
+ block below so that rule's max-height:0 still collapses it on short
+ viewports. */
+ #welcome-screen .welcome-tip {
+ max-height: 120px;
+ }
+ @media (max-height: 650px) {
+ #welcome-screen { top: 28%; }
+ #welcome-screen .welcome-tip { opacity: 0; max-height: 0; margin: 0; }
+ #welcome-screen .welcome-version { margin-top: 6px; }
+ .incognito-btn { margin-top: 8px; }
+ }
+ @media (max-height: 500px) {
+ #welcome-screen { top: 22%; }
+ #welcome-screen .welcome-name { font-size: 1.4rem; margin-bottom: 0; }
+ #welcome-screen .welcome-sub { opacity: 0; max-height: 0; margin: 0; }
+ .incognito-btn { margin-top: 4px !important; }
+ }
+ @media (max-height: 380px) {
+ #welcome-screen { opacity: 0; pointer-events: none; }
+ }
+ #welcome-screen.hidden { display:none; }
+ #welcome-screen.kb-hidden {
+ opacity: 0;
+ pointer-events: none;
+ transform: translate(-50%, -50%);
+ transition: opacity 0.16s ease;
+ }
+ @media (max-width: 768px) {
+ #welcome-screen { top: 42%; }
+ #welcome-screen .welcome-name { margin-bottom: 2px; }
+ #welcome-screen .welcome-sub { margin-bottom: 0; }
+ #welcome-screen .incognito-btn { margin-top: 6px; }
+ }
+ #welcome-screen .welcome-name {
+ font-size:2.2rem;
+ font-weight:700;
+ background: linear-gradient(135deg, var(--brand-color, var(--red)), color-mix(in srgb, var(--brand-color, var(--red)) 60%, var(--fg)));
+ -webkit-background-clip: text;
+ -webkit-text-fill-color: transparent;
+ background-clip: text;
+ letter-spacing:0.03em;
+ margin-bottom:10px;
+ }
+ .welcome-boat {
+ width: 1.8rem;
+ height: 1.8rem;
+ margin-right: 0.4rem;
+ vertical-align: -0.15em;
+ color: var(--brand-color, var(--red));
+ }
+ #welcome-screen .welcome-sub {
+ font-size:0.85rem;
+ color:color-mix(in srgb, var(--fg) 60%, transparent);
+ opacity:0.6;
+ line-height:1.5;
+ max-width:300px;
+ }
+ #welcome-screen .welcome-version {
+ font-size:0.7rem;
+ opacity:0.25;
+ margin-top:12px;
+ pointer-events:none;
+ user-select:none;
+ }
+ #welcome-screen .welcome-tip {
+ font-size:0.75rem;
+ color:var(--fg);
+ opacity:0.2;
+ margin-top:24px;
+ max-width:320px;
+ line-height:1.4;
+ }
+ #welcome-screen .welcome-tip.nobody-session-note {
+ display:flex;
+ flex-direction:column;
+ gap:2px;
+ }
+ /* Incognito toggle — on welcome screen */
+ .incognito-btn {
+ pointer-events: auto;
+ background: none;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ opacity: 0.25;
+ cursor: pointer;
+ padding: 6px 12px;
+ border-radius: 20px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ transition: all 0.15s;
+ margin-top: 16px;
+ font-family: inherit;
+ font-size: 11px;
+ max-width: min(160px, 70vw);
+ }
+ .incognito-btn:hover {
+ opacity: 0.6;
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ }
+ .incognito-btn.active {
+ opacity: 1;
+ color: var(--accent);
+ border-color: var(--accent);
+ background: color-mix(in srgb, var(--accent) 10%, transparent);
+ }
+ .incognito-btn.active .eye-open { display: none; }
+ .incognito-btn.active .eye-blinded { display: inline !important; }
+ .incognito-label {
+ font-size: 11px;
+ font-weight: 500;
+ letter-spacing: 0.3px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ /* When welcome is active, push input bar up toward center */
+ .chat-container .chat-input-bar {
+ transition: margin 0.3s ease, max-width 0.3s ease;
+ }
+ .chat-container.welcome-active .chat-input-bar {
+ margin-bottom:30vh;
+ margin-left:auto;
+ margin-right:auto;
+ max-width: 800px;
+ width: 100%;
+ }
+ @media (max-width:768px) {
+ .chat-meta-overlay {
+ left: 36px;
+ right: 36px;
+ }
+ #welcome-screen .welcome-name { font-size:1.8rem; }
+ #welcome-screen .welcome-sub { font-size:0.8rem; }
+ .chat-container.welcome-active .chat-input-bar {
+ margin-bottom:0;
+ margin-left:0;
+ margin-right:0;
+ position: relative;
+ z-index: 20;
+ }
+ .chat-container.welcome-active:has(.chat-input-bar:focus-within) #welcome-screen,
+ .chat-container.welcome-active:has(textarea#message:not(:placeholder-shown)) #welcome-screen {
+ opacity: 0;
+ pointer-events: none;
+ transform: translate(-50%, -50%);
+ transition: opacity 0.16s ease;
+ }
+ .chat-container.welcome-active:has(.input-icon-btn.expanded) #welcome-screen,
+ .chat-container.welcome-active:has(.send-btn.newchat-expanded) #welcome-screen,
+ .chat-container.welcome-active:has(#model-picker-wrap:not(.picker-auto-hidden) .model-picker-menu:not(.hidden)) #welcome-screen {
+ opacity: 0.45;
+ transform: translate(-50%, -76%) scale(0.94);
+ }
+ .chat-container.welcome-active:has(.input-icon-btn.expanded) #welcome-screen .welcome-tip,
+ .chat-container.welcome-active:has(.send-btn.newchat-expanded) #welcome-screen .welcome-tip,
+ .chat-container.welcome-active:has(#model-picker-wrap:not(.picker-auto-hidden) .model-picker-menu:not(.hidden)) #welcome-screen .welcome-tip {
+ opacity: 0.14;
+ }
+ .chat-container.welcome-active textarea#message {
+ max-height: min(34vh, 150px);
+ }
+ }
+ @media (max-width: 420px) {
+ .chat-meta-overlay {
+ left: 34px;
+ right: 34px;
+ }
+ .chat-meta-overlay #session-cost-display,
+ .chat-meta-overlay .chat-meta-count {
+ display: none !important;
+ }
+ #welcome-screen {
+ width: calc(100vw - 36px);
+ }
+ #welcome-screen .welcome-name,
+ #welcome-screen .welcome-sub,
+ #welcome-screen .welcome-tip {
+ max-width: 100%;
+ }
+ .incognito-btn {
+ padding: 6px 9px;
+ max-width: 120px;
+ }
+ }
+ @media (max-width: 340px) {
+ .incognito-btn .incognito-label {
+ display: none;
+ }
+ .incognito-btn {
+ width: 30px;
+ height: 30px;
+ padding: 0;
+ border-radius: 999px;
+ }
+ }
+ .msg {
+ margin: 8px 0;
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ width: fit-content;
+ max-width: 85%;
+ min-width: 80px;
+ border-radius: 12px;
+ padding: 10px 12px;
+ line-height: 1.4;
+ word-wrap: break-word;
+ overflow-wrap: break-word;
+ overflow: hidden;
+ animation: msg-enter 0.3s ease-out both;
+ }
+ .msg-user {
+ align-items: flex-end;
+ margin-left: auto;
+ margin-right: 8px;
+ background: var(--user-bubble-bg, color-mix(in srgb, var(--fg) 8%, var(--bg)));
+ border: 1px solid var(--bubble-border, var(--border));
+ border-radius: 18px 18px 0 18px;
+ align-self: flex-end;
+ width: fit-content;
+ max-width: 85%;
+ min-width: 80px;
+ word-wrap: break-word;
+ overflow-wrap: break-word;
+ overflow: hidden;
+ }
+ .msg-user:has(textarea) {
+ width: 85%;
+ }
+ .msg-ai {
+ align-items: flex-start;
+ margin-right: auto;
+ margin-left: 8px;
+ background: var(--ai-bubble-bg, var(--panel));
+ border: 1px solid var(--bubble-border, var(--border));
+ border-radius: 18px 18px 18px 0;
+ align-self: flex-start;
+ width: 85%;
+ max-width: 85%;
+ min-width: 80px;
+ word-wrap: break-word;
+ overflow-wrap: break-word;
+ overflow: hidden;
+ transition: min-height 0.25s ease-out;
+ }
+ .msg .role {
+ font-weight: 600;
+ margin-bottom: 6px;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .msg .role::before {
+ content: '';
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--model-dot, color-mix(in srgb, var(--fg) 30%, transparent));
+ flex-shrink: 0;
+ }
+ .msg .role.has-logo::before { display: none; }
+ .role-provider-logo { display: inline-flex; align-items: center; flex-shrink: 0; }
+ .role-provider-logo svg { width: 12px; height: 12px; }
+ .msg-user .role {
+ color: color-mix(in srgb, var(--fg) 60%, transparent);
+ }
+ .msg-user .role::before {
+ background: color-mix(in srgb, var(--fg) 40%, transparent);
+ }
+ .user-mode-pill {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ height: 15px;
+ min-width: 15px;
+ padding: 0 3px;
+ border-radius: 4px;
+ border: 1px solid color-mix(in srgb, var(--fg) 14%, transparent);
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ color: color-mix(in srgb, var(--fg) 58%, transparent);
+ font-size: 10px;
+ font-weight: 600;
+ line-height: 15px;
+ text-transform: lowercase;
+ }
+ .user-mode-pill svg {
+ display: block;
+ width: 11px;
+ height: 11px;
+ }
+ .user-mode-pill[data-auto="true"]::after {
+ content: 'auto';
+ margin-left: 4px;
+ opacity: 0.65;
+ font-weight: 500;
+ }
+ .msg .body {
+ width: 100%;
+ white-space: normal;
+ word-break: break-word;
+ overflow-wrap: anywhere;
+ line-height: 1.5;
+ font-size: 0.95em;
+ margin: 0;
+ overflow: hidden;
+ max-width: 100%;
+ }
+ .msg .body > * {
+ margin-top: 8px;
+ margin-bottom: 8px;
+ }
+ .msg .body > *:first-child {
+ margin-top: 0;
+ }
+ .msg .body > *:last-child {
+ margin-bottom: 0;
+ }
+ .msg .body p:empty {
+ display: none;
+ }
+ .msg-user .body {
+ color: var(--fg);
+ }
+ .chat-queued-bubble-host {
+ order: 2147483647;
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ flex: 0 0 auto;
+ width: 100%;
+ min-width: 0;
+ }
+ .msg-user.msg-user-queued {
+ opacity: 0.62;
+ cursor: pointer;
+ animation: none;
+ border: 1px dashed color-mix(in srgb, var(--accent, var(--red)) 55%, transparent);
+ background: color-mix(in srgb, var(--accent, var(--red)) 8%, var(--input-bg, var(--panel)));
+ transition: opacity 0.12s ease, border-color 0.12s ease, transform 0.12s ease;
+ }
+ .msg-user.msg-user-queued:hover {
+ opacity: 0.9;
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 85%, transparent);
+ transform: translateY(-1px);
+ }
+ .msg-user.msg-user-queued .queued-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ height: 14px;
+ padding: 0 5px;
+ margin-left: 5px;
+ border-radius: 999px;
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 45%, transparent);
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 10%, transparent);
+ font-size: 8px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.03em;
+ vertical-align: 1px;
+ }
+ .msg-user.msg-user-queued .queued-pill svg {
+ flex: 0 0 auto;
+ opacity: 0.9;
+ }
+ .msg-ai .body {
+ color: var(--fg);
+ }
+ .model-endpoint-add-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ margin-left: 7px;
+ padding: 2px 7px;
+ border: 1px solid color-mix(in srgb, var(--red) 34%, var(--border));
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--red) 8%, transparent);
+ color: var(--red);
+ font: inherit;
+ font-size: 0.78em;
+ line-height: 1.45;
+ cursor: pointer;
+ vertical-align: 1px;
+ }
+ .model-endpoint-add-btn:hover {
+ background: color-mix(in srgb, var(--red) 14%, transparent);
+ border-color: color-mix(in srgb, var(--red) 55%, var(--border));
+ }
+ .model-endpoint-add-btn:disabled {
+ cursor: default;
+ opacity: 0.72;
+ }
+ .model-endpoint-add-btn.added {
+ color: var(--color-save-green, #4caf50);
+ border-color: color-mix(in srgb, var(--color-save-green, #4caf50) 45%, var(--border));
+ background: color-mix(in srgb, var(--color-save-green, #4caf50) 9%, transparent);
+ }
+ .task-completed-marker {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ margin: 7px 0 2px;
+ padding: 5px 9px;
+ border: 1px solid color-mix(in srgb, var(--color-save-green, #4caf50) 42%, var(--border));
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--color-save-green, #4caf50) 9%, transparent);
+ color: var(--color-save-green, #4caf50);
+ font-size: 0.86em;
+ font-weight: 600;
+ }
+ .task-completed-icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 17px;
+ height: 17px;
+ border-radius: 50%;
+ background: color-mix(in srgb, var(--color-save-green, #4caf50) 18%, transparent);
+ flex: 0 0 auto;
+ }
+ .rag-sources {
+ margin-top: 12px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 8px;
+ font-size: 11px;
+ }
+ .rag-sources summary {
+ cursor: pointer;
+ color: var(--red);
+ font-weight: bold;
+ font-size: 11px;
+ }
+ .rag-source-item {
+ margin-top: 8px;
+ padding: 6px;
+ background: color-mix(in srgb, var(--fg) 4%, transparent);
+ border-radius: 4px;
+ border-left: 2px solid var(--red);
+ }
+ .rag-similarity {
+ color: color-mix(in srgb, var(--fg) 50%, transparent);
+ font-size: 10px;
+ margin-left: 6px;
+ }
+ .rag-snippet {
+ color: color-mix(in srgb, var(--fg) 65%, transparent);
+ font-size: 11px;
+ margin-top: 4px;
+ white-space: pre-wrap;
+ max-height: 60px;
+ overflow: hidden;
+ }
+ .rag-file-delete {
+ background: none;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ color: color-mix(in srgb, var(--fg) 50%, transparent);
+ cursor: pointer;
+ font-size: 10px;
+ padding: 1px 5px;
+ }
+ .rag-file-delete:hover { color: var(--fg); border-color: var(--fg); }
+ .rag-file-size {
+ color: color-mix(in srgb, var(--fg) 50%, transparent);
+ font-size: 10px;
+ margin-left: 4px;
+ }
+ .rag-upload-zone {
+ border: 2px dashed var(--border);
+ border-radius: 6px;
+ padding: 12px;
+ text-align: center;
+ color: color-mix(in srgb, var(--fg) 45%, transparent);
+ font-size: 11px;
+ cursor: pointer;
+ transition: border-color 0.2s;
+ }
+ .rag-upload-zone.dragover {
+ border-color: var(--red);
+ color: var(--red);
+ }
+ .msg .timestamp {
+ font-size: 10px;
+ color: color-mix(in srgb, var(--fg) 45%, transparent);
+ margin-top: 4px;
+ text-align: right;
+ opacity: 0.7;
+ }
+ .msg-user .timestamp {
+ color: color-mix(in srgb, var(--fg) 72%, transparent);
+ }
+ pre {
+ overflow: hidden;
+ padding: 6px 4px 2px 4px;
+ border: 1px solid var(--border);
+ background: var(--bg);
+ position: relative;
+ line-height: 1.4;
+ font-size: 0.95em;
+ font-family: 'Fira Code', 'Courier New', monospace;
+ min-height: 38px;
+ max-width: 100%;
+ margin: 8px 0;
+ white-space: pre-wrap;
+ word-break: break-word;
+ border-radius: 4px;
+ min-height: 20px;
+ min-width: 80px;
+ }
+
+ /* Ensure code block headers are only slightly larger than regular text */
+ pre h1, pre h2, pre h3, pre h4, pre h5, pre h6 {
+ font-size: 1.1em;
+ font-weight: bold;
+ margin: 8px 0 4px 0;
+ color: var(--fg);
+ }
+ .code-lang {
+ font-size:0.8em;
+ color:color-mix(in srgb, var(--fg) 60%, transparent);
+ display:block;
+ margin-bottom:2px;
+ font-style:italic;
+ }
+ code { font-family:inherit; }
+ .loading { color:var(--red); font-style:italic; }
+ #chat-form { display:none; }
+
+ /* Unified chat input bar */
+ .chat-input-bar {
+ background: var(--input-bg, var(--panel));
+ border: 1px solid var(--input-border, var(--border));
+ border-radius: 16px;
+ padding: 10px 12px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ max-width: 800px;
+ margin-left: auto;
+ margin-right: auto;
+ width: 100%;
+ transition: border-color 0.16s ease, background 0.16s ease;
+ }
+ body.plan-mode-active .chat-input-bar {
+ border-style: dashed;
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 55%, transparent);
+ background: color-mix(in srgb, var(--accent, var(--red)) 8%, var(--input-bg, var(--panel)));
+ }
+ .chat-input-top {
+ width: 100%;
+ position: relative;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ align-items: start;
+ }
+ .plan-mode-status {
+ position: absolute;
+ right: 0;
+ bottom: 2px;
+ z-index: 245;
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ height: 22px;
+ padding: 0 6px 0 8px;
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 35%, transparent);
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--accent, var(--red)) 12%, var(--input-bg, var(--panel)));
+ color: var(--accent, var(--red));
+ font-size: 10px;
+ font-weight: 700;
+ line-height: 1;
+ transition: opacity 0.22s ease, transform 0.22s ease;
+ }
+ .plan-mode-status[hidden] {
+ display: none !important;
+ }
+ .plan-mode-status.plan-mode-status-autohide {
+ opacity: 0;
+ pointer-events: none;
+ transform: translateY(-4px) scale(0.96);
+ }
+ .plan-mode-status-toggle {
+ width: 26px;
+ height: 14px;
+ padding: 0;
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 55%, transparent);
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--accent, var(--red)) 22%, transparent);
+ cursor: pointer;
+ position: relative;
+ flex-shrink: 0;
+ }
+ .plan-mode-status-toggle span {
+ position: absolute;
+ top: 2px;
+ right: 2px;
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--accent, var(--red));
+ }
+ .plan-mode-status-toggle:hover {
+ background: color-mix(in srgb, var(--accent, var(--red)) 30%, transparent);
+ }
+ .chat-input-top > .model-picker-wrap {
+ position: relative;
+ grid-column: 2;
+ grid-row: 1;
+ top: 0;
+ right: auto;
+ z-index: 250;
+ transform-origin: top right;
+ transition: opacity 0.22s ease, transform 0.22s ease;
+ will-change: opacity, transform;
+ }
+ body.plan-mode-active .chat-input-top > .model-picker-wrap {
+ opacity: 0;
+ pointer-events: none;
+ transform: translateY(-4px) scale(0.96);
+ }
+ .chat-input-top > .model-picker-wrap.model-picker-autohide,
+ .chat-input-top > .model-picker-wrap.picker-auto-hidden {
+ display: none !important;
+ opacity: 0;
+ pointer-events: none;
+ transform: translateY(-4px) scale(0.96);
+ }
+ .ghost-text-overlay {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ pointer-events: none;
+ white-space: pre-wrap;
+ overflow-wrap: break-word;
+ font-family: inherit;
+ font-size: 14px;
+ line-height: 1.5;
+ padding: 0;
+ border: 1px solid transparent;
+ color: transparent;
+ z-index: 1;
+ }
+ .ghost-text-overlay .ghost-suggestion {
+ color: color-mix(in srgb, var(--fg) 30%, transparent);
+ }
+ .chat-input-bar textarea#message {
+ grid-column: 1;
+ grid-row: 1;
+ min-width: 0;
+ width: 100%;
+ background: transparent;
+ border: none;
+ outline: none;
+ resize: none;
+ font-size: 14px;
+ line-height: 1.5;
+ color: var(--fg);
+ min-height: 24px;
+ max-height: 200px;
+ padding: 0;
+ font-family: inherit;
+ transition: height 0.12s ease-out;
+ }
+ .chat-input-bar textarea#message::placeholder {
+ color: color-mix(in srgb, var(--fg) 35%, transparent);
+ }
+ .chat-input-bottom {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-top: 4px;
+ }
+ /* Progressive shrinkage: as the chat input bar gets narrow, sacrifice
+ chrome before the typing area. First the Agent/Chat toggle drops out,
+ then the model picker — textarea + send button always stay. Container
+ queries so it responds to *bar width*, not viewport width (the bar
+ can be in a split pane). */
+ .chat-input-bar { container-type: inline-size; container-name: chatbar; }
+ @container chatbar (max-width: 340px) {
+ .chat-input-right .mode-toggle { display: none !important; }
+ }
+ .chat-input-left {
+ display: flex;
+ gap: 4px;
+ align-items: center;
+ flex-wrap: nowrap;
+ overflow: hidden;
+ min-width: 0;
+ flex: 1;
+ }
+ /* Collapsible buttons shrink away; collapsed ones disappear */
+ .chat-input-left > .input-icon-btn {
+ flex-shrink: 0;
+ }
+ .chat-input-left > .input-icon-btn.toolbar-collapsed {
+ display: none !important;
+ }
+ /* Always keep overflow wrapper visible and leftmost */
+ .chat-input-left > .overflow-wrapper {
+ flex-shrink: 0;
+ position: relative;
+ z-index: 1;
+ }
+ .input-divider {
+ width: 1px;
+ height: 16px;
+ background: var(--border);
+ opacity: 0.4;
+ margin: 0 2px;
+ flex-shrink: 0;
+ }
+ .chat-input-right {
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ flex-shrink: 0;
+ }
- /* Reasoning effort pill / dropdown in composer */
++ /* Reasoning effort dropdown in Chat Context */
+ .reasoning-effort-wrap {
+ position: relative;
+ display: inline-flex;
+ align-items: center;
+ }
+ .reasoning-effort-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ height: 28px;
+ padding: 0 8px;
+ border-radius: 6px;
+ border: 1px solid var(--border);
+ background: color-mix(in srgb, var(--fg) 4%, transparent);
+ color: var(--fg);
+ font-size: 11.5px;
+ font-weight: 500;
+ cursor: pointer;
+ user-select: none;
+ transition: background 0.15s, border-color 0.15s;
+ }
+ .reasoning-effort-btn:hover {
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ border-color: color-mix(in srgb, var(--fg) 20%, transparent);
+ }
+ .reasoning-effort-chevron {
+ opacity: 0.5;
+ transition: transform 0.15s;
+ flex-shrink: 0;
+ }
+ .reasoning-effort-btn[aria-expanded="true"] .reasoning-effort-chevron {
+ transform: rotate(180deg);
+ }
+ .reasoning-effort-menu {
+ position: absolute;
+ bottom: calc(100% + 6px);
+ right: 0;
+ min-width: 140px;
+ background: var(--bg-surface, var(--bg));
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.35);
+ padding: 4px;
+ z-index: 1000;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+ .reasoning-effort-menu.hidden {
+ display: none !important;
+ }
+ .reasoning-effort-option {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 6px 10px;
+ border-radius: 5px;
+ font-size: 12px;
+ color: var(--fg);
+ cursor: pointer;
+ background: transparent;
+ border: none;
+ text-align: left;
+ width: 100%;
+ transition: background 0.12s;
+ }
+ .reasoning-effort-option:hover {
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
+ .reasoning-effort-option.active {
+ color: var(--accent);
+ font-weight: 600;
+ }
- @container chatbar (max-width: 480px) {
- .reasoning-effort-prefix { display: none; }
++ .chat-context-popup .reasoning-effort-wrap {
++ width: 100%;
++ margin-top: 8px;
++ }
++ .chat-context-popup .reasoning-effort-btn {
++ width: 100%;
++ font: inherit;
++ }
++ .chat-context-popup .reasoning-effort-prefix {
++ flex: 1;
++ text-align: left;
+ }
- @media (max-width: 480px) {
- .reasoning-effort-prefix { display: none; }
++ .chat-context-popup .reasoning-effort-menu {
++ top: calc(100% + 4px);
++ bottom: auto;
++ max-height: 180px;
++ overflow-y: auto;
+ }
+ .input-icon-btn {
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.5;
+ cursor: pointer;
+ padding: 6px;
+ border-radius: 8px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ transition: opacity 0.15s, background 0.15s, color 0.15s;
+ position: relative;
+ }
+ .input-icon-btn:hover {
+ opacity: 0.8;
+ background: color-mix(in srgb, var(--accent) 8%, transparent);
+ }
+ .input-icon-btn.active,
+ .input-icon-btn.expanded {
+ opacity: 1;
+ color: var(--fg);
+ background: color-mix(in srgb, var(--fg) 9%, transparent);
+ }
+ .plan-mode-btn {
+ width: 28px;
+ height: 28px;
+ padding: 0;
+ flex-shrink: 0;
+ top: -2px;
+ }
+ .plan-mode-btn.active {
+ color: var(--accent);
+ background: color-mix(in srgb, var(--accent) 14%, transparent);
+ }
+ /* GitHub-style task lists (- [ ] / - [x]) */
+ li.task-item {
+ list-style: none;
+ margin-left: -1.2em;
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ }
+ li.task-item .task-check {
+ flex: 0 0 auto;
+ width: 15px;
+ height: 15px;
+ margin-top: 3px;
+ border-radius: 4px;
+ border: 1.5px solid color-mix(in srgb, var(--fg) 45%, transparent);
+ box-sizing: border-box;
+ position: relative;
+ }
+ li.task-item.task-done .task-check {
+ background: var(--accent);
+ border-color: var(--accent);
+ }
+ li.task-item.task-done .task-check::after {
+ content: '';
+ position: absolute;
+ left: 4px;
+ top: 1px;
+ width: 4px;
+ height: 8px;
+ border: solid var(--bg);
+ border-width: 0 2px 2px 0;
+ transform: rotate(45deg);
+ }
+ li.task-item.task-done .task-text {
+ opacity: 0.6;
+ text-decoration: line-through;
+ }
+ .plan-inline-actions {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ margin-top: 10px;
+ }
+ .plan-inline-execute,
+ .plan-inline-clear {
+ height: 26px;
+ border-radius: 7px;
+ border: 1px solid color-mix(in srgb, var(--fg) 13%, transparent);
+ background: transparent;
+ color: var(--fg);
+ font: inherit;
+ font-size: 11px;
+ padding: 0 9px;
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ cursor: pointer;
+ }
+ .plan-inline-execute {
+ background: color-mix(in srgb, var(--accent, var(--red)) 16%, transparent);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 35%, transparent);
+ color: var(--accent, var(--red));
+ font-weight: 650;
+ }
+ .plan-review-panel {
+ position: fixed;
+ right: 24px;
+ bottom: 92px;
+ z-index: 500;
+ width: min(520px, calc(100vw - 32px));
+ max-height: min(560px, calc(100vh - 120px));
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 35%, var(--border));
+ border-radius: 8px;
+ background: var(--panel);
+ color: var(--fg);
+ box-shadow: 0 14px 40px color-mix(in srgb, #000 32%, transparent);
+ }
+ .plan-review-panel[hidden] { display: none !important; }
+ .plan-review-panel-header,
+ .plan-review-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 10px 12px;
+ }
+ .plan-review-panel-header {
+ justify-content: space-between;
+ border-bottom: 1px solid var(--border);
+ }
+ .plan-review-panel-header h3 {
+ margin: 0;
+ font-size: 13px;
+ line-height: 1.2;
+ }
+ .plan-review-close {
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: var(--fg);
+ font-size: 19px;
+ line-height: 1;
+ cursor: pointer;
+ opacity: 0.65;
+ }
+ .plan-review-close:hover { opacity: 1; }
+ .plan-review-content {
+ margin: 0;
+ padding: 12px;
+ overflow: auto;
+ white-space: pre-wrap;
+ word-break: break-word;
+ font-size: 12px;
+ line-height: 1.55;
+ font-family: inherit;
+ }
+ .plan-review-actions {
+ border-top: 1px solid var(--border);
+ }
+ .plan-review-execute,
+ .plan-review-clear {
+ height: 28px;
+ padding: 0 9px;
+ border: 1px solid color-mix(in srgb, var(--fg) 14%, transparent);
+ border-radius: 6px;
+ background: transparent;
+ color: var(--fg);
+ font: inherit;
+ font-size: 11px;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ }
+ .plan-review-execute {
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 35%, transparent);
+ background: color-mix(in srgb, var(--accent, var(--red)) 16%, transparent);
+ color: var(--accent, var(--red));
+ font-weight: 650;
+ }
+ /* While the menu is open the chevron stays in its highlighted state
+ — don't run the opacity fade transition so we never flash from
+ 0.5 → hover-1.0 → drop-back. The state holds steady. */
+ .input-icon-btn.expanded { transition: none; }
+ /* Accent color for Research, Compare toolbar indicators */
+ #research-toggle-btn.active,
+ .tool-indicator.active {
+ color: var(--red);
+ background: color-mix(in srgb, var(--red) 12%, transparent);
+ }
+ #workspace-indicator-btn.active {
+ opacity: 1;
+ color: var(--fg);
+ background: color-mix(in srgb, var(--fg) 9%, transparent);
+ }
+ #workspace-indicator-btn.active:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--fg) 9%, transparent);
+ }
+ #workspace-indicator-btn.active > svg:not(.tool-indicator-x),
+ #workspace-indicator-btn.active > span {
+ opacity: 1;
+ }
+ #workspace-indicator-btn .workspace-indicator-icon {
+ opacity: 1 !important;
+ color: currentColor !important;
+ stroke: currentColor !important;
+ flex-shrink: 0;
+ }
+ #workspace-indicator-btn > svg:first-of-type {
+ opacity: 1 !important;
+ color: currentColor !important;
+ stroke: currentColor !important;
+ }
+ /* Research button glow while actively running */
+ #research-toggle-btn.research-running {
+ opacity: 1 !important;
+ color: var(--red);
+ animation: research-pulse 2s ease-in-out infinite;
+ }
+ .tool-indicator-x {
+ margin-left: 2px;
+ opacity: 0.4;
+ flex-shrink: 0;
+ transition: opacity 0.15s;
+ }
+ .tool-indicator:hover .tool-indicator-x {
+ opacity: 1;
+ }
+ /* Character indicator — hide name text below 768px, icon always visible */
+ @media (max-width: 768px) {
+ #character-indicator-name { display: none; }
+ }
+
+ /* Document indicator — hidden by default, shown when docs exist */
+ #doc-indicator-btn { display: none !important; }
+ #doc-indicator-btn.visible { display: inline-flex !important; }
+ /* On mobile, the minimized-dock chip replaces this indicator — keep
+ it hidden regardless of `.visible`. */
+ @media (max-width: 768px) {
+ #doc-indicator-btn,
+ #doc-indicator-btn.visible { display: none !important; }
+ }
+ .doc-indicator-active {
+ color: var(--accent, var(--accent-primary, var(--red))) !important;
+ opacity: 1 !important;
+ }
+ #doc-indicator-btn.active {
+ color: var(--accent, var(--accent-primary, var(--red))) !important;
+ opacity: 1 !important;
+ background: color-mix(in srgb, var(--fg) 9%, transparent) !important;
+ }
+ #overflow-doc-btn.has-docs,
+ #overflow-doc-btn.active {
+ color: var(--accent, var(--red));
+ opacity: 1;
+ }
+ #overflow-doc-btn.has-docs.active {
+ background: color-mix(in srgb, var(--accent, var(--red)) 12%, transparent);
+ }
+ .send-btn {
+ /* Prefer the theme accent (--red). A stored custom `--send-btn-bg`
+ override only kicks in if it's set to a non-white value — guards
+ against ChatGPT-style themes where the stored override leaked
+ to white and rendered the send button invisible. */
+ background: var(--send-btn-bg, var(--red));
+ color: #fff;
+ border: none;
+ border-radius: 8px;
+ min-width: 32px;
+ width: 32px;
+ height: 32px !important;
+ padding: 0;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ transition: background 0.25s, border-color 0.25s, color 0.25s, width 0.3s cubic-bezier(0.34, 1, 0.64, 1), padding 0.3s, border-radius 0.3s, opacity 0.1s;
+ flex-shrink: 0;
+ overflow: hidden;
+ }
+ /* Instant feedback while the send handler is spinning up before streaming begins */
+ .send-btn.send-pending {
+ opacity: 0.55;
+ pointer-events: none;
+ animation: send-pending-pulse 0.9s ease-in-out infinite;
+ }
+ @keyframes send-pending-pulse {
+ 0%, 100% { opacity: 0.55; }
+ 50% { opacity: 0.85; }
+ }
+ /* Send button icon transitions — send mode forces no animation */
+ .send-btn[data-mode="send"] svg { animation: none !important; }
+ /* Spin out: + rotates away, then arrow spins in via anim-spin */
+ .send-btn.anim-spin-swap svg { animation: btn-spin-out 0.15s ease-in forwards; }
+ .send-btn.anim-spin-swap .send-btn-label { opacity: 0; transition: opacity 0.1s; }
+ @keyframes btn-spin-out {
+ 0% { transform: rotate(0deg) scale(1); opacity: 1; }
+ 100% { transform: rotate(90deg) scale(0); opacity: 0; }
+ }
+ .send-btn.anim-spin svg { animation: btn-spin-in 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); }
+ .send-btn.anim-launch svg { animation: btn-launch 0.3s cubic-bezier(0.6, 0, 0.4, 1) forwards; }
+ .send-btn.anim-land svg { animation: btn-land 0.25s cubic-bezier(0.34, 1.56, 0.64, 1); }
+ @keyframes btn-spin-in {
+ 0% { transform: rotate(-180deg) scale(0); opacity: 0; }
+ 100% { transform: rotate(0deg) scale(1); opacity: 1; }
+ }
+ /* Arrow flies UP and OUT of the button before the stop icon lands in.
+ Stays opaque most of the way so it reads as a real launch instead of a
+ fade-in-place. .anim-launch temporarily lifts the button's overflow so
+ the icon escapes the 32px box. */
+ @keyframes btn-launch {
+ 0% { transform: translateY(0) scale(1); opacity: 1; }
+ 70% { transform: translateY(-30px) scale(0.95); opacity: 1; }
+ 100% { transform: translateY(-58px) scale(0.55); opacity: 0; }
+ }
+ .send-btn.anim-launch { overflow: visible !important; }
+ .send-btn.anim-launch svg { transform-origin: 50% 50%; }
+ @keyframes btn-land {
+ 0% { transform: translateY(10px) scale(0.3); opacity: 0; }
+ 100% { transform: translateY(0) scale(1); opacity: 1; }
+ }
+ /* Stop button — Processing: Siren pulse, Receiving: Quarter turn spin */
+ .send-btn[data-mode="streaming"][data-phase="processing"] svg {
+ animation: siren-icon 1.5s ease-in-out infinite;
+ }
+ .send-btn[data-mode="streaming"][data-phase="receiving"] svg {
+ animation: quarter-turn 2s cubic-bezier(0.4, 0, 0.2, 1) infinite;
+ }
+ @keyframes siren-icon {
+ 0%, 100% { transform: scale(1); }
+ 50% { transform: scale(0.8); }
+ }
+ @keyframes quarter-turn {
+ 0%, 15% { transform: rotate(0deg); }
+ 25%, 40% { transform: rotate(90deg); }
+ 50%, 65% { transform: rotate(180deg); }
+ 75%, 90% { transform: rotate(270deg); }
+ 100% { transform: rotate(360deg); }
+ }
+ .send-btn:hover {
+ background: var(--send-btn-hover, color-mix(in srgb, var(--red) 80%, white));
+ color: #fff;
+ }
+ .send-btn.mic-mode,
+ .send-btn.newchat-mode {
+ /* Idle / new-chat / mic states blend the picked Send Btn color into
+ the panel so the user's color choice is visible across every state,
+ not only briefly while typing. */
+ background: color-mix(in srgb, var(--send-btn-bg, var(--red)) 30%, var(--panel, #2a2a2a));
+ color: var(--fg);
+ border: 1px solid var(--border);
+ transition: width 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), background 0.25s, border-color 0.25s, color 0.25s, border-radius 0.3s;
+ }
+ .send-btn.mic-mode:hover,
+ .send-btn.newchat-mode:hover {
+ background: color-mix(in srgb, var(--send-btn-hover, var(--send-btn-bg, var(--red))) 85%, var(--panel, #2a2a2a));
+ color: #fff;
+ }
+ /* Hover: just spin the + 90° (no size change). The "New chat" affordance
+ is the tooltip (title="New chat") plus the icon rotation.
+ Gated on data-mode="newchat" so the arrow variant (empty-session state
+ which keeps the newchat-mode class but shows the send arrow) does NOT
+ rotate on hover. */
+ .send-btn[data-mode="newchat"] svg {
+ transition: transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ .send-btn[data-mode="newchat"]:hover svg {
+ transform: rotate(90deg);
+ }
+ /* "New Session" expanding label */
+ .send-btn-label {
+ width: 0;
+ max-width: 0;
+ overflow: hidden;
+ white-space: nowrap;
+ font-size: 11px;
+ font-weight: 500;
+ letter-spacing: 0.3px;
+ opacity: 0;
+ padding: 0;
+ margin: 0;
+ transition: max-width 0.35s cubic-bezier(0.34, 1.2, 0.64, 1), width 0.35s, opacity 0.25s, margin-left 0.25s;
+ }
+ .send-btn.newchat-expanded .send-btn-label {
+ width: auto;
+ max-width: 50px;
+ opacity: 1;
+ margin-left: 4px;
+ }
+ .send-btn.newchat-expanded {
+ width: 68px;
+ padding: 0 10px 0 8px;
+ }
+ .send-btn.recording {
+ background: var(--red) !important;
+ color: #fff !important;
+ border: none !important;
+ animation: pulse-recording 1.5s infinite;
+ }
+ @keyframes pulse-recording {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.7; }
+ }
+ /* Mode toggle — Agent / Chat */
+ .mode-toggle {
+ display: flex;
+ flex-shrink: 0;
+ height: 28px;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ overflow: hidden;
+ position: relative;
+ }
+ .mode-toggle::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 50%;
+ height: 100%;
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ border-radius: 9px;
+ transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
+ z-index: 0;
+ }
+ .mode-toggle.mode-chat::before,
+ .mode-toggle.mode-right::before {
+ transform: translateX(100%);
+ }
+ .mode-toggle.mode-toggle-three::before {
+ width: 33.3333%;
+ }
+ .mode-toggle.mode-toggle-three.mode-mid::before {
+ transform: translateX(100%);
+ }
+ .mode-toggle.mode-toggle-three.mode-third::before {
+ transform: translateX(200%);
+ }
+ #mode-agent-btn {
+ border-radius: 10px 0 0 10px;
+ }
+ #mode-chat-btn {
+ border-radius: 0 10px 10px 0;
+ }
+ .mode-toggle-btn {
+ background: none;
+ border: none;
+ color: color-mix(in srgb, var(--fg) 40%, transparent);
+ cursor: pointer;
+ padding: 0 10px;
+ font-size: 11px;
+ font-weight: 500;
+ font-family: inherit;
+ transition: color 0.2s;
+ white-space: nowrap;
+ height: 100%;
+ position: relative;
+ z-index: 1;
+ }
+ .mode-toggle-btn:not(.active):hover {
+ color: color-mix(in srgb, var(--fg) 60%, transparent);
+ }
+ .mode-toggle-btn:hover {
+ background: none !important;
+ border-color: transparent !important;
+ }
+ .mode-toggle-btn.active,
+ .mode-toggle-btn.active:hover,
+ .mode-toggle-btn.active:focus {
+ color: var(--fg) !important;
+ background: none !important;
+ border-color: transparent !important;
+ cursor: default;
+ }
+ .mode-toggle-btn + .mode-toggle-btn {
+ border-left: none;
+ }
+ @media (max-width: 768px) {
+ .mode-toggle.mode-toggle-three [data-llama-mode="unified"] > span {
+ font-size: 0;
+ }
+ .mode-toggle.mode-toggle-three [data-llama-mode="unified"] > span::after {
+ content: 'Unif';
+ font-size: 11px;
+ }
+ }
+ /* Message count badge in the chat-meta header (next to the title).
+ Auto-hides when empty so a brand-new chat doesn't show "0 msgs". */
+ .chat-meta-count {
+ font-size: inherit;
+ font-weight: 400;
+ color: color-mix(in srgb, var(--fg) 35%, transparent);
+ white-space: nowrap;
+ user-select: none;
+ margin-left: 6px;
+ }
+ .chat-meta-count:empty { display: none; }
+ /* Session cost indicator (next to chevron in header) */
+ .session-cost-display {
+ font-size: inherit;
+ font-weight: 400;
+ color: color-mix(in srgb, var(--fg) 35%, transparent);
+ white-space: nowrap;
+ user-select: none;
+ margin-left: 7px;
+ margin-right: 5px;
+ }
+ .chat-context-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ height: auto;
+ padding: 0;
+ margin-left: 7px;
+ border: 0;
+ border-radius: 0;
+ background: transparent;
+ color: color-mix(in srgb, var(--fg) 35%, transparent);
+ font-family: inherit;
+ font-size: 0.7rem;
+ font-weight: 400;
+ line-height: 1;
+ cursor: pointer;
+ white-space: nowrap;
+ position: relative;
+ z-index: 2;
+ --ctx-stroke: var(--color-muted, #888);
+ transition: color 0.15s, opacity 0.15s;
+ }
+ .chat-context-pill[hidden] {
+ display: none !important;
+ }
+ .chat-context-pill:hover,
+ .chat-context-pill.open {
+ color: color-mix(in srgb, var(--fg) 70%, transparent);
+ --ctx-stroke: var(--ctx-color);
+ border: 0;
+ background: transparent;
+ }
+ .chat-context-pill.loading {
+ opacity: 0.55;
+ }
+ .chat-context-pill.warn {
+ color: var(--orange, #f59e0b);
+ background: transparent;
+ }
+ .chat-context-pill.danger {
+ color: var(--red, #ef4444);
+ background: transparent;
+ }
+ .chat-context-pill svg {
+ flex-shrink: 0;
+ }
+ .chat-context-pill .ctx-ring-pct {
+ color: currentColor;
+ font-size: inherit;
+ font-weight: inherit;
+ line-height: 1;
+ }
+ .chat-context-dot {
+ display: none;
+ }
+ .chat-context-popup {
+ position: fixed;
+ z-index: 10060;
+ width: 238px;
+ padding: 10px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--panel);
+ color: var(--fg);
+ box-shadow: 0 12px 34px color-mix(in srgb, #000 26%, transparent);
+ font-size: 11px;
+ line-height: 1.35;
+ }
+ .chat-context-popup.warn {
+ color: var(--orange, #f59e0b);
+ }
+ .chat-context-popup.danger {
+ color: var(--red, #ef4444);
+ }
+ .chat-context-popup-title {
+ font-weight: 650;
+ margin-bottom: 8px;
+ color: var(--accent, var(--red));
+ }
+ .chat-context-popup-bar {
+ height: 6px;
+ overflow: hidden;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ margin-bottom: 6px;
+ }
+ .chat-context-popup-fill {
+ height: 100%;
+ width: 0;
+ border-radius: inherit;
+ background: var(--red, var(--fg));
+ }
+ .chat-context-popup-row {
+ display: flex;
+ justify-content: space-between;
+ gap: 10px;
+ margin-top: 4px;
+ color: color-mix(in srgb, var(--fg) 70%, transparent);
+ }
+ .chat-context-popup-row span:last-child {
+ color: var(--fg);
+ text-align: right;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ max-width: 148px;
+ }
+ .chat-context-toggle-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ margin-top: 8px;
+ padding-top: 8px;
+ border-top: 1px solid color-mix(in srgb, var(--border) 45%, transparent);
+ }
+ .chat-context-toggle-copy {
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ min-width: 0;
+ color: color-mix(in srgb, var(--fg) 76%, transparent);
+ }
+ .chat-context-toggle-copy > span:first-child {
+ white-space: nowrap;
+ color: var(--accent, var(--red));
+ }
+ .chat-context-toggle-state {
+ font-size: 10px;
+ color: color-mix(in srgb, var(--fg) 45%, transparent);
+ }
+ .chat-context-toggle {
+ position: relative;
+ flex: 0 0 auto;
+ width: 32px;
+ height: 18px;
+ border: 1px solid color-mix(in srgb, var(--border) 75%, transparent);
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s, opacity 0.15s;
+ }
+ .chat-context-toggle::after {
+ content: "";
+ position: absolute;
+ top: 3px;
+ left: 3px;
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ background: color-mix(in srgb, var(--fg) 62%, transparent);
+ transition: transform 0.15s, background 0.15s;
+ }
+ .chat-context-toggle.active {
+ border-color: color-mix(in srgb, var(--accent) 55%, transparent);
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
+ }
+ .chat-context-toggle.active::after {
+ transform: translateX(14px);
+ background: var(--fg);
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--fg) 18%, transparent);
+ }
+ .chat-context-toggle:disabled {
+ opacity: 0.6;
+ cursor: default;
+ }
+ .chat-context-threshold-row {
+ margin-top: 8px;
+ }
+ .chat-context-threshold-top {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ margin-bottom: 5px;
+ color: color-mix(in srgb, var(--fg) 70%, transparent);
+ }
+ .chat-context-threshold-top span:last-child {
+ color: var(--fg);
+ font-variant-numeric: tabular-nums;
+ }
+ .chat-context-threshold-slider {
+ width: 100%;
+ margin: 0;
+ }
+ .chat-context-compact-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 1px;
+ width: 100%;
+ height: 26px;
+ margin-top: 9px;
+ border: 1px solid color-mix(in srgb, var(--accent) 40%, transparent);
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--accent) 12%, transparent);
+ color: var(--accent);
+ cursor: pointer;
+ font: inherit;
+ font-size: 11px;
+ font-weight: 600;
+ }
+ .chat-context-compact-btn svg { display: block; flex: 0 0 auto; margin-left: -2px; }
+ .chat-context-compact-btn svg circle:last-child {
+ stroke: var(--accent, var(--red));
+ transition: stroke-dasharray 0.22s ease;
+ }
+ .chat-context-compact-btn:hover svg circle:last-child {
+ stroke-dasharray: 35 0;
+ }
+ .chat-context-compact-btn:hover {
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
+ }
+ .chat-context-popup,
+ .chat-context-popup * {
+ font-size: 10px !important;
+ }
+ /* Model picker — input bar drop-up */
+ .model-picker-wrap {
+ position: relative;
+ flex-shrink: 0;
+ }
+ .model-picker-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ height: 21px;
+ padding: 0 6px;
+ font-size: 11px;
+ font-weight: 500;
+ font-family: inherit;
+ background: none;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ /* 65% mix lifts the model label above the WCAG AA 4.5:1 threshold
+ against the dark chat-bar (40% only reached ~2.9:1). */
+ color: color-mix(in srgb, var(--fg) 65%, transparent);
+ cursor: pointer;
+ white-space: nowrap;
+ transition: background 0.15s, color 0.15s, border-color 0.15s;
+ }
+ .model-picker-btn:hover {
+ border-color: var(--border);
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ color: var(--fg);
+ }
+ .model-picker-btn #model-picker-label {
+ max-width: 120px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .model-picker-btn svg {
+ flex-shrink: 0;
+ opacity: 0.5;
+ }
+ .model-picker-logo {
+ display: inline-flex;
+ align-items: center;
+ vertical-align: -2px;
+ }
+ .model-picker-logo svg {
+ width: 12px;
+ height: 12px;
+ opacity: 0.7;
+ }
+ .model-picker-menu {
+ position: absolute;
+ bottom: calc(100% + 16px);
+ right: 0;
+ z-index: 250;
+ min-width: 260px;
+ max-width: 360px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 -4px 20px rgba(0,0,0,0.4);
+ padding: 6px;
+ animation: picker-roll-up 0.2s ease-out;
+ transform-origin: bottom right;
+ }
+ .model-picker-menu.closing {
+ animation: picker-roll-down 0.15s ease-in forwards;
+ }
+ .model-picker-menu.hidden { display: none; }
+ .model-picker-search-row {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 30px;
+ gap: 4px;
+ align-items: center;
+ margin-bottom: 4px;
+ transition: grid-template-columns 0.18s ease, gap 0.18s ease;
+ }
+ .model-picker-menu.no-models .model-picker-search-row {
+ margin-bottom: 0;
+ }
+ .model-picker-search-row.searching {
+ grid-template-columns: minmax(0, 1fr) 0px;
+ gap: 0;
+ }
+ .model-picker-search-row.searching .model-picker-action-btn {
+ opacity: 0;
+ transform: translateX(10px) scale(0.88);
+ pointer-events: none;
+ }
+ .model-picker-search-wrap {
+ position: relative;
+ min-width: 0;
+ }
+ .model-picker-menu input[type="text"] {
+ width: 100%;
+ box-sizing: border-box;
+ padding: 6px 30px 6px 8px;
+ font-size: 0.82em;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--fg);
+ font-family: inherit;
+ outline: none;
+ min-width: 0;
+ transition: border-color 0.15s, padding 0.18s ease, background 0.18s ease;
+ }
+ .model-picker-menu input[type="text"]:focus {
+ border-color: var(--red);
+ }
+ .model-picker-menu input[type="text"]::placeholder {
+ color: color-mix(in srgb, var(--fg) 30%, transparent);
+ }
+ .model-picker-refresh-btn {
+ appearance: none;
+ position: absolute;
+ top: 50%;
+ right: 4px;
+ transform: translateY(-50%);
+ width: 22px;
+ height: 22px;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ color: color-mix(in srgb, var(--fg) 54%, transparent);
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0;
+ cursor: pointer;
+ }
+ .model-picker-refresh-btn:hover,
+ .model-picker-refresh-btn:focus-visible {
+ color: var(--fg);
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ outline: none;
+ }
+ .model-picker-refresh-btn:disabled {
+ opacity: 0.7;
+ cursor: default;
+ }
+ .model-picker-refresh-btn.spinning svg {
+ animation: model-picker-refresh-spin 0.75s linear infinite;
+ }
+ .model-picker-action-btn {
+ appearance: none;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 30px;
+ height: 30px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--fg) 4%, transparent);
+ color: color-mix(in srgb, var(--fg) 66%, transparent);
+ cursor: pointer;
+ padding: 0;
+ overflow: hidden;
+ transform: translateX(0) scale(1);
+ transition: opacity 0.16s ease, transform 0.18s ease, border-color 0.15s, color 0.15s, background 0.15s;
+ }
+ .model-picker-action-btn:hover,
+ .model-picker-action-btn:focus-visible {
+ border-color: var(--red);
+ color: var(--fg);
+ background: color-mix(in srgb, var(--red) 10%, var(--panel));
+ outline: none;
+ }
+ .model-picker-action-btn.primary {
+ color: var(--red);
+ background: color-mix(in srgb, var(--red) 8%, transparent);
+ }
+ .model-picker-action-btn svg {
+ width: 14px;
+ height: 14px;
+ transition: transform 0.28s ease;
+ }
+ .model-picker-action-btn:hover svg,
+ .model-picker-action-btn:focus-visible svg {
+ transform: rotate(90deg);
+ }
+ .model-picker-list {
+ max-height: min(280px, 50dvh);
+ overflow-y: auto;
+ }
+ .model-picker-list.is-loading {
+ max-height: min(120px, 28dvh);
+ overflow: hidden;
+ }
+ .model-picker-list.is-empty {
+ max-height: 0;
+ overflow: hidden;
+ }
+ .model-picker-list .model-picker-loading-row {
+ justify-content: center;
+ gap: 7px;
+ min-height: 38px;
+ padding: 8px 10px;
+ color: color-mix(in srgb, var(--fg) 58%, transparent);
+ font-size: 0.82em;
+ }
+ .model-picker-list .model-picker-loading-row .ai-spinner-whirlpool {
+ position: relative;
+ top: 1px;
+ }
+ .model-picker-list .model-switch-item {
+ display: flex;
+ align-items: center;
+ padding: 5px 8px;
+ border-radius: 4px;
+ cursor: pointer;
+ font-size: 0.82em;
+ color: var(--fg);
+ gap: 6px;
+ }
+ .model-picker-list .model-switch-item:hover {
+ background: color-mix(in srgb, var(--red) 8%, transparent);
+ }
+ .model-picker-list .model-switch-empty {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 5px 8px;
+ color: color-mix(in srgb, var(--fg) 50%, transparent);
+ font-size: 0.82em;
+ }
+ .model-picker-list .mp-section-label {
+ font-size: 0.72em;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ opacity: 0.4;
+ padding: 6px 8px 2px;
+ }
+ .model-picker-list .mp-section-label:first-child {
+ padding-top: 2px;
+ }
+ /* Model name takes the slack so the endpoint label + favorite dot sit on the right. */
+ .model-picker-list .model-switch-item .mp-model-name {
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .model-picker-list .model-switch-item .model-switch-ep {
+ flex: 0 1 auto;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 0.9em;
+ opacity: 0.45;
+ }
+ /* Keyboard navigation highlight (Arrow keys in the search box). */
+ .model-picker-list .model-switch-item.kb-active {
+ background: color-mix(in srgb, var(--red) 14%, transparent);
+ }
+ /* Inline favorite bookmark — always visible (works on touch), active when on. */
+ .model-picker-list .mp-fav-dot {
+ flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 30px;
+ height: 24px;
+ margin: -5px -8px -5px 8px;
+ padding: 0;
+ border: none;
+ background: transparent;
+ cursor: pointer;
+ color: color-mix(in srgb, var(--fg) 22%, transparent);
+ font-family: inherit;
+ font-size: 13px;
+ line-height: 1;
+ transition: color 0.15s ease, opacity 0.15s ease, transform 0.12s ease;
+ -webkit-tap-highlight-color: transparent;
+ }
+ .model-picker-list .mp-fav-dot:hover {
+ color: color-mix(in srgb, var(--fg) 68%, transparent);
+ }
+ .model-picker-list .mp-fav-dot:focus-visible {
+ outline: none;
+ color: color-mix(in srgb, var(--fg) 68%, transparent);
+ }
+ .model-picker-list .mp-fav-dot.active {
+ color: var(--accent, var(--red));
+ opacity: 1;
+ }
+ .model-picker-list .mp-fav-dot svg { display: block; }
+ .model-picker-list .mp-fav-dot.active:hover {
+ color: var(--accent, var(--red));
+ opacity: 0.72;
+ }
+ .model-picker-list .mp-fav-dot.pulse {
+ animation: mpFavPulse 0.32s ease-out;
+ }
+ @keyframes mpFavPulse {
+ 0% { text-shadow: 0 0 0 color-mix(in srgb, var(--accent, var(--red)) 0%, transparent); }
+ 45% { text-shadow: 0 0 10px color-mix(in srgb, var(--accent, var(--red)) 60%, transparent); }
+ 100% { text-shadow: 0 0 0 color-mix(in srgb, var(--accent, var(--red)) 0%, transparent); }
+ }
+ /* First-run hint when a large catalog has no Recent/Favorites yet. */
+ .model-picker-list .mp-empty-hint {
+ flex-direction: column;
+ gap: 2px;
+ padding: 14px 8px;
+ text-align: center;
+ }
+ .model-picker-list .mp-empty-hint .mp-empty-title {
+ font-size: 1.05em;
+ color: color-mix(in srgb, var(--fg) 70%, transparent);
+ }
+ .model-picker-list .mp-empty-hint .mp-empty-sub {
+ font-size: 0.92em;
+ opacity: 0.7;
+ }
+ /* Provider group headers */
+ .model-picker-list .mp-provider-header {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 8px;
+ cursor: pointer;
+ font-size: 0.78em;
+ font-weight: 500;
+ color: var(--fg);
+ border-radius: 4px;
+ user-select: none;
+ }
+ .model-picker-list .mp-provider-header:hover {
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ }
+ .model-picker-list .mp-provider-chevron {
+ display: inline-flex;
+ opacity: 0.4;
+ transition: transform 0.2s, opacity 0.15s;
+ flex-shrink: 0;
+ }
+ .model-picker-list .mp-provider-header:hover .mp-provider-chevron {
+ opacity: 0.7;
+ }
+ .model-picker-list .mp-provider-chevron.collapsed {
+ transform: rotate(-90deg);
+ }
+ .model-picker-list .mp-provider-name { flex: 1; }
+ .model-picker-list .mp-provider-count { font-size: 0.85em; opacity: 0.4; }
+ /* Domino expand (15% faster than sidebar) */
+ .mp-provider-group.mp-just-expanded .model-switch-item {
+ animation: mp-domino-in 0.31s cubic-bezier(0.22, 1.61, 0.36, 1) backwards;
+ }
+ .mp-provider-group.mp-just-expanded .model-switch-item:nth-child(1) { animation-delay: 0.035s; }
+ .mp-provider-group.mp-just-expanded .model-switch-item:nth-child(2) { animation-delay: 0.07s; }
+ .mp-provider-group.mp-just-expanded .model-switch-item:nth-child(3) { animation-delay: 0.105s; }
+ .mp-provider-group.mp-just-expanded .model-switch-item:nth-child(4) { animation-delay: 0.14s; }
+ .mp-provider-group.mp-just-expanded .model-switch-item:nth-child(5) { animation-delay: 0.175s; }
+ .mp-provider-group.mp-just-expanded .model-switch-item:nth-child(6) { animation-delay: 0.21s; }
+ .mp-provider-group.mp-just-expanded .model-switch-item:nth-child(7) { animation-delay: 0.245s; }
+ .mp-provider-group.mp-just-expanded .model-switch-item:nth-child(8) { animation-delay: 0.28s; }
+ .mp-provider-group.mp-just-expanded .model-switch-item:nth-child(9) { animation-delay: 0.315s; }
+ .mp-provider-group.mp-just-expanded .model-switch-item:nth-child(10) { animation-delay: 0.35s; }
+ @keyframes mp-domino-in {
+ 0% { opacity: 0; transform: translateY(6px) scale(0.94); }
+ 60% { opacity: 1; }
+ 100% { opacity: 1; transform: translateY(0) scale(1); }
+ }
+ /* Comfortable touch targets on phones / narrow screens. */
+ @media (hover: none) and (pointer: coarse), (max-width: 768px) {
+ .model-picker-list .model-switch-item {
+ padding-top: 8px;
+ padding-bottom: 8px;
+ }
+ .model-picker-list .mp-fav-dot {
+ width: 30px;
+ height: 30px;
+ margin: -7px -8px -7px 8px;
+ }
+ }
+ /* Overflow "+" menu */
+ .overflow-wrapper {
+ position: relative;
+ display: flex;
+ align-items: center;
+ }
+ .plus-active-dot {
+ position: absolute;
+ top: 4px;
+ right: 2px;
+ width: 6px;
+ height: 6px;
+ background: var(--fg);
+ border-radius: 50%;
+ display: none;
+ }
+ .overflow-plus-btn.has-active .plus-active-dot {
+ display: block;
+ }
+ .overflow-menu {
+ position: fixed;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ padding: 4px;
+ min-width: 170px;
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
+ z-index: 1000;
+ /* Container spring-in: the rounded panel scales/grows out of the
+ chevron's position before the menu items domino in on top. */
+ transform-origin: bottom left;
+ animation: overflow-menu-pop 0.08s ease-out;
+ }
+ @keyframes overflow-menu-pop {
+ 0% { transform: scale(0.96) translateY(2px); opacity: 0; }
+ 100% { transform: scale(1) translateY(0); opacity: 1; }
+ }
+ .overflow-menu.hidden {
+ display: none;
+ }
+ /* Closing state: JS adds `.closing` to play the fold-in animation,
+ waits for it to finish, then flips to `.hidden`. Container
+ scales/translates back into the chevron while items peel off from
+ the top down so the menu collapses into its anchor. */
+ .overflow-menu.closing {
+ animation: overflow-menu-pop-out 0.08s ease-in forwards;
+ animation-delay: 0s;
+ }
+ @keyframes overflow-menu-pop-out {
+ 0% { transform: scale(1) translateY(0); opacity: 1; }
+ 100% { transform: scale(0.96) translateY(2px); opacity: 0; }
+ }
+ .overflow-menu-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 8px 12px;
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.7;
+ cursor: pointer;
+ border-radius: 6px;
+ font-size: 13px;
+ font-family: inherit;
+ transition: background 0.15s, opacity 0.15s, color 0.15s;
+ /* Domino-style cascade: each item slides up + fades in with a tiny
+ delay after the previous one (set via nth-last-child below so the
+ BOTTOM item appears first and the cascade rolls upward — visually
+ feels like the menu is "stacking up" from the chevron). The
+ container itself springs in via .overflow-menu's keyframe. */
+ animation: overflow-item-in 0.08s ease-out backwards;
+ animation-delay: 0s !important;
+ }
+ .overflow-menu:not(.hidden):not(.closing) .overflow-menu-item:nth-last-child(1) { animation-delay: 0.06s; }
+ .overflow-menu:not(.hidden):not(.closing) .overflow-menu-item:nth-last-child(2) { animation-delay: 0.10s; }
+ .overflow-menu:not(.hidden):not(.closing) .overflow-menu-item:nth-last-child(3) { animation-delay: 0.14s; }
+ .overflow-menu:not(.hidden):not(.closing) .overflow-menu-item:nth-last-child(4) { animation-delay: 0.18s; }
+ .overflow-menu:not(.hidden):not(.closing) .overflow-menu-item:nth-last-child(5) { animation-delay: 0.22s; }
+ .overflow-menu:not(.hidden):not(.closing) .overflow-menu-item:nth-last-child(6) { animation-delay: 0.26s; }
+ .overflow-menu:not(.hidden):not(.closing) .overflow-menu-item:nth-last-child(7) { animation-delay: 0.30s; }
+ .overflow-menu:not(.hidden):not(.closing) .overflow-menu-item:nth-last-child(8) { animation-delay: 0.34s; }
+ .overflow-menu:not(.hidden):not(.closing) .overflow-menu-item:nth-last-child(9) { animation-delay: 0.38s; }
+ .overflow-menu:not(.hidden):not(.closing) .overflow-menu-item:nth-last-child(10) { animation-delay: 0.42s; }
+ @keyframes overflow-item-in {
+ 0% { opacity: 0; transform: translateY(10px) translateX(-6px) scale(0.9); }
+ 60% { opacity: 1; }
+ 100% { opacity: 1; transform: translateY(0) translateX(0) scale(1); }
+ }
+ /* Fold-in: items peel off top-down (mirror of the open's bottom-up
+ cascade) so the menu visibly empties before the container scales
+ back into the chevron. */
+ .overflow-menu.closing .overflow-menu-item {
+ animation: overflow-item-out 0.06s ease-in forwards;
+ animation-delay: 0s !important;
+ }
+ .overflow-menu.closing .overflow-menu-item:nth-child(1) { animation-delay: 0.00s; }
+ .overflow-menu.closing .overflow-menu-item:nth-child(2) { animation-delay: 0.02s; }
+ .overflow-menu.closing .overflow-menu-item:nth-child(3) { animation-delay: 0.04s; }
+ .overflow-menu.closing .overflow-menu-item:nth-child(4) { animation-delay: 0.06s; }
+ .overflow-menu.closing .overflow-menu-item:nth-child(5) { animation-delay: 0.08s; }
+ .overflow-menu.closing .overflow-menu-item:nth-child(6) { animation-delay: 0.10s; }
+ .overflow-menu.closing .overflow-menu-item:nth-child(7) { animation-delay: 0.12s; }
+ .overflow-menu.closing .overflow-menu-item:nth-child(8) { animation-delay: 0.14s; }
+ .overflow-menu.closing .overflow-menu-item:nth-child(9) { animation-delay: 0.16s; }
+ .overflow-menu.closing .overflow-menu-item:nth-child(10) { animation-delay: 0.18s; }
+ @keyframes overflow-item-out {
+ 0% { opacity: 1; transform: translateY(0) translateX(0) scale(1); }
+ 100% { opacity: 0; transform: translateY(6px) translateX(-3px) scale(0.92); }
+ }
+ .overflow-menu-item:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--red) 10%, transparent);
+ }
+ #overflow-attach-btn {
+ position: relative;
+ font-weight: 600;
+ }
+ #overflow-attach-btn svg {
+ transition: transform 0.16s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ .overflow-menu-item.active {
+ opacity: 1;
+ color: var(--fg);
+ }
+ .overflow-active-dot {
+ width: 6px;
+ height: 6px;
+ background: var(--fg);
+ border-radius: 50%;
+ margin-left: auto;
+ display: none;
+ flex-shrink: 0;
+ }
+ .overflow-menu-item.active .overflow-active-dot {
+ display: block;
+ }
+ .attach-strip {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ margin: 0 0 8px;
+ min-height: 0;
+ }
+ .attach-strip:empty {
+ display: none;
+ }
+ .attach-strip {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ margin: 6px 0 0;
+ min-height: 32px;
+ padding: 2px;
+ }
+ .attachment-placeholder {
+ display: flex;
+ align-items: center;
+ color: var(--fg);
+ opacity: 0.7;
+ font-style: italic;
+ padding: 4px 8px;
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ }
+ .attach-btn { width:32px; display:grid; place-items:center; }
+ .hidden { display:none; }
+ .toggle { position:relative; display:inline-block; width:30px; height:16px; vertical-align:middle; }
+ .toggle input { opacity:0; width:0; height:0; }
+ .toggle .slider {
+ position:absolute; cursor:pointer; top:0; left:0; right:0; bottom:0;
+ background:color-mix(in srgb, var(--fg) 15%, transparent); transition:background .08s; border-radius:8px;
+ }
+ .toggle .slider:before {
+ position:absolute; content:""; height:12px; width:12px; left:2px; top:2px;
+ background:var(--panel); border-radius:50%; transform:translateX(0); transition:transform .08s;
+ box-shadow:0 1px 2px rgba(0,0,0,0.25);
+ }
+ .toggle input:checked + .slider { background:var(--red); }
+ .toggle input:checked + .slider:before { transform:translateX(14px); }
+ .copy-btn {
+ position:absolute; top:6px; right:6px;
+ background:var(--bg); color:var(--fg);
+ border:1px solid var(--border); border-radius:6px;
+ font-size:12px; height:24px; padding:0 8px; cursor:pointer;
+ opacity:0; transition:.15s;
+ }
+ .msg:hover .copy-btn { opacity:1; }
+ .role-timestamp {
+ font-size:0.7rem; color:var(--color-muted-alt); font-weight:normal; margin-left:6px;
+ }
+ .msg-footer {
+ display:flex; align-items:center; gap:6px;
+ flex-wrap: wrap;
+ margin-top:6px;
+ color:var(--color-muted-alt); font-size:0.75rem;
+ position: relative;
+ }
+ .msg-footer .timestamp {
+ font-size:0.75rem; color:var(--color-muted-alt);
+ margin:0; opacity:1;
+ }
++ .msg-footer-enter {
++ animation: msg-footer-enter 180ms ease-out both;
++ }
++ @keyframes msg-footer-enter {
++ from { opacity: 0; transform: translateY(2px); }
++ to { opacity: 1; transform: translateY(0); }
++ }
++ @media (prefers-reduced-motion: reduce) {
++ .msg-footer-enter { animation: none; }
++ }
+ .msg-footer .response-metrics {
+ font-size:0.75rem; color:var(--color-muted-alt);
+ transition: color .15s;
+ }
+ .msg-footer .response-metrics:hover { color:var(--fg); }
+ .agent-thread > .agent-thread-footer {
+ margin-top: 4px;
+ margin-left: 2px;
+ }
+ /* Keep the context ring and percentage together at the footer's left edge. */
+ .ctx-ring {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ margin-left: 0;
+ line-height: 0;
+ opacity: 0.6;
+ cursor: default;
+ transition: opacity 0.15s;
+ --ctx-stroke: var(--color-muted, #888);
+ }
+ .ctx-ring .ctx-ring-pct {
+ color: var(--color-muted, #888);
+ transition: color 0.1s ease;
+ }
+ .ctx-ring svg circle {
+ transition: stroke 0.1s ease;
+ }
+ .ctx-ring:hover {
+ opacity: 1;
+ --ctx-stroke: var(--ctx-color);
+ }
+ .ctx-ring:hover .ctx-ring-pct {
+ color: var(--ctx-color);
+ }
+ .ctx-ring-pct {
+ font-size: 0.7rem;
+ font-weight: 600;
+ line-height: 1;
+ }
+ /* Context detail popup */
+ .ctx-detail-popup {
+ position: fixed;
+ z-index: 200;
+ background: var(--panel, var(--bg));
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 12px 14px;
+ box-shadow: 0 4px 20px rgba(0,0,0,0.4);
+ min-width: 220px;
+ max-width: 280px;
+ font-size: 0.85rem;
+ color: var(--fg);
+ }
+ .ctx-bar-wrap {
+ width: 100%;
+ height: 6px;
+ background: var(--border);
+ border-radius: 4px;
+ overflow: hidden;
+ }
+ .ctx-bar-fill {
+ height: 100%;
+ border-radius: 4px;
+ transition: width 0.3s;
+ }
+ .ctx-compact-btn {
+ display: block;
+ width: 100%;
+ margin-top: 10px;
+ padding: 6px 0;
+ background: none;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--fg);
+ font-size: 0.8rem;
+ cursor: pointer;
+ transition: border-color 0.15s, color 0.15s;
+ }
+ .ctx-compact-btn:hover {
+ border-color: var(--accent, var(--red));
+ color: var(--accent, var(--red));
+ }
+ .ctx-compact-btn:disabled {
+ opacity: 0.5;
+ cursor: default;
+ }
+ .compact-wave {
+ display: inline-block;
+ color: var(--accent, var(--red));
+ letter-spacing: 1px;
+ font-size: 0.9em;
+ }
+ /* Memory-used indicator pill */
+ .memory-used-pill {
+ display: inline-flex;
+ align-items: center;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ color: var(--fg);
+ font-size: 0.7rem;
+ padding: 2px 8px;
+ border-radius: 10px;
+ cursor: pointer;
+ opacity: 0.6;
+ transition: opacity 0.15s, background 0.15s;
+ white-space: nowrap;
+ position: relative;
+ z-index: 1;
+ }
+ .memory-used-pill:hover { opacity: 1; background: var(--border); }
+ /* Nudge label text 1px down so it visually centers with the icon. */
+ .memory-used-pill-text { position: relative; top: 1px; display: inline-block; }
+ .memory-used-detail {
+ position: fixed;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 6px 8px;
+ min-width: 200px;
+ max-width: min(360px, calc(100vw - 16px));
+ max-height: 50vh;
+ overflow-y: auto;
+ z-index: 300;
+ box-shadow: 0 4px 12px rgba(0,0,0,0.3);
+ font-size: 0.75rem;
+ }
+ .memory-used-row {
+ display: flex;
+ align-items: flex-start;
+ gap: 6px;
+ padding: 3px 0;
+ line-height: 1.3;
+ }
+ .memory-used-row + .memory-used-row {
+ border-top: 1px solid color-mix(in srgb, var(--border) 50%, transparent);
+ }
+ .memory-used-badge {
+ flex-shrink: 0;
+ font-size: 0.7rem;
+ width: 16px;
+ text-align: center;
+ }
+ .memory-used-badge.pinned { color: var(--red); }
+ .memory-used-badge.recalled { color: var(--fg); opacity: 0.5; }
+ .memory-used-text {
+ color: var(--fg);
+ opacity: 0.85;
+ }
+
+ .msg-actions {
+ display:inline-flex; align-items:center; gap:4px;
+ }
+ .footer-copy-btn {
+ background:none; border:none;
+ color:var(--color-muted-alt); cursor:pointer;
+ padding:2px 6px; border-radius:4px;
+ transition: color .15s;
+ line-height:1;
+ display: inline-flex; align-items: center; justify-content: center;
+ }
+ .footer-copy-btn:hover { color:var(--accent); }
+ .footer-open-gallery-btn {
+ gap: 4px;
+ font-size: 11px;
+ }
+ /* Delete action — same chrome as copy/download/edit but hover reveals
+ the destructive red tint so the user can tell it's not a benign op. */
+ .footer-delete-btn:hover { color: var(--red); }
+ .regen-btn {
+ background:none; border:none;
+ color:var(--color-muted-alt); font-size:1.1rem; cursor:pointer;
+ padding:2px 6px; border-radius:4px;
+ transition: color .15s;
+ line-height:1;
+ }
+ .regen-btn:hover { color:var(--accent); }
+ .fork-btn {
+ background:none; border:none;
+ color:var(--color-muted-alt); font-size:1.1rem; cursor:pointer;
+ padding:2px 6px; border-radius:4px;
+ transition: color .15s;
+ line-height:1;
+ }
+ .fork-btn:hover { color:var(--accent); }
+ .msg-action-btn {
+ background:none; border:none;
+ color:var(--muted, var(--color-muted-alt)); font-size:1.1rem; cursor:pointer;
+ padding:2px 6px; border-radius:4px;
+ transition: color .15s;
+ line-height:1;
+ }
+ .msg-action-btn:hover { color:var(--accent); }
+ .msg-action-btn .resend-message-icon {
+ display:block;
+ width:13px;
+ height:13px;
+ transform:translateY(1px);
+ }
+ .msg-action-btn[data-action="shorten"] { position:relative; top:1px; font-size:1.25rem; }
+ .msg-delete-btn { position:relative; top:1px; }
+ .msg-delete-btn:hover { color:var(--red); }
+ .msg-more-btn {
+ font-size:0.7rem; letter-spacing:0.5px;
+ }
+ .msg-overflow-menu {
+ position:fixed;
+ background:var(--panel);
+ border:1px solid var(--border);
+ border-radius:6px;
+ padding:4px;
+ box-shadow:0 4px 16px rgba(0,0,0,0.4);
+ z-index:100;
+ min-width:150px;
+ }
+ .msg-overflow-item {
+ display:flex;
+ align-items:center;
+ gap:6px;
+ width:100%;
+ background:none;
+ border:none;
+ border-bottom:1px solid color-mix(in srgb, var(--border) 40%, transparent);
+ color:var(--fg);
+ font-size:0.8rem;
+ padding:5px 8px;
+ border-radius:4px;
+ cursor:pointer;
+ text-align:left;
+ font-family:inherit;
+ transition:background .1s;
+ }
+ .msg-overflow-item:last-child { border-bottom:none; }
+ .msg-overflow-item:hover {
+ background:color-mix(in srgb, var(--red) 8%, transparent);
+ }
+ .overflow-icon {
+ width:16px;
+ text-align:center;
+ flex-shrink:0;
+ font-size:1rem;
+ }
+ .overflow-icon .resend-message-icon {
+ display:block;
+ width:13px;
+ height:13px;
+ margin:0 auto;
+ }
+ .variant-nav {
+ display:inline-flex;
+ align-items:center;
+ gap:0px;
+ margin-left:auto;
+ font-size:0.85em;
+ font-family:inherit;
+ opacity:0.6;
+ }
+ .variant-divider {
+ opacity:0.25;
+ margin:0 4px 0 2px;
+ }
+ .variant-tag {
+ font-size:1.1em;
+ opacity:0.8;
+ margin-right:2px;
+ position:relative;
+ top:-1px;
+ }
+ .variant-tag-scissors {
+ top:-1px;
+ }
+ /* The ✂ "Rewrite shorter" action button glyph sits a touch low against the
+ other footer icons — nudge it up 2px. */
+ .msg-action-btn[data-action="shorten"] {
+ position: relative;
+ top: -2px;
+ }
+ /* The "?" Explain-simpler glyph also sits slightly low — nudge it up 1px. */
+ .msg-action-btn[data-action="explain"] {
+ position: relative;
+ top: -1px;
+ }
+ .variant-btn {
+ background:none;
+ border:none;
+ color:var(--fg);
+ cursor:pointer;
+ padding:4px 6px;
+ font-size:1em;
+ font-family:inherit;
+ opacity:0.7;
+ line-height:1;
+ }
+ .variant-btn:hover { opacity:1; color:var(--fg); }
+ .variant-btn:disabled { opacity:0.3; cursor:default; }
+ .variant-num {
+ background:none;
+ border:none;
+ color:var(--fg);
+ cursor:pointer;
+ padding:4px 4px;
+ font-size:1em;
+ font-family:inherit;
+ opacity:0.7;
+ line-height:1;
+ }
+ .variant-num:hover { opacity:1; color:var(--fg); }
+ .variant-num:disabled { opacity:0.5; cursor:default; }
+ .variant-slash {
+ opacity:0.4;
+ font-size:1em;
+ }
+ .continue-separator {
+ display:inline;
+ opacity:0.35;
+ font-size:0.85em;
+ font-style:italic;
+ }
+ .stopped-indicator {
+ color:var(--red);
+ margin-top:8px;
+ font-size:0.85em;
+ opacity:0.8;
+ display:flex;
+ align-items:center;
+ gap:8px;
+ flex-wrap:wrap;
+ }
+
+ /* Message edit UI */
+ .msg-edit-textarea {
+ background:var(--bg);
+ color:var(--fg);
+ border:1px solid var(--border);
+ border-radius:6px;
+ padding:10px;
+ font-family:inherit;
+ font-size:inherit;
+ line-height:1.6;
+ resize:vertical;
+ box-sizing:border-box;
+ }
+ .msg-edit-textarea:focus { outline:1px solid var(--hl-function, #61afef); border-color:var(--hl-function, #61afef); }
+ .msg-edit-bar {
+ display:flex;
+ gap:8px;
+ margin-top:6px;
+ }
+ .msg-edit-save, .msg-edit-cancel {
+ background:var(--bg);
+ color:var(--fg);
+ border:1px solid var(--border);
+ border-radius:6px;
+ padding:4px 14px;
+ cursor:pointer;
+ font-size:0.85em;
+ }
+ .msg-edit-save:hover { border-color:var(--color-save-green, #4caf50); color:var(--color-save-green, #4caf50); }
+ .msg-edit-cancel:hover { border-color:var(--red); color:var(--red); }
+
+ /* Edited indicator — similar to stopped-indicator */
+ .edited-indicator {
+ color:var(--fg);
+ margin-top:8px;
+ font-size:0.85em;
+ opacity:0.4;
+ font-style:italic;
+ }
+ .continue-btn {
+ background:none;
+ border:none;
+ color:var(--fg);
+ opacity:0.5;
+ cursor:pointer;
+ font-size:2.6em;
+ padding:2px 2px 0;
+ line-height:1;
+ }
+ .continue-btn:hover {
+ opacity:0.8;
+ }
+ .continue-btn.resume-btn {
+ display:inline-flex;
+ align-items:center;
+ justify-content:space-between;
+ gap:8px;
+ padding:3px 8px 3px 5px;
+ border:none;
+ border-radius:5px;
+ font-size:0.85em;
+ font-weight:400;
+ line-height:1.2;
+ position:relative;
+ top:2px;
+ }
+ .continue-btn.resume-btn:hover {
+ border:none;
+ }
++ .agent-finish-editor {
++ margin: 4px 0 6px 16px;
++ font-size: 0.8em;
++ }
++ .agent-finish-editor:disabled {
++ cursor: default;
++ opacity: 0.5;
++ }
+ .continue-btn.resume-btn .resume-btn-icon {
+ display:block;
+ width:16px;
+ height:16px;
+ flex:0 0 16px;
+ margin-left:auto;
+ }
+
+ /* Round-cap "Continue" affordance — a cohesive centered pill at the chat
+ bottom (not the bare red in-message stopped style). */
+ .rounds-exhausted {
+ justify-content:center;
+ gap:12px;
+ width:fit-content;
+ max-width:90%;
+ margin:14px auto 4px;
+ padding:7px 8px 7px 16px;
+ border:1px solid var(--border);
+ border-radius:999px;
+ background:color-mix(in srgb, var(--fg) 4%, transparent);
+ opacity:1;
+ }
+ .rounds-exhausted .rounds-exhausted-label {
+ color:color-mix(in srgb, var(--fg) 60%, transparent);
+ font-size:0.95em;
+ }
+ .rounds-exhausted .continue-btn {
+ font-size:0.9em;
+ font-weight:600;
+ opacity:1;
+ color:var(--bg);
+ background:var(--accent, var(--red));
+ border-radius:999px;
+ padding:4px 14px;
+ line-height:1.3;
+ }
+ .rounds-exhausted .continue-btn:hover {
+ opacity:0.88;
+ }
+ .ctx-indicator {
+ display:inline-flex; align-items:center; gap:1px;
+ font-size:0.75rem;
+ }
+ .ctx-popup {
+ position:fixed;
+ z-index:250;
+ background:var(--panel);
+ border:1px solid var(--border);
+ border-radius:8px;
- padding:11px 13px 12px;
++ padding:9px 12px 10px;
+ font-size:0.78rem;
+ color:var(--fg);
+ box-shadow:0 8px 24px rgba(0,0,0,0.4);
- min-width:250px;
++ min-width:280px;
+ max-width:min(360px, calc(100vw - 16px));
+ line-height:1.45;
+ }
+ .ctx-label {
+ display:block;
+ width:auto;
+ color:var(--color-muted-alt);
+ font-size:0.75rem;
+ }
+ .ctx-popup-title {
+ display:flex;
+ align-items:center;
+ gap:6px;
+ margin-bottom:8px;
+ padding-bottom:7px;
+ border-bottom:1px solid color-mix(in srgb, var(--border) 65%, transparent);
+ font-weight:650;
+ letter-spacing:.01em;
+ }
+ .ctx-popup-title::before {
+ content:'';
+ width:6px;
+ height:6px;
+ flex:0 0 6px;
+ border-radius:50%;
+ background:var(--accent, var(--red));
+ box-shadow:0 0 0 3px color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ }
+ .ctx-stat-section {
+ display:flex;
+ flex-direction:column;
- gap:4px;
++ gap:2px;
+ }
+ .ctx-stat-section + .ctx-stat-section {
- margin-top:9px;
- padding-top:8px;
++ margin-top:6px;
++ padding-top:6px;
+ border-top:1px solid color-mix(in srgb, var(--border) 45%, transparent);
+ }
+ .ctx-stat-row {
+ display:grid;
- grid-template-columns:minmax(0, 1fr) auto;
++ grid-template-columns:minmax(82px, 1fr) minmax(0, 2fr);
+ align-items:baseline;
- gap:14px;
- min-height:18px;
++ gap:10px;
++ min-height:16px;
+ }
+ .ctx-stat-row .ctx-label {
+ white-space:nowrap;
+ }
+ .ctx-stat-value {
+ color:var(--fg);
+ text-align:right;
+ font-variant-numeric:tabular-nums;
+ white-space:nowrap;
++ overflow:hidden;
++ text-overflow:ellipsis;
+ }
+ .edit-btn {
+ background:none; border:none;
+ color:var(--color-muted-alt); font-size:1.1rem; cursor:pointer;
+ padding:2px 6px; border-radius:4px;
+ transition: color .15s;
+ line-height:1;
+ }
+ .edit-btn:hover { color:var(--accent); }
+ .edit-textarea {
+ width:100%; background:var(--bg); color:var(--fg);
+ border:1px solid var(--border); border-radius:6px;
+ padding:8px; font-family:inherit; font-size:0.95rem;
+ resize:vertical; outline:none;
+ min-height:80px;
+ }
+ .edit-textarea:focus { border-color:var(--red); }
+ .edit-save-btn, .edit-cancel-btn {
+ background:var(--bg); color:var(--fg);
+ border:1px solid var(--border); border-radius:6px;
+ padding:4px 12px; cursor:pointer; font-size:0.8rem;
+ display:inline-flex; align-items:center; justify-content:center; gap:5px;
+ }
+ .edit-save-btn:hover { background:var(--panel); }
+ .edit-cancel-btn:hover { background:var(--panel); }
+ pre .copy-code {
+ position:absolute; right:6px;
+ background:var(--bg); color:var(--fg);
+ border:1px solid var(--border); border-radius:6px;
+ width:28px; height:28px; padding:0; cursor:pointer;
+ opacity:0; transition: opacity .15s, color .15s, border-color .15s;
+ display:flex; align-items:center; justify-content:center;
+ }
+ pre .copy-code { top:6px; }
+ pre .copy-code.bottom { top:auto; bottom:6px; }
+ pre:hover .copy-code { opacity:0.7; }
+ pre .copy-code:hover { opacity:1; }
+ pre .copy-code.copied {
+ opacity: 1;
+ color: var(--color-save-green, #4caf50);
+ border-color: var(--color-save-green, #4caf50);
+ background: color-mix(in srgb, var(--color-save-green, #4caf50) 18%, var(--bg));
+ animation: code-copy-pulse 0.36s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ @keyframes code-copy-pulse {
+ 0% { transform: scale(1); }
+ 50% { transform: scale(1.15); }
+ 100% { transform: scale(1); }
+ }
+ /* Slim text-button variant: swap "Copy" → "✓ Copied" via the
+ ::before content while still inheriting the green flash + pulse. */
+ pre.pre-compact .copy-code.copied::before { content: '✓ Copied'; }
+
+ /* Edit code button — positioned left of copy button */
+ pre .edit-code {
+ position:absolute; right:42px; top:6px;
+ background:var(--bg); color:var(--fg);
+ border:1px solid var(--border); border-radius:6px;
+ width:28px; height:28px; padding:0; cursor:pointer;
+ opacity:0; transition: opacity .15s, color .15s, border-color .15s;
+ display:flex; align-items:center; justify-content:center;
+ }
+ pre .edit-code.bottom { top:auto; bottom:6px; }
+ pre:hover .edit-code { opacity:0.7; }
+ pre .edit-code:hover { opacity:1; }
+ /* When the edit-code button is in "save" mode (checkmark), use the
+ theme accent so it matches the EDITING outline + label that are
+ also accent-coloured — clearer that this is the confirm action. */
+ pre .edit-code.active {
+ opacity: 1;
+ color: var(--accent-primary, var(--red));
+ border-color: var(--accent-primary, var(--red));
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 12%, var(--bg));
+ }
+ pre .use-code {
+ position:absolute; right:42px; top:6px;
+ background:var(--bg); color:var(--fg);
+ border:1px solid var(--border); border-radius:6px;
+ width:28px; height:28px; padding:0; cursor:pointer;
+ opacity:0; transition: opacity .15s, color .15s, border-color .15s;
+ display:flex; align-items:center; justify-content:center;
+ }
+ pre .use-code.bottom { top:auto; bottom:6px; }
+ pre:hover .use-code { opacity:0.7; }
+ pre .use-code:hover { opacity:1; }
+ pre .use-code.used {
+ opacity: 1;
+ color: var(--color-save-green, #4caf50);
+ border-color: var(--color-save-green, #4caf50);
+ background: color-mix(in srgb, var(--color-save-green, #4caf50) 18%, var(--bg));
+ animation: code-copy-pulse 0.36s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ .setup-trigger-link, .setup-clickable-provider, .setup-clickable-code {
+ transition: color 0.15s ease, opacity 0.15s ease;
+ }
+ .setup-trigger-link:hover,
+ .setup-clickable-provider:hover,
+ .setup-clickable-code:hover {
+ color: var(--accent, var(--red)) !important;
+ opacity: 0.9;
+ }
+
+ /* Tapping the code body (not a button) toggles the overlay buttons off so
+ they stop covering the text on touch screens. Tap again to bring back. */
+ pre.buttons-hidden .copy-code,
+ pre.buttons-hidden .edit-code,
+ pre.buttons-hidden .run-code { opacity:0 !important; pointer-events:none !important; }
+
+ /* Editing state — subtle border on the code block */
+ /* Editing state: was a 1px subtle outline that was almost invisible on
+ mobile, so users couldn't tell their tap-to-edit had actually engaged.
+ Use the accent colour + a tinted background so it reads at a glance. */
+ pre.editing {
+ outline: 2px solid var(--accent-primary, var(--red));
+ outline-offset: -2px;
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 6%, var(--bg)) !important;
+ }
+ pre.editing code.editing { outline:none; cursor:text; }
+ pre.editing::before {
+ content: 'EDITING';
+ position: absolute; top: 0; left: 0;
+ padding: 2px 8px;
+ font-size: 9px; font-weight: 700; letter-spacing: 0.5px;
+ background: var(--accent-primary, var(--red));
+ color: #fff;
+ border-radius: 0 0 4px 0;
+ z-index: 2;
+ pointer-events: none;
+ }
+
+ /* Run code button — positioned left of edit button */
+ pre .run-code {
+ position:absolute; right:78px; top:6px;
+ background:var(--bg); color:var(--fg);
+ border:1px solid var(--border); border-radius:6px;
+ width:28px; height:28px; padding:0; cursor:pointer;
+ opacity:0; transition: opacity .15s, color .15s, border-color .15s;
+ display:flex; align-items:center; justify-content:center;
+ }
+ pre .run-code.bottom { top:auto; bottom:6px; }
+ pre:hover .run-code { opacity:0.7; }
+ pre .run-code:hover { opacity:1; color:var(--hl-function, #61afef); border-color:var(--hl-function, #61afef); }
+
+ /* Compact (single-line) code blocks: slim buttons so the row doesn't
+ double the height of a 1-line bash. Copy is text ("Copy" → "✓ Copied"),
+ Run and Edit keep their icons but at smaller sizes. Edit swaps to
+ a "Save" text label when its .active state is on. */
+ pre.pre-compact { padding-right: 200px; min-height: 0; }
+ pre.pre-compact .copy-code,
+ pre.pre-compact .edit-code,
+ pre.pre-compact .run-code {
+ height: 20px;
+ padding: 0;
+ font-size: 10px;
+ font-weight: 500;
+ line-height: 20px;
+ top: 3px;
+ }
+ /* Copy: text-only, hide SVG */
+ pre.pre-compact .copy-code {
+ width: auto;
+ padding: 0 8px;
+ right: 6px;
+ gap: 0;
+ }
+ pre.pre-compact .copy-code svg { display: none; }
+ pre.pre-compact .copy-code::before { content: 'Copy'; }
+ pre.pre-compact .copy-code.copied::before { content: '✓ Copied'; }
+ /* Edit: icon + "Edit" label, swap to "Save" when editing */
+ pre.pre-compact .edit-code {
+ width: auto;
+ padding: 0 8px 0 6px;
+ gap: 3px;
+ right: 64px;
+ }
+ pre.pre-compact .edit-code svg { width: 12px; height: 12px; }
+ pre.pre-compact .edit-code::after { content: 'Edit'; }
+ pre.pre-compact .edit-code.active::after { content: 'Save'; }
+ /* Run: icon + "Run" label */
+ pre.pre-compact .run-code {
+ width: auto;
+ padding: 0 8px 0 6px;
+ gap: 3px;
+ right: 126px;
+ }
+ pre.pre-compact .run-code svg { width: 12px; height: 12px; }
+ pre.pre-compact .run-code::after { content: 'Run'; }
+ /* Bottom-positioned slim buttons (when pre is near the top of the
+ viewport, the existing JS toggles .bottom to flip them down). */
+ pre.pre-compact .copy-code.bottom,
+ pre.pre-compact .edit-code.bottom,
+ pre.pre-compact .run-code.bottom { top: auto; bottom: 3px; }
+
+ /* Touch devices: no hover, so always show copy/run/edit buttons */
+ @media (hover: none) {
+ pre .copy-code { opacity:0.7; }
+ pre .edit-code { opacity:0.7; }
+ pre .run-code { opacity:0.7; }
+ }
+
+ /* Code runner output panel */
+ .code-runner-output {
+ position:relative;
+ border:1px solid var(--border); border-top:2px solid var(--hl-function, #61afef);
+ border-radius:0 0 4px 4px;
+ background:var(--bg);
+ margin:-4px 0 8px 0;
+ padding:8px 12px;
+ max-height:400px;
+ overflow:auto;
+ }
+
+ /* Chat-native visual explanations render in an isolated preview. */
+ .chat-svg-visual {
+ width: 100%;
+ max-width: 760px;
+ margin: 12px 0 16px;
+ }
+ .chat-svg-preview {
+ display: block;
+ width: 100%;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--bg);
+ }
+ .code-runner-pre {
+ margin:0; padding:0;
+ font-family:'Fira Code', 'Courier New', monospace;
+ font-size:0.9em; line-height:1.5;
+ white-space:pre-wrap; word-break:break-word;
+ color:var(--fg);
+ background:none !important;
+ border:none !important;
+ }
+ .code-runner-error { color:var(--red); }
+ .code-runner-loading { font-style:italic; color:var(--red); padding:4px 0; }
+ .code-runner-close {
+ position:absolute; top:4px; right:4px;
+ background:none; border:none; color:var(--fg);
+ cursor:pointer; opacity:0.5; font-size:14px; padding:2px 6px;
+ }
+ .code-runner-close:hover { opacity:1; }
+ /* Labeled copy pill — pinned top-right INSIDE the run-output panel, not
+ in a separate footer. Panel is position:relative so absolute works. */
+ .code-runner-copy-inline {
+ position: absolute; top: 6px; right: 32px; /* sits LEFT of the X close (top:4 right:4 ~24px wide) */
+ z-index: 2;
+ background: var(--panel); color: var(--fg);
+ border: 1px solid var(--border); border-radius: 6px;
+ padding: 3px 10px; font-size: 11px; cursor: pointer;
+ display: inline-flex; align-items: center;
+ transition: border-color 0.15s, color 0.15s, background 0.15s;
+ }
+ .code-runner-copy-inline:hover {
+ border-color: var(--accent-primary, var(--red));
+ color: var(--accent-primary, var(--red));
+ }
+ /* Reserve room on the right so the output text doesn't slide under
+ either the Copy pill or the Close X. Applies to both the chat run
+ panel AND the document panel (doc-run-output reuses the same children). */
+ .code-runner-output,
+ .doc-run-output { padding-right: 110px; }
+
+ .toast {
+ position:fixed;
+ top: 16px; right: 16px;
+ left: auto; bottom: auto;
+ background:var(--panel); color:var(--fg);
+ border:1px solid color-mix(in srgb, var(--accent) 30%, transparent);
+ border-left: 3px solid var(--accent);
+ padding:9px 9px 9px 10px; border-radius:8px; font-size:12px; opacity:0;
+ /* Off-screen to the right by default; .show slides to 0;
+ removing .show transitions to -120% (off-screen left). */
+ transform: translateX(120%);
+ transition: opacity .35s cubic-bezier(0.22, 1, 0.36, 1),
+ transform .45s cubic-bezier(0.22, 1, 0.36, 1);
+ /* Toasts must stay above the chat-context settings popup so a setting
+ change is visible while that popup remains open. */
+ z-index: 10070; pointer-events: none;
+ box-shadow: 0 4px 12px rgba(0,0,0,0.2);
+ backdrop-filter: blur(12px);
+ max-width: min(420px, calc(100vw - 32px));
+ min-width: min(240px, calc(100vw - 32px));
+ min-height: 40px;
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr) auto;
+ align-items: start;
+ column-gap: 8px;
+ box-sizing: border-box;
+ }
+ .toast.show { opacity:1; transform: translateX(0); }
+ .toast:not(:has(.toast-checkmark, .toast-whirlpool, .toast-error-icon)) {
+ grid-template-columns: minmax(0, 1fr) auto;
+ }
+ .toast-message {
+ min-width: 0;
+ padding: 3px 0 2px;
+ position: relative;
+ top: 0;
+ line-height: 1.35;
+ overflow-wrap: anywhere;
+ }
+ .toast.toast-ai-reply-progress .toast-message {
+ top: 2px;
+ }
+ .toast.toast-ai-reply-result .toast-message {
+ top: 0;
+ }
+ .toast.toast-sending .toast-message {
+ top: 2px;
+ }
+ .toast.toast-message-sent .toast-message {
+ top: 4px;
+ }
+ .toast-actions {
+ display: inline-flex;
+ align-items: center;
+ align-self: start;
+ gap: 3px;
+ margin-left: 2px;
+ }
+ .toast-action-btn {
+ min-height: 26px;
+ padding: 3px 7px 3px 9px;
+ border: 1px solid color-mix(in srgb, var(--fg) 34%, transparent);
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--fg) 4%, transparent);
+ color: var(--fg);
+ cursor: pointer;
+ font: inherit;
+ font-weight: 600;
+ line-height: 1;
+ pointer-events: auto;
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ transition: border-color 0.15s ease, background 0.15s ease;
+ }
+ .toast-action-btn:hover {
+ border-color: color-mix(in srgb, var(--accent) 65%, var(--border));
+ background: color-mix(in srgb, var(--accent) 10%, transparent);
+ }
+ .toast-action-icon { display: inline-flex; align-items: center; }
+ .toast-action-hint {
+ padding: 2px 4px;
+ border: 0;
+ border-radius: 3px;
+ background: color-mix(in srgb, var(--fg) 9%, transparent);
+ color: inherit;
+ font: 500 8px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ letter-spacing: 0.2px;
+ opacity: 0.62;
+ text-transform: uppercase;
+ pointer-events: none;
+ }
+ .toast .toast-checkmark {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 16px;
+ height: 16px;
+ margin-top: 5px;
+ margin-right: 0;
+ position: relative;
+ top: 4px;
+ color: var(--accent, var(--red));
+ vertical-align: -3px;
+ transform: scale(0.65);
+ opacity: 0;
+ animation: toastCheckPop 360ms cubic-bezier(0.2, 0.9, 0.25, 1.25) forwards;
+ }
+ .toast .toast-checkmark svg polyline {
+ stroke-dasharray: 24;
+ stroke-dashoffset: 24;
+ animation: toastCheckDraw 420ms ease-out 120ms forwards;
+ }
+ .toast .toast-whirlpool {
+ position: relative;
+ top: 4px;
+ }
+ @keyframes toastCheckPop {
+ 0% { opacity: 0; transform: scale(0.65); }
+ 65% { opacity: 1; transform: scale(1.16); }
+ 100% { opacity: 1; transform: scale(1); }
+ }
+ @keyframes toastCheckDraw {
+ to { stroke-dashoffset: 0; }
+ }
+ .toast-close-btn {
+ margin-left: 0;
+ padding: 0;
+ width: 22px;
+ height: 22px;
+ line-height: 1;
+ border: none;
+ background: none;
+ color: var(--fg);
+ opacity: 0.5;
+ cursor: pointer;
+ font-size: 16px;
+ border-radius: 50%;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ pointer-events: auto;
+ flex-shrink: 0;
+ transition: transform 0.22s ease, opacity 0.15s ease, background 0.15s ease;
+ }
+ .toast-error-icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 17px;
+ height: 17px;
+ margin-top: 4px;
+ border: 1px solid currentColor;
+ border-radius: 50%;
+ font-size: 10px;
+ font-weight: 800;
+ line-height: 1;
+ }
+ .toast-close-btn:hover {
+ opacity: 1;
+ transform: rotate(90deg);
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
+ .toast.exiting {
+ opacity: 0;
+ transform: translateX(-120%);
+ }
+ .toast.error {
+ border-color: color-mix(in srgb, var(--color-error) 40%, transparent);
+ border-left-color: var(--color-error);
+ color: var(--color-error);
+ }
+ /* When the notes panel is docked to the right, the toast enters from the
+ panel side. ui.js supplies the exact right edge and available width. */
+ body:has(.notes-pane.modal-right-docked) .toast {
+ transform: translateX(-120%);
+ }
+ body:has(.notes-pane.modal-right-docked) .toast.show { transform: translateX(0); }
+ body:has(.notes-pane.modal-right-docked) .toast.exiting { transform: translateX(120%); }
+ /* Notes-only panel-aware placement. Documents and Email retain the normal
+ top-right toast position. */
+ .toast.toast-panel-offset { transform: translateX(120%); }
+ .toast.toast-panel-offset.show { transform: translateX(0); }
+ .toast.toast-panel-offset.exiting { transform: translateX(-120%); }
+ @media (max-width: 768px) {
+ .toast {
+ top: 12px;
+ right: 12px;
+ max-width: calc(100vw - 24px);
+ /* Receive touches so the swipe-to-dismiss gesture works (desktop keeps
+ pointer-events:none so the toast never blocks clicks). Horizontal pan
+ only, so it doesn't fight page scroll. */
+ pointer-events: auto;
+ touch-action: pan-x;
+ }
+ .toast-action-hint { display: none; }
+ }
+
+ .stop-btn {
+ position:absolute; top:2px; right:2px;
+ background:var(--panel);
+ color:var(--fg);
+ border:1px solid var(--fg);
+ font-family:inherit;
+ font-size:1em; line-height:1; padding:2px 5px;
+ cursor:pointer;
+ }
+ .small-note { font-size:12px; color:color-mix(in srgb, var(--fg) 60%, transparent); margin-top:4px; }
+ .row-end { justify-content:flex-end; }
+ .model-chat-btn {
+ height:32px; padding:0 10px; margin-left:auto;
+ }
+ /* Nudge the "+ Chat" label down 1px to sit centered in the button. */
+ .model-chat-btn-label {
+ position: relative;
+ top: 1px;
+ }
+ .openai-row {
+ display:flex; align-items:center; gap:6px;
+ }
+ .models-row {
+ display:flex; align-items:center; gap:6px; border:1px solid var(--border); padding:4px; margin:4px 0; border-radius: 4px;
+ }
+ .models-row .grow,
+ .models-row select {
+ flex:1;
+ display:flex;
+ align-items:center;
+ font-size: 9.75px;
+ }
+ .model-fav-btn {
+ width: 8px; height: 8px;
+ border-radius: 50%;
+ border: 1.5px solid color-mix(in srgb, var(--fg) 22%, transparent);
+ flex-shrink: 0;
+ cursor: pointer;
+ transition: all 0.15s;
+ position: relative;
+ margin-left: 4px;
+ }
+ .model-fav-btn::before {
+ content: '';
+ position: absolute;
+ top: -10px; left: -10px; right: -10px; bottom: -10px;
+ }
+ .model-fav-btn:hover {
+ border-color: var(--fg);
+ background: color-mix(in srgb, var(--fg) 27%, transparent);
+ transform: scale(1.3);
+ }
+ .model-fav-btn.active {
+ background: var(--fg);
+ border-color: var(--fg);
+ }
+ .model-fav-btn.active:hover {
+ opacity: 0.6;
+ }
+ .model-search-input {
+ width: 100%;
+ padding: 6px 10px;
+ margin-bottom: 4px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--bg);
+ color: var(--fg);
+ font-family: inherit;
+ font-size: 0.8rem;
+ outline: none;
+ box-sizing: border-box;
+ transition: border-color 0.15s;
+ }
+ .model-search-input:focus {
+ border-color: var(--red);
+ }
+ .model-search-input::placeholder {
+ color: color-mix(in srgb, var(--fg) 30%, transparent);
+ }
+ .models-row button {
+ font-size: 9px;
+ height: 24px;
+ padding: 0 8px;
+ }
+ @media (max-width:768px){
+ .box { max-height:none; }
+ .chat-container { padding:10px; flex:1; margin-top:0; padding-top:42px; min-height:0; }
+ .scroll-nav-btn { width:44px; height:44px; font-size:14px; margin-bottom:0; }
+ .send-btn { width:48px; height:48px !important; border-radius:12px; }
+ .send-btn svg { width:22px; height:22px; }
+ #compare-toggle-btn { display:none !important; }
+ .section[draggable] { -webkit-user-drag:none; }
+ .drag-handle, .item-drag-handle, .folder-drag-handle { display:none !important; }
+ /* Sidebar overlays chat on mobile */
+ .sidebar {
+ position: fixed !important;
+ top: 0; bottom: 0; left: 0;
+ z-index: 400;
+ width: 80% !important;
+ max-width: 340px;
+ box-shadow: 4px 0 20px rgba(0,0,0,0.5);
+ transition: transform 0.25s ease, opacity 0.25s ease !important;
+ opacity: 1 !important;
+ overflow: visible !important;
+ /* Force opaque background — Firefox mobile renders the
+ backdrop-filter+background combo as semi-transparent on
+ the slide-out drawer, letting the chat input model picker
+ label show through the sidebar. */
+ /* Keep the drawer tied to the Sidebar color picker. This used to
+ force --panel on mobile, leaving only the header responsive to
+ --sidebar-bg. */
+ background: var(--sidebar-bg, var(--panel)) !important;
+ backdrop-filter: none !important;
+ }
+ .sidebar.hidden {
+ width: 80% !important;
+ transform: translateX(-100%);
+ pointer-events: none;
+ overflow: hidden !important;
+ }
+ .sidebar.right-side.hidden {
+ transform: translateX(100%);
+ }
+ .sidebar.right-side {
+ left: auto; right: 0;
+ box-shadow: -4px 0 20px rgba(0,0,0,0.5);
+ }
+ html.ody-sidebar-off .sidebar,
+ html.ody-mobile-startup-sidebar-hidden .sidebar {
+ transform: translateX(-100%) !important;
+ pointer-events: none !important;
+ opacity: 0 !important;
+ }
+ html.ody-sidebar-off .sidebar.right-side,
+ html.ody-mobile-startup-sidebar-hidden .sidebar.right-side {
+ transform: translateX(100%) !important;
+ }
+ html.ody-sidebar-off .icon-rail,
+ html.ody-mobile-startup-sidebar-hidden .icon-rail {
+ display: none !important;
+ }
+ /* Backdrop behind sidebar */
+ #sidebar-backdrop {
+ position: fixed;
+ inset: 0;
+ z-index: 390;
+ background: rgba(0,0,0,0.4);
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.35s ease;
+ }
+ #sidebar-backdrop.visible { opacity: 1; pointer-events: auto; }
+ /* Elastic overscroll on sidebar */
+ .sidebar-inner {
+ -webkit-overflow-scrolling: touch;
+ overscroll-behavior-y: auto;
+ overflow-y: scroll !important;
+ padding-bottom: 40px;
+ }
+ .sidebar:not(.hidden) {
+ overscroll-behavior: auto;
+ }
+ /* Sidebar header — room for hamburger */
+ .sidebar-header {
+ padding: 18px 12px 8px 12px;
+ min-height: 44px;
+ }
+ .sidebar-brand-title {
+ font-size: 1.2rem;
+ left: 0 !important;
+ }
+ /* Sidebar inner — bigger spacing */
+ .sidebar-inner {
+ padding: 12px 10px 12px !important;
+ gap: 4px !important;
+ }
+ /* Section headers — match list item sizing */
+ .section-header-flex {
+ padding: 12px 10px !important;
+ height: 48px !important;
+ border-radius: 8px;
+ box-sizing: border-box;
+ }
+ .section-header-flex h4,
+ .section-header-flex .section-title {
+ font-size: 14px !important;
+ gap: 11px !important;
+ }
+ .section-icon,
+ .sidebar-action-icon {
+ width: 16px !important;
+ height: 16px !important;
+ left: 0 !important;
+ }
+ /* List items — bigger touch targets, bigger text */
+ .list-item {
+ padding: 12px 10px !important;
+ min-height: 48px;
+ font-size: 14px;
+ border-radius: 8px;
+ gap: 10px !important;
+ }
+ .list-item .grow {
+ font-size: 14px !important;
+ }
+ /* Search, New Chat & Assistant */
+ #sidebar-search-btn,
+ #sidebar-new-chat-btn,
+ .sidebar-assistant-entry {
+ padding: 12px 10px !important;
+ min-height: 48px !important;
+ }
+ #sidebar-search-btn .grow,
+ #sidebar-new-chat-btn .grow,
+ .sidebar-assistant-entry .grow {
+ font-size: 14px !important;
+ left: 0 !important;
+ }
+ /* Section separator — more breathing room */
+ .section {
+ margin-top: 4px;
+ border-radius: 8px;
+ }
+ /* Wave accent — slightly bigger on mobile */
+ .section-header-flex h4::before {
+ height: 18px;
+ }
+ /* Compact top bar on mobile — align with sidebar header */
+ .chat-top-bar {
+ padding: 1px 8px;
+ min-height: 14px;
+ margin-top: -31px;
+ padding-top: 31px;
+ }
+ .chat-top-bar .chat-new-btn { display: none; }
+ .chat-meta-overlay {
+ font-size: 0.65em;
+ left: 50% !important;
+ right: auto !important;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ position: absolute;
+ width: min(calc(100vw - 104px), 320px);
+ max-width: calc(100vw - 104px);
+ overflow: hidden;
+ justify-content: center;
+ }
+ .chat-meta-overlay #current-meta {
+ max-width: 100%;
+ }
+ .chat-meta-overlay .export-dl-btn { display: inline-flex; }
+ #export-compact-btn {
+ position: relative;
+ left: -2px;
+ }
+ /* Incognito — smaller on mobile */
+ .incognito-btn {
+ padding: 4px 10px;
+ font-size: 10px;
+ }
+ /* Keep the active Nobody indicator inside the chat header on mobile.
+ Pinning it next to the hamburger made it collide with the title/splash
+ on tight screens and detached it from the chat state it represents. */
+ .incognito-indicator {
+ display: none !important;
+ }
+ /* Icon rail on mobile — hidden by default, shown in mini-sidebar state */
+ .icon-rail { display: none !important; }
+ .icon-rail.mobile-mini {
+ display: flex !important;
+ position: fixed;
+ top: 0; bottom: 0; left: 0;
+ z-index: 200;
+ width: 48px;
+ box-shadow: 2px 0 12px rgba(0,0,0,0.4);
+ }
+ .icon-rail.mobile-mini.right-side {
+ left: auto; right: 0;
+ box-shadow: -2px 0 12px rgba(0,0,0,0.4);
+ }
+ /* Chat bubbles — AI stretches full width, user stays compact */
+ .msg { font-size: 0.85em; }
+ .msg .body { font-size: 0.9em; }
+ .msg-user { max-width: 90% !important; margin-left: auto; margin-right: 4px; }
+ .msg-ai, .agent-thread { width: 100% !important; max-width: 100% !important; margin: 8px 0; }
+ /* Prevent inner scrollable elements from trapping vertical scroll */
+ .msg pre,
+ .agent-tool-output pre,
+ .agent-thread-cmd,
+ .msg details {
+ overflow-y: hidden !important;
+ max-height: none !important;
+ overflow-x: auto;
+ -webkit-overflow-scrolling: touch;
+ touch-action: pan-y pan-x;
+ }
+ /* Models row — match list items */
+ .models-row {
+ padding: 12px 10px;
+ min-height: 48px;
+ }
+ /* Input icon buttons — bigger touch targets */
+ .input-icon-btn {
+ padding: 10px;
+ min-width: 44px;
+ min-height: 44px;
+ }
+ /* Tool indicators — icon only on mobile (hide text, keep x) */
+ .tool-indicator > span {
+ display: none !important;
+ }
+ .tool-indicator .tool-indicator-x {
+ display: inline-block !important;
+ opacity: 0.6;
+ }
+ /* Hamburger — always right on mobile */
+ .hamburger-btn {
+ width: 44px;
+ height: 44px;
+ top: 6px;
+ left: auto !important;
+ right: 4px !important;
+ -webkit-tap-highlight-color: transparent;
+ }
+ .hamburger-btn:hover,
+ .hamburger-btn:active {
+ background: none !important;
+ border: none !important;
+ box-shadow: none !important;
+ }
+ /* New chat — always left on mobile */
+ .mobile-new-chat-btn {
+ display: flex;
+ position: fixed;
+ top: 12px;
+ left: 8px;
+ z-index: 210;
+ width: 32px;
+ height: 32px;
+ align-items: center;
+ justify-content: center;
+ background: none;
+ border: none;
+ color: var(--fg);
+ cursor: pointer;
+ opacity: 0.5;
+ padding: 0;
+ }
+ /* Modal close button — bigger on mobile */
+ .close-btn,
+ .modal-close {
+ min-width: 44px;
+ min-height: 44px;
+ width: 44px;
+ height: 44px;
+ font-size: 14px;
+ }
+ /* Code block buttons — slightly bigger touch targets */
+ pre .copy-code,
+ pre .edit-code,
+ pre .run-code {
+ width: 44px;
+ height: 44px;
+ }
+ /* Touch-friendly targets for small buttons */
+ .export-dl-btn {
+ min-width: 44px;
+ min-height: 44px;
+ }
+ .section-header-btn {
+ min-width: 44px;
+ min-height: 44px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ }
+ /* 44×44 touch buttons starting from right:6 ends at 50. ~8px gap is
+ enough to be distinguishable without spreading them too far apart. */
+ pre .edit-code {
+ right: 58px;
+ }
+ pre .run-code {
+ right: 110px;
+ }
+ /* Dropdowns — bigger touch targets on mobile */
+ .dropdown-item-compact {
+ padding: 12px 12px !important;
+ font-size: 14px !important;
+ min-height: 44px;
+ gap: 10px !important;
+ }
+ .dropdown-item-compact .dropdown-icon {
+ width: 18px !important;
+ height: 18px !important;
+ }
+ .dropdown-item-compact .dropdown-icon svg {
+ width: 16px !important;
+ height: 16px !important;
+ }
+ .dropdown,
+ .session-dropdown {
+ padding: 6px !important;
+ border-radius: 12px !important;
+ }
+ /* Safe area padding for notched devices */
+ .chat-input-bar {
+ padding-bottom: calc(10px + env(safe-area-inset-bottom, 0px));
+ }
+ /* Mode toggle — larger touch targets */
+ .mode-toggle {
+ height: 34px;
+ border-radius: 12px;
+ }
+ .mode-toggle::before {
+ border-radius: 11px;
+ }
+ .mode-toggle-btn {
+ padding: 0 14px;
+ font-size: 12px;
+ min-height: 34px;
+ }
+ #mode-agent-btn { border-radius: 12px 0 0 12px; }
+ #mode-chat-btn { border-radius: 0 12px 12px 0; }
+ /* Diff mode — stack toolbar, bigger buttons */
+ .diff-toolbar {
+ padding: 8px 12px;
+ gap: 6px;
+ flex-wrap: wrap;
+ }
+ .diff-toolbar-btn {
+ padding: 6px 12px;
+ font-size: 12px;
+ min-height: 36px;
+ }
+ .diff-chunk-btn {
+ width: 28px;
+ height: 28px;
+ font-size: 14px;
+ }
+ /* Document/email/gallery/research library — full-height bottom-sheet
+ on mobile. Keep the rounded top corners + border-top so they match
+ the cookbook/calendar/compare look instead of looking like raw
+ full-bleed panels. */
+ .doclib-modal-content,
+ .gallery-modal-content {
+ width: 100vw !important;
+ max-width: 100vw !important;
+ /* vh fallback, dvh override so the modal adapts to mobile
+ URL-bar show/hide. Order matters: later same-specificity rule
+ wins, so dvh must come after vh. */
+ max-height: 100vh !important;
+ max-height: 100dvh !important;
+ height: 100vh;
+ height: 100dvh;
+ border-radius: 14px 14px 0 0 !important;
+ border: none !important;
+ border-top: 1px solid var(--border) !important;
+ box-shadow: none !important;
+ padding: 6px !important;
+ padding-bottom: env(safe-area-inset-bottom, 6px) !important;
+ margin: 0 !important;
+ overflow-y: auto;
+ -webkit-overflow-scrolling: touch;
+ }
+ #email-lib-modal .doclib-grid {
+ max-height: none;
+ flex: 1;
+ overflow-y: auto;
+ -webkit-overflow-scrolling: touch;
+ }
+ /* Library modal layout: pin the header + tab strip, give the active
+ panel (admin-card) the remaining height, and let the grid scroll
+ internally. The load-more button sits below the grid as a sibling
+ inside admin-card so it stays visible at the bottom of the panel
+ without competing with the grid for scroll. */
+ #doclib-modal .doclib-modal-content {
+ display: flex !important;
+ flex-direction: column !important;
+ overflow: hidden !important;
+ }
+ #doclib-modal .modal-header,
+ #doclib-modal .lib-tabs {
+ flex: 0 0 auto !important;
+ }
+ #doclib-modal .modal-body {
+ flex: 1 1 0 !important;
+ min-height: 0 !important;
+ overflow: hidden !important;
+ }
+ #doclib-modal .admin-card {
+ flex: 1 1 0 !important;
+ min-height: 0 !important;
+ }
+ /* :not(:has(.doclib-card-expanded)) scopes these to the normal list
+ state — when a document card is expanded, the existing expand-state
+ rules take over (grid claims flex:1 with overflow:hidden so the
+ expanded card can scroll itself). */
+ #doclib-modal .doclib-grid:not(:has(.doclib-card-expanded)) {
+ flex: 1 1 0 !important;
+ min-height: 0 !important;
+ max-height: none !important;
+ overflow-y: auto !important;
+ -webkit-overflow-scrolling: touch;
+ }
+ #doclib-modal .doclib-load-more {
+ margin: 8px auto 12px !important;
+ }
+ /* Squeeze a little more height for the preview content by tightening
+ the spacing inside an expanded doc card on mobile. */
+ #doclib-modal .doclib-card.doclib-card-expanded,
+ #email-lib-modal .doclib-card.doclib-card-expanded,
+ #memory-modal .doclib-card.doclib-card-expanded {
+ gap: 2px !important;
+ padding: 4px 6px !important;
+ height: 100% !important;
+ }
+ /* Skills preview kept stopping at partial height because the flex
+ chain (modal → tabs → panel → admin-card → grid → card) wouldn't
+ reliably hand the card a full-height parent. But the skills LIST
+ already scrolls correctly inside #skills-list, so that grid box
+ already has the right bounded height (the area below the tabs).
+ Anchor the expanded card to THAT box with position:absolute so it
+ fills the list area exactly — header + tabs stay visible.
+
+ NOTE: position:relative here is UNCONDITIONAL (not gated behind
+ :has(.doclib-card-expanded)). Firefox mobile builds without :has()
+ support never applied the gated rule, so the absolute card lost its
+ anchor and only filled ~50% — while Chromium/desktop-narrow worked.
+ Relative-when-collapsed is harmless (no abs children then). */
+ #memory-modal #skills-list.doclib-grid {
+ position: relative !important;
+ }
+ #memory-modal .doclib-card.skill-card.doclib-card-expanded {
+ position: absolute !important;
+ inset: 0 !important;
+ /* Height is set in JS (skills.js _fillSkillCardHeight) as an explicit
+ px value — Firefox does NOT treat inset:0 stretch OR height:100%
+ (against the flex-sized grid) as a definite height, so grid/flex
+ children never filled. An explicit px height is unambiguous. */
+ margin: 0 !important;
+ padding: 8px 10px calc(8px + env(safe-area-inset-bottom, 0px)) !important;
+ background: var(--bg) !important;
+ /* Flex column. JS (_fillSkillCardHeight) sets EXPLICIT px heights on
+ the preview + <pre>; in a flex column an explicit-height item
+ (flex:0 0 auto + height) is honoured. (Grid was worse here — the
+ collapsed 1fr track overrode the preview's explicit height.) */
+ display: flex !important;
+ flex-direction: column !important;
+ overflow: hidden !important;
+ border: none !important;
+ border-radius: 0 !important;
+ box-sizing: border-box !important;
+ }
+ /* Preview is the 1fr grid track — give it a definite-height flex column
+ so the <pre> (flex:1) fills and the footer pins at the bottom. */
+ #memory-modal .doclib-card.skill-card.doclib-card-expanded > .doclib-card-preview {
+ display: flex !important;
+ flex-direction: column !important;
+ min-height: 0 !important;
+ overflow: hidden !important;
+ }
+ /* The card now fills the screen, but a base rule (.skill-card...
+ .doclib-card-preview { flex: 0 1 auto }) sizes the preview to its
+ CONTENT — so a medium SKILL.md left the preview at ~half the card
+ (the "only 50%" the debug confirmed: card was full, content wasn't).
+ Force the preview AND the <pre> to FILL the card. Extra .skill-card
+ in the selector out-specifies both the base and the generic mobile
+ rule so this wins without ambiguity. */
+ #memory-modal .doclib-card.skill-card.doclib-card-expanded > .doclib-card-preview {
+ flex: 1 1 auto !important;
+ min-height: 0 !important;
+ }
+ #memory-modal .doclib-card.skill-card.doclib-card-expanded .skill-md-pre {
+ flex: 1 1 auto !important;
+ min-height: 0 !important;
+ }
+ /* Flatten the expanded doc/email card on mobile — drop the inner
+ border + background so it doesn't read as a "subwindow" inside the
+ modal (the chat preview doesn't have that nested-card look). The
+ body prefix beats the desktop email rule later in the file that
+ paints a 2px accent border + box-shadow with !important. */
+ body #doclib-modal .doclib-card.doclib-card-expanded,
+ body #email-lib-modal .doclib-card.doclib-card-expanded,
+ body #memory-modal .doclib-card.doclib-card-expanded {
+ background: transparent !important;
+ border: none !important;
+ border-radius: 0 !important;
+ box-shadow: none !important;
+ }
+ /* Same layout pattern the chat preview uses: preview itself clips,
+ the <pre> (or PDF iframe) inside owns the scroll, and the action
+ bar pins to the bottom with extra bottom padding so it floats
+ above the iOS safe-area / home-indicator strip. */
+ #doclib-modal .doclib-card.doclib-card-expanded .doclib-card-preview,
+ #email-lib-modal .doclib-card.doclib-card-expanded .doclib-card-preview,
+ #memory-modal .doclib-card.doclib-card-expanded .doclib-card-preview {
+ padding: 4px 6px 20px !important;
+ flex: 1 1 auto !important;
+ /* The preview lives inside an already bounded expanded card. Giving
+ it a viewport-sized minimum pushes its footer below that card,
+ where overflow:hidden clips it. The text child owns scrolling. */
+ min-height: 0 !important;
+ overflow: hidden !important;
+ display: flex !important;
+ flex-direction: column !important;
+ border-top: none !important;
+ }
+ /* The "Load more" button is flex-shrink:0 and sits in the panel AFTER the
+ grid, so even when a card is expanded it reserves ~40px at the panel
+ bottom — shrinking the visible grid and clipping the action bar by that
+ much (the "black bar"). The global collapse rule's max-height:0 can't
+ remove a flex-shrink:0 item, so hide it outright on expand. */
+ #doclib-modal [data-doclib-panel="documents"]:has(.doclib-card-expanded) .doclib-load-more,
+ #doclib-modal [data-doclib-panel="documents"]:has(.doclib-card-expanded) .doclib-inline-load-more {
+ display: none !important;
+ }
+ /* Small bottom padding now that the load-more no longer steals space —
+ the action bar sits low, just clearing the home-indicator safe area. */
+ #doclib-modal [data-doclib-panel="documents"] .doclib-card.doclib-card-expanded .doclib-card-preview {
+ padding-bottom: calc(18px + env(safe-area-inset-bottom, 0px)) !important;
+ }
+ #doclib-modal .doclib-card.doclib-card-expanded .doclib-card-preview pre,
+ #doclib-modal .doclib-card.doclib-card-expanded .doclib-card-preview .doclib-card-pdf-frame,
+ #email-lib-modal .doclib-card.doclib-card-expanded .doclib-card-preview pre,
+ #email-lib-modal .doclib-card.doclib-card-expanded .doclib-card-preview .email-reader-body,
+ #memory-modal .doclib-card.doclib-card-expanded .doclib-card-preview pre,
+ #memory-modal .doclib-card.doclib-card-expanded .doclib-card-preview .skill-md-editor {
+ flex: 1 1 0 !important;
+ min-height: 0 !important;
+ overflow-y: auto !important;
+ -webkit-overflow-scrolling: touch;
+ /* Strip the code-box visual treatment so the <pre> / reader body
+ doesn't read as a "sub-window" inside the modal. */
+ background: transparent !important;
+ border: none !important;
+ box-shadow: none !important;
+ padding: 0 !important;
+ margin: 0 !important;
+ border-radius: 0 !important;
+ }
+ /* The skill editor textarea keeps a light frame on mobile (it's an
+ input, not read-only text) — override the strip-down above. */
+ #memory-modal .doclib-card.doclib-card-expanded .doclib-card-preview .skill-md-editor {
+ background: var(--bg) !important;
+ border: 1px solid var(--border) !important;
+ padding: 8px !important;
+ }
+ #doclib-modal .doclib-card.doclib-card-expanded .doclib-card-preview pre code,
+ #doclib-modal .doclib-card.doclib-card-expanded .doclib-card-preview code.hljs,
+ #email-lib-modal .doclib-card.doclib-card-expanded .doclib-card-preview pre code,
+ #email-lib-modal .doclib-card.doclib-card-expanded .doclib-card-preview code.hljs,
+ #memory-modal .doclib-card.doclib-card-expanded .doclib-card-preview pre code {
+ background: transparent !important;
+ border: none !important;
+ padding: 0 !important;
+ box-shadow: none !important;
+ }
+ #doclib-modal .doclib-card.doclib-card-expanded .doclib-card-expanded-actions,
+ #email-lib-modal .doclib-card.doclib-card-expanded .doclib-card-expanded-actions,
+ #memory-modal .doclib-card.doclib-card-expanded .doclib-card-expanded-actions {
+ padding: 6px 4px 0 !important;
+ margin-top: 4px !important;
+ flex-shrink: 0 !important;
+ }
+ /* Email reader on mobile inherits the library modal's horizontal
+ padding (the .doclib-modal-content default — 6px). No extra
+ overrides for the modal-content / modal-body / admin-card / grid
+ chain; we just clean up the inner email reader header/body
+ padding so the From / To lines align with the email subject. */
+ #email-lib-modal .doclib-card.doclib-card-expanded .doclib-card-preview .email-reader-header,
+ #email-lib-modal .doclib-card.doclib-card-expanded .doclib-card-preview .email-reader-atts,
+ #email-lib-modal .doclib-card.doclib-card-expanded .doclib-card-preview .email-reader-body {
+ padding-left: 6px !important;
+ padding-right: 6px !important;
+ }
+ #email-lib-modal .doclib-card.doclib-card-expanded .doclib-card-preview .email-reader-body {
+ margin-left: -6px !important;
+ margin-right: -6px !important;
+ padding-left: 12px !important;
+ padding-right: 12px !important;
+ background: var(--panel) !important;
+ box-shadow: inset 0 1px 0 color-mix(in srgb, var(--border) 65%, transparent) !important;
+ }
+ /* Mobile email-reader header: meta on the left, actions on the right
+ (two stacked rows). The two .email-reader-actions-row siblings
+ render as their own flex-row strips so primary (reply/reply-all/
+ forward) sits above secondary (AI/summary/more), instead of
+ flattening into one line that collided with the recipient chips. */
+ #email-lib-modal .email-reader-header,
+ .email-reader-tab-modal .email-reader-header,
+ .email-window-modal .email-reader-header {
+ padding: 8px 8px !important;
+ gap: 6px !important;
+ flex-direction: row !important;
+ /* Top-align meta + actions on mobile. With the two-row action
+ cluster (Summary/More above Reply/Forward/AI), align-items:
+ center pulled the meta's From:/To: rows down into the visual
+ middle of the header, leaving them visibly off-axis. */
+ align-items: flex-start !important;
+ }
+ #email-lib-modal .email-reader-actions,
+ .email-reader-tab-modal .email-reader-actions,
+ .email-window-modal .email-reader-actions {
+ display: flex !important;
+ flex-direction: column !important;
+ align-items: flex-end !important;
+ gap: 4px !important;
+ flex-shrink: 0 !important;
+ margin-left: auto !important;
+ order: 0 !important;
+ }
+ #email-lib-modal .email-reader-actions-row,
+ .email-reader-tab-modal .email-reader-actions-row,
+ .email-window-modal .email-reader-actions-row {
+ display: flex !important;
+ flex-direction: row !important;
+ flex-wrap: nowrap !important;
+ align-items: center !important;
+ justify-content: flex-end !important;
+ gap: 4px !important;
+ }
+ /* Meta on mobile: From / To / Cc each on their own row, label
+ tight to chips, chips scroll horizontally per row. */
+ #email-lib-modal .email-reader-meta,
+ .email-reader-tab-modal .email-reader-meta,
+ .email-window-modal .email-reader-meta {
+ display: flex !important;
+ flex-direction: column !important;
+ gap: 2px !important;
+ min-width: 0 !important;
+ width: 100% !important;
+ }
+ #email-lib-modal .email-reader-meta-row,
+ .email-reader-tab-modal .email-reader-meta-row,
+ .email-window-modal .email-reader-meta-row {
+ display: flex !important;
+ grid-template-columns: none !important;
+ align-items: center !important;
+ gap: 6px !important;
+ padding-right: 0 !important;
+ min-width: 0 !important;
+ }
+ #email-lib-modal .email-reader-meta-row .recipient-chips,
+ .email-reader-tab-modal .email-reader-meta-row .recipient-chips,
+ .email-window-modal .email-reader-meta-row .recipient-chips {
+ display: inline-flex !important;
+ flex-wrap: nowrap !important;
+ overflow-x: auto !important;
+ overflow-y: hidden !important;
+ max-width: 100% !important;
+ scrollbar-width: none !important;
+ gap: 4px !important;
+ }
+ #email-lib-modal .email-reader-meta-row .recipient-chips::-webkit-scrollbar,
+ .email-reader-tab-modal .email-reader-meta-row .recipient-chips::-webkit-scrollbar,
+ .email-window-modal .email-reader-meta-row .recipient-chips::-webkit-scrollbar {
+ display: none !important;
+ }
+ #email-lib-modal .email-reader-actions .memory-toolbar-btn.reader-icon-btn,
+ .email-reader-tab-modal .email-reader-actions .memory-toolbar-btn.reader-icon-btn,
+ .email-window-modal .email-reader-actions .memory-toolbar-btn.reader-icon-btn {
+ width: auto !important;
+ height: 44px !important;
+ flex: 0 0 auto !important;
+ display: inline-flex !important;
+ flex-direction: column !important;
+ align-items: center !important;
+ justify-content: center !important;
+ gap: 3px !important;
+ padding: 4px 2px !important;
+ }
+ #email-lib-modal .email-reader-actions .memory-toolbar-btn.reader-icon-btn svg,
+ .email-reader-tab-modal .email-reader-actions .memory-toolbar-btn.reader-icon-btn svg,
+ .email-window-modal .email-reader-actions .memory-toolbar-btn.reader-icon-btn svg {
+ width: 16px !important;
+ height: 16px !important;
+ }
+ /* Gallery-style label under each button — only on mobile. The
+ global rule below the @media block hides them on desktop. */
+ #email-lib-modal .reader-btn-label,
+ .email-reader-tab-modal .reader-btn-label,
+ .email-window-modal .reader-btn-label {
+ display: inline-block !important;
+ font-size: 8.5px !important;
+ font-weight: 500 !important;
+ line-height: 1 !important;
+ letter-spacing: 0.02em !important;
+ opacity: 0.75 !important;
+ white-space: nowrap !important;
+ }
+ /* List-view cards keep the framed look from their own .doclib-card /
+ .memory-item base styles — no extra grid padding here, so the
+ spacing matches the documents/library tab exactly. */
+ /* Tighten the top of the email sheet — modal header + description +
+ account row + toolbar were stacking with full desktop spacing and
+ pushed the email subjects way down. */
+ #email-lib-modal .modal-header {
+ padding: 4px 8px !important;
+ min-height: 0 !important;
+ }
+ #email-lib-modal .modal-header h4 {
+ /* Match the other tool headers (base .modal-header h4 = 1rem); was
+ 13px, which read noticeably smaller than Calendar/Tasks/etc. */
+ font-size: 1rem !important;
+ line-height: 1.2 !important;
+ }
+ #email-lib-modal .modal-body {
+ gap: 4px !important;
+ }
+ #email-lib-modal .admin-card {
+ gap: 4px !important;
+ }
+ #email-lib-modal .admin-card > .doclib-desc {
+ display: none !important;
+ }
+ /* When an email is expanded the list-mode toolbar siblings are
+ already hidden by the existing :has rule. Hide the modal-header
+ entirely AND zero out the modal-content top padding so the email
+ reader claims the full sheet height. The swipe-down gesture (and
+ the dock chip) still dismiss the modal. */
+ #email-lib-modal:has(.doclib-card-expanded) .modal-header,
+ #email-lib-modal.email-reading .modal-header {
+ display: none !important;
+ }
+ #email-lib-modal:has(.doclib-card-expanded) .doclib-modal-content,
+ #email-lib-modal.email-reading .doclib-modal-content {
+ padding-top: 0 !important;
+ }
+ #email-lib-modal:has(.doclib-card-expanded) .modal-body,
+ #email-lib-modal.email-reading .modal-body {
+ gap: 0 !important;
+ }
+ /* Flatten the From / To bar so it doesn't read as a cut-off framed
+ strip with a hard background change. Remove the background, drop
+ the border-bottom to a faint divider, and let it blend with the
+ sheet. */
+ #email-lib-modal .email-reader-header {
+ background: transparent !important;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 40%, transparent) !important;
+ }
+ #email-lib-modal .email-card-nav-btn {
+ padding: 6px 10px !important;
+ min-width: 40px !important;
+ height: 38px !important;
+ }
+ #email-lib-modal .email-card-nav-btn svg {
+ width: 18px !important;
+ height: 18px !important;
+ }
+ /* Nudge the prev/next arrow cluster ~4px to the right so it sits
+ comfortably out at the edge instead of crowding the subject text. */
+ #email-lib-modal .email-card-nav-arrows {
+ transform: translateX(4px);
+ }
+ /* Done check — extend the actual TAP area via padding + negative
+ margin (a transparent ::before doesn't change the parent's hit
+ box). Layout stays the same height as library cards because the
+ margin cancels the padding visually, but the clickable region is
+ ~37px square. */
+ #email-lib-modal .email-card-done {
+ position: relative !important;
+ z-index: 5 !important;
+ pointer-events: auto !important;
+ touch-action: manipulation !important;
+ padding: 12px !important;
+ margin: -12px !important;
+ }
+ #email-lib-modal .email-card-done svg {
+ width: 13px !important;
+ height: 13px !important;
+ }
+ /* Make sure no overlay or pseudo intercepts the tap. */
+ #email-lib-modal .email-card-done * { pointer-events: none; }
+ /* Tighten the From / To meta bar and the email body — they had
+ desktop padding (10–14px) that wasted real estate on phones. */
+ #email-lib-modal .email-reader-header {
+ padding: 6px 4px !important;
+ gap: 4px !important;
+ }
+ #email-lib-modal .email-reader-meta {
+ font-size: 11px !important;
+ }
+ #email-lib-modal .email-reader-meta-row strong {
+ min-width: 28px !important;
+ }
+ #email-lib-modal .email-reader-atts {
+ padding: 6px 4px !important;
+ }
+ #email-lib-modal .email-reader-body {
+ padding: 8px 4px !important;
+ }
+ /* Make sure the grid claims the full admin-card height when a doc
+ is expanded — the existing rule sets flex:1, but on mobile we also
+ need a hard height fallback because the parent uses dvh which
+ desktop-tuned selectors don't always trickle through. */
+ #doclib-modal .admin-card:has(.doclib-card-expanded) > .doclib-grid,
+ #memory-modal .admin-card:has(.doclib-card-expanded) > .doclib-grid {
+ height: 100% !important;
+ }
+ /* Documents need the same bounded flex chain as skills when a card is
+ opened. Without this, the grid falls back to its list layout and the
+ expanded preview only grows to its content height on mobile. */
+ #doclib-modal .admin-card:has(.doclib-card-expanded) > .doclib-grid {
+ display: flex !important;
+ flex: 1 1 0 !important;
+ flex-direction: column !important;
+ min-height: 0 !important;
+ overflow: hidden !important;
+ }
+ #doclib-modal .doclib-card.doclib-card-expanded {
+ flex: 1 1 auto !important;
+ height: 100% !important;
+ min-height: 0 !important;
+ }
+ #doclib-modal .doclib-card.doclib-card-expanded .doclib-card-preview {
+ flex: 1 1 0 !important;
+ min-height: 0 !important;
+ }
+ #doclib-modal .doclib-card.doclib-card-expanded .doclib-card-pdf-frame {
+ height: auto !important;
+ flex: 1 1 0 !important;
+ min-height: 0 !important;
+ }
+ /* Skills modal: keep the header + tab strip visible; the expanded
+ card fills the skills-list area below them via position:absolute
+ (see the #skills-list rule above). Just make sure the tab-panel +
+ its card give the list its full height. */
+ #memory-modal .memory-tab-panel[data-memory-panel="skills"] > .admin-card:has(.doclib-card-expanded) {
+ flex: 1 1 auto !important;
+ min-height: 0 !important;
+ }
+ .doclib-card-header {
+ padding: 10px 8px;
+ gap: 4px;
+ }
+ .doclib-card-session,
+ .doclib-card-time {
+ display: none;
+ }
+ .doclib-card-expanded-actions {
+ flex-wrap: nowrap;
+ }
+ /* Keep the footer buttons identical to the chat/research footers on
+ mobile too — those have no mobile enlargement, so neither should
+ these (otherwise the doc footer reads in a larger/different font). */
+ .doclib-card-action-btn {
+ font-size: 10px;
+ padding: 3px 8px;
+ }
+ /* On phones, keep Delete explicit while the other secondary actions
+ stay available from the kebab. */
+ #doclib-modal .doclib-card-expanded-actions > .doclib-expanded-archive-btn,
+ #doclib-modal .doclib-card-expanded-actions .doclib-expanded-clone-btn,
+ #doclib-modal .doclib-card-expanded-actions .doclib-expanded-export-btn {
+ display: none !important;
+ }
+ #doclib-modal .doclib-card-expanded-actions > .doclib-expanded-delete-btn {
+ display: inline-flex !important;
+ order: 0;
+ left: 0 !important;
+ margin-left: 0;
+ }
+ #doclib-modal .doclib-card-expanded-actions > .doclib-action-group {
+ order: 2;
+ margin-left: 6px !important;
+ min-width: 0;
+ }
+ #doclib-modal .doclib-card.doclib-card-expanded .doclib-card-expanded-actions {
+ box-sizing: border-box;
+ width: 100%;
+ max-width: 100%;
+ min-width: 0;
+ overflow: visible;
+ }
+ #doclib-modal .doclib-card-expanded-actions .doclib-expanded-open-btn {
+ min-height: 30px;
+ padding: 5px 10px;
+ max-width: 100%;
+ }
+ #doclib-modal .doclib-card-expanded-actions > .doclib-expanded-mobile-more {
+ display: inline-flex;
+ order: 1;
+ width: 32px;
+ min-width: 32px;
+ min-height: 30px;
+ margin-left: auto;
+ padding: 0;
+ }
+ /* Chat top bar — adjusted for reduced height */
+ /* Suggestion nav — bigger touch targets */
+ .doc-suggestion-nav-btn {
+ padding: 6px 8px;
+ font-size: 18px;
+ }
+ .doc-suggestion-close {
+ padding: 10px 12px;
+ margin: -10px -12px;
+ }
+ }
+ #mobile-backdrop, #mobile-menu-btn { display:none !important; }
+ #sidebar-backdrop { display:none !important; }
+ /* ----- Loading spinner ----- */
+
+ .spinner {
+ width: 24px;
+ height: 24px;
+ margin: 8px auto;
+ border: 3px solid var(--border);
+ border-top-color: var(--red);
+ border-radius: 50%;
+ animation: spin 0.9s linear infinite;
+ }
+ /* Inline spinner for buttons */
+ .btn-spinner {
+ display: inline-block;
+ width: 12px;
+ height: 12px;
+ border: 2px solid transparent;
+ border-top-color: currentColor;
+ border-radius: 50%;
+ animation: spin 1s linear infinite;
+ margin-right: 6px;
+ }
+ .search-status {
+ font-size: 0.85em;
+ color: var(--red);
+ margin-top: 4px;
+ padding: 4px;
+ border-left: 2px solid var(--red);
+ background: color-mix(in srgb, var(--red) 5%, transparent);
+ }
+ /* Loading indicator for messages */
+ .loading-indicator {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 10px;
+ }
+ .loading-dots {
+ display: flex;
+ gap: 4px;
+ }
+ .loading-dot {
+ width: 6px;
+ height: 6px;
+ background-color: var(--red);
+ border-radius: 50%;
+ }
+ .loading-dot:nth-child(1) {
+ animation: loading-bounce 1.4s infinite ease-in-out both;
+ }
+ .loading-dot:nth-child(2) {
+ animation: loading-bounce 1.4s infinite ease-in-out both;
+ animation-delay: -0.32s;
+ }
+ .loading-dot:nth-child(3) {
+ animation: loading-bounce 1.4s infinite ease-in-out both;
+ animation-delay: -0.64s;
+ }
+ .session-loading-state {
+ min-height: 100%;
+ display: flex;
+ flex-direction: column;
+ justify-content: flex-start;
+ gap: 12px;
+ color: var(--fg);
+ font-size: 12px;
+ pointer-events: none;
+ position: relative;
+ padding: 16px 14px 24px;
+ box-sizing: border-box;
+ overflow: hidden;
+ }
+ .session-loading-state::before { content: none; }
+ .session-skeleton-bubble {
+ width: min(78%, 680px);
+ border: 1px solid color-mix(in srgb, var(--border) 74%, transparent);
+ border-radius: 10px;
+ background: color-mix(in srgb, var(--panel, var(--bg)) 72%, transparent);
+ padding: 10px 12px 12px;
+ box-shadow: 0 8px 22px rgba(0, 0, 0, 0.14);
+ }
+ .session-skeleton-bubble.is-user {
+ align-self: flex-end;
+ width: min(64%, 520px);
+ }
+ .session-skeleton-bubble.is-ai {
+ align-self: flex-start;
+ }
+ .session-skeleton-line {
+ position: relative;
+ overflow: hidden;
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ border: 1px solid color-mix(in srgb, var(--border) 82%, transparent);
+ border-radius: 999px;
+ }
+ .session-skeleton-line {
+ height: 10px;
+ margin-top: 8px;
+ opacity: 0.62;
+ }
+ .session-skeleton-line::after {
+ content: '';
+ position: absolute;
+ inset: -1px;
+ transform: translateX(-120%);
+ background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--fg) 14%, transparent), transparent);
+ animation: session-skeleton-shimmer 1.25s ease-in-out infinite;
+ }
+ .session-skeleton-bubble:nth-child(2) .session-skeleton-line::after { animation-delay: 0.12s; }
+ .session-skeleton-bubble:nth-child(3) .session-skeleton-line::after { animation-delay: 0.24s; }
+ .session-skeleton-bubble:nth-child(4) .session-skeleton-line::after { animation-delay: 0.36s; }
+ @keyframes session-skeleton-shimmer {
+ 100% { transform: translateX(120%); }
+ }
+ @media (max-width: 768px) {
+ .session-loading-state { padding: 12px 10px 18px; gap: 10px; }
+ .session-skeleton-bubble { width: 86%; padding: 9px 10px 11px; border-radius: 9px; }
+ .session-skeleton-bubble.is-user { width: 72%; }
+ .session-skeleton-line { height: 9px; margin-top: 7px; }
+ }
+
+ /* Modal styling */
+ .modal {
+ position:fixed;
+ top:0; left:0; width:100%; height:100%;
+ background:none;
+ display:flex; align-items:center; justify-content:center;
+ z-index:250;
+ backdrop-filter:none;
+ pointer-events:none;
+ }
+ /* Cookbook always sits above Gallery so the "Serve a model in
+ Cookbook…" flow (and any other "open Cookbook from inside another
+ modal") is visible no matter which modal was opened first. */
+ #cookbook-modal { z-index: 260; }
+ .modal.hidden { display:none; }
+
+ /* Tool windows open centered in the CHAT AREA (the space right of the
+ sidebar + icon rail), rather than the full viewport.
+ We narrow the overlay to the chat area so its flex-centering lands the
+ window there; fullscreen / docked states use position:fixed so they
+ escape this narrowed overlay and still fill the screen. The
+ --sidebar-w / --icon-rail-w vars track collapse state live, so when a
+ window (e.g. Cookbook) hides the sidebar this naturally re-centers.
+ Desktop only — on mobile these are full-screen sheets. */
+ @media (min-width: 769px) {
+ #calendar-modal,
+ #gallery-modal,
+ #tasks-modal,
+ #memory-modal,
+ #doclib-modal,
+ #compare-model-overlay,
+ #research-overlay,
+ #theme-modal,
+ #settings-modal,
+ #email-lib-modal {
+ left: calc(var(--icon-rail-w, 48px) + var(--sidebar-w, 0px));
+ width: calc(100% - (var(--icon-rail-w, 48px) + var(--sidebar-w, 0px)));
+ box-sizing: border-box;
+ /* Slide in sync with the sidebar's 0.25s collapse/expand so the
+ centered window glides instead of jumping when the nav toggles. */
+ transition: left 0.25s ease, width 0.25s ease;
+ }
+ }
+ .modal-content {
+ background:var(--panel);
+ border:1px solid var(--border);
+ width:min(520px, 92vw); max-height:85vh; padding:10px;
+ box-sizing:border-box; font-size:14px;
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+ letter-spacing: -0.015em;
+ display:flex; flex-direction:column;
+ position:relative;
+ overflow-y:auto;
+ border-radius:10px;
+ box-shadow:0 8px 32px rgba(0,0,0,0.45);
+ pointer-events:auto;
+ animation: modal-enter 0.25s ease-out both;
+ }
+ .memory-modal-content,
+ .tasks-modal-content,
+ .preset-modal-content,
+ #cookbook-modal .modal-content,
+ #theme-popup,
+ .doclib-modal-content,
+ .gallery-modal-content {
+ container-type: inline-size;
+ }
+ .modal-header {
+ display:flex; justify-content:space-between; align-items:center; margin-bottom:6px;
+ cursor:grab; user-select:none;
+ /* Pin the header (with its close button) to the top of the
+ scrollable modal-content so users can always dismiss the modal
+ even after scrolling far down — especially important on mobile
+ where the modal can be taller than the viewport. */
+ position: sticky;
+ top: 0;
+ z-index: 5;
+ /* Inherit the modal-content's background so the header matches the
+ panel body. Many tool modals set their content to var(--bg) inline
+ while this header was hard-coded to var(--panel) — making the title
+ strip a different shade in every theme. `inherit` tracks whatever
+ the content uses (var(--bg) or the default var(--panel)) and stays
+ opaque, so the sticky header still masks scrolled content. */
+ background-color: inherit;
+ }
+ .modal-header:active { cursor:grabbing; }
+ /* Edge/corner window resize (windowResize.js). While a resize is in
+ progress, suppress text selection and force the active resize cursor
+ across the whole document so it does not flicker as the pointer passes
+ over child elements mid-drag. */
+ body.window-resizing-active { user-select:none !important; }
+ body.window-resizing-active * { cursor:inherit !important; }
+ /* Suppress only TRANSITIONS while resizing so the edge tracks the cursor
+ crisply. We deliberately do NOT toggle `animation` here: toggling
+ animation off→on re-triggers the modal open-animation (a scale-in) on
+ mouseup, which both mis-measures the final size and visibly "pops" the
+ window. windowResize.js instead kills the one-shot open animation inline
+ once, in begin(). */
+ .window-resizing {
+ transition:none !important;
+ }
+ /* Cookbook opts out of the sticky header on mobile; the title bar scrolls
+ away with the content instead of following. Background is inherited from
+ the shared .modal-header rule so frosted/glass themes stay consistent. */
+ #cookbook-modal .modal-header {
+ position: static;
+ top: auto;
+ }
+ .modal-header h4 {
+ margin:0;
+ /* Push every header control (opacity slider, minimize, close) into one
+ group on the right — works whether or not optional controls like the
+ opacity slider are present, so the minimize button never floats to
+ the centre when a sibling is hidden. */
+ margin-right:auto;
+ font-size:1rem;
+ font-weight:600;
+ letter-spacing:-0.03em;
+ color:var(--red);
+ }
+ /* Headers with an optional Peek control already have the title's
+ auto-margin grouping all right-side controls. A second auto-margin on
+ the injected minimize button splits the group and makes it look
+ different from the other modal headers. */
+ .modal-header .theme-opacity-wrap + .modal-minimize-btn {
+ margin-left: 0 !important;
+ }
+ .close-btn,
+ .modal-close {
+ background:transparent;
+ color:color-mix(in srgb, var(--fg) 58%, transparent);
+ border:1px solid transparent;
+ font-size:0;
+ width:24px;
+ height:24px;
+ padding:0;
+ display:inline-flex;
+ align-items:center;
+ justify-content:center;
+ line-height:1;
+ text-indent:0;
+ cursor:pointer;
+ border-radius:999px;
+ line-height:1;
+ flex-shrink:0;
+ position:relative;
+ }
+ .close-btn > svg,
+ .modal-close > svg {
+ display:none;
+ }
+ .close-btn::before,
+ .modal-close::before {
+ content:"";
+ width:10px;
+ height:10px;
+ display:block;
+ background:currentColor;
+ -webkit-mask:
+ url("data:image/svg+xml,%3Csvg width='10' height='10' viewBox='0 0 10 10' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M2 2L8 8M8 2L2 8' stroke='black' stroke-width='1.8' stroke-linecap='round'/%3E%3C/svg%3E")
+ center / contain no-repeat;
+ mask:
+ url("data:image/svg+xml,%3Csvg width='10' height='10' viewBox='0 0 10 10' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M2 2L8 8M8 2L2 8' stroke='black' stroke-width='1.8' stroke-linecap='round'/%3E%3C/svg%3E")
+ center / contain no-repeat;
+ }
+ .close-btn:hover,
+ .modal-close:hover {
+ background:color-mix(in srgb, var(--fg) 10%, transparent);
+ border-color:color-mix(in srgb, var(--fg) 12%, transparent);
+ color:var(--fg);
+ }
+ /* Minimize button — sits beside the close button on every modal */
+ .minimize-btn {
+ background:transparent;
+ color:color-mix(in srgb, var(--fg) 58%, transparent);
+ border:1px solid transparent;
+ font-size:0;
+ font-weight:700;
+ width:24px;
+ height:24px;
+ padding:0;
+ display:inline-flex;
+ align-items:center;
+ justify-content:center;
+ line-height:1;
+ cursor:pointer;
+ border-radius:999px;
+ flex-shrink:0;
+ margin-left:auto; /* push to the right so it docks next to .close-btn */
+ margin-right:4px;
+ }
+ .minimize-btn::before {
+ content:"";
+ width:9px;
+ height:2px;
+ border-radius:999px;
+ background:currentColor;
+ display:block;
+ transform:translateY(2px);
+ }
+ .modal-minimize-btn.minimize-btn::before {
+ content:none;
+ display:none;
+ }
+ .minimize-btn:hover {
+ background:color-mix(in srgb, var(--fg) 10%, transparent);
+ border-color:color-mix(in srgb, var(--fg) 12%, transparent);
+ color:var(--fg);
+ }
+ @media (max-width: 768px) {
+ .minimize-btn { display: none !important; }
+ #modal-dock { display: none !important; }
+ }
+ /* Minimized modals are hidden but stay in the DOM with their state intact */
+ .modal.minimized { display:none !important; }
+ /* Bottom dock for minimized modals */
+ #modal-dock {
+ position:fixed;
+ bottom:var(--composer-clearance, 0px);
+ left:0;
+ right:0;
+ display:flex;
+ flex-wrap:wrap;
+ gap:4px;
+ padding:4px 8px;
+ z-index:240;
+ pointer-events:none;
+ justify-content:flex-start;
+ }
+ #modal-dock:empty { display:none; }
+ .modal-dock-item {
+ background:var(--panel);
+ border:1px solid var(--border);
+ border-bottom:none;
+ border-radius:6px 6px 0 0;
+ padding:4px 4px 4px 10px;
+ display:inline-flex;
+ align-items:center;
+ gap:6px;
+ cursor:pointer;
+ pointer-events:auto;
+ font-size:12px;
+ color:var(--fg);
+ max-width:220px;
+ box-shadow:0 -2px 8px rgba(0,0,0,0.25);
+ transition:background 0.15s;
+ }
+ .modal-dock-item:hover { background:var(--bg); }
+ .modal-dock-label {
+ white-space:nowrap;
+ overflow:hidden;
+ text-overflow:ellipsis;
+ max-width:180px;
+ }
+ .modal-dock-close {
+ background:transparent;
+ border:none;
+ color:var(--fg);
+ cursor:pointer;
+ font-size:14px;
+ padding:0 4px;
+ line-height:1;
+ opacity:0.6;
+ }
+ .modal-dock-close:hover { color:var(--red); opacity:1; }
+ .modal-body { flex:1; overflow-y:auto; }
+ .modal-body button { margin-top:6px; }
+ /* Styled confirm dialog — keeps backdrop */
+ #styled-confirm-overlay {
+ background:rgba(0,0,0,0.5);
+ backdrop-filter:blur(4px);
+ pointer-events:auto !important;
+ z-index: 99999 !important;
+ position: fixed !important;
+ top: 0 !important;
+ left: 0 !important;
+ width: 100% !important;
+ height: 100% !important;
+ top: 0; left: 0; width: 100%; height: 100%;
+ }
+ #styled-confirm-overlay .modal-content {
+ position: relative;
+ z-index: 10001;
+ }
+ .email-attachment-warning-modal {
+ z-index: 99999 !important;
+ }
+ .email-attachment-warning-modal .modal-content {
+ position: relative;
+ z-index: 100001;
+ }
+ .styled-confirm-box {
+ width:360px; max-width:90vw;
+ max-height:none; /* override modal-content's 85vh */
+ padding:14px 18px;
+ }
+ .styled-confirm-box .modal-header { margin-bottom:4px; }
+ .styled-confirm-box .modal-body p {
+ margin:8px 0 12px; color:var(--fg); font-size:0.92rem; line-height:1.45;
+ white-space:pre-line;
+ }
+ .styled-confirm-box .modal-footer {
+ display:flex; justify-content:flex-end; gap:8px; padding-top:6px;
+ border-top:1px solid var(--border); margin-top:4px;
+ }
+ @media (max-width:768px) {
+ .styled-confirm-box {
+ width: 85vw;
+ padding: 12px 16px;
+ font-size: 0.88rem;
+ border-radius: 12px;
+ }
+ .styled-confirm-box .modal-header h4 { font-size: 0.9rem; }
+ .styled-confirm-box .modal-body p { font-size: 0.85rem; margin: 6px 0 10px; }
+ .styled-confirm-box .modal-footer { gap: 10px; }
+ .styled-confirm-box .confirm-btn {
+ flex: 1;
+ /* More bottom than top padding nudges the label up ~2px so it isn't
+ sitting low in the taller mobile buttons. */
+ padding: 8px 12px 12px;
+ font-size: 0.85rem;
+ border-radius: 8px;
+ text-align: center;
+ }
+ }
+ .confirm-btn {
+ /* Asymmetric padding nudges the label UP ~2px from where it was (more
+ bottom than top padding), so the confirm-dialog text isn't sitting low. */
+ padding:3px 16px 5px; border-radius:4px; font-size:0.85rem;
+ cursor:pointer; border:1px solid var(--border);
+ font-family:inherit;
+ }
+ @media (max-width: 820px) {
+ /* Mobile: flip the asymmetry to shift the text 1 px UP from
+ centre instead (the bigger touch targets on mobile read better
+ with the label sitting slightly high). */
+ .confirm-btn { padding:2px 16px 4px; }
+ }
+ .confirm-btn-secondary { background:var(--bg); color:var(--fg); }
+ .confirm-btn-secondary:hover { background:var(--border); }
++ #styled-confirm-ok {
++ position: relative;
++ top: 2px;
++ }
+ #styled-confirm-cancel .styled-confirm-cancel-label {
+ position:relative;
+ top:2px;
+ }
+ .confirm-btn-primary { background:var(--accent-primary, var(--red, #4a9eff)); color:#fff; border-color:transparent; }
+ .confirm-btn-primary:hover { filter:brightness(1.15); }
+ .confirm-btn-danger { background:var(--color-danger); color:#fff; border-color:transparent; }
+ .confirm-btn-danger:hover { background:var(--color-error); }
+ .cookbook-gguf-delete-box {
+ width:560px;
+ max-width:92vw;
+ }
+ .cookbook-gguf-delete-list {
+ display:flex;
+ flex-direction:column;
+ gap:6px;
+ max-height:42vh;
+ overflow:auto;
+ padding:2px 2px 4px;
+ }
+ .cookbook-gguf-delete-row {
+ display:grid;
+ grid-template-columns:18px minmax(0,1fr);
+ gap:7px 8px;
+ align-items:start;
+ padding:7px 8px;
+ border:1px solid var(--border);
+ border-radius:7px;
+ background:color-mix(in srgb, var(--panel, var(--bg)) 92%, var(--fg) 8%);
+ cursor:pointer;
+ }
+ .cookbook-gguf-delete-row:hover {
+ border-color:color-mix(in srgb, var(--accent-primary, var(--fg)) 45%, var(--border));
+ }
+ .cookbook-gguf-delete-cb {
+ -webkit-appearance:none;
+ appearance:none;
+ width:8px !important;
+ height:8px !important;
+ min-width:8px;
+ min-height:8px;
+ padding:0;
+ margin:4px 0 0;
+ border:1px solid var(--border);
+ border-radius:50%;
+ background:transparent;
+ box-sizing:content-box;
+ cursor:pointer;
+ transition:background 0.15s, border-color 0.15s, transform 0.12s;
+ }
+ .cookbook-gguf-delete-cb:hover {
+ border-color:var(--accent, var(--red));
+ transform:scale(1.12);
+ }
+ .cookbook-gguf-delete-cb:checked {
+ background:var(--accent, var(--red));
+ border-color:var(--accent, var(--red));
+ }
+ .cookbook-gguf-delete-main,
+ .cookbook-gguf-delete-path {
+ min-width:0;
+ overflow:hidden;
+ text-overflow:ellipsis;
+ white-space:nowrap;
+ }
+ .cookbook-gguf-delete-main {
+ font-size:0.86rem;
+ color:var(--fg);
+ }
+ .cookbook-gguf-delete-path {
+ grid-column:2;
+ margin-top:-2px;
+ font-size:0.74rem;
+ opacity:0.58;
+ }
+ /* Styled prompt — text-input dialog (used in place of window.prompt) */
+ #styled-prompt-overlay {
+ background:rgba(0,0,0,0.5);
+ backdrop-filter:blur(4px);
+ pointer-events:auto !important;
+ z-index: 99999 !important;
+ position: fixed !important;
+ top: 0 !important;
+ left: 0 !important;
+ width: 100% !important;
+ height: 100% !important;
+ }
+ #styled-prompt-overlay .modal-content {
+ position: relative;
+ z-index: 10001;
+ }
+ .styled-prompt-box { width: min(400px, 92vw); max-width: 100%; box-sizing: border-box; }
+ .styled-prompt-box .modal-body { padding-top: 4px; }
+ .styled-prompt-input {
+ width:100%;
+ box-sizing:border-box;
+ margin-top:8px;
+ padding:9px 12px;
+ border:1px solid var(--border);
+ border-radius:6px;
+ background:var(--bg);
+ color:var(--fg);
+ font:inherit;
+ font-size:0.95rem;
+ outline:none;
+ transition: border-color 0.15s, box-shadow 0.15s;
+ }
+ .styled-prompt-input:focus {
+ border-color: var(--accent-primary, var(--red, #4a9eff));
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent-primary, var(--red, #4a9eff)) 25%, transparent);
+ }
+ @media (max-width:768px) {
+ .styled-prompt-box { width: 85vw; }
+ .styled-prompt-input { font-size: 0.9rem; padding: 10px 12px; }
+ }
+ /* Scroll navigation buttons */
+ .scroll-nav-btn {
+ position:fixed;
+ background:var(--panel);
+ color: var(--accent);
+ border:none;
+ border-radius:10px;
+ width:38px; height:38px;
+ padding:0;
+ display:flex; align-items:center; justify-content:center;
+ font-size:14px;
+ line-height:1;
+ font-family:inherit;
+ cursor:pointer;
+ opacity:0;
+ pointer-events:none;
+ transition: opacity .2s, transform .3s cubic-bezier(0.25, 1, 0.5, 1), background .15s;
+ z-index:100;
+ transform: translateY(0);
+ }
+ .scroll-nav-btn::before {
+ content: '';
+ position: absolute;
+ inset: 0;
+ border-radius: 10px;
+ padding: 1px;
+ background: linear-gradient(to bottom, var(--border), color-mix(in srgb, var(--border) 30%, transparent));
+ -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
+ mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
+ -webkit-mask-composite: xor;
+ mask-composite: exclude;
+ pointer-events: none;
+ }
+ .scroll-nav-btn.agent-working::after,
+ body.chat-agent-working #scroll-bottom-btn.show::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ border-radius: 10px;
+ padding: 1px;
+ background: conic-gradient(
+ from 0deg,
+ transparent 0deg,
+ transparent 245deg,
+ color-mix(in srgb, var(--accent, var(--red)) 78%, transparent) 315deg,
+ transparent 360deg
+ );
+ -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
+ mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
+ -webkit-mask-composite: xor;
+ mask-composite: exclude;
+ opacity: 0.65;
+ pointer-events: none;
+ animation: scrollAgentWorkingRing 1.05s linear infinite;
+ }
+ @keyframes scrollAgentWorkingRing {
+ to { transform: rotate(360deg); }
+ }
+ #scroll-bottom-btn.show { opacity:1; pointer-events:auto; }
+ .scroll-nav-caret {
+ display: inline-block;
+ font-family: Arial, Helvetica, sans-serif;
+ font-size: 16px;
+ line-height: 1;
+ transform: translateY(-1px);
+ pointer-events: none;
+ }
+ @media (hover: hover) and (pointer: fine) {
+ #scroll-bottom-btn.show:hover {
+ border-color: color-mix(in srgb, var(--fg) 25%, transparent);
+ }
+ }
+ #scroll-bottom-btn.slide-out {
+ transform: translateY(20px);
+ opacity: 0 !important;
+ pointer-events: none;
+ }
+ /* Focus outline for accessibility */
+ :focus-visible {
+ outline: 2px solid var(--red);
+ outline-offset: 2px;
+ }
+ /* Hamburger menu button */
+ .hamburger {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 32px;
+ height: 32px;
+ background: none;
+ border: 1px solid transparent;
+ border-radius: 6px;
+ padding: 0;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s;
+ }
+ .hamburger:hover {
+ background: color-mix(in srgb, var(--fg) 7%, transparent);
+ border-color: var(--border);
+ }
+ .hamburger span {
+ display: block;
+ width: 16px;
+ height: 2px;
+ background: var(--fg);
+ border-radius: 1px;
+ transition: transform 0.2s, opacity 0.2s;
+ }
+ .hamburger span + span { margin-top: 3px; }
+ /* Agent indicator */
+ #agent-indicator {
+ position: fixed;
+ top: 20px;
+ right: 20px;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ padding: 6px 12px;
+ border-radius: 6px;
+ font-size: 12px;
+ display: none;
+ z-index: 100;
+ cursor: pointer;
+ transition: all 0.2s ease;
+ }
+ #agent-indicator.active {
+ display: block;
+ border-color: var(--color-agent-active);
+ box-shadow: 0 0 10px rgba(0, 255, 0, 0.3);
+ }
+ #agent-indicator:hover {
+ border-color: var(--color-agent-active);
+ background: var(--panel);
+ }
+ #research-toggle-btn:disabled {
+ opacity: 0.6;
+ cursor: not-allowed;
+ }
+
+ /* ── Drag & Drop ── */
+
+ /* ---------- Color palette (dark / light) ---------- */
+
+ /* Drag and drop styling */
+ .section[dnd-active="true"] {
+ background: color-mix(in srgb, var(--red) 10%, transparent) !important;
+ border-color: var(--red) !important;
+ }
+
+ .section[dnd-over="true"] {
+ background: color-mix(in srgb, var(--red) 20%, transparent) !important;
+ border-color: var(--red) !important;
+ transform: scale(1.02);
+ }
+
+ .drag-handle {
+ cursor: grab;
+ opacity: 0.5;
+ padding: 0 6px;
+ user-select: none;
+ }
+
+ .drag-handle:hover {
+ opacity: 0.8;
+ }
+
+ .drag-handle:active {
+ cursor: grabbing;
+ }
+
+ /* ── UI Controls (Radio, Presets, Toolbar, Settings) ── */
+
+
+ /* Custom radio button styling */
+ .radio-option {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ cursor: pointer;
+ transition: all 0.2s ease;
+ }
+
+ .radio-option:hover {
+ background: color-mix(in srgb, var(--fg) 9%, transparent);
+ border-color: var(--fg);
+ }
+
+ .radio-option input[type="radio"] {
+ appearance: none;
+ -webkit-appearance: none;
+ width: 18px;
+ height: 18px;
+ border: 2px solid var(--border);
+ border-radius: 50%;
+ outline: none;
+ margin: 0;
+ background: var(--bg);
+ transition: all 0.2s ease;
+ position: relative;
+ flex-shrink: 0;
+ }
+
+ .radio-option input[type="radio"]:checked {
+ border-color: var(--red);
+ background: var(--red);
+ }
+
+ .radio-option input[type="radio"]:focus {
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--red) 30%, transparent);
+ }
+
+ .radio-label {
+ color: var(--fg);
+ font-size: 14px;
+ user-select: none;
+ }
+
+ /* Preset buttons */
+ .preset-btn {
+ height: 27.2px; /* 15% smaller than 32px */
+ padding: 0 8.5px; /* 15% smaller than 10px */
+ margin-left: 4px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--fg);
+ font-family: 'Fira Code', monospace;
+ font-size: 10.2px; /* 15% smaller than 12px */
+ cursor: pointer;
+ transition: all 0.2s ease;
+ }
+
+ .preset-btn:hover {
+ background: var(--panel);
+ border-color: var(--fg);
+ }
+
+ .preset-btn.active {
+ background: var(--panel);
+ border-color: var(--fg);
+ box-shadow: 0 0 0 1px var(--fg), 0 0 8px color-mix(in srgb, var(--fg) 16%, transparent);
+ font-weight: 600;
+ }
+
+ /* All preset buttons use the same blue color */
+ .preset-btn {
+ border-color: var(--red); /* Blue color */
+ }
+
+ .preset-btn.active {
+ border-color: var(--red); /* Blue color when active */
+ box-shadow: 0 0 0 1px var(--red), 0 0 8px color-mix(in srgb, var(--red) 30%, transparent);
+ }
+
+ /* Custom preset modal: the base .preset-modal-content sets overflow:hidden
+ (for desktop rounded-corner clipping), which on the mobile sheet clipped
+ the footer (Start/Cancel) off the bottom with no way to reach it. Let the
+ whole sheet scroll — same as every other mobile modal (.modal-content is
+ overflow-y:auto on mobile) — so the footer is always reachable. No flex
+ changes, so the body can't collapse. */
+ #custom-preset-modal .preset-modal-content {
+ overflow-y: auto !important;
+ }
+ #custom-preset-modal .modal-body label {
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--fg);
+ margin-top: 8px;
+ margin-bottom: 4px;
+ display: block;
+ }
+
+ #custom-preset-modal .modal-body input,
+ #custom-preset-modal .modal-body textarea {
+ width: 100%;
+ margin-bottom: 8px;
+ box-sizing: border-box;
+ }
+ #custom-preset-modal .modal-body textarea,
+ #custom-preset-modal .modal-body input[type="text"] {
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--fg);
+ padding: 8px 10px;
+ font-size: 13px;
+ font-family: inherit;
+ transition: border-color 0.15s;
+ }
+ #custom-preset-modal .modal-body textarea {
+ resize: vertical;
+ }
+ #custom-preset-modal .modal-body textarea:focus,
+ #custom-preset-modal .modal-body input[type="text"]:focus {
+ outline: none;
+ border-color: var(--red);
+ }
+
+ #custom-preset-modal .modal-footer {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ margin-top: 12px;
+ padding-top: 10px;
+ border-top: 1px solid var(--border);
+ }
+
+ #custom-preset-modal .modal-footer button {
+ padding: 7px 14px;
+ border-radius: 6px;
+ font-size: 12px;
+ font-weight: 500;
+ border: 1px solid var(--border);
+ background: none;
+ color: var(--fg);
+ cursor: pointer;
+ transition: all 0.15s;
+ }
+ #custom-preset-modal .modal-footer button:hover {
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
+
+ #custom-preset-modal .modal-footer button#save-custom-preset {
+ /* The theme's accent is stored in --red (theme.js sets --red = accentHex)
+ and --accent is undefined, so the canonical accent expression is
+ var(--accent, var(--red)). The old bare var(--accent) resolved to nothing
+ which, with color:var(--bg), made the button invisible. */
+ background: var(--accent, var(--red));
+ color: var(--bg);
+ border-color: var(--accent, var(--red));
+ }
+ #custom-preset-modal .modal-footer button#save-custom-preset:hover {
+ opacity: 0.85;
+ }
+ /* Toolbar visibility tab */
+ .toolbar-hint {
+ font-size: 12px;
+ color: color-mix(in srgb, var(--fg) 55%, transparent);
+ margin-bottom: 12px;
+ }
+ /* ── Appearance visibility toggles ── */
+ .vis-toggles {
+ display: flex;
+ flex-direction: column;
+ }
+ .vis-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ cursor: pointer;
+ padding: 5px 6px;
+ border-radius: 4px;
+ transition: background 0.12s;
+ }
+ .vis-row:hover {
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ }
+ .vis-row input[type="checkbox"] {
+ display: none;
+ }
+ .vis-icon {
+ width: 20px;
+ height: 20px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ color: color-mix(in srgb, var(--fg) 40%, transparent);
+ }
+ .vis-icon-text {
+ font-size: 10px;
+ font-weight: 700;
+ font-family: inherit;
+ letter-spacing: -0.5px;
+ }
+ .vis-label {
+ flex: 1;
+ font-size: 12px;
+ color: var(--fg);
+ user-select: none;
+ }
+ .vis-switch {
+ position: relative;
+ width: 30px;
+ height: 16px;
+ background: color-mix(in srgb, var(--fg) 15%, transparent);
+ border-radius: 8px;
+ transition: background 0.2s;
+ flex-shrink: 0;
+ }
+ .vis-switch::after {
+ content: '';
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 12px;
+ height: 12px;
+ background: var(--panel);
+ border-radius: 50%;
+ transition: transform 0.2s;
+ box-shadow: 0 1px 2px rgba(0,0,0,0.25);
+ }
+ .vis-row input:checked + .vis-switch {
+ background: var(--red);
+ }
+ .vis-row input:checked + .vis-switch::after {
+ transform: translateX(14px);
+ }
+ .vis-row input:checked ~ .vis-icon,
+ .vis-row:has(input:checked) .vis-icon {
+ color: var(--fg);
+ }
+ .persona-display-name-row .vis-label {
+ position: relative;
+ top: -4px;
+ }
+ .persona-display-name-row .vis-switch {
+ position: relative;
+ left: 4px;
+ }
+ .md-attach-paperclip-icon {
+ position: relative;
+ top: 1px;
+ }
+ /* Compare model selector — match the calendar modal's clean header
+ (no border underline). */
+ #compare-model-overlay .modal-header h4 {
+ pointer-events: none;
+ }
+ /* Compare model selector: keep manually-resized/tiny windows contained.
+ Picker dropdowns are appended to document.body, so the card itself can
+ clip and scroll without cropping the dropdown list. */
+ #compare-model-overlay .modal-content {
+ display: flex;
+ flex-direction: column;
+ max-height: min(720px, calc(100dvh - 48px));
+ overflow: hidden;
+ min-height: 180px;
+ }
+ #compare-model-overlay .modal-body {
+ overflow: auto;
+ flex: 1 1 auto;
+ min-height: 0;
+ }
+ .vis-hint {
+ font-size: 10px;
+ color: color-mix(in srgb, var(--fg) 30%, transparent);
+ font-weight: 400;
+ margin-left: 2px;
+ }
+ /* Settings toggle — admin-only lock indicator */
+ .ui-vis-lock {
+ display: none;
+ }
+ /* (legacy toolbar-toggle styles removed — now using .vis-* classes) */
+
+ /* Demo highlight pulse */
+ .odysseus-highlight {
+ outline: 2px solid var(--accent, var(--red)) !important;
+ outline-offset: 1px;
+ box-shadow: 0 0 0 4px color-mix(in srgb, var(--accent, var(--red)) 18%, transparent);
+ animation: ody-pulse 1.5s ease-in-out infinite;
+ z-index: 100;
+ position: relative;
+ }
+ @keyframes ody-pulse {
+ 0%, 100% { outline-color: var(--accent, var(--red)); box-shadow: 0 0 0 4px color-mix(in srgb, var(--accent, var(--red)) 18%, transparent); }
+ 50% { outline-color: color-mix(in srgb, var(--accent, var(--red)) 40%, transparent); box-shadow: 0 0 0 6px color-mix(in srgb, var(--accent, var(--red)) 8%, transparent); }
+ }
+ /* Floating breathing halo. Rendered as a body-level div positioned over
+ the target, so we don't fight the target's own outline / box-shadow /
+ overflow chain. JS keeps it in sync with the target's bounding rect. */
+ .tour-halo {
+ position: fixed;
+ pointer-events: none;
+ border: 3px solid var(--accent, var(--red));
+ border-radius: 10px;
+ z-index: 10000;
+ animation: ody-breathe 1.4s ease-in-out infinite;
+ opacity: 0;
+ transform: scale(0.94);
+ transition: opacity 0.35s ease-out, transform 0.35s ease-out;
+ }
+ .tour-halo.tour-fade-in {
+ opacity: 1;
+ transform: scale(1);
+ }
+ @keyframes ody-breathe {
+ 0%, 100% {
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent, var(--red)) 55%, transparent),
+ 0 0 22px 4px color-mix(in srgb, var(--accent, var(--red)) 40%, transparent);
+ border-color: var(--accent, var(--red));
+ }
+ 50% {
+ box-shadow: 0 0 0 6px color-mix(in srgb, var(--accent, var(--red)) 30%, transparent),
+ 0 0 40px 14px color-mix(in srgb, var(--accent, var(--red)) 70%, transparent);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 80%, transparent);
+ }
+ }
+ /* While the tour is active, lift overflow:hidden on common clipping
+ ancestors so the halo around a highlighted child isn't cropped. */
+ body.tour-active .sidebar,
+ body.tour-active .sidebar-inner,
+ body.tour-active .chat-input-bar,
+ body.tour-active .chat-input-top,
+ body.tour-active .chat-input-wrap,
+ body.tour-active .chat-input-right,
+ body.tour-active .mode-toggle,
+ body.tour-active .model-picker-wrap {
+ overflow: visible !important;
+ }
+
+ /* ── Secret tour hint (drag-to-snap on first modal open) ── */
+ .tour-hint {
+ position: fixed;
+ z-index: 10002;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ padding: 12px 14px 10px;
+ width: 240px;
+ font-size: 0.78rem;
+ line-height: 1.5;
+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.32);
+ opacity: 0;
+ transform: translateY(-4px);
+ transition: opacity 0.28s ease-out, transform 0.28s ease-out;
+ pointer-events: auto;
+ }
+ .tour-hint.tour-hint-in { opacity: 1; transform: translateY(0); }
+ .tour-hint.tour-hint-out { opacity: 0; transform: translateY(-4px); }
+ .tour-hint-visual {
+ display: flex;
+ justify-content: center;
+ margin-bottom: 8px;
+ color: var(--accent, var(--red));
+ }
+ .tour-hint-visual svg { display: block; }
+ .tour-hint-text { margin-bottom: 10px; opacity: 0.92; }
+ .tour-hint-text b { color: var(--accent, var(--red)); font-weight: 600; }
+ .tour-hint-dismiss {
+ display: block;
+ margin: 0 0 0 auto;
+ background: none;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ border-radius: 6px;
+ padding: 3px 12px;
+ cursor: pointer;
+ font-family: inherit;
+ font-size: 0.72rem;
+ opacity: 0.85;
+ transition: opacity 0.15s, background 0.15s;
+ }
+ .tour-hint-dismiss:hover { opacity: 1; background: color-mix(in srgb, var(--fg) 8%, transparent); }
+
+ /* SVG dance: cursor approaches title bar, drags right, modal snaps to a
+ right-half zone, holds, returns. 3.2s loop. */
+ .th-cursor { animation: th-cursor 3.2s ease-in-out infinite; transform-origin: 0 0; }
+ .th-modal-group { animation: th-modal-slide 3.2s ease-in-out infinite; transform-origin: 39px 31px; }
+ .th-zone { animation: th-zone-flash 3.2s ease-in-out infinite; }
+ @keyframes th-cursor {
+ 0%, 5% { transform: translate(35px, 32px); }
+ 18% { transform: translate(35px, 22px); }
+ 48% { transform: translate(80px, 22px); }
+ 72% { transform: translate(80px, 22px); }
+ 90%, 100% { transform: translate(35px, 32px); }
+ }
+ @keyframes th-modal-slide {
+ 0%, 18% { transform: translate(0, 0) scale(1, 1); }
+ 48% { transform: translate(45px, 0) scale(1, 1); }
+ 58% { transform: translate(30px, -19px) scale(1.4, 2.4); }
+ 72% { transform: translate(30px, -19px) scale(1.4, 2.4); }
+ 90%, 100% { transform: translate(0, 0) scale(1, 1); }
+ }
+ @keyframes th-zone-flash {
+ 0%, 38% { opacity: 0; }
+ 48% { opacity: 0.22; }
+ 58%, 72% { opacity: 0; }
+ 100% { opacity: 0; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .th-cursor, .th-modal-group, .th-zone { animation: none !important; }
+ }
+ .odysseus-hl-label {
+ position: absolute;
+ top: -22px;
+ left: 8px;
+ background: var(--red);
+ color: var(--bg);
+ font-size: 0.7rem;
+ padding: 2px 8px;
+ border-radius: 4px;
+ white-space: nowrap;
+ z-index: 101;
+ pointer-events: none;
+ }
+
+ /* Generated images inside chat bubbles */
+ .msg.generated-image-wrap .body { text-align: center; }
+ .generated-image {
+ max-width: 100%;
+ max-height: 512px;
+ border-radius: 8px;
+ cursor: pointer;
+ transition: transform 0.2s;
+ display: inline-block;
+ margin: 0 auto;
+ }
+ .generated-image:hover { transform: scale(1.02); }
+ .generated-image-caption {
+ font-size: 0.8rem;
+ opacity: 0.5;
+ margin-top: 6px;
+ font-style: italic;
+ text-align: center;
+ }
+
+ /* Setup wizard */
+ .setup-wizard { padding: 16px; max-width: 500px; }
+ .setup-wizard .setup-title { font-size: 1.1rem; font-weight: 600; margin-bottom: 12px; color: var(--fg); }
+ .setup-wizard .setup-label { font-size: 0.85rem; color: var(--fg); opacity: 0.7; margin-bottom: 8px; }
+ .setup-wizard .setup-presets { display: flex; flex-wrap: wrap; gap: 8px; }
+ .setup-wizard .setup-preset-btn {
+ padding: 8px 14px; border: 1px solid var(--border); border-radius: 6px;
+ background: var(--panel); color: var(--fg); cursor: pointer;
+ font-size: 0.85rem; transition: all 0.2s;
+ }
+ .setup-wizard .setup-preset-btn:hover { border-color: var(--red); background: color-mix(in srgb, var(--red) 11%, transparent); }
+ .setup-wizard .setup-input {
+ display: block; width: 100%; padding: 8px 12px; margin-bottom: 8px;
+ background: var(--panel); border: 1px solid var(--border);
+ border-radius: 6px; color: var(--fg); font-size: 0.85rem; box-sizing: border-box;
+ }
+ .setup-wizard .setup-input:focus { border-color: var(--red); outline: none; }
+ .setup-wizard .setup-connect-btn {
+ padding: 8px 20px; background: var(--red); color: var(--bg);
+ border: none; border-radius: 6px; cursor: pointer; font-weight: 600; margin-top: 4px;
+ }
+ .setup-wizard .setup-connect-btn:hover { opacity: 0.9; }
+ .setup-wizard .setup-status { font-size: 0.8rem; margin-top: 8px; color: var(--fg); opacity: 0.7; }
+ .setup-wizard .setup-model-list { display: flex; flex-wrap: wrap; gap: 8px; }
+ .setup-wizard .setup-model-btn {
+ padding: 8px 14px; border: 1px solid var(--border); border-radius: 6px;
+ background: var(--panel); color: var(--fg); cursor: pointer;
+ font-size: 0.85rem; transition: all 0.2s;
+ }
+ .setup-wizard .setup-model-btn:hover { border-color: var(--red); background: color-mix(in srgb, var(--red) 11%, transparent); }
+ .setup-wizard .setup-step.hidden { display: none; }
+
+ /* Dropdown menu styles */
+ .dropdown {
+ position: absolute;
+ top: calc(100% + 6px);
+ right: 0;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3), 0 0 0 1px color-mix(in srgb, var(--fg) 5%, transparent);
+ z-index: 1000;
+ display: none;
+ min-width: 220px;
+ padding: 6px;
+ backdrop-filter: blur(12px);
+ }
+
+ .dropdown.show {
+ display: block;
+ animation: dropdown-in 0.15s ease-out;
+ }
+ @keyframes dropdown-in {
+ from { opacity:0; transform:translateY(-6px) scale(0.97); }
+ to { opacity:1; transform:translateY(0) scale(1); }
+ }
+
+ .dropdown-item {
+ padding: 8px 10px;
+ border-radius: 6px;
+ cursor: pointer;
+ transition: background 0.12s ease;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 40%, transparent);
+ }
+
+ .dropdown-item:last-child {
+ border-bottom: none;
+ }
+
+ .dropdown-item .menu-icon {
+ width: 28px;
+ height: 28px;
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 14px;
+ flex-shrink: 0;
+ }
+
+ .dropdown-item .menu-text h4 {
+ margin: 0;
+ font-size: 12.5px;
+ font-weight: 500;
+ color: var(--fg);
+ line-height: 1.3;
+ }
+
+ .dropdown-item .menu-text p {
+ margin: 0;
+ font-size: 10.5px;
+ color: var(--color-subheader);
+ line-height: 1.3;
+ }
+
+ .dropdown-item:hover {
+ background: color-mix(in srgb, var(--red) 10%, transparent);
+ }
+ .dropdown-item:hover .menu-icon {
+ background: color-mix(in srgb, var(--red) 15%, transparent);
+ }
+
+ /* Compact dropdown items (session/model context menus) */
+ .dropdown-item-compact {
+ cursor: pointer;
+ padding: 6px 8px;
+ font-size: 11px;
+ border-radius: 8px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ color: var(--fg);
+ transition: background 0.1s;
+ }
+ .dropdown-item-compact:hover {
+ background: color-mix(in srgb, var(--accent) 10%, transparent);
+ }
+ .dropdown-item-compact .dropdown-icon {
+ width: 14px;
+ height: 14px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ opacity: 0.5;
+ }
+ .dropdown-item-compact .dropdown-icon svg {
+ width: 14px;
+ height: 14px;
+ }
+ .dropdown-item-compact .dropdown-shortcut {
+ margin-left: auto;
+ font-size: 9.5px;
+ opacity: 0.35;
+ font-weight: 400;
+ }
+ /* Keyboard shortcut hints (⌘+Alt+D etc.) are meaningless on touch —
+ hide them in the per-chat actions menu on mobile. */
+ @media (max-width: 768px) {
+ .session-dropdown .dropdown-shortcut { display: none; }
+ }
+ .dropdown-item-danger {
+ color: var(--red) !important;
+ }
+ .dropdown-item-danger .dropdown-icon {
+ opacity: 0.7;
+ }
+
+ /* Inline rename input for sessions */
+ .session-rename-input {
+ width: 100%;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--accent, var(--accent-primary));
+ border-radius: 4px;
+ padding: 2px 6px;
+ font-family: inherit;
+ font-size: 12px;
+ line-height: 1.3;
+ outline: none;
+ }
+
+ /* Session dropdown container */
+ .session-dropdown-menu {
+ position: fixed;
+ z-index: 1000;
+ display: none;
+ min-width: auto;
+ width: max-content;
+ padding: 4px;
+ animation: dropdown-in 0.15s ease-out;
+ }
+
+ /* Folder move submenu */
+ .session-folder-submenu {
+ position: fixed;
+ z-index: 1001;
+ display: none;
+ min-width: auto;
+ width: max-content;
+ padding: 4px;
+ }
+
+ .dropdown-divider {
+ height: 1px;
+ background: var(--border);
+ margin: 4px 8px;
+ }
+
+ /* Search toggle styles */
+ .search-toggle {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 6px 0;
+ border-bottom: 1px solid var(--border);
+ margin-bottom: 8px;
+ }
+
+ .search-provider-label {
+ font-size: 14px;
+ color: var(--fg);
+ }
+
+ /* ── Voice, Search, Themes, Comparison, Censor, Print ── */
+
+ /* Voice recording styles */
+ #mic-btn {
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ transition: all 0.2s ease;
+ }
+
+ #mic-btn:hover {
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ border-color: var(--fg);
+ }
+
+ #mic-btn.recording {
+ background: var(--color-recording);
+ border-color: var(--color-recording);
+ animation: pulse 1.5s infinite;
+ }
+
+
+
+ #recording-indicator {
+ position: fixed;
+ top: 10px;
+ left: 0;
+ right: 0;
+ background: rgba(0, 0, 0, 0.8);
+ backdrop-filter: blur(10px);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 12px;
+ margin: 10px;
+ z-index: 1000;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
+ }
+
+ #recording-indicator.hidden {
+ display: none !important;
+ }
+
+ .recording-content {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ color: white;
+ }
+
+ .recording-icon {
+ color: var(--color-recording);
+ font-size: 20px;
+ animation: pulse 1.5s infinite;
+ }
+
+ .recording-text {
+ font-size: 16px;
+ font-weight: 500;
+ }
+
+ #stop-recording {
+ background: var(--color-recording);
+ color: white;
+ border: none;
+ border-radius: 6px;
+ padding: 6px 12px;
+ font-size: 14px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: background 0.2s ease;
+ }
+
+ #stop-recording:hover {
+ background: var(--color-recording-hover);
+ }
+
+ /* Error state for recording */
+ #recording-indicator.error {
+ background: rgba(173, 26, 26, 0.9);
+ }
+
+ .recording-error {
+ color: var(--color-recording);
+ font-size: 14px;
+ margin-top: 4px;
+ }
+
+ @media (max-width: 768px) {
+ #recording-indicator {
+ margin: 8px;
+ padding: 10px;
+ }
+
+ .recording-text {
+ font-size: 14px;
+ }
+
+ #stop-recording {
+ padding: 6px 10px;
+ font-size: 12px;
+ }
+ }
+ /* SYNTAX HIGHLIGHTING — uses theme vars from style.css, no hardcoded overrides */
+ .hljs { color: var(--hl-fg, #9cdef2); background: none !important; }
+ pre { background: var(--code-bg, var(--hl-bg, #282c34)) !important; }
+
+ /* ---------- Search overlay (Ctrl+K command palette) ---------- */
+ .search-overlay {
+ position: fixed;
+ top: 0; left: 0; width: 100%; height: 100%;
+ background: rgba(0, 0, 0, 0.6);
+ display: flex;
+ align-items: flex-start;
+ justify-content: center;
+ padding-top: var(--search-overlay-top, 15vh);
+ z-index: 300;
+ backdrop-filter: blur(6px);
+ }
+ .search-overlay.hidden { display: none; }
+ .search-popup {
+ width: 520px;
+ max-width: 90vw;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ box-shadow: 0 16px 48px rgba(0, 0, 0, 0.5), 0 0 0 1px color-mix(in srgb, var(--fg) 6%, transparent);
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ max-height: 60vh;
+ }
+ .search-popup input#search-input {
+ width: 100%;
+ background: transparent;
+ border: none;
+ border-bottom: 1px solid var(--border);
+ outline: none;
+ color: var(--fg);
+ font-size: 16px;
+ font-family: 'Fira Code', monospace;
+ padding: 14px 16px;
+ box-sizing: border-box;
+ }
+ .search-popup input#search-input::placeholder {
+ color: color-mix(in srgb, var(--fg) 30%, transparent);
+ }
+ .search-results {
+ overflow-y: auto;
+ flex: 1;
+ padding: 4px;
+ }
+ .search-results:empty {
+ display: none;
+ }
+ .search-group-header {
+ font-size: 10px;
+ font-weight: 600;
+ color: var(--color-subheader);
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ padding: 10px 12px 4px;
+ }
+ .search-result-item {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+ padding: 8px 12px;
+ border-radius: 6px;
+ cursor: pointer;
+ transition: background 0.1s;
+ }
+ .search-result-item:hover,
+ .search-result-item.selected {
+ background: color-mix(in srgb, var(--red) 10%, transparent);
+ }
+ .search-result-role {
+ font-size: 10px;
+ font-weight: 600;
+ color: var(--color-subheader);
+ flex-shrink: 0;
+ min-width: 24px;
+ }
+ .search-result-snippet {
+ flex: 1;
+ font-size: 12px;
+ color: var(--fg);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .search-result-time {
+ font-size: 10px;
+ color: color-mix(in srgb, var(--fg) 35%, transparent);
+ flex-shrink: 0;
+ white-space: nowrap;
+ }
+ mark.search-highlight {
+ /* Was orange-on-orange (0.35 alpha bg + orange text) — too low-contrast
+ to read. Solid accent fill with bg-colored text reads clearly. */
+ background: var(--accent, #e8a830);
+ color: var(--bg, #1a1a1a);
+ border-radius: 2px;
+ padding: 0 2px;
+ font-weight: 600;
+ }
+ .search-empty {
+ text-align: center;
+ color: color-mix(in srgb, var(--fg) 35%, transparent);
+ padding: 24px;
+ font-size: 13px;
+ }
+
+ /* ---------- Theme popup (uses .modal > .modal-content frame) ---------- */
+ #theme-modal { z-index: 260; }
+ #theme-popup .theme-popup-sub { color: color-mix(in srgb, var(--fg) 50%, transparent); font-size: 11px; margin-bottom: 10px; }
+ /* `max-height` instead of a fixed height so the popup shrinks to fit its
+ content (avoids the leftover whitespace after the time-based switching
+ card was removed). The inner .theme-tab-panel keeps overflow:auto, so
+ any taller content still scrolls inside. */
+ #theme-popup { overflow-y: hidden; max-height: min(85vh, 600px); }
+ #theme-popup .modal-header { flex-shrink: 0; }
+ #theme-popup .admin-tabs { margin: 0 -10px 8px; padding: 0 10px; flex-shrink: 0; }
+ .theme-tab-panel { overflow-y: auto; min-height: 0; flex: 1; padding-bottom: 10px; }
+
+ .theme-grid {
+ display: grid; grid-template-columns: repeat(auto-fill, minmax(66px, 1fr));
+ gap: 6px; margin-bottom: 12px;
+ }
+ .theme-swatch {
+ border: 2px solid var(--border); border-radius: 8px; cursor: pointer;
+ padding: 5px; text-align: center; font-size: 0.65rem; color: var(--fg);
+ transition: border-color 0.15s, transform 0.15s;
+ }
+ .theme-swatch:hover { transform: scale(1.06); }
+ .theme-swatch.active { border-color: var(--red); box-shadow: 0 0 0 2px color-mix(in srgb, var(--red) 33%, transparent); }
+ .theme-swatch-colors {
+ display: flex; justify-content: center; margin-bottom: 3px;
+ }
+ .theme-swatch-colors span {
+ width: 15px; height: 15px; border-radius: 50%;
+ margin-left: -5px;
+ border: 1.5px solid color-mix(in srgb, var(--fg) 12%, transparent);
+ }
+ .theme-swatch-colors span:first-child { margin-left: 0; }
+ .theme-custom-label { font-size: 11px; font-weight: 600; color: color-mix(in srgb, var(--fg) 50%, transparent); text-transform: uppercase; letter-spacing: 0.06em; margin: 10px 0 6px; }
+ .theme-custom { display: grid; grid-template-columns: 1fr 1fr; gap: 4px 12px; }
+ .color-row { display: flex; align-items: center; gap: 4px; position: relative; }
+ .color-row label { font-size: 13px; font-weight: 500; color: var(--fg); opacity: 0.7; flex: 1; }
+ .color-row input[type="color"],
+ .color-row input.cp-swatch-input {
+ width: 24px; height: 24px; border: 1px solid var(--border); border-radius: 50%;
+ background: none; cursor: pointer; padding: 0; flex-shrink: 0;
+ overflow: hidden;
+ -webkit-appearance: none;
+ appearance: none;
+ }
+ .color-row input[type="color"]::-webkit-color-swatch-wrapper { padding: 0; }
+ .color-row input[type="color"]::-webkit-color-swatch { border: none; border-radius: 50%; }
+ .color-row input[type="color"]::-moz-color-swatch { border: none; border-radius: 50%; }
+ #theme-bg-effect-color { position: relative; top: 2px; }
+ .color-row input.cp-swatch-input {
+ color: transparent;
+ text-shadow: none;
+ caret-color: transparent;
+ font-size: 0;
+ user-select: none;
+ }
+ .color-row input.cp-swatch-input::selection { background: transparent; }
+ .color-row input.cp-swatch-input:focus { outline: 1px solid var(--red); outline-offset: 1px; }
+ .color-reset-btn {
+ width: 24px; height: 24px; border: none; background: none; cursor: pointer;
+ color: var(--fg); opacity: 0; font-size: 1.15rem; padding: 0; line-height: 1;
+ transition: opacity 0.15s, color 0.15s; flex-shrink: 0; pointer-events: none;
+ position: absolute; right: 6px; top: 50%; transform: translateY(-50%);
+ }
+ .color-row input[type="color"],
+ .color-row input.cp-swatch-input { margin-left: auto; }
+ /* Keep the harmony hex readout on the left, with the swatch dot anchored
+ to the right like the other color controls. */
+ #theme-harmony-card #harmony-accent-hex {
+ order: -1;
+ margin-right: auto;
+ }
+ .color-row:has(.color-reset-btn.changed) input[type="color"],
+ .color-row:has(.color-reset-btn.changed) input.cp-swatch-input { margin-right: 28px; }
+ .color-reset-btn.changed { opacity: 0.4; pointer-events: auto; }
+ .color-reset-btn.changed:hover { opacity: 1; color: var(--red); }
+ .theme-custom-divider {
+ grid-column: 1 / -1; font-size: 11px; color: var(--fg); opacity: 0.5;
+ text-transform: uppercase; letter-spacing: 0.04em; margin: 6px 0 2px;
+ border-top: 1px solid var(--border); padding-top: 6px;
+ }
+ .theme-swatch[data-custom] { position: relative; overflow: visible; }
+ /* Accent-coloured circular X — always visible (mobile-friendly), sits
+ INSIDE the swatch's top-right corner so it never crops into a
+ neighbouring swatch. */
+ .theme-delete-btn {
+ position: absolute;
+ top: -2px;
+ right: -2px;
+ width: 20px;
+ height: 20px;
+ padding: 0;
+ border: none;
+ border-radius: 50%;
+ background: var(--accent, var(--red, #d92534));
+ color: #fff;
+ cursor: pointer;
+ z-index: 2;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.35);
+ transition: transform 0.12s, background 0.12s;
+ }
+ .theme-delete-btn:hover {
+ background: color-mix(in srgb, var(--accent, var(--red)) 80%, white);
+ transform: scale(1.12);
+ }
+ .theme-delete-btn:active { transform: scale(0.95); }
+ .theme-delete-btn svg {
+ display: block;
+ /* Optical nudge — the X reads off-center inside the circle without it. */
+ position: relative;
+ left: 1px;
+ top: -1px;
+ }
+ .theme-save-row {
+ display: flex; gap: 6px; margin-top: 8px;
+ }
+ .theme-save-row input {
+ flex: 1; padding: 5px 8px; border: 1px solid var(--border); border-radius: 6px;
+ background: var(--bg); color: var(--fg); font-size: 12px; font-family: inherit;
+ }
+ .theme-save-row input:focus { outline: none; border-color: var(--red); }
+ .theme-save-row input::placeholder { color: color-mix(in srgb, var(--fg) 35%, transparent); }
+ .theme-save-row button {
+ padding: 6px 12px; border: 1px solid var(--red); border-radius: 6px;
+ background: transparent; color: var(--red); cursor: pointer;
+ font-size: 12px; font-family: inherit; white-space: nowrap; transition: all 0.15s;
+ }
+ .theme-save-row button:hover { background: color-mix(in srgb, var(--red) 11%, transparent); }
+ .theme-save-error {
+ font-size: 11px; color: var(--red); margin-top: 2px; display: none;
+ }
+ /* Import/Export */
+ .theme-io-row { display: flex; gap: 6px; margin-top: 6px; }
+ .theme-io-btn {
+ flex: 1; padding: 5px 10px; border: 1px solid var(--border); border-radius: 6px;
+ background: transparent; color: var(--fg); cursor: pointer;
+ font-size: 12px; opacity: 0.7; transition: all 0.15s; font-family: inherit;
+ }
+ .theme-io-btn:hover { opacity: 1; border-color: var(--fg); background: color-mix(in srgb, var(--fg) 5%, transparent); }
+
+ #memory-import-btn svg,
+ #memory-export-btn svg {
+ color: var(--accent, var(--red));
+ }
+ .theme-import-area {
+ width: 100%; margin-top: 6px; padding: 6px 8px;
+ border: 1px solid var(--border); border-radius: 6px;
+ background: var(--bg); color: var(--fg); font-size: 0.7rem;
+ font-family: inherit; resize: vertical; min-height: 48px;
+ }
+ .theme-import-area:focus { outline: none; border-color: var(--red); }
+ .theme-import-area.hidden { display: none; }
+ .theme-import-actions { display: flex; gap: 6px; margin-top: 4px; }
+ .theme-import-actions.hidden { display: none; }
+ /* Font & Density */
+ .theme-fd-row { display: flex; gap: 8px; margin-bottom: 8px; }
+ .theme-fd-group { flex: 1; display: flex; flex-direction: column; gap: 3px; }
+ .theme-fd-label { font-size: 12px; font-weight: 500; color: var(--fg); opacity: 0.6; }
+ .theme-fd-select {
+ padding: 5px 8px; border: 1px solid var(--border); border-radius: 6px;
+ background: var(--bg); color: var(--fg); font-size: 12px;
+ font-family: inherit; cursor: pointer;
+ }
+ .theme-fd-select:focus { outline: none; border-color: var(--red); }
+ @media (max-width: 768px) {
+ /* The switch is too cramped beside the Font and Density selects on
+ narrow screens; give Frosted a dedicated row instead. */
+ .theme-fd-row:first-of-type {
+ flex-wrap: wrap;
+ }
+ .theme-fd-row:first-of-type #theme-frosted-group {
+ flex: 1 1 100%;
+ flex-direction: row;
+ align-items: center;
+ justify-content: space-between;
+ min-width: 0;
+ }
+ }
+ .theme-fd-range {
+ width: 100%;
+ max-width: 100%;
+ box-sizing: border-box;
+ margin: 0;
+ padding: 0;
+ height: 24px;
+ background: transparent;
+ cursor: pointer;
+ -webkit-appearance: none;
+ appearance: none;
+ accent-color: var(--red);
+ }
+ .theme-fd-range::-webkit-slider-runnable-track {
+ height: 4px; background: var(--border); border-radius: 2px;
+ }
+ .theme-fd-range::-moz-range-track {
+ height: 4px; background: var(--border); border-radius: 2px;
+ }
+ .theme-fd-range::-webkit-slider-thumb {
+ -webkit-appearance: none; appearance: none;
+ width: 14px; height: 14px; border-radius: 50%;
+ background: var(--red); border: none; margin-top: -5px; cursor: pointer;
+ }
+ .theme-fd-range::-moz-range-thumb {
+ width: 14px; height: 14px; border-radius: 50%;
+ background: var(--red); border: none; cursor: pointer;
+ }
+ .theme-fd-range:focus { outline: none; }
+ /* Color Harmony Generator */
+ .theme-harmony-row { display: flex; gap: 8px; align-items: flex-end; }
+ .harmony-generate-btn {
+ padding: 5px 14px; border: 1px solid var(--red); border-radius: 6px;
+ background: transparent; color: var(--red); cursor: pointer;
+ font-size: 12px; white-space: nowrap; transition: all 0.15s;
+ font-family: inherit; width: 100%;
+ }
diff --cc static/css/05-documents.css
index 000000000,2c79ef37f..b1bb54a22
mode 000000,100644..100644
--- a/static/css/05-documents.css
+++ b/static/css/05-documents.css
@@@ -1,0 -1,3199 +1,3202 @@@
+ /* 05-documents - part of the former static/style.css.
+ *
+ * The stylesheet is split by area, but the split is mechanical: rules were
+ * moved verbatim and NOT regrouped. The numeric prefix is the load order, and
+ * that order is what preserves the cascade. A rule sits in the file its
+ * original position fell into, so an area's rules are not all in its file and
+ * a file is not only that area's rules.
+ *
+ * Do not reorder the <link> tags in static/index.html, and do not move a rule
+ * between files: with 1,151 redeclarations and 1,886 !important in this
+ * cascade, either can change which declaration wins.
+ *
+ * static/index.html and the PRECACHE list in static/sw.js must agree on this
+ * order. tests/test_static_stylesheet_manifest.py and
+ * tests/test_css_computed_style_snapshot.py fail if that drifts.
+ */
+ .memory-suggestions-actions {
+ position: relative;
+ left: -4px;
+ }
+ .memory-suggestions-actions .memory-item-btn,
+ .memory-suggestion-actions .memory-item-btn {
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ border-color: color-mix(in srgb, var(--border) 85%, transparent);
+ }
+ .memory-suggestions-actions .memory-item-btn.save,
+ .memory-suggestion-actions .memory-item-btn.save {
+ background: color-mix(in srgb, var(--red) 9%, transparent);
+ border-color: color-mix(in srgb, var(--red) 28%, transparent);
+ }
+
+ .memory-suggestion-item {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 6px;
+ padding: 5px 8px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--red) 3%, transparent);
+ }
+
+ /* Tidy animations */
+ .memory-tidy-editing {
+ border-color: color-mix(in srgb, var(--hl-function) 40%, transparent);
+ background: color-mix(in srgb, var(--hl-function) 6%, transparent);
+ transition: all 0.3s;
+ }
+
+ .memory-tidy-text-old {
+ opacity: 0.4;
+ text-decoration: line-through;
+ transition: opacity 0.25s;
+ }
+
+ .memory-tidy-text-new {
+ color: var(--hl-function);
+ transition: color 0.4s;
+ }
+
+ .memory-tidy-removing {
+ text-decoration: line-through;
+ opacity: 0;
+ max-height: 0;
+ padding-top: 0;
+ padding-bottom: 0;
+ margin-top: 0;
+ margin-bottom: 0;
+ border-color: transparent;
+ overflow: hidden;
+ transition: opacity 0.3s, max-height 0.4s 0.1s, padding 0.4s 0.1s, border-color 0.3s;
+ }
+
+ /* ===== DOCUMENT EDITOR (ARTIFACTS) PANEL ===== */
+
+ /* Doc editor is a body-level sibling of chat-container */
+
+ /* Divider between chat and doc editor */
+ .doc-divider {
+ width: 1px;
+ flex-shrink: 0;
+ background: color-mix(in srgb, var(--fg) 11%, transparent);
+ cursor: col-resize;
+ transition: background 0.15s;
+ position: relative;
+ z-index: 10;
+ }
+ .doc-divider::before {
+ content: '';
+ position: absolute;
+ top: 0; bottom: 0;
+ left: -10px;
+ width: 21px;
+ cursor: col-resize;
+ }
+ .doc-divider:hover {
+ background: color-mix(in srgb, var(--fg) 30%, transparent);
+ }
+ /* Always-visible "›" handle on the drag divider — clickable to collapse the
+ panel, and signals the divider is interactive. */
+ .doc-divider-collapse {
+ position: absolute;
+ top: 50%;
+ left: 2px;
+ transform: translateY(-50%);
+ width: 20px;
+ height: 34px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ background: var(--panel);
+ color: var(--fg);
+ font-size: 16px;
+ font-weight: 700;
+ line-height: 1;
+ opacity: 0.6;
+ cursor: pointer;
+ transition: opacity 0.1s, border-color 0.1s, left 0.08s ease;
+ z-index: 12;
+ }
+ .doc-divider.doc-divider-handle-idle:hover .doc-divider-collapse,
+ .doc-divider.doc-divider-handle-idle:focus-within .doc-divider-collapse {
+ opacity: 0.92;
+ pointer-events: auto;
+ }
+ /* When in fullscreen mode (cursor outside the doc), the flap itself slides
+ to the OUTSIDE edge of the divider — visually belonging to the chat side
+ the cursor is on, not the doc. The left/right shift pairs with the glyph
+ rotation for a single coordinated transition. */
+ .doc-divider-collapse[data-mode="fullscreen"] {
+ left: -22px;
+ }
+ .doc-divider-collapse:hover { opacity: 1 !important; border-color: var(--accent, var(--red)); }
+ /* The same `›` glyph is in the markup; CSS rotates 180° for the left-pointing
+ (fullscreen) state. Smooth transition pairs with the chevron's slide. */
+ .doc-divider-collapse > span {
+ display: inline-block;
+ transition: transform 0.08s ease, opacity 0.08s ease;
+ }
+ .doc-divider-collapse[data-mode="fullscreen"] > span {
+ transform: rotate(180deg);
+ }
+ /* Secondary "hide panel" X button in the divider — invisible until the pane
+ is fullscreen, then floats just below the unfullscreen chevron so the user
+ has a one-tap escape that minimises the pane instead of just exiting
+ fullscreen. */
+ .doc-divider-hide {
+ position: absolute;
+ top: 50%;
+ left: 2px;
+ width: 20px;
+ height: 20px;
+ margin-top: 22px;
+ display: none;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ background: var(--panel);
+ color: var(--accent, var(--red));
+ cursor: pointer;
+ padding: 0;
+ z-index: 12;
+ opacity: 0.85;
+ transition: opacity 0.15s, border-color 0.15s;
+ }
+ .doc-divider-hide:hover {
+ opacity: 1;
+ border-color: var(--accent, var(--red));
+ }
+
+ /* Copy / Export split button — main click copies, the caret opens the export menu. */
+ .doc-split-btn {
+ display: inline-flex;
+ align-items: stretch;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ overflow: hidden;
+ height: 22px;
+ flex-shrink: 0;
+ }
+ .doc-split-btn .doc-split-main,
+ .doc-split-btn .doc-split-caret {
+ border: none !important;
+ border-radius: 0 !important;
+ height: 100% !important;
+ min-height: 0 !important;
+ /* Keep the element fully opaque so the divider line stays crisp; dim the
+ glyph via colour instead (the base .doc-action-icon-btn fades the whole
+ element to 0.3, which also hides the divider). */
+ opacity: 1 !important;
+ color: color-mix(in srgb, var(--fg) 55%, transparent) !important;
+ background: none !important;
+ transition: color 0.12s, background 0.12s;
+ }
+ .doc-split-btn:hover .doc-split-main,
+ .doc-split-btn:hover .doc-split-caret { color: var(--fg) !important; }
+ .doc-split-btn .doc-split-caret {
+ border-left: 1px solid var(--border) !important;
+ padding: 0 5px 0 7px !important;
+ }
+ .doc-split-btn .doc-split-main:hover,
+ .doc-split-btn .doc-split-caret:hover {
+ background: color-mix(in srgb, var(--fg) 8%, transparent) !important;
+ color: var(--fg) !important;
+ }
+
+ /* Editor pane — body-level flex sibling */
+ .doc-editor-pane {
+ flex: 1;
+ min-width: 0;
+ max-width: 70vw;
+ container-type: inline-size;
+ container-name: docpane;
+ display: flex;
+ flex-direction: column;
+ background: var(--bg);
+ border-left: 1px solid var(--border);
+ box-shadow: -10px 0 22px rgba(0, 0, 0, 0.16);
+ overflow: hidden;
+ height: 100%;
+ position: relative;
+ z-index: 1;
+ color-scheme: dark;
+ /* Desktop entrance is driven by openPanel() so the pane has one transform
+ owner. The mobile sheet has its own animation below. */
+ animation: none;
+ transform-origin: right center;
+ will-change: clip-path, opacity;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .doc-editor-pane,
+ .doc-editor-pane.doc-pane-leaving { animation: none; }
+ }
+ .doc-loading-overlay {
+ position: absolute;
+ inset: 0;
+ z-index: 10;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--bg);
+ }
+
+ /* ---- Tab bar ---- */
+ .doc-tab-bar {
+ display: flex;
+ align-items: stretch;
+ background: var(--bg);
+ border-bottom: 1px solid var(--border);
+ flex-shrink: 0;
+ height: 36px;
+ }
+ .doc-tab-scroll {
+ display: flex;
+ align-items: stretch;
+ flex: 1;
+ min-width: 0;
+ overflow-x: auto;
+ overflow-y: hidden;
+ scrollbar-width: none;
+ justify-content: flex-start;
+ /* Fade tabs into the bar's background at the edges (next to the scroll
+ arrows) so an overflowing tab dissolves instead of being hard-cut. The
+ fade is conditional — when we're at an edge there's nothing to fade to,
+ so the mask gradient becomes flat on that side (no shadow). */
+ -webkit-mask-image: linear-gradient(to right, transparent 0, #000 18px, #000 calc(100% - 18px), transparent 100%);
+ mask-image: linear-gradient(to right, transparent 0, #000 18px, #000 calc(100% - 18px), transparent 100%);
+ }
+ .doc-tab-arrow {
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.55;
+ cursor: pointer;
+ font-size: 18px;
+ padding: 0 6px;
+ flex-shrink: 0;
+ transition: opacity 0.15s;
+ line-height: 1;
+ display: flex;
+ align-items: center;
+ position: relative;
+ top: -2px;
+ }
+ .doc-tab-arrow:hover {
+ opacity: 1;
+ }
+ /* Mobile swipe-down grab handle at the top of the doc sheet. */
+ .doc-mobile-grabber { display: none; }
+ @media (max-width: 768px) {
+ body.doc-view .doc-mobile-grabber {
+ display: block;
+ flex-shrink: 0;
+ height: 18px;
+ position: relative;
+ background: transparent;
+ background-color: transparent;
+ background-image: none;
+ touch-action: none;
+ cursor: grab;
+ }
+ body.doc-view .doc-mobile-grabber::before {
+ content: '';
+ position: absolute;
+ top: 7px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 36px;
+ height: 4px;
+ background: var(--fg);
+ opacity: 0.25;
+ border-radius: 2px;
+ }
+ }
+
+ .doc-tab {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 0 10px;
+ font-family: inherit;
+ font-size: 11px;
+ color: var(--fg);
+ opacity: 0.4;
+ cursor: pointer;
+ white-space: nowrap;
+ transition: opacity 0.1s, background 0.1s;
+ flex-shrink: 0;
+ border-right: 1px solid color-mix(in srgb, var(--border) 50%, transparent);
+ position: relative;
+ }
+ .doc-tab:hover {
+ opacity: 0.7;
+ background: color-mix(in srgb, var(--fg) 3%, transparent);
+ }
+ .doc-tab.active {
+ opacity: 1;
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ border-radius: 7px 7px 0 0;
+ }
+ .doc-tab-title {
+ max-width: 140px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .doc-tab-title-input {
+ background: transparent;
+ border: 1px solid var(--fg);
+ border-radius: 2px;
+ color: var(--fg);
+ font-family: inherit;
+ font-size: 11px;
+ padding: 0 4px;
+ height: 18px;
+ width: 120px;
+ max-width: 180px;
+ outline: none;
+ }
+ .doc-tab-lang {
+ font-size: 9px;
+ opacity: 0.5;
+ }
+ .doc-tab-close {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: none;
+ border: 1px solid transparent;
+ border-radius: 999px;
+ color: var(--fg);
+ opacity: 0.4;
+ cursor: pointer;
+ font-size: 18px;
+ line-height: 1;
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ box-sizing: border-box;
+ margin-left: 3px;
+ flex-shrink: 0;
+ align-self: center;
+ transition: opacity 0.12s, color 0.12s, background 0.12s, border-color 0.12s;
+ }
+ .doc-tab-close:hover {
+ opacity: 1;
+ color: var(--fg);
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ border-color: color-mix(in srgb, var(--fg) 12%, transparent);
+ }
+ /* Mobile-only footer (Close + Copy); hidden on desktop and in email mode. */
+ .doc-mobile-footer { display: none; }
+ .doc-tab-new {
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.25;
+ cursor: pointer;
+ font-size: 11px;
+ font-weight: 600;
+ padding: 0 10px;
+ transition: opacity 0.1s;
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ height: 100%;
+ }
+ .doc-tab-new:hover {
+ opacity: 0.7;
+ }
+ .doc-tab-play {
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.55;
+ cursor: pointer;
+ padding: 0 2px;
+ font-size: 10px;
+ line-height: 1;
+ transition: opacity 0.1s, color 0.1s;
+ flex-shrink: 0;
+ }
+ .doc-tab-play:hover {
+ opacity: 1;
+ color: var(--green, #4ec970);
+ }
+ .doc-tab-play.active {
+ opacity: 1;
+ color: var(--green, #4ec970);
+ }
+ .doc-tab.dragging {
+ opacity: 0.3;
+ }
+ .doc-tab.drag-over {
+ border-left: 2px solid var(--fg);
+ }
+
+ /* ---- HTML preview iframe ---- */
+ .doc-html-preview {
+ flex: 1;
+ width: 100%;
+ border: none;
+ background: #fff;
+ }
+
+ /* ---- Editor header ---- */
+ .doc-editor-header {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 10px;
+ /* Moved to the bottom as a footer: flex order pushes it last in the pane
+ column, and the divider flips to the top edge. */
+ order: 99;
+ border-top: 1px solid var(--border);
+ flex-shrink: 0;
+ flex-wrap: nowrap;
+ min-height: 36px;
+ background: var(--bg);
+ }
+ /* Version now lives in the document tab, not the footer. */
+ #doc-version-badge { display: none !important; }
+ /* Language icon chip on doc tabs — sits between the version pill and title.
+ Hidden when empty so docs without a language don't get awkward spacing. */
+ .doc-tab-lang {
+ display: inline-flex; align-items: center;
+ flex-shrink: 0;
+ align-self: center;
+ }
+ .doc-tab-lang:empty { display: none; }
+ .doc-tab-lang svg { display: block; }
+
+ .doc-tab-version {
+ font-size: 9px;
+ font-weight: 600;
+ padding: 1px 6px;
+ cursor: pointer;
+ flex-shrink: 0;
+ align-self: center;
+ line-height: 1.4;
+ /* Sits to the LEFT of the title now — space it off the title text. */
+ margin-right: 6px;
+ /* Accent pill so it's obvious the version is a clickable control. */
+ color: var(--accent-primary, var(--red));
+ border: 1px solid color-mix(in srgb, var(--accent-primary, var(--red)) 45%, transparent);
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 12%, transparent);
+ border-radius: 9px;
+ }
+ .doc-tab-version:hover {
+ border-color: var(--accent-primary, var(--red));
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 22%, transparent);
+ }
+ .doc-close-btn {
+ order: -1;
+ opacity: 0.5;
+ flex-shrink: 0;
+ }
+ .doc-close-btn:hover {
+ opacity: 1;
+ }
+
+ .doc-editor-actions {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex: 1;
+ justify-content: flex-end;
+ }
+ .doc-left .doc-editor-actions {
+ margin-left: 0;
+ }
+
+ .doc-version-badge {
+ background: color-mix(in srgb, var(--red) 12%, transparent);
+ border: 1px solid color-mix(in srgb, var(--red) 55%, transparent);
+ color: var(--red);
+ padding: 1px 8px;
+ border-radius: 999px;
+ font-size: 10px;
+ font-weight: 600;
+ line-height: 1.4;
+ cursor: pointer;
+ user-select: none;
+ transition: background 0.1s, border-color 0.1s;
+ opacity: 0.9;
+ }
+ .doc-version-badge:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--red) 20%, transparent);
+ border-color: var(--red);
+ }
+
+ .doc-stream-indicator {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ font-size: 11px;
+ color: var(--accent);
+ opacity: 0.9;
+ white-space: nowrap;
+ animation: doc-stream-pulse 1.5s ease-in-out infinite;
+ }
+ .doc-stream-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--accent);
+ }
+
+ /* In the doc footer the type picker sits next to the accent Copy/Export split —
+ match its 28px height and 6px radius so the right-hand controls line up. */
+ .doc-actions-footer #doc-language-select {
+ height: 28px;
+ border-radius: 6px;
+ font-size: 11px;
+ top: 0;
+ }
+ /* Lang-type icon shown to the LEFT of the language select. Browsers won't
+ render SVG inside <option>, so this surface the current selection's icon
+ externally. */
+ #doc-language-icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 18px; height: 18px;
+ color: var(--accent-primary, var(--red));
+ flex-shrink: 0;
+ }
+ #doc-language-icon:empty { display: none; }
+ #doc-language-icon svg { display: block; }
+
+ /* Visually hidden but available to assistive tech (screen readers, axe).
+ Use for content that should be announced/structural but not painted —
+ e.g. the persistent page <h1>. */
+ .a11y-visually-hidden {
+ position: absolute !important;
+ width: 1px !important; height: 1px !important;
+ padding: 0 !important; margin: -1px !important;
+ overflow: hidden !important; clip: rect(0, 0, 0, 0) !important;
+ white-space: nowrap !important; border: 0 !important;
+ }
+
+ /* ── Custom language type picker (replaces visible chrome of native <select>
+ — <option>s can't render SVG). Hidden select stays as the source of truth. */
+ .doc-langpicker-native-hidden {
+ position: absolute !important;
+ width: 1px !important; height: 1px !important;
+ padding: 0 !important; margin: -1px !important;
+ overflow: hidden !important; clip: rect(0,0,0,0) !important;
+ border: 0 !important;
+ }
+ .doc-langpicker-trigger {
+ display: inline-flex; align-items: center; gap: 6px;
+ height: 28px; padding: 0 8px 0 10px;
+ background: var(--bg); color: var(--fg);
+ border: 1px solid var(--border); border-radius: 6px;
+ font-size: 11px; cursor: pointer;
+ transition: border-color 0.12s, background 0.12s;
+ }
+ .doc-langpicker-trigger:hover {
+ border-color: color-mix(in srgb, var(--accent-primary, var(--red)) 60%, var(--border));
+ }
+ .doc-langpicker-trigger.doc-langpicker-email-compact .doc-langpicker-label,
+ .doc-langpicker-trigger.doc-langpicker-email-compact > svg:last-child {
+ display: none;
+ }
+ .doc-langpicker-trigger svg { display: block; flex-shrink: 0; }
+ .doc-langpicker-label {
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+ max-width: 90px;
+ }
+ .doc-langpicker-ico-blank {
+ display: inline-block; width: 14px; height: 14px; flex-shrink: 0;
+ }
+ .doc-langpicker-menu {
+ background: var(--bg);
+ border: 1px solid var(--border); border-radius: 8px;
+ padding: 4px;
+ box-shadow: 0 10px 28px rgba(0,0,0,0.32);
+ max-height: 60vh; overflow-y: auto;
+ z-index: 10000;
+ min-width: 160px;
+ }
+ .doc-langpicker-item {
+ display: flex; align-items: center; gap: 8px;
+ width: 100%;
+ padding: 6px 10px;
+ background: none; color: var(--fg);
+ border: none; border-radius: 5px;
+ font-size: 12px; text-align: left;
+ cursor: pointer;
+ }
+ .doc-langpicker-item:hover {
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
+ .doc-langpicker-group {
+ padding: 6px 10px 3px;
+ color: var(--fg-muted, var(--fg));
+ font-size: 9px;
+ font-weight: 600;
+ letter-spacing: 0.05em;
+ text-transform: uppercase;
+ opacity: 0.55;
+ }
+ .doc-langpicker-divider {
+ height: 1px;
+ margin: 4px 6px;
+ background: var(--border);
+ opacity: 0.65;
+ }
+ .doc-langpicker-item.is-selected {
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 14%, transparent);
+ color: var(--accent-primary, var(--red));
+ }
+ .doc-langpicker-item svg { display: block; flex-shrink: 0; }
+ .doc-langpicker-item .doc-langpicker-label { max-width: 220px; }
+
+ .doc-language-select {
+ background-color: var(--bg);
+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%239cdef2' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'><polyline points='6 15 12 9 18 15'/></svg>");
+ background-repeat: no-repeat;
+ background-position: right 4px center;
+ color: var(--fg);
+ color-scheme: dark;
+ border: 1px solid var(--border);
+ border-radius: 5px;
+ position: relative;
+ top: 0;
+ font-family: inherit;
+ font-size: 10px;
+ padding: 2px 20px 2px 8px;
+ height: 22px;
+ /* Fixed width so the right-anchored chevron doesn't shift when the selected
+ option's text width changes. */
+ width: 96px;
+ text-overflow: ellipsis;
+ opacity: 0.8;
+ cursor: pointer;
+ -moz-appearance: none;
+ appearance: none;
+ }
+ /* Light theme: tint the chevron with the light foreground instead of cyan. */
+ :root.light .doc-language-select {
+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%232b2b2b' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'><polyline points='6 15 12 9 18 15'/></svg>");
+ }
+ /* New-tab "+" spins on hover, like the library sidebar "+". */
+ .doc-tab-new svg { transition: transform 0.45s cubic-bezier(0.34, 1.56, 0.64, 1); }
+ .doc-tab-new:hover svg { transform: rotate(180deg) scale(1.15); }
+
+ .doc-action-btn {
+ background: none;
+ color: var(--fg);
+ border: none;
+ font-family: inherit;
+ font-size: 10px;
+ padding: 2px 8px;
+ height: 22px;
+ cursor: pointer;
+ opacity: 0.45;
+ transition: opacity 0.1s;
+ }
+ .doc-action-btn:hover {
+ opacity: 1;
+ }
+ .doc-action-icon-btn {
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.3;
+ cursor: pointer;
+ padding: 3px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ transition: opacity 0.1s;
+ }
+ .doc-action-icon-btn:hover {
+ opacity: 1;
+ }
+ .doc-action-icon-btn:disabled {
+ opacity: 0.18;
+ cursor: default;
+ pointer-events: none;
+ }
+ #doc-undo-btn:not(:disabled),
+ #doc-redo-btn:not(:disabled) {
+ opacity: 0.68;
+ }
+ .doc-fontsize-levels {
+ position: absolute;
+ right: 6px;
+ bottom: 3px;
+ display: inline-flex;
+ line-height: 1;
+ pointer-events: none;
+ }
+ .doc-fontsize-levels i {
+ font-style: normal;
+ font-weight: 700;
+ font-size: 7px;
+ /* Bare --accent is undefined in this codebase, was falling back to the
+ hardcoded blue #4a9eff — use the real theme accent. */
+ color: var(--accent-primary, var(--red));
+ opacity: 1;
+ }
+ .doc-fontsize-levels i.active { opacity: 1; }
+ /* Collapsed buttons hidden in header, shown in overflow menu */
+ .doc-collapsible-btn.doc-collapsed { display: none !important; }
+ .doc-overflow-toggle:hover { opacity: 1; }
+ .doc-overflow-menu {
+ display: none;
+ position: fixed;
+ z-index: 9999;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ padding: 4px 0;
+ min-width: 140px;
+ box-shadow: 0 4px 12px rgba(0,0,0,0.3);
+ }
+ .doc-overflow-menu.open { display: block; }
+ .doc-overflow-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 5px 12px;
+ background: none;
+ border: none;
+ color: var(--fg);
+ font-family: inherit;
+ font-size: 11px;
+ cursor: pointer;
+ white-space: nowrap;
+ transition: background 0.1s;
+ }
+ .doc-overflow-item:hover,
+ .doc-overflow-item:focus-visible {
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 12%, transparent);
+ outline: none;
+ }
+ .doc-overflow-item .rich-align-preview {
+ display: inline-block;
+ white-space: nowrap;
+ }
+ .doc-overflow-item:disabled {
+ opacity: 0.28;
+ cursor: default;
+ }
+ .doc-overflow-item.is-current {
+ color: var(--accent-primary, var(--red));
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 9%, transparent);
+ }
+ .md-dd-current {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 14px;
+ margin-left: auto;
+ opacity: 0;
+ }
+ .doc-overflow-item.is-current .md-dd-current { opacity: 1; }
+ .doc-overflow-item.rich-table-danger { color: var(--color-danger, #c0392b); }
+ .doc-overflow-item svg { flex-shrink: 0; opacity: 0.5; }
+ .doc-ai-writing-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 2px;
+ color: var(--accent-primary, var(--red));
+ }
+ .doc-ai-writing-btn svg:first-child { color: var(--accent-primary, var(--red)); opacity: 1; }
+ .doc-ai-writing-whirlpool { position: relative; top: -4px; }
+ .doc-ai-writing-menu { min-width: 206px; }
+ .doc-ai-writing-menu-title {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 12px 6px;
+ color: var(--accent-primary, var(--red));
+ font-size: 10px;
+ font-weight: 600;
+ border-bottom: 1px solid var(--border);
+ }
+ .doc-ai-writing-menu-title svg { opacity: 1; }
+ .doc-ai-writing-item-icon {
+ width: 16px;
+ flex: 0 0 16px;
+ text-align: center;
+ color: var(--accent-primary, var(--red));
+ font-size: 11px;
+ font-weight: 600;
+ }
+
+ /* Markdown Edit/Preview two-icon switch — segmented, styled to match the Copy
+ split button. The active half gets a static highlight (no sliding). */
+ .md-view-toggle {
+ display: inline-flex;
+ align-items: center;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ overflow: hidden;
+ flex-shrink: 0;
+ height: 22px;
+ }
+ .md-view-toggle .md-view-opt {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ min-width: 26px;
+ width: auto;
+ height: 100%;
+ padding: 0 7px !important;
+ border: none !important;
+ border-radius: 0 !important;
+ background: none !important;
+ color: var(--fg);
+ opacity: 0.45;
+ cursor: pointer;
+ transition: opacity 0.12s, color 0.12s, background 0.12s;
+ }
+ .md-view-label {
+ font-size: 10px;
+ font-weight: 600;
+ line-height: 1;
+ }
+ .md-view-toggle .md-view-opt:hover { opacity: 0.8; }
+ .md-view-toggle .md-view-opt.active {
+ opacity: 1;
+ color: var(--fg);
+ background: var(--bg) !important;
+ /* "Punch" pop when a side becomes active (only fires on an actual switch —
+ re-applying .active without a change doesn't restart the animation). */
+ animation: md-view-punch 0.28s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ @keyframes md-view-punch {
+ 0% { transform: scale(0.8); }
+ 55% { transform: scale(1.18); }
+ 100% { transform: scale(1); }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .md-view-toggle .md-view-opt.active { animation: none; }
+ }
+
+ .doc-md-toolbar.md-preview-active {
+ border-bottom-color: var(--bg);
+ }
+ .doc-md-toolbar.md-write-active {
+ border-bottom-color: var(--sidebar-bg, var(--panel));
+ }
+ .doc-md-toolbar.md-preview-active #doc-md-view-toggle,
+ .doc-md-toolbar.md-write-active #doc-md-view-toggle {
+ align-self: flex-end;
+ height: 28px;
+ margin-bottom: -6px;
+ border-radius: 7px 7px 0 0;
+ box-shadow: 0 -1px 0 var(--border), -1px 0 0 var(--border), 1px 0 0 var(--border);
+ }
+ .doc-md-toolbar.md-preview-active #doc-md-view-toggle {
+ background: var(--bg);
+ border-bottom-color: var(--bg);
+ }
+ .doc-md-toolbar.md-write-active #doc-md-view-toggle {
+ background: var(--sidebar-bg, var(--panel));
+ border-bottom-color: var(--sidebar-bg, var(--panel));
+ }
+ .doc-md-toolbar.md-preview-active #doc-md-view-toggle .md-view-opt.active {
+ background: var(--bg) !important;
+ }
+ .doc-md-toolbar.md-write-active #doc-md-view-toggle .md-view-opt.active {
+ background: var(--bg) !important;
+ }
+ .doc-md-preview.md-preview-active {
+ background: var(--bg);
+ border-top: 0;
+ margin-top: 0;
+ }
+
+ /* Write and Preview are separate tabs that sit out from the toolbar. */
+ .md-view-toggle {
+ position: relative;
+ gap: 2px;
+ height: 28px;
+ border: 0;
+ border-radius: 0;
+ overflow: visible;
+ background: var(--bg) !important;
+ box-shadow: none !important;
+ }
+ /* The toolbar owns the boundary beneath the editor. A second full-width
+ baseline here would remain visible directly under the active tab. */
+ .md-view-toggle::after { content: none; }
+ .md-view-toggle .md-view-opt {
+ height: 28px;
+ border: 1px solid var(--border) !important;
+ border-bottom-color: transparent !important;
+ border-radius: 7px 7px 0 0 !important;
+ position: relative;
+ z-index: 2;
+ }
+ .md-view-toggle .md-view-opt.active {
+ z-index: 3;
+ }
+ .md-view-toggle .md-view-opt:first-child,
+ #doc-render-view-toggle .md-view-opt:first-child {
+ background: var(--sidebar-bg, var(--panel)) !important;
+ }
+ .md-view-toggle .md-view-opt:last-child,
+ #doc-render-view-toggle .md-view-opt:last-child {
+ background: var(--sidebar-bg, var(--panel)) !important;
+ }
+
+ /* Keep code's Edit/Run switch in the same visual language as Write/Preview:
+ Edit is attached to the sidebar-colored editor surface, while Run/Preview
+ is attached to the lighter content surface. */
+ #doc-render-view-toggle .md-view-opt {
+ color: var(--fg);
+ border-color: var(--border) !important;
+ }
+ #doc-render-view-toggle .md-view-opt.active {
+ opacity: 1;
+ color: var(--fg);
+ }
+
+ /* Code/Run uses the same tab shape and baseline as Write/Preview. */
+ .doc-md-toolbar #doc-render-view-toggle {
+ align-self: flex-end;
+ height: 28px;
+ margin-bottom: -6px;
+ }
+ .doc-md-toolbar #doc-render-view-toggle .md-view-opt:first-child {
+ background: var(--sidebar-bg, var(--panel)) !important;
+ }
+ .doc-md-toolbar #doc-render-view-toggle .md-view-opt:last-child {
+ background: var(--bg) !important;
+ }
+
+ /* Mobile: the doc/email footer controls (format toggle, export button, export
+ menu) were slimmer than the Send button, so the row looked ragged. Bump them
+ to match the Send button height (and give the export/overflow menu bigger,
+ touch-friendly rows). */
+ @media (max-width: 768px) {
+ .md-view-toggle { height: 28px; }
+ .md-view-toggle .md-view-opt { min-width: 38px; padding: 0 8px !important; }
+ .doc-action-icon-btn { padding: 6px; }
+ .email-send-btn { height: 28px; }
+ /* The type/language picker was the slim one stuck at 22px — match it to the
+ rest of the row. */
+ .doc-language-select { height: 28px; font-size: 13px; padding: 2px 22px 2px 10px; }
+ .doc-overflow-item { font-size: 13px; padding: 9px 14px; }
+ .doc-overflow-item .overflow-icon svg,
+ .doc-overflow-item svg { width: 16px; height: 16px; }
+ .email-more-menu .dropdown-item-compact { padding: 9px 12px; font-size: 13px; }
+
+ /* The doc footer is tight once the run/preview toggle joins it, so on mobile
+ go icon-only for Close, Undo & Copy (their icons are clear).
+ font-size:0 drops the text node next to the SVG (the SVG has fixed w/h, so
+ it's unaffected). Slightly narrower type picker buys a little more room. */
+ #doc-actions-footer #doc-undo-btn span,
+ #doc-actions-footer #doc-footer-close-btn span,
+ #doc-email-actions #doc-email-discard-btn span { display: none; }
+ #doc-actions-footer #doc-undo-btn,
+ #doc-actions-footer #doc-redo-btn,
+ #doc-actions-footer #doc-footer-close-btn,
+ #doc-email-actions #doc-email-discard-btn { gap: 0; padding: 0 9px; }
+ #doc-actions-footer #doc-footer-copy-btn { gap: 0; padding: 0 13px; font-size: 0 !important; }
+ /* In reply mode the button carries a "Reply" label that should stay visible
+ (the icon-only treatment above is only for the plain Copy action). */
+ #doc-actions-footer #doc-footer-copy-btn[data-mode="reply"] { gap: 5px; padding: 0 13px; font-size: 12px; }
+ #doc-actions-footer #doc-language-select { width: 80px; }
+ #doc-actions-footer .doc-stats-btn { width: 28px; padding: 0 4px; }
+ #doc-actions-footer .doc-stats-unit { display: none; }
+ #doc-actions-footer .doc-stats-popover { right: -34px; }
+ #doc-actions-footer .doc-save-button-label { display: none; }
+ }
+
+ /* Very narrow document panes: keep the primary Save action visible while
+ collapsing secondary labels before allowing the footer to clip. This uses
+ the pane width, not the viewport width, because the editor can be docked. */
+ @container docpane (max-width: 420px) {
+ #doc-actions-footer {
+ gap: 4px;
+ padding-left: 8px;
+ padding-right: 8px;
+ overflow: hidden;
+ }
+ #doc-actions-footer > #doc-undo-btn,
+ #doc-actions-footer > #doc-redo-btn {
+ flex: 0 0 28px;
+ padding-left: 4px;
+ padding-right: 4px;
+ }
+ #doc-actions-footer > #doc-undo-btn span,
+ #doc-actions-footer > #doc-footer-copy-btn,
+ #doc-actions-footer .doc-save-button-label,
+ #doc-actions-footer > #doc-stats .doc-stats-unit {
+ font-size: 0;
+ }
+ #doc-actions-footer > #doc-undo-btn span,
+ #doc-actions-footer .doc-save-button-label,
+ #doc-actions-footer > #doc-stats .doc-stats-unit {
+ display: none;
+ }
+ #doc-actions-footer > #doc-stats {
+ flex: 0 0 28px;
+ }
+ #doc-actions-footer #doc-copy-export-split {
+ flex: 0 0 auto;
+ }
+ #doc-actions-footer #doc-footer-copy-btn {
+ flex: 0 0 36px;
+ width: 36px;
+ min-width: 36px;
+ padding-left: 0;
+ padding-right: 0;
+ font-size: 0 !important;
+ align-items: center;
+ justify-content: center;
+ }
+ #doc-actions-footer #doc-footer-export-btn {
+ flex: 0 0 24px;
+ width: 24px;
+ min-width: 24px;
+ padding-left: 4px;
+ padding-right: 4px;
+ }
+ #doc-actions-footer #doc-copy-export-split {
+ border: 1px solid color-mix(in srgb, var(--accent-primary, var(--red)) 50%, transparent);
+ border-radius: 6px;
+ overflow: hidden;
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 20%, transparent);
+ }
+ #doc-actions-footer #doc-copy-export-split .email-send-btn {
+ border-top: 0;
+ border-bottom: 0;
+ }
+ #doc-actions-footer #doc-copy-export-split #doc-footer-copy-btn {
+ border-left: 0;
+ }
+ #doc-actions-footer #doc-copy-export-split #doc-footer-export-btn {
+ border-right: 0;
+ }
+ #doc-actions-footer #doc-footer-export-btn svg {
+ width: 10px;
+ height: 10px;
+ }
+ }
+
+ /* Markdown formatting toolbar */
+ .doc-md-toolbar [data-md="unlink"] { display: none !important; }
+ /* In code-mode the toolbar only hosts the view toggles + utility buttons
+ (font-size, diff). Hide markdown-only formatting controls — bold,
+ italic, headings, list, link, attach, code-dropdown, emoji, hr, and
+ the PDF-only buttons. The view toggles + fontsize + diff stay. */
+ .doc-md-toolbar[data-mode="code"] [data-md],
+ .doc-md-toolbar[data-mode="code"] .md-dd-toggle,
+ .doc-md-toolbar[data-mode="code"] #md-toolbar-attach-btn,
+ .doc-md-toolbar[data-mode="code"] #md-toolbar-emoji-slot,
+ .doc-md-toolbar[data-mode="code"] .md-toolbar-pdf-only,
+ .doc-md-toolbar[data-mode="code"] .md-toolbar-sep {
+ display: none !important;
+ }
+ .doc-md-toolbar {
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+ gap: 1px;
+ padding: 2px 8px;
+ border-bottom: 1px solid var(--border);
+ background: var(--sidebar-bg, var(--panel));
+ flex-shrink: 0;
+ overflow: hidden;
+ height: 36px;
+ position: relative;
+ /* Same edge fade as the tab strip — toolbar buttons dissolve into the bar's
+ background at the edges instead of being hard-cut when they overflow. */
+ -webkit-mask-image: linear-gradient(to right, transparent 0, #000 18px, #000 calc(100% - 18px), transparent 100%);
+ mask-image: linear-gradient(to right, transparent 0, #000 18px, #000 calc(100% - 18px), transparent 100%);
+ }
+ .doc-md-toolbar button {
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.85;
+ padding: 4px 7px;
+ font-family: inherit;
+ font-size: 11px;
+ cursor: pointer;
+ white-space: nowrap;
+ line-height: 1.3;
+ transition: opacity 0.1s;
+ min-height: 28px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .doc-md-toolbar button:hover {
+ opacity: 1;
+ }
+ .doc-md-toolbar button:disabled {
+ opacity: 0.28;
+ cursor: default;
+ pointer-events: none;
+ }
+ .doc-link-remove-btn {
+ color: var(--red, #dc2626);
+ border-color: color-mix(in srgb, var(--red, #dc2626) 45%, var(--border));
+ }
+ .doc-md-toolbar button:active {
+ opacity: 0.6;
+ }
+ /* Active formatting state — set by the email WYSIWYG sync. Mirrors the
+ selection's current marks (B/I/S, heading level, list) so the toolbar
+ acts as an indicator, not just a launcher. */
+ .doc-md-toolbar button.is-active {
+ opacity: 1;
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ }
+ .doc-md-toolbar button.is-active:hover {
+ background: color-mix(in srgb, var(--accent, var(--red)) 22%, transparent);
+ }
+ .doc-md-toolbar button:focus:not(:focus-visible),
+ .doc-tab-new:focus:not(:focus-visible),
+ .doc-tab-arrow:focus:not(:focus-visible) {
+ outline: none;
+ background: none;
+ }
+ .doc-md-toolbar button:focus-visible,
+ .doc-tab-new:focus-visible,
+ .doc-tab-arrow:focus-visible {
+ outline: 1px solid var(--accent-primary, var(--red));
+ outline-offset: -1px;
+ }
+ /* Grouped formatting dropdown toggles (heading / code / list) */
+ .md-dd-toggle { gap: 1px !important; }
+ /* Tint only dropdown chevrons accent; the main tool icon keeps toolbar color. */
+ .md-dd-toggle svg { opacity: 1; margin-left: 1px; flex-shrink: 0; transform: translateY(0); }
+ .md-dd-toggle > svg:last-child { color: var(--accent-primary, var(--red, #4a9eff)); }
+ .md-dd-ico {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 22px;
+ flex-shrink: 0;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 11px;
+ opacity: 0.7;
+ }
+ .md-toolbar-sep {
+ width: 1px;
+ height: 12px;
+ background: color-mix(in srgb, var(--border) 60%, transparent);
+ margin: 0 4px;
+ flex-shrink: 0;
+ }
+ .md-toolbar-items {
+ display: flex;
+ align-items: center;
+ gap: 1px;
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow-x: auto;
+ scrollbar-width: none;
+ scroll-behavior: auto;
+ -webkit-overflow-scrolling: touch;
+ touch-action: pan-x pan-y;
+ }
+ .md-toolbar-leading-controls {
+ display: flex;
+ align-items: center;
+ flex: 0 0 auto;
+ }
+ .md-toolbar-items::-webkit-scrollbar { display: none; }
+ /* On a PDF, the annotation tools (text / checkmark / signature) are the primary
+ actions — pull them to the far left of the toolbar. `order` is visual only
+ (they're display:none on non-PDF docs), so it has no effect elsewhere. */
+ .md-toolbar-items #doc-pdf-add-text-btn { order: -3; }
+ .md-toolbar-items #doc-pdf-add-check-btn { order: -2; }
+ .md-toolbar-items #doc-pdf-add-sign-btn { order: -1; }
+ @media (min-width: 769px) {
+ .md-toolbar-items #doc-pdf-add-text-btn {
+ margin-left: 14px;
+ }
+ }
+ /* Stack the signature icon over a tiny "sign" caption so the tool reads
+ clearly (the icon alone is ambiguous). The JS toggles inline display
+ none/'' for PDF mode, so this flex display only applies when shown. */
+ #doc-pdf-add-sign-btn {
+ flex-direction: column;
+ align-items: center;
+ gap: 0;
+ line-height: 1;
+ }
+ .doc-pdf-sign-label {
+ font-size: 6.5px;
+ letter-spacing: 0.3px;
+ margin-top: 0;
+ opacity: 1;
+ color: var(--accent, var(--red));
+ }
+ /* Edge scroll arrows — appear when the toolbar has more icons off-screen. */
+ .md-scroll-arrow {
+ position: static;
+ flex: 0 0 28px;
+ align-self: stretch;
+ width: 28px;
+ display: flex;
+ align-items: center;
+ border: none;
+ cursor: pointer;
+ color: var(--fg);
+ padding: 0 !important;
+ min-height: 0 !important;
+ opacity: 1 !important;
+ z-index: 6;
+ }
+ .md-scroll-arrow svg { position: relative; top: 2px; opacity: 0.75; transition: opacity 0.1s; }
+ .md-scroll-arrow:hover svg { opacity: 1; }
+ @media (min-width: 769px) {
+ /* On desktop the arrow rides 2px lower than the toolbar baseline. */
+ .md-scroll-arrow svg { top: 0; }
+ }
+ .md-scroll-left {
+ justify-content: flex-start;
+ padding-left: 3px;
+ /* Mostly-solid toolbar bg so the icons behind the arrow are hidden, fading
+ to transparent only at the inner edge. */
+ background: linear-gradient(to right, var(--bg) 0%, var(--bg) 80%, transparent 100%);
+ }
+ .md-scroll-right {
+ justify-content: flex-end;
+ padding-right: 3px;
+ background: linear-gradient(to left, var(--bg) 0%, var(--bg) 80%, transparent 100%);
+ }
+ .md-toolbar-overflow-wrapper {
+ position: relative;
+ flex-shrink: 0;
+ margin-left: auto;
+ }
+ .md-toolbar-overflow-toggle {
+ background: none;
+ border: 1px solid transparent;
+ color: var(--fg);
+ opacity: 0.4;
+ padding: 2px 4px;
+ border-radius: 4px;
+ cursor: pointer;
+ transition: opacity 0.1s;
+ }
+ .md-toolbar-overflow-toggle:hover {
+ opacity: 1;
+ }
+ .md-toolbar-overflow-menu {
+ display: none;
+ position: fixed;
+ z-index: 1000;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 4px;
+ min-width: 0;
+ width: max-content;
+ box-shadow: 0 8px 24px rgba(0,0,0,0.3);
+ backdrop-filter: blur(12px);
+ }
+ .md-toolbar-overflow-menu.open {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 2px;
+ max-width: 200px;
+ }
+ .md-toolbar-overflow-item {
+ background: none;
+ border: 1px solid transparent;
+ color: var(--fg);
+ opacity: 0.5;
+ padding: 4px 8px;
+ border-radius: 4px;
+ font-family: inherit;
+ font-size: 11px;
+ cursor: pointer;
+ white-space: nowrap;
+ line-height: 1.3;
+ transition: opacity 0.1s, background 0.1s;
+ }
+ .md-toolbar-overflow-item:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ border-color: var(--border);
+ }
+
+ /* Find bar */
+ .doc-find-bar {
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ gap: 4px;
+ padding: 4px 8px;
+ background: var(--panel, var(--bg));
+ border-bottom: 1px solid var(--border);
+ flex-shrink: 0;
+ }
+ .doc-find-row,
+ .doc-replace-row {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ width: 100%;
+ }
+ .doc-replace-row[hidden] { display: none; }
+ .doc-find-input {
+ flex: 1;
+ min-width: 0;
+ padding: 3px 6px;
+ font-size: 12px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--fg);
+ outline: none;
+ }
+ .doc-find-input:focus { border-color: var(--accent); }
+ .doc-find-count {
+ font-size: 11px;
+ opacity: 0.6;
+ white-space: nowrap;
+ min-width: 50px;
+ text-align: center;
+ }
+ .doc-find-nav, .doc-find-close {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: none;
+ border: none;
+ color: var(--fg);
+ cursor: pointer;
+ padding: 2px 5px;
+ font-size: 14px;
+ border-radius: 3px;
+ opacity: 0.7;
+ }
+ .doc-find-nav:hover, .doc-find-close:hover,
+ .doc-find-nav.is-active { opacity: 1; background: color-mix(in srgb, var(--fg) 10%, transparent); }
+ .doc-find-action {
+ min-height: 25px;
+ padding: 3px 8px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--fg);
+ font: inherit;
+ font-size: 11px;
+ cursor: pointer;
+ white-space: nowrap;
+ }
+ .doc-find-action:hover,
+ .doc-find-action:focus-visible {
+ border-color: var(--accent);
+ outline: none;
+ }
+
+ /* Live document outline. It is body-portaled so the toolbar's clipping and
+ edge mask cannot cut it off in the mobile full-screen editor. */
+ .doc-outline-menu {
+ position: fixed;
+ box-sizing: border-box;
+ max-height: min(420px, calc(100vh - 24px));
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ background: var(--panel, var(--bg));
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ box-shadow: 0 10px 28px rgba(0, 0, 0, 0.3);
+ color: var(--fg);
+ }
+ .doc-outline-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ min-height: 32px;
+ padding: 0 10px;
+ border-bottom: 1px solid var(--border);
+ font-size: 11px;
+ font-weight: 600;
+ }
+ .doc-outline-list {
+ overflow-y: auto;
+ padding: 4px;
+ overscroll-behavior: contain;
+ }
+ .doc-outline-item {
+ width: 100%;
+ min-height: 30px;
+ display: grid;
+ grid-template-columns: 24px minmax(0, 1fr);
+ align-items: center;
+ gap: 4px;
+ padding: 4px 8px 4px 7px;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ color: var(--fg);
+ font: inherit;
+ font-size: 11px;
+ text-align: left;
+ cursor: pointer;
+ }
+ .doc-outline-item:hover,
+ .doc-outline-item:focus-visible {
+ background: color-mix(in srgb, var(--accent, var(--red)) 12%, transparent);
+ outline: none;
+ }
+ .doc-outline-level {
+ opacity: 0.42;
+ font-size: 9px;
+ font-variant-numeric: tabular-nums;
+ }
+ .doc-outline-label {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .doc-outline-empty {
+ padding: 18px 12px;
+ text-align: center;
+ font-size: 11px;
+ opacity: 0.52;
+ }
+
+ @media (max-width: 768px) {
+ .doc-outline-menu { max-height: min(52vh, 420px); }
+ .doc-outline-item { min-height: 38px; font-size: 12px; }
+ }
+
+ /* Selection formatting stays close to the selected text. The controls are
+ symbols only and mirror the same commands as the full Rich Text toolbar. */
+ .doc-rich-selection-toolbar {
+ position: fixed;
+ display: flex;
+ align-items: center;
+ gap: 1px;
+ padding: 3px;
+ background: var(--panel, var(--bg));
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.32);
+ color: var(--fg);
+ user-select: none;
+ overflow: visible;
+ }
+ .doc-rich-selection-toolbar button {
+ width: 30px;
+ height: 28px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+ touch-action: manipulation;
+ }
+ .doc-rich-selection-toolbar button:nth-child(5) {
+ margin-left: 3px;
+ border-left: 1px solid var(--border);
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+ }
+ .doc-rich-selection-toolbar button:hover,
+ .doc-rich-selection-toolbar button:focus-visible,
+ .doc-rich-selection-toolbar button.is-active {
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ outline: none;
+ }
+ .doc-rich-selection-toolbar .doc-rich-selection-close {
+ position: absolute;
+ top: -9px;
+ right: -9px;
+ z-index: 2;
+ width: 18px;
+ height: 18px;
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ background: var(--panel, var(--bg));
+ color: var(--fg);
+ font: 700 15px/1 system-ui, sans-serif;
+ box-shadow: 0 2px 7px rgba(0, 0, 0, 0.35);
+ }
+ .doc-rich-selection-toolbar .doc-rich-selection-close:hover,
+ .doc-rich-selection-toolbar .doc-rich-selection-close:focus-visible {
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 16%, var(--panel, var(--bg)));
+ outline: none;
+ }
+
+ @media (max-width: 768px) {
+ .doc-rich-selection-toolbar { padding: 4px; }
+ .doc-rich-selection-toolbar button { width: 38px; height: 34px; font-size: 13px; }
+ .doc-rich-selection-toolbar .doc-rich-selection-close { width: 20px; height: 20px; top: -10px; right: -10px; }
+ }
+
+ .doc-rich-slash-menu {
+ position: fixed;
+ box-sizing: border-box;
+ display: flex;
+ flex-direction: column;
+ max-height: min(420px, calc(100vh - 24px));
+ overflow: hidden;
+ background: var(--panel, var(--bg));
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ box-shadow: 0 10px 28px rgba(0, 0, 0, 0.32);
+ color: var(--fg);
+ }
+ .doc-rich-slash-header {
+ min-height: 32px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 0 10px;
+ border-bottom: 1px solid var(--border);
+ font-size: 11px;
+ font-weight: 600;
+ }
+ .doc-rich-slash-list {
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ padding: 4px;
+ }
+ .doc-rich-slash-item {
+ width: 100%;
+ min-height: 34px;
+ display: grid;
+ grid-template-columns: 30px minmax(0, 1fr);
+ align-items: center;
+ gap: 5px;
+ padding: 3px 8px;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ color: var(--fg);
+ font: inherit;
+ font-size: 11px;
+ text-align: left;
+ cursor: pointer;
+ }
+ .doc-rich-slash-item:hover,
+ .doc-rich-slash-item:focus-visible,
+ .doc-rich-slash-item.is-active {
+ background: color-mix(in srgb, var(--accent, var(--red)) 13%, transparent);
+ outline: none;
+ }
+ .doc-rich-slash-icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 26px;
+ height: 24px;
+ color: var(--accent, var(--red));
+ font-size: 10px;
+ font-weight: 600;
+ opacity: 0.82;
+ }
+ .doc-rich-slash-empty {
+ padding: 18px 12px;
+ text-align: center;
+ font-size: 11px;
+ opacity: 0.52;
+ }
+
+ @media (max-width: 768px) {
+ .doc-rich-slash-menu { max-height: min(54vh, 420px); }
+ .doc-rich-slash-item { min-height: 42px; font-size: 12px; }
+ }
+
+ /* Editor — highlighted overlay + transparent textarea.
+ Lock the editor wrap to a fixed text-column width, centered horizontally
+ in the doc pane. This eliminates wrap-related drift bugs as a class:
+ the textarea + overlay always have the same available width regardless
+ of viewport, sidebar state, dock state, or window resize. Whitespace on
+ either side reads like a writing-app column (Bear / iA Writer pattern).
+ container-type: inline-size lets us hide the line-number gutter via a
+ container query when the editor's own width is narrow (rather than
+ viewport-width, which would miss the case of a narrow side-docked
+ editor inside a wide window). */
+ .doc-editor-wrap {
+ position: relative;
+ flex: 1;
+ min-height: 0;
+ /* Cap the column at ~820px outer (~760px content area after the 60px
+ of horizontal padding the textarea+overlay use for the gutter). */
+ max-width: 820px;
+ width: 100%;
+ margin-left: auto;
+ margin-right: auto;
+ overflow: hidden;
+ background: var(--bg);
+ container-type: inline-size;
+ container-name: doceditor;
+ }
+
+ /* When the editor itself is narrow, soft-wrap makes one logical line
+ span multiple visual rows but the gutter still shows ONE number per
+ logical line — so the gutter and the visible rows fall out of sync.
+ Hide the gutter (and reclaim the 48px of left padding it reserved)
+ below a threshold where the mismatch reads as a glitch. */
+ @container doceditor (max-width: 360px) {
+ .doc-line-numbers { display: none !important; }
+ .doc-editor-textarea,
+ .doc-editor-highlight {
+ padding-left: 12px !important;
+ }
+ }
+ .doc-line-numbers {
+ position: absolute;
+ top: 0; left: 0; bottom: 0;
+ width: 36px;
+ padding: 10px 8px 10px 0;
+ margin: 0;
+ font-family: inherit;
+ font-size: 11px;
+ line-height: 1.45;
+ text-align: right;
+ color: var(--fg);
+ opacity: 0.18;
+ background: var(--bg);
+ overflow: hidden;
+ white-space: pre;
+ tab-size: 4;
+ font-variant-ligatures: none !important;
+ font-feature-settings: "kern" 0, "liga" 0, "calt" 0, "dlig" 0 !important;
+ font-kerning: none !important;
+ text-rendering: geometricPrecision !important;
+ z-index: 2;
+ pointer-events: none;
+ user-select: none;
+ }
+ .doc-line-number-content {
+ display: block;
+ will-change: transform;
+ }
+ .doc-line-number-row {
+ position: relative;
+ box-sizing: border-box;
+ }
+ .doc-line-number-label {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 36px;
+ text-align: right;
+ }
+ .doc-line-number-measure {
+ position: absolute !important;
+ visibility: hidden !important;
+ pointer-events: none !important;
+ left: -9999px !important;
+ top: 0 !important;
+ height: 0 !important;
+ min-height: 0 !important;
+ max-height: none !important;
+ overflow: hidden !important;
+ padding: 0 !important;
+ border: 0 !important;
+ resize: none !important;
+ box-sizing: content-box !important;
+ color: transparent !important;
+ background: transparent !important;
+ }
+ mark.doc-find-mark.current {
+ background: var(--accent) !important;
+ color: var(--bg) !important;
+ box-shadow: 0 0 0 2px var(--fg);
+ outline: 1px solid var(--fg);
+ }
+
+ /* Find-match overlay rects — drawn on top of the textarea, work in
+ every doc mode (markdown, email, plain) regardless of whether the
+ syntax-highlight overlay is shown. Translucent band so the underlying
+ text stays readable; current match gets a brighter solid band. */
+ .doc-find-rect {
+ background: color-mix(in srgb, var(--accent) 25%, transparent);
+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 65%, transparent);
+ }
+ .doc-find-rect.current {
+ background: color-mix(in srgb, var(--accent) 55%, transparent);
+ box-shadow: inset 0 0 0 2px var(--accent);
+ }
+
+ .doc-editor-highlight {
+ position: absolute;
+ top: 0; left: 0; right: 0; bottom: 0;
+ margin: 0;
+ padding: 10px 12px 10px 48px;
+ font-family: inherit;
+ font-size: 11px !important;
+ line-height: 1.45 !important;
+ tab-size: 4;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ overflow: hidden;
+ /* `scrollbar-gutter: stable` reserves scrollbar-track width in the
+ layout even when no scrollbar is shown. The textarea below has the
+ same setting — without this, the textarea would consume scrollbar
+ space the moment its content overflows vertically, shrinking its
+ content width and wrapping lines earlier than the overlay. The
+ visible-text-drift bug user reports as "after ~16 rows it wraps
+ even though there's space" was caused by exactly that. */
+ scrollbar-gutter: stable;
+ scrollbar-width: none;
+ pointer-events: none;
+ z-index: 0;
+ background: var(--bg) !important;
+ color: var(--hl-fg, var(--fg));
+ border: none;
+ /* Disable ligatures + kerning everywhere in the editor. Monospace fonts
+ like Fira Code form ligatures for `=>`, `!=`, `->`, `==` etc., but
+ hljs splits those pairs into separate <span>s in the overlay, which
+ breaks the ligature on this side while the textarea still forms it.
+ Result: visible row drift whenever code contains those pairs. Pin
+ ligatures off in both layers (textarea below) so widths stay equal. */
+ font-variant-ligatures: none !important;
+ font-feature-settings: "kern" 0, "liga" 0, "calt" 0, "dlig" 0 !important;
+ font-kerning: none !important;
+ text-rendering: geometricPrecision !important;
+ box-sizing: border-box;
+ }
+
+ /* Document font size options */
+ .doc-font-m .doc-editor-textarea,
+ .doc-font-m .doc-editor-highlight,
+ .doc-font-m .doc-line-numbers { font-size: 13px !important; }
+ .doc-font-l .doc-editor-textarea,
+ .doc-font-l .doc-editor-highlight,
+ .doc-font-l .doc-line-numbers { font-size: 15px !important; }
+ .doc-email-richbody.doc-font-m { font-size: 15px !important; }
+ .doc-email-richbody.doc-font-l { font-size: 17px !important; }
+ /* Markdown base text should match chat text color, not code color */
+ .doc-editor-highlight .language-markdown {
+ color: var(--fg) !important;
+ }
+ .doc-editor-highlight code,
+ .doc-editor-highlight code.hljs,
+ .doc-editor-highlight .hljs {
+ font-family: inherit;
+ font-size: inherit !important;
+ line-height: inherit !important;
+ background: transparent !important;
+ padding: 0 !important;
+ margin: 0 !important;
+ border-radius: 0 !important;
+ overflow: hidden !important;
+ display: block;
+ pointer-events: none;
+ }
+ .doc-editor-textarea {
+ position: absolute;
+ top: 0; left: 0; right: 0; bottom: 0;
+ width: 100%;
+ height: 100% !important;
+ max-height: none !important;
+ min-height: 0 !important;
+ z-index: 1;
+ background: var(--bg) !important;
+ color: transparent !important;
+ color-scheme: dark;
+ caret-color: var(--fg);
+ border: none;
+ outline: none;
+ resize: none;
+ font-family: inherit;
+ /* Caret position only matches the underlying highlight if BOTH layers use
+ identical metrics — !important on font-size + line-height defends against
+ anything else in the cascade nudging the textarea but not the overlay. */
+ font-size: 11px !important;
+ line-height: 1.45 !important;
+ padding: 10px 12px 10px 48px;
+ overflow-y: scroll;
+ /* Pair with .doc-editor-highlight's scrollbar-gutter: stable so the
+ textarea's content width DOESN'T shrink the moment its scrollbar
+ appears (overflow-y: scroll keeps scrollbar permanent, gutter
+ reserves the space layout-wise). Without this, line wrap diverges
+ between textarea and overlay whenever content exceeds the visible
+ area — caret stays right, but typed text appears on a different row
+ than the caret. */
+ scrollbar-gutter: stable;
+ /* Show a real scrollbar for long documents. scrollbar-gutter above keeps
+ the text column stable so the gutter, textarea, and find overlay stay
+ metrically aligned while the scrollbar is present. */
+ scrollbar-width: thin;
+ scrollbar-color: color-mix(in srgb, var(--fg) 28%, transparent) transparent;
+ -webkit-overflow-scrolling: touch;
+ tab-size: 4;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ -moz-appearance: none;
+ appearance: none;
+ box-sizing: border-box;
+ /* Mirror the ligature/kerning lockdown from .doc-editor-highlight above.
+ Without this the textarea forms `=>`/`!=`/`->`/`==` as single-glyph
+ ligatures while the overlay can't (hljs splits the pair into
+ separate spans), so glyph widths diverge and the visible text drifts
+ down relative to the caret as code accumulates. */
+ font-variant-ligatures: none !important;
+ font-feature-settings: "kern" 0, "liga" 0, "calt" 0, "dlig" 0 !important;
+ font-kerning: none !important;
+ text-rendering: geometricPrecision !important;
+ }
+ .doc-editor-textarea::-webkit-scrollbar { width: 8px; }
+ .doc-editor-textarea::-webkit-scrollbar-track { background: transparent; }
+ .doc-editor-textarea::-webkit-scrollbar-thumb {
+ background: color-mix(in srgb, var(--fg) 24%, transparent);
+ border-radius: 999px;
+ }
+ .doc-editor-textarea::-webkit-scrollbar-thumb:hover {
+ background: color-mix(in srgb, var(--fg) 36%, transparent);
+ }
+ .doc-editor-textarea:hover,
+ .doc-editor-textarea:focus,
+ .doc-editor-textarea:active {
+ background: var(--bg) !important;
+ /* Used to force `color: transparent` here so the hidden two-layer
+ textarea wouldn't bleed through on hover/focus. Now that the
+ textarea renders its OWN visible text (overlay is hidden), forcing
+ transparent here makes typed text disappear the moment the cursor
+ enters the page. Keep the visible fg color instead. */
+ color: var(--fg) !important;
+ outline: none !important;
+ }
+ .doc-editor-textarea::placeholder {
+ color: var(--fg);
+ opacity: 0.25;
+ }
+ /* Show real text when selecting so copy/paste is visible */
+ .doc-editor-textarea::selection {
+ color: var(--fg);
+ background: color-mix(in srgb, var(--accent, var(--red)) 48%, transparent);
+ }
+
+ /* ---- Selection indicator badge ---- */
+ .doc-selection-badge {
+ font-size: 10px;
+ color: var(--red);
+ background: color-mix(in srgb, var(--red) 12%, transparent);
+ border: 1px solid color-mix(in srgb, var(--red) 30%, transparent);
+ border-radius: 4px;
+ padding: 1px 4px 1px 6px;
+ white-space: nowrap;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ height: 32px;
+ box-sizing: border-box;
+ }
+ .doc-selection-clear {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: none;
+ border: 1px solid transparent;
+ border-radius: 999px;
+ color: var(--fg);
+ opacity: 0.4;
+ cursor: pointer;
+ font-size: 16px;
+ line-height: 1;
+ width: 20px;
+ height: 20px;
+ padding: 0;
+ box-sizing: border-box;
+ transition: opacity 0.12s, color 0.12s, background 0.12s, border-color 0.12s;
+ }
+ .doc-selection-clear:hover {
+ opacity: 1;
+ color: var(--fg);
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ border-color: color-mix(in srgb, var(--fg) 12%, transparent);
+ }
+ .doc-selection-chip-clear {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 18px;
+ height: 18px;
+ margin-left: 3px;
+ padding: 0;
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ background: var(--panel, var(--bg));
+ color: var(--fg);
+ font: 700 15px/1 system-ui, sans-serif;
+ box-shadow: 0 2px 7px rgba(0, 0, 0, 0.35);
+ cursor: pointer;
+ }
+ .doc-selection-chip-clear:hover,
+ .doc-selection-chip-clear:focus-visible {
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 16%, var(--panel, var(--bg)));
+ outline: none;
+ }
+ .doc-selection-clear {
+ width: auto;
+ height: 18px;
+ margin-left: 3px;
+ padding: 0 7px;
+ border-radius: 999px;
+ font: 700 11px/1 system-ui, sans-serif;
+ opacity: 1;
+ }
+ .doc-edit-tag {
+ display: inline-flex;
+ align-items: center;
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 32%, transparent);
+ color: var(--accent, var(--red));
+ cursor: pointer;
+ font-family: inherit;
+ font-size: 0.68em;
+ line-height: 1;
+ opacity: 0.78;
+ background: color-mix(in srgb, var(--accent, var(--red)) 10%, transparent);
+ border-radius: 999px;
+ padding: 1px 5px;
+ margin-right: 2px;
+ white-space: nowrap;
+ transition: opacity 0.12s, background 0.12s, border-color 0.12s;
+ }
+ .doc-edit-tag:hover,
+ .doc-edit-tag:focus-visible {
+ opacity: 1;
+ background: color-mix(in srgb, var(--accent, var(--red)) 18%, transparent);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 55%, transparent);
+ }
+ .doc-edit-tag:focus-visible {
+ outline: 2px solid color-mix(in srgb, var(--accent, var(--red)) 45%, transparent);
+ outline-offset: 2px;
+ }
+ /* Attachment cards in user messages */
+ .attach-cards {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-top: 8px;
+ }
+ .attach-card {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 10px;
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ /* Same border as the chat bubbles. */
+ border: 1px solid var(--bubble-border, var(--border));
+ font-size: 12px;
+ transition: background 0.15s;
+ }
+ .attach-card[style*="cursor: pointer"]:hover,
+ .attach-card[data-file-id]:hover {
+ background: color-mix(in srgb, var(--fg) 12%, transparent);
+ }
+ .attach-card-icon {
+ flex-shrink: 0;
+ opacity: 0.6;
+ }
+ .attach-card-name {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ max-width: 200px;
+ }
+ .attach-card-size {
+ opacity: 0.45;
+ font-size: 11px;
+ white-space: nowrap;
+ }
+ .history-attach-card {
+ cursor: default;
+ opacity: 0.82;
+ }
+ .history-attach-card .attach-card-size {
+ text-transform: lowercase;
+ }
+ /* Import prompt banner (above chatbar) */
+ .import-prompt-banner {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 12px;
+ margin: 0 auto 6px;
+ max-width: 800px;
+ background: var(--panel);
+ border: 1px solid color-mix(in srgb, var(--accent) 30%, transparent);
+ border-left: 3px solid var(--accent);
+ border-radius: 6px;
+ font-size: 12px;
+ color: var(--fg);
+ box-shadow: 0 4px 12px rgba(0,0,0,0.2);
+ backdrop-filter: blur(12px);
+ animation: modal-enter 0.15s ease-out;
+ }
+ .import-prompt-banner span { flex: 1; }
+ .import-prompt-banner button {
+ padding: 3px 12px;
+ border: 1px solid var(--border);
+ border-radius: 5px;
+ background: none;
+ color: var(--fg);
+ cursor: pointer;
+ font-size: 12px;
+ white-space: nowrap;
+ }
+ .import-prompt-banner button:hover {
+ border-color: var(--fg);
+ }
+ .import-prompt-dismiss {
+ border: none !important;
+ background: none !important;
+ opacity: 0.5;
+ font-size: 16px !important;
+ padding: 0 4px !important;
+ }
+ .import-prompt-dismiss:hover { opacity: 1; background: none !important; }
+ .doc-selection-overlay {
+ position: absolute;
+ background: color-mix(in srgb, var(--red) 10%, transparent);
+ border-left: 2px solid color-mix(in srgb, var(--red) 50%, transparent);
+ pointer-events: none;
+ z-index: 2;
+ transition: top 0.05s;
+ }
+ .doc-selection-overlay-clear {
+ position: absolute;
+ top: 1px;
+ right: 3px;
+ width: 18px;
+ height: 18px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0;
+ border: 0;
+ border-radius: 50%;
+ background: color-mix(in srgb, var(--panel) 82%, transparent);
+ color: var(--fg);
+ font: 16px/1 inherit;
+ opacity: 0.7;
+ cursor: pointer;
+ pointer-events: auto;
+ }
+ .doc-selection-overlay-clear:hover,
+ .doc-selection-overlay-clear:focus-visible {
+ opacity: 1;
+ background: color-mix(in srgb, var(--accent, var(--red)) 18%, var(--panel));
+ outline: none;
+ }
+ .doc-selection-rich-clear {
+ position: fixed;
+ z-index: 10040;
+ width: 18px;
+ height: 18px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0;
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ background: var(--panel, var(--bg));
+ color: var(--fg);
+ font: 700 15px/1 system-ui, sans-serif;
+ opacity: 1;
+ cursor: pointer;
+ box-shadow: 0 2px 7px rgba(0, 0, 0, 0.35);
+ }
+ .doc-selection-rich-clear:hover,
+ .doc-selection-rich-clear:focus-visible {
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 16%, var(--panel, var(--bg)));
+ outline: none;
+ }
+
+ /* ── Suggestion comments (Google Docs style) ── */
+ .doc-suggestion-highlight {
+ position: absolute;
+ box-sizing: border-box;
+ background: color-mix(in srgb, var(--accent) 32%, transparent);
+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 72%, transparent);
+ border-radius: 2px;
+ pointer-events: none;
+ z-index: 3;
+ transition: top 0.1s, opacity 0.15s;
+ }
+ /* Suggestion card — fixed next to editor, anchored to the change */
+ .doc-suggestion-card {
+ position: fixed;
+ width: 250px;
+ background: var(--panel);
+ border: 1px solid var(--accent);
+ border-radius: 10px;
+ padding: 12px 12px 10px;
+ font-size: 12px;
+ box-shadow: 0 4px 20px rgba(0,0,0,0.25);
+ animation: suggestion-enter 0.25s ease-out;
+ z-index: 250;
+ overflow: visible;
+ }
+ .doc-suggestion-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 6px;
+ }
+ .doc-suggestion-nav {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ }
+ .doc-suggestion-nav-btn {
+ background: none;
+ border: none;
+ color: var(--fg);
+ cursor: pointer;
+ font-size: 16px;
+ line-height: 1;
+ padding: 2px 4px;
+ opacity: 0.35;
+ transition: opacity 0.1s;
+ }
+ .doc-suggestion-nav-btn:hover { opacity: 1; }
+ .doc-suggestion-close {
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ margin: -2px -2px -2px 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ border: 1px solid transparent;
+ border-radius: 999px;
+ color: color-mix(in srgb, var(--fg) 58%, transparent);
+ opacity: 1;
+ cursor: pointer;
+ font-size: 0;
+ line-height: 1;
+ flex-shrink: 0;
+ position: relative;
+ }
+ .doc-suggestion-close:hover,
+ .doc-suggestion-close:focus-visible {
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ border-color: color-mix(in srgb, var(--fg) 12%, transparent);
+ color: var(--fg);
+ outline: none;
+ }
+ .doc-suggestion-counter {
+ font-size: 10px;
+ opacity: 0.4;
+ font-weight: 600;
+ letter-spacing: 0.5px;
+ }
+ /* Inline diff markers — injected into the code highlight element */
+ .sugg-inline-del {
+ background: color-mix(in srgb, var(--red) 20%, transparent);
+ color: color-mix(in srgb, var(--red) 70%, var(--fg));
+ text-decoration: line-through;
+ text-decoration-thickness: 1px;
+ text-decoration-color: color-mix(in srgb, var(--red) 40%, transparent);
+ border-radius: 2px;
+ padding: 0 2px;
+ }
+ .sugg-inline-add {
+ background: color-mix(in srgb, var(--green) 25%, transparent);
+ color: var(--green);
+ border-radius: 2px;
+ padding: 0 2px;
+ }
+ /* ---- Diff mode ---- */
+ .diff-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 5px 12px;
+ background: color-mix(in srgb, var(--fg) 4%, var(--bg));
+ border-bottom: 1px solid var(--border);
+ font-size: 11px;
+ flex-shrink: 0;
+ }
+ .diff-toolbar-status {
+ opacity: 0.5;
+ font-size: 10px;
+ margin-right: auto;
+ }
+ .diff-toolbar-btn {
+ background: none;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ font-size: 10px;
+ padding: 3px 10px;
+ border-radius: 4px;
+ cursor: pointer;
+ font-family: inherit;
+ transition: border-color 0.15s, background 0.15s;
+ }
+ .diff-toolbar-btn:hover {
+ border-color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 8%, transparent);
+ }
+ .diff-toolbar-btn-accept { color: #58a6ff; border-color: color-mix(in srgb, #58a6ff 36%, transparent); }
+ .diff-toolbar-btn-accept:hover { border-color: #58a6ff; background: color-mix(in srgb, #58a6ff 12%, transparent); }
+ .diff-toolbar-btn-reject { color: #f2cc60; border-color: color-mix(in srgb, #f2cc60 36%, transparent); }
+ .diff-toolbar-btn-reject:hover { border-color: #f2cc60; background: color-mix(in srgb, #f2cc60 12%, transparent); }
+ .diff-line-del {
+ display: block;
+ background: color-mix(in srgb, #f2cc60 24%, transparent);
+ border-left: 3px solid #f2cc60;
+ color: #f2cc60;
+ padding-left: 4px;
+ margin-left: -7px;
+ text-decoration: line-through;
+ }
+ .diff-line-add {
+ display: block;
+ background: color-mix(in srgb, #58a6ff 24%, transparent);
+ border-left: 3px solid #58a6ff;
+ color: #58a6ff;
+ padding-left: 4px;
+ margin-left: -7px;
+ }
+ /* Inline diff summary (version history cards) */
+ .diff-del {
+ color: #f2cc60;
+ background: color-mix(in srgb, #f2cc60 16%, transparent);
+ text-decoration: line-through;
+ border-radius: 2px;
+ padding: 0 2px;
+ }
+ .diff-add {
+ color: #58a6ff;
+ background: color-mix(in srgb, #58a6ff 16%, transparent);
+ font-weight: 600;
+ border-radius: 2px;
+ padding: 0 2px;
+ }
+ .diff-line-equal {
+ display: block;
+ }
+ .diff-chunk-resolved {
+ opacity: 0.3;
+ transition: opacity 0.3s;
+ }
+ .diff-chunk-actions {
+ position: absolute;
+ right: 8px;
+ top: 0;
+ display: flex;
+ gap: 4px;
+ z-index: 5;
+ pointer-events: auto;
+ }
+ /* Diff mode: textarea sits on top of the highlight where chunk buttons live.
+ Disable its pointer events so clicks reach the buttons in the layer below. */
+ .doc-editor-wrap.diff-mode .doc-editor-textarea {
+ pointer-events: none;
+ color: transparent !important;
+ caret-color: transparent !important;
+ }
+ .doc-editor-wrap.diff-mode .doc-editor-highlight {
+ display: block !important;
+ pointer-events: auto;
+ z-index: 3;
+ color: var(--fg) !important;
+ background: var(--sidebar-bg, var(--panel)) !important;
+ overflow: hidden;
+ }
+ .doc-editor-wrap.diff-mode .doc-editor-highlight * {
+ color: inherit;
+ }
+ .doc-editor-wrap.diff-mode .diff-line-del {
+ color: #f2cc60 !important;
+ }
+ .doc-editor-wrap.diff-mode .diff-line-add {
+ color: #58a6ff !important;
+ }
+ .diff-chunk-btn {
+ width: 20px;
+ height: 20px;
+ border-radius: 4px;
+ border: 1px solid var(--border);
+ background: var(--bg);
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 12px;
+ line-height: 1;
+ transition: border-color 0.15s, background 0.15s;
+ opacity: 0.6;
+ }
+ .diff-chunk-btn:hover { opacity: 1; }
+ .diff-chunk-btn-accept { color: #58a6ff; }
+ .diff-chunk-btn-accept:hover { border-color: #58a6ff; background: color-mix(in srgb, #58a6ff 15%, transparent); }
+ .diff-chunk-btn-reject { color: #f2cc60; }
+ .diff-chunk-btn-reject:hover { border-color: #f2cc60; background: color-mix(in srgb, #f2cc60 15%, transparent); }
+
+ .doc-suggestion-accept-all {
- flex: 1;
++ flex: 1.3;
++ min-width: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ padding: 5px 8px;
+ border: none;
+ border-radius: 5px;
+ cursor: pointer;
- font-size: 10px;
++ font-size: 11px;
+ font-family: inherit;
- background: transparent;
++ white-space: nowrap;
++ background: var(--accent);
+ border: 1px solid var(--accent);
- color: var(--accent);
++ color: var(--bg);
+ transition: background 0.1s;
+ }
+ .doc-suggestion-accept-all:hover {
- background: color-mix(in srgb, var(--accent) 15%, transparent);
++ background: color-mix(in srgb, var(--accent) 85%, var(--bg));
+ }
+ .doc-suggestion-reason {
+ opacity: 0.6;
+ margin-bottom: 6px;
+ font-size: 11px;
+ line-height: 1.4;
+ }
+ .doc-suggestion-diff {
+ background: var(--bg);
+ border-radius: 4px;
+ padding: 6px 8px;
+ font-family: var(--code-font, monospace);
+ font-size: 11px;
+ margin-bottom: 8px;
+ max-height: 100px;
+ overflow-y: auto;
+ word-break: break-word;
+ }
+ .doc-suggestion-del {
+ color: var(--red);
+ text-decoration: line-through;
+ opacity: 0.7;
+ }
+ .doc-suggestion-add {
+ color: var(--green);
+ }
+ .doc-suggestion-actions {
+ display: flex;
+ gap: 6px;
+ }
+ .doc-suggestion-accept,
+ .doc-suggestion-dismiss {
+ flex: 1;
+ padding: 5px 8px;
+ border: none;
+ border-radius: 5px;
+ cursor: pointer;
+ font-size: 11px;
+ font-family: inherit;
+ font-weight: 500;
+ transition: background 0.1s;
+ }
+ .doc-suggestion-accept {
+ background: var(--accent, var(--red));
+ color: #fff;
+ }
+ .doc-suggestion-dismiss {
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ }
+ .doc-suggestion-dismiss:hover {
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
+ @keyframes suggestion-enter {
+ from { opacity: 0; transform: translateX(10px); }
+ to { opacity: 1; transform: translateX(0); }
+ }
+ /* Mobile: suggestion card overlays top of editor (no room on side) */
+ @media (max-width: 768px) {
+ .doc-suggestion-card {
- right: 8px;
++ box-sizing: border-box;
++ left: 8px;
+ right: 8px;
+ width: auto;
- top: 8px !important;
++ overflow-y: auto;
+ }
+ .doc-suggestion-card::before { display: none; }
+ }
+
+ /* ---- Streaming animation ---- */
+ .doc-editor-textarea[readonly] {
+ caret-color: var(--red);
+ }
+
+ /* Diff overlay */
+ .doc-diff-overlay {
+ position: absolute;
+ inset: 0;
+ background: var(--bg);
+ z-index: 5;
+ overflow-y: auto;
+ padding: 8px 12px;
+ font-family: 'Fira Code', monospace;
+ font-size: 0.85rem;
+ line-height: 1.5;
+ opacity: 0;
+ transition: opacity 0.3s ease;
+ border-radius: 6px;
+ }
+ .doc-diff-overlay.visible { opacity: 1; }
+ .doc-diff-overlay.fading { opacity: 0; transition: opacity 0.4s ease; }
+ .doc-diff-stats {
+ display: flex;
+ gap: 10px;
+ padding: 4px 0 8px;
+ font-size: 0.8rem;
+ font-weight: 600;
+ }
+ .diff-stat-del { color: var(--warn); }
+ .diff-stat-add { color: var(--green); }
+ .doc-diff-line {
+ padding: 1px 8px;
+ border-radius: 4px;
+ white-space: pre-wrap;
+ word-break: break-all;
+ }
+ .doc-diff-line.same {
+ opacity: 0.4;
+ }
+ .doc-diff-line.del {
+ background: color-mix(in srgb, var(--warn) 15%, transparent);
+ color: var(--warn);
+ text-decoration: line-through;
+ text-decoration-color: color-mix(in srgb, var(--warn) 40%, transparent);
+ }
+ .doc-diff-line.add {
+ background: color-mix(in srgb, var(--green) 12%, transparent);
+ color: var(--green);
+ }
+ .doc-diff-sep {
+ text-align: center;
+ padding: 2px 0;
+ font-size: 0.7rem;
+ opacity: 0.3;
+ color: var(--fg);
+ }
+
+ /* Version history panel (slide-out) */
+ .doc-version-panel {
+ position: fixed;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ width: 300px;
+ background: var(--bg);
+ border-right: 1px solid var(--border);
+ display: flex;
+ flex-direction: column;
+ z-index: 200;
+ box-shadow: 4px 0 16px rgba(0,0,0,0.35);
+ animation: version-slide-in 0.2s ease-out;
+ /* Match the app modal aesthetic so nothing inherits the large body font. */
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+ font-size: 12px;
+ letter-spacing: -0.01em;
+ }
+ @keyframes version-slide-in {
+ from { opacity: 0; transform: translateX(-30px); }
+ to { opacity: 1; transform: translateX(0); }
+ }
+ .doc-version-panel.hidden {
+ display: none;
+ }
+ @media (max-width: 768px) {
+ .doc-version-panel {
+ left: 0;
+ right: 0;
+ top: auto;
+ bottom: 0;
+ width: 100%;
+ height: 50vh;
+ border-right: none;
+ border-left: none;
+ border-top: 1px solid var(--border);
+ border-radius: 14px 14px 0 0;
+ box-shadow: 0 -4px 16px rgba(0,0,0,0.3);
+ /* It's a bottom sheet on mobile — slide UP from the bottom, not in from
+ the left (the desktop animation looked like a black box janking in). */
+ animation: version-slide-up 0.2s ease-out;
+ }
+ }
+ @keyframes version-slide-up {
+ from { opacity: 0; transform: translateY(30px); }
+ to { opacity: 1; transform: translateY(0); }
+ }
+
+ .doc-version-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 10px 12px;
+ border-bottom: 1px solid var(--border);
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--fg);
+ }
+
+ .doc-version-list {
+ flex: 1;
+ overflow-y: auto;
+ padding: 8px;
+ }
+
+ .doc-version-item {
+ padding: 8px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ margin-bottom: 6px;
+ cursor: pointer;
+ transition: all 0.15s;
+ background: color-mix(in srgb, var(--fg) 3%, transparent);
+ }
+ .doc-version-item:hover {
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ border-color: var(--fg);
+ }
+
+ .doc-version-info {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 4px;
+ }
+
+ .doc-version-num {
+ font-weight: 600;
+ font-size: 12px;
+ color: var(--fg);
+ }
+ .doc-version-source {
+ font-size: 10px;
+ color: var(--fg);
+ opacity: 0.5;
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ padding: 1px 6px;
+ border-radius: 4px;
+ }
+ .doc-version-time {
+ font-size: 10px;
+ color: var(--fg);
+ opacity: 0.4;
+ margin-left: auto;
+ }
+ .doc-version-summary {
+ font-size: 11px;
+ color: var(--fg);
+ opacity: 0.5;
+ margin-bottom: 4px;
+ }
+
+ .doc-version-restore {
+ background: none;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ font-size: 10px;
+ padding: 2px 8px;
+ border-radius: 4px;
+ cursor: pointer;
+ transition: all 0.15s;
+ }
+ .doc-version-restore:hover {
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ border-color: var(--fg);
+ }
+ /* "latest" badge */
+ .doc-version-latest {
+ font-size: 10px;
+ font-weight: 600;
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ padding: 1px 6px;
+ border-radius: 4px;
+ }
+ /* Diff preview lines — small and muted so they don't dominate the item. */
+ .doc-version-diff {
+ font-size: 10px;
+ line-height: 1.5;
+ opacity: 0.8;
+ margin-top: 2px;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ word-break: break-word;
+ }
+ .doc-version-diff .diff-del {
+ color: #f2cc60;
+ background: color-mix(in srgb, #f2cc60 16%, transparent);
+ opacity: 1;
+ }
+ .doc-version-diff .diff-add {
+ color: #58a6ff;
+ background: color-mix(in srgb, #58a6ff 16%, transparent);
+ }
+
+ /* Mobile: doc editor takes over full screen as toggle */
+ @media (max-width: 768px) {
+ body.doc-view .doc-editor-pane {
+ /* Force its own full-screen window on mobile. !important on these so an
+ inline width/position left over from desktop drag-resize, or the base
+ desktop split layout (flex: 1; max-width: 70vw; border-left), can never
+ render it as a narrow side pane ("sidebar") on a phone. */
+ position: fixed !important;
+ inset: 0 !important;
+ top: 0 !important; right: 0 !important; bottom: 0 !important; left: 0 !important;
+ max-width: 100% !important;
+ width: 100% !important;
+ flex: none !important;
+ z-index: 170;
+ /* Stroke the top edge so the rounded corners read as a curved sheet edge. */
+ border: 1px solid var(--border);
+ border-bottom: none;
+ /* Rounded top corners like the other mobile sheet windows. */
+ border-radius: 14px 14px 0 0;
+ /* Slide up from the bottom (sheet), not in from the side, on mobile. */
+ animation: sheet-enter 0.25s cubic-bezier(0.2, 0.8, 0.2, 1) both;
+ transform-origin: bottom center;
+ }
+ /* A document that was already open before refresh should be restored in
+ place, not replay the mobile sheet entrance and visibly jump upward. */
+ body.doc-view .doc-editor-pane.doc-pane-restoring {
+ animation: none;
+ transform: none;
+ }
+ body.doc-view .doc-divider {
+ display: none;
+ }
+ /* Hide chat behind doc panel on mobile */
+ body.doc-view .chat-container {
+ display: none;
+ }
+ /* Doc + email windows alternate: whichever was opened last is in front.
+ Default (a doc was opened last) → email windows sit BELOW the full-screen
+ doc pane (170) so the draft is on top. When the user re-opens an email
+ window (body.email-front, set by openEmailLibrary / reader open+restore) →
+ the email windows jump ABOVE the doc. Covers the email library AND any open
+ reader window (email-reader-<uid>); both are .modal at z-250 by default. */
+ body.doc-view #email-lib-modal,
+ body.doc-view .modal[id^="email-reader-"] { z-index: 150 !important; }
+ body.doc-view.email-front #email-lib-modal,
+ body.doc-view.email-front .modal[id^="email-reader-"] { z-index: 300 !important; }
+ body.doc-view:not(.email-front) .doc-editor-pane { z-index: 10010 !important; }
+ body.doc-view:not(.email-front) #email-lib-modal,
+ body.doc-view:not(.email-front) .modal[id^="email-reader-"] { z-index: 10000 !important; }
+ /* Hide new-session button and hamburger when doc editor is open on mobile */
+ body.doc-view .mobile-new-chat-btn,
+ /* Hide the global hamburger while Compare Mode is active — the compare
+ header has its own close button in the top-right, and overlapping the
+ two looks like a bug. The .compare-active class lives on the chat
+ container, not body, so use :has(). */
+ body:has(.compare-active) .hamburger-btn { display: none !important; }
+ /* Mobile: hide the sidebar hamburger when a document panel (or notes pane)
+ is open — those sheets cover the whole screen on mobile, so a floating
+ hamburger sticking out over them is just clutter / mis-tap bait. */
+ @media (max-width: 768px) {
+ body.doc-view .hamburger-btn,
+ body:has(#notes-pane) .hamburger-btn { display: none !important; }
+ }
+ /* Make room for hamburger button alongside the tab/header bars (fallback if shown) */
+ body.doc-view.sidebar-collapsed.hamburger-left .doc-tab-bar,
+ body.doc-view.sidebar-collapsed.hamburger-left .doc-editor-header,
+ body.doc-view.sidebar-collapsed.hamburger-left .doc-md-toolbar {
+ padding-left: 44px;
+ }
+ body.doc-view.sidebar-collapsed.hamburger-right .doc-tab-bar,
+ body.doc-view.sidebar-collapsed.hamburger-right .doc-editor-header,
+ body.doc-view.sidebar-collapsed.hamburger-right .doc-md-toolbar {
+ padding-right: 44px;
+ }
+ /* ── Tab bar — match header height, bigger touch targets ── */
+ .doc-tab-bar {
+ padding: 0;
+ height: 40px;
+ }
+ .doc-tab {
+ padding: 0 12px;
+ font-size: 13px;
+ }
+ /* Bigger × touch target on mobile. */
+ .doc-tab-close {
+ font-size: 22px;
+ width: 32px;
+ height: 32px;
+ padding: 0;
+ opacity: 0.5;
+ }
+ .doc-tab .doc-tab-menu-btn {
+ opacity: 0.4 !important;
+ padding: 4px 6px !important;
+ }
+ .doc-tab .doc-tab-menu-btn svg {
+ width: 14px !important;
+ height: 14px !important;
+ }
+ /* Footer is identical to desktop now, so the separate mobile Close/Copy
+ footer is dropped and the per-tab × stays (matching desktop). */
+ .doc-mobile-footer { display: none !important; }
+ .doc-tab-new {
+ font-size: 13px !important;
+ padding: 0 14px !important;
+ gap: 4px;
+ }
+ /* No hamburger padding — it's hidden in doc-view */
+ body.doc-view.sidebar-collapsed.hamburger-left .doc-tab-bar,
+ body.doc-view.sidebar-collapsed.hamburger-left .doc-editor-header,
+ body.doc-view.sidebar-collapsed.hamburger-left .doc-md-toolbar {
+ padding-left: 0 !important;
+ }
+ body.doc-view.sidebar-collapsed.hamburger-right .doc-tab-bar,
+ body.doc-view.sidebar-collapsed.hamburger-right .doc-editor-header,
+ body.doc-view.sidebar-collapsed.hamburger-right .doc-md-toolbar {
+ padding-right: 0 !important;
+ }
+ /* ── Header — identical layout to desktop (left-aligned), match tab height ── */
+ .doc-editor-header {
+ padding: 6px 12px 6px 8px;
+ gap: 6px;
+ min-height: 40px;
+ }
+ .doc-import-label,
+ #doc-version-badge {
+ display: none !important;
+ }
+ /* ── Markdown toolbar — same height as tab bar ── */
+ .doc-md-toolbar {
+ height: 40px !important;
+ padding: 4px 8px;
+ gap: 2px;
+ overflow-x: auto;
+ -webkit-overflow-scrolling: touch;
+ }
+ /* The toolbar's padding-left is forced to 0 by the hamburger rules, so give
+ the Edit/Preview toggle its own left margin to clear the screen edge +
+ the 18px mask fade. Margin isn't overridden by those !important paddings. */
+ .doc-md-toolbar .md-view-toggle { margin-left: 8px; }
+ .doc-md-toolbar button {
+ font-size: 13px !important;
+ padding: 6px 10px !important;
+ min-width: 34px;
+ min-height: 26px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ }
+ .md-toolbar-sep {
+ height: 18px;
+ margin: 0 4px;
+ }
+ }
+
+ /* Opacity slider in the theme tabs row — lets the user see the page behind
+ the modal while tweaking colors. JS toggles .hidden based on active tab. */
+ .theme-opacity-wrap {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ margin-left: auto;
+ margin-right: 6px;
+ padding: 2px 9px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ opacity: 0.65;
+ transition: opacity 0.15s, border-color 0.15s, background 0.15s, color 0.15s;
+ height: 22px;
+ align-self: center;
+ /* Now a <button> toggle, not a slider wrapper. */
+ cursor: pointer;
+ color: var(--fg);
+ font: inherit;
+ background: transparent;
+ }
+ .theme-opacity-wrap.hidden { display: none; }
+ .theme-opacity-wrap:hover { opacity: 1; }
+ /* The title h4 already carries margin-right:auto to group header controls
+ on the right. BOTH the Peek button AND the injected minimize button also
+ have margin-left:auto — and multiple competing auto-margins split the
+ free space, stranding Peek in the middle. Zero their left-autos here so
+ the h4 alone pushes Peek + minimize + close together, flush right. */
+ .modal-header .theme-opacity-wrap,
+ .modal-header .modal-minimize-btn { margin-left: 0 !important; }
+ /* On = peeking through; highlight with the accent so the state is obvious. */
+ .theme-opacity-wrap.active {
+ opacity: 1;
+ border-color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ color: var(--accent, var(--red));
+ }
+ .theme-opacity-label { font-size: 10px; font-weight: 600; letter-spacing: 0.02em; }
+ .theme-opacity-wrap > svg { flex-shrink: 0; opacity: 0.7; }
+ .theme-opacity-wrap input[type="range"] {
+ width: 92px;
+ height: 4px;
+ -webkit-appearance: none;
+ appearance: none;
+ background: color-mix(in srgb, var(--fg) 18%, transparent);
+ border-radius: 2px;
+ outline: none;
+ margin: 0;
+ }
+ .theme-opacity-wrap input[type="range"]::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ background: var(--accent, var(--red));
+ border: none;
+ cursor: pointer;
+ }
+ .theme-opacity-wrap input[type="range"]::-moz-range-thumb {
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ background: var(--accent, var(--red));
+ border: none;
+ cursor: pointer;
+ }
+
+ /* ── Theme editor: hover-to-highlight zone ── */
+ .theme-zone-highlight {
+ position: fixed;
+ pointer-events: none;
+ z-index: 9998;
+ border: 2px dashed var(--accent, var(--red));
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--accent, var(--red)) 40%, transparent),
+ 0 0 18px color-mix(in srgb, var(--accent, var(--red)) 35%, transparent);
+ animation: theme-zone-pulse 1.4s ease-in-out infinite;
+ }
+ @keyframes theme-zone-pulse {
+ 0%, 100% { opacity: 0.95; }
+ 50% { opacity: 0.55; }
+ }
+ /* Highlight the color row itself too so the user has a strong visual link
+ between the input they're hovering and the zone overlay on the page. */
+ #theme-tab-customize .color-row {
+ transition: background 0.15s, border-color 0.15s;
+ border-radius: 6px;
+ }
+ #theme-tab-customize .color-row:hover {
+ background: color-mix(in srgb, var(--accent, var(--red)) 8%, transparent);
+ }
+
+ /* "Auto-saved" pill that flashes after each color/font change. */
+ .theme-autosaved-pill {
+ position: sticky;
+ bottom: 8px;
+ margin: 8px auto 0;
+ width: fit-content;
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ background: color-mix(in srgb, var(--color-success, #4caf50) 18%, var(--bg));
+ color: var(--color-success, #4caf50);
+ border: 1px solid color-mix(in srgb, var(--color-success, #4caf50) 40%, transparent);
+ border-radius: 12px;
+ padding: 4px 10px;
+ font-size: 11px;
+ font-weight: 500;
+ opacity: 0;
+ transform: translateY(4px);
+ transition: opacity 0.2s ease-out, transform 0.2s ease-out;
+ pointer-events: none;
+ z-index: 5;
+ }
+ .theme-autosaved-pill.visible {
+ opacity: 1;
+ transform: translateY(0);
+ }
+
+ /* ---- Doc fullscreen ---- */
+ .doc-editor-pane.doc-fullscreen {
+ flex: 1;
+ max-width: 100%;
+ width: 100% !important;
+ border-left: none;
+ }
+ /* Keep the hamburger reachable in fullscreen — version history can still
+ hide it (the panel covers that area). */
+ body:has(.doc-version-panel:not(.hidden)) .hamburger-btn {
+ display: none !important;
+ }
+
+ /* ---- Document run output ---- */
+ .doc-run-output {
+ border-top: 2px solid var(--hl-function, #61afef);
+ background: var(--bg);
+ padding: 6px 12px 8px;
+ max-height: 200px;
+ overflow: auto;
+ font-family: 'Fira Code', 'Courier New', monospace;
+ font-size: 0.85em;
+ line-height: 1.5;
+ position: relative;
+ }
+ .doc-run-output .code-runner-pre { background: none !important; border: none !important; margin: 0; padding: 0; }
+ .doc-run-output .code-runner-copy-inline {
+ right: 16px;
+ width: 28px;
+ height: 26px;
+ padding: 0;
+ align-items: center;
+ justify-content: center;
+ }
+ .doc-run-output .code-runner-error { color: var(--red); }
+ .doc-run-output .code-runner-loading { font-style: italic; color: var(--red); }
+ .doc-run-output .code-runner-empty { color: var(--fg-muted, var(--fg)); padding: 2px 0; }
+ .doc-run-output .code-runner-close { position: absolute; top: 4px; right: 4px; background: none; border: none; color: var(--fg); cursor: pointer; opacity: 0.5; font-size: 14px; padding: 2px 6px; }
+ .doc-run-output .code-runner-close:hover { opacity: 1; }
+ .doc-run-pre { color: var(--fg); white-space: pre-wrap; word-break: break-word; margin: 0; }
+ .doc-run-error { color: var(--red); white-space: pre-wrap; word-break: break-word; margin: 0; }
+
+ /* ---- Markdown preview ---- */
+ .doc-md-preview {
+ flex: 1;
+ overflow-y: auto;
+ padding: 16px 20px;
+ font-family: inherit;
+ font-size: 12px;
+ line-height: 1.6;
+ color: var(--fg);
+ background: var(--bg);
+ }
+ .doc-md-preview.doc-rich-preview {
+ background: #fff;
+ color: #111;
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
+ font-size: 14px;
+ line-height: 1.6;
+ padding: 32px max(24px, calc((100% - 780px) / 2));
+ }
+ .doc-rich-preview > :not(.doc-preview-hover-edit) {
+ max-width: 780px;
+ margin-left: auto;
+ margin-right: auto;
+ }
+ .doc-rich-preview-empty {
+ position: relative;
+ left: -16px;
+ top: -8px;
+ color: #6b7280;
+ text-align: center;
+ }
+ .doc-preview-hover-edit {
+ position: sticky;
+ top: 0;
+ z-index: 4;
+ float: right;
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ margin: 0 0 8px 12px;
+ padding: 5px 8px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--panel);
+ color: var(--fg);
+ font: inherit;
+ font-size: 11px;
+ cursor: pointer;
+ opacity: 0;
+ pointer-events: none;
+ transform: translateY(-2px);
+ transition: opacity 0.12s, transform 0.12s, background 0.12s, border-color 0.12s;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
+ }
+ .doc-md-preview:hover .doc-preview-hover-edit,
+ .doc-preview-hover-edit:focus-visible {
+ opacity: 1;
+ pointer-events: auto;
+ transform: translateY(0);
+ }
+ .doc-preview-hover-edit:hover {
+ background: color-mix(in srgb, var(--accent, var(--red)) 12%, var(--panel));
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 55%, var(--border));
+ }
+
+ /* DOCX visual preview — keep the Word document on a readable white sheet even
+ when the surrounding workspace uses a dark theme. */
+ .doc-docx-preview {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow: auto;
+ padding: 28px 18px 42px;
+ background: #d9dce1;
+ color: #111827;
+ }
+ .doc-docx-paper {
+ width: min(816px, 100%);
+ min-height: 1056px;
+ box-sizing: border-box;
+ margin: 0 auto;
+ padding: 72px 76px;
+ background: #fff;
+ color: #111;
+ font-family: Arial, Helvetica, sans-serif;
+ font-size: 15px;
+ line-height: 1.55;
+ box-shadow: 0 4px 18px rgba(0,0,0,.22);
+ }
+ .doc-docx-paper h1, .doc-docx-paper h2, .doc-docx-paper h3,
+ .doc-docx-paper h4, .doc-docx-paper h5, .doc-docx-paper h6 {
+ color: #111;
+ line-height: 1.2;
+ margin: 1.2em 0 .55em;
+ }
+ .doc-docx-paper p { margin: 0 0 .8em; }
+ .doc-docx-paper img { max-width: 100%; height: auto; }
+ .doc-docx-paper table { width: 100%; border-collapse: collapse; margin: 1em 0; }
+ .doc-docx-paper td, .doc-docx-paper th { border: 1px solid #c7cbd1; padding: 6px 8px; vertical-align: top; }
+ .doc-docx-paper th { background: #f2f3f5; }
+ .doc-docx-paper a { color: #1757a6; }
+ .doc-docx-preview-loading, .doc-docx-preview-error {
+ max-width: 816px;
+ margin: 40px auto;
+ padding: 20px;
+ color: var(--fg);
+ text-align: center;
+ }
+ .doc-docx-preview-error { color: var(--color-error, #c2413d); }
+ @media (max-width: 700px) {
+ .doc-docx-preview { padding: 12px 8px 28px; }
+ .doc-docx-paper { min-height: 0; padding: 34px 24px; font-size: 14px; }
+ }
+ .doc-md-preview pre {
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 10px 12px;
+ overflow-x: auto;
+ }
+ .doc-md-preview code {
+ font-size: 0.95em;
+ }
+ .doc-md-preview p { margin: 0.6em 0; }
+ .doc-md-preview h1, .doc-md-preview h2, .doc-md-preview h3 {
+ margin: 0.8em 0 0.4em;
+ color: var(--hl-string);
+ }
+ .doc-md-preview ul, .doc-md-preview ol {
+ margin-left: 20px;
+ margin-bottom: 0.6em;
+ }
+ .doc-md-preview blockquote {
+ border-left: 3px solid var(--border);
+ padding-left: 12px;
+ margin: 0.6em 0;
+ opacity: 0.8;
+ }
+
+ /* ---- Active state for doc action icon buttons ---- */
+ .doc-action-icon-btn.active {
+ opacity: 1;
+ color: var(--red);
+ background: color-mix(in srgb, var(--red) 12%, transparent);
+ }
+ #doc-run-btn:hover {
+ color: var(--hl-function, #61afef);
+ }
+
+ /* ===== ADMIN PANEL (inside settings modal) ===== */
+
+ /* Cards */
+ .admin-card {
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 12px;
+ margin-bottom: 10px;
+ }
+ /* When the integrations editor opens, the inner admin-card should match the
+ listed integration cards (subtle tint, same border) instead of reverting
+ to the solid-panel admin-card surface used elsewhere. */
+ #unified-intg-form .admin-card,
+ #integrations-form .admin-card {
+ background: color-mix(in srgb, var(--fg) 3%, transparent);
+ }
+ .admin-card h2 {
+ font-size: 14px;
+ font-weight: 600;
+ letter-spacing: -0.03em;
+ margin-bottom: 8px;
+ padding-bottom: 6px;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 40%, transparent);
+ }
+ .admin-danger-card {
+ border-color: color-mix(in srgb, var(--color-error) 27%, transparent);
+ }
+
+ /* Toggle switch */
+ .admin-toggle-row {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ }
+ .admin-toggle-label {
+ font-size: 13px;
+ font-weight: 500;
+ }
+ .admin-toggle-sub {
+ /* 65% mix keeps this helper text above WCAG AA 4.5:1 on the dark panel
+ (50% only reached ~3.9:1). */
+ color: color-mix(in srgb, var(--fg) 65%, transparent);
+ font-size: 11px;
+ margin-top: 2px;
+ }
+ /* Hide the native up/down spinners on the Max auto-skills number input. */
+ #skill-max-input {
+ -moz-appearance: textfield;
+ appearance: textfield;
+ }
+ #skill-max-input::-webkit-inner-spin-button,
+ #skill-max-input::-webkit-outer-spin-button {
+ -webkit-appearance: none;
+ margin: 0;
+ }
+ .admin-switch {
+ position: relative;
+ width: 30px;
+ height: 16px;
+ flex-shrink: 0;
+ display: inline-block;
+ }
+ .admin-switch input {
+ opacity: 0;
+ width: 0;
+ height: 0;
+ }
+ .admin-slider {
+ position: absolute;
+ inset: 0;
+ background: color-mix(in srgb, var(--fg) 50%, transparent);
+ border-radius: 8px;
+ cursor: pointer;
+ transition: background 0.08s;
+ }
diff --cc static/css/06-admin-settings.css
index 000000000,4c2e95a30..ba1b0f38b
mode 000000,100644..100644
--- a/static/css/06-admin-settings.css
+++ b/static/css/06-admin-settings.css
@@@ -1,0 -1,1426 +1,1435 @@@
+ /* 06-admin-settings - part of the former static/style.css.
+ *
+ * The stylesheet is split by area, but the split is mechanical: rules were
+ * moved verbatim and NOT regrouped. The numeric prefix is the load order, and
+ * that order is what preserves the cascade. A rule sits in the file its
+ * original position fell into, so an area's rules are not all in its file and
+ * a file is not only that area's rules.
+ *
+ * Do not reorder the <link> tags in static/index.html, and do not move a rule
+ * between files: with 1,151 redeclarations and 1,886 !important in this
+ * cascade, either can change which declaration wins.
+ *
+ * static/index.html and the PRECACHE list in static/sw.js must agree on this
+ * order. tests/test_static_stylesheet_manifest.py and
+ * tests/test_css_computed_style_snapshot.py fail if that drifts.
+ */
+ .admin-slider::before {
+ content: '';
+ position: absolute;
+ left: 2px;
+ top: 2px;
+ width: 12px;
+ height: 12px;
+ background: var(--panel);
+ border-radius: 50%;
+ transition: transform 0.08s;
+ box-shadow: 0 1px 2px rgba(0,0,0,0.25);
+ }
+ .admin-switch input:checked + .admin-slider {
+ background: var(--red);
+ }
+ .admin-switch input:checked + .admin-slider::before {
+ transform: translateX(14px);
+ }
+
+ /* User rows */
+ .admin-user-row {
+ display: flex;
+ flex-direction: column;
+ padding: 10px 12px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ margin-bottom: 6px;
+ transition: border-color 0.15s;
+ }
+ .admin-user-row:hover {
+ border-color: color-mix(in srgb, var(--fg) 20%, var(--border));
+ }
+ .admin-user-info {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .admin-user-name { font-size: 13px; font-weight: 500; }
+ /* Privilege panel */
+ .admin-priv-panel {
+ max-height: 600px;
+ transition: max-height 0.3s ease, opacity 0.2s ease, padding 0.2s ease;
+ overflow: hidden;
+ }
+ .admin-priv-panel.hidden {
+ max-height: 0 !important;
+ opacity: 0;
+ padding-top: 0 !important;
+ padding-bottom: 0 !important;
+ margin-top: 0 !important;
+ border-top: none !important;
+ }
+ /* Privilege toggle rows */
+ .admin-priv-panel [data-priv] {
+ accent-color: var(--accent, var(--red));
+ }
+ /* Section headers */
+ .admin-priv-section {
+ font-size: 10px;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ opacity: 0.35;
+ font-weight: 600;
+ margin: 10px 0 4px;
+ }
+ .admin-priv-section:first-child {
+ margin-top: 0;
+ }
+ /* Model checkbox list */
+ .priv-models-list {
+ max-height: 150px;
+ overflow-y: auto;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 4px 6px;
+ background: var(--bg);
+ scrollbar-width: thin;
+ }
+ .priv-models-list::-webkit-scrollbar {
+ width: 4px;
+ }
+ .priv-models-list::-webkit-scrollbar-thumb {
+ background: color-mix(in srgb, var(--fg) 15%, transparent);
+ border-radius: 2px;
+ }
+ .priv-models-list label {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 3px 2px;
+ font-size: 11px;
+ cursor: pointer;
+ border-radius: 3px;
+ transition: background 0.1s;
+ }
+ .priv-models-list label:hover {
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ }
+ .priv-models-list input[type="checkbox"] {
+ accent-color: var(--accent, var(--red));
+ margin: 0;
+ flex-shrink: 0;
+ }
+ /* All/None links */
+ .priv-models-all,
+ .priv-models-none {
+ font-size: 10px;
+ opacity: 0.5;
+ color: var(--fg);
+ text-decoration: none;
+ cursor: pointer;
+ transition: opacity 0.1s;
+ }
+ .priv-models-all:hover,
+ .priv-models-none:hover {
+ opacity: 1;
+ }
+
+ /* MCP tool toggles panel */
+ .mcp-tools-panel {
+ width: 100%;
+ padding: 8px 0 4px;
+ border-top: 1px solid var(--border);
+ margin-top: 8px;
+ max-height: 600px;
+ transition: max-height 0.3s ease, opacity 0.2s ease, padding 0.2s ease;
+ overflow: hidden;
+ }
+ .mcp-tools-panel.hidden {
+ max-height: 0 !important;
+ opacity: 0;
+ padding-top: 0 !important;
+ padding-bottom: 0 !important;
+ margin-top: 0 !important;
+ }
+ .mcp-tools-panel .mcp-tools-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 6px;
+ }
+ .mcp-tools-panel .mcp-tools-header span:first-child {
+ font-size: 10px;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ opacity: 0.35;
+ font-weight: 600;
+ }
+ .mcp-tools-panel .mcp-tools-header a {
+ font-size: 10px;
+ opacity: 0.5;
+ color: var(--fg);
+ text-decoration: none;
+ cursor: pointer;
+ transition: opacity 0.1s;
+ }
+ .mcp-tools-panel .mcp-tools-header a:hover {
+ opacity: 1;
+ }
+ .mcp-tools-list {
+ max-height: 200px;
+ overflow-y: auto;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 4px 6px;
+ background: color-mix(in srgb, var(--fg) 3%, transparent);
+ }
+ .mcp-tools-list::-webkit-scrollbar {
+ width: 4px;
+ }
+ .mcp-tools-list::-webkit-scrollbar-thumb {
+ background: color-mix(in srgb, var(--fg) 15%, transparent);
+ border-radius: 2px;
+ }
+ .mcp-tools-list label {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 4px 6px;
+ font-size: 11px;
+ cursor: pointer;
+ border-radius: 3px;
+ min-width: 0;
+ }
+ .mcp-tools-list label > span {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ flex: 1;
+ }
+ .mcp-tools-list label:hover {
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ }
+ .mcp-tools-list input[type="checkbox"] {
+ accent-color: var(--accent, var(--red));
+ margin: 0;
+ flex-shrink: 0;
+ }
+ /* Dot-style toggle (mirrors .note-check-dot) for the Add Models row,
+ replacing the native checkbox while keeping it for click handling. */
+ .adm-cb-hidden {
+ position: absolute;
+ width: 0;
+ height: 0;
+ opacity: 0;
+ pointer-events: none;
+ }
+ .adm-check-dot {
+ /* Lock the dot to a fixed 12×12 box. The parent rule
+ `.mcp-tools-list label > span { flex: 1 }` was stretching this span
+ to fill the row when it didn't have its own flex override. */
+ flex: 0 0 12px !important;
+ width: 12px !important;
+ height: 12px;
+ min-width: 12px;
+ max-width: 12px;
+ box-sizing: border-box;
+ border-radius: 50%;
+ border: 1.5px solid color-mix(in srgb, var(--fg) 35%, transparent);
+ position: relative;
+ transition: background 0.2s, border-color 0.2s, transform 0.15s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ .adm-model-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 28px;
+ padding: 2px 4px;
+ box-sizing: border-box;
+ width: 100%;
+ }
++.adm-endpoint-select-label {
++ width: auto;
++ min-height: 0;
++ padding: 0;
++ margin-right: 5px;
++ flex: 0 0 auto;
++ justify-content: flex-start;
++ cursor: pointer;
++}
+ .adm-model-label {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex: 1 1 auto;
+ min-width: 0;
+ cursor: pointer;
+ }
+ .adm-model-name {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ flex: 1;
+ }
+ .adm-model-tools-col {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ flex: 0 0 auto;
+ margin-left: auto;
+ }
+ .adm-model-tools-label {
+ font-size: 10px;
+ opacity: 0.45;
+ flex-shrink: 0;
+ user-select: none;
+ }
+ .adm-model-tool-mode,
+ .admin-tools-select {
+ height: 24px;
+ min-height: 24px;
+ line-height: 22px;
+ font-size: 11px;
+ padding: 0 18px 0 6px;
+ width: 124px;
+ max-width: 130px;
+ flex-shrink: 0;
+ border-radius: 4px;
+ border: 1px solid var(--border);
+ background-color: var(--select-bg);
+ color: var(--select-fg);
+ box-sizing: border-box;
+ vertical-align: middle;
+ }
+ @media (max-width: 480px) {
+ .adm-model-tool-mode,
+ .admin-tools-select {
+ width: 105px;
+ max-width: 110px;
+ font-size: 10px;
+ padding: 0 14px 0 4px;
+ }
+ }
+ .adm-model-row:hover .adm-check-dot {
+ border-color: var(--accent, var(--red));
+ transform: scale(1.15);
+ }
+ .adm-cb-hidden:checked + .adm-check-dot {
+ background: var(--accent, var(--red));
+ border-color: var(--accent, var(--red));
+ }
+ /* Added Models bulk selection uses the shared dot, without a check glyph. */
+ .adm-endpoint-select-dot {
+ flex-basis: 11px !important;
+ width: 11px !important;
+ height: 11px;
+ min-width: 11px;
+ max-width: 11px;
+ }
+ /* Disabled endpoints — dim the row but keep the toggle/delete buttons
+ at full opacity so the user can re-enable or remove without squinting. */
+ .admin-user-row.admin-ep-disabled { opacity: 0.55; }
+
+
+ .admin-user-row.adm-ep-just-added {
+ border-radius: 8px;
+ animation: adm-ep-just-added-glow 2.2s ease-out;
+ }
+ .admin-user-row.admin-ep-disabled .admin-btn-sm,
+ .admin-user-row.admin-ep-disabled .admin-btn-delete,
+ .admin-user-row.admin-ep-disabled .admin-badge-off { opacity: 1; }
+ /* Local / API subsection labels inside the Endpoints card */
+ .adm-ep-section-head {
+ display: flex;
+ align-items: center;
+ font-size: 10px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--fg);
+ opacity: 0.5;
+ margin-bottom: 4px;
+ }
+
+ /* Collapsible Add-Models subsections (API / Local) — the whole header row
+ acts as a toggle so a long cloud-API form can be tucked away when you
+ only want to paste a local URL. */
+ .adm-section-toggle {
+ cursor: pointer;
+ user-select: none;
+ opacity: 0.8;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 6px 9px;
+ margin-bottom: 6px;
+ background: color-mix(in srgb, var(--fg) 4%, transparent);
+ transition: border-color 0.12s, background 0.12s, opacity 0.12s;
+ }
+ .adm-section-toggle:hover {
+ opacity: 1;
+ border-color: var(--red);
+ background: color-mix(in srgb, var(--red) 8%, transparent);
+ }
+ .adm-section-toggle .adm-section-caret { opacity: 0.6; }
+ /* When expanded, square off the bottom so the header reads as attached to
+ the form it controls. */
+ .adm-add-section:not(.collapsed) .adm-section-toggle {
+ border-bottom-left-radius: 0;
+ border-bottom-right-radius: 0;
+ margin-bottom: 0;
+ }
+ .adm-section-caret {
+ margin-left: auto;
+ flex-shrink: 0;
+ transition: transform 0.18s ease;
+ }
+ .adm-quickstart-toggle {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ cursor: pointer;
+ user-select: none;
+ opacity: 0.72;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 4px 8px;
+ font-size: 11px;
+ background: color-mix(in srgb, var(--fg) 3%, transparent);
+ }
+ .adm-quickstart-toggle:hover {
+ opacity: 1;
+ border-color: var(--red);
+ }
+ .adm-quickstart-body {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ border: 1px solid var(--border);
+ border-top: 0;
+ border-radius: 0 0 6px 6px;
+ padding: 6px 8px;
+ }
+
+ /* Custom provider picker (logo + name) replacing the native <select> */
+ .adm-provider-picker { position: relative; margin-bottom: 6px; }
+ .adm-provider-combo {
+ display: flex;
+ align-items: stretch;
+ }
+ .adm-provider-combo input {
+ flex: 1;
+ min-width: 0;
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+ }
+ .adm-provider-btn {
+ width: 100%;
+ display: flex; align-items: center; gap: 8px;
+ background: var(--bg); color: var(--fg);
+ border: 1px solid var(--border); border-radius: 6px;
+ padding: 5px 8px; font-family: inherit; font-size: 12px;
+ cursor: pointer; text-align: left;
+ }
+ .adm-provider-combo .adm-provider-btn {
+ width: 128px;
+ flex-shrink: 0;
+ border-left: 0;
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+ justify-content: space-between;
+ }
+ .adm-provider-btn:hover { border-color: color-mix(in srgb, var(--fg) 30%, var(--border)); }
+ .adm-provider-current { flex: 1; display: flex; align-items: center; gap: 8px; min-width: 0; }
+ .adm-provider-logo {
+ width: 14px; height: 14px;
+ display: inline-flex; align-items: center; justify-content: center;
+ flex-shrink: 0; color: var(--fg); opacity: 0.85;
+ }
+ .adm-provider-logo svg { width: 14px; height: 14px; }
+ /* Pull the settings-select 4px closer to its logo chip so the row
+ reads as logo+select instead of having an extra gap. */
+ .adm-model-logo + .settings-select { margin-left: -4px; }
+ /* Fallback rows: stretch the model select so the trash button on
+ the right aligns with the right edge of the Endpoint and Model
+ dropdowns above the fallback list. Without flex:1 the model
+ select shrinks to its content and the trash button rides up
+ tight to it. */
+ .settings-fallback-row > .settings-select { flex: 1 1 0; min-width: 0; }
+ /* Constrain logo SVGs in settings dropdown chips. Many provider
+ icons in providers.js declare only viewBox (no width/height),
+ so without this rule the browser falls back to 300x150 and
+ blows up the row. */
+ .settings-fallback-row > span[style*="width:18px"] svg:not([width]),
+ .settings-row > span[style*="width:18px"] svg:not([width]),
+ span[id$="-logo"] svg:not([width]) {
+ width: 100%;
+ height: 100%;
+ display: block;
+ }
+ .adm-provider-logo:empty {
+ background: color-mix(in srgb, var(--fg) 12%, transparent);
+ border-radius: 50%;
+ }
+ .adm-provider-caret { flex-shrink: 0; transition: transform 0.15s; }
+ .adm-provider-picker:has(.adm-provider-menu:not(.hidden)) .adm-provider-caret {
+ transform: rotate(180deg);
+ }
+ .adm-provider-menu {
+ position: absolute; top: calc(100% + 4px); left: 0; right: 0; z-index: 100;
+ max-height: 280px; overflow-y: auto;
+ background: var(--panel);
+ border: 1px solid var(--border); border-radius: 6px;
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25);
+ padding: 4px;
+ }
+ .adm-provider-menu.hidden { display: none; }
+ .adm-provider-item {
+ display: flex; align-items: center; gap: 8px;
+ padding: 5px 8px; border-radius: 4px;
+ font-size: 12px; cursor: pointer;
+ }
+ .adm-provider-item:hover { background: color-mix(in srgb, var(--fg) 8%, transparent); }
+ .adm-provider-item.active { background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent); }
+
+ /* When the Appearance tab is open, the #settings-modal-opacity slider (in
+ the header) fades the modal so the user can see the rest of the UI react
+ as toggles flip. The fade is applied as a background color-mix in JS
+ (settings.js) rather than element opacity, so the controls/text stay
+ crisp — mirroring the Theme customizer's opacity slider. */
+
+ /* Search provider fallback chain — chips + drag-reorder */
+ .search-fallback-chain {
+ flex: 1; display: flex; align-items: center;
+ flex-wrap: wrap; gap: 6px; min-height: 28px;
+ }
+ .search-fb-chip {
+ display: inline-flex; align-items: center; gap: 4px;
+ padding: 3px 4px 3px 6px;
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ border: 1px solid var(--border); border-radius: 10px;
+ font-size: 11px; cursor: grab; user-select: none;
+ }
+ .search-fb-chip.dragging { opacity: 0.4; }
+ .search-fb-grip { opacity: 0.35; font-size: 10px; line-height: 1; cursor: grab; }
+ .search-fb-logo {
+ width: 12px; height: 12px;
+ display: inline-flex; align-items: center; justify-content: center;
+ flex-shrink: 0; opacity: 0.85;
+ }
+ .search-fb-logo svg { width: 12px; height: 12px; }
+ .search-fb-remove {
+ background: none; border: none; color: var(--fg);
+ opacity: 0.45; cursor: pointer;
+ font-size: 14px; line-height: 1; padding: 0 2px;
+ transition: opacity 0.15s, color 0.15s;
+ }
+ .search-fb-remove:hover { opacity: 1; color: var(--red); }
+ .search-fb-add {
+ background: var(--bg); color: var(--fg);
+ border: 1px dashed var(--border); border-radius: 10px;
+ padding: 2px 6px; font-family: inherit; font-size: 11px;
+ outline: none; cursor: pointer;
+ }
+ .search-fb-add:focus,
+ .search-fb-add:hover {
+ border-color: var(--accent, var(--red));
+ border-style: solid;
+ }
+
+ .mcp-tools-search {
+ width: 100%;
+ box-sizing: border-box;
+ margin-bottom: 6px;
+ padding: 5px 8px;
+ font-size: 11px;
+ font-family: inherit;
+ background: color-mix(in srgb, var(--fg) 4%, transparent);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ color: var(--fg);
+ outline: none;
+ }
+ .mcp-tools-search:focus {
+ border-color: color-mix(in srgb, var(--accent) 60%, var(--border));
+ }
+ .mcp-tools-count {
+ font-size: 11px;
+ font-weight: 600;
+ opacity: 0.7;
+ }
+
+ /* Badges */
+ .admin-badge {
+ font-size: 10px;
+ padding: 2px 6px;
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--red) 20%, transparent);
+ color: var(--red);
+ font-weight: 600;
+ }
+ .admin-badge-off {
+ background: color-mix(in srgb, var(--color-error) 20%, transparent);
+ color: var(--color-error);
+ }
+
+ /* Buttons */
+ .admin-btn-delete {
+ background: none;
+ border: 1px solid color-mix(in srgb, var(--color-error) 27%, transparent);
+ color: var(--color-error);
+ padding: 4px 10px;
+ border-radius: 6px;
+ cursor: pointer;
+ font-size: 11px;
+ font-family: inherit;
+ transition: all 0.15s;
+ }
+ .admin-btn-delete:hover {
+ background: var(--color-error);
+ border-color: var(--color-error);
+ color: #fff;
+ }
+ .admin-btn-add {
+ padding: 4px 10px;
+ border: 1px solid var(--accent, var(--red));
+ border-radius: 6px;
+ background: var(--accent, var(--red));
+ color: var(--bg);
+ cursor: pointer;
+ font-weight: 600;
+ font-size: 11px;
+ font-family: inherit;
+ box-sizing: border-box;
+ transition: opacity 0.15s, background 0.15s, border-color 0.15s;
+ }
+ .admin-btn-add:hover {
+ background: var(--accent, var(--red));
+ border-color: var(--accent, var(--red));
+ opacity: 0.9;
+ }
+ .admin-btn-add:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+ .admin-btn-sm {
+ padding: 3px 8px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--panel);
+ color: var(--fg);
+ cursor: pointer;
+ font-size: 11px;
+ }
+ .admin-btn-sm:hover {
+ background: var(--border);
+ border-color: var(--red);
+ }
+ .admin-spinner {
+ display: inline-block;
+ width: 12px;
+ height: 12px;
+ border: 2px solid var(--border);
+ border-top-color: var(--red);
+ border-radius: 50%;
+ animation: admin-spin 0.6s linear infinite;
+ vertical-align: -2px;
+ margin-right: 2px;
+ }
+
+ /* Forms */
+ .admin-add-form {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-top: 8px;
+ }
+ .admin-add-form input {
+ flex: 1;
+ min-width: 120px;
+ padding: 5px 8px;
+ height: 32px;
+ box-sizing: border-box;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--fg);
+ font-family: inherit;
+ font-size: 12px;
+ }
+ .admin-add-form input:focus { outline: none; border-color: var(--red); }
+ .admin-switch-inline {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 11px;
+ color: color-mix(in srgb, var(--fg) 60%, transparent);
+ cursor: default;
+ }
+
+ .admin-model-form {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin-bottom: 8px;
+ }
+ .admin-model-form input,
+ .admin-model-form select {
+ padding: 5px 8px;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--fg);
+ font-size: 12px;
+ }
+ .admin-model-form input:focus { outline: none; border-color: var(--red); }
+ .admin-model-form-row {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap; /* let buttons drop to a new row on narrow widths
+ instead of overflowing the modal */
+ align-items: center;
+ }
+ .admin-model-form-row input {
+ flex: 1 1 180px; /* api-key input takes the long axis but allows
+ dropping below the buttons at small widths */
+ min-width: 0; /* don't refuse to shrink past content width */
+ }
+ .admin-model-form-row select {
+ flex: 0 0 auto;
+ }
+ .admin-model-form-row button {
+ flex: 0 0 auto;
+ white-space: nowrap;
+ }
+ /* On narrow screens, give buttons their own row + push the Add button
+ to the right so it remains the obvious primary action. */
+ @media (max-width: 540px) {
+ .admin-model-form-row input { flex-basis: 100%; }
+ .admin-model-form-row .admin-btn-add { margin-left: auto; }
+ }
+ .adm-ep-inline-msg {
+ min-height: 16px;
+ margin-top: 5px;
+ font-size: 11px;
+ }
+
+ /* Endpoint items */
+ .admin-ep-item {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 8px;
+ background: var(--bg);
+ border-radius: 6px;
+ margin-bottom: 4px;
+ font-size: 12px;
+ }
+ .admin-ep-info { flex: 1; overflow: hidden; }
+ .admin-ep-name { color: var(--fg); font-weight: 500; }
+ .admin-ep-detail {
+ color: color-mix(in srgb, var(--fg) 40%, transparent);
+ font-size: 10px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ margin-top: -4px;
+ }
+
+ /* Settings panel — tint each card's h2 title icon with the user's accent
+ colour. Direct-child selector (`> h2 > svg`) so SVGs nested inside
+ header buttons (Test, kebab, etc.) are untouched. Each title icon uses
+ stroke="currentColor", so setting color propagates; existing inline
+ opacity:0.6 stays so the tint reads soft. */
+ /* Selected integration card — class beats inline borderColor reset */
+ .intg-card.intg-card-active { border-color: var(--accent, var(--red)) !important; }
+
+ /* Edge-dock resize handle: invisible at rest, accent stripe animates in
+ on hover. Inline background:transparent + transition come from
+ modalSnap.js; this rule paints the accent gradient on hover, beating
+ the inline style with !important. */
+ .edge-dock-resize-handle-left:hover {
+ background: linear-gradient(to right, transparent 0 3px, color-mix(in srgb, var(--accent, var(--red)) 35%, transparent) 3px 7px, transparent 7px 10px) !important;
+ }
+ .edge-dock-resize-handle-right:hover {
+ background: linear-gradient(to left, transparent 0 3px, color-mix(in srgb, var(--accent, var(--red)) 35%, transparent) 3px 7px, transparent 7px 10px) !important;
+ }
+
+ [data-settings-panel] .admin-card > h2 > svg,
+ #theme-popup .admin-card > h2 > svg,
+ [data-settings-panel="added-models"] .adm-ep-section-head > svg {
+ color: var(--accent, var(--red));
+ }
+ .admin-ep-actions {
+ display: flex;
+ gap: 4px;
+ flex-shrink: 0;
+ }
+
+ /* Status messages */
+ .admin-error { color: var(--color-error); font-size: 11px; margin-top: 4px; }
+ .admin-success { color: var(--color-success); font-size: 11px; margin-top: 4px; }
+ .admin-empty {
+ color: color-mix(in srgb, var(--fg) 40%, transparent);
+ font-size: 12px;
+ padding: 10px 0;
+ text-align: center;
+ }
+ /* Endpoint-list empty states ("No endpoints configured" / "None") get a
+ left-aligned, accent-colored treatment so they read as "this row is your
+ placeholder, click Add" rather than a centered "nothing here" grey blob. */
+ #adm-epList-local .admin-empty,
+ #adm-epList-api .admin-empty {
+ text-align: left;
+ padding: 8px 4px;
+ color: var(--accent-primary, var(--accent, var(--red)));
+ }
+
+ /* RAG upload zone */
+ .admin-rag-upload-zone {
+ border: 2px dashed var(--border);
+ border-radius: 8px;
+ padding: 14px;
+ text-align: center;
+ cursor: pointer;
+ transition: border-color 0.2s, background 0.2s;
+ margin-bottom: 8px;
+ }
+ .admin-rag-upload-zone:hover,
+ .admin-rag-upload-zone.dragover {
+ border-color: var(--red);
+ background: color-mix(in srgb, var(--red) 7%, transparent);
+ }
+ .admin-rag-upload-zone p {
+ color: color-mix(in srgb, var(--fg) 50%, transparent);
+ font-size: 11px;
+ margin-top: 4px;
+ }
+ .admin-rag-icon { font-size: 18px; }
+ .admin-rag-dir-row {
+ display: flex;
+ gap: 6px;
+ margin-bottom: 8px;
+ }
+ .admin-rag-dir-row input {
+ flex: 1;
+ padding: 5px 8px;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--fg);
+ font-size: 12px;
+ }
+ .admin-rag-dir-row input:focus { outline: none; border-color: var(--red); }
+ .admin-rag-dir-row button {
+ padding: 5px 8px;
+ border: none;
+ border-radius: 6px;
+ background: var(--red);
+ color: #fff;
+ cursor: pointer;
+ font-size: 12px;
+ white-space: nowrap;
+ }
+ .admin-rag-toolbar {
+ display: flex;
+ justify-content: flex-end;
+ margin-bottom: 6px;
+ }
+ .admin-rag-section-label {
+ font-size: 10px;
+ color: color-mix(in srgb, var(--fg) 50%, transparent);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ margin: 8px 0 4px;
+ }
+ .admin-rag-item {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 6px 8px;
+ background: var(--bg);
+ border-radius: 6px;
+ margin-bottom: 4px;
+ font-size: 12px;
+ }
+ .admin-rag-item-name {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--fg);
+ }
+ .admin-rag-item-meta {
+ color: color-mix(in srgb, var(--fg) 40%, transparent);
+ font-size: 10px;
+ margin: 0 6px;
+ flex-shrink: 0;
+ }
+ .admin-rag-status {
+ font-size: 11px;
+ color: color-mix(in srgb, var(--fg) 50%, transparent);
+ margin-top: 6px;
+ }
+
+ /* Token reveal */
+ .admin-token-reveal {
+ margin-top: 8px;
+ padding: 8px;
+ background: color-mix(in srgb, var(--red) 8%, var(--bg));
+ border: 1px solid color-mix(in srgb, var(--red) 25%, var(--border));
+ border-radius: 8px;
+ }
+
+ /* Selects in admin cards */
+ .admin-card select {
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--fg);
+ font-size: 12px;
+ }
+ .admin-card input {
+ font-family: inherit;
+ font-size: 12px;
+ }
+ .admin-card label {
+ font-size: 12px;
+ }
+
+ /* ---- Document Library ---- */
+
+ .doclib-modal-content {
+ width: min(600px, 92vw);
+ max-height: 85vh;
+ font-size: 12px;
+ background: var(--bg);
+ }
+ /* Anchor doclib modal to top so only the bottom edge moves on resize */
+ #doclib-modal {
+ align-items: flex-start;
+ padding-top: 8vh;
+ }
+ .doclib-modal-content .modal-header h4 {
+ font-size: 1rem;
+ }
+ /* The "open in new tab" email modal inherited the 1rem doclib header, which
+ read way bigger than the email subject in the regular (inline) reader. Pin
+ it smaller so the two views are consistent. */
+ .email-reader-tab-modal .modal-header h4 {
+ font-size: 13px;
+ font-weight: 600;
+ }
+ /* Match the sticky modal-header to the doclib modal-content body color
+ (var(--bg)) instead of the global var(--panel) default — otherwise the
+ header reads as a darker stripe above the email list. */
+ .doclib-modal-content > .modal-header {
+ background: var(--bg);
+ }
+ .doclib-stats {
+ font-size: 11px;
+ color: var(--fg-muted);
+ margin-bottom: 8px;
+ }
+ .doclib-toolbar {
+ display: flex;
+ gap: 8px;
+ margin-bottom: 8px;
+ align-items: center;
+ }
+ .doclib-search {
+ flex: 1;
+ padding: 6px 8px;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--fg);
+ font-size: 12px;
+ font-family: inherit;
+ outline: none;
+ transition: border-color 0.15s;
+ }
+ #archive-select-btn { height: auto; padding: 5px 8px; }
+ .doclib-search:focus {
+ border-color: var(--red);
+ }
+ .doclib-sort {
+ padding: 6px 8px;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--fg);
+ font-size: 12px;
+ font-family: inherit;
+ outline: none;
+ cursor: pointer;
+ }
+ .doclib-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ margin-bottom: 8px;
+ }
+ .doclib-chip {
+ padding: 2px 10px;
+ border-radius: 12px;
+ font-size: 10px;
+ border: 1px solid var(--border);
+ background: transparent;
+ color: var(--fg-muted);
+ cursor: pointer;
+ user-select: none;
+ transition: background 0.15s, border-color 0.15s;
+ }
+ .doclib-chip:hover {
+ border-color: var(--red);
+ }
+ .doclib-chip.active {
+ background: color-mix(in srgb, var(--red) 15%, transparent);
+ border-color: color-mix(in srgb, var(--red) 40%, transparent);
+ color: var(--red);
+ }
+ /* Document library — language chip row */
+ .doclib-lang-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ padding: 2px 0;
+ max-height: 52px;
+ overflow-y: auto;
+ }
+ .doclib-lang-chips:empty { display: none; }
+ /* Mobile: keep tag chips on ONE row and scroll horizontally instead of wrapping
+ into a tall multi-line block (Serve, library — anywhere .doclib-lang-chips is used). */
+ @media (max-width: 768px) {
+ .doclib-lang-chips {
+ flex-wrap: nowrap;
+ overflow-x: auto;
+ overflow-y: hidden;
+ max-height: none;
+ -webkit-overflow-scrolling: touch;
+ scrollbar-width: none;
+ }
+ .doclib-lang-chips::-webkit-scrollbar { display: none; }
+ .doclib-lang-chips > * { flex-shrink: 0; }
+ }
+ #doclib-tidy-btn, #doclib-select-btn, #doclib-chats-tidy-btn {
+ position: relative;
+ top: -3px;
+ }
+ /* Document library — list layout */
+ .doclib-grid {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ max-height: 400px;
+ overflow-y: auto;
+ padding: 0;
+ position: relative;
+ }
+
+ /* Gallery grid domino-in cascade on open — same recipe as the document/email
+ libraries. Applied to #gallery-grid in gallery.js on the first render after
+ each open, removed after the longest delay so re-renders feel instant. */
+ .gallery-just-opened > .gallery-card {
+ animation: section-domino-in 0.36s cubic-bezier(0.22, 1.61, 0.36, 1) backwards;
+ }
+ .gallery-just-opened > :nth-child(1) { animation-delay: 0.02s; }
+ .gallery-just-opened > :nth-child(2) { animation-delay: 0.04s; }
+ .gallery-just-opened > :nth-child(3) { animation-delay: 0.06s; }
+ .gallery-just-opened > :nth-child(4) { animation-delay: 0.08s; }
+ .gallery-just-opened > :nth-child(5) { animation-delay: 0.10s; }
+ .gallery-just-opened > :nth-child(6) { animation-delay: 0.12s; }
+ .gallery-just-opened > :nth-child(7) { animation-delay: 0.14s; }
+ .gallery-just-opened > :nth-child(8) { animation-delay: 0.16s; }
+ .gallery-just-opened > :nth-child(9) { animation-delay: 0.18s; }
+ .gallery-just-opened > :nth-child(10) { animation-delay: 0.20s; }
+ .gallery-just-opened > :nth-child(11) { animation-delay: 0.22s; }
+ .gallery-just-opened > :nth-child(12) { animation-delay: 0.24s; }
+ .gallery-just-opened > :nth-child(13) { animation-delay: 0.26s; }
+ .gallery-just-opened > :nth-child(14) { animation-delay: 0.28s; }
+ .gallery-just-opened > :nth-child(15) { animation-delay: 0.30s; }
+ .gallery-just-opened > :nth-child(16) { animation-delay: 0.32s; }
+ .gallery-just-opened > :nth-child(17) { animation-delay: 0.34s; }
+ .gallery-just-opened > :nth-child(18) { animation-delay: 0.36s; }
+ .gallery-just-opened > :nth-child(19) { animation-delay: 0.38s; }
+ .gallery-just-opened > :nth-child(20) { animation-delay: 0.40s; }
+ .gallery-just-opened > :nth-child(n+21) { animation-delay: 0.42s; }
+
+ /* Tasks list domino-in cascade on open — mirrors gallery / doclib. Applied to
+ #tasks-list in tasks.js on the first render after each open, removed after
+ the longest delay so re-renders feel instant. */
+ .tasks-just-opened > .task-card {
+ animation: section-domino-in 0.36s cubic-bezier(0.22, 1.61, 0.36, 1) backwards;
+ }
+ .tasks-just-opened > :nth-child(1) { animation-delay: 0.02s; }
+ .tasks-just-opened > :nth-child(2) { animation-delay: 0.04s; }
+ .tasks-just-opened > :nth-child(3) { animation-delay: 0.06s; }
+ .tasks-just-opened > :nth-child(4) { animation-delay: 0.08s; }
+ .tasks-just-opened > :nth-child(5) { animation-delay: 0.10s; }
+ .tasks-just-opened > :nth-child(6) { animation-delay: 0.12s; }
+ .tasks-just-opened > :nth-child(7) { animation-delay: 0.14s; }
+ .tasks-just-opened > :nth-child(8) { animation-delay: 0.16s; }
+ .tasks-just-opened > :nth-child(9) { animation-delay: 0.18s; }
+ .tasks-just-opened > :nth-child(10) { animation-delay: 0.20s; }
+ .tasks-just-opened > :nth-child(11) { animation-delay: 0.22s; }
+ .tasks-just-opened > :nth-child(12) { animation-delay: 0.24s; }
+ .tasks-just-opened > :nth-child(13) { animation-delay: 0.26s; }
+ .tasks-just-opened > :nth-child(14) { animation-delay: 0.28s; }
+ .tasks-just-opened > :nth-child(15) { animation-delay: 0.30s; }
+ .tasks-just-opened > :nth-child(16) { animation-delay: 0.32s; }
+ .tasks-just-opened > :nth-child(17) { animation-delay: 0.34s; }
+ .tasks-just-opened > :nth-child(18) { animation-delay: 0.36s; }
+ .tasks-just-opened > :nth-child(19) { animation-delay: 0.38s; }
+ .tasks-just-opened > :nth-child(20) { animation-delay: 0.40s; }
+ .tasks-just-opened > :nth-child(n+21) { animation-delay: 0.42s; }
+
+ /* Document library cascade — same recipe as email library, applied per-tab
+ the first time content loads (chats / archive / research / documents).
+ Module-level Set in documentLibrary.js prevents re-firing on tab swaps
+ or filter/sort re-renders within the same page session. */
+ .doclib-just-opened > .memory-item,
+ .doclib-just-opened > .doclib-card {
+ animation: section-domino-in 0.36s cubic-bezier(0.22, 1.61, 0.36, 1) backwards;
+ }
+ .doclib-just-opened > :nth-child(1) { animation-delay: 0.02s; }
+ .doclib-just-opened > :nth-child(2) { animation-delay: 0.04s; }
+ .doclib-just-opened > :nth-child(3) { animation-delay: 0.06s; }
+ .doclib-just-opened > :nth-child(4) { animation-delay: 0.08s; }
+ .doclib-just-opened > :nth-child(5) { animation-delay: 0.10s; }
+ .doclib-just-opened > :nth-child(6) { animation-delay: 0.12s; }
+ .doclib-just-opened > :nth-child(7) { animation-delay: 0.14s; }
+ .doclib-just-opened > :nth-child(8) { animation-delay: 0.16s; }
+ .doclib-just-opened > :nth-child(9) { animation-delay: 0.18s; }
+ .doclib-just-opened > :nth-child(10) { animation-delay: 0.20s; }
+ .doclib-just-opened > :nth-child(11) { animation-delay: 0.22s; }
+ .doclib-just-opened > :nth-child(12) { animation-delay: 0.24s; }
+ .doclib-just-opened > :nth-child(13) { animation-delay: 0.26s; }
+ .doclib-just-opened > :nth-child(14) { animation-delay: 0.28s; }
+ .doclib-just-opened > :nth-child(15) { animation-delay: 0.30s; }
+ .doclib-just-opened > :nth-child(16) { animation-delay: 0.32s; }
+ .doclib-just-opened > :nth-child(17) { animation-delay: 0.34s; }
+ .doclib-just-opened > :nth-child(18) { animation-delay: 0.36s; }
+ .doclib-just-opened > :nth-child(19) { animation-delay: 0.38s; }
+ .doclib-just-opened > :nth-child(20) { animation-delay: 0.40s; }
+ .doclib-just-opened > :nth-child(n+21) { animation-delay: 0.42s; }
+
+ /* Domino cascade on first open of the email library — mirrors the sidebar
+ .section-just-expanded recipe so list items spring in staggered. Class
+ is applied to #email-lib-grid in emailLibrary.js on the first render
+ only, then removed after the longest delay so re-renders feel instant. */
+ .email-lib-just-opened :is(.doclib-card, .date-section-header) {
+ animation: section-domino-in 0.36s cubic-bezier(0.22, 1.61, 0.36, 1) backwards;
+ }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(1) { animation-delay: 0.02s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(2) { animation-delay: 0.04s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(3) { animation-delay: 0.06s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(4) { animation-delay: 0.08s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(5) { animation-delay: 0.10s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(6) { animation-delay: 0.12s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(7) { animation-delay: 0.14s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(8) { animation-delay: 0.16s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(9) { animation-delay: 0.18s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(10) { animation-delay: 0.20s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(11) { animation-delay: 0.22s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(12) { animation-delay: 0.24s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(13) { animation-delay: 0.26s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(14) { animation-delay: 0.28s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(15) { animation-delay: 0.30s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(16) { animation-delay: 0.32s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(17) { animation-delay: 0.34s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(18) { animation-delay: 0.36s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(19) { animation-delay: 0.38s; }
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(20) { animation-delay: 0.40s; }
+ /* Cap the cascade at 20 — beyond that they animate together so opening a
+ long inbox doesn't take forever to settle. */
+ .email-lib-just-opened :is(.doclib-card, .date-section-header):nth-child(n+21) { animation-delay: 0.42s; }
+
+ /* Inside the email library modal, the grid needs to grow with the modal —
+ but `flex: 1 1 0` collapses to 0 when the parent isn't height-constrained
+ (which is the non-fullscreen default). Use `auto` basis + a sensible
+ `min-height` floor so it shows ~400px naturally and absorbs more when
+ the modal is resized / fullscreened. */
+ #email-lib-modal .doclib-grid {
+ max-height: none;
+ height: auto;
+ flex: 1 1 auto;
+ min-height: 400px;
+ }
+
+ /* ── Mobile compose FAB (email) ──
+ Replaces the top-right "New" button on phones with a round mail-icon button
+ bottom-right that collapses to a circle while the list scrolls and springs
+ back out to "New" when scrolling stops. Desktop is unchanged. */
+ .email-lib-fab { display: none; }
+ @media (max-width: 768px) {
+ /* The absolute FAB anchors to the email panel card. */
+ #email-lib-modal .admin-card { position: relative; }
+ /* Hide the toolbar "New" button — the FAB is the mobile entry point. */
+ #email-lib-compose-btn { display: none; }
+
+ #email-lib-modal .email-lib-fab {
+ --fab-size: 56px;
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ /* Hidden until the email list has rendered; JS adds .fab-revealed to pop
+ it in (scale-from-center). Avoids the button flashing at the top and
+ sliding down before _positionFab() places it. */
+ transform: scale(0);
+ opacity: 0;
+ transform-origin: center center;
+ position: absolute;
+ right: calc(16px + env(safe-area-inset-right, 0px));
+ bottom: calc(18px + env(safe-area-inset-bottom, 0px));
+ height: var(--fab-size);
+ min-width: var(--fab-size);
+ padding: 0 20px 0 18px;
+ border: none;
+ border-radius: 999px;
+ background: var(--accent-primary, var(--red));
+ color: #fff;
+ font-family: inherit;
+ font-size: 15px;
+ font-weight: 600;
+ line-height: 1;
+ cursor: pointer;
+ box-shadow: 0 6px 18px rgba(0,0,0,.38), 0 2px 6px rgba(0,0,0,.28);
+ z-index: 30;
+ pointer-events: auto;
+ /* This (base) transition governs the EXPAND — slower + graceful. */
+ transition:
+ padding 420ms cubic-bezier(0.22, 1, 0.36, 1),
+ box-shadow 240ms ease,
+ transform 140ms ease,
+ background 140ms ease;
+ will-change: padding, transform;
+ }
+ #email-lib-modal .email-lib-fab svg { flex: 0 0 auto; display: block; }
+ #email-lib-modal .email-lib-fab .email-lib-fab-label {
+ overflow: hidden;
+ white-space: nowrap;
+ max-width: 120px;
+ opacity: 1;
+ /* EXPAND timing — label eases out a touch after the width opens up. */
+ transition:
+ max-width 420ms cubic-bezier(0.22, 1, 0.36, 1),
+ opacity 300ms 60ms cubic-bezier(0.22, 1, 0.36, 1),
+ margin 420ms cubic-bezier(0.22, 1, 0.36, 1);
+ }
+ /* Collapsed (while scrolling) → pure circle, icon only. We DON'T set an
+ explicit width: the container is auto-width and shrinks smoothly as the
+ padding + label max-width animate (min-width keeps it circular). Setting a
+ fixed width here made the collapse snap, since auto↔px width can't tween.
+ This (.collapsed) transition governs the COLLAPSE — kept snappy. */
+ #email-lib-modal .email-lib-fab.collapsed {
+ padding: 0;
+ justify-content: center;
+ transition:
+ padding 230ms cubic-bezier(0.4, 0, 0.2, 1),
+ box-shadow 200ms ease,
+ transform 140ms ease;
+ }
+ #email-lib-modal .email-lib-fab.collapsed .email-lib-fab-label {
+ max-width: 0;
+ opacity: 0;
+ margin-left: -9px;
+ transition:
+ max-width 230ms cubic-bezier(0.4, 0, 0.2, 1),
+ opacity 150ms cubic-bezier(0.4, 0, 0.2, 1),
+ margin 230ms cubic-bezier(0.4, 0, 0.2, 1);
+ }
+ /* Entrance: circle-expand-from-middle pop, played once when revealed. No
+ `forwards` fill so the resting transform (scale 1) comes from this rule —
+ that keeps the :active press transform working afterwards. */
+ #email-lib-modal .email-lib-fab.fab-revealed {
+ transform: scale(1);
+ opacity: 1;
+ animation: emailFabPop 380ms cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ #email-lib-modal .email-lib-fab:active {
+ transform: scale(0.93);
+ filter: brightness(0.92);
+ box-shadow: 0 3px 10px rgba(0,0,0,.4);
+ }
+ }
+ @keyframes emailFabPop {
+ from { transform: scale(0); opacity: 0; }
+ 60% { transform: scale(1.06); opacity: 1; }
+ to { transform: scale(1); opacity: 1; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ #email-lib-modal .email-lib-fab,
+ #email-lib-modal .email-lib-fab .email-lib-fab-label { transition-duration: 1ms; }
+ #email-lib-modal .email-lib-fab.fab-revealed { animation: none; }
+ }
+ /* When the modal-content has explicit height (fullscreen or user-resized),
+ drop the floor so the grid sizes purely from flex. */
+ #email-lib-modal.email-lib-fullscreen .doclib-grid,
+ #email-lib-modal .modal-content[style*="height"] .doclib-grid {
+ min-height: 0;
+ }
+ /* Document library: same fix as the email library (#74). When fullscreened
+ the modal-content gets an inline `height: 100vh`, but the inner
+ .doclib-grid stays capped at the 400px default so the list looks like a
+ tiny strip floating in a giant empty modal. Mirror the email recipe:
+ make the modal a flex column, give the body/admin-card claim of the
+ remaining height, and let the grid take the rest. Scoped to the
+ fullscreen class so windowed-mode layout is unchanged. */
+ /* Inner flex chain that lets the chats/documents grid claim the full
+ remaining height of the modal. Applies in BOTH fullscreen AND
+ right-docked states — without the docked state included, dragging a
+ fullscreen doclib to the right snap zone breaks the flex layout
+ because exitFullscreen removes .doclib-fullscreen, and the grid
+ falls back to its base max-height: 400px showing only ~8 items.
+ The CSS variable :is() selector lets both states share one rule. */
+ #doclib-modal.doclib-fullscreen .doclib-modal-content,
+ #doclib-modal.modal-right-docked .doclib-modal-content,
+ #doclib-modal.modal-left-docked .doclib-modal-content {
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ }
+ /* Fullscreen positioning — scoped to NOT apply when also right-docked.
+ Without this exclusion, dragging a fullscreen doclib to the right snap
+ zone keeps .doclib-fullscreen on the modal and these !important rules
+ override the dock's inline styles, leaving the modal stuck fullscreen
+ instead of becoming a side panel. */
+ #doclib-modal.doclib-fullscreen:not(.modal-right-docked) .doclib-modal-content {
+ position: fixed !important;
+ top: 0 !important;
+ left: calc(var(--icon-rail-w, 48px) + var(--sidebar-w, 0px)) !important;
+ right: 0 !important;
+ bottom: 0 !important;
+ width: auto !important;
+ max-width: none !important;
+ height: 100vh !important;
+ max-height: 100vh !important;
+ border-radius: 0 !important;
+ transform: none !important;
+ }
+ #doclib-modal.doclib-fullscreen .modal-header,
+ #doclib-modal.doclib-fullscreen .lib-tabs,
+ #doclib-modal.modal-right-docked .modal-header,
+ #doclib-modal.modal-right-docked .lib-tabs,
+ #doclib-modal.modal-left-docked .modal-header,
+ #doclib-modal.modal-left-docked .lib-tabs {
+ flex: 0 0 auto;
+ }
+ #doclib-modal.doclib-fullscreen .modal-body,
+ #doclib-modal.modal-right-docked .modal-body,
+ #doclib-modal.modal-left-docked .modal-body {
+ flex: 1 1 0;
+ min-height: 0;
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ }
+ #doclib-modal.doclib-fullscreen .admin-card,
+ #doclib-modal.modal-right-docked .admin-card,
+ #doclib-modal.modal-left-docked .admin-card {
+ flex: 1 1 0;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ }
+ #doclib-modal.doclib-fullscreen .doclib-grid:not(:has(.doclib-card-expanded)),
+ #doclib-modal.modal-right-docked .doclib-grid:not(:has(.doclib-card-expanded)),
+ #doclib-modal.modal-left-docked .doclib-grid:not(:has(.doclib-card-expanded)) {
+ max-height: none;
+ height: auto;
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow-y: auto;
+ }
+ /* "Reply" docks the open email modal to the left as a sidebar so the doc
+ panel (which slides in from the right of the chat area) is visible
+ side-by-side. The .modal backdrop is already pointer-events:none for
+ email modals — only the content takes pointer events — so the chat /
+ doc panel underneath stays interactive. */
+ .modal.email-snap-left {
+ align-items: stretch;
+ justify-content: flex-start;
+ left: 0 !important;
+ width: 100% !important;
+ }
+ .modal.email-snap-left .modal-content {
+ left: var(--email-doc-split-left-x, 0px) !important;
+ width: var(--email-doc-split-email-w, 420px) !important;
+ max-width: var(--email-doc-split-email-w, 420px) !important;
+ border-right: 1px solid var(--border);
+ box-shadow: 4px 0 14px rgba(0, 0, 0, 0.18);
+ border-radius: 0;
+ }
+ @media (min-width: 769px) {
+ body.email-doc-split-active.doc-view #email-lib-modal,
+ body.email-doc-split-active.doc-view.email-front #email-lib-modal,
+ body.email-doc-split-active.doc-view .modal[id^="email-reader-"],
+ body.email-doc-split-active.doc-view.email-front .modal[id^="email-reader-"] {
+ z-index: 150 !important;
+ }
+ body.email-doc-split-active #email-lib-modal.email-snap-left,
+ body.email-doc-split-active #email-lib-modal.modal-left-docked {
+ left: var(--email-doc-split-left-x, 0px) !important;
+ width: var(--email-doc-split-email-w, 420px) !important;
+ overflow: hidden !important;
+ z-index: 155 !important;
+ }
+ body.email-doc-split-active #email-lib-modal.email-snap-left:not(.modal-dragging) .modal-content,
+ body.email-doc-split-active #email-lib-modal.modal-left-docked:not(.modal-dragging) .modal-content,
+ body.email-doc-split-active .modal[id^="email-reader-"].email-snap-left:not(.modal-dragging) .modal-content,
+ body.email-doc-split-active .modal[id^="email-reader-"].modal-left-docked:not(.modal-dragging) .modal-content {
+ position: absolute !important;
+ left: 0 !important;
+ top: 0 !important;
+ bottom: 0 !important;
+ right: auto !important;
+ width: var(--email-doc-split-email-w, 420px) !important;
+ max-width: var(--email-doc-split-email-w, 420px) !important;
+ height: 100vh !important;
+ max-height: 100vh !important;
+ transform: none !important;
+ margin: 0 !important;
+ }
+ body.email-doc-split-active.doc-view .doc-divider {
+ display: none !important;
+ }
+ body.email-doc-split-active.doc-view .doc-editor-pane {
+ position: fixed !important;
+ left: var(--email-doc-split-right-x, 420px) !important;
+ right: var(--right-dock-w, 0px) !important;
+ top: 0 !important;
+ bottom: 0 !important;
+ width: auto !important;
+ max-width: none !important;
+ height: 100vh !important;
+ z-index: 260 !important;
+ margin-top: 0 !important;
+ transform: none !important;
+ border-left: none !important;
+ }
+ }
+
+ /* Edge docking. Docked panels are fixed to the viewport edge; the workspace
+ panes reserve room with margins so left + right docks can be active at the
+ same time without skewing the entire body box. */
+ body.right-dock-active {
+ padding-right: 0;
+ }
+ body.left-dock-active {
+ padding-left: 0;
+ }
+ body.left-dock-active:not(.email-doc-split-active) .chat-container {
+ margin-left: var(--left-dock-w, 0px);
+ }
+ body.right-dock-active .chat-container,
+ body.right-dock-active:not(.email-doc-split-active) .doc-editor-pane {
+ margin-right: var(--right-dock-w, 0px);
+ }
+ .modal.modal-right-docked {
+ align-items: stretch;
+ justify-content: flex-end;
+ }
+ .modal.modal-right-docked .modal-content {
+ border-left: 1px solid var(--border);
+ box-shadow: -4px 0 14px rgba(0, 0, 0, 0.18);
+ border-radius: 0;
+ }
diff --cc static/css/13-image-editor.css
index 000000000,d759ed7d3..257e2805e
mode 000000,100644..100644
--- a/static/css/13-image-editor.css
+++ b/static/css/13-image-editor.css
@@@ -1,0 -1,4823 +1,4902 @@@
+ /* 13-image-editor - part of the former static/style.css.
+ *
+ * The stylesheet is split by area, but the split is mechanical: rules were
+ * moved verbatim and NOT regrouped. The numeric prefix is the load order, and
+ * that order is what preserves the cascade. A rule sits in the file its
+ * original position fell into, so an area's rules are not all in its file and
+ * a file is not only that area's rules.
+ *
+ * Do not reorder the <link> tags in static/index.html, and do not move a rule
+ * between files: with 1,151 redeclarations and 1,886 !important in this
+ * cascade, either can change which declaration wins.
+ *
+ * static/index.html and the PRECACHE list in static/sw.js must agree on this
+ * order. tests/test_static_stylesheet_manifest.py and
+ * tests/test_css_computed_style_snapshot.py fail if that drifts.
+ */
+ .ge-draft-status[data-state="pending"],
+ .ge-draft-status[data-state="saving"] { color: color-mix(in srgb, var(--accent, var(--red)) 75%, var(--fg)); }
+ .ge-draft-status[data-state="saved"] { color: color-mix(in srgb, var(--color-success, #4ade80) 78%, var(--fg)); }
+ .ge-draft-status[data-state="error"] { color: var(--color-error, #ef4444); }
+ /* "ALPHA" badge — flags the editor as in-development. */
+ .ge-alpha-badge {
+ flex-shrink: 0;
+ font-size: 9px;
+ font-weight: 700;
+ letter-spacing: 0.1em;
+ line-height: 1;
+ padding: 3px 6px;
+ margin-right: 4px;
+ border-radius: 4px;
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 16%, transparent);
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 40%, transparent);
+ text-transform: uppercase;
+ user-select: none;
+ cursor: default;
+ }
+ @media (max-width: 768px) {
+ /* Keep the toolbar tight on mobile — badge stays but shrinks. */
+ .ge-alpha-badge { font-size: 8px; padding: 2px 5px; margin-right: 2px; }
+ }
+ .ge-diffusion-status {
+ font-size: 11px;
+ cursor: pointer;
+ padding: 2px 8px;
+ border-radius: 4px;
+ transition: all 0.15s;
+ white-space: nowrap;
+ }
+ .ge-diffusion-status.online {
+ color: var(--color-success, #4ade80);
+ }
+ .ge-diffusion-status.offline {
+ color: var(--color-error, #ef4444);
+ opacity: 0.7;
+ }
+ .ge-diffusion-status.offline:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--color-error) 10%, transparent);
+ }
+ .ge-topbar-fill {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ color: var(--accent, var(--red));
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 50%, var(--border));
+ background: color-mix(in srgb, var(--accent, var(--red)) 12%, transparent);
+ }
+ .ge-topbar-fill:hover {
+ background: color-mix(in srgb, var(--accent, var(--red)) 22%, transparent);
+ border-color: var(--accent, var(--red));
+ }
+ /* Mask-color swatch in the topbar — small label + circular swatch so
+ the user can pick a contrasting overlay colour from anywhere. */
+ .ge-topbar-mask-color-wrap {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ cursor: pointer;
+ }
+ .ge-topbar-mask-color-label {
+ font-size: 10px;
+ opacity: 0.6;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ }
+ .ge-topbar-mask-color {
+ width: 18px;
+ height: 18px;
+ flex: 0 0 18px;
+ }
+ .ge-topbar-mask-color.cp-swatch-input {
+ width: 18px;
+ height: 18px;
+ flex: 0 0 18px;
+ border-radius: 50%;
+ padding: 0;
+ }
+ .ge-topbar-sep {
+ width: 1px;
+ height: 16px;
+ background: var(--border);
+ margin: 0 4px;
+ }
+
+ /* Editor body (toolbar + canvas + panel) */
+ .ge-editor-body {
+ display: flex;
+ flex: 1;
+ min-height: 0;
+ overflow: hidden;
+ position: relative;
+ }
++.ge-editor-footer {
++ display: flex;
++ align-items: center;
++ justify-content: space-between;
++ gap: 10px;
++ min-height: 34px;
++ padding: 3px 10px;
++ box-sizing: border-box;
++ flex: 0 0 auto;
++ border-top: 1px solid var(--border);
++ background: var(--panel);
++}
++.ge-editor-footer .ge-canvas-size {
++ min-width: 0;
++ font-size: 11px;
++ color: color-mix(in srgb, var(--fg) 65%, transparent);
++}
++.ge-footer-zoom {
++ display: flex;
++ align-items: center;
++ gap: 5px;
++ margin-left: auto;
++ white-space: nowrap;
++}
++.ge-footer-zoom > .ge-btn { min-width: 28px; min-height: 26px; }
++.ge-footer-zoom .ge-zoom-stack { flex-direction: row; gap: 5px; min-width: 56px; }
++.ge-footer-zoom .ge-zoom-label { top: 0; left: 0; font-size: 11px; letter-spacing: 0; opacity: 0.8; }
++.ge-footer-zoom .ge-zoom-glyph { left: 0; }
++.ge-footer-zoom .ge-stacked-btn { min-width: 48px; }
+ .gallery-editor-container {
+ flex: 1;
+ min-height: 0;
+ display: none;
+ }
++.gallery-editor-container input[type="number"] {
++ -moz-appearance: textfield;
++ appearance: textfield;
++}
++.gallery-editor-container input[type="number"]::-webkit-inner-spin-button,
++.gallery-editor-container input[type="number"]::-webkit-outer-spin-button {
++ -webkit-appearance: none;
++ appearance: none;
++ margin: 0;
++}
+
+ .ge-toolbar {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ /* Asymmetric horizontal padding shifts the whole column 4 px left —
+ buttons, hover backgrounds, active highlight pills, and section
+ separators all move together. */
+ padding: 8px 8px 8px 0;
+ background: var(--panel);
+ border-right: 1px solid var(--border);
+ width: 64px;
+ flex-shrink: 0;
+ min-height: 0;
+ overflow-x: hidden;
+ overflow-y: auto;
+ scrollbar-width: none;
+ }
+ .ge-toolbar::-webkit-scrollbar { display: none; }
+ .ge-tool-sep {
+ font-size: 8px;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--color-muted);
+ text-align: center;
+ padding: 8px 0 4px;
+ border-top: 1px solid var(--border);
+ margin-top: 4px;
+ opacity: 0.6;
+ flex-shrink: 0;
+ }
+ /* All tool buttons share a fixed height so the column reads as a clean
+ grid. Long labels (e.g. "Remove BG") truncate with ellipsis instead of
+ wrapping to two lines and making one button taller than the others. */
+ .ge-tool-btn {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 2px;
+ padding: 0 2px;
+ height: 42px;
+ flex-shrink: 0;
+ border: none;
+ background: none;
+ color: var(--fg);
+ opacity: 0.6;
+ cursor: pointer;
+ border-radius: 6px;
+ transition: background 0.15s, opacity 0.15s;
+ }
+ .ge-tool-btn { position: relative; }
+ /* Hover background is now a pseudo so we can shift it 2 px left
+ independently from the button's own bounds (which contain the icon
+ and label at their already-shifted positions). */
+ .ge-tool-btn:hover { opacity: 0.85; }
+ .ge-tool-btn.active {
+ opacity: 1;
+ color: var(--red);
+ background: none;
+ /* Padding stays the same as inactive buttons so the icon stays
+ horizontally aligned with its neighbors. The taller highlight is
+ drawn by ::before so it can extend up/down without pushing the
+ button or shifting the icon. */
+ }
+ /* Tool button contents stay above the active highlight pseudo. Also
+ shifted an additional 2 px left so the icon + label sit further inside
+ the highlight pill (which still anchors to the button bounds). */
+ .ge-tool-btn > * { position: relative; z-index: 1; left: -2px; }
+ .ge-tool-icon { font-size: 18px; line-height: 1; }
+ .ge-tool-label { font-size: 10px; line-height: 1.25; }
+ /* AI badge — same ✦ glyph the Enhance tool uses, pinned to the top-
+ left of any tool button marked `ai: true`. Same color as the icon
+ itself (inherits foreground) so it reads as part of the tool, not
+ a flag. */
+ .ge-tool-ai {
+ position: absolute !important;
+ top: 1px;
+ z-index: 2;
+ color: inherit;
+ opacity: 0.7;
+ pointer-events: none;
+ font-size: 11px;
+ line-height: 1;
+ font-weight: 700;
+ left: 3px !important;
+ }
+ .ge-tool-btn.is-ai:hover .ge-tool-ai { opacity: 0.95; }
+ .ge-tool-btn.is-ai.active .ge-tool-ai { opacity: 1; }
+ /* Inline ✦ marker used on AI action buttons (Generate, Remove, etc.)
+ so they read as AI-backed at a glance — same glyph as .ge-tool-ai
+ in the toolbar, just sitting inline next to the label. */
+ .ge-btn-ai-mark {
+ display: inline-block;
+ font-size: 11px;
+ line-height: 1;
+ font-weight: 700;
+ opacity: 0.75;
+ margin-right: 1px;
+ }
+
+ /* Per-tool clear-selection badge — shows a tiny X in the top-right of
+ the Lasso / Wand button when each holds a selection. Click clears
+ the selection without switching tools (handler stops propagation). */
+ .ge-tool-clear {
+ position: absolute !important;
+ top: 3px;
+ right: 3px;
+ width: 14px;
+ height: 14px;
+ display: none;
+ align-items: center;
+ justify-content: center;
+ border-radius: 50%;
+ color: #fff;
+ background: var(--red);
+ cursor: pointer;
+ opacity: 0.95;
+ z-index: 2;
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--red) 70%, transparent),
+ 0 1px 4px color-mix(in srgb, var(--red) 50%, transparent);
+ transition: opacity 0.12s, transform 0.12s, box-shadow 0.12s;
+ left: auto !important;
+ }
+ .ge-tool-clear:hover {
+ opacity: 1;
+ transform: scale(1.15);
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--red) 80%, transparent),
+ 0 2px 6px color-mix(in srgb, var(--red) 60%, transparent);
+ }
+
+ /* Aspect-ratio placeholder shown while a draft is loading. */
+ .ge-canvas-placeholder {
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ border: 1px dashed color-mix(in srgb, var(--fg) 20%, transparent);
+ border-radius: 4px;
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ z-index: 1;
+ }
+ /* Canvas area (center) */
+ .ge-canvas-area {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: auto;
+ background: var(--bg);
+ position: relative;
+ min-width: 0;
+ /* Stop touch interactions inside the editor from dragging the whole
+ page (or the gallery modal). Touches on the canvas are owned by the
+ editor's drawing logic — no native pan/zoom. */
+ overscroll-behavior: contain;
+ }
+ .ge-ruler {
+ position: absolute;
+ z-index: 16;
+ touch-action: none;
+ user-select: none;
+ }
+ .ge-ruler-horizontal {
+ top: 0;
+ left: 18px;
+ right: 0;
+ width: calc(100% - 18px);
+ height: 18px;
+ cursor: row-resize;
+ }
+ .ge-ruler-vertical {
+ top: 18px;
+ bottom: 0;
+ left: 0;
+ width: 18px;
+ height: calc(100% - 18px);
+ cursor: col-resize;
+ }
+ .ge-ruler-corner {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 17;
+ width: 18px;
+ height: 18px;
+ background: var(--panel);
+ border-right: 1px solid var(--border);
+ border-bottom: 1px solid var(--border);
+ box-sizing: border-box;
+ }
+ .ge-wand-loading {
+ position: absolute;
+ inset: 0;
+ z-index: 25;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: color-mix(in srgb, var(--bg) 30%, transparent);
+ pointer-events: none;
+ }
+ .ge-ai-command {
+ position: absolute;
+ left: 50%;
+ bottom: 14px;
+ z-index: 18;
+ width: min(430px, calc(100% - 28px));
+ transform: translateX(-50%);
+ padding: 7px;
+ box-sizing: border-box;
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 42%, var(--border));
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--panel, var(--bg)) 94%, transparent);
+ box-shadow: 0 8px 22px color-mix(in srgb, #000 26%, transparent);
+ backdrop-filter: blur(8px);
+ transition: bottom 0.16s ease, opacity 0.16s ease, border-color 0.16s ease, box-shadow 0.16s ease;
+ }
+ .ge-ai-command-toggle {
+ width: 100%;
+ height: 28px;
+ display: none;
+ align-items: center;
+ justify-content: center;
+ gap: 5px;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--accent, var(--red));
+ font: inherit;
+ font-size: 11px;
+ font-weight: 600;
+ cursor: pointer;
+ }
+ .ge-ai-command-toggle-caret {
+ opacity: 0.7;
+ flex-shrink: 0;
+ }
+ .ge-ai-command-head {
+ display: flex;
+ align-items: center;
+ min-height: 24px;
+ padding: 0 2px 5px;
+ color: var(--fg);
+ }
+ .ge-ai-command-title {
+ margin-left: 5px;
+ font-size: 11px;
+ font-weight: 650;
+ }
+ .ge-ai-command-scope {
+ margin-left: 7px;
+ padding-left: 7px;
+ border-left: 1px solid var(--border);
+ color: var(--fg-muted);
+ font-size: 9px;
+ line-height: 1;
+ text-transform: uppercase;
+ }
+ .ge-ai-command-collapsed {
+ bottom: -16px;
+ width: auto;
+ min-width: 102px;
+ padding: 2px 9px;
+ opacity: 0.32;
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 18%, var(--border));
+ box-shadow: 0 3px 10px color-mix(in srgb, #000 16%, transparent);
+ }
+ .ge-canvas-area:hover .ge-ai-command-collapsed,
+ .ge-ai-command-collapsed:hover,
+ .ge-ai-command-collapsed:focus-within {
+ bottom: 10px;
+ opacity: 0.94;
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 42%, var(--border));
+ box-shadow: 0 8px 22px color-mix(in srgb, #000 24%, transparent);
+ }
+ .ge-ai-command-form {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .ge-ai-command-input {
+ flex: 1 1 auto;
+ min-width: 0;
+ height: 32px;
+ box-sizing: border-box;
+ padding: 0 9px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--bg) 76%, #000 24%);
+ color: var(--fg);
+ font: inherit;
+ font-size: 12px;
+ }
+ .ge-ai-command-input:focus {
+ outline: none;
+ border-color: var(--accent, var(--red));
+ }
+ .ge-ai-command-clear {
+ position: relative;
+ top: -2px;
+ width: 26px;
+ height: 32px;
+ flex: 0 0 26px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ margin-left: -38px;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--fg-muted);
+ cursor: pointer;
+ padding: 0;
+ z-index: 1;
+ }
+ .ge-ai-command-clear:hover {
+ color: var(--fg);
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ }
+ .ge-ai-command-run {
+ position: relative;
+ top: -2px;
+ background: var(--send-btn-bg, var(--red));
+ color: #fff;
+ border: none;
+ border-radius: 8px;
+ min-width: 32px;
+ width: 32px;
+ height: 32px !important;
+ padding: 0;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex: 0 0 auto;
+ transition: background 0.25s, opacity 0.12s;
+ overflow: hidden;
+ }
+ .ge-ai-command-run:hover {
+ background: var(--send-btn-hover, color-mix(in srgb, var(--red) 80%, white));
+ }
+ .ge-ai-command-busy .ge-ai-command-run {
+ opacity: 0.58;
+ cursor: wait;
+ }
+ .ge-ai-command-busy .ge-ai-command-run svg {
+ display: none;
+ }
+ .ge-ai-command-close {
+ width: 28px;
+ height: 32px;
+ flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ border: 0;
+ border-radius: 8px;
+ background: transparent;
+ color: var(--fg);
+ opacity: 0.52;
+ cursor: pointer;
+ padding: 0;
+ margin-left: auto;
+ }
+ .ge-ai-command-close:hover {
+ opacity: 0.9;
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ }
+ .ge-ai-command-suggestions {
+ position: absolute;
+ left: 7px;
+ right: 7px;
+ bottom: calc(100% - 2px);
+ z-index: 2;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ max-height: 236px;
+ overflow: auto;
+ padding: 5px;
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 34%, var(--border));
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--panel, var(--bg)) 97%, #000 3%);
+ box-shadow: 0 10px 28px color-mix(in srgb, #000 28%, transparent);
+ }
+ .ge-ai-command-suggestion {
+ width: 100%;
+ display: grid;
+ grid-template-columns: 38px minmax(82px, auto) minmax(0, 1fr);
+ align-items: center;
+ gap: 8px;
+ min-height: 28px;
+ padding: 4px 7px;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--fg);
+ text-align: left;
+ cursor: pointer;
+ font: inherit;
+ }
+ .ge-ai-command-suggestion:hover,
+ .ge-ai-command-suggestion.active {
+ background: color-mix(in srgb, var(--accent, var(--red)) 16%, transparent);
+ }
+ .ge-ai-command-suggestion-kind {
+ min-width: 0;
+ overflow: hidden;
+ color: var(--accent, var(--red));
+ font-size: 8px;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ }
+ .ge-ai-command-suggestion-main {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 11px;
+ font-weight: 650;
+ }
+ .ge-ai-command-suggestion-hint {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--fg-muted);
+ font-size: 10px;
+ }
+ .ge-ai-command-status {
+ margin-top: 4px;
+ font-size: 10px;
+ line-height: 1.3;
+ color: var(--fg-muted);
+ }
+ .ge-ai-command-status[data-kind="running"] {
+ color: var(--accent, var(--red));
+ }
+ .ge-ai-command-status[data-kind="done"] {
+ color: var(--green, #4caf50);
+ }
+ .ge-ai-command-status[data-kind="error"] {
+ color: var(--red, #e5484d);
+ }
+ /* Loading overlay shown while a large image is decoding — centered
+ whirlpool + "Loading" caption over a translucent dim. */
+ .ge-loading-overlay {
+ position: absolute;
+ inset: 0;
+ z-index: 20;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: color-mix(in srgb, var(--bg) 70%, transparent);
+ pointer-events: none;
+ }
+ /* Full-editor cover (project load): above the toolbar/panel and near-opaque so
+ the top toolbar/old content doesn't peek through while loading. */
+ .ge-loading-overlay-full {
+ z-index: 200;
+ background: color-mix(in srgb, var(--bg) 92%, transparent);
+ pointer-events: auto;
+ }
+ .ge-loading-overlay .ge-loading-inner {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 16px;
+ border-radius: 10px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ box-shadow: 0 4px 14px color-mix(in srgb, var(--fg) 18%, transparent);
+ }
+ .ge-loading-overlay .ge-loading-text {
+ font-size: 12px;
+ opacity: 0.8;
+ }
+
+ /* Shortcuts cheatsheet (toggled by `?` or the keyboard icon in the top bar). */
+ #ge-shortcuts-overlay {
+ position: absolute;
+ inset: 0;
+ z-index: 50;
+ background: color-mix(in srgb, var(--bg) 70%, transparent);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 12px;
+ }
+ #ge-shortcuts-overlay[hidden] { display: none; }
+ .ge-shortcuts-card {
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ padding: 14px 18px 12px;
+ box-shadow: 0 8px 30px color-mix(in srgb, var(--fg) 25%, transparent);
+ width: min(720px, 92vw);
+ max-height: 86vh;
+ overflow-y: auto;
+ color: var(--fg);
+ }
+ .ge-shortcuts-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 10px;
+ font-weight: 600;
+ font-size: 13px;
+ }
+ .ge-shortcuts-grid {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: 14px 24px;
+ }
+ @media (min-width: 720px) {
+ .ge-shortcuts-grid { grid-template-columns: repeat(4, 1fr); }
+ }
+ .ge-shortcuts-col h5 {
+ margin: 0 0 6px;
+ font-size: 11px;
+ opacity: 0.6;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ font-weight: 600;
+ }
+ .ge-shortcuts-foot {
+ margin-top: 12px;
+ font-size: 11px;
+ opacity: 0.55;
+ text-align: center;
+ }
+ .ge-main-canvas {
+ /* Cursor is managed entirely by JS so each tool can show its own
+ icon (move arrow, circle overlay, etc.) without CSS fighting it. */
+ image-rendering: pixelated;
+ box-shadow: 0 2px 12px rgba(0,0,0,0.3);
+ background: repeating-conic-gradient(#808080 0% 25%, #a0a0a0 0% 50%) 50% / 16px 16px;
+ }
+
+ /* Transform-overlay canvas — sits over the main canvas with extra
+ margin so resize / rotation handles can render OUTSIDE the image
+ bounds. Pointer events disabled so it doesn't intercept clicks. */
+ .ge-transform-overlay {
+ position: absolute;
+ image-rendering: pixelated;
+ pointer-events: none;
+ z-index: 5;
+ }
+ .ge-selection-overlay {
+ position: absolute;
+ image-rendering: pixelated;
+ pointer-events: none;
+ z-index: 4;
+ }
+ .ge-quick-mask-bar {
+ position: absolute;
+ top: 10px;
+ left: 50%;
+ transform: translateX(-50%);
+ z-index: 18;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 32px;
+ padding: 4px 5px 4px 10px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--panel);
+ box-shadow: 0 4px 16px rgba(0,0,0,0.24);
+ color: var(--fg);
+ font-size: 11px;
+ white-space: nowrap;
+ }
+ .ge-quick-mask-label { font-weight: 600; }
+ .ge-quick-mask-tools { display: flex; }
+ .ge-quick-mask-tool,
+ .ge-quick-mask-done {
+ min-height: 24px;
+ padding: 2px 8px;
+ border: 1px solid var(--border);
+ background: var(--bg);
+ color: inherit;
+ font: inherit;
+ cursor: pointer;
+ }
+ .ge-quick-mask-tool:first-child { border-radius: 4px 0 0 4px; }
+ .ge-quick-mask-tool:last-child { border-radius: 0 4px 4px 0; border-left: 0; }
+ .ge-quick-mask-tool.active { background: var(--accent); color: #fff; border-color: var(--accent); }
+ .ge-quick-mask-done { border-radius: 4px; }
+ .ge-marquee-constraint-row {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr);
+ align-items: center;
+ gap: 5px 7px;
+ font-size: 10px;
+ }
+ .ge-marquee-constraint-row > select {
+ min-width: 0;
+ height: 26px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--fg);
+ font: inherit;
+ }
+ .ge-marquee-dimensions {
+ grid-column: 1 / -1;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) 26px;
+ gap: 5px;
+ align-items: center;
+ }
+ .ge-marquee-dimensions label {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr);
+ align-items: center;
+ gap: 4px;
+ }
+ .ge-marquee-dimensions input {
+ width: 100%;
+ min-width: 0;
+ height: 26px;
+ padding: 2px 5px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--fg);
+ font: inherit;
+ }
+ .ge-marquee-dimensions .ge-icon-btn { width: 26px; height: 26px; }
+
+ /* Right panel */
+ .ge-right-panel {
+ width: 250px;
+ flex-shrink: 0;
+ display: flex;
+ flex-direction: column;
+ border-left: 1px solid var(--border);
+ background: var(--panel);
+ /* The whole panel scrolls so every tool control is reachable; the
+ layers-actions row uses position:sticky to stay pinned at the
+ bottom of the viewport while scrolling. */
+ overflow-y: auto;
+ overflow-x: hidden;
+ }
+
+ /* Controls */
+ .ge-controls {
+ flex: 0 0 auto;
+ padding: 10px 10px 6px;
+ border-bottom: 1px solid var(--border);
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .ge-layer-geometry-section {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ #ge-layer-geometry-name {
+ margin-left: auto;
+ min-width: 0;
+ max-width: 110px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--color-muted);
+ font-size: 9px;
+ font-weight: 400;
+ text-transform: none;
+ }
+ .ge-layer-geometry-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 5px;
+ }
+ .ge-layer-geometry-grid label {
+ display: grid;
+ grid-template-columns: 12px minmax(0, 1fr);
+ align-items: center;
+ gap: 2px;
+ min-width: 0;
+ color: var(--color-muted);
+ font-size: 9px;
+ }
+ .ge-layer-geometry-grid input {
+ width: 100%;
+ height: 26px;
+ box-sizing: border-box;
+ min-width: 0;
+ padding: 3px 4px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--fg);
+ font: inherit;
+ text-align: right;
+ appearance: textfield;
+ }
+ .ge-layer-geometry-grid input:focus { outline: none; border-color: var(--red); }
+ .ge-layer-geometry-grid input[readonly] { opacity: 0.58; cursor: default; }
+ @media (max-width: 700px) {
+ .ge-layer-geometry-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
+ }
+ /* Brush controls (Color + Size) — give the two rows breathing room
+ between them, since neither sits inside a separator-bordered section. */
+ #ge-brush-controls {
+ display: flex;
+ flex-direction: column;
+ gap: 9px;
+ }
+ .ge-brush-pressure-row { justify-content: space-between; gap: 6px; }
+ .ge-pressure-option { display: inline-flex; align-items: center; gap: 4px; font-size: 10px; opacity: 0.7; }
+ .ge-pressure-option .toggle-switch { width: 24px; height: 14px; }
+ .ge-pressure-option .toggle-slider::before { width: 10px; height: 10px; }
+ .ge-pressure-option .toggle-switch input:checked + .toggle-slider::before { transform: translateX(10px); }
+ .ge-brush-preset-row select { flex: 1 1 auto; min-width: 0; }
+ .ge-brush-preset-row .ge-btn { flex: 0 0 auto; }
+ .ge-text-section,
+ .ge-shape-section {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ min-width: 0;
+ }
+ .ge-shape-gradient-extra-stops {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ .ge-gradient-extra-stop {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto;
+ gap: 6px;
+ align-items: end;
+ }
+ .ge-gradient-stop-remove {
+ min-width: 28px;
+ height: 28px;
+ padding: 0 6px;
+ }
+ .ge-text-section textarea,
+ .ge-text-section select,
+ .ge-text-section input[type="number"],
+ .ge-shape-section input[type="number"] {
+ box-sizing: border-box;
+ min-width: 0;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--fg);
+ font: inherit;
+ }
+ .ge-text-section textarea {
+ width: 100%;
+ min-height: 58px;
+ resize: vertical;
+ padding: 6px 7px;
+ line-height: 1.35;
+ }
+ .ge-text-grid {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(56px, 0.42fr) auto;
+ gap: 6px;
+ align-items: end;
+ }
+ .ge-text-field {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ min-width: 0;
+ font-size: 9px;
+ color: var(--color-muted);
+ }
+ .ge-text-field select,
+ .ge-text-field input { width: 100%; height: 28px; padding: 3px 6px; }
+ .ge-text-format-row { gap: 4px; }
+ .ge-text-toggle {
+ width: auto;
+ min-width: 24px;
+ flex: 1 1 24px;
+ height: 28px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: transparent;
+ color: var(--fg);
+ cursor: pointer;
+ }
+ .ge-text-toggle:hover { background: color-mix(in srgb, var(--fg) 7%, transparent); }
+ .ge-text-toggle.active {
+ color: var(--red);
+ border-color: color-mix(in srgb, var(--red) 55%, var(--border));
+ background: color-mix(in srgb, var(--red) 12%, transparent);
+ }
+ .ge-text-format-sep { width: 1px; height: 20px; background: var(--border); margin: 0 2px; }
+ .ge-shape-types { display: flex; gap: 4px; }
+ .ge-shape-sides-field { max-width: 90px; }
+ .ge-direct-text-editor {
+ position: fixed;
+ z-index: 10020;
+ box-sizing: border-box;
+ padding: 4px;
+ overflow: hidden;
+ resize: both;
+ border: 1px dashed var(--red);
+ outline: 1px solid color-mix(in srgb, var(--red) 24%, transparent);
+ border-radius: 2px;
+ background: color-mix(in srgb, var(--bg) 8%, transparent);
+ caret-color: var(--red);
+ transform-origin: top left;
+ box-shadow: none;
+ }
+
+ /* Floating Transform popup — horizontal layout, draggable from
+ anywhere on the popup (matches the FX / adjust popups). Defaults
+ to the right side of the editor (over the layers panel). */
+ /* Match the .ge-adj-popup layout convention: icon + title + [_][×]
+ header bar, then the body. Drag from the header (same as FX popups). */
+ .ge-transform-popup {
+ position: absolute;
+ z-index: 10020;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 0 0 8px;
+ background: color-mix(in srgb, var(--panel) 98%, var(--bg));
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 42%, var(--border));
+ border-radius: 8px;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
+ backdrop-filter: blur(6px);
+ user-select: none;
+ }
+ .ge-transform-popup-head {
+ /* Inherits .ge-adj-head styling — flex row, icon + title + buttons,
+ bottom border, grab cursor — with the title nudged down 2px for
+ visual balance and explicit horizontal padding so the icon doesn't
+ hug the left edge. */
+ display: flex !important;
+ align-items: center;
+ gap: 6px;
+ padding: 8px 12px;
+ padding-top: 10px;
+ touch-action: none;
+ cursor: grab;
+ }
+ .ge-transform-popup-head:active { cursor: grabbing; }
+ .ge-transform-popup-head .ge-head-btns { margin-left: auto !important; }
+ .ge-transform-popup-head .ge-adj-title { position: relative; top: 2px; }
+ /* Icon nudged 4px lower than the title baseline so it reads as the
+ row's anchor rather than floating above it. */
+ .ge-transform-popup-head .ge-adj-icon { position: relative; top: 4px; }
+ /* Mobile-only: shift the head content UP to match the rest of the
+ editor's mobile popup styling. */
+ @media (max-width: 820px) {
+ .ge-transform-popup-head .ge-adj-title { top: -2px; }
+ .ge-transform-popup-head .ge-adj-icon { top: 0; }
+ }
+ /* Make sure the head-buttons cluster sits hard-right with a small
+ gap, matching the FX-popup convention. */
+ .ge-transform-popup-head .ge-head-btns { margin-left: auto; }
+ .ge-transform-min-hint {
+ display: inline-flex;
+ align-items: center;
+ opacity: 0.45;
+ margin-right: -2px;
+ line-height: 1;
+ color: var(--fg-muted);
+ }
+ /* Small "Merge" text label next to each merge / flatten button so the
+ icons read at a glance instead of needing the title-tooltip. */
+ .ge-merge-label {
+ font-size: 10px;
+ margin-left: 4px;
+ opacity: 0.75;
+ }
+ .ge-transform-popup-body {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 12px;
+ }
+ .ge-transform-popup-hint { padding: 0 12px; }
+ .ge-transform-field {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ position: relative;
+ }
+ .ge-transform-field label {
+ font-size: 11px;
+ font-weight: 600;
+ opacity: 0.65;
+ min-width: 12px;
+ text-align: right;
+ }
+ /* Hide the native browser spin-buttons entirely — we render our own
+ themed ▲/▼ via .ge-transform-spin (see below). */
+ .ge-transform-popup-input {
+ width: 76px;
+ height: 24px;
+ padding: 0 18px 0 6px;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ font: inherit;
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+ text-align: right;
+ cursor: text;
+ -moz-appearance: textfield;
+ box-sizing: border-box;
+ }
+ /* Rotation field reserves extra room on the right for both the °
+ suffix AND the custom spinner so they don't sit on top of each other.
+ The suffix renders inside that reserved zone. */
+ .ge-transform-popup-input-rot { width: 76px; padding-right: 30px; }
+ .ge-transform-popup-input:focus { outline: none; border-color: var(--red); }
+ /* Custom themed spinner — two slim chevron buttons stacked to the right
+ of the input. Tight stack so the pair reads as one control instead of
+ two floating arrows. */
+ .ge-transform-spin {
+ position: absolute;
+ right: 3px;
+ top: 50%;
+ /* Nudged up 4px relative to the input's vertical center. */
+ transform: translateY(calc(-50% - 4px));
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ gap: 0;
+ height: 18px;
+ }
+ .ge-transform-spin button {
+ flex: 1 1 0;
+ width: 12px;
+ min-height: 0;
+ padding: 0;
+ background: transparent;
+ color: var(--fg-muted);
+ border: 1px solid color-mix(in srgb, var(--border) 60%, transparent);
+ font-size: 7px;
+ line-height: 1;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ transition: background 0.12s, color 0.12s, border-color 0.12s;
+ }
+ .ge-transform-spin button:first-child { border-radius: 3px 3px 0 0; border-bottom: 0; }
+ .ge-transform-spin button:last-child { border-radius: 0 0 3px 3px; }
+ .ge-transform-spin button:hover {
+ background: color-mix(in srgb, var(--accent, var(--red)) 25%, transparent);
+ color: var(--fg);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 55%, var(--border));
+ }
+ .ge-transform-spin button:active {
+ background: color-mix(in srgb, var(--accent, var(--red)) 55%, transparent);
+ }
+ /* Position the ° suffix to the LEFT of the spinner so they don't
+ overlap. The rotation input's larger padding leaves room. */
+ .ge-transform-popup-suffix {
+ position: absolute;
+ right: 20px;
+ top: 50%;
+ transform: translateY(-50%);
+ font-size: 10px;
+ opacity: 0.55;
+ pointer-events: none;
+ }
+ .ge-transform-aspect-btn {
+ background: none;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ color: var(--fg-muted);
+ cursor: pointer;
+ /* 2px smaller than the W/H input height so it reads as a chip-style
+ toggle rather than another form field. Pulled up 2px so it tucks
+ between W and H rather than sitting on their baseline. */
+ height: 22px;
+ width: 22px;
+ padding: 0;
+ position: relative;
+ top: -3px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0.5;
+ transition: opacity 0.12s, color 0.12s, border-color 0.12s;
+ }
+ .ge-transform-aspect-btn:hover { opacity: 1; }
+ .ge-transform-aspect-btn.active {
+ opacity: 1;
+ color: var(--accent, var(--red));
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 50%, var(--border));
+ }
+ /* Quick-action cluster (flip H, flip V, rotate 90°) — sits between the
+ rotation input and the Apply button. Each button matches the input
+ height and uses the editor's accent palette on hover. */
+ .ge-transform-quick {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ padding: 0 4px;
+ /* Pulled up 2px so the flip/rotate icons sit slightly higher than the
+ W/H/rotation inputs, matching the visual weight of the head row. */
+ position: relative;
+ top: -2px;
+ border-left: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
+ }
+ .ge-transform-quick-btn {
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ background: none;
+ color: var(--fg-muted);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0.7;
+ transition: opacity 0.12s, color 0.12s, border-color 0.12s, background 0.12s;
+ }
+ .ge-transform-quick-btn:hover {
+ opacity: 1;
+ color: var(--fg);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 55%, var(--border));
+ background: color-mix(in srgb, var(--accent, var(--red)) 12%, transparent);
+ }
+ .ge-transform-quick-btn:active {
+ background: color-mix(in srgb, var(--accent, var(--red)) 25%, transparent);
+ }
+ .ge-transform-popup-hint {
+ font-size: 10px;
+ opacity: 0.5;
+ margin: 0;
+ line-height: 1.3;
+ }
+ .ge-transform-preserve-field {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 0 12px;
+ font-size: 10px;
+ color: var(--fg-muted);
+ cursor: pointer;
+ }
+ .ge-transform-preserve-field input {
+ accent-color: var(--accent, var(--red));
+ margin: 0;
+ }
+
+ /* Floating Inpaint prompt — pops next to the user's last brush stroke
+ so they can type a description and Generate without diverting to
+ the side panel. */
+ .ge-inpaint-popup {
+ position: fixed;
+ z-index: 280;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 8px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 4px 14px color-mix(in srgb, var(--fg) 25%, transparent);
+ }
+ .ge-inpaint-popup-input {
+ width: 240px;
+ padding: 6px 8px;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ font: inherit;
+ font-size: 12px;
+ position: relative;
+ top: 0;
+ }
+ .ge-inpaint-popup-input:focus { outline: none; border-color: var(--red); }
+ .ge-inpaint-popup-run {
+ padding: 6px 12px;
+ font-size: 12px;
+ font-weight: 600;
+ position: relative;
+ top: 1px;
+ }
+ .ge-inpaint-popup-close {
+ background: none;
+ border: none;
+ color: var(--fg-muted);
+ font-size: 16px;
+ line-height: 1;
+ padding: 2px 4px;
+ margin-left: 2px;
+ cursor: pointer;
+ position: relative;
+ top: 0;
+ opacity: 0.7;
+ transition: opacity 0.15s, color 0.15s;
+ }
+ .ge-inpaint-popup-close:hover { opacity: 1; color: var(--fg); }
+ /* Loading state: the popup's panel chrome (bg/border/shadow) gets out
+ of the way so only the whirlpool floats over the canvas. */
+ .ge-inpaint-popup.ge-inpaint-popup-loading {
+ background: transparent;
+ border-color: transparent;
+ box-shadow: none;
+ padding: 0;
+ min-width: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .ge-controls input[type="range"] {
+ width: 100%;
+ box-sizing: border-box;
+ margin: 0;
+ display: block;
+ }
+ .ge-control-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 11px;
+ color: var(--fg);
+ }
+ .ge-control-row label {
+ flex-shrink: 0;
+ opacity: 0.7;
+ min-width: 36px;
+ }
+ .ge-color-picker {
+ width: 24px;
+ height: 24px;
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ padding: 0;
+ cursor: pointer;
+ background: none;
+ overflow: hidden;
+ }
+ /* attachColorPicker swaps the native <input type="color"> for a styled
+ text input with the same `.ge-color-picker` class plus
+ `.cp-swatch-input`. Force the 24×24 circular swatch back on it so
+ it doesn't render as a wide text box stretched across the row. */
+ .ge-color-picker.cp-swatch-input {
+ width: 24px;
+ height: 24px;
+ flex: 0 0 24px;
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ padding: 0;
+ cursor: pointer;
+ -webkit-appearance: none;
+ appearance: none;
+ /* Hide the (read-only) text caret + selection so the element reads
+ as a swatch, not a text field. */
+ color: transparent;
+ text-shadow: none;
+ caret-color: transparent;
+ font-size: 0;
+ user-select: none;
+ }
+ .ge-color-picker.cp-swatch-input:focus {
+ outline: 1px solid var(--red);
+ outline-offset: 1px;
+ }
+ .ge-size-slider {
+ flex: 1 1 auto;
+ min-width: 0;
+ height: 8px;
+ accent-color: var(--red);
+ -webkit-appearance: none;
+ appearance: none;
+ background: color-mix(in srgb, var(--fg) 25%, transparent);
+ border-radius: 999px;
+ margin: 0;
+ }
+ .ge-size-label { font-size: 10px; opacity: 0.5; min-width: 28px; text-align: right; }
+
+ /* Eraser controls: tighter rows + a small brush preview on the left of
+ each label so the user can see what each slider affects. The three
+ previews share the same dot but each leans on a different rendering
+ trick (alpha / scatter / blur) to mirror its slider's effect. */
+ .ge-eraser-row {
+ display: flex !important;
+ align-items: center !important;
+ gap: 8px;
+ padding: 2px 0;
+ /* Lets the trailing value span pin to the row's right edge so it
+ stays visible when the slider expands left over the label. */
+ position: relative;
+ }
+ /* Inline value chip next to the label text. (Previously absolutely-
+ positioned over the slider track to ride the expand animation, which
+ caused overlap now that the dynamic-slider behavior is off for these.) */
+ .ge-eraser-row label > span[id$="-label"] {
+ margin-left: 4px;
+ padding: 0 4px;
+ border-radius: 3px;
+ cursor: text;
+ font-size: 10px;
+ opacity: 0.7;
+ font-variant-numeric: tabular-nums;
+ }
+ /* When the value chip is pulled out of its label and placed AFTER the
+ slider (see DOM transform in galleryEditor.js init), it sits on the
+ row's right edge and naturally shortens the slider's flex space. */
+ .ge-eraser-row > span[id$="-label"].ge-slider-value {
+ flex: 0 0 auto;
+ margin: 0 0 0 6px;
+ padding: 0 4px;
+ font-size: 10px;
+ opacity: 0.7;
+ font-variant-numeric: tabular-nums;
+ min-width: 34px;
+ text-align: right;
+ cursor: text;
+ border-radius: 3px;
+ white-space: nowrap;
+ }
+
+ /* Per-tool model selector row (lives at the top of each AI tool's
+ section in the side panel). Mirrors the inpaint Model row layout. */
+ .ge-tool-model-row {
+ display: flex !important;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 6px;
+ min-width: 0;
+ }
+ .ge-tool-model-row > label {
+ font-size: 11px;
+ opacity: 0.6;
+ flex: 0 0 auto;
+ }
+ .ge-tool-model {
+ flex: 1 1 0;
+ min-width: 0;
+ font-size: 10px;
+ padding: 2px 4px;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ }
+
+ /* Section label inside a dropdown — small uppercase header. */
+ .dropdown-section-label {
+ font-size: 9px;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ opacity: 0.5;
+ font-weight: 600;
+ padding: 6px 8px 2px;
+ }
+ .dropdown-section-divider {
+ height: 1px;
+ background: var(--border);
+ margin: 4px 0;
+ opacity: 0.6;
+ }
+
+ /* Inline numeric editor that replaces the value chip on click. */
+ .ge-slider-edit {
+ position: absolute;
+ z-index: 11;
+ font: inherit;
+ font-size: 10px;
+ font-variant-numeric: tabular-nums;
+ padding: 1px 4px;
+ border: 1px solid var(--red);
+ border-radius: 3px;
+ background: var(--bg);
+ color: var(--fg);
+ outline: none;
+ text-align: center;
+ }
+
+ /* Merge dropdown — position is set by JS each time it opens (relative to
+ the button's bounding rect) because the parent .ge-layers has
+ overflow:hidden which would otherwise clip the popup. */
+ .ge-merge-menu {
+ position: fixed;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 3px;
+ box-shadow: 0 4px 14px color-mix(in srgb, var(--fg) 25%, transparent);
+ z-index: 50;
+ display: flex;
+ flex-direction: column;
+ min-width: 140px;
+ }
+ .ge-merge-menu .dropdown-item-compact {
+ background: none;
+ border: none;
+ width: 100%;
+ text-align: left;
+ padding: 5px 8px;
+ font-size: 11px;
+ gap: 8px;
+ font: inherit;
+ font-size: 11px;
+ }
+
+ /* Thin separator inside a tool section. */
+ .ge-section-divider {
+ border: 0;
+ border-top: 1px solid var(--border);
+ margin: 10px -2px;
+ opacity: 0.6;
+ }
+
+ /* Small explanatory paragraph under AI tool section labels. */
+ .ge-section-hint {
+ font-size: 10.5px;
+ line-height: 1.45;
+ opacity: 0.55;
+ margin: 0 0 8px;
+ }
+ /* Clone-tool hint swaps between "Alt-click" (desktop) and "Double-tap"
+ (mobile) so the on-screen instruction matches the actual gesture. */
+ .ge-clone-hint-mobile { display: none; }
+ @media (max-width: 820px) {
+ .ge-clone-hint-desktop { display: none; }
+ .ge-clone-hint-mobile { display: inline; }
+ }
+ /* Section title + adjacent "?" affordance — collapses the long
+ explanatory paragraph into a hoverable tooltip so the side panel
+ stays compact. */
+ .ge-section-title-with-help {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ }
+ /* Drop the source-whitespace text node between the title text and the
+ ? span so the chip hugs the title with no extra gap. */
+ .ge-section-title-with-help .ge-section-help { margin-left: 0; }
+ .ge-section-help {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: color-mix(in srgb, var(--fg) 12%, transparent);
+ color: var(--fg-muted);
+ font-size: 9px;
+ font-weight: 700;
+ cursor: help;
+ user-select: none;
+ transition: background 0.12s, color 0.12s;
+ }
+ .ge-section-help:hover,
+ .ge-section-help:focus-visible {
+ background: color-mix(in srgb, var(--fg) 24%, transparent);
+ color: var(--fg);
+ outline: none;
+ }
+
+ /* Lightweight section title — used inside the inpaint panel to group
+ the mask actions (Eye / Invert / Clear) under a "Selection" header. */
+ .ge-section-title {
+ margin: 10px 0 4px;
+ font-size: 10px;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ opacity: 0.5;
+ font-weight: 600;
+ }
+ /* Selection-row buttons stay compact so eye + invert + clear fit on
+ one line beside each other. */
+ .ge-inpaint-mask-row {
+ display: flex !important;
+ gap: 4px;
+ align-items: center;
+ }
+ .ge-inpaint-mask-row .ge-btn {
+ flex: 0 0 auto;
+ }
+ .ge-inpaint-mask-label {
+ font-size: 10px;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ opacity: 0.5;
+ font-weight: 600;
+ margin-right: 4px;
+ }
+
+ /* Fixed label column so the three sliders start at the same x and have
+ the same length when unused. Without this, "Flow" (4 chars) leaves
+ more room than "Opacity" (7 chars). */
+ .ge-eraser-row label {
+ font-size: 10px;
+ opacity: 0.55;
+ flex: 0 0 78px;
+ white-space: nowrap;
+ display: inline-flex;
+ justify-content: space-between;
+ gap: 4px;
+ }
+ /* Fixed-size slider track for all side-panel sliders — no dynamic
+ width/height expansion on drag. Only the thumb grows on interaction
+ (see ::-webkit-slider-thumb / ::-moz-range-thumb below). */
+ .ge-eraser-row input[type="range"] {
+ flex: 1 1 auto;
+ min-width: 0;
+ height: 8px;
+ accent-color: var(--red);
+ -webkit-appearance: none;
+ appearance: none;
+ background: color-mix(in srgb, var(--fg) 25%, transparent);
+ border-radius: 999px;
+ margin: 0;
+ position: relative;
+ z-index: 2;
+ }
+ .ge-eraser-row input[type="range"]::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 9px;
+ height: 9px;
+ border-radius: 50%;
+ background: var(--red);
+ border: none;
+ cursor: pointer;
+ transition: width 0.12s ease 0.5s, height 0.12s ease 0.5s;
+ }
+ .ge-eraser-row input[type="range"]:hover::-webkit-slider-thumb,
+ .ge-eraser-row input[type="range"].is-using::-webkit-slider-thumb,
+ .ge-eraser-row input[type="range"]:active::-webkit-slider-thumb {
+ width: 16px; height: 16px;
+ transition: width 0.12s ease 0s, height 0.12s ease 0s;
+ }
+ .ge-eraser-row input[type="range"]::-moz-range-thumb {
+ width: 9px; height: 9px;
+ border-radius: 50%;
+ background: var(--red);
+ border: none;
+ cursor: pointer;
+ transition: width 0.12s ease 0.5s, height 0.12s ease 0.5s;
+ }
+ .ge-eraser-row input[type="range"]:hover::-moz-range-thumb,
+ .ge-eraser-row input[type="range"].is-using::-moz-range-thumb,
+ .ge-eraser-row input[type="range"]:active::-moz-range-thumb {
+ width: 16px; height: 16px;
+ transition: width 0.12s ease 0s, height 0.12s ease 0s;
+ }
+
+ /* Help "?" icon next to a section title. Subtle by default, hover
+ brightens. Tooltip via native `title` attribute. */
+ .ge-section-help {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 14px;
+ height: 14px;
+ margin-left: 4px;
+ font-size: 9px;
+ font-weight: 600;
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ color: var(--fg-muted);
+ background: none;
+ cursor: help;
+ vertical-align: middle;
+ position: relative;
+ top: -1px;
+ opacity: 0.7;
+ transition: opacity 0.15s, color 0.15s, border-color 0.15s;
+ }
+ .ge-section-help:hover { opacity: 1; color: var(--fg); border-color: var(--fg-muted); }
+
+ /* Layer-FX popup — floating window bound to one layer. */
+ .ge-fx-popup {
+ position: fixed;
+ z-index: 300;
+ width: 320px;
+ max-height: 80vh;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 12px 32px rgba(0,0,0,0.45);
+ display: flex;
+ flex-direction: column;
+ font-size: 11px;
+ color: var(--fg);
+ }
+ .ge-fx-popup-head {
+ display: flex; align-items: center; justify-content: space-between;
+ padding: 8px 10px;
+ border-bottom: 1px solid var(--border);
+ font-weight: 600;
+ }
+ .ge-fx-popup-title { font-size: 12px; }
+ .ge-fx-popup-close {
+ background: none; border: none; color: var(--fg-muted);
+ font-size: 18px; line-height: 1; cursor: pointer; padding: 0 4px;
+ }
+ .ge-fx-popup-close:hover { color: var(--fg); }
+ .ge-fx-popup-body { padding: 8px 10px; overflow-y: auto; }
+ .ge-fx-popup-foot {
+ display: flex; gap: 6px; padding: 6px 10px;
+ border-top: 1px solid var(--border);
+ }
+ .ge-fx-group-title {
+ font-size: 10px; font-weight: 600; opacity: 0.6;
+ text-transform: uppercase; letter-spacing: 0.5px;
+ margin: 8px 0 4px;
+ }
+ .ge-fx-group-title:first-child { margin-top: 0; }
+ .ge-fx-cb-tone {
+ font-size: 10px; opacity: 0.55; font-style: italic;
+ margin: 4px 0 2px;
+ }
+ .ge-fx-row {
+ display: flex; align-items: center; gap: 6px;
+ padding: 2px 0;
+ }
+ .ge-fx-row-label {
+ font-size: 10px; opacity: 0.7;
+ flex: 0 0 110px; white-space: nowrap;
+ }
+ .ge-fx-row input[type="range"] {
+ flex: 1 1 auto; min-width: 0;
+ height: 6px; accent-color: var(--red);
+ -webkit-appearance: none; appearance: none;
+ background: color-mix(in srgb, var(--fg) 25%, transparent);
+ border-radius: 999px;
+ }
+ .ge-fx-row input[type="range"]::-webkit-slider-thumb {
+ -webkit-appearance: none; appearance: none;
+ width: 11px; height: 11px; border-radius: 50%;
+ background: var(--red); border: none; cursor: pointer;
+ }
+ .ge-fx-row input[type="range"]::-moz-range-thumb {
+ width: 11px; height: 11px; border-radius: 50%;
+ background: var(--red); border: none; cursor: pointer;
+ }
+ .ge-fx-row-value {
+ font-size: 10px; opacity: 0.7; font-variant-numeric: tabular-nums;
+ flex: 0 0 40px; text-align: right;
+ }
+
+ /* Layer-row FX button — tinted when the layer has any non-identity FX. */
+ .ge-layer-fx-btn {
+ opacity: 0.55;
+ }
+ .ge-layer-fx-btn:hover { opacity: 0.9; }
+ .ge-layer-fx-btn.active {
+ opacity: 1;
+ color: var(--accent, var(--red));
+ }
+ /* Add-mask button on each layer row. Subtle by default; lights up red
+ when a lasso/wand selection is live so the user instantly sees that
+ clicking it will bake that selection into a mask on this layer. */
+ .ge-layer-mask-btn {
+ opacity: 0.45;
+ }
+ .ge-layer-mask-btn:hover { opacity: 0.9; }
+ .ge-layer-mask-btn.from-selection {
+ opacity: 1;
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ }
+
+ /* Shared frosted-glass style for FX menu + adjustment popups. */
+ .ge-frosted {
+ background: color-mix(in srgb, var(--panel) 70%, transparent);
+ backdrop-filter: blur(14px) saturate(140%);
+ -webkit-backdrop-filter: blur(14px) saturate(140%);
+ border: 1px solid color-mix(in srgb, var(--fg) 12%, transparent);
+ box-shadow: 0 12px 40px rgba(0,0,0,0.55);
+ }
+
+ /* FX dropdown menu from the layer-row fx icon. */
+ .ge-fx-menu {
+ position: fixed;
+ z-index: 305;
+ min-width: 200px;
+ padding: 4px;
+ border-radius: 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+ .ge-fx-menu-item {
+ background: none;
+ border: none;
+ text-align: left;
+ padding: 7px 10px;
+ font-size: 12px;
+ color: var(--fg);
+ border-radius: 5px;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .ge-fx-menu-icon {
+ display: inline-flex;
+ align-items: center;
+ color: var(--fg-muted);
+ flex-shrink: 0;
+ }
+ .ge-fx-menu-item:hover {
+ background: color-mix(in srgb, var(--fg) 12%, transparent);
+ }
+ .ge-fx-menu-item:hover .ge-fx-menu-icon { color: var(--fg); }
+
+ .ge-add-layer-menu {
+ position: fixed;
+ z-index: 10004;
+ width: 218px;
+ padding: 5px;
+ border-radius: 7px;
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ }
+ .ge-add-layer-menu button {
+ height: 30px;
+ padding: 0 9px;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ color: var(--fg);
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ text-align: left;
+ font: inherit;
+ font-size: 11px;
+ cursor: pointer;
+ }
+ .ge-add-layer-menu button:hover { background: color-mix(in srgb, var(--fg) 10%, transparent); }
+ .ge-add-layer-symbol {
+ width: 16px;
+ display: inline-flex;
+ justify-content: center;
+ color: var(--accent, var(--red));
+ font-size: 13px;
+ }
+ .ge-add-layer-divider { height: 1px; margin: 4px 5px; background: color-mix(in srgb, var(--fg) 10%, transparent); }
+
+ /* Per-type adjustment popup. */
+ .ge-adj-popup {
+ position: fixed;
+ z-index: 305;
+ width: 320px;
+ border-radius: 10px;
+ display: flex;
+ flex-direction: column;
+ font-size: 11px;
+ color: var(--fg);
+ }
+ .ge-adj-popup .ge-adj-head {
+ display: flex; align-items: center; gap: 6px;
+ padding: 8px 12px;
+ border-bottom: 1px solid color-mix(in srgb, var(--fg) 10%, transparent);
+ cursor: grab;
+ user-select: none;
+ }
+ .ge-adj-popup .ge-head-btns { margin-left: auto; }
+ .ge-adj-icon {
+ display: inline-flex;
+ align-items: center;
+ color: var(--fg-muted);
+ flex-shrink: 0;
+ }
+ .ge-adj-title { font-weight: 600; font-size: 12px; flex: 1 1 auto; }
+ .ge-adj-min, .ge-adj-close, .ge-history-close {
+ background: none; border: none; color: var(--fg-muted);
+ font-size: 16px; line-height: 1; cursor: pointer; padding: 0 4px;
+ flex-shrink: 0;
+ }
+ .ge-history-close:hover { color: var(--fg); }
+ /* Mobile-only: shift head icons/buttons up and enlarge the minimise
+ glyph so it reads as a window-minimise affordance, not a centered
+ minus. Desktop keeps the original tight head styling. */
+ @media (max-width: 820px) {
+ .ge-adj-icon {
+ position: relative;
+ top: -4px;
+ }
+ .ge-adj-title {
+ position: relative;
+ top: -2px;
+ }
+ .ge-adj-min, .ge-adj-close, .ge-history-close {
+ position: relative;
+ top: -4px;
+ }
+ .ge-adj-min,
+ .ge-adj-popup .ge-adj-min,
+ .ge-history-head .ge-adj-min,
+ .ge-transform-popup-head .ge-adj-min {
+ font-size: 22px !important;
+ font-weight: 600 !important;
+ padding: 0 8px !important;
+ line-height: 0.6 !important;
+ position: relative;
+ top: 4px;
+ }
+ .ge-adj-head .ge-transform-aspect-btn {
+ position: relative;
+ top: -4px;
+ }
+ }
+ .ge-adj-min:hover, .ge-adj-close:hover { color: var(--fg); }
+
+ /* Floating dock at bottom-right for minimised FX popups. */
+ #ge-fx-dock {
+ position: fixed;
+ left: 50%;
+ transform: translateX(-50%);
+ bottom: 12px;
+ z-index: 304;
+ display: flex;
+ flex-direction: row;
+ gap: 6px;
+ align-items: center;
+ pointer-events: none;
+ max-width: calc(100vw - 24px);
+ flex-wrap: wrap;
+ justify-content: center;
+ }
+ .ge-fx-dock-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 8px;
+ border-radius: 6px;
+ font-size: 11px;
+ color: var(--fg);
+ cursor: pointer;
+ pointer-events: auto;
+ max-width: 220px;
+ white-space: nowrap;
+ overflow: hidden;
+ }
+ .ge-fx-dock-chip:hover {
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
+ .ge-fx-dock-icon { display: inline-flex; align-items: center; }
+ .ge-fx-dock-close {
+ margin-left: 2px; opacity: 0.55; padding: 0 2px;
+ font-size: 14px; line-height: 1;
+ }
+ .ge-fx-dock-close:hover { opacity: 1; color: var(--red); }
+
+ /* Sub-layer row icon in the layer panel. */
+ .ge-adj-sub-name {
+ display: inline-flex !important;
+ align-items: center;
+ gap: 4px;
+ }
+ .ge-adj-sub-icon {
+ display: inline-flex; align-items: center;
+ color: var(--accent, var(--red));
+ flex-shrink: 0;
+ }
+ .ge-adj-sub-icon svg { width: 11px; height: 11px; }
+
+ /* History panel — labeled timeline of edits. */
+ #ge-history-panel {
+ position: fixed;
+ z-index: 10004;
+ width: 240px;
+ max-height: 60vh;
+ border-radius: 8px;
+ display: flex;
+ flex-direction: column;
+ color: var(--fg);
+ font-size: 11px;
+ }
+ .ge-history-head {
+ display: flex; align-items: center; gap: 6px;
+ padding: 8px 10px;
+ border-bottom: 1px solid color-mix(in srgb, var(--fg) 10%, transparent);
+ cursor: grab;
+ user-select: none;
+ }
+ .ge-history-title { font-weight: 600; font-size: 12px; flex: 1 1 auto; }
+ .ge-history-close {
+ background: none; border: none; color: var(--fg-muted);
+ font-size: 16px; line-height: 1; cursor: pointer; padding: 0 4px;
+ flex-shrink: 0;
+ }
+ .ge-history-close:hover { color: var(--fg); }
+ .ge-history-list { overflow-y: auto; padding: 4px 0; }
+ .ge-history-row {
+ display: flex; align-items: center; gap: 8px;
+ width: 100%;
+ padding: 5px 10px;
+ background: none; border: none;
+ text-align: left; cursor: pointer;
+ color: var(--fg); font-size: 11px;
+ }
+ .ge-history-row:hover { background: color-mix(in srgb, var(--fg) 8%, transparent); }
+ .ge-history-row.current { background: color-mix(in srgb, var(--accent, var(--red)) 18%, transparent); }
+ .ge-history-row.current .ge-history-row-dot { background: var(--accent, var(--red)); }
+ .ge-history-row.future { opacity: 0.45; }
+ .ge-history-row-dot {
+ width: 6px; height: 6px; border-radius: 50%;
+ background: var(--fg-muted);
+ flex-shrink: 0;
+ }
+ .ge-history-row-label { flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .ge-history-row-time { font-size: 9px; opacity: 0.55; flex-shrink: 0; }
+
+ /* Tight button group in popup heads — min + close sit immediately next
+ to each other with no inherited flex gap, pushed to the right edge. */
+ .ge-head-btns {
+ display: inline-flex;
+ align-items: center;
+ gap: 0;
+ margin-left: auto;
+ flex-shrink: 0;
+ }
+ .ge-head-btns > button {
+ width: 26px;
+ height: 26px;
+ padding: 0 !important;
+ margin: 0;
+ font-size: 18px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 6px;
+ }
+ .ge-head-btns > button:hover {
+ background: color-mix(in srgb, var(--fg) 12%, transparent);
+ }
+
+ /* Detail-header heart toggle — sits next to the icon Edit button. */
+ .gallery-detail-fav-header { opacity: 0.7; transition: opacity 0.15s, color 0.15s; }
+ .gallery-detail-fav-header:hover { opacity: 1; }
+ .gallery-detail-fav-header.active { color: var(--red); opacity: 1; }
+
+ /* Canvas loading overlay — covers the canvas area while a blocking op
+ (rotation, big resize, etc.) runs. */
+ .ge-canvas-loading {
+ position: absolute;
+ inset: 0;
+ z-index: 50;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ border-radius: 8px;
+ pointer-events: auto;
+ }
+ .ge-canvas-loading-spinner {
+ width: 32px; height: 32px;
+ border: 3px solid color-mix(in srgb, var(--fg) 25%, transparent);
+ border-top-color: var(--accent, var(--red));
+ border-radius: 50%;
+ animation: ge-canvas-spin 0.8s linear infinite;
+ }
+ .ge-canvas-loading-msg { font-size: 12px; opacity: 0.85; }
+
+ /* Missing-dependency notice in tool sections (Bg Remove etc.). */
+ .ge-dep-notice {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 10px;
+ background: color-mix(in srgb, var(--accent, var(--red)) 10%, transparent);
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 30%, transparent);
+ border-radius: 6px;
+ margin: 4px 0 8px;
+ font-size: 11px;
+ }
+ .ge-dep-notice-text { flex: 1 1 auto; line-height: 1.4; }
+ .ge-dep-notice-text strong { display: block; margin-bottom: 2px; }
+ .ge-dep-notice-text code {
+ font-family: 'Fira Code', monospace;
+ font-size: 10px;
+ padding: 1px 4px;
+ border-radius: 3px;
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ }
+ .ge-dep-notice .ge-btn { flex-shrink: 0; }
+
+ /* Brief highlight on a Cookbook deps row arrived-at via deep-link. */
+ .cookbook-pkg-flash { animation: cookbook-pkg-flash 1.4s ease-out; }
+ @keyframes cookbook-pkg-flash {
+ 0% { background: color-mix(in srgb, var(--accent, var(--red)) 30%, transparent); }
+ 100% { background: transparent; }
+ }
+
+ /* Flash highlight when an anchor-link ([Name](#task-/#skill-/#research-))
+ opens a panel and focuses a specific item. */
+ @keyframes anchor-item-flash {
+ 0% { background: color-mix(in srgb, var(--accent, var(--red)) 28%, transparent); }
+ 60% { background: color-mix(in srgb, var(--accent, var(--red)) 18%, transparent); }
+ 100% { background: transparent; }
+ }
+ .task-card-flash,
+ .skill-row-flash,
+ .research-card-flash {
+ animation: anchor-item-flash 2s ease-out;
+ border-radius: 6px;
+ }
+
+ .memory-item-focus {
+ animation: anchor-item-flash 2.2s ease-out;
+ outline: 1px solid color-mix(in srgb, var(--accent, var(--red)) 45%, transparent);
+ outline-offset: 2px;
+ border-radius: 6px;
+ }
+
+ /* Preview dot icons for the Blur sub-menu — visual cue for each blur
+ type (Gaussian = soft round, Zoom = radial streaks). */
+ .ge-blur-icon {
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ display: inline-block;
+ flex-shrink: 0;
+ background: var(--fg);
+ }
+ .ge-blur-icon.ge-blur-gaussian {
+ background: radial-gradient(circle, var(--fg) 0%, var(--fg) 25%, transparent 75%);
+ filter: blur(1.5px);
+ }
+ .ge-blur-icon.ge-blur-zoom {
+ background: radial-gradient(circle, var(--fg) 0%, var(--fg) 20%, transparent 60%);
+ box-shadow:
+ 0 -5px 0 -3px var(--fg),
+ 0 5px 0 -3px var(--fg),
+ -5px 0 0 -3px var(--fg),
+ 5px 0 0 -3px var(--fg),
+ -4px -4px 0 -3px var(--fg),
+ 4px -4px 0 -3px var(--fg),
+ -4px 4px 0 -3px var(--fg),
+ 4px 4px 0 -3px var(--fg);
+ }
+
+ /* Inline-swatch color picker — small square that fits next to a title. */
+ .ge-inline-swatch {
+ width: 16px !important;
+ height: 16px !important;
+ padding: 0 !important;
+ border: 1px solid var(--border) !important;
+ border-radius: 3px !important;
+ cursor: pointer;
+ flex-shrink: 0;
+ -webkit-appearance: none;
+ appearance: none;
+ background: none;
+ }
+
+ /* Drop overlay over the gallery editor while a file drag is in flight. */
+ .ge-drop-overlay {
+ position: absolute;
+ inset: 0;
+ z-index: 200;
+ pointer-events: none;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: color-mix(in srgb, var(--accent, var(--red)) 18%, transparent);
+ border: 3px dashed color-mix(in srgb, var(--accent, var(--red)) 80%, transparent);
+ border-radius: 8px;
+ }
+ .ge-drop-overlay-msg {
+ padding: 12px 20px;
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--fg);
+ background: color-mix(in srgb, var(--panel) 70%, transparent);
+ backdrop-filter: blur(10px);
+ border-radius: 8px;
+ }
+
+ /* Small buttons that show an SVG icon + text label side-by-side. */
+ .ge-btn-iconlabel {
+ display: inline-flex !important;
+ align-items: center;
+ gap: 4px;
+ white-space: nowrap;
+ }
+ .ge-btn-iconlabel svg {
+ flex-shrink: 0;
+ opacity: 0.85;
+ }
+ .ge-btn-iconlabel:hover svg { opacity: 1; }
+
+ .ge-adj-body {
+ padding: 8px 12px;
+ max-height: 60vh;
+ overflow-y: auto;
+ overflow-x: hidden;
+ }
+ .ge-adj-preset-field {
+ display: grid;
+ grid-template-columns: 46px 1fr;
+ align-items: center;
+ gap: 8px;
+ margin: 8px 12px 0;
+ color: color-mix(in srgb, var(--fg) 65%, transparent);
+ font-size: 10px;
+ }
+ .ge-adj-preset-select {
+ min-width: 0;
+ width: 100%;
+ padding: 5px 7px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--panel) 90%, transparent);
+ color: var(--fg);
+ font: inherit;
+ }
+ .ge-adj-preset-select:focus { outline: none; border-color: var(--accent, var(--red)); }
+ .ge-adj-popup { box-sizing: border-box; overflow: hidden; }
+ .ge-adj-foot {
+ display: flex; gap: 6px; justify-content: flex-end;
+ padding: 8px 12px;
+ border-top: 1px solid color-mix(in srgb, var(--fg) 10%, transparent);
+ }
+ .ge-adj-foot-spacer { flex: 1 1 auto; }
+ .ge-adj-compare-btn.is-active {
+ color: var(--accent, var(--red));
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 65%, transparent);
+ background: color-mix(in srgb, var(--accent, var(--red)) 12%, transparent);
+ }
+ .ge-adj-channel-field {
+ display: grid;
+ grid-template-columns: 64px 1fr;
+ align-items: center;
+ gap: 8px;
+ margin: 0 0 8px;
+ color: color-mix(in srgb, var(--fg) 65%, transparent);
+ font-size: 10px;
+ }
+ .ge-adj-channel-select,
+ .ge-adj-selective-range {
+ width: 100%;
+ min-width: 0;
+ height: 27px;
+ padding: 0 25px 0 7px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--panel);
+ color: var(--fg);
+ font: inherit;
+ }
+ .ge-gradient-map-preview {
+ height: 24px;
+ margin-bottom: 9px;
+ border: 1px solid color-mix(in srgb, var(--fg) 18%, transparent);
+ border-radius: 4px;
+ background: linear-gradient(90deg, var(--ge-gradient-start), var(--ge-gradient-end));
+ }
+ .ge-gradient-color-row {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 10px;
+ margin-bottom: 8px;
+ }
+ .ge-gradient-color-row label {
+ display: grid;
+ grid-template-columns: 1fr 30px;
+ align-items: center;
+ gap: 6px;
+ font-size: 10px;
+ opacity: .75;
+ }
+ .ge-gradient-color-row input[type="color"] {
+ width: 30px;
+ height: 24px;
+ padding: 1px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: transparent;
+ }
+ .ge-adj-toggle-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ min-height: 28px;
+ font-size: 10px;
+ color: color-mix(in srgb, var(--fg) 70%, transparent);
+ }
+ .ge-adj-toggle-row input { accent-color: var(--red); }
+ .ge-curves-wrap {
+ width: 100%;
+ aspect-ratio: 14 / 9;
+ border: 1px solid color-mix(in srgb, var(--fg) 14%, transparent);
+ background: #0b0d10;
+ overflow: hidden;
+ }
+ .ge-curves-canvas { display: block; width: 100%; height: 100%; touch-action: none; cursor: crosshair; }
+ .ge-adj-help { margin: 7px 0 0; font-size: 9px; line-height: 1.35; opacity: .5; }
+ .ge-adjustment-layer-item .ge-layer-adjustment-marker { color: var(--accent, var(--red)); }
+ .ge-adjustment-layer-item .ge-layer-adjustment-marker svg { width: 12px; height: 12px; }
+ /* Mobile-only: oversize the foot Cancel/Apply buttons to match the
+ Transform popup. Desktop keeps the original ge-btn-sm sizing. */
+ @media (max-width: 820px) {
+ .ge-adj-foot .ge-adj-cancel-btn,
+ .ge-adj-foot .ge-adj-apply-btn {
+ padding: 8px 16px !important;
+ font-size: 13px !important;
+ min-width: 80px;
+ text-align: center;
+ }
+ }
+ .ge-adj-row {
+ display: flex; align-items: center; gap: 3px;
+ padding: 0;
+ margin: 0;
+ min-width: 0;
+ line-height: 1;
+ }
+ .ge-adj-row > label {
+ flex: 0 0 96px;
+ font-size: 10px;
+ opacity: 0.7;
+ }
+ .ge-adj-row input[type="range"] {
+ flex: 1 1 auto;
+ min-width: 0;
+ height: 6px;
+ accent-color: var(--red);
+ -webkit-appearance: none; appearance: none;
+ background: color-mix(in srgb, var(--fg) 25%, transparent);
+ border-radius: 999px;
+ }
+ /* Mobile-only: fixed-size sliders + taller rows so the thumb growing
+ on active doesn't push the row height around. */
+ @media (max-width: 820px) {
+ .ge-adj-row {
+ min-height: 28px;
+ }
+ /* Let the slider consume the space left after the label and value chip.
+ A fixed 160px track overflows the 320px phone sheet once the popup's
+ horizontal padding and controls are included. */
+ .ge-adj-row > label {
+ flex: 0 0 clamp(72px, 26vw, 96px);
+ min-width: 0;
+ }
+ .ge-adj-row input[type="range"] {
+ flex: 1 1 auto;
+ width: auto;
+ min-width: 56px;
+ max-width: none;
+ }
+ }
+ @media (max-width: 360px) {
+ /* Give Gradient Map's color labels and swatches a usable tap width on
+ narrow phones; the popup remains scrollable if the extra row is needed. */
+ .ge-gradient-color-row {
+ grid-template-columns: 1fr;
+ gap: 6px;
+ }
+ }
+ .ge-adj-row input[type="range"]::-webkit-slider-thumb {
+ -webkit-appearance: none; appearance: none;
+ width: 12px; height: 12px;
+ border-radius: 50%;
+ background: var(--red);
+ cursor: pointer; border: none;
+ transition: width 0.12s ease, height 0.12s ease;
+ }
+ .ge-adj-row input[type="range"]:hover::-webkit-slider-thumb,
+ .ge-adj-row input[type="range"]:active::-webkit-slider-thumb {
+ width: 18px; height: 18px;
+ }
+ .ge-adj-row input[type="range"]::-moz-range-thumb {
+ width: 12px; height: 12px;
+ border-radius: 50%; background: var(--red); border: none; cursor: pointer;
+ transition: width 0.12s ease, height 0.12s ease;
+ }
+ .ge-adj-row input[type="range"]:hover::-moz-range-thumb,
+ .ge-adj-row input[type="range"]:active::-moz-range-thumb {
+ width: 18px; height: 18px;
+ }
+ /* Value chip — fixed-width column, text aligned LEFT so the chip's
+ left edge always sits immediately after the slider regardless of
+ value length. Without a fixed width Hue's "180 °" made its slider
+ shorter than Saturation's "100" since slider was flex-1. */
+ .ge-adj-value {
+ flex: 0 0 34px;
+ margin-left: 0;
+ padding: 0 2px;
+ font-size: 10px; opacity: 0.7; text-align: left;
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ cursor: text;
+ }
+ .ge-adj-value:hover { opacity: 1; }
+ .ge-adj-cb-tone {
+ font-size: 10px; opacity: 0.55; font-style: italic;
+ margin: 2px 0 0;
+ line-height: 1;
+ }
+ .ge-adj-cb-row {
+ padding: 0;
+ gap: 3px;
+ }
+ .ge-adj-cb-tone-select {
+ width: 100%;
+ padding: 6px 8px;
+ font-size: 12px;
+ border-radius: 6px;
+ border: 1px solid var(--border);
+ background: color-mix(in srgb, var(--panel) 90%, transparent);
+ color: var(--fg);
+ }
+ .ge-adj-cb-tone-select:focus { outline: none; border-color: var(--red); }
+ .ge-adj-hist-details[open] > summary::before {
+ content: '▾ ';
+ }
+ .ge-adj-hist-details .ge-adj-hist-wrap {
+ margin-top: 4px;
+ }
+ .ge-adj-histogram {
+ display: block;
+ width: 100%;
+ height: 80px;
+ border-radius: 4px;
+ background: rgba(0,0,0,0.25);
+ }
+ .ge-adj-hist-wrap {
+ position: relative;
+ margin-bottom: 14px;
+ }
+ .ge-adj-clip-status {
+ margin-top: 3px;
+ color: var(--fg-muted);
+ font-size: 10px;
+ line-height: 1.25;
+ font-variant-numeric: tabular-nums;
+ }
+ .ge-adj-hist-handles {
+ position: absolute;
+ left: 0; right: 0;
+ bottom: -10px;
+ height: 12px;
+ pointer-events: none;
+ }
+ .ge-adj-hist-handle {
+ position: absolute;
+ width: 12px;
+ height: 12px;
+ cursor: ew-resize;
+ pointer-events: auto;
+ border-style: solid;
+ border-width: 0 6px 10px 6px;
+ border-color: transparent transparent var(--fg-muted) transparent;
+ filter: drop-shadow(0 1px 1px rgba(0,0,0,0.4));
+ }
+ .ge-adj-hist-handle:hover { border-bottom-color: var(--fg); }
+ .ge-adj-hist-handle.hist-h-black { border-bottom-color: #111; }
+ .ge-adj-hist-handle.hist-h-white { border-bottom-color: #fff; }
+ .ge-adj-hist-handle.hist-h-gamma { border-bottom-color: var(--accent, var(--red)); }
+ /* Per-slider revert button. */
+ .ge-adj-revert {
+ background: none; border: none;
+ color: var(--fg-muted); cursor: pointer;
+ padding: 2px 4px; margin-left: 2px;
+ opacity: 0.55;
+ display: inline-flex; align-items: center; justify-content: center;
+ transition: opacity 0.15s, color 0.15s;
+ }
+ .ge-adj-revert:hover { opacity: 1; color: var(--fg); }
+
+ /* Adjustment sub-layer row in the layer panel — indented under parent. */
+ .ge-adj-sub-item {
+ padding-left: 18px;
+ opacity: 0.85;
+ border-left: 2px solid color-mix(in srgb, var(--accent, var(--red)) 35%, transparent);
+ margin-left: 6px;
+ font-size: 10.5px;
+ }
+ .ge-adj-sub-item .ge-layer-name {
+ opacity: 0.85;
+ font-style: italic;
+ }
+ /* Mask sub-layer rows. Same indent as adj sub-layers but the
+ highlight bar uses fg-muted instead of accent — these aren't FX
+ effects, just selection-state. When activated (the click target
+ for paint / inpaint / generate), border + name go full strength. */
+ .ge-mask-sub-item {
+ border-left-color: color-mix(in srgb, var(--fg) 30%, transparent);
+ }
+ .ge-mask-sub-item.active {
+ border-left-color: var(--red);
+ opacity: 1;
+ }
+ .ge-clone-source-status {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-height: 24px;
+ margin: 2px 0 5px;
+ padding: 0 6px;
+ color: var(--fg);
+ opacity: 0.68;
+ font-size: 10px;
+ }
+ .ge-clone-source-status span { flex: 1; min-width: 0; }
+ .ge-clone-source-status .ge-icon-btn { margin-left: auto; }
+ .ge-mask-inline-thumb {
+ width: 34px;
+ height: 26px;
+ flex: 0 0 34px;
+ opacity: 0.78;
+ }
+ .ge-eraser-preview {
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: var(--fg);
+ flex-shrink: 0;
+ display: inline-block;
+ position: relative;
+ }
+ .ge-actions {
+ display: flex;
+ gap: 4px;
+ flex-wrap: wrap;
+ }
+ .ge-btn {
+ padding: 4px 8px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--fg);
+ font-size: 11px;
+ cursor: pointer;
+ transition: background 0.15s;
+ }
+ .ge-btn:hover { background: color-mix(in srgb, var(--fg) 10%, var(--bg)); }
+ .ge-btn.active {
+ background: color-mix(in srgb, var(--accent, var(--red)) 16%, var(--bg));
+ border-color: var(--accent, var(--red));
+ color: var(--accent, var(--red));
+ }
+ .ge-btn-sm { padding: 3px 6px; font-size: 10px; }
+ /* Busy state on AI tool buttons — whirlpool + verb text side by side. */
+ .ge-btn-processing {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ }
+ .ge-btn-busy-label { font-size: inherit; line-height: 1; }
+ /* Mask-vis eye button is icon-only — strip the inherited .ge-btn
+ background / border so it reads as a plain affordance, matching
+ the layer-row eye toggles. */
+ .ge-mask-vis-btn {
+ background: none !important;
+ border: none !important;
+ padding: 2px 4px !important;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0.5;
+ transition: opacity 0.12s;
+ }
+ .ge-mask-vis-btn:hover { opacity: 0.85; background: none !important; }
+ .ge-mask-vis-btn.visible { opacity: 0.9; }
+ /* Paint/Erase segmented toggle in the Inpaint Brush section. */
+ .ge-inpaint-mode-btn {
+ font-size: 11px;
+ padding: 4px 8px;
+ opacity: 0.6;
+ border: 1px solid var(--border);
+ }
+ .ge-inpaint-mode-btn:hover { opacity: 0.85; }
+ .ge-inpaint-mode-btn.active {
+ opacity: 1;
+ background: color-mix(in srgb, var(--accent, var(--red)) 18%, transparent);
+ border-color: var(--accent, var(--red));
+ color: var(--accent, var(--red));
+ font-weight: 600;
+ }
+ /* Wand New / + Add / − Subtract segmented toggle. */
+ .ge-wand-mode-btn {
+ flex: 1 1 0;
+ font-size: 11px;
+ padding: 4px 6px;
+ opacity: 0.6;
+ border: 1px solid var(--border);
+ }
+ .ge-wand-mode-btn:hover { opacity: 0.85; }
+ .ge-wand-mode-btn.active {
+ opacity: 1;
+ background: color-mix(in srgb, var(--accent, var(--red)) 18%, transparent);
+ border-color: var(--accent, var(--red));
+ color: var(--accent, var(--red));
+ font-weight: 600;
+ }
+ .ge-wand-live-btn {
+ flex: 0 0 auto;
+ opacity: 0.6;
+ min-width: 46px;
+ height: 22px;
+ padding: 0 10px !important;
+ border-radius: 999px !important;
+ font-size: 10px;
+ line-height: 1;
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ transition: opacity 0.15s, color 0.15s, border-color 0.15s, background 0.15s;
+ }
+ .ge-wand-live-btn:hover { opacity: 0.85; }
+ .ge-wand-live-btn.active {
+ opacity: 1;
+ background: color-mix(in srgb, var(--accent, var(--red)) 18%, transparent);
+ border-color: var(--accent, var(--red));
+ color: var(--accent, var(--red));
+ font-weight: 600;
+ }
+ /* Top-bar buttons (undo/redo, zoom +/-, Fit, 1:1, Resize, Edge, Import,
+ Download, Save) — visually their glyphs sit too low compared to the
+ surrounding labels, so shift contents up 2 px via asymmetric padding. */
+ /* Visually the buttons sit lower than the surrounding text labels on the
+ topbar. Keep the box padding symmetric but lift the whole box 2 px so it
+ centers against the adjacent label baselines. */
+ .ge-topbar .ge-btn,
+ .ge-topbar .ge-btn-sm,
+ .ge-topbar select,
+ .ge-topbar input { position: relative; top: -2px; }
+ /* The tiny "Gen" / "Inpaint" inline labels now look too high relative to
+ the shifted-up controls — nudge them down 2 px to re-align. */
+ .ge-topbar span[style*="font-size:9px"] { position: relative; top: 2px; }
+ /* The Gen and Inpaint model selects — must visually sit on the same line as
+ the small "Gen" / "Inpaint" labels (which are at top:2px). Use !important
+ so this beats the generic `.ge-topbar select` rule above no matter what
+ element-vs-class specificity quirks. */
+ .ge-topbar .ge-ai-model { position: relative !important; top: 1px !important; }
+ /* The ◢ glyph baseline reads lower than the surrounding text — shift it
+ up 1 px so it visually centers with the "Edge" label. */
+ .ge-edge-glyph { position: relative; top: -1px; }
+ /* Flex-line-break helper used in the mobile transform popup. Hidden by
+ default so desktop keeps its single-row layout. */
+ .ge-row-break { display: none; }
+ /* Stacked button — glyph on top, small uppercase label below. Currently
+ used for Undo/Redo so users get an obvious "UNDO" / "REDO" affordance
+ label without losing the compact icon. */
+ .ge-stacked-btn {
+ display: inline-flex !important;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 1px;
+ padding: 2px 8px !important;
+ line-height: 1;
+ }
+ .ge-stacked-btn .ge-stacked-glyph svg { display: block; }
+ .ge-stacked-btn .ge-stacked-caret {
+ margin-left: 2px;
+ font-size: 7px;
+ line-height: 1;
+ opacity: 0.55;
+ }
+ .ge-stacked-btn .ge-stacked-label {
+ font-size: 8px;
+ letter-spacing: 0.06em;
+ opacity: 0.65;
+ font-weight: 600;
+ position: relative;
+ top: 2px;
+ }
+ /* Zoom % indicator — magnifier glyph on top, percentage label below.
+ Matches the Undo/Redo stacked-button layout so the topbar reads as
+ one consistent row of stacked icons. */
+ .ge-zoom-stack {
+ display: inline-flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 1px;
+ line-height: 1;
+ padding: 0 4px;
+ }
+ .ge-zoom-stack .ge-zoom-glyph {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0.7;
+ /* Glyph nudged 1 px right (was 2 px left). */
+ position: relative;
+ left: -1px;
+ }
+ .ge-zoom-stack .ge-zoom-glyph svg {
+ width: 16px;
+ height: 16px;
+ }
+ .ge-zoom-stack .ge-zoom-label {
+ font-size: 8px;
+ letter-spacing: 0.06em;
+ opacity: 0.65;
+ font-weight: 600;
+ position: relative;
+ top: 4px;
+ left: 1px;
+ }
+ /* + Add sits 1 px below the title baseline to match the surrounding
+ header buttons after the recent header restructure. */
+ .ge-layers-header #ge-add-layer { position: relative; top: 1px; }
+ .ge-layer-blend-row {
+ display: grid;
+ grid-template-columns: 38px minmax(0, 1fr);
+ align-items: center;
+ gap: 6px;
+ padding: 4px 7px;
+ border-bottom: 1px solid color-mix(in srgb, var(--fg) 8%, transparent);
+ font-size: 10px;
+ color: color-mix(in srgb, var(--fg) 62%, transparent);
+ }
+ .ge-layer-blend-row select {
+ width: 100%;
+ min-width: 0;
+ height: 25px;
+ padding: 0 24px 0 7px;
+ border-radius: 4px;
+ font-size: 10px;
+ }
+ .ge-layer-selection-bar {
+ min-height: 30px;
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ padding: 3px 10px;
+ border-bottom: 1px solid var(--border);
+ background: color-mix(in srgb, var(--accent, var(--red)) 8%, var(--bg-secondary));
+ color: var(--fg);
+ font-size: 10px;
+ }
+ .ge-layer-selection-bar > span { flex: 1; opacity: 0.72; }
+ .ge-layer-selection-bar .ge-icon-btn {
+ width: 24px;
+ height: 24px;
+ min-width: 24px;
+ border: 0;
+ background: transparent;
+ color: inherit;
+ opacity: 0.72;
+ }
+ .ge-layer-selection-bar .ge-icon-btn.danger:hover { color: var(--red); }
+ /* Layer-row buttons in the right panel — the unicode glyphs (◉, ⤢) have
+ irregular baseline metrics so the box reads as too low; shift up 2 px. */
+ .ge-layer-vis,
+ .ge-layer-btn { position: relative; top: -2px; }
+ /* Delete (×) button glyph baseline reads even lower than the visibility
+ icon — push it up an extra 2 px so it visually centers. */
+ .ge-layer-btn.danger { top: -4px; }
+ /* Save / Save as new / Download dropdown anchored to the primary Save
+ button in the topbar. */
+ .ge-save-wrap {
+ position: relative;
+ display: inline-block;
+ flex-shrink: 0;
+ }
+ .ge-save-menu {
+ position: fixed;
+ min-width: 160px;
+ padding: 4px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 4px 14px color-mix(in srgb, var(--fg) 18%, transparent);
+ z-index: 10005;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+ .ge-save-state-icon { display: none; }
+ .ge-save-label { white-space: nowrap; min-width: 0; }
+ .ge-save-state-saved { color: var(--fg); }
+ .ge-save-menu .dropdown-item-compact {
+ width: 100%;
+ background: none;
+ border: none;
+ text-align: left;
+ font: inherit;
+ }
+
+ /* Resize and Edge popups in the topbar — same anchored-dropdown pattern as
+ the Save menu. Resize lists preset canvas sizes; Edge is a tiny form.
+ Image + Filter menus reuse the same chrome. */
+ .ge-resize-wrap,
+ .ge-edge-wrap,
+ .ge-view-wrap,
+ .ge-image-wrap,
+ .ge-selection-wrap,
+ .ge-filter-wrap { position: relative; display: inline-block; }
+ .ge-resize-menu,
+ .ge-edge-menu,
+ .ge-view-menu,
+ .ge-image-menu,
+ .ge-selection-menu,
+ .ge-filter-menu {
+ position: absolute;
+ top: calc(100% + 2px);
+ right: 0;
+ padding: 4px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 4px 14px color-mix(in srgb, var(--fg) 18%, transparent);
+ z-index: 12;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+ /* Mobile: escape the topbar's stacking context (z 5) so the dropdown
+ lands above the bottom-sheet panels (z 50 / 60). Switch to fixed and
+ pin under the topbar. */
+ @media (max-width: 820px) {
+ .ge-resize-menu,
+ .ge-edge-menu,
+ .ge-view-menu,
+ .ge-image-menu,
+ .ge-selection-menu,
+ .ge-filter-menu {
+ position: fixed;
+ top: 44px;
+ right: 8px;
+ z-index: 500;
+ max-width: calc(100vw - 16px);
+ }
+ }
+ .ge-resize-menu { min-width: 200px; }
+ .ge-edge-menu { min-width: 220px; padding: 10px; gap: 6px; }
+ .ge-view-menu { min-width: 174px; }
+ .ge-image-menu { min-width: 180px; }
+ .ge-selection-menu { min-width: 224px; }
+ .ge-filter-menu { min-width: 180px; }
+ .ge-resize-menu .dropdown-item-compact,
+ .ge-view-menu .dropdown-item-compact,
+ .ge-image-menu .dropdown-item-compact,
+ .ge-selection-menu .dropdown-item-compact,
+ .ge-filter-menu .dropdown-item-compact {
+ width: 100%;
+ background: none;
+ border: none;
+ text-align: left;
+ font: inherit;
+ }
+ .ge-view-toggle .ge-view-check { opacity: 0; }
+ .ge-view-toggle.active .ge-view-check { opacity: 1; color: var(--red); }
+ .ge-view-grid-size {
+ display: grid;
+ grid-template-columns: 1fr 52px auto;
+ align-items: center;
+ gap: 5px;
+ padding: 4px 8px;
+ font-size: 10px;
+ color: var(--color-muted);
+ }
+ .ge-view-grid-size input {
+ width: 52px;
+ height: 24px;
+ box-sizing: border-box;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--fg);
+ font: inherit;
+ text-align: right;
+ }
+ /* Sub-menu label inside the Filter / Image dropdown — small uppercase
+ header so "Blur" / "Selection" reads as a category, not an action. */
+ .ge-filter-submenu-label {
+ font-size: 9px;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ opacity: 0.45;
+ font-weight: 600;
+ padding: 4px 8px 2px;
+ pointer-events: none;
+ }
+ /* Disabled dropdown items (e.g. Fill when there's no selection) read
+ as muted + non-interactive. */
+ .ge-image-menu .dropdown-item-compact:disabled,
+ .ge-selection-menu .dropdown-item-compact:disabled,
+ .ge-filter-menu .dropdown-item-compact:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+ }
+ .ge-selection-save-row {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 28px;
+ gap: 5px;
+ padding: 3px 4px;
+ }
+ .ge-selection-save-row input {
+ min-width: 0;
+ height: 27px;
+ padding: 3px 7px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--fg);
+ font: inherit;
+ }
+ .ge-saved-selection-list { display: flex; flex-direction: column; gap: 1px; }
+ .ge-saved-selection-row { display: grid; grid-template-columns: minmax(0, 1fr) 26px; align-items: center; }
+ .ge-saved-selection-load,
+ .ge-saved-selection-delete {
+ min-width: 0;
+ height: 26px;
+ border: 0;
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ cursor: pointer;
+ }
+ .ge-saved-selection-load { padding: 3px 8px; overflow: hidden; text-align: left; text-overflow: ellipsis; white-space: nowrap; }
+ .ge-saved-selection-delete { opacity: 0.45; font-size: 15px; }
+ .ge-saved-selection-load:hover,
+ .ge-saved-selection-delete:hover { background: var(--hover); opacity: 1; }
+ .ge-saved-selection-empty { padding: 4px 8px 6px; font-size: 10px; opacity: 0.45; }
+ /* Filter live-preview modal — translucent backdrop over the editor
+ with a frosted parameter panel anchored top-right. The active layer
+ re-renders live as the user drags the sliders. */
+ .ge-filter-overlay {
+ position: absolute;
+ inset: 0;
+ z-index: 14;
+ display: flex;
+ align-items: flex-start;
+ justify-content: flex-end;
+ padding: 60px 20px 20px;
+ background: rgba(0, 0, 0, 0.18);
+ pointer-events: auto;
+ }
+ .ge-filter-modal {
+ width: 240px;
+ background: color-mix(in srgb, var(--panel) 95%, transparent);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 6px 18px rgba(0, 0, 0, 0.35);
+ backdrop-filter: blur(10px);
+ padding: 12px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .ge-filter-modal-head {
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ opacity: 0.7;
+ }
+ .ge-filter-row {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+ .ge-filter-row label {
+ font-size: 10px;
+ opacity: 0.7;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ }
+ .ge-filter-row-value {
+ font-variant-numeric: tabular-nums;
+ font-weight: 600;
+ opacity: 0.85;
+ }
+ .ge-filter-row input[type="range"] {
+ width: 100%;
+ }
+ .ge-filter-row input[type="color"] {
+ width: 100%;
+ height: 24px;
+ padding: 1px;
+ border: 1px solid var(--border, #333);
+ border-radius: 4px;
+ background: transparent;
+ cursor: pointer;
+ }
+ .ge-filter-modal-actions {
+ display: flex;
+ gap: 6px;
+ justify-content: flex-end;
+ margin-top: 4px;
+ }
+
+ /* Controlled image export. */
+ .ge-export-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 10020;
+ display: grid;
+ place-items: center;
+ padding: 16px;
+ background: rgba(0, 0, 0, 0.56);
+ }
+ .ge-export-dialog {
+ width: min(720px, calc(100vw - 32px));
+ max-height: calc(100vh - 32px);
+ overflow: auto;
+ background: var(--panel);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 18px 54px rgba(0, 0, 0, 0.48);
+ }
+ .ge-export-head,
+ .ge-export-footer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 12px 14px;
+ }
+ .ge-export-head { border-bottom: 1px solid var(--border); }
+ .ge-export-head h2 {
+ margin: 0;
+ font-size: 13px;
+ letter-spacing: 0;
+ }
+ .ge-export-close {
+ border: 0;
+ background: transparent;
+ color: var(--fg);
+ width: 28px;
+ height: 28px;
+ padding: 0;
+ font-size: 20px;
+ line-height: 1;
+ cursor: pointer;
+ opacity: 0.6;
+ }
+ .ge-export-close:hover { opacity: 1; }
+ .ge-export-body {
+ display: grid;
+ grid-template-columns: minmax(260px, 1.25fr) minmax(220px, 0.75fr);
+ gap: 14px;
+ padding: 14px;
+ }
+ .ge-export-preview-wrap {
+ min-height: 300px;
+ display: grid;
+ place-items: center;
+ overflow: hidden;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background-color: #22262d;
+ background-image:
+ linear-gradient(45deg, rgba(255,255,255,0.06) 25%, transparent 25%),
+ linear-gradient(-45deg, rgba(255,255,255,0.06) 25%, transparent 25%),
+ linear-gradient(45deg, transparent 75%, rgba(255,255,255,0.06) 75%),
+ linear-gradient(-45deg, transparent 75%, rgba(255,255,255,0.06) 75%);
+ background-size: 20px 20px;
+ background-position: 0 0, 0 10px, 10px -10px, -10px 0;
+ }
+ .ge-export-preview {
+ display: block;
+ max-width: calc(100% - 24px);
+ max-height: 420px;
+ box-shadow: 0 4px 18px rgba(0,0,0,0.38);
+ }
+ .ge-export-fields {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ }
+ .ge-export-field {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ min-width: 0;
+ font-size: 10px;
+ opacity: 0.78;
+ }
+ .ge-export-field > span {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ }
+ .ge-export-field input[type="text"],
+ .ge-export-field input[type="number"] {
+ width: 100%;
+ box-sizing: border-box;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ padding: 7px 8px;
+ font: inherit;
+ font-size: 11px;
+ }
+ .ge-export-field input:focus { outline: none; border-color: var(--red); }
+ .ge-export-format {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ border: 1px solid var(--border);
+ border-radius: 5px;
+ overflow: hidden;
+ }
+ .ge-export-format button {
+ min-height: 30px;
+ border: 0;
+ border-right: 1px solid var(--border);
+ background: var(--bg);
+ color: var(--fg);
+ font: inherit;
+ font-size: 10px;
+ cursor: pointer;
+ }
+ .ge-export-format button:last-child { border-right: 0; }
+ .ge-export-format button.active {
+ background: color-mix(in srgb, var(--red) 18%, var(--bg));
+ color: var(--red);
+ }
+ .ge-export-dimensions {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 28px minmax(0, 1fr);
+ gap: 5px;
+ align-items: end;
+ }
+ .ge-export-link {
+ width: 28px;
+ height: 29px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--fg);
+ opacity: 0.45;
+ cursor: pointer;
+ }
+ .ge-export-link.active { opacity: 1; color: var(--red); border-color: var(--red); }
+ .ge-export-quality input { width: 100%; accent-color: var(--red); }
+ .ge-export-surface-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ border-top: 1px solid var(--border);
+ padding-top: 10px;
+ }
+ .ge-export-toggle,
+ .ge-export-matte {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 10px;
+ }
+ .ge-export-matte.disabled { opacity: 0.35; pointer-events: none; }
+ .ge-export-footer {
+ border-top: 1px solid var(--border);
+ font-size: 10px;
+ }
+ @media (max-width: 700px) {
+ .ge-export-overlay { padding: 8px; place-items: end center; }
+ .ge-export-dialog { width: 100%; max-height: calc(100dvh - 16px); }
+ .ge-export-body { grid-template-columns: 1fr; padding: 10px; }
+ .ge-export-preview-wrap { min-height: 190px; max-height: 260px; }
+ .ge-export-preview { max-height: 230px; }
+ }
+ .ge-menu-divider {
+ height: 1px;
+ background: var(--border);
+ margin: 4px 0;
+ }
+ .ge-edge-form {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .ge-edge-label {
+ font-size: 11px;
+ opacity: 0.65;
+ }
+ .ge-edge-input {
+ padding: 6px 8px;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ font: inherit;
+ font-size: 12px;
+ }
+ .ge-edge-input:focus { outline: none; border-color: var(--red); }
+ .ge-edge-actions {
+ display: flex;
+ gap: 6px;
+ }
+ .ge-edge-actions .ge-btn { flex: 1; }
+ .ge-edge-hint {
+ margin: 0;
+ font-size: 10px;
+ opacity: 0.5;
+ line-height: 1.4;
+ }
+
+ /* Styled "New canvas" prompt — replaces the native browser prompt(). */
+ .ge-canvas-prompt {
+ max-width: 430px;
+ width: 90vw;
+ }
+ .ge-canvas-prompt .modal-header h4 { margin: 0; font-size: 14px; }
+ .ge-canvas-prompt-row {
+ display: flex;
+ align-items: flex-end;
+ gap: 10px;
+ justify-content: center;
+ margin: 6px 0 2px;
+ }
+ .ge-canvas-prompt-field {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ flex: 1;
+ min-width: 0;
+ }
+ .ge-canvas-prompt-field > span {
+ font-size: 11px;
+ opacity: 0.65;
+ }
+ .ge-canvas-prompt-field input {
+ width: 100%;
+ padding: 8px 10px;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ font: inherit;
+ font-size: 14px;
+ }
+ .ge-canvas-prompt-field input:focus { outline: none; border-color: var(--red); }
+ .ge-canvas-prompt-x {
+ font-size: 18px;
+ opacity: 0.4;
+ align-self: center;
+ padding-bottom: 8px;
+ position: relative;
+ top: 8px;
+ }
+ .ge-canvas-prompt-hint {
+ margin: 0 auto 0 0;
+ font-size: 11px;
+ opacity: 0.5;
+ line-height: 1.35;
+ text-align: left;
+ }
+ .ge-canvas-prompt-section-label {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ margin: 2px 0 7px;
+ font-size: 10px;
+ font-weight: 650;
+ letter-spacing: .04em;
+ text-transform: uppercase;
+ opacity: .62;
+ }
+ .ge-canvas-units-field {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ margin: 8px 0 2px;
+ font-size: 11px;
+ opacity: .75;
+ }
+ .ge-canvas-control-label {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ min-width: 0;
+ }
+ .ge-canvas-prompt-icon,
+ .ge-canvas-preset-icon {
+ flex: 0 0 auto;
+ opacity: .68;
+ }
+ .ge-canvas-units-field select,
+ .ge-canvas-interpolation-field select {
+ min-width: 112px;
+ padding: 5px 7px;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ font: inherit;
+ }
+ .ge-canvas-anchor-label {
+ margin: 14px 0 6px;
+ font-size: 10px;
+ font-weight: 650;
+ letter-spacing: .04em;
+ text-transform: uppercase;
+ opacity: .62;
+ text-align: center;
+ }
+ .ge-canvas-anchor-grid {
+ display: grid;
+ grid-template-columns: repeat(3, 22px);
+ gap: 5px;
+ justify-content: center;
+ }
+ .ge-canvas-anchor {
+ width: 22px;
+ height: 22px;
+ padding: 0;
+ border: 1px solid color-mix(in srgb, var(--border) 85%, transparent);
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ cursor: pointer;
+ position: relative;
+ }
+ .ge-canvas-anchor:hover,
+ .ge-canvas-anchor.active {
+ border-color: var(--red);
+ background: color-mix(in srgb, var(--red) 12%, transparent);
+ }
+ .ge-canvas-resize-options {
+ display: flex;
+ align-items: flex-end;
+ justify-content: space-between;
+ gap: 12px;
+ margin-top: 12px;
+ }
+ .ge-canvas-lock-option {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ font-size: 11px;
+ opacity: .72;
+ cursor: pointer;
+ }
+ .ge-canvas-interpolation-field {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 11px;
+ opacity: .72;
+ }
+ .ge-canvas-interpolation-field select {
+ min-width: 92px;
+ padding: 4px 6px;
+ border: 1px solid var(--border);
+ border-radius: 5px;
+ background: var(--bg);
+ color: var(--fg);
+ font: inherit;
+ }
+ .ge-canvas-preset-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 6px;
+ }
+ .ge-canvas-preset {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 3px;
+ min-width: 0;
+ padding: 8px 9px;
+ border: 1px solid color-mix(in srgb, var(--border) 85%, transparent);
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--fg) 4%, transparent);
+ color: var(--fg);
+ font: inherit;
+ text-align: left;
+ cursor: pointer;
+ box-sizing: border-box;
+ overflow: hidden;
+ }
+ .ge-canvas-preset:hover,
+ .ge-canvas-preset.active {
+ border-color: var(--red);
+ background: color-mix(in srgb, var(--red) 12%, transparent);
+ }
+ .ge-canvas-preset span,
+ .ge-canvas-preset strong {
+ display: block;
+ width: 100%;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .ge-canvas-preset span { font-size: 11px; font-weight: 600; }
+ .ge-canvas-preset strong { font-size: 10px; font-weight: 500; opacity: .62; }
+ .ge-canvas-prompt-footer {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 8px;
+ padding-top: 8px;
+ border-top: 1px solid var(--border);
+ margin-top: 8px;
+ }
+
+ .ge-btn-primary {
+ background: var(--red);
+ color: #fff;
+ border-color: var(--red);
+ font-weight: 600;
+ }
+ .ge-btn-primary:hover { background: color-mix(in srgb, var(--red) 85%, #000); }
+ .ge-zoom-label { font-size: 10px; opacity: 0.5; }
+
+ /* Nudge whirlpool spinners 1px down so they sit on the text baseline
+ when placed inside action buttons (Generate, Harmonize, etc). */
+ .ge-btn .ai-spinner-whirlpool,
+ .ge-btn .spinner-whirlpool,
+ button .ai-spinner-whirlpool,
+ button .spinner-whirlpool {
+ position: relative;
+ top: 1px;
+ }
+
+ /* Layers panel */
+ .ge-layers {
+ /* Natural height now that the whole right panel scrolls — flex:1
+ would collapse the list inside a scrolling parent. */
+ flex: 0 0 auto;
+ display: flex;
+ flex-direction: column;
+ }
+ /* Vertical drag handle that sits on the LEFT edge of the right panel.
+ Drag horizontally to widen / narrow the entire side panel. Slim
+ by default; brighter on hover so the user notices it's interactive. */
+ .ge-panel-resize {
+ position: absolute;
+ left: -3px;
+ top: 0;
+ bottom: 0;
+ width: 6px;
+ cursor: ew-resize;
+ background: transparent;
+ z-index: 5;
+ transition: background 0.12s;
+ }
+ .ge-panel-resize:hover,
+ .ge-panel-resize:active {
+ background: color-mix(in srgb, var(--red) 30%, transparent);
+ }
+ /* The right panel needs `position: relative` so the handle (absolute)
+ anchors to it instead of the viewport. */
+ .ge-right-panel {
+ position: relative;
+ }
+
+ /* Floating value bubble that pops above the slider thumb while
+ dragging. Solves the "I can't see the number" problem when the
+ slider's opaque plate covers the row's right-edge value chip. */
+ .ge-slider-bubble {
+ /* Fixed positioning so the bubble escapes any overflow:hidden/auto
+ on the slider's ancestor chain (the layers list clips, and used
+ to swallow the bubble entirely). JS sets viewport-relative
+ left/top; the translate centers and lifts the bubble above the
+ slider thumb. */
+ position: fixed;
+ transform: translate(-50%, -100%);
+ z-index: 10000;
+ padding: 5px 10px;
+ background: var(--red);
+ color: #fff;
+ font-size: 13px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ border-radius: 6px;
+ box-shadow: 0 3px 10px color-mix(in srgb, var(--red) 40%, transparent);
+ pointer-events: none;
+ white-space: nowrap;
+ opacity: 0;
+ transition: opacity 0.1s;
+ }
+ .ge-slider-bubble.visible { opacity: 1; }
+
+ /* Floating thumbnail shown when hovering a layer row. */
+ .ge-layer-thumb {
+ position: fixed;
+ z-index: 60;
+ padding: 4px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 6px 18px color-mix(in srgb, var(--fg) 30%, transparent);
+ pointer-events: none;
+ display: none;
+ }
+ .ge-layers-header {
+ display: flex;
++ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 10px;
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--fg);
+ opacity: 0.8;
+ border-bottom: 1px solid var(--border);
+ position: relative;
+ }
+ .ge-layers-title { flex: 1; }
++.ge-layers-header #ge-add-layer { flex: 0 0 auto; white-space: nowrap; }
++.ge-layer-header-tools {
++ display: flex;
++ flex: 0 0 100%;
++ flex-wrap: wrap;
++ align-items: center;
++ gap: 6px;
++}
+ .ge-layers-grab { display: none; } /* mobile only */
+ .ge-layers-merge-wrap { position: relative; display: inline-flex; }
+ .ge-layers-merge-wrap #ge-layers-merge-btn { position: relative; top: 0; }
+ .ge-layers-merge-menu {
+ /* Fixed positioning so the menu escapes the layers panel's overflow
+ clipping (which made it look transparent). JS sets exact coords
+ via getBoundingClientRect on the trigger button at open time. */
+ position: fixed;
+ z-index: 200;
+ min-width: 160px;
+ padding: 4px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 4px 14px color-mix(in srgb, var(--fg) 18%, transparent);
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ pointer-events: auto;
+ }
+ .ge-layers-merge-menu .dropdown-item-compact {
+ width: 100%;
+ background: none;
+ border: none;
+ text-align: left;
+ font: inherit;
+ }
+ .ge-layers-actions {
+ display: flex;
+ gap: 4px;
+ padding: 6px 8px;
+ border-top: 1px solid var(--border);
+ flex-wrap: wrap;
+ /* Pin the action row to the bottom of the right panel's scroll
+ viewport. Without this, when the tool-controls section is tall
+ enough to overflow the panel, the merge buttons get pushed below
+ the fold and require scrolling to reach. */
+ position: sticky;
+ bottom: 0;
+ background: var(--panel);
+ z-index: 4;
+ /* Centered cluster instead of stretching the buttons to fill the
+ panel width. */
+ justify-content: center;
+ }
+ /* Merge / flatten buttons sit content-sized so the cluster reads as a
+ centered group of three, not three stretched bars across the panel. */
+ .ge-layers-actions .ge-btn {
+ flex: 0 0 auto;
+ min-width: 0;
+ padding: 4px 8px;
+ font-size: 10px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ white-space: nowrap;
+ }
+ .ge-layers-actions .ge-icon-btn {
+ /* Icon-only buttons stay narrow — no risk of label overflow. */
+ flex: 0 0 auto;
+ padding: 4px 8px;
+ }
+ .ge-layers-actions .ge-btn svg {
+ flex-shrink: 0;
+ margin-right: 0 !important;
+ }
+ .ge-layers-list {
+ /* Cap the list so a huge layer stack scrolls within its own box
+ rather than pushing the whole panel arbitrarily tall. */
+ max-height: 320px;
++ min-height: 0;
+ overflow-y: auto;
+ overflow-x: hidden;
- padding: 0;
++ padding: 0 0 6px;
+ }
+ .ge-layer-item {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 5px 8px;
+ cursor: pointer;
+ border-left: 2px solid transparent;
+ transition: background 0.1s;
+ font-size: 11px;
+ color: var(--fg);
+ }
+ .ge-layer-item:focus-visible,
+ .ge-layer-group-row:focus-visible {
+ outline: 1px solid var(--accent, var(--red));
+ outline-offset: -1px;
+ }
+ @media (min-width: 701px) {
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) {
+ display: grid;
+ grid-template-columns: 12px 22px 34px minmax(0, 1fr) 24px;
+ row-gap: 5px;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-drag {
+ grid-column: 1;
+ grid-row: 1;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-vis {
+ grid-column: 2;
+ grid-row: 1;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-inline-thumb {
+ grid-column: 3;
+ grid-row: 1;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-name,
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-name-input {
+ grid-column: 4;
+ grid-row: 1;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-lock-btn {
+ grid-column: 5;
+ grid-row: 1;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-opacity-row {
+ grid-column: 1 / -1;
+ grid-row: 2;
+ width: 100%;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-controls {
+ grid-column: 1 / -1;
+ grid-row: 3;
+ justify-content: flex-end;
+ min-width: 0;
+ }
+ }
+ .ge-layer-inline-thumb {
+ display: block;
+ width: 34px;
+ height: 26px;
+ flex: 0 0 34px;
+ object-fit: contain;
+ border: 1px solid color-mix(in srgb, var(--border) 80%, transparent);
+ border-radius: 3px;
+ background: #303030;
+ image-rendering: auto;
+ }
+ /* Row-hover tint removed — kept the layer row's background stable so
+ it doesn't shift visually as the user reaches for the opacity slider. */
+ .ge-layer-item.active {
- background: color-mix(in srgb, var(--red) 8%, transparent);
- border-left-color: var(--red);
++ background: color-mix(in srgb, var(--accent, var(--red)) 52%, var(--bg-secondary, var(--bg)));
++ border-left-color: var(--accent, var(--red));
++ box-shadow: inset 3px 0 0 var(--accent, var(--red)), inset 0 0 0 1px color-mix(in srgb, var(--accent, var(--red)) 80%, transparent);
+ }
++.ge-layer-item.active > .ge-layer-name,
++.ge-layer-group-row.active > .ge-layer-group-name { font-weight: 700; }
+ /* "Active parent" — the layer is selected, but a mask sub-layer below
+ it is the actual paint target. Soft hint so the user can see which
+ parent owns the active mask without competing with the mask's
+ strong red highlight. */
+ .ge-layer-item.active-parent {
+ background: color-mix(in srgb, var(--fg) 4%, transparent);
+ border-left-color: color-mix(in srgb, var(--fg) 30%, transparent);
+ }
+ .ge-layer-item.selected:not(.active):not(.active-parent) {
- background: color-mix(in srgb, var(--accent, var(--red)) 7%, transparent);
++ background: color-mix(in srgb, var(--accent, var(--red)) 22%, var(--bg));
+ box-shadow: inset 2px 0 0 color-mix(in srgb, var(--accent, var(--red)) 55%, transparent);
+ }
+ .ge-layer-group-row {
+ min-height: 36px;
+ display: grid;
+ grid-template-columns: 12px 18px 24px 34px minmax(0, 1fr) 24px;
+ grid-template-rows: auto auto auto;
+ align-items: center;
+ gap: 3px;
+ padding: 3px 7px 3px calc(7px + var(--group-depth, 0) * 14px);
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 72%, transparent);
+ background: color-mix(in srgb, var(--bg-secondary) 78%, var(--bg));
+ color: var(--fg);
+ width: 100%;
+ box-sizing: border-box;
+ }
+ .ge-layer-group-row .ge-layer-group-drag { grid-column: 1; grid-row: 1; }
+ .ge-layer-group-row .ge-layer-group-toggle { grid-column: 2; grid-row: 1; }
+ .ge-layer-group-row .ge-layer-vis { grid-column: 3; grid-row: 1; }
+ .ge-layer-group-row .ge-group-inline-thumb { grid-column: 4; grid-row: 1; }
+ .ge-layer-group-row .ge-layer-group-name { grid-column: 5; grid-row: 1; }
+ .ge-layer-group-row .ge-layer-lock-btn { grid-column: 6; grid-row: 1; }
+ .ge-layer-group-row .ge-layer-opacity-row {
+ grid-column: 1 / -1;
+ grid-row: 2;
+ display: flex;
+ width: 100%;
+ min-width: 0;
+ }
+ .ge-layer-group-row .ge-layer-opacity-row .ge-layer-opacity {
+ flex: 1 1 auto;
+ width: 100%;
+ min-width: 0;
+ }
+ .ge-layer-opacity-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ }
+ .ge-layer-opacity-row .ge-layer-opacity { flex: 1 1 auto; width: auto; }
+ .ge-layer-group-row .ge-layer-controls {
+ grid-column: 1 / -1;
+ grid-row: 3;
+ justify-content: flex-end;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-opacity-row {
+ grid-column: 1 / -1;
+ grid-row: 2;
+ width: 100%;
+ }
+ .ge-layer-group-drag { touch-action: none; }
+ .ge-layer-group-row.group-dragging {
+ opacity: 0.62;
+ outline: 1px solid color-mix(in srgb, var(--accent, var(--red)) 65%, transparent);
+ }
+ .ge-group-drop-line {
+ position: absolute;
+ z-index: 20;
+ left: 6px;
+ right: 6px;
+ height: 2px;
+ pointer-events: none;
+ background: var(--accent, var(--red));
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--bg) 65%, transparent);
+ }
+ .ge-layer-group-row.active {
- background: color-mix(in srgb, var(--accent, var(--red)) 12%, var(--bg-secondary));
- box-shadow: inset 2px 0 0 var(--accent, var(--red));
++ background: color-mix(in srgb, var(--accent, var(--red)) 38%, var(--bg-secondary));
++ box-shadow: inset 2px 0 0 var(--accent, var(--red)), inset 0 0 0 1px color-mix(in srgb, var(--accent, var(--red)) 50%, transparent);
+ }
+ .ge-layer-group-toggle {
+ width: 18px;
+ height: 22px;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: inherit;
+ opacity: 0.62;
+ }
+ .ge-layer-group-toggle svg { transition: transform 120ms ease; }
+ .ge-layer-group-toggle.expanded svg { transform: rotate(90deg); }
+ .ge-layer-group-name {
+ min-width: 0;
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ overflow: hidden;
+ font-size: 11px;
+ font-weight: 600;
+ }
+ .ge-layer-group-name span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .ge-group-mask-sub-item { padding-left: calc(20px + var(--group-mask-depth, 1) * 14px); }
+ .ge-layer-vis {
+ border: none;
+ background: none;
+ color: var(--fg);
+ cursor: pointer;
+ padding: 2px 4px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0.4;
+ transition: opacity 0.12s;
+ }
+ .ge-layer-vis:hover { opacity: 0.8; }
+ .ge-layer-vis.visible { opacity: 0.9; }
+ .ge-layer-name {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ min-width: 0;
+ }
+ .ge-layer-clipped-marker {
+ display: inline-flex;
+ align-items: center;
+ flex: 0 0 auto;
+ color: var(--accent, var(--red));
+ opacity: 0.82;
+ }
+ .ge-layer-name-input {
+ flex: 1;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ color: var(--fg);
+ font-size: 11px;
+ padding: 1px 4px;
+ border-radius: 3px;
+ min-width: 0;
+ }
+ /* All sliders inside the image editor share the same visual language as
+ the layer opacity slider — rounded pill, dim track, red thumb. Track
+ AND thumb grow when interacting for finer tweaking. */
+ .gallery-editor-container input[type="range"] {
+ -webkit-appearance: none;
+ appearance: none;
+ height: 4px;
+ background: color-mix(in srgb, var(--fg) 25%, transparent);
+ border-radius: 999px;
+ accent-color: var(--red);
+ cursor: pointer;
+ transition: height 0.15s ease;
+ }
+ .gallery-editor-container input[type="range"]:hover,
+ .gallery-editor-container input[type="range"]:focus,
+ .gallery-editor-container input[type="range"]:active {
+ height: 10px;
+ }
+ .gallery-editor-container input[type="range"]::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 12px;
+ height: 12px;
+ border-radius: 50%;
+ background: var(--red);
+ border: none;
+ cursor: pointer;
+ transition: width 0.12s ease, height 0.12s ease;
+ }
+ .gallery-editor-container input[type="range"]::-moz-range-thumb {
+ width: 12px;
+ height: 12px;
+ border-radius: 50%;
+ background: var(--red);
+ border: none;
+ cursor: pointer;
+ transition: width 0.12s ease, height 0.12s ease;
+ }
+ .gallery-editor-container input[type="range"]:hover::-webkit-slider-thumb,
+ .gallery-editor-container input[type="range"]:focus::-webkit-slider-thumb,
+ .gallery-editor-container input[type="range"]:active::-webkit-slider-thumb {
+ width: 18px;
+ height: 18px;
+ }
+ .gallery-editor-container input[type="range"]:hover::-moz-range-thumb,
+ .gallery-editor-container input[type="range"]:focus::-moz-range-thumb,
+ .gallery-editor-container input[type="range"]:active::-moz-range-thumb {
+ width: 18px;
+ height: 18px;
+ }
+
+ /* Layer-row opacity slider — fixed track, only thumb grows on
+ interaction. Takes a bit of row space at rest, but no jumpy expand
+ animation. */
+ .ge-layer-opacity {
+ width: 70px;
+ height: 6px;
+ accent-color: var(--red);
+ flex-shrink: 0;
+ -webkit-appearance: none;
+ appearance: none;
+ background: color-mix(in srgb, var(--fg) 25%, transparent);
+ border-radius: 999px;
+ position: relative;
+ top: 0;
+ }
+ .ge-layer-opacity:hover::-webkit-slider-thumb,
+ .ge-layer-opacity:active::-webkit-slider-thumb,
+ .ge-layer-opacity.dragging::-webkit-slider-thumb {
+ width: 18px;
+ height: 18px;
+ }
+ .ge-layer-opacity:hover::-moz-range-thumb,
+ .ge-layer-opacity:active::-moz-range-thumb,
+ .ge-layer-opacity.dragging::-moz-range-thumb {
+ width: 18px;
+ height: 18px;
+ }
+ .ge-layer-controls {
+ display: flex;
+ gap: 2px;
+ flex-shrink: 0;
+ }
+ .ge-layer-controls .ge-mask-inspect-btn.active {
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ }
+ .ge-mask-properties {
+ position: relative;
- flex: 0 0 30px;
++ flex: 0 0 22px;
+ }
+ .ge-mask-properties > summary:hover,
+ .ge-mask-properties[open] > summary {
- color: var(--accent, var(--red));
- background: color-mix(in srgb, var(--accent, var(--red)) 12%, transparent);
++ opacity: 0.8;
+ }
++.ge-mask-properties[open] > summary { color: var(--accent, var(--red)); opacity: 0.95; }
+ .ge-mask-properties-panel {
+ position: fixed;
++ box-sizing: border-box;
++ margin: 0;
++ bottom: auto;
++ overflow: auto;
++ color: var(--fg);
+ z-index: 9999;
+ right: auto;
+ top: 0;
+ width: 190px;
+ padding: 8px;
+ display: grid;
+ gap: 7px;
+ border: 1px solid color-mix(in srgb, var(--border) 85%, transparent);
+ border-radius: 5px;
+ background: var(--bg-secondary, var(--bg));
+ box-shadow: 0 8px 24px rgba(0,0,0,.28);
+ }
++.ge-mask-properties-panel:not(:popover-open) { display: none; }
+ .ge-mask-property-row {
+ display: grid;
+ grid-template-columns: 52px minmax(0, 1fr) 35px;
+ align-items: center;
+ gap: 6px;
+ font-size: 10px;
+ }
+ .ge-mask-property-row input { min-width: 0; width: 100%; }
+ .ge-mask-apply-btn {
+ width: 100%;
+ min-height: 26px;
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 55%, var(--border));
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--accent, var(--red)) 12%, transparent);
+ color: var(--fg);
+ cursor: pointer;
+ font-size: 10px;
+ }
+ .ge-mask-apply-btn:hover { background: color-mix(in srgb, var(--accent, var(--red)) 22%, transparent); }
+ .ge-layer-tools {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 2px;
+ min-height: 34px;
+ padding: 3px 7px;
+ border-top: 1px solid color-mix(in srgb, var(--border) 80%, transparent);
+ background: color-mix(in srgb, var(--bg-secondary) 72%, var(--bg));
+ }
+ .ge-layer-tools .ge-layer-controls {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ width: 100%;
+ }
+ .ge-eyedropper-live {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ min-height: 28px;
+ padding: 3px 6px;
+ border: 1px solid color-mix(in srgb, var(--border) 82%, transparent);
+ border-radius: 5px;
+ background: color-mix(in srgb, var(--fg) 4%, transparent);
+ }
+ .ge-eyedropper-loupe {
+ width: 42px;
+ height: 42px;
+ flex: 0 0 42px;
+ border-radius: 4px;
+ image-rendering: pixelated;
+ background: var(--bg);
+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--fg) 22%, transparent);
+ }
+ .ge-eyedropper-live-swatch {
+ width: 20px;
+ height: 20px;
+ flex: 0 0 20px;
+ border-radius: 4px;
+ background: transparent;
+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--fg) 22%, transparent);
+ }
+ .ge-eyedropper-live-values {
+ display: grid;
+ gap: 1px;
+ min-width: 0;
+ font-size: 10px;
+ line-height: 1.25;
+ }
+ .ge-eyedropper-live-values > span { opacity: .62; font-variant-numeric: tabular-nums; }
+ .ge-eyedropper-live-swatch.empty {
+ background: repeating-linear-gradient(135deg, transparent 0 4px, color-mix(in srgb, var(--fg) 18%, transparent) 4px 6px);
+ }
+ .ge-eyedropper-live code {
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+ opacity: .75;
+ }
+ /* Left-edge drag handle on each layer row. */
+ .ge-layer-drag {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 12px;
+ margin-right: 2px;
+ opacity: 0.4;
+ cursor: grab;
+ touch-action: none;
+ user-select: none;
+ flex-shrink: 0;
+ }
+ .ge-layer-drag:hover { opacity: 0.85; }
+ /* While dragSort lifts the item via absolute positioning, the placeholder
+ slot shows where it'll land — give it a subtle red outline so users see
+ the target clearly. */
+ .ge-layers-list .drag-placeholder {
+ background: color-mix(in srgb, var(--red) 12%, transparent);
+ border: 1px dashed color-mix(in srgb, var(--red) 50%, transparent);
+ border-radius: 4px;
+ box-sizing: border-box;
+ }
+ .ge-layer-item.dragging {
+ background: var(--panel);
+ box-shadow: 0 4px 14px color-mix(in srgb, var(--fg) 25%, transparent);
+ border-radius: 4px;
+ }
+ .ge-layer-btn {
+ border: none;
+ background: none;
+ color: var(--fg);
+ cursor: pointer;
+ font-size: 12px;
+ padding: 0 2px;
+ opacity: 0.4;
+ transition: opacity 0.1s;
+ }
+ .ge-layer-btn:hover { opacity: 0.8; }
+ .ge-layer-btn.active { color: var(--accent, var(--red)); opacity: 0.95; }
+ .ge-layer-btn:disabled { cursor: default; opacity: 0.16; }
++.ge-layer-style-btn { font-style: italic; font-weight: 700; font-size: 13px; }
++.ge-layer-style-menu {
++ animation: none;
++ position: fixed;
++ inset: auto;
++ margin: 0;
++ padding: 4px;
++ min-width: 170px;
++ max-width: calc(100vw - 12px);
++ max-height: calc(100dvh - 12px);
++ overflow-y: auto;
++ box-sizing: border-box;
++ background: var(--panel, var(--bg));
++ color: var(--fg);
++ border: 1px solid var(--border);
++ border-radius: 6px;
++ box-shadow: 0 8px 24px #0005;
++}
++.ge-layer-style-menu:not(:popover-open) { display: none; }
++.ge-layer-style-menu:popover-open { display: block; }
++.ge-layer-style-menu > button { width: 100%; border: 0; background: none; font: inherit; text-align: left; }
+ .ge-layer-btn.danger:hover { color: var(--red); opacity: 1; }
+
+ .ge-layer-lock-menu {
+ position: fixed;
+ z-index: 10004;
+ width: 176px;
+ padding: 4px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--panel, var(--bg));
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.28);
+ }
+ .ge-layer-lock-option {
+ width: 100%;
+ height: 30px;
+ display: grid;
+ grid-template-columns: 20px minmax(0, 1fr);
+ align-items: center;
+ gap: 6px;
+ padding: 0 8px;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ color: var(--fg);
+ font: inherit;
+ font-size: 11px;
+ text-align: left;
+ cursor: pointer;
+ }
+ .ge-layer-lock-option:hover,
+ .ge-layer-lock-option:focus-visible {
+ outline: none;
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
+ .ge-layer-align-menu { width: 218px; }
+ .ge-layer-lock-check {
+ width: 16px;
+ height: 16px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid color-mix(in srgb, var(--fg) 28%, transparent);
+ border-radius: 3px;
+ color: var(--accent, var(--red));
+ font-size: 11px;
+ line-height: 1;
+ }
+ @media (max-width: 700px) {
+ .ge-layer-lock-menu { width: auto; }
+ .ge-layer-lock-option { height: 44px; font-size: 13px; }
+ }
+
+ /* Crop apply button */
+ .ge-crop-apply {
+ position: absolute;
+ z-index: 10;
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 6px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ box-shadow: 0 2px 8px rgba(0,0,0,0.3);
+ }
+ .ge-crop-apply input[type="number"] {
+ width: 56px;
+ padding: 3px 4px;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ font: inherit;
+ font-size: 11px;
+ -moz-appearance: textfield;
+ }
+ .ge-crop-x { font-size: 11px; opacity: 0.5; }
+ .ge-crop-apply-btn {
+ padding: 4px 10px;
+ background: var(--red);
+ color: #fff;
+ border: none;
+ border-radius: 4px;
+ font-size: 11px;
+ font-weight: 600;
+ cursor: pointer;
+ position: relative;
+ top: -2px;
+ }
+ .ge-crop-apply-btn:hover { background: color-mix(in srgb, var(--red) 85%, #000); }
+
+ /* Text input floating */
+ .ge-text-input {
+ background: var(--bg);
+ border: 1px solid var(--red);
+ color: var(--fg);
+ padding: 4px 8px;
+ font-size: 14px;
+ border-radius: 4px;
+ min-width: 120px;
+ }
+ .ge-brush-cursor {
+ position: fixed; pointer-events: none; z-index: 2147483647;
+ border: 1.5px solid #fff; border-radius: 50%;
+ box-shadow: 0 0 0 1px rgba(0,0,0,0.72);
+ display: none;
+ box-sizing: border-box;
+ }
+ .ge-inpaint-section {
+ padding: 8px 0; border-top: 1px solid var(--border); margin-top: 4px;
+ }
+ .ge-inpaint-popover-head {
+ display: none;
+ }
+ @media (min-width: 821px) {
+ .ge-controls.ge-inpaint-popover-host {
+ padding: 0;
+ border-bottom: 0;
+ gap: 0;
+ }
+ .ge-inpaint-section.ge-inpaint-popover {
+ position: fixed;
+ z-index: 10004;
+ width: 330px;
+ max-height: calc(100vh - 24px);
+ overflow-y: auto;
+ padding: 10px;
+ margin: 0;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--panel);
+ box-shadow: 0 12px 36px rgba(0, 0, 0, 0.42);
+ }
+ .ge-inpaint-section.ge-inpaint-popover .ge-inpaint-popover-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ margin: -10px -10px 8px;
+ padding: 8px 10px;
+ border-bottom: 1px solid var(--border);
+ cursor: grab;
+ user-select: none;
+ }
+ .ge-inpaint-section.ge-inpaint-popover > .ge-section-title-with-help:not(.ge-inpaint-popover-title) {
+ display: none;
+ }
+ .ge-inpaint-section.ge-inpaint-popover .ge-inpaint-popover-title {
+ margin: 0;
+ flex: 1 1 auto;
+ }
+ .ge-inpaint-section.ge-inpaint-popover .ge-inpaint-popover-close {
+ flex: 0 0 auto;
+ position: relative;
+ top: -8px;
+ border: none;
+ background: none;
+ color: var(--fg-muted);
+ font-size: 18px;
+ line-height: 1;
+ cursor: pointer;
+ padding: 0 4px;
+ border-radius: 4px;
+ transition: color 0.14s ease, background-color 0.14s ease;
+ }
+ .ge-inpaint-section.ge-inpaint-popover .ge-inpaint-popover-close:hover {
+ color: var(--fg);
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ }
+ }
+ .ge-inpaint-model-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .ge-inpaint-model-row label {
+ flex: 0 0 auto;
+ font-size: 10px;
+ opacity: 0.65;
+ }
+ .ge-inpaint-model-row #ge-ai-inpaint {
+ flex: 1 1 auto;
+ min-width: 0;
+ font-size: 10px;
+ padding: 4px 6px;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ }
+ .ge-inpaint-prompt {
+ width: 100%; padding: 6px 8px; background: var(--bg); color: var(--fg);
+ border: 1px solid var(--border); border-radius: 4px; font-size: 12px;
+ font-family: inherit; margin-top: 4px; box-sizing: border-box;
+ }
+ .ge-inpaint-prompt:focus { border-color: var(--red); outline: none; }
+
+ /* Responsive: stack on narrow screens */
+ @media (max-width: 700px) {
+ /* The editor body holds the sidebar | canvas | layers panel; on
+ mobile we stack them as toolbar (top) → canvas (middle) → layers
+ (bottom). Without this the body stays a flex row and the canvas
+ ends up zero-width because the sidebar takes the full width. */
+ .ge-editor-body {
+ flex-direction: column;
+ }
+ /* Brush/Size-style rows: stack the label above its slider so the
+ slider gets a full row instead of getting smashed against the
+ panel's right edge. Doesn't touch .ge-eraser-row which has its own
+ value-chip-on-the-right layout. */
+ .ge-control-row:not(.ge-eraser-row):has(input[type="range"]) {
+ flex-direction: column;
+ align-items: stretch;
+ gap: 2px;
+ }
+ .ge-control-row:not(.ge-eraser-row):has(input[type="range"]) > input[type="range"] {
+ width: 100%;
+ }
+ /* More breathing room around lasso/wand sliders on mobile so they
+ don't hug the right edge of the controls panel. */
+ #ge-lasso-section .ge-eraser-row,
+ #ge-wand-section .ge-eraser-row {
+ padding-right: 12px;
+ margin-top: 6px;
+ }
+ /* Lasso action buttons (Clear / Copy / To Mask / Bg Remove): pin to
+ the right edge of the row instead of left-aligned. */
+ #ge-lasso-section .ge-actions,
+ #ge-wand-section .ge-actions {
+ justify-content: flex-end;
+ }
+ /* Universal thumb-grow on active for every slider on mobile. */
+ .ge-controls input[type="range"]:active::-webkit-slider-thumb,
+ .ge-controls input[type="range"].is-using::-webkit-slider-thumb {
+ width: 22px;
+ height: 22px;
+ }
+ .ge-controls input[type="range"]:active::-moz-range-thumb,
+ .ge-controls input[type="range"].is-using::-moz-range-thumb {
+ width: 22px;
+ height: 22px;
+ }
+ .ge-controls input[type="range"]::-webkit-slider-thumb,
+ .ge-controls input[type="range"]::-moz-range-thumb {
+ transition: width 0.12s ease, height 0.12s ease;
+ }
+ .ge-toolbar {
+ flex-direction: row;
+ width: 100%;
+ height: auto;
+ padding: 4px 0;
+ border-right: none;
+ border-bottom: 1px solid var(--border);
+ overflow-x: auto;
+ overflow-y: hidden;
+ flex-shrink: 0;
+ gap: 0;
+ -webkit-overflow-scrolling: touch;
+ scrollbar-width: none;
+ }
+ .ge-toolbar::-webkit-scrollbar { display: none; }
+ /* Section labels in the toolbar were vertical breaks — turn them
+ into thin vertical dividers when the column flows horizontally. */
+ .ge-tool-sep {
+ border-top: none;
+ border-left: 1px solid var(--border);
+ margin: 0 4px;
+ padding: 0;
+ width: 1px;
+ height: 24px;
+ text-indent: -9999px;
+ overflow: hidden;
+ flex-shrink: 0;
+ }
+ .ge-tool-btn {
+ flex-shrink: 0;
+ width: 48px;
+ }
+ /* Canvas is the main thing — give it as much vertical space as
+ the editor body can spare. min-height keeps it visible even when
+ the right panel is at its max. */
+ .ge-canvas-area {
+ flex: 1 1 auto;
+ min-height: 40vh;
+ }
+ /* Right panel = layers list. Docked as a bottom sheet with a peek
+ state: collapsed shows the header strip (and the active layer
+ row peeks through), expanded reveals all layers + actions. The
+ user swipes up to expand, down to collapse — the active layer is
+ never fully hidden. */
+ .ge-right-panel {
+ position: fixed;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ width: 100%;
+ max-height: 70vh;
+ height: 70vh;
+ background: var(--panel);
+ border-left: none;
+ border-top: 1px solid var(--border);
+ border-radius: 12px 12px 0 0;
+ box-shadow: 0 -8px 24px rgba(0, 0, 0, 0.35);
+ z-index: 50;
+ flex-shrink: 0;
+ /* Peek height grows with the layer count up to a cap. JS sets the
+ `--peek-height` custom property from _renderLayerPanel(); default
+ fallback is enough for the header + one row. */
+ transform: translateY(calc(100% - var(--peek-height, 110px)));
+ transition: transform 0.22s ease-out;
+ }
+ .ge-right-panel.expanded {
+ transform: translateY(0);
+ }
+ /* Minimized: panel slides almost fully off-screen — only a thin
+ handle strip remains visible so the user can swipe back up. */
+ .ge-right-panel.minimized {
+ transform: translateY(calc(100% - 24px));
+ }
+ .ge-layers-grab {
+ display: block !important;
+ position: absolute;
+ top: 6px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 40px;
+ height: 4px;
+ background: color-mix(in srgb, var(--fg) 30%, transparent);
+ border-radius: 2px;
+ }
+ .ge-layers-header {
+ padding-top: 16px;
+ position: relative;
+ }
+ /* In peek state, the layers list takes the full panel height (~70vh)
+ and never overflows so its own scrollbar doesn't activate. Constrain
+ the list to the visible peek area so it scrolls properly when there
+ are more layers than the peek can show. */
+ .ge-right-panel:not(.expanded) .ge-layers-list {
+ max-height: calc(var(--peek-height, 110px) - 52px);
+ -webkit-overflow-scrolling: touch;
+ }
+ /* Mobile layer-row buttons — bump hit targets up so fingers can
+ reliably tap visibility / fx / delete. */
+ .ge-layer-vis,
+ .ge-layer-btn,
+ .ge-layer-fx-btn {
+ width: 40px !important;
+ height: 40px !important;
+ font-size: 18px !important;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .ge-layer-btn svg,
+ .ge-layer-fx-btn svg {
+ width: 18px;
+ height: 18px;
+ }
+ .ge-layers-list {
+ overflow-x: clip;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) {
+ display: grid;
+ grid-template-columns: 12px 40px 34px minmax(0, 1fr) 40px;
+ grid-template-rows: 40px auto 40px;
+ align-items: center;
+ row-gap: 3px;
+ }
+ .ge-layers-list > .ge-layer-group-row {
+ grid-template-columns: 12px 40px 40px 34px minmax(0, 1fr) 40px;
+ grid-template-rows: 40px auto 40px;
+ align-items: center;
+ row-gap: 3px;
+ }
+ .ge-layer-group-row .ge-layer-group-drag { grid-column: 1; grid-row: 1; }
+ .ge-layer-group-row .ge-layer-group-toggle { grid-column: 2; grid-row: 1; }
+ .ge-layer-group-row .ge-layer-vis { grid-column: 3; grid-row: 1; }
+ .ge-layer-group-row .ge-group-inline-thumb { grid-column: 4; grid-row: 1; }
+ .ge-layer-group-row .ge-layer-group-name { grid-column: 5; grid-row: 1; }
+ .ge-layer-group-row .ge-layer-lock-btn { grid-column: 6; grid-row: 1; }
+ .ge-layer-group-row .ge-layer-opacity-row {
+ grid-column: 1 / -1;
+ grid-row: 2;
+ margin-left: 52px;
+ width: auto;
+ }
+ .ge-layer-group-row .ge-layer-controls {
+ grid-column: 1 / -1;
+ grid-row: 3;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-drag {
+ grid-column: 1;
+ grid-row: 1;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-vis {
+ grid-column: 2;
+ grid-row: 1;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-inline-thumb {
+ grid-column: 3;
+ grid-row: 1;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-name,
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-name-input {
+ grid-column: 4;
+ grid-row: 1;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-lock-btn {
+ grid-column: 5;
+ grid-row: 1;
+ }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-opacity-row {
+ grid-column: 1 / -1;
+ grid-row: 2;
+ display: flex;
+ width: auto;
+ min-width: 0;
+ margin-left: 52px;
+ }
+ .ge-mask-sub-item {
+ display: grid;
+ grid-template-columns: 40px 34px minmax(80px, 1fr) auto;
+ grid-template-rows: 40px;
+ align-items: center;
+ padding-left: 8px;
+ }
+ .ge-mask-sub-item > .ge-layer-vis { grid-column: 1; grid-row: 1; }
+ .ge-mask-sub-item > .ge-mask-inline-thumb { grid-column: 2; grid-row: 1; }
+ .ge-mask-sub-item > .ge-layer-name {
+ grid-column: 3;
+ grid-row: 1;
+ display: flex !important;
+ min-width: 0;
+ }
+ .ge-mask-sub-item > .ge-layer-controls {
+ grid-column: 4;
+ grid-row: 1;
+ min-width: 0;
+ justify-content: flex-start;
+ }
+ .ge-mask-sub-item > .ge-layer-controls .ge-layer-btn {
+ width: 30px !important;
+ min-width: 30px !important;
+ height: 30px !important;
+ font-size: 14px !important;
+ }
+ /* Layer opacity slider stays at its expanded size at all times on
+ mobile — there's room for it and the resize-on-hover felt jittery
+ when scrolling. */
+ .ge-layer-opacity,
+ .ge-layer-opacity:hover,
+ .ge-layer-opacity:active,
+ .ge-layer-opacity.dragging {
+ width: 160px !important;
+ height: 10px !important;
+ }
+ /* Transform / adjust popups dock at the TOP of the viewport on
+ mobile so they overlay the topbar instead of eating canvas space.
+ Fixed positioning escapes any transformed ancestor stacking. */
+ .ge-transform-popup,
+ .ge-adj-popup,
+ .ge-fx-popup {
+ position: fixed !important;
+ left: 8px !important;
+ right: 8px !important;
+ top: 32px !important;
+ bottom: auto !important;
+ max-width: calc(100vw - 16px) !important;
+ width: auto !important;
+ min-width: 0 !important;
+ min-height: 240px !important;
+ max-height: calc(100vh - 40px);
+ overflow-y: auto;
+ z-index: 10003 !important;
+ }
+ .ge-fx-menu {
+ position: fixed !important;
+ left: 8px !important;
+ right: 8px !important;
+ top: auto !important;
+ bottom: calc(env(safe-area-inset-bottom, 0px) + 8px) !important;
+ width: auto !important;
+ min-width: 0 !important;
+ max-width: calc(100vw - 16px) !important;
+ z-index: 10002 !important;
+ }
+ /* Hide both the minimise and × close buttons in the header on
+ mobile — a clearly labelled Cancel button next to Apply in the
+ body is more discoverable than tiny header icons. */
+ .ge-transform-popup #ge-transform-min,
+ .ge-transform-popup #ge-transform-cancel {
+ display: none !important;
+ }
+ /* Wrap the transform body into precision rows on mobile:
+ Row 1: X + Y
+ Row 2: W + H
+ Row 3: ↻ rotate + quick actions + Apply/Cancel */
+ .ge-transform-popup-body {
+ flex-wrap: wrap !important;
+ align-items: center;
+ row-gap: 8px;
+ column-gap: 6px;
+ }
+ .ge-transform-popup-body #ge-transform-rot {
+ width: 3.5ch !important;
+ min-width: 0 !important;
+ }
+ /* 3-row layout, enforced by explicit `.ge-row-break` elements in the
+ DOM (the only reliable way to force a flex-wrap line break).
+ Row 1: W input + H input
+ Row 2: aspect lock + ↻ rotate input
+ Row 3: flip-h, flip-v, rot-90 + Cancel + Apply */
+ .ge-transform-popup-body .ge-row-break {
+ display: block;
+ flex-basis: 100%;
+ height: 0;
+ width: 100%;
+ }
+ /* Flip buttons slightly bigger so they're easier to tap. */
+ .ge-transform-quick-btn {
+ padding: 8px 10px !important;
+ min-width: 40px;
+ min-height: 40px;
+ }
+ .ge-transform-quick-btn svg {
+ width: 18px;
+ height: 18px;
+ }
+ /* Cancel + Apply share the right side of row 2, same size, paired. */
+ .ge-transform-popup-body #ge-transform-cancel-btn {
+ margin-left: auto;
+ }
+ .ge-transform-popup-body #ge-transform-cancel-btn,
+ .ge-transform-popup-body #ge-transform-apply {
+ padding: 8px 16px !important;
+ font-size: 13px !important;
+ min-width: 80px;
+ text-align: center;
+ }
+ /* Stepper-style number control on mobile:
+ [ − ] [ input ] [ + ]
+ Stack reverses so the − sits visually on the LEFT of the input, +
+ on the RIGHT. Big finger-sized squares, big +/- glyphs, both
+ buttons support tap-and-hold auto-repeat (JS) for fast scrubbing. */
+ .ge-transform-field {
+ display: inline-flex !important;
+ align-items: stretch;
+ gap: 0;
+ }
+ .ge-transform-field > label {
+ display: inline-flex;
+ align-items: center;
+ padding-right: 6px;
+ font-weight: 600;
+ }
+ .ge-transform-field:not(:has(#ge-transform-rot)) > label {
+ position: relative;
+ top: -1px;
+ }
+ .ge-transform-spin {
+ display: inline-flex !important;
+ flex-direction: row !important;
+ /* Use grid-order to swap positions of [−][+]: the − should sit
+ BEFORE the input, the + AFTER it. Achieve this by absolute
+ order — first child styled differently, second styled
+ differently, then we move the whole .ge-transform-spin's first
+ button visually before the input via reverse-flex. */
+ order: 0;
+ width: auto !important;
+ }
+ .ge-transform-field {
+ flex-direction: row;
+ }
+ /* Re-flow: label + [-] + input + [+]
+ We split the .ge-transform-spin's two buttons across the field's
+ flex line using order: order:0 for −, order:2 for input, order:3
+ for +. The spin <span> itself gets `display: contents` so its
+ children can be reordered independently against the input. */
+ .ge-transform-spin {
+ display: contents !important;
+ }
+ .ge-transform-field > input.ge-transform-popup-input {
+ order: 2;
+ text-align: center;
+ }
+ .ge-transform-spin button[data-spin="down"] {
+ order: 1;
+ }
+ .ge-transform-spin button[data-spin="up"] {
+ order: 3;
+ }
+ /* The buttons themselves — chunky, square, identical in size. Reset
+ the base `:first-child` rule (which strips the bottom border for
+ the old stacked layout) so both buttons render with the same
+ visual box in the new row layout. */
+ .ge-transform-spin button {
+ box-sizing: border-box !important;
+ width: 36px !important;
+ height: 36px !important;
+ min-width: 36px;
+ min-height: 36px;
+ padding: 0 0 0 0 !important;
+ font-size: 18px !important;
+ font-weight: 700;
+ line-height: 1 !important;
+ border: 1px solid var(--border) !important;
+ border-radius: 6px !important;
+ flex-shrink: 0;
+ display: inline-flex !important;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ top: -4px;
+ }
+ .ge-transform-spin button:first-child,
+ .ge-transform-spin button:last-child {
+ border-radius: 6px !important;
+ border-bottom: 1px solid var(--border) !important;
+ }
+ /* Graphic-editor adjustment buttons use text glyphs that sit visually low —
+ lift them to match the +/- button alignment. */
+ .ge-adj-close,
+ .ge-adj-min {
+ padding-top: 0 !important;
+ padding-bottom: 8px !important;
+ display: inline-flex !important;
+ align-items: center !important;
+ justify-content: center !important;
+ }
+ .ge-transform-spin button[data-spin="down"] { margin-right: 4px; }
+ .ge-transform-spin button[data-spin="up"] { margin-left: 4px; }
+ /* The input between them — generous tap area and clear typography. */
+ .ge-transform-field > input.ge-transform-popup-input {
+ height: 36px !important;
+ padding: 0 6px !important;
+ font-size: 14px !important;
+ min-width: 56px;
+ position: relative;
+ top: 2px;
+ }
+ /* Rotate input — compact so it fits on row 2 alongside the flip
+ quick buttons and the Cancel + Apply pair. */
+ .ge-transform-field > #ge-transform-rot.ge-transform-popup-input {
+ min-width: 0;
+ width: 64px !important;
+ }
+ /* Suffix (°) sits right after the rotate input but before the + button. */
+ .ge-transform-popup-suffix { order: 3; align-self: center; padding: 0 2px; }
+ /* Slider thumb grows only while actively dragged — keeps the resting
+ row compact, thumb pops larger when the user grabs it. */
+ .gallery-editor-container input[type="range"]:active::-webkit-slider-thumb,
+ .ge-layer-opacity:active::-webkit-slider-thumb,
+ .ge-layer-opacity.dragging::-webkit-slider-thumb {
+ width: 22px !important;
+ height: 22px !important;
+ }
+ .gallery-editor-container input[type="range"]:active::-moz-range-thumb,
+ .ge-layer-opacity:active::-moz-range-thumb,
+ .ge-layer-opacity.dragging::-moz-range-thumb {
+ width: 22px !important;
+ height: 22px !important;
+ }
+ /* Slider value bubble on mobile — bigger text/padding for
+ readability. Position is JS-driven via `position: fixed` from the
+ base rule, so don't override top/bottom here — `bottom: 100%`
+ with fixed positioning was pushing the bubble off-screen. */
+ .ge-slider-bubble {
+ font-size: 14px !important;
+ padding: 5px 10px !important;
+ }
+ /* Editor topbar — scrolls horizontally on narrow viewports. Buttons
+ fill more vertical+horizontal space so each is a comfortable
+ finger-tap target instead of feeling cramped. */
+ .ge-topbar {
+ overflow-x: auto;
+ overflow-y: hidden;
+ flex-wrap: nowrap;
+ justify-content: flex-start;
+ gap: 6px;
+ padding: 6px 8px;
+ -webkit-overflow-scrolling: touch;
+ scrollbar-width: none;
+ }
+ .ge-topbar::-webkit-scrollbar { display: none; }
+ .ge-topbar-left,
+ .ge-topbar-right {
+ flex-shrink: 0;
+ gap: 6px;
+ }
+ .ge-alpha-badge {
+ display: none;
+ }
+ #ge-undo {
+ position: sticky !important;
+ left: 8px;
+ background: var(--panel);
+ z-index: 8;
+ box-shadow: 8px 0 10px -10px color-mix(in srgb, var(--fg) 55%, transparent);
+ }
+ .ge-topbar .ge-btn,
+ .ge-topbar .ge-btn-sm {
+ padding: 7px 11px !important;
+ font-size: 13px !important;
+ min-height: 34px;
+ line-height: 1;
+ top: 0 !important;
+ }
+ .ge-topbar .ge-btn svg,
+ .ge-topbar .ge-btn-sm svg {
+ width: 16px;
+ height: 16px;
+ }
+ .ge-topbar select,
+ .ge-topbar input,
+ .ge-topbar .ge-ai-model {
+ padding: 6px 8px !important;
+ font-size: 12px !important;
+ min-height: 32px;
+ top: 0 !important;
+ }
+ .ge-topbar .ge-canvas-size {
+ font-size: 12px !important;
+ padding: 0 6px;
+ line-height: 34px;
+ }
+ #ge-history-panel {
+ left: 0 !important;
+ right: 0 !important;
+ top: auto !important;
+ bottom: 0 !important;
+ width: auto !important;
+ max-height: min(60dvh, 420px);
+ border-radius: 12px 12px 0 0 !important;
+ z-index: 10001 !important;
+ box-shadow: 0 -8px 24px rgba(0, 0, 0, 0.35);
+ }
+ #ge-history-panel .ge-history-head { cursor: default; }
+ #ge-shortcuts-btn {
+ display: none !important;
+ }
+ /* Topbar popups that need real interaction (Resize sliders, Edge
+ form, Save with sub-items) become bottom-sheet slide-ups on
+ mobile so there's room to interact. Image and Filter are tight
+ single-column dropdowns — they stay anchored to their button. */
+ .ge-resize-menu,
+ .ge-edge-menu,
+ .ge-save-menu {
+ position: fixed !important;
+ left: 0 !important;
+ right: 0 !important;
+ top: auto !important;
+ bottom: 0 !important;
+ min-width: 0 !important;
+ max-width: 100vw !important;
+ width: auto;
+ padding: 18px 16px 24px !important;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 12px 12px 0 0 !important;
+ box-shadow: 0 -8px 24px rgba(0, 0, 0, 0.35);
+ z-index: 10005;
+ animation: ge-controls-slide-up 0.2s ease-out;
+ }
+ /* Image / Filter stay as anchored dropdowns; just cap width
+ so they don't run off-screen on narrow viewports. */
+ .ge-image-menu,
+ .ge-selection-menu,
+ .ge-filter-menu {
+ max-width: calc(100vw - 16px);
+ }
+ .ge-resize-menu::before,
+ .ge-edge-menu::before,
+ .ge-save-menu::before {
+ content: '';
+ position: absolute;
+ top: 6px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 40px;
+ height: 4px;
+ background: color-mix(in srgb, var(--fg) 30%, transparent);
+ border-radius: 2px;
+ }
+ /* The Edge form needs a bit of breathing room when it spans the
+ viewport; the W/H inputs in the crop apply pop should stay compact. */
+ .ge-edge-menu { padding: 12px; }
+ .ge-canvas-prompt {
+ width: calc(100vw - 16px) !important;
+ max-width: none !important;
+ }
+ .ge-canvas-prompt-footer {
+ flex-wrap: wrap;
+ }
+ .ge-canvas-prompt-footer .ge-canvas-prompt-hint {
+ flex: 1 0 100%;
+ margin-bottom: 2px;
+ }
+ /* Inpaint floating prompt — keep it inside the canvas area on
+ mobile so it doesn't run off the right edge. */
+ .ge-inpaint-popup {
+ max-width: calc(100vw - 16px);
+ }
+ .ge-inpaint-popup-input { width: 160px; }
+
+ /* Tool-specific controls (brush size/color, eraser opacity/flow,
+ lasso feather, inpaint prompt panel, etc.) lift out of the right
+ panel and dock as a slide-up bottom sheet so they have actual room
+ to breathe on a phone. A short grab-handle visually separates it
+ from the canvas. */
+ .ge-controls {
+ position: fixed !important;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ z-index: 60;
+ border-bottom: none;
+ border-top: 1px solid var(--border);
+ background: var(--panel);
+ border-radius: 12px 12px 0 0;
+ box-shadow: 0 -8px 24px rgba(0, 0, 0, 0.35);
+ max-height: 60vh;
+ overflow-y: auto;
+ padding: 18px 16px 24px;
+ gap: 12px;
+ /* Slide-up entrance animation when the controls become visible. */
+ animation: ge-controls-slide-up 0.18s ease-out;
+ }
+ .ge-controls::before {
+ content: '';
+ position: absolute;
+ top: 6px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 40px;
+ height: 4px;
+ background: color-mix(in srgb, var(--fg) 30%, transparent);
+ border-radius: 2px;
+ }
+ @keyframes ge-controls-slide-up {
+ from { transform: translateY(100%); }
+ to { transform: translateY(0); }
+ }
+ /* User swiped the sheet down — keep tool active but hide its
+ controls. Re-tapping the same tool button toggles back. */
+ .ge-controls.dismissed {
+ transform: translateY(100%);
+ pointer-events: none;
+ /* Smooth slide-out matching the slide-in duration. */
+ animation: none;
+ transition: transform 0.18s ease-in;
+ }
+ }
+
+ /* ── Group Chat ────────────────────────────────────── */
+ .msg-group .role {
+ font-weight: 600;
+ }
+ #group-toggle-btn.active,
+ .overflow-menu-item#overflow-group-btn.active {
+ color: var(--red);
+ background: color-mix(in srgb, var(--red) 12%, transparent);
+ }
+ /* Group model picker — match app theme */
+ #group-model-picker .modal-content {
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ }
+ #group-model-picker .modal-header {
+ border-bottom: 1px solid var(--border);
+ }
+ #group-model-picker .memory-item {
+ border-radius: 6px;
+ transition: background 0.1s;
+ }
+ #group-model-picker .memory-item:hover {
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ }
diff --cc static/css/14-email.css
index 000000000,56d1df6df..0ef60aca4
mode 000000,100644..100644
--- a/static/css/14-email.css
+++ b/static/css/14-email.css
@@@ -1,0 -1,4729 +1,4751 @@@
+ /* 14-email - part of the former static/style.css.
+ *
+ * The stylesheet is split by area, but the split is mechanical: rules were
+ * moved verbatim and NOT regrouped. The numeric prefix is the load order, and
+ * that order is what preserves the cascade. A rule sits in the file its
+ * original position fell into, so an area's rules are not all in its file and
+ * a file is not only that area's rules.
+ *
+ * Do not reorder the <link> tags in static/index.html, and do not move a rule
+ * between files: with 1,151 redeclarations and 1,886 !important in this
+ * cascade, either can change which declaration wins.
+ *
+ * static/index.html and the PRECACHE list in static/sw.js must agree on this
+ * order. tests/test_static_stylesheet_manifest.py and
+ * tests/test_css_computed_style_snapshot.py fail if that drifts.
+ */
+ #group-model-picker input[type="checkbox"] {
+ accent-color: var(--accent, var(--red));
+ }
+ #group-model-picker input[type="radio"] {
+ accent-color: var(--accent, var(--red));
+ }
+ #group-model-picker .btn-primary {
+ background: var(--accent, var(--red));
+ color: #fff;
+ border: none;
+ border-radius: 6px;
+ cursor: pointer;
+ font-weight: 500;
+ }
+ #group-model-picker .btn-primary:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+ }
+ #group-model-picker .btn-primary:hover:not(:disabled) {
+ filter: brightness(1.1);
+ }
+
+ /* ── Email document type ── */
+ .doc-email-header {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 10px 12px;
+ border-bottom: 1px solid var(--border);
+ background: var(--bg);
+ flex-shrink: 0;
+ }
+ .email-field {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .email-field label {
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--fg);
+ opacity: 0.5;
+ min-width: 50px;
+ text-align: right;
+ }
+ .email-field input {
+ flex: 1;
+ background: transparent;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ padding: 5px 8px;
+ font-size: 13px;
+ font-family: inherit;
+ color: var(--fg);
+ outline: none;
+ }
+ .email-field input:focus {
+ border-color: var(--accent, #4a9eff);
+ }
+ .email-actions {
+ display: flex;
+ gap: 8px;
+ justify-content: flex-end;
+ margin-top: 2px;
+ }
+ .email-draft-btn {
+ background: transparent;
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ padding: 6px 14px;
+ font-size: 12px;
+ cursor: pointer;
+ font-family: inherit;
+ }
+ .email-draft-btn:hover { background: var(--hover-bg, rgba(255,255,255,0.05)); }
+ .email-draft-btn:disabled { opacity: 0.5; cursor: not-allowed; }
+
+ /* ── Email inbox list ── */
+ .email-body { border-top: 1px solid var(--border); }
+ .email-folder-bar { padding: 4px 8px; border-bottom: 1px solid var(--border); }
+ .email-folder-select {
+ background: transparent; border: 1px solid var(--border); border-radius: 4px;
+ color: var(--fg); font-size: 11px; padding: 2px 6px; cursor: pointer; width: 100%; height: 26px;
+ }
+ .email-item {
+ display: flex; align-items: flex-start; gap: 8px; padding: 8px 12px;
+ cursor: pointer; border-bottom: 1px solid var(--border); position: relative; transition: background 0.1s;
+ }
+ .email-item:hover { background: var(--hover-bg, rgba(255,255,255,0.03)); }
+ .email-item-spam:hover { opacity: 0.75; }
+ .email-tag-spam {
+ display: inline-flex; align-items: center; gap: 4px;
+ background: color-mix(in srgb, var(--accent, var(--red)) 15%, transparent);
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 30%, transparent);
+ color: var(--accent, var(--red));
+ border-radius: 10px; padding: 1px 6px; font-size: 9px; font-weight: 600;
+ text-transform: lowercase; letter-spacing: 0.3px;
+ }
+ .email-spam-unflag {
+ background: none; border: none; color: inherit; cursor: pointer;
+ padding: 0 2px; font-size: 10px; line-height: 1; opacity: 0.6;
+ }
+ .email-spam-unflag:hover { opacity: 1; color: var(--fg); }
+ /* Unread state is now a subtle icon, not full styling */
+ .email-done-check {
+ display: inline-flex; align-items: center; justify-content: center;
+ width: 16px; height: 16px; border-radius: 50%; background: transparent;
+ border: 1.5px solid var(--border); color: transparent;
+ flex-shrink: 0; cursor: pointer; transition: all 0.15s;
+ margin-right: 4px;
+ }
+ .email-done-check:hover { border-color: var(--accent, #4a9eff); }
+ .email-done-check.active { background: var(--accent, #4a9eff); border-color: var(--accent, #4a9eff); color: #fff; }
+ .email-done-check.active svg { display: block; }
+ .email-done-check svg { display: none; }
+
+
+
+
+ .email-delete-busy > :not(.email-delete-overlay) {
+ opacity: 0.42;
+ transition: opacity 0.12s ease;
+ }
+
+ .email-delete-overlay {
+ position: absolute;
+ inset: 0;
+ z-index: 8;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: inherit;
+ background: color-mix(in srgb, var(--panel, var(--bg)) 82%, transparent);
+ pointer-events: none;
+ }
+
+ .email-delete-overlay .spinner-whirlpool,
+ .email-delete-overlay .ai-spinner-whirlpool {
+ margin: 0 !important;
+ }
+
+ .doclib-card.email-card-removing {
+ pointer-events: none !important;
+ max-height: 0 !important;
+ padding-top: 0 !important;
+ padding-bottom: 0 !important;
+ margin-top: 0 !important;
+ margin-bottom: 0 !important;
+ border-color: transparent !important;
+ opacity: 0;
+ transform: translateX(-10px) scale(0.985);
+ transition:
+ opacity 0.18s ease,
+ transform 0.22s ease,
+ max-height 0.23s ease,
+ padding 0.23s ease,
+ margin 0.23s ease,
+ border-color 0.18s ease;
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ .doclib-card.email-card-removing {
+ transition: opacity 0.08s ease;
+ transform: none;
+ }
+ }
+
+ /* Library card done check — always visible, subtle icon next to title */
+ .email-card-done {
+ display: inline-flex; align-items: center; justify-content: center;
+ flex-shrink: 0; cursor: pointer;
+ transition: opacity 0.15s, color 0.15s;
+ opacity: 0.15; color: var(--fg);
+ }
+ .email-card-titlerow .memory-item-title {
+ flex: 1 1 auto;
+ min-width: 0;
+ }
+ .email-card-titlerow { position: relative; min-width: 0; }
+ .email-card-status {
+ display: inline-flex;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 7px;
+ flex: 0 0 auto;
+ min-width: max-content;
+ margin-left: auto;
+ white-space: nowrap;
+ }
+ .email-card-status > * {
+ flex: 0 0 auto;
+ }
+ .email-card-status + .email-card-nav-arrows {
+ margin-left: 6px;
+ }
+ .email-card-status .email-card-nav-arrows {
+ margin-left: 2px;
+ }
+ .email-card-attachment {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex: 0 0 13px;
+ width: 13px;
+ height: 18px;
+ }
+ /* Hover preview: bright accent when unchecked so the user sees a check coming.
+ Once active, keep the exact same color on hover so the done state does not
+ visually flip while the pointer is still over it. */
+ .email-card-done:not(.active):hover {
+ opacity: 0.75 !important;
+ color: var(--accent-primary, var(--red));
+ }
+ .email-card-done.active { opacity: 0.95; color: var(--accent-primary, var(--red)); }
+ .email-card-done.active:hover {
+ opacity: 0.95 !important;
+ color: var(--accent-primary, var(--red)) !important;
+ }
+ .email-card-favorite {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex: 0 0 18px;
+ width: 18px;
+ height: 18px;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: var(--fg);
+ cursor: pointer;
+ position: relative;
+ top: -3px;
+ opacity: 0.18;
+ transition: opacity 0.15s, color 0.15s, transform 0.15s;
+ }
+ .email-card-favorite:hover,
+ .email-card-favorite:focus-visible {
+ opacity: 0.8;
+ color: var(--accent-primary, var(--red));
+ }
+ .email-card-favorite.active {
+ opacity: 0.9;
+ color: var(--accent-primary, var(--red));
+ }
+ @keyframes check-pop {
+ 0% { transform: scale(1); }
+ 40% { transform: scale(1.7) rotate(-10deg); }
+ 70% { transform: scale(1.1) rotate(4deg); }
+ 100% { transform: scale(1) rotate(0); }
+ }
+ @keyframes check-unpop {
+ 0% { transform: scale(1); opacity: 0.95; }
+ 35% { transform: scale(0.45) rotate(8deg); opacity: 0.05; }
+ 65% { transform: scale(0.9); opacity: 0.2; }
+ 100% { transform: scale(1); }
+ }
+
+ /* Expanded email preview in library — override .memory-item row layout */
+ .doclib-card.email-card-expanded.memory-item {
+ cursor: default !important;
+ background: var(--bg) !important;
+ border: 1px solid var(--border) !important;
+ display: flex !important;
+ flex-direction: column !important;
+ align-items: stretch !important;
+ /* Fill the available grid height instead of the old hardcoded 70vh —
+ the modal already caps height (90dvh on mobile, auto on desktop), so
+ the card just needs to flex into whatever remains. */
+ flex: 1 1 auto !important;
+ height: 100% !important;
+ min-height: 0 !important;
+ max-height: none !important;
+ padding: 0 !important;
+ overflow: hidden !important;
+ gap: 0 !important;
+ }
+ .doclib-card.email-card-expanded.memory-item > div:first-child {
+ /* The summary content (subject, date) - acts as the title bar. Left padding
+ trimmed 14→6px to shift the title 8px left total. */
+ padding: 2px 4px 10px !important; /* top trimmed to lift the header text up */
+ margin-top: -14px !important; /* pull the whole bar up into the freed space */
+ border-bottom: 1px solid var(--border);
+ flex: 0 0 auto !important;
+ width: 100%;
+ }
+ /* Keep the per-card '...' actions menu visible while the email card is
+ expanded — we used to hide it and surface a duplicate menu button in
+ the expanded header, but that was redundant. The bottom menu now
+ carries the actions in both states. */
+ /* When expanded inline, show the subject a touch larger than the 12px card
+ title (close to the new-tab window header) without being oversized. */
+ .doclib-card.email-card-expanded .memory-item-title {
+ font-size: 14px;
+ font-weight: 600;
+ }
+ /* The sender name is redundant once expanded (the From: row shows it just
+ below), so drop it and keep only the date — which then sits left-aligned
+ directly under the subject. Nudge the date 1px right to line up exactly with
+ the subject text, and up closer to it. */
+ .doclib-card.email-card-expanded .email-meta-sender,
+ .doclib-card.email-card-expanded .email-meta-sep {
+ display: none;
+ }
+ .doclib-card.email-card-expanded .memory-item-meta {
+ margin-top: -9px !important;
+ }
+ .doclib-card.email-card-expanded .email-meta-date {
+ margin-left: 3px;
+ }
+ .email-card-reader {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ min-height: 0;
+ font-size: 12px;
+ }
+ .email-card-reader-loading {
+ background: color-mix(in srgb, var(--bg) 86%, #000 14%);
+ border-top: 1px solid color-mix(in srgb, var(--border) 78%, transparent);
+ min-height: 240px;
+ }
+ .email-card-reader-error {
+ background: color-mix(in srgb, var(--bg) 86%, #000 14%);
+ border-top: 1px solid color-mix(in srgb, var(--border) 78%, transparent);
+ }
+ .email-reader-load-error {
+ display: flex;
+ min-height: 180px;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 9px;
+ padding: 24px 16px;
+ text-align: center;
+ color: var(--fg);
+ }
+ .email-reader-load-error-title {
+ font-size: 13px;
+ font-weight: 700;
+ }
+ .email-reader-load-error-msg {
+ max-width: min(460px, 92%);
+ color: color-mix(in srgb, var(--fg) 62%, transparent);
+ font-size: 11px;
+ line-height: 1.35;
+ overflow-wrap: anywhere;
+ }
+ .email-skeleton-line,
+ .email-skeleton-dot {
+ display: block;
+ border-radius: 999px;
+ background: linear-gradient(
+ 90deg,
+ color-mix(in srgb, var(--fg) 12%, transparent) 0%,
+ color-mix(in srgb, var(--fg) 22%, transparent) 45%,
+ color-mix(in srgb, var(--fg) 12%, transparent) 90%
+ );
+ background-size: 220% 100%;
+ animation: email-skeleton-shimmer 1.35s ease-in-out infinite;
+ }
+ .email-skeleton-dot {
+ width: 9px;
+ height: 9px;
+ flex: 0 0 auto;
+ }
+ .email-list-skeleton {
+ position: absolute;
+ inset: 0;
+ padding: 10px 7px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ pointer-events: none;
+ }
+ .email-skeleton-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-height: 48px;
+ padding: 8px 10px;
+ border: 1px solid color-mix(in srgb, var(--border) 76%, transparent);
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--panel) 70%, transparent);
+ }
+ .email-skeleton-lines {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 7px;
+ }
+ .email-reader-skeleton {
+ display: flex;
+ flex-direction: column;
+ min-height: 100%;
+ flex: 1;
+ }
+ .email-reader-skeleton-header {
+ min-height: 60px;
+ padding: 12px 14px;
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ border-bottom: 1px solid var(--border);
+ background: color-mix(in srgb, var(--panel) 72%, transparent);
+ }
+ .email-reader-skeleton-header .chip { width: 132px; height: 18px; }
+ .email-reader-skeleton-header .chip.short { width: 78px; }
+ .email-reader-skeleton-header .action {
+ width: 38px;
+ height: 28px;
+ margin-left: auto;
+ border-radius: 6px;
+ }
+ .email-reader-skeleton-header .action + .action { margin-left: 0; }
+ .email-reader-skeleton-atts {
+ display: flex;
+ gap: 7px;
+ padding: 8px 14px;
+ border-bottom: 1px solid var(--border);
+ }
+ .email-reader-skeleton-atts .attachment { width: 126px; height: 20px; border-radius: 6px; }
+ .email-reader-skeleton-atts .attachment.short { width: 88px; }
+ .email-reader-skeleton-body {
+ display: flex;
+ flex-direction: column;
+ gap: 11px;
+ padding: 16px 14px;
+ min-height: 340px;
+ flex: 1;
+ }
+ .email-reader-skeleton-body .body { width: 88%; height: 9px; border-radius: 6px; }
+ .email-reader-skeleton-body .body.wide { width: 100%; }
+ .email-reader-skeleton-body .body.medium { width: 94%; }
+ .email-reader-skeleton-body .body.short { width: 62%; }
+ .email-reader-skeleton-body .body.gap {
+ margin-top: 12px;
+ width: 78%;
+ }
+ .email-search-progress-row {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 7px;
+ min-height: 30px;
+ padding: 6px 10px;
+ font-size: 11px;
+ opacity: 0.65;
+ }
+ .email-search-progress-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--accent-primary, var(--red));
+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent-primary, var(--red)) 35%, transparent);
+ animation: email-search-progress-pulse 1.2s ease-in-out infinite;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .email-skeleton-line,
+ .email-skeleton-dot,
+ .email-inline-image-skeleton,
+ .email-inline-image-placeholder.is-loading .email-inline-image-icon,
+ .email-inline-image-frame.is-loading,
+ .email-search-progress-dot {
+ animation: none;
+ }
+ }
+ /* Per-email unread dot in the expanded reader's title row. Background color
+ stays inline (per-sender hue from _senderColor), but the dot gets a soft
+ breathing glow + a 4px vertical nudge so it reads as centered against
+ the row instead of riding the baseline. */
+ .email-card-unread-dot {
+ position: relative;
+ top: 0;
+ animation: email-card-unread-breathe 2.2s ease-in-out infinite;
+ }
+ .email-reader-header {
+ display: flex;
+ flex-direction: row;
+ /* Top-align so when the user expands To/Cc, the action cluster
+ stays on the From line above instead of drifting to the middle. */
+ align-items: flex-start;
+ gap: 12px;
+ /* Taller header so the 44px-tall absolute-positioned action
+ cluster inside the From row has vertical breathing room. */
+ padding: 8px 14px;
+ min-height: 60px;
+ border-bottom: 1px solid var(--border);
+ background: var(--bg);
+ flex-shrink: 0;
+ /* Containing block for the absolute action cluster. */
+ position: relative;
+ /* Container so the action-cluster wrap breakpoints below react to
+ the reader's own width instead of the page viewport. */
+ container-type: inline-size;
+ container-name: emailreader;
+ }
+ .email-reader-header > .email-reader-actions {
+ margin-left: auto;
+ flex-shrink: 0;
+ }
+ /* Meta block stacks the From / To / Cc rows; each row keeps label
+ tight to its chip(s) on the same line. The recipient-chips inside
+ scroll horizontally so long lists slide under the floating action
+ cluster on the right. */
+ .email-reader-meta {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+ /* Positioning context for the absolute action cluster. */
+ position: relative;
+ }
+ .email-reader-meta .recipient-chips {
+ display: inline-flex;
+ flex-wrap: nowrap;
+ overflow-x: auto;
+ overflow-y: hidden;
+ gap: 4px;
+ max-width: 100%;
+ scrollbar-width: none;
+ -ms-overflow-style: none;
+ }
+ .email-reader-meta .recipient-chips::-webkit-scrollbar { display: none; }
+ .email-reader-meta-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ }
+ .email-reader-meta-row.email-reader-meta-from {
+ position: relative;
+ /* Never wrap "From:" off the chip onto its own line — the chip
+ span has overflow-x scroll built in, so it shrinks/scrolls
+ instead of jumping to a new row. */
+ flex-wrap: nowrap;
+ min-width: 0;
+ /* Reserve space on the right for the 1-row cluster in wide mode. */
+ padding-right: 320px;
+ }
+ .email-reader-meta > .email-reader-meta-details {
+ min-width: 0;
+ padding-right: 320px;
+ }
+ .email-reader-meta > .email-reader-actions-inline {
+ position: absolute;
+ top: 1px;
+ right: 0;
+ display: flex;
+ flex-direction: row;
+ flex-wrap: wrap;
+ align-items: flex-start;
+ justify-content: flex-end;
+ gap: 4px;
+ z-index: 2;
+ /* Sit visually above the From baseline like the lifted overlay. */
+ margin-top: -9px;
+ }
+ /* Recipient chip span keeps at least ~4 characters visible (60px)
+ before the overflow-scroll kicks in, so the sender / first
+ recipient name is always partly readable. */
+ .email-reader-meta .recipient-chips {
+ min-width: 60px;
+ }
+ /* Medium reader widths: cap the cluster at 3 icons per row so it
+ never wraps past 2 rows. min-width forces the cluster to reserve
+ enough room for 3 icons in a row — without it, grid col 2 could
+ shrink below the cap and the cluster fanned out into 4+ short
+ rows. */
+ @container emailreader (max-width: 450px) {
+ .email-reader-meta > .email-reader-actions-inline {
+ /* 3 icons (48px each) + 2 gaps (4px each) = 152px exact. Adding
+ 6px slack so subpixel rounding can't tip a row from 3 to 2
+ icons and fan the cluster into a 3rd row. */
+ min-width: 158px;
+ max-width: 158px;
+ /* Solid background so the email body content behind the cluster
+ doesn't peek through the gaps between icons or the slack on
+ the right edge when the cluster's wrapped to 2 rows. */
+ background: var(--bg);
+ }
+ .email-reader-meta > .email-reader-actions-inline .memory-toolbar-btn.reader-icon-btn {
+ width: 48px;
+ min-width: 48px;
+ max-width: 48px;
+ height: 40px;
+ padding-left: 0;
+ padding-right: 0;
+ gap: 2px;
+ }
+ .email-reader-meta > .email-reader-actions-inline .reader-btn-label {
+ display: block;
+ max-width: 44px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-size: 8px;
+ line-height: 1;
+ }
+ /* Tighten the right-side padding now that the cluster is 158px
+ wide (instead of the ~308 wide 1-row layout). */
+ .email-reader-meta-row.email-reader-meta-from,
+ .email-reader-meta > .email-reader-meta-details {
+ padding-right: 170px;
+ }
+ /* Cluster wrapped to 2 rows (44px + 4 gap + 44px = 92px) sits
+ absolute above the From baseline. Set min-height on the meta
+ (a descendant of the container, more reliable than targeting
+ the container itself) so the header grows enough to contain
+ the cluster + 4px of breathing room between the cluster's
+ bottom and the header bottom. */
+ .email-reader-meta {
+ min-height: 96px;
+ }
+ }
+ /* Very narrow reader: once the chip span has shrunk to its ~4
+ character min, the cluster snaps to absolute overlay with a soft
+ shadow so it visually floats above the truncated chip. */
+ @container emailreader (max-width: 380px) {
+ /* Pane too narrow even for 158px of right-side reservation — kill
+ the padding so chips use the full width, and let the cluster
+ overlay via z-index + shadow. */
+ .email-reader-meta-row.email-reader-meta-from,
+ .email-reader-meta > .email-reader-meta-details {
+ padding-right: 0;
+ }
+ .email-reader-meta > .email-reader-actions-inline {
+ /* Keep the same -7px lift as the medium-width state so the
+ cluster doesn't slide ~4px DOWN when it transitions into
+ overlay mode. */
+ /* margin-top stays inherited at -7px from the base rule. */
+ /* 158px content + 22px padding-left so the inner row still fits
+ 3 icons cleanly. */
+ min-width: 180px;
+ max-width: 180px;
+ background: linear-gradient(to right, transparent 0, var(--bg) 18px);
+ padding-left: 22px;
+ /* Soft shadow on the left edge so the overlap reads as the
+ cluster "floating over" the chip. */
+ box-shadow: -6px 0 12px -6px rgba(0, 0, 0, 0.25);
+ }
+ }
+ /* Mobile: drop the box-shadow AND the left-edge gradient fade —
+ either can read as a shadow under the icons on phone screens.
+ Also lift the cluster 1px more. !important needed because the
+ @container query overlay rule has the same selector specificity. */
+ @media (max-width: 768px) {
+ .memory-toolbar-btn[data-mode="ai-reply-fast"] {
+ height: 30px !important;
+ min-height: 30px !important;
+ }
+ .email-reader-meta > .email-reader-actions-inline {
+ box-shadow: none !important;
+ background: none !important;
+ padding-left: 0 !important;
+ margin-top: -10px;
+ }
+ }
+ /* Docked panes used to flow the cluster under the meta; now they
+ share the same absolute-top-right + wrap behaviour as undocked.
+ No docked-specific overrides — the container queries below pick
+ the right cluster size and overlay state from the reader width. */
+ /* Gmail-style chevron — collapsed view shows only From; the chevron
+ reveals the To/Cc details inline below. */
+ .email-reader-meta-toggle {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 18px;
+ height: 18px;
+ margin-left: -3px;
+ padding: 0;
+ border: none;
+ background: transparent;
+ color: inherit;
+ opacity: 0.55;
+ cursor: pointer;
+ border-radius: 4px;
+ flex-shrink: 0;
+ }
+ .email-reader-meta-toggle:hover { opacity: 1; background: color-mix(in srgb, currentColor 10%, transparent); }
+ .email-reader-meta-toggle svg { transition: transform 0.15s ease; }
+ .email-reader-meta-toggle.open svg { transform: rotate(180deg); }
+ .email-reader-meta-toggle.email-reader-cc-toggle {
+ width: auto;
+ min-width: 18px;
+ gap: 3px;
+ margin-left: 1px;
+ padding: 0 5px;
+ color: var(--accent, var(--red));
+ font-family: inherit;
+ font-size: 9px;
+ font-weight: 600;
+ line-height: 1;
+ }
+ .email-reader-meta-details {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ /* When expanded, To/Cc details live in the header flow. A floating popover
+ can overlap the folded attachment strip directly beneath the header. */
+ .email-reader-meta > .email-reader-meta-details:not([hidden]) {
+ position: relative;
+ top: auto;
+ left: auto;
+ right: auto;
+ margin-top: 4px;
+ background: transparent;
+ border: 0;
+ border-radius: 0;
+ padding: 0;
+ box-shadow: none;
+ z-index: 1;
+ }
+ /* Reserve a fixed label width so From: / To: / Cc: all align and
+ their chips start at the same x. */
+ .email-reader-meta-row strong { opacity: 0.5; font-weight: 600; flex-shrink: 0; min-width: 36px; }
+ .email-reader-meta-row > span {
+ white-space: nowrap;
+ min-width: 0;
+ }
+ /* Recipient chips */
+ .recipient-chips {
+ display: inline-flex !important; flex-wrap: wrap; gap: 4px;
+ white-space: normal !important; overflow: visible !important;
+ text-overflow: clip !important;
+ }
+ .recipient-chip {
+ display: inline-flex; align-items: center;
+ gap: 5px;
+ padding: 1px 8px; font-size: 10px;
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ color: var(--fg);
+ white-space: nowrap;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s, max-width 0.2s;
+ max-width: 220px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .recipient-chip-label {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .recipient-chip-copy {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ top: -2px;
+ width: 14px;
+ height: 14px;
+ padding: 0;
+ border: none;
+ background: none;
+ color: inherit;
+ opacity: 0.55;
+ cursor: pointer;
+ flex: 0 0 auto;
+ }
+ .recipient-chip-copy:hover,
+ .recipient-chip-copy.copied {
+ opacity: 1;
+ color: var(--accent-primary, var(--red));
+ }
+ .recipient-chip-copy[hidden] {
+ display: none !important;
+ }
+ .recipient-chip:hover {
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 12%, transparent);
+ border-color: color-mix(in srgb, var(--accent-primary, var(--red)) 40%, transparent);
+ }
+ .recipient-chip.expanded {
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 15%, transparent);
+ border-color: var(--accent-primary, var(--red));
+ max-width: 500px;
+ }
+ .recipient-chip.popover-open {
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 15%, transparent);
+ border-color: var(--accent-primary, var(--red));
+ }
+ .recipient-chip-popover {
+ position: fixed;
+ z-index: 12050;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ max-width: min(420px, calc(100vw - 20px));
+ padding: 8px 10px;
+ border: 1px solid color-mix(in srgb, var(--accent-primary, var(--red)) 45%, var(--border));
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--bg) 96%, var(--fg) 4%);
+ color: var(--fg);
+ box-shadow: 0 14px 34px rgba(0, 0, 0, 0.42);
+ font-size: 12px;
+ line-height: 1.35;
+ pointer-events: auto;
+ }
+ .recipient-chip-popover-main {
+ min-width: 0;
+ }
+ .recipient-chip-popover-name {
+ font-weight: 650;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .recipient-chip-popover-detail {
+ overflow-wrap: anywhere;
+ opacity: 0.86;
+ }
+ .recipient-chip-popover-copy {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex: 0 0 auto;
+ width: 26px;
+ height: 26px;
+ padding: 0;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ color: inherit;
+ cursor: pointer;
+ }
+ .recipient-chip-popover-copy:hover,
+ .recipient-chip-popover-copy.copied {
+ color: var(--accent-primary, var(--red));
+ border-color: color-mix(in srgb, var(--accent-primary, var(--red)) 55%, transparent);
+ }
+ @container docpane (max-width: 460px) {
+ .email-reader-header {
+ flex-direction: column;
+ gap: 6px;
+ }
+ .email-reader-header > .email-reader-actions {
+ /* On narrow widths fall back to in-flow so it doesn't overlap
+ the meta entirely. */
+ position: static;
+ align-self: flex-end;
+ background: none;
+ padding-left: 0;
+ }
+ .email-reader-meta-row:not(.email-reader-meta-from) {
+ padding-right: 0;
+ }
+ .email-reader-meta-row strong {
+ min-width: 0;
+ }
+ .recipient-chip {
+ max-width: 100%;
+ }
+ }
+ /* Mobile: long recipient lists (To/Cc with many addresses) shouldn't wrap to
+ N rows and push the body down. Keep them on one row, horizontally scrollable,
+ no scrollbar chrome. */
+ @media (max-width: 768px) {
+ .recipient-chips {
+ flex-wrap: nowrap !important;
+ overflow-x: auto !important;
+ overflow-y: hidden !important;
+ scrollbar-width: none;
+ -webkit-overflow-scrolling: touch;
+ }
+ .recipient-chips::-webkit-scrollbar { display: none; }
+ .recipient-chip { flex-shrink: 0; }
+ }
+ .email-reader-actions {
+ display: flex; flex-direction: column; gap: 4px; align-items: flex-end;
+ flex-shrink: 0;
+ margin-top: -4px;
+ }
+ /* Two stacked rows: Reply/Reply-all/Forward on the From line, with
+ Summary/AI-reply/More on a row below. */
+ .email-reader-actions-row {
+ display: flex;
+ flex-direction: row;
+ flex-wrap: nowrap;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 4px;
+ }
+ .email-reader-atts {
+ display: flex; flex-wrap: wrap; gap: 6px;
+ padding: 8px 14px;
+ border-bottom: 1px solid var(--border);
+ flex-shrink: 0;
+ }
+ .email-reader-body {
+ font-size: 12px;
+ line-height: 1.55;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ overflow-wrap: anywhere;
+ flex: 1;
+ overflow-y: auto;
+ padding: 14px;
+ min-height: 0;
+ background: var(--panel);
+ box-shadow: inset 0 1px 0 color-mix(in srgb, var(--border) 65%, transparent);
+ /* Use the OS colored emoji font for incoming mail content */
+ font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif,
+ "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", "Twemoji Mozilla";
+ font-variant-emoji: emoji;
+ }
+ .email-reader-body.html-body img { max-width: 100%; height: auto; }
+ .email-reader-body.html-body [style*="max-width:600px"],
+ .email-reader-body.html-body [style*="max-width: 600px"],
+ .email-reader-body.html-body [style*="width:600px"],
+ .email-reader-body.html-body [style*="width: 600px"],
+ .email-reader-body.html-body table[width="600"] {
+ max-width: none !important;
+ width: 100% !important;
+ margin-left: 0 !important;
+ margin-right: 0 !important;
+ }
+ .email-reader-body.html-body [align="center"] {
+ margin-left: 0 !important;
+ margin-right: 0 !important;
+ }
+ .email-reader-body .email-inline-image-placeholder {
+ display: inline-flex;
+ align-items: center;
+ gap: 9px;
+ max-width: min(100%, 360px);
+ min-height: 58px;
+ margin: 6px 0;
+ padding: 8px 10px;
+ border: 1px solid color-mix(in srgb, var(--border) 85%, transparent);
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--panel) 72%, transparent);
+ color: var(--fg);
+ vertical-align: middle;
+ }
+ .email-inline-image-skeleton {
+ width: 58px;
+ height: 42px;
+ flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 6px;
+ background: linear-gradient(
+ 90deg,
+ color-mix(in srgb, var(--fg) 7%, transparent) 0%,
+ color-mix(in srgb, var(--fg) 13%, transparent) 45%,
+ color-mix(in srgb, var(--fg) 7%, transparent) 90%
+ );
+ background-size: 220% 100%;
+ animation: email-skeleton-shimmer 1.35s ease-in-out infinite;
+ }
+ .email-inline-image-icon {
+ opacity: 0.52;
+ display: inline-flex;
+ }
+ .email-inline-image-placeholder.is-loading .email-inline-image-icon svg {
+ display: none;
+ }
+ .email-inline-image-info {
+ display: inline-flex;
+ flex-direction: column;
+ min-width: 0;
+ line-height: 1.25;
+ }
+ .email-inline-image-title {
+ font-size: 11px;
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .email-inline-image-sub {
+ font-size: 10px;
+ opacity: 0.58;
+ }
+ .email-inline-image-actions {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ margin-left: auto;
+ flex: 0 0 auto;
+ }
+ .email-inline-image-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ transform: translateY(-2px);
+ height: 24px;
+ line-height: 1;
+ padding: 0 8px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ color: inherit;
+ font: inherit;
+ font-size: 10px;
+ text-decoration: none;
+ cursor: pointer;
+ }
+ .email-inline-image-btn:hover {
+ border-color: color-mix(in srgb, var(--accent-primary, var(--red)) 55%, var(--border));
+ color: var(--accent-primary, var(--red));
+ }
+ .email-inline-image-download-btn {
+ width: 24px;
+ min-width: 24px;
+ padding: 0;
+ }
+ .email-inline-image-loaded {
+ max-width: 100%;
+ height: auto;
+ border-radius: 6px;
+ }
+ .email-inline-image-frame {
+ display: inline-flex;
+ max-width: 100%;
+ min-width: min(360px, 100%);
+ min-height: 90px;
+ margin: 6px 0;
+ align-items: center;
+ justify-content: center;
+ border-radius: 8px;
+ background: linear-gradient(
+ 90deg,
+ color-mix(in srgb, var(--fg) 7%, transparent) 0%,
+ color-mix(in srgb, var(--fg) 13%, transparent) 45%,
+ color-mix(in srgb, var(--fg) 7%, transparent) 90%
+ );
+ background-size: 220% 100%;
+ }
+ .email-inline-image-frame .email-inline-image-loaded {
+ opacity: 0;
+ transition: opacity 0.15s ease;
+ }
+ .email-inline-image-load-all {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ max-width: 100%;
+ margin: -4px 0 6px;
+ padding: 7px 9px;
+ border: 1px solid color-mix(in srgb, var(--border) 85%, transparent);
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--panel) 72%, transparent);
+ font-size: 11px;
+ }
+ .email-inline-image-load-all span {
+ opacity: 0.68;
+ margin-right: auto;
+ }
+ .email-inline-image-load-all button {
+ transform: translateY(-4px);
+ height: 24px;
+ padding: 0 8px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ color: inherit;
+ font: inherit;
+ font-size: 10px;
+ cursor: pointer;
+ }
+ .email-inline-image-load-all button:hover {
+ border-color: color-mix(in srgb, var(--accent-primary, var(--red)) 55%, var(--border));
+ color: var(--accent-primary, var(--red));
+ }
+ @media (max-width: 520px) {
+ .email-reader-body .email-inline-image-placeholder {
+ display: flex;
+ width: 100%;
+ }
+ .email-inline-image-skeleton {
+ width: 48px;
+ }
+ .email-inline-image-actions {
+ flex-direction: column;
+ align-items: stretch;
+ }
+ }
+ .email-reader-body.html-body table { max-width: 100%; border-collapse: collapse; }
+ /* Gmail Drive chips arrive with inline width/height/border/padding from
+ Gmail's composer (border:1px solid #ddd, white-ish bg assumed). On a
+ dark theme that reads as a near-invisible white box. Override with a
+ theme-aware chip surface so the filename + icon stay visible. */
+ .email-reader-body .gmail_chip,
+ .email-reader-body .gmail_drive_chip {
+ width: auto !important;
+ max-width: 100% !important;
+ height: auto !important;
+ max-height: none !important;
+ display: inline-flex !important;
+ align-items: center !important;
+ gap: 6px;
+ padding: 6px 10px !important;
+ margin: 6px 0 !important;
+ border: 1px solid var(--border) !important;
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--fg) 4%, transparent);
+ }
+ .email-reader-body .gmail_chip:hover,
+ .email-reader-body .gmail_drive_chip:hover {
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 45%, var(--border)) !important;
+ background: color-mix(in srgb, var(--accent, var(--red)) 6%, transparent);
+ }
+ .email-reader-body .gmail_chip a,
+ .email-reader-body .gmail_drive_chip a {
+ color: var(--accent, var(--red)) !important;
+ display: inline-flex !important;
+ align-items: center;
+ gap: 6px;
+ max-width: 100% !important;
+ }
+ .email-reader-body .gmail_chip a > span,
+ .email-reader-body .gmail_drive_chip a > span {
+ color: var(--fg) !important;
+ font-size: 12px;
+ }
+ .email-reader-body .gmail_chip img,
+ .email-reader-body .gmail_drive_chip img {
+ width: 16px !important;
+ height: 16px !important;
+ padding-right: 0 !important;
+ filter: none;
+ }
+
+ /* Force any phone/sms/date/address auto-link to inherit the body color so
+ numbers don't render as bright-blue browser-default text inside email
+ content. format-detection in <head> turns off detection on iOS, but some
+ mail clients ship pre-wrapped tel: links — those still need taming. */
+ .email-reader-body a[href^="tel:"],
+ .email-reader-body a[href^="sms:"],
+ .email-reader-body a[x-apple-data-detectors],
+ .email-bubble-body a[href^="tel:"],
+ .email-bubble-body a[href^="sms:"],
+ .email-bubble-body a[x-apple-data-detectors],
+ .email-thread-turn-body a[href^="tel:"],
+ .email-thread-turn-body a[href^="sms:"],
+ .email-thread-turn-body a[x-apple-data-detectors] {
+ color: inherit !important;
+ text-decoration: none !important;
+ pointer-events: auto;
+ }
+ .email-reader-body a,
+ .email-bubble-body a,
+ .email-thread-turn-body a {
+ color: var(--accent-primary, var(--red));
+ text-decoration: underline;
+ overflow-wrap: anywhere;
+ word-break: normal;
+ cursor: pointer;
+ }
+ .email-reader-body a:hover,
+ .email-bubble-body a:hover,
+ .email-thread-turn-body a:hover { opacity: 0.8; }
+ /* Summary block — same band chrome as Attachments / Signature / Earlier-
+ thread (no accent tint, no rounded corners, no leading star icon). The
+ only difference is the label, so all collapsible sections in the email
+ reader look uniform. */
+ .email-summary-panel {
+ margin: 0 0 12px 0;
+ padding: 10px 12px;
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 8%, transparent);
+ border: 1px solid color-mix(in srgb, var(--accent-primary, var(--red)) 30%, transparent);
+ border-radius: 6px;
+ }
+ .email-summary-header {
+ display: flex; align-items: center; gap: 5px;
+ font-size: 10px; font-weight: 600; text-transform: uppercase;
+ color: var(--accent-primary, var(--red)); opacity: 0.85;
+ margin-bottom: 6px; letter-spacing: 0.4px;
+ }
+ .email-summary-content {
+ font-size: 12px; line-height: 1.5; color: var(--fg); white-space: pre-wrap;
+ }
+ /* Click-to-fold: tap the summary header to collapse/expand. The chevron
+ flips when collapsed, the content hides + the panel's bottom margin
+ tightens so a folded summary doesn't take up vertical space. */
+ .email-summary-toggle { cursor: pointer; user-select: none; }
+ .email-summary-panel.collapsed { padding-bottom: 6px; margin-bottom: 6px; }
+ .email-translation-loading {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 26px;
+ }
+ .email-translation-busy {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 7px;
+ }
+ .email-translation-spinner {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 18px;
+ height: 18px;
+ }
+ .email-translation-loading-text {
+ opacity: 0.68;
+ font-size: 12px;
+ }
+ .email-translation-panel .email-translation-icon {
+ color: var(--accent-primary, var(--red));
+ }
+
+ /* Foldable attachments — same fold-on-click UX as the summary panel. */
+ .email-reader-atts-wrap {
+ display: flex; flex-direction: column;
+ border-bottom: 1px solid var(--border);
+ flex-shrink: 0;
+ }
+ .email-reader-atts-header {
+ display: flex; align-items: center; gap: 5px;
+ padding: 6px 14px;
+ font-size: 10px; font-weight: 600; text-transform: uppercase;
+ color: var(--fg); opacity: 0.7;
+ cursor: pointer; user-select: none;
+ letter-spacing: 0.4px;
+ }
+ .email-attachments-download-all {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ height: 22px;
+ padding: 0 8px;
+ border-radius: 999px;
+ border: 1px solid color-mix(in srgb, var(--accent-primary, var(--red)) 35%, transparent);
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 9%, transparent);
+ color: var(--accent-primary, var(--red));
+ font: inherit;
+ font-size: 10px;
+ font-weight: 700;
+ text-transform: none;
+ letter-spacing: 0;
+ cursor: pointer;
+ flex: 0 0 auto;
+ }
+ .email-attachments-download-all:hover {
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 18%, transparent);
+ border-color: color-mix(in srgb, var(--accent-primary, var(--red)) 60%, transparent);
+ }
+ .email-attachments-download-all .spinner-whirlpool,
+ .email-attachments-download-all .ai-spinner-whirlpool {
+ width: 12px !important;
+ height: 12px !important;
+ margin: 0 !important;
+ }
+ .email-reader-atts-wrap > .email-reader-atts {
+ border-bottom: none !important;
+ }
+ .email-reader-atts-hidden-note {
+ padding: 0 14px 6px;
+ font-size: 10px;
+ color: var(--fg-muted);
+ opacity: 0.65;
+ }
+
+ /* Quote fold = neutral full-width band (matches attachments header). */
+ .email-quote-fold {
+ margin: 0 -14px;
+ padding: 0;
+ border: 0;
+ border-top: 1px solid var(--border) !important;
+ border-radius: 0;
+ outline: 0 !important;
+ box-shadow: none !important;
+ /* Neutralise any rich-mail HTML that injects a yellow / colored bg
+ or border onto blockquote ancestors. */
+ background: transparent !important;
+ }
+ /* Same neutralisation for any element nested inside the fold (the inner
+ blockquote, paragraphs, divs from the original message). Yellow outlines
+ in Outlook-style mails almost always come from inline border-color or
+ box-shadow on these. */
+ .email-quote-fold *,
+ .email-quote-fold *::before,
+ .email-quote-fold *::after {
+ outline-color: transparent !important;
+ box-shadow: none !important;
+ }
+ .email-quote-fold blockquote,
+ .email-quote-fold blockquote[type="cite"],
+ .email-quote-fold table,
+ .email-quote-fold div {
+ border-color: var(--border) !important;
+ /* Override the .msg blockquote rule that sets a colored left border via
+ var(--hl-function) — that's where the "yellow" outline was coming from. */
+ border-left-color: var(--border) !important;
+ border-radius: 0 !important;
+ background: transparent !important;
+ }
+ /* JS marks the last .email-quote-fold in each email body with this class,
+ so it's the only one that gets rounded bottom corners. Avoids :has()
+ browser-support quirks. */
+ .email-quote-fold.last-fold {
+ border-radius: 0 0 8px 8px;
+ overflow: hidden;
+ }
+ /* ── Threaded reply turns (recursive parser) ── */
+ .email-thread-turn-body {
+ padding: 8px 14px 4px;
+ font-size: 12px;
+ line-height: 1.45;
+ }
+ /* Nested turns indent slightly + get their own card outline so the
+ reply hierarchy is obvious at a glance. */
+ .email-thread-turn-body .email-thread-turn {
+ margin: 8px 0 4px;
+ margin-left: 8px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--fg) 2%, transparent);
+ }
+ /* The original blockquote's left stripe is redundant when each turn is
+ already a card — drop it inside thread bodies. */
+ .email-thread-turn-body blockquote {
+ border-left: none !important;
+ margin: 0 !important;
+ padding: 0 !important;
+ background: transparent !important;
+ }
+ /* Flatten the inner blockquote: no rounded corners, no yellow tint
+ inherited from rich-mail HTML. Subtle left border + neutral bg. */
+ .email-quote-fold blockquote {
+ margin: 0;
+ padding: 8px 12px;
+ border: 0;
+ border-left: 2px solid var(--border);
+ border-radius: 0 !important;
+ background: transparent !important;
+ color: inherit;
+ }
+ /* "From … · Date …" chip appended to the summary line */
+ .email-fold-summary-meta {
+ margin-left: 6px;
+ font-size: 10px;
+ font-weight: 500;
+ text-transform: none;
+ letter-spacing: 0;
+ opacity: 0.55;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ min-width: 0;
+ }
+ /* Sender name is the primary affordance — slightly larger and not all-caps so
+ "From: Sam" feels like a click target on the person, not a section label. */
+ .email-fold-summary-name {
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: none;
+ letter-spacing: 0.1px;
+ color: var(--fg);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ min-width: 0;
+ }
+ .email-quote-fold .email-fold-summary {
+ display: flex; align-items: center; gap: 5px;
+ padding: 6px 14px;
+ cursor: pointer; list-style: none;
+ font-size: 10px; font-weight: 600; text-transform: uppercase;
+ letter-spacing: 0.4px;
+ /* Force neutral page colors regardless of any rich-mail HTML wrapping us */
+ color: var(--fg) !important;
+ background: transparent !important;
+ background-color: transparent !important;
+ text-shadow: none !important;
+ font-style: normal !important;
+ opacity: 0.7;
+ user-select: none;
+ border-radius: 0;
+ }
+ .email-quote-fold .email-fold-summary > * {
+ /* Prevent inline-color attrs on summary children (icon SVGs, meta span)
+ from picking up a forced color from ancestor email HTML. */
+ color: inherit !important;
+ background: transparent !important;
+ }
+ .email-quote-fold .email-fold-summary { list-style: none; list-style-type: none; }
+ .email-quote-fold[open] > *:not(summary) {
+ padding: 8px 14px 12px 14px;
+ border-top: 1px solid var(--border);
+ }
+
+ /* Signature fold = clean full-width band like the attachments header. No
+ accent overlay, no rounded corners — neutral chrome so it doesn't look
+ like the AI Summary panel. */
+ .email-sig-fold {
+ margin: 8px 0 0;
+ padding: 0;
+ border: 0;
+ border-top: 1px dashed color-mix(in srgb, var(--fg) 18%, transparent);
+ background: transparent;
+ border-radius: 0;
+ }
+ .email-sig-fold .email-fold-summary {
+ display: flex; align-items: center; gap: 5px;
+ padding: 4px 0;
+ cursor: pointer;
+ list-style: none; list-style-type: none;
+ font-size: 9.5px; font-weight: 600; text-transform: uppercase;
+ letter-spacing: 0.4px;
+ color: var(--fg); opacity: 0.55;
+ user-select: none;
+ }
+ .email-sig-fold[open] > *:not(summary) {
+ padding: 6px 0 0;
+ border-top: 0;
+ font-size: 11px; line-height: 1.45;
+ color: color-mix(in srgb, var(--fg) 75%, transparent);
+ white-space: pre-wrap;
+ }
+
+ /* ── Chat-bubble layout for email threads ──
+ Each parsed turn becomes a bubble. The active account's outgoing
+ replies align right (mine); everyone else aligns left (theirs).
+ Bubbles read top→bottom oldest→newest, like a chat. */
+ .email-bubbles {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ padding: 4px 0 8px;
+ margin: 0 -2px;
+ }
+ .email-bubble-row {
+ display: flex;
+ align-items: flex-end;
+ gap: 8px;
+ width: 100%;
+ min-width: 0;
+ }
+ .email-bubble {
+ flex: 0 1 auto;
+ max-width: 90%;
+ min-width: 0;
+ padding: 8px 12px;
+ border: 1px solid var(--border);
+ background: var(--panel);
+ font-size: 12.5px;
+ line-height: 1.5;
+ word-wrap: break-word;
+ overflow-wrap: anywhere;
+ overflow: hidden;
+ }
+ .email-bubble-mine .email-bubble {
+ background: color-mix(in srgb, var(--bubble-accent, var(--fg)) 10%, var(--bg));
+ border-color: color-mix(in srgb, var(--bubble-accent, var(--border)) 35%, var(--border));
+ border-radius: 14px 14px 4px 14px;
+ }
+ .email-bubble-theirs .email-bubble {
+ background: color-mix(in srgb, var(--bubble-accent, var(--fg)) 5%, var(--panel));
+ border-color: color-mix(in srgb, var(--bubble-accent, var(--border)) 25%, var(--border));
+ border-radius: 14px 14px 14px 4px;
+ }
+ .email-bubble-head {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+ font-size: 10.5px;
+ margin-bottom: 4px;
+ opacity: 0.7;
+ min-width: 0;
+ }
+ .email-bubble-author {
+ font-weight: 600;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 50ch;
+ }
+ .email-bubble-date {
+ opacity: 0.7;
+ font-weight: 400;
+ white-space: nowrap;
+ }
+ .email-bubble-body {
+ white-space: normal;
+ /* Reader-controlled typography — override sender's inline styles AND
+ attribute-based sizing (<font size>, <big>, <small>, h1..h6). Weight
+ and italics still pass through for emphasis. */
+ font-family: inherit;
+ font-size: var(--email-body-size, 13.5px);
+ line-height: 1.5;
+ }
+ /* Heading tags carry browser-default font-size multipliers that bypass
+ `font-size: inherit` when an inline style was set; pin them too. */
+ .email-bubble-body h1,
+ .email-bubble-body h2,
+ .email-bubble-body h3,
+ .email-bubble-body h4,
+ .email-bubble-body h5,
+ .email-bubble-body h6,
+ .email-bubble-body big,
+ .email-bubble-body small,
+ .email-bubble-body font {
+ font-size: inherit !important;
+ line-height: inherit !important;
+ }
+ /* Sender HTML often wraps content in a fixed-width <div style="width:600px">
+ or <table width="600">. Override so content fills the reader's available
+ width — otherwise resizing the email window doesn't reflow anything. */
+ .email-bubble-body,
+ .email-bubble-body * {
+ max-width: 100% !important;
+ }
+ .email-bubble-body div[style*="width"],
+ .email-bubble-body table[width],
+ .email-bubble-body table {
+ width: 100% !important;
+ box-sizing: border-box !important;
+ }
+ .email-bubble-body blockquote {
+ border-left: 2px solid var(--border) !important;
+ margin: 4px 0 !important;
+ padding: 4px 10px !important;
+ background: transparent !important;
+ border-radius: 0 !important;
+ color: inherit;
+ }
+ .email-bubble-avatar {
+ flex-shrink: 0;
+ width: 26px;
+ height: 26px;
+ border-radius: 50%;
+ /* Per-sender color set inline (`style="background:hsl(...)"`); this
+ fallback only kicks in when JS hasn't assigned one. */
+ background: color-mix(in srgb, var(--fg) 14%, transparent);
+ color: #fff;
+ text-shadow: 0 1px 0 rgba(0, 0, 0, 0.22);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 9.5px;
+ font-weight: 600;
+ letter-spacing: 0.3px;
+ user-select: none;
+ }
+ /* Sig folds inside a bubble: tone down — no full-bleed band, since the
+ bubble already provides the chrome. */
+ .email-bubble-body .email-sig-fold {
+ margin: 8px 0 0;
+ border-top: 1px dashed var(--border);
+ }
+ .email-bubble-body .email-sig-fold[open] > *:not(summary),
+ .email-bubble-body .email-quote-fold[open] > *:not(summary) {
+ padding: 6px 0 0;
+ border-top: 0;
+ }
+ @media (max-width: 600px) {
+ .email-bubble { max-width: 96%; }
+ .email-bubble-avatar { display: none; }
+ }
+
+ /* ── Schedule Send modal ── */
+ .schedule-send-body {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 16px 18px 12px;
+ }
+ .schedule-send-label {
+ font-size: 11px;
+ font-weight: 500;
+ letter-spacing: 0.3px;
+ text-transform: uppercase;
+ color: var(--fg);
+ opacity: 0.55;
+ margin-top: 6px;
+ }
+ .schedule-send-label:first-child { margin-top: 0; }
+ .schedule-send-presets {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 6px;
+ margin-bottom: 4px;
+ }
+ .schedule-send-presets .memory-toolbar-btn {
+ padding: 5px 10px 11px;
+ font-size: 12px;
+ justify-content: center;
+ line-height: 1;
+ }
+ .schedule-send-confirm svg {
+ width: 12px;
+ height: 12px;
+ vertical-align: -1px;
+ margin-right: 6px;
+ }
+ .schedule-send-datetime {
+ font-size: 13px;
+ padding: 8px 10px;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ outline: none;
+ font-family: inherit;
+ width: 100%;
+ box-sizing: border-box;
+ }
+ .schedule-send-datetime:focus {
+ border-color: var(--hl-function);
+ }
+ .schedule-send-footer {
+ display: flex;
+ justify-content: flex-end;
+ align-items: center;
+ gap: 8px;
+ padding: 10px 18px 14px;
+ border-top: 1px solid var(--border);
+ margin-top: 4px;
+ }
+ .schedule-send-confirm {
+ background: var(--accent-primary, var(--red)) !important;
+ color: #fff !important;
+ border-color: var(--accent-primary, var(--red)) !important;
+ }
+ .schedule-send-confirm:hover {
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 85%, white) !important;
+ }
+
+ /* Senders embed inline colors in their HTML that clash with the app's
+ theme (black text in dark mode, white backgrounds, yellow highlights,
+ etc.). Force theme colors on every descendant of the rendered body so
+ emails inherit the user's chosen palette regardless of what the
+ sender's mail client emits. */
+ .email-reader-body *,
+ .email-bubble-body * {
+ color: var(--fg) !important;
+ -webkit-text-fill-color: currentColor !important;
+ background-color: transparent !important;
+ background-image: none !important;
+ }
+ .email-reader-body a,
+ .email-bubble-body a,
+ .email-thread-turn-body a {
+ color: var(--hl-function) !important;
+ }
+ .email-reader-body a[href^="tel:"],
+ .email-reader-body a[href^="sms:"],
+ .email-reader-body a[href^="x-apple-data-detectors:"],
+ .email-reader-body a[x-apple-data-detectors],
+ .email-bubble-body a[href^="tel:"],
+ .email-bubble-body a[href^="sms:"],
+ .email-bubble-body a[href^="x-apple-data-detectors:"],
+ .email-bubble-body a[x-apple-data-detectors],
+ .email-thread-turn-body a[href^="tel:"],
+ .email-thread-turn-body a[href^="sms:"],
+ .email-thread-turn-body a[href^="x-apple-data-detectors:"],
+ .email-thread-turn-body a[x-apple-data-detectors] {
+ color: inherit !important;
+ -webkit-text-fill-color: currentColor !important;
+ text-decoration: none !important;
+ background-color: transparent !important;
+ background-image: none !important;
+ -webkit-background-clip: border-box !important;
+ background-clip: border-box !important;
+ }
+
+ /* Prefer local/system emoji fonts; avoid remote font providers. */
+ .doc-editor-textarea, .doc-editor-highlight, #doc-editor-code,
+ .doc-md-preview, .doc-csv-preview {
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', 'Noto Color Emoji', 'Apple Color Emoji', 'Segoe UI Emoji', monospace;
+ font-variant-emoji: text;
+ }
+ /* Preview panes claim the editor's space so the action footer stays pinned
+ at the bottom of the pane even when the rendered content is short
+ (shorter table, single-paragraph markdown, etc). */
+ .doc-csv-preview,
+ .doc-md-preview {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow: auto;
+ }
+
+ /* Email documents override: use colored system emoji in compose. */
+ .doc-editor-textarea.email-mode,
+ #doc-editor-code.email-mode,
+ #doc-editor-code.email-mode .doc-editor-highlight,
+ #doc-editor-code.email-mode .doc-editor-textarea {
+ font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif,
+ "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", "Twemoji Mozilla" !important;
+ font-variant-emoji: emoji;
+ }
+
+ /* Single-layer rendering for ALL documents (not just email): the highlight
+ overlay (<pre> with hljs spans) and the transparent textarea use two
+ different rendering paths internally — the textarea uses the browser's
+ native form line-breaker, the overlay uses CSS line-breaking — and they
+ can never be guaranteed to wrap byte-identical no matter how many CSS
+ properties are pinned. Pick one source of truth: make the textarea its
+ own visible text, hide the overlay. Trade-off: no syntax highlighting in
+ the live editor (rendered markdown preview / chat output still has it).
+ The caret is now glued to the typed text by definition since both are
+ rendered by the same element. */
+ .doc-editor-highlight,
+ #doc-editor-code.email-mode .doc-editor-highlight {
+ display: none !important;
+ }
+ /* Find bar is open: float the highlight overlay ON TOP of the
+ textarea with transparent background + transparent text, so only
+ the solid <mark.doc-find-mark> spans are visible. pointer-events
+ off so clicks still go through to the textarea below. */
+ body.doc-find-active .doc-editor-highlight,
+ body.doc-find-active #doc-editor-code.email-mode .doc-editor-highlight {
+ display: block !important;
+ z-index: 5 !important;
+ background: transparent !important;
+ pointer-events: none;
+ }
+ body.doc-find-active .doc-editor-highlight,
+ body.doc-find-active .doc-editor-highlight * {
+ color: transparent !important;
+ background: transparent !important;
+ }
+ .doc-editor-textarea,
+ #doc-editor-code.email-mode .doc-editor-textarea {
+ color: var(--fg) !important;
+ caret-color: var(--fg) !important;
+ z-index: 1;
+ }
+
++/* Code uses non-wrapping, identical lines in both layers. Prose keeps the
++ single-layer caret fix above. Colors come from the current theme's --hl-*.
++ Find mode retains its own overlay and visible textarea text. */
++.doc-code-syntax .doc-editor-textarea,
++.doc-code-syntax .doc-editor-highlight,
++.doc-code-syntax .doc-editor-highlight code {
++ white-space: pre !important;
++ overflow-wrap: normal !important;
++ word-break: normal !important;
++}
++.doc-code-syntax .doc-editor-highlight code {
++ width: max-content;
++ min-width: 100%;
++}
++body:not(.doc-find-active) .doc-code-syntax:not(.diff-mode) .doc-editor-highlight {
++ display: block !important;
++}
++body:not(.doc-find-active) .doc-code-syntax:not(.diff-mode) .doc-editor-textarea {
++ color: transparent !important;
++ background: transparent !important;
++}
++
+ /* Emoji picker (monochrome icon picker) */
+ .emoji-picker-btn {
+ background: none; border: none; color: var(--fg); opacity: 0.35;
+ padding: 4px 7px; cursor: pointer; min-height: 28px;
+ display: inline-flex; align-items: center; justify-content: center;
+ transition: opacity 0.1s;
+ }
+ .emoji-picker-btn:hover { opacity: 1; }
+ .emoji-picker {
+ width: min(300px, 92vw); max-height: min(300px, 55vh);
+ background: var(--panel); border: 1px solid var(--border); border-radius: 8px;
+ box-shadow: 0 8px 24px rgba(0,0,0,0.3);
+ display: flex; flex-direction: column; overflow: hidden;
+ }
+ .emoji-picker-search {
+ padding: 8px 12px; background: var(--panel); border: none;
+ border-bottom: 1px solid var(--border); color: var(--fg);
+ font-size: 12px; font-family: inherit; outline: none;
+ }
+ .emoji-picker-groups { overflow-y: auto; padding: 4px 0; flex: 1; }
+ .emoji-picker-group { padding: 0 6px 4px 6px; }
+ .emoji-picker-group-name {
+ font-size: 10px; font-weight: 600; opacity: 0.5;
+ text-transform: uppercase; letter-spacing: 0.5px;
+ padding: 4px 4px 2px 4px;
+ }
+ .emoji-picker-grid { display: grid; grid-template-columns: repeat(8, 1fr); gap: 1px; }
+ .emoji-picker-item {
+ background: none; border: none; cursor: pointer;
+ padding: 4px; border-radius: 4px;
+ display: flex; align-items: center; justify-content: center;
+ color: var(--fg); transition: background 0.1s;
+ }
+ .emoji-picker-item:hover { background: color-mix(in srgb, var(--accent) 15%, transparent); }
+ .emoji-picker-item svg { width: 16px; height: 16px; }
+
+ .email-avatar {
+ width: 28px; height: 28px; border-radius: 50%; background: var(--accent, #4a9eff);
+ color: #fff; display: flex; align-items: center; justify-content: center;
+ font-size: 12px; font-weight: 600; flex-shrink: 0; margin-top: 1px;
+ }
+ .email-item-content { flex: 1; min-width: 0; overflow: hidden; }
+ .email-item-top { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; }
+ .email-sender { font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+ .email-filter-chip {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 6px;
+ margin: 4px 8px 6px;
+ padding: 4px 8px;
+ border-radius: 12px;
+ font-size: 11px;
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 40%, transparent);
+ color: var(--fg);
+ }
+ .email-filter-chip-clear {
+ background: none;
+ border: none;
+ color: inherit;
+ cursor: pointer;
+ font-size: 14px;
+ line-height: 1;
+ padding: 0 2px;
+ opacity: 0.6;
+ }
+ .email-date { font-size: 10px; opacity: 0.5; white-space: nowrap; flex-shrink: 0; }
+ .email-subject { font-size: 11px; opacity: 0.6; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 1px; }
+ .email-sent-chip,
+ .email-folder-chip {
+ display: inline-flex;
+ align-items: center;
+ height: 14px;
+ padding: 0 5px;
+ margin-right: 5px;
+ border-radius: 999px;
+ font-size: 8px;
+ line-height: 1;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0;
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 28%, transparent);
+ vertical-align: 1px;
+ }
+ .email-folder-chip {
+ position: relative;
+ top: 4px;
+ color: color-mix(in srgb, var(--fg) 75%, transparent);
+ background: rgba(127, 127, 127, 0.13);
+ border-color: rgba(127, 127, 127, 0.24);
+ }
+ .email-meta-date-group {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ white-space: nowrap;
+ }
+ .email-meta-date-group .email-folder-chip {
+ margin-right: 0;
+ }
+ .email-card-expanded .email-sent-chip,
+ .email-card-reader .email-sent-chip {
+ position: relative;
+ top: 4px;
+ }
+ .email-tags { display: inline-flex; align-items: center; flex-wrap: nowrap; gap: 3px; margin-left: 6px; vertical-align: middle; position: relative; top: -2px; }
+ .email-card-tags {
+ flex: 0 0 auto;
+ min-width: 0;
+ max-width: 48%;
+ position: relative;
+ top: -4px;
+ }
+ .email-card-expanded .email-tags,
+ .email-card-reader .email-tags { top: -4px; }
+ .doclib-card-expanded .email-card-tags { top: -4px; }
+ .email-card-expanded .email-card-titlerow .email-tag,
+ .email-card-expanded .email-card-titlerow .email-tags-more {
+ transform: translateY(-2px);
+ }
+ @media (max-width: 768px) {
+ .email-card-expanded .email-card-titlerow .email-tag,
+ .email-card-expanded .email-card-titlerow .email-tags-more {
+ transform: translateY(2px);
+ }
+ }
+ .email-card-tags.email-tags-expanded {
+ position: absolute;
+ z-index: 4;
+ right: calc(var(--email-status-width, 44px) + 6px);
+ top: -5px;
+ max-width: min(58%, 260px);
+ padding: 4px 5px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--panel, var(--bg));
+ box-shadow: 0 5px 14px color-mix(in srgb, #000 20%, transparent);
+ }
+ .email-tags-more {
+ appearance: none;
+ border: 0;
+ box-sizing: border-box;
+ border-radius: 999px;
+ background: rgba(127, 127, 127, 0.16);
+ color: var(--fg);
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 1px;
+ height: 13px !important;
+ min-height: 0 !important;
+ min-width: 23px;
+ padding: 1px 4px;
+ font-family: inherit;
+ font-size: 9px;
+ line-height: 1;
+ margin: 0;
+ opacity: 0.68;
+ position: relative;
+ top: 0;
+ vertical-align: middle;
+ }
+ .email-tags-more svg { display: block; flex: 0 0 auto; }
+ .email-tags-expanded .email-tags-more svg { transform: rotate(180deg); }
+ .email-tags-toggle-inline {
+ position: absolute;
+ right: 94px;
+ top: 50%;
+ transform: translateY(calc(-50% - 5px));
+ height: 20px !important;
+ min-width: 34px;
+ padding: 2px 6px !important;
+ font-size: 10px !important;
+ line-height: 1 !important;
+ opacity: 0.62;
+ border-radius: 999px !important;
+ }
+ .email-tags-toggle-inline.active {
+ opacity: 1;
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 12%, transparent);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 36%, transparent);
+ }
+ .email-tags-toggle-inline.email-tags-empty {
+ color: var(--warning, #d6b35a);
+ background: color-mix(in srgb, var(--warning, #d6b35a) 12%, transparent);
+ border-color: color-mix(in srgb, var(--warning, #d6b35a) 34%, transparent);
+ }
+ .email-tag {
+ display: inline-block;
+ font-size: 9px;
+ line-height: 1;
+ padding: 2px 5px;
+ border-radius: 8px;
+ font-weight: 500;
+ text-transform: uppercase;
+ letter-spacing: 0.3px;
+ background: rgba(127, 127, 127, 0.18);
+ color: var(--fg);
+ }
+ .email-tag-clickable {
+ appearance: none;
+ border: 0;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ box-sizing: border-box;
+ font-family: inherit;
+ font-size: 9px;
+ font-weight: 500;
+ height: 13px !important;
+ min-height: 0 !important;
+ line-height: 1;
+ margin: 0;
+ padding: 2px 5px !important;
+ text-transform: uppercase;
+ vertical-align: middle;
+ flex: 0 0 auto;
+ }
+ .email-tag-work { background: rgba(96, 165, 250, 0.22); color: #60a5fa; }
+ .email-tag-personal { background: rgba(74, 222, 128, 0.22); color: #4ade80; }
+ .email-tag-finance { background: rgba(250, 204, 21, 0.22); color: #facc15; }
+ .email-tag-bills { background: rgba(251, 146, 60, 0.22); color: #fb923c; }
+ .email-tag-receipt { background: rgba(251, 146, 60, 0.22); color: #fb923c; }
+ .email-tag-travel { background: rgba(167, 139, 250, 0.22); color: #a78bfa; }
+ .email-tag-newsletter { background: rgba(148, 163, 184, 0.22); color: #94a3b8; }
+ .email-tag-promo,
+ .email-tag-marketing { background: rgba(244, 114, 182, 0.22); color: #f472b6; }
+ .email-tag-notification { background: rgba(148, 163, 184, 0.22); color: #94a3b8; }
+ .email-tag-security { background: rgba(248, 113, 113, 0.22); color: #f87171; }
+ .email-tag-urgent { background: color-mix(in srgb, var(--color-error, #e06c75) 25%, transparent); color: var(--color-error, #e06c75); font-weight: 600; }
+ .email-tag-reply-soon { background: rgba(240, 173, 78, 0.22); color: #f0ad4e; }
+ .email-tag-social { background: rgba(56, 189, 248, 0.22); color: #38bdf8; }
+ .email-tag-shopping { background: rgba(236, 72, 153, 0.22); color: #ec4899; }
+ .email-tag-calendar { background: rgba(167, 139, 250, 0.22); color: #a78bfa; }
+ .email-menu-wrap { position: relative; flex-shrink: 0; }
+ .email-menu-btn {
+ background: none; border: none; color: var(--fg); opacity: 0; cursor: pointer;
+ padding: 4px; transition: opacity 0.15s;
+ position: relative; top: 0px;
+ }
+ .email-dropdown {
+ position: absolute; right: 0; top: 100%; z-index: 9999;
+ min-width: 120px; background: var(--bg); border: 1px solid var(--border);
+ border-radius: 6px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); padding: 4px 0;
+ }
+ .email-loading { padding: 16px; text-align: center; font-size: 12px; opacity: 0.5; }
+ .email-load-more { padding: 8px; text-align: center; }
+ .email-load-more-btn {
+ background: transparent; border: 1px solid var(--border); border-radius: 4px;
+ color: var(--fg); padding: 4px 12px; font-size: 11px; cursor: pointer;
+ }
+ .email-load-more-btn:hover { background: var(--hover-bg, rgba(255,255,255,0.05)); }
+ .email-spinner {
+ display: inline-block; width: 12px; height: 12px; border: 2px solid rgba(255,255,255,0.3);
+ border-top-color: #fff; border-radius: 50%; animation: email-spin 0.6s linear infinite;
+ vertical-align: middle; margin-right: 4px;
+ }
+
+ /* Email section doesn't collapse — hide the auto-injected chevron */
+ #email-section .section-collapse-btn { display: none !important; }
+
+ #email-section:hover #email-compose-btn {
+ opacity: 0.7 !important;
+ }
+ #email-compose-btn:hover {
+ opacity: 1 !important;
+ background: none !important;
+ }
+ #email-compose-btn svg {
+ width: 11px;
+ height: 11px;
+ transition: transform 0.45s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ #email-compose-btn .list-item-plus-label {
+ top: calc(50% - 0.5px);
+ color: var(--fg);
+ font-size: 10px;
+ }
+ #email-compose-btn:hover svg {
+ transform: rotate(180deg) scale(1.15);
+ }
+
+ /* Library row "+" — identical to the email compose "+": hidden until the row
+ is hovered, no accent box, and the same rotate-in animation. */
+ #library-new-doc-btn,
+ #notes-new-note-btn {
+ opacity: 0.4 !important;
+ transition: opacity 0.15s ease;
+ }
+ #tool-library-btn:hover #library-new-doc-btn,
+ #tool-notes-btn:hover #notes-new-note-btn {
+ opacity: 0.7 !important;
+ }
+ #library-new-doc-btn:hover,
+ #notes-new-note-btn:hover {
+ opacity: 1 !important;
+ background: none !important;
+ }
+ #library-new-doc-btn svg,
+ #notes-new-note-btn svg {
+ transition: transform 0.45s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ #library-new-doc-btn .list-item-plus-label,
+ #notes-new-note-btn .list-item-plus-label {
+ top: calc(50% + 1px);
+ }
+ #library-new-doc-btn:hover svg,
+ #notes-new-note-btn:hover svg {
+ transform: rotate(180deg) scale(1.15);
+ }
+
+
+ /* MD toolbar attach button — matches other toolbar buttons */
+ .md-toolbar-attach-btn {
+ background: none; border: none; color: var(--fg); opacity: 0.35;
+ padding: 4px 7px; cursor: pointer; min-height: 28px;
+ display: inline-flex; align-items: center; justify-content: center;
+ transition: opacity 0.1s;
+ }
+ .md-toolbar-attach-btn:hover { opacity: 1; }
+
+ /* Email reader icon buttons — vertical icon + label stack. */
+ .memory-toolbar-btn.reader-icon-btn {
+ width: auto;
+ height: 44px;
+ /* padding: 4px 2px; */
+ position: relative;
+ top: 1px;
+ display: inline-flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 3px;
+ flex: 0 0 auto;
+ }
+ .memory-toolbar-btn.reader-icon-btn svg { width: 18px; height: 18px; }
+ .memory-toolbar-btn.reader-icon-btn[data-act="reply"] svg {
+ color: inherit;
+ stroke: currentColor;
+ }
+ .memory-toolbar-btn.reader-icon-btn.active {
+ background: color-mix(in srgb, var(--accent, var(--red)) 16%, transparent);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 40%, transparent);
+ color: var(--accent, var(--red));
+ }
+ .memory-toolbar-btn.reader-icon-btn[data-act="more"] {
+ color: inherit;
+ }
+ .memory-toolbar-btn.reader-icon-btn[data-act="more"] svg { fill: currentColor; }
+ .memory-toolbar-btn.reader-icon-btn.reader-more-active {
+ background: color-mix(in srgb, var(--fg) 12%, transparent);
+ border-color: color-mix(in srgb, var(--fg) 24%, transparent);
+ color: inherit;
+ }
+ /* Cookbook Serve dropdown triggers (the cached-model kebab + the saved-config
+ arrow) — accent-colored to signal they open a menu, with a filled tint when
+ their dropdown is open. Matches the email reader More button pattern. */
+ .hwfit-cached-menu-btn,
+ .cookbook-saved-arrow {
+ color: var(--accent, var(--red));
+ /* Base .memory-item-btn is flex with align-items but no justify-content,
+ so the kebab SVG sat left-aligned inside the button instead of being
+ horizontally centered. Pin it center. */
+ justify-content: center;
+ }
+ .hwfit-cached-menu-btn.cookbook-menu-active,
+ .cookbook-saved-arrow.cookbook-menu-active {
+ background: color-mix(in srgb, var(--accent, var(--red)) 18%, transparent);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 45%, transparent);
+ color: var(--accent, var(--red));
+ }
+
+ /* Card action menus share one hit target and baseline. Keep this late in the
+ cascade because modal buttons and Cookbook Serve add their own offsets. */
+ .memory-item-actions > .memory-item-btn,
+ .memory-item-actions .hwfit-cached-menu-btn {
+ box-sizing: border-box;
+ width: 28px;
+ min-width: 28px;
+ height: 22px;
+ min-height: 22px;
+ margin: 0 !important;
+ padding: 0;
+ border: 1px solid transparent;
+ border-radius: 6px;
+ color: var(--color-muted);
+ font-size: 11px;
+ display: inline-flex;
+ align-items: center;
+ align-self: center;
+ justify-content: center;
+ position: relative;
+ top: 0 !important;
+ transform: none !important;
+ line-height: 1;
+ transition: background 0.15s, border-color 0.15s, color 0.15s, opacity 0.15s;
+ }
+ .memory-item-actions .hwfit-cached-menu-btn:hover {
+ opacity: 1 !important;
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ border-color: color-mix(in srgb, var(--fg) 24%, transparent);
+ color: var(--fg);
+ }
+ .memory-item-actions .hwfit-cached-menu-btn {
+ transform: translateY(2px) !important;
+ }
+
+ @media (min-width: 769px) {
+ .task-card .memory-item-actions {
+ top: 6px;
+ }
+ .task-card .memory-item-actions > .memory-item-btn {
+ transform: none !important;
+ }
+ }
+
+ /* All kebab menus use the same muted tone as the expand/collapse chevron. */
+ :is(
+ .memory-menu-btn,
+ .memory-item-actions .memory-item-btn:not(.save):not(.pin):not(.delete):not(.doclib-card-action-btn),
+ .hwfit-cached-menu-btn,
+ .cookbook-task-menu-btn,
+ .skill-kebab-btn,
+ .archive-menu-btn,
+ .doc-tab-menu-btn,
+ .email-menu-btn
+ ) {
+ color: var(--color-muted, var(--fg)) !important;
+ }
+ :is(
+ .memory-menu-btn,
+ .memory-item-actions .memory-item-btn:not(.save):not(.pin):not(.delete):not(.doclib-card-action-btn),
+ .hwfit-cached-menu-btn,
+ .cookbook-task-menu-btn,
+ .skill-kebab-btn,
+ .archive-menu-btn,
+ .doc-tab-menu-btn,
+ .email-menu-btn
+ ) svg {
+ color: inherit;
+ fill: currentColor;
+ }
+ /* Card kebabs are lightweight menu affordances, not bordered buttons. The
+ old base hover rule gave only some library cards a boxed outline while
+ chats, tasks, and cookbook stayed borderless. */
+ :is(
+ .memory-menu-btn,
+ .memory-item-actions .memory-item-btn:not(.save):not(.pin):not(.delete):not(.doclib-card-action-btn),
+ .hwfit-cached-menu-btn,
+ .cookbook-task-menu-btn,
+ .skill-kebab-btn,
+ .archive-menu-btn,
+ .doc-tab-menu-btn,
+ .email-menu-btn
+ ):hover {
+ background: none !important;
+ border-color: transparent !important;
+ color: var(--fg) !important;
+ opacity: 1;
+ }
+ /* Skills used a separate, larger kebab with a different hover treatment.
+ Match every other card action trigger. */
+ .skill-kebab-btn {
+ box-sizing: border-box;
+ width: 28px;
+ min-width: 28px;
+ height: 22px;
+ min-height: 22px;
+ padding: 0;
+ border: 1px solid transparent;
+ border-radius: 6px;
+ color: var(--color-muted) !important;
+ opacity: 0.55;
+ top: -2px;
+ }
+ @media (max-width: 768px) {
+ .memory-item-actions > .memory-item-btn,
+ .memory-item-actions .hwfit-cached-menu-btn {
+ width: 40px;
+ min-width: 40px;
+ height: 40px;
+ min-height: 40px;
+ }
+ /* Card menus all need the same comfortable tap target. These components
+ previously escaped the shared action-button sizing through more-specific
+ desktop selectors. */
+ .memory-menu-btn,
+ .skill-kebab-btn,
+ .task-card .memory-item-actions .memory-item-btn {
+ width: 40px !important;
+ min-width: 40px !important;
+ height: 40px !important;
+ min-height: 40px !important;
+ }
+ .memory-menu-btn { opacity: 0.7; }
+ /* Document cards seat their actions on a slightly higher title baseline
+ than chats/research cards. Bring only that kebab down 4px. */
+ #doclib-modal .doclib-card[data-doc-id] > .doclib-document-header .memory-item-actions .memory-item-btn {
+ transform: translateY(-2px) !important;
+ }
+ }
+ /* Mobile: center the kebab/menu dropdowns in the viewport so they don't
+ slide left/right as the window width changes (they were positioned via
+ inline `right: ...px` relative to the kebab button). Stable position is
+ easier to land on by touch. The inline `top:` set by the menu code is
+ preserved; we only override the horizontal axis. */
+ @media (max-width: 768px) {
+ .email-card-dropdown,
+ .cookbook-saved-menu,
+ .cookbook-dep-menu {
+ left: 50% !important;
+ right: auto !important;
+ transform: translateX(-50%);
+ }
+ }
+ /* Mobile-only Cancel item appended to dropdowns (kebab/More menus). On
+ desktop outside-click closes them cleanly; on touch that's fiddly, so
+ give an explicit Cancel row. Visually separated from the action items
+ above by a top divider + slight muted color. */
+ .dropdown-cancel-mobile { display: none; }
+ @media (max-width: 768px) {
+ .dropdown-cancel-mobile {
+ display: flex;
+ border-top: 1px solid var(--border);
+ margin-top: 4px;
+ padding-top: 8px;
+ opacity: 0.85;
+ }
+ }
+ /* Launch-command Copy button morphs into Cancel once Launch has been clicked. */
+ .hwfit-serve-copy.hwfit-serve-cancel {
+ border-color: var(--color-danger, #e06c75) !important;
+ color: var(--color-danger, #e06c75) !important;
+ }
+ .hwfit-serve-copy.hwfit-serve-cancel:hover {
+ background: color-mix(in srgb, var(--color-danger, #e06c75) 14%, transparent);
+ }
+
+ /* One visual contract for card kebab menus. These menus are built by several
+ modules, and native button defaults previously made identical rows render
+ with different fonts, heights, and hover movement. */
+ :is(
+ .session-dropdown-menu,
+ .email-card-dropdown,
+ .memory-item-dropdown,
+ .task-dropdown,
+ .skill-kebab-menu,
+ .doclib-card-dropdown,
+ .gallery-detail-menu
+ ) {
+ box-sizing: border-box;
+ padding: 4px !important;
+ color: var(--fg);
+ background: var(--panel, var(--bg)) !important;
+ border: 1px solid var(--border) !important;
+ border-radius: 8px !important;
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3) !important;
+ font-family: inherit !important;
+ font-size: 11px !important;
+ line-height: 1.2;
+ }
+ :is(
+ .session-dropdown-menu,
+ .email-card-dropdown,
+ .memory-item-dropdown,
+ .task-dropdown,
+ .skill-kebab-menu,
+ .doclib-card-dropdown,
+ .gallery-detail-menu
+ ) > .dropdown-item-compact {
+ box-sizing: border-box;
+ width: 100%;
+ min-height: 28px;
+ padding: 6px 8px;
+ gap: 10px;
+ border: 0;
+ border-radius: 6px;
+ color: var(--fg);
+ background: transparent;
+ font: inherit !important;
+ line-height: 1.2;
+ text-align: left;
+ white-space: nowrap;
+ }
+ :is(
+ .session-dropdown-menu,
+ .email-card-dropdown,
+ .memory-item-dropdown,
+ .task-dropdown,
+ .skill-kebab-menu,
+ .doclib-card-dropdown,
+ .gallery-detail-menu
+ ) > .dropdown-item-compact:hover:not(:disabled) {
+ color: var(--fg);
+ background: color-mix(in srgb, var(--accent, var(--red)) 10%, transparent);
+ transform: none;
+ }
+ @media (max-width: 768px) {
+ :is(
+ .session-dropdown-menu,
+ .email-card-dropdown,
+ .memory-item-dropdown,
+ .task-dropdown,
+ .skill-kebab-menu,
+ .doclib-card-dropdown,
+ .gallery-detail-menu
+ ) > .dropdown-item-compact {
+ min-height: 44px;
+ padding: 12px !important;
+ gap: 10px !important;
+ font-size: 14px !important;
+ }
+ }
+ /* Email modal title unread badge — small accent pill next to "Email". */
+ .email-lib-unread-badge {
+ display: inline-block;
+ font-size: 0.55em;
+ font-weight: 700;
+ background: var(--accent-primary, var(--red));
+ color: var(--bg, #1a1a1a);
+ border-radius: 9px;
+ padding: 1px 7px;
+ margin-left: 8px;
+ vertical-align: 2px;
+ line-height: 1.3;
+ letter-spacing: 0.02em;
+ cursor: pointer;
+ }
+ .email-lib-unread-badge.email-lib-away-badge {
+ background: color-mix(in srgb, var(--accent, var(--red)) 18%, transparent);
+ color: var(--accent, var(--red));
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 42%, transparent);
+ padding: 0 7px;
+ }
+ .email-lib-auto-reply-badge {
+ display: inline-block;
+ margin-left: 7px;
+ padding: 1px 7px;
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 48%, var(--border));
+ border-radius: 9px;
+ background: color-mix(in srgb, var(--accent, var(--red)) 15%, transparent);
+ color: var(--accent, var(--red));
+ font-size: 0.55em;
+ font-weight: 700;
+ line-height: 1.3;
+ letter-spacing: 0.01em;
+ vertical-align: 2px;
+ cursor: pointer;
+ }
+ .email-lib-auto-reply-status-dot {
+ width: 6px;
+ height: 6px;
+ margin-left: 6px;
+ border-radius: 50%;
+ background: var(--accent, var(--red));
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent, var(--red)) 18%, transparent),
+ 0 0 8px color-mix(in srgb, var(--accent, var(--red)) 72%, transparent);
+ vertical-align: 2px;
+ }
+ .modal-header h4 > .email-lib-auto-reply-badge {
+ font-size: 0.65em;
+ white-space: nowrap;
+ vertical-align: 1px;
+ }
+ #email-lib-modal.email-lib-unread-active .doclib-modal-content {
+ box-shadow:
+ 0 0 0 1px color-mix(in srgb, var(--accent, var(--red)) 22%, transparent),
+ 0 0 18px color-mix(in srgb, var(--accent, var(--red)) 18%, transparent),
+ var(--shadow-lg, 0 18px 50px rgba(0, 0, 0, 0.35));
+ }
+ #email-lib-modal .email-lib-header-actions .minimize-btn {
+ position: relative;
+ left: 6px;
+ }
+ /* Per-card prev/next nav — only visible on the currently expanded card,
+ sits at the right of the title row next to the done check. */
+ .email-card-nav-arrows {
+ display: none;
+ margin-left: auto;
+ gap: 2px;
+ flex-shrink: 0;
+ align-items: center;
+ position: relative;
+ top: -3px;
+ left: 19px;
+ }
+ .doclib-card.email-card-expanded .email-card-nav-arrows {
+ display: inline-flex;
+ }
+ .email-card-header-menu {
+ display: none;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ width: 28px;
+ height: 28px;
+ padding: 0;
+ border: none;
+ border-radius: 6px;
+ background: none;
+ color: var(--fg);
+ opacity: 0.65;
+ cursor: pointer;
+ position: relative;
+ top: -3px;
+ transition: opacity 0.12s, background 0.12s;
+ }
+ .doclib-card.email-card-expanded .email-card-header-menu {
+ display: inline-flex;
+ }
+ .email-card-header-menu:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
+ .email-card-nav-btn {
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.65;
+ cursor: pointer;
+ padding: 6px 8px;
+ border-radius: 6px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ transition: opacity 0.12s, background 0.12s;
+ }
+ .email-card-nav-btn:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
+
+ /* ── Email document editor ── */
+ .doc-email-header {
+ display: flex; flex-direction: column; gap: 6px; padding: 10px 12px;
+ border-bottom: 1px solid var(--border); background: var(--bg); flex-shrink: 0;
+ }
+ .doc-email-fields {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ min-height: 0;
+ }
+ .doc-email-collapse-btn {
+ width: 100%;
+ min-height: 24px;
+ display: none;
+ align-items: center;
+ gap: 7px;
+ padding: 2px 4px 3px;
+ border: none;
+ background: transparent;
+ color: var(--fg);
+ font: inherit;
+ font-size: 11px;
+ cursor: pointer;
+ opacity: 0.72;
+ text-align: left;
+ }
+ .doc-email-collapse-btn:hover { opacity: 1; color: var(--accent, var(--red)); }
+ .doc-email-collapse-btn svg {
+ flex-shrink: 0;
+ opacity: 0.65;
+ transition: transform 0.14s ease;
+ }
+ .doc-email-collapse-summary {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ opacity: 0.74;
+ }
+ .doc-email-header.doc-email-header-collapsed .doc-email-collapse-btn svg {
+ transform: rotate(180deg);
+ }
+ .email-field { display: flex; align-items: center; gap: 8px; position: relative; }
+ .email-field label { font-size: 11px; font-weight: 600; color: var(--fg); opacity: 0.5; min-width: 50px; text-align: right; flex-shrink: 0; }
+ .email-field input {
+ flex: 1; width: 100%; background: transparent; border: 1px solid var(--border); border-radius: 4px;
+ padding: 5px 8px; font-size: 13px; font-family: inherit; color: var(--fg); outline: none;
+ min-width: 0;
+ }
+ .email-field input:focus { border-color: var(--accent, #4a9eff); }
+ @container docpane (max-width: 460px) {
+ .doc-email-header .email-field {
+ display: grid;
+ grid-template-columns: 1fr;
+ gap: 3px;
+ align-items: stretch;
+ }
+ .doc-email-header .email-field label {
+ min-width: 0;
+ text-align: left;
+ }
+ .doc-email-header .email-field input {
+ width: 100%;
+ }
+ }
+ /* Cc toggle and attach button are absolute so they don't steal width
+ from the To input. Anchored to the input's vertical center + 4px
+ nudge so the label sits where the user expects it. */
+ .email-field .email-cc-toggle {
+ position: absolute; right: 6px; top: calc(50% + 1px); transform: translateY(-50%);
+ z-index: 2;
+ }
+ /* Accent-tinted prefix label (To / Cc / Bcc / Subject) sitting at
+ the left edge of each input. Replaces both the old <label> tag
+ and the all-placeholder accent. */
+ .email-field .email-field-prefix {
+ position: absolute;
+ left: 10px;
+ top: 50%;
+ transform: translateY(-50%);
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--accent-primary, var(--red));
+ pointer-events: none;
+ z-index: 1;
+ line-height: 1;
+ }
+ .email-field input { padding-left: 44px; }
+ .email-field #doc-email-subject { padding-left: 64px; }
+ /* X close button inside Cc / Bcc fields. */
+ .email-field .email-cc-close {
+ position: absolute; right: 6px; top: calc(50% + 1px); transform: translateY(-50%);
+ background: none; border: none; color: var(--fg);
+ opacity: 0.4; cursor: pointer;
+ width: 22px; height: 22px;
+ display: inline-flex; align-items: center; justify-content: center;
+ border-radius: 4px;
+ padding: 0;
+ z-index: 2;
+ }
+ .email-field .email-cc-close:hover {
+ opacity: 1;
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, currentColor 10%, transparent);
+ }
+ .email-field input { padding-right: 60px; }
+ .email-field #doc-email-cc, .email-field #doc-email-bcc { padding-right: 32px; }
+ .email-field #doc-email-subject { padding-right: 8px; }
+
+ .doc-email-actions {
+ display: flex; gap: 8px; justify-content: flex-end; padding: 10px 14px;
+ border-top: 1px solid var(--border); background: var(--bg); flex-shrink: 0;
+ align-items: center;
+ position: relative;
+ z-index: 30;
+ pointer-events: auto;
+ }
+ #doc-actions-footer .email-send-split {
+ margin-left: auto;
+ }
+ .doc-save-state-icon { display: none; flex: 0 0 auto; }
+ .doc-save-button[data-save-state="dirty"] { color: var(--accent, var(--red)); }
+ .doc-save-button[data-save-state="saving"] { color: var(--fg-muted, var(--fg)); }
+ .doc-save-button[data-save-state="saved"] { color: var(--fg); }
+ .doc-save-button[data-save-state="error"] { color: var(--color-danger, #e06c75); }
+ .doc-stats-wrap {
+ position: relative;
+ margin-left: 0;
+ flex: 0 0 auto;
+ }
+ .doc-stats-btn {
+ height: 28px;
+ border: 0;
+ border-radius: 4px;
+ padding: 0 7px;
+ background: transparent;
+ color: var(--fg-muted, var(--fg));
+ font: inherit;
+ font-size: 10px;
+ cursor: pointer;
+ white-space: nowrap;
+ }
+ .doc-stats-btn:hover,
+ .doc-stats-btn[aria-expanded="true"] {
+ color: var(--fg);
+ background: color-mix(in srgb, var(--fg) 7%, transparent);
+ }
+ .doc-stats-btn.doc-stats-selected {
+ color: var(--accent, var(--red));
+ font-weight: 600;
+ }
+ .doc-stats-popover {
+ position: fixed;
+ right: auto;
+ bottom: auto;
+ width: 190px;
+ padding: 8px 10px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--panel, var(--bg));
+ box-shadow: 0 8px 22px rgba(0, 0, 0, 0.24);
+ color: var(--fg);
+ font-size: 11px;
+ }
+ .doc-stats-scope {
+ padding-bottom: 6px;
+ margin-bottom: 5px;
+ border-bottom: 1px solid var(--border);
+ color: var(--fg-muted, var(--fg));
+ font-size: 10px;
+ font-weight: 600;
+ text-transform: uppercase;
+ }
+ .doc-stats-row {
+ min-height: 22px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 14px;
+ }
+ /* WYSIWYG email body — what the recipient sees, edited in place. */
+ .doc-email-richbody {
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+ padding: 12px 16px;
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
+ font-size: 14px;
+ line-height: 1.6;
+ color: var(--fg);
+ background: var(--bg);
+ outline: none;
+ white-space: pre-wrap;
+ text-align: left;
+ word-wrap: break-word;
+ }
+ .doc-email-richbody.richtext-mode {
+ background: var(--bg);
+ }
+ .doc-rich-empty-import {
+ position: absolute;
+ top: 90px;
+ right: 18px;
+ bottom: auto;
+ left: auto;
+ z-index: 2;
+ display: flex;
+ pointer-events: none;
+ }
+ .doc-rich-empty-import .doc-rich-empty-import-btn {
+ position: static;
+ float: none;
+ margin: 0;
+ opacity: 1;
+ pointer-events: auto;
+ transform: none;
+ }
+ .doc-email-richbody.richtext-mode ul.rich-checklist {
+ list-style: none;
+ padding-left: 1.8em;
+ }
+ .doc-email-richbody.richtext-mode ul.rich-checklist > li {
+ position: relative;
+ min-height: 1.6em;
+ }
+ .doc-email-richbody.richtext-mode ul.rich-checklist > li::before {
+ content: "";
+ position: absolute;
+ left: -1.55em;
+ top: 0.3em;
+ width: 0.95em;
+ height: 0.95em;
+ box-sizing: border-box;
+ border: 1.5px solid color-mix(in srgb, var(--fg) 48%, transparent);
+ border-radius: 3px;
+ background: var(--sidebar-bg, var(--panel));
+ cursor: pointer;
+ }
+ .doc-email-richbody.richtext-mode ul.rich-checklist > li[data-checked="true"]::before {
+ border-color: var(--accent, var(--red));
+ background: var(--accent, var(--red));
+ }
+ .doc-email-richbody.richtext-mode ul.rich-checklist > li[data-checked="true"]::after {
+ content: "";
+ position: absolute;
+ left: -1.27em;
+ top: 0.44em;
+ width: 0.28em;
+ height: 0.5em;
+ border: solid #fff;
+ border-width: 0 1.5px 1.5px 0;
+ transform: rotate(45deg);
+ pointer-events: none;
+ }
+ .doc-email-richbody.richtext-mode ul.rich-checklist > li[data-checked="true"] {
+ color: color-mix(in srgb, var(--fg) 62%, transparent);
+ text-decoration: line-through;
+ }
+ .doc-email-richbody.richtext-mode hr {
+ border: 0;
+ border-top: 1px solid var(--border);
+ margin: 1.25em 0;
+ }
+ .doc-email-richbody.richtext-mode hr.richtext-page-break {
+ height: 8px;
+ border-top: 1px dashed color-mix(in srgb, var(--fg) 42%, transparent);
+ border-bottom: 1px dashed color-mix(in srgb, var(--fg) 42%, transparent);
+ margin: 1.6em 0;
+ opacity: 0.8;
+ }
+ .doc-email-richbody.richtext-mode table {
+ width: 100%;
+ margin: 12px 0;
+ border-collapse: collapse;
+ table-layout: fixed;
+ }
+ .doc-email-richbody.richtext-mode th,
+ .doc-email-richbody.richtext-mode td {
+ min-width: 48px;
+ padding: 7px 8px;
+ border: 1px solid var(--border);
+ vertical-align: top;
+ overflow-wrap: anywhere;
+ }
+ .doc-email-richbody.richtext-mode th {
+ background: color-mix(in srgb, var(--sidebar-bg, var(--panel)) 85%, var(--fg) 15%);
+ font-weight: 600;
+ }
+ .doc-email-richbody.richtext-mode code,
+ .doc-email-richbody.richtext-mode span[style*="OdysseusInlineCode"] {
+ padding: 0.12em 0.35em;
+ border: 1px solid color-mix(in srgb, var(--border) 80%, transparent);
+ border-radius: 3px;
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+ font-size: 0.9em;
+ white-space: break-spaces;
+ }
+ .doc-email-richbody.richtext-mode pre {
+ margin: 1em 0;
+ padding: 12px 14px;
+ overflow-x: auto;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--sidebar-bg, var(--panel)) 82%, #000 18%) !important;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+ font-size: 0.9em;
+ line-height: 1.5;
+ white-space: pre-wrap;
+ tab-size: 2;
+ }
+
+ ::highlight(doc-find-results) {
+ color: inherit;
+ background-color: color-mix(in srgb, #facc15 48%, transparent);
+ }
+
+ ::highlight(doc-find-current) {
+ color: inherit;
+ background-color: color-mix(in srgb, var(--accent, #ef4444) 68%, #facc15);
+ }
+
+ ::highlight(doc-ai-selections) {
+ color: inherit;
+ background-color: color-mix(in srgb, var(--accent, #ef4444) 30%, transparent);
+ }
+ .doc-email-richbody img.richtext-image {
+ display: block;
+ margin: 12px 0;
+ max-width: 100%;
+ height: auto;
+ border-radius: 4px;
+ cursor: pointer;
+ }
+ .doc-email-richbody figure.richtext-image {
+ margin: 12px 0;
+ max-width: 100%;
+ }
+ .doc-email-richbody figure.richtext-image:not(:has(img)) { display: none; }
+ .doc-email-richbody figure.richtext-image img.richtext-image {
+ display: block;
+ margin-top: 0;
+ margin-bottom: 0;
+ max-width: 100%;
+ height: auto;
+ border-radius: 4px;
+ }
+ .doc-email-richbody figure.richtext-image:has(img.richtext-image-size-60) .richtext-image-caption { width: 60%; }
+ .doc-email-richbody figure.richtext-image:has(img.richtext-image-size-35) .richtext-image-caption { width: 35%; }
+ .doc-email-richbody figure.richtext-image:has(img.richtext-image-align-left) .richtext-image-caption { margin-left: 0; margin-right: auto; }
+ .doc-email-richbody figure.richtext-image:has(img.richtext-image-align-center) .richtext-image-caption { margin-left: auto; margin-right: auto; }
+ .doc-email-richbody figure.richtext-image:has(img.richtext-image-align-right) .richtext-image-caption { margin-left: auto; margin-right: 0; }
+ .doc-email-richbody img.richtext-image-size-100 { width: 100%; }
+ .doc-email-richbody img.richtext-image-size-60 { width: 60%; }
+ .doc-email-richbody img.richtext-image-size-35 { width: 35%; }
+ .doc-email-richbody img.richtext-image-align-left { margin-left: 0; margin-right: auto; }
+ .doc-email-richbody img.richtext-image-align-center { margin-left: auto; margin-right: auto; }
+ .doc-email-richbody img.richtext-image-align-right { margin-left: auto; margin-right: 0; }
+ .doc-email-richbody img.richtext-image[data-editor-image-selected] {
+ outline: 2px solid var(--accent, var(--red));
+ outline-offset: 3px;
+ }
+ .doc-rich-image-toolbar {
+ position: fixed;
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ padding: 2px;
+ border: 1px solid var(--border);
+ border-radius: 5px;
+ background: var(--bg);
+ color: var(--fg);
+ box-shadow: 0 3px 12px color-mix(in srgb, var(--fg) 18%, transparent);
+ z-index: 10032;
+ }
+ .doc-rich-image-toolbar button {
+ width: 24px;
+ height: 24px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0;
+ border: 0;
+ border-radius: 3px;
+ background: transparent;
+ color: inherit;
+ cursor: pointer;
+ }
+ .doc-rich-image-toolbar button:hover {
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ color: var(--accent, var(--red));
+ }
+ .doc-rich-image-toolbar .doc-rich-image-remove:hover {
+ color: var(--accent, var(--red));
+ }
+ .doc-rich-image-source-menu {
+ position: fixed;
+ width: 260px;
+ min-width: 260px;
+ padding: 5px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--bg);
+ color: var(--fg);
+ box-shadow: 0 4px 16px color-mix(in srgb, var(--fg) 20%, transparent);
+ z-index: 10033;
+ font-size: 11px;
+ }
+ .doc-rich-image-source-title {
+ padding: 5px 7px 4px;
+ color: var(--fg);
+ font-weight: 700;
+ opacity: .75;
+ }
+ .doc-rich-image-source-menu > button,
+ .doc-rich-gallery-item {
+ width: 100%;
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding: 7px 8px;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ color: var(--fg);
+ font: inherit;
+ text-align: left;
+ cursor: pointer;
+ }
+ .doc-rich-image-source-menu > button[data-image-source="computer"] {
+ padding-left: 9px;
+ }
+ .doc-rich-image-source-menu > button:hover,
+ .doc-rich-gallery-item:hover {
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ color: var(--accent, var(--red));
+ }
+ .doc-rich-gallery-list {
+ display: grid;
+ gap: 2px;
+ max-height: 300px;
+ overflow-y: auto;
+ }
+ .doc-rich-gallery-item {
+ min-height: 44px;
+ min-width: 0;
+ }
+ .doc-rich-gallery-item > span:last-child {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .doc-rich-gallery-thumb {
+ width: 40px;
+ height: 40px;
+ flex: 0 0 40px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background-position: center;
+ background-size: cover;
+ background-repeat: no-repeat;
+ }
+ .rich-color-letter {
+ border-bottom: 2px solid var(--accent, var(--red));
+ font-weight: 700;
+ line-height: 14px;
+ }
+ .rich-color-swatch {
+ width: 13px !important;
+ height: 13px !important;
+ border: 1px solid color-mix(in srgb, var(--fg) 35%, transparent);
+ border-radius: 50%;
+ }
+ .rich-highlight-swatch { border-radius: 50%; }
+ .rich-color-swatch.is-transparent {
+ background:
+ linear-gradient(135deg, transparent 43%, var(--red) 44%, var(--red) 56%, transparent 57%),
+ var(--bg);
+ }
+ .rich-color-palette-menu {
+ min-width: min(292px, calc(100vw - 16px));
+ }
+ .rich-color-palette-menu .rich-color-reset {
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
+ margin-bottom: 3px;
+ padding-bottom: 7px;
+ }
+ .rich-color-palette-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(126px, 1fr));
+ gap: 0 4px;
+ padding: 0 4px;
+ }
+ .rich-color-palette-group {
+ min-width: 0;
+ }
+ .rich-color-palette-label {
+ padding: 4px 8px 3px;
+ color: color-mix(in srgb, var(--fg) 58%, transparent);
+ font-size: 9px;
+ font-weight: 600;
+ text-transform: uppercase;
+ }
+ .rich-color-palette-group .doc-overflow-item {
+ min-width: 0;
+ padding-inline: 8px;
+ }
+ .rich-toolbar-color-custom {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin-top: 3px;
+ padding: 7px 9px 4px 10px;
+ border-top: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
+ color: var(--fg);
+ font-size: 11px;
+ }
+ .rich-toolbar-color-input.cp-swatch-input {
+ width: 22px;
+ height: 22px;
+ flex: 0 0 22px;
+ padding: 0;
+ border: 1px solid color-mix(in srgb, var(--fg) 28%, var(--border));
+ border-radius: 50%;
+ cursor: pointer;
+ }
+ .rich-toolbar-color-input.cp-swatch-input:focus-visible {
+ outline: 2px solid var(--accent, var(--red));
+ outline-offset: 2px;
+ }
+
+ .rich-toolbar-slider-row {
+ display: grid;
+ grid-template-columns: auto minmax(104px, 1fr) 42px;
+ align-items: center;
+ gap: 9px;
+ min-width: 220px;
+ padding: 10px;
+ color: var(--fg);
+ font-size: 11px;
+ }
+ .rich-toolbar-range {
+ width: 100%;
+ min-width: 0;
+ height: 8px;
+ margin: 0;
+ border: 0;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--fg) 25%, transparent);
+ accent-color: var(--red);
+ cursor: pointer;
+ -webkit-appearance: none;
+ appearance: none;
+ }
+ .rich-toolbar-range::-webkit-slider-thumb {
+ width: 9px;
+ height: 9px;
+ border: 0;
+ border-radius: 50%;
+ background: var(--red);
+ cursor: pointer;
+ -webkit-appearance: none;
+ appearance: none;
+ transition: width 0.12s ease, height 0.12s ease;
+ }
+ .rich-toolbar-range:hover::-webkit-slider-thumb,
+ .rich-toolbar-range:focus::-webkit-slider-thumb,
+ .rich-toolbar-range:active::-webkit-slider-thumb {
+ width: 16px;
+ height: 16px;
+ }
+ .rich-toolbar-range::-moz-range-thumb {
+ width: 9px;
+ height: 9px;
+ border: 0;
+ border-radius: 50%;
+ background: var(--red);
+ cursor: pointer;
+ transition: width 0.12s ease, height 0.12s ease;
+ }
+ .rich-toolbar-range:hover::-moz-range-thumb,
+ .rich-toolbar-range:focus::-moz-range-thumb,
+ .rich-toolbar-range:active::-moz-range-thumb {
+ width: 16px;
+ height: 16px;
+ }
+ .rich-toolbar-range:focus-visible {
+ outline: 2px solid var(--accent, var(--red));
+ outline-offset: 4px;
+ }
+ .rich-toolbar-slider-value {
+ width: 42px;
+ box-sizing: border-box;
+ padding: 2px 3px;
+ border: 1px solid transparent;
+ border-radius: 3px;
+ background: transparent;
+ text-align: right;
+ color: color-mix(in srgb, var(--fg) 68%, transparent);
+ font-variant-numeric: tabular-nums;
+ -webkit-appearance: textfield;
+ appearance: textfield;
+ }
+ .rich-toolbar-slider-value::-webkit-inner-spin-button {
+ -webkit-appearance: none;
+ margin: 0;
+ }
+ .rich-toolbar-slider-value:focus {
+ border-color: var(--accent, var(--red));
+ outline: none;
+ color: var(--fg);
+ }
+
+ .rich-script-icon,
+ .rich-font-icon,
+ .rich-font-size-icon {
+ display: inline-block;
+ line-height: 1;
+ font-size: 11px;
+ }
+ .rich-highlight-icon {
+ display: block;
+ flex-shrink: 0;
+ color: var(--accent-primary, var(--red));
+ }
+
+ .rich-script-icon sup,
+ .rich-script-icon sub {
+ font-size: 7px;
+ line-height: 0;
+ }
+
+ .rich-font-icon {
+ font-family: Georgia, serif;
+ font-size: 12px;
+ }
+
+ .rich-font-size-icon {
+ min-width: 16px;
+ font-size: 10px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ text-align: center;
+ }
+ .rich-align-center { text-align: center; }
+ .rich-align-right { text-align: right; }
+ .doc-email-richbody .email-quoted-history {
+ margin-top: 14px;
+ padding: 10px 0 10px 12px;
+ border-left: 3px solid var(--border);
+ color: color-mix(in srgb, var(--fg) 70%, transparent);
+ font-size: 0.92em;
+ line-height: 1.45;
+ white-space: pre-wrap;
+ user-select: text;
+ pointer-events: none;
+ }
+ .doc-email-richbody h1, .doc-email-richbody h2, .doc-email-richbody h3,
+ .doc-email-richbody h4, .doc-email-richbody h5, .doc-email-richbody h6 { margin: 0.4em 0; }
+ .email-more-menu {
+ position: absolute; bottom: 100%; right: 0; margin-bottom: 6px;
+ min-width: 160px; background: var(--bg); border: 1px solid var(--border);
+ border-radius: 6px; box-shadow: 0 -4px 12px rgba(0,0,0,0.2); padding: 4px;
+ z-index: 100;
+ }
+ .email-send-btn {
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 20%, transparent);
+ color: var(--accent-primary, var(--red));
+ border: 1px solid color-mix(in srgb, var(--accent-primary, var(--red)) 50%, transparent);
+ border-radius: 6px;
+ padding: 0 14px; height: 28px; font-size: 11px; font-weight: 600; cursor: pointer;
+ font-family: inherit; transition: all 0.15s; white-space: nowrap;
+ display: inline-flex; align-items: center; gap: 6px;
+ }
+ /* Split send button: [ Send │ ▾ ] — the caret drops the send-options menu UP. */
+ .email-send-split { position: relative; display: inline-flex; }
+ .email-send-split .email-send-main {
+ border-top-right-radius: 0; border-bottom-right-radius: 0; border-right: none;
+ }
+ .email-send-split .email-send-caret {
+ border-top-left-radius: 0; border-bottom-left-radius: 0;
+ padding: 0 8px; gap: 0;
+ /* its left border is the single divider between the two halves */
+ border-left: 1px solid color-mix(in srgb, var(--accent-primary, var(--red)) 50%, transparent);
+ }
+ .email-send-split .email-send-caret svg { transition: transform 0.15s ease; }
+ .email-send-split .email-send-caret[aria-expanded="true"] svg { transform: none; }
+ .email-send-btn svg { flex-shrink: 0; }
+ .email-send-btn:hover {
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 30%, transparent);
+ border-color: var(--accent-primary, var(--red));
+ }
+ .email-draft-btn {
+ background: none; border: 1px solid var(--border);
+ color: color-mix(in srgb, var(--fg) 60%, transparent);
+ border-radius: 6px;
+ padding: 0 12px; height: 28px; font-size: 11px; cursor: pointer;
+ font-family: inherit; transition: all 0.15s; white-space: nowrap;
+ }
+ .email-draft-btn:hover { border-color: var(--fg); color: var(--fg); }
+ .email-discard-btn {
+ background: transparent;
+ /* Dim the label text via color-mix instead of `opacity:0.6` on the whole
+ button — opacity multiplies through to the SVG and washes out the accent
+ X glyph. Per-element color dimming keeps the X at full accent strength. */
+ color: color-mix(in srgb, var(--fg) 60%, transparent);
+ border: 1px solid var(--border); border-radius: 6px;
+ padding: 6px 14px; font-size: 12px; cursor: pointer; font-family: inherit;
+ }
+ /* The ✕ glyph itself reads in accent. */
+ .email-discard-btn svg { color: var(--accent-primary, var(--red)); opacity: 1; }
+ .email-discard-btn:hover { opacity: 1; color: var(--red, #e55); border-color: var(--red, #e55); }
+
+ /* Compose email "more" menu button — icon only, matches draft btn height */
+ #doc-email-more-btn {
+ background: none; border: 1px solid var(--border);
+ color: color-mix(in srgb, var(--fg) 60%, transparent);
+ border-radius: 6px;
+ width: 28px; height: 28px; padding: 0;
+ cursor: pointer; font-family: inherit; transition: all 0.15s;
+ display: inline-flex; align-items: center; justify-content: center;
+ }
+ #doc-email-more-btn:hover {
+ border-color: var(--fg); color: var(--fg);
+ }
+ .email-more-wrap { display: inline-flex; }
+ .email-attachments {
+ display: flex; flex-wrap: wrap; gap: 6px; padding: 4px 0 0 58px;
+ }
+ .email-attachment-chip {
+ display: inline-flex; align-items: center; gap: 4px;
+ padding: 4px 8px; font-size: 11px; background: var(--hover-bg, rgba(255,255,255,0.05));
+ border: 1px solid var(--border); border-radius: 12px; color: var(--fg);
+ text-decoration: none; cursor: pointer; transition: background 0.15s, border-color 0.15s;
+ max-width: 200px; min-width: 0;
+ }
+ .email-attachment-chip:hover {
+ background: color-mix(in srgb, var(--accent) 15%, transparent);
+ border-color: var(--accent);
+ }
+ .email-attachment-chip.is-expanded {
+ max-width: 90vw;
+ }
+ .email-attachment-chip > span:not(.att-size):not(.email-attachment-open):not(.email-attachment-download):not(.email-attachment-calendar-open) {
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ flex: 1 1 auto; min-width: 0;
+ }
+ .email-attachment-chip.is-expanded > span:not(.att-size):not(.email-attachment-open):not(.email-attachment-download):not(.email-attachment-calendar-open) {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .email-attachment-chip-related {
+ border-color: color-mix(in srgb, var(--accent) 30%, var(--border));
+ }
+ /* "Open in editor" launch icon — same prominent style on desktop AND mobile
+ (was 24px / dim / no border on desktop, easy to miss). Accent-tinted
+ background + border makes it read as a real action. */
+ .email-attachment-open,
+ .email-attachment-download,
+ .email-attachment-calendar-open,
+ .cal-event-email-source {
+ display: inline-flex; align-items: center; gap: 4px;
+ height: 22px; padding: 0 9px; border-radius: 999px;
+ margin-left: 6px; flex: 0 0 auto;
+ min-width: 52px; justify-content: center;
+ font-size: 10px; font-weight: 500; letter-spacing: 0.02em;
+ color: var(--accent-primary, var(--red));
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 10%, transparent);
+ border: 1px solid color-mix(in srgb, var(--accent-primary, var(--red)) 40%, transparent);
+ cursor: pointer; transition: background 0.1s, border-color 0.1s, color 0.1s;
+ }
+ .email-attachment-open {
+ width: 24px;
+ min-width: 24px;
+ padding: 0;
+ margin-left: 4px;
+ }
+ .email-attachment-open svg,
+ .email-attachment-open > svg,
+ .email-attachment-download svg,
+ .email-attachment-download > svg,
+ .email-attachment-calendar-open svg,
+ .email-attachment-calendar-open > svg,
+ .cal-event-email-source svg,
+ .cal-event-email-source > svg {
+ width: 12px; height: 12px;
+ opacity: 0.9;
+ }
+ .email-attachment-open:hover,
+ .email-attachment-download:hover,
+ .email-attachment-calendar-open:hover,
+ .cal-event-email-source:hover {
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 22%, transparent);
+ border-color: color-mix(in srgb, var(--accent-primary, var(--red)) 70%, transparent);
+ }
+ .email-attachment-download {
+ width: 24px;
+ min-width: 24px;
+ padding: 0;
+ margin-left: 4px;
+ }
+ .email-attachment-calendar-open {
+ width: 24px;
+ min-width: 24px;
+ padding: 0;
+ margin-left: 4px;
+ }
+ .cal-event-email-source {
+ width: 24px;
+ min-width: 24px;
+ padding: 0;
+ margin-left: 4px;
+ }
+ .email-attachment-open-label { line-height: 1; }
+ .email-attachment-chip.is-expanded .email-attachment-open,
+ .email-attachment-chip.is-expanded .email-attachment-download,
+ .email-attachment-chip.is-expanded .email-attachment-calendar-open {
+ width: 24px;
+ min-width: 24px;
+ padding: 0;
+ margin-left: 4px;
+ }
+ .email-attachment-chip.is-expanded .email-attachment-open-label {
+ display: none;
+ }
+ @media (max-width: 768px) {
+ .doc-email-collapse-btn {
+ background: inherit;
+ }
+ /* Mobile: keep the pill but ensure a comfortable touch target. */
+ .email-attachment-open {
+ height: 26px; padding: 0 10px;
+ min-height: 26px !important;
+ min-width: 58px;
+ }
+ .email-attachments,
+ .email-compose-atts {
+ flex-wrap: nowrap;
+ overflow-x: auto;
+ overflow-y: hidden;
+ -webkit-overflow-scrolling: touch;
+ scrollbar-width: none;
+ padding-left: 0;
+ padding-bottom: 2px;
+ }
+ .email-attachments::-webkit-scrollbar,
+ .email-compose-atts::-webkit-scrollbar {
+ display: none;
+ }
+ /* Attachment chip body — modest minimum height so the open icon sits
+ neatly without dominating. */
+ .email-attachment-chip,
+ .email-compose-chip {
+ flex: 0 0 auto;
+ padding: 6px 8px !important;
+ min-height: 36px !important;
+ }
+ .email-attachment-chip.is-expanded {
+ flex-wrap: nowrap;
+ align-items: center;
+ max-width: min(92vw, 360px);
+ }
+ .email-attachment-chip.is-expanded > span:not(.att-size):not(.email-attachment-open):not(.email-attachment-download):not(.email-attachment-calendar-open) {
+ flex: 1 1 auto;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ line-height: 1.25;
+ min-width: 0;
+ }
+ .email-attachment-chip.is-expanded .att-size {
+ margin-left: 0;
+ }
+ .email-attachment-chip.is-expanded .email-attachment-open,
+ .email-attachment-chip.is-expanded .email-attachment-download,
+ .email-attachment-chip.is-expanded .email-attachment-calendar-open {
+ width: 28px;
+ min-width: 28px;
+ padding: 0;
+ margin-left: 4px;
+ }
+ .email-compose-chip .compose-chip-name {
+ max-width: 190px;
+ }
+ }
+
+ /* Compose attachment chips (when sending new email) */
+ .email-compose-atts {
+ display: flex; flex-direction: row; flex-wrap: wrap; align-items: center; gap: 6px;
+ padding: 6px 0 0 0;
+ }
+ .email-compose-chip {
+ display: inline-flex; align-items: center; gap: 4px;
+ flex: 0 1 auto;
+ min-width: 0;
+ max-width: min(240px, 100%);
+ height: 24px; min-height: 24px; box-sizing: border-box;
+ padding: 2px 3px 2px 7px; font-size: 11px;
+ background: var(--hover-bg, rgba(255,255,255,0.05));
+ border: 1px solid var(--border); border-radius: 12px; color: var(--fg);
+ }
+ .email-compose-chip .compose-chip-name { max-width: 180px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .email-compose-chip .compose-chip-remove {
+ background: none; border: none; color: var(--fg); opacity: 0.5;
+ height: 18px; font-size: 14px; line-height: 18px; padding: 0 3px; cursor: pointer;
+ flex-shrink: 0;
+ }
+ .email-compose-chip .compose-chip-remove:hover { opacity: 1; color: var(--red, #e55); }
+
+ .pdf-annotation-line-value {
+ width: 48px;
+ height: 22px;
+ box-sizing: border-box;
+ padding: 0 5px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ outline: none;
+ background: var(--bg-elev, var(--panel));
+ color: var(--fg);
+ font-family: inherit;
+ font-size: 10px;
+ font-weight: 500;
+ line-height: 1;
+ text-align: right;
+ }
+ .pdf-annotation-line-value:hover { border-color: color-mix(in srgb, var(--fg) 38%, var(--border)); }
+ .pdf-annotation-line-value:focus { border-color: var(--accent, var(--red)); }
+
+ .email-odysseus-attach-menu {
+ position: fixed;
+ z-index: 10050;
+ width: 300px;
+ max-width: calc(100vw - 16px);
+ max-height: min(420px, calc(100vh - 16px));
+ padding: 7px;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ background: var(--bg);
+ color: var(--fg);
+ box-shadow: 0 12px 30px rgba(0,0,0,0.28);
+ overflow: hidden;
+ }
+ .email-odysseus-attach-local {
+ width: 100%;
+ height: 30px;
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding: 0 9px;
+ border: 1px solid color-mix(in srgb, var(--accent-primary, var(--red)) 35%, var(--border));
+ border-radius: 5px;
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 9%, transparent);
+ color: var(--fg);
+ font: inherit;
+ font-size: 11px;
+ cursor: pointer;
+ }
+ .email-odysseus-attach-local:hover {
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 16%, transparent);
+ border-color: color-mix(in srgb, var(--accent-primary, var(--red)) 55%, var(--border));
+ }
+ .email-odysseus-attach-tabs {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 5px;
+ margin: 7px 0;
+ }
+ .email-odysseus-attach-tabs button {
+ height: 26px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ border: 1px solid var(--border);
+ border-radius: 5px;
+ background: transparent;
+ color: var(--fg);
+ opacity: 0.72;
+ font: inherit;
+ font-size: 11px;
+ cursor: pointer;
+ }
+ .email-odysseus-attach-tabs button.active {
+ opacity: 1;
+ color: var(--accent-primary, var(--red));
+ border-color: color-mix(in srgb, var(--accent-primary, var(--red)) 45%, var(--border));
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 8%, transparent);
+ }
+ .email-odysseus-attach-tabs button svg {
+ flex-shrink: 0;
+ }
+ .email-odysseus-attach-search-wrap {
+ height: 28px;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin: -1px 0 7px;
+ padding: 0 8px;
+ border: 1px solid var(--border);
+ border-radius: 5px;
+ background: color-mix(in srgb, var(--fg) 3%, transparent);
+ color: color-mix(in srgb, var(--fg) 48%, transparent);
+ }
+ .email-odysseus-attach-search-wrap:focus-within {
+ border-color: color-mix(in srgb, var(--accent-primary, var(--red)) 45%, var(--border));
+ color: var(--accent-primary, var(--red));
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 6%, transparent);
+ }
+ .email-odysseus-attach-search {
+ min-width: 0;
+ flex: 1;
+ border: 0;
+ outline: 0;
+ background: transparent;
+ color: var(--fg);
+ font: inherit;
+ font-size: 11px;
+ }
+ .email-odysseus-attach-search::placeholder {
+ color: color-mix(in srgb, var(--fg) 38%, transparent);
+ }
+ .email-odysseus-attach-list {
+ max-height: 320px;
+ overflow: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .email-odysseus-attach-row {
+ width: 100%;
+ min-height: 38px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 7px;
+ border: 1px solid transparent;
+ border-radius: 5px;
+ background: transparent;
+ color: var(--fg);
+ text-align: left;
+ font: inherit;
+ cursor: pointer;
+ }
+ .email-odysseus-attach-row:hover {
+ background: var(--hover-bg, rgba(255,255,255,0.06));
+ border-color: var(--border);
+ }
+ .email-odysseus-attach-row.is-selected {
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 10%, transparent);
+ border-color: color-mix(in srgb, var(--accent-primary, var(--red)) 45%, var(--border));
+ }
+ .email-odysseus-attach-dot {
+ width: 8px;
+ height: 8px;
+ flex: 0 0 auto;
+ display: inline-block;
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ background: color-mix(in srgb, var(--fg) 4%, transparent);
+ }
+ .email-odysseus-attach-row.is-selected .email-odysseus-attach-dot {
+ border-color: var(--accent-primary, var(--red));
+ background: var(--accent-primary, var(--red));
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--accent-primary, var(--red)) 18%, transparent);
+ }
+ .email-odysseus-attach-icon,
+ .email-odysseus-attach-thumb {
+ width: 28px;
+ height: 28px;
+ flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--fg) 7%, transparent);
+ overflow: hidden;
+ }
+ .email-odysseus-attach-main {
+ min-width: 0;
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+ .email-odysseus-attach-title,
+ .email-odysseus-attach-meta {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .email-odysseus-attach-title {
+ font-size: 11px;
+ line-height: 1.2;
+ }
+ .email-odysseus-attach-meta {
+ font-size: 10px;
+ line-height: 1.15;
+ opacity: 0.52;
+ }
+ .email-odysseus-attach-empty {
+ padding: 14px 8px;
+ color: var(--muted, #888);
+ font-size: 11px;
+ text-align: center;
+ }
+ .email-odysseus-attach-actions {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-top: 2px;
+ padding-top: 5px;
+ border-top: 1px solid color-mix(in srgb, var(--border) 75%, transparent);
+ background: var(--bg);
+ position: sticky;
+ bottom: 0;
+ }
+ .email-odysseus-attach-count {
+ flex: 1;
+ min-width: 0;
+ color: var(--muted, #888);
+ font-size: 11px;
+ }
+ .email-odysseus-attach-selected {
+ height: 28px;
+ min-width: 72px;
+ padding: 0 12px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ border-radius: 999px;
+ border: 1px solid color-mix(in srgb, var(--accent-primary, var(--red)) 45%, var(--border));
+ background: var(--accent-primary, var(--red));
+ color: #fff;
+ font: inherit;
+ font-size: 11px;
+ cursor: pointer;
+ }
+ .email-odysseus-attach-selected svg {
+ flex-shrink: 0;
+ }
+
+ .email-cc-toggle {
+ background: none; border: none; color: var(--fg);
+ opacity: 0.4; font-size: 11px; cursor: pointer;
+ padding: 4px 8px; font-family: inherit;
+ }
+ .email-cc-toggle:hover {
+ opacity: 1;
+ color: var(--accent, #4a9eff);
+ background: none !important;
+ }
+
+ @media (max-width: 768px) {
+ .doc-email-collapse-btn {
+ display: flex;
+ }
+ }
+
+ .email-autocomplete {
+ position: absolute; top: 100%; left: 58px; right: 0; z-index: 1000;
+ background: var(--bg); border: 1px solid var(--border); border-radius: 6px;
+ box-shadow: 0 4px 12px rgba(0,0,0,0.2); max-height: 240px; overflow-y: auto;
+ margin-top: 2px;
+ }
+ .contact-suggestion {
+ display: flex; justify-content: space-between; gap: 8px;
+ padding: 6px 10px; font-size: 12px; cursor: pointer;
+ border-bottom: 1px solid var(--border);
+ }
+ .contact-suggestion:last-child { border-bottom: none; }
+ .contact-suggestion:hover,
+ .contact-suggestion.active,
+ .contact-suggestion[aria-selected="true"] {
+ background: color-mix(in srgb, var(--accent-primary, var(--accent, var(--red))) 15%, transparent);
+ outline: 1px solid color-mix(in srgb, var(--accent-primary, var(--accent, var(--red))) 40%, transparent);
+ outline-offset: -1px;
+ }
+ .contact-suggestion .contact-name { font-weight: 600; color: var(--fg); }
+ .contact-suggestion .contact-email { opacity: 0.6; font-size: 11px; }
+ .contact-suggestion-status {
+ padding: 7px 10px;
+ color: color-mix(in srgb, var(--fg) 65%, transparent);
+ font-size: 11px;
+ cursor: default;
+ }
+ .contact-suggestion-status.is-loading { opacity: 0.72; }
+ .contact-suggestion-status.is-unavailable {
+ color: color-mix(in srgb, var(--red) 82%, var(--fg));
+ }
+ .email-ai-reply-btn {
+ background: none;
+ color: color-mix(in srgb, var(--fg) 60%, transparent);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 0 12px; height: 28px; font-size: 11px; cursor: pointer;
+ font-family: inherit; transition: all 0.15s;
+ display: inline-flex; align-items: center; white-space: nowrap;
+ }
+ .email-ai-reply-btn:hover {
+ border-color: var(--accent, #4a9eff);
+ color: var(--accent, #4a9eff);
+ }
+ /* Align select/new buttons in popup library toolbar */
+ #email-lib-select-btn, #email-lib-refresh-btn, #email-lib-settings-btn, #email-lib-compose-btn { position: relative; top: -4px; }
+ /* Select + Refresh sit slightly lower than Compose on desktop. */
+ #email-lib-select-btn, #email-lib-refresh-btn, #email-lib-settings-btn { top: -2px; }
+
+ #email-lib-modal.email-settings-mode .email-accounts-row,
+ #email-lib-modal.email-settings-mode .admin-card > .memory-toolbar,
+ #email-lib-modal.email-settings-mode #email-lib-bulk,
+ #email-lib-modal.email-settings-mode #email-lib-grid,
+ #email-lib-modal.email-settings-mode #email-lib-sync-status,
+ #email-lib-modal.email-settings-mode #email-lib-fab {
+ display: none !important;
+ }
+ #email-lib-settings-page[hidden] {
+ display: none !important;
+ }
+ #email-lib-modal.email-settings-mode #email-lib-settings-page {
+ display: flex;
+ }
+ .email-settings-page {
+ display: flex;
+ flex: 1;
+ min-height: 0;
+ min-width: 0;
+ flex-direction: column;
+ gap: 6px;
+ overflow: hidden;
+ padding: 2px 0 8px;
+ width: 100%;
+ box-sizing: border-box;
+ -webkit-overflow-scrolling: touch;
+ }
+ .settings-email-preferences-card {
+ display: contents;
+ }
+ .settings-email-preferences-card .email-settings-section {
+ margin: 0 0 10px;
+ padding: 14px 12px 12px;
+ background: var(--panel);
+ }
+ .settings-email-preferences-card .email-settings-section:last-child {
+ margin-bottom: 0;
+ }
+ .settings-email-preferences-card .email-settings-style-section {
+ margin-bottom: 4px;
+ }
+ .settings-email-default-card #settings-email-default-host {
+ display: flex;
+ justify-content: flex-end;
+ min-width: 0;
+ margin-left: auto;
+ }
+ .settings-email-default-card .settings-email-default-title {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ }
+ .settings-email-default-card .settings-email-default-title > span {
+ min-width: 0;
+ }
+ .settings-email-default-card .settings-email-default-title > span > svg {
+ color: var(--accent, var(--red));
+ }
+ .settings-email-default-card .email-settings-account-picker {
+ margin-left: 0 !important;
+ }
+ .settings-email-default-card .email-settings-support-copy {
+ position: relative;
+ top: 6px;
+ }
+ .settings-email-default-spacer {
+ height: 12px;
+ }
+ .settings-email-default-card .cookbook-srv-default-label {
+ position: relative;
+ top: 2px;
+ }
+ .settings-email-default-card .cookbook-srv-default-icon > svg {
+ position: relative;
+ top: 7px;
+ }
+ .settings-email-settings-legacy {
+ display: none;
+ }
+
+ /* Keep the standalone Email Settings cards aligned with the expandable
+ preference cards below them. */
+ [data-settings-panel="email"] > .admin-card {
+ padding-top: 14px;
+ }
+ .email-settings-page-host {
+ display: flex;
+ flex: 0 0 auto;
+ min-height: 0;
+ padding: 0;
+ overflow: visible;
+ }
+ .settings-email-preferences-card > .email-settings-page-host { width: 100%; }
+ .email-settings-page-head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ min-height: 32px;
+ padding-bottom: 2px;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
+ }
+ .email-settings-account-picker {
+ min-width: 0;
+ max-width: 100%;
+ }
+ .email-settings-account-picker select {
+ min-width: 0;
+ max-width: 100%;
+ }
+ .email-settings-back {
+ position: relative;
+ top: -2px;
+ }
+ .email-settings-header-back {
+ background: transparent;
+ color: color-mix(in srgb, var(--fg) 58%, transparent);
+ border: 1px solid transparent;
+ width: auto;
+ height: 24px;
+ padding: 0 8px 0 6px;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ cursor: pointer;
+ border-radius: 999px;
+ flex-shrink: 0;
+ position: relative;
+ font-size: 11px;
+ font-weight: 600;
+ line-height: 1;
+ }
+ .email-settings-header-back:hover {
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ border-color: color-mix(in srgb, var(--fg) 12%, transparent);
+ color: var(--fg);
+ }
+ .email-settings-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ margin-bottom: 8px;
+ }
+ .email-settings-title {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ flex: 1 1 auto;
+ width: 100%;
+ min-width: 0;
+ font-size: 12px;
+ font-weight: 700;
+ }
+ .email-settings-title svg {
+ color: var(--accent, var(--red));
+ flex-shrink: 0;
+ }
+ .email-settings-close {
+ width: 24px;
+ height: 24px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: transparent;
+ color: color-mix(in srgb, var(--fg) 70%, transparent);
+ cursor: pointer;
+ font-size: 14px;
+ line-height: 1;
+ }
+ .email-settings-close:hover {
+ color: var(--fg);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 45%, var(--border));
+ }
+ .email-settings-body {
+ display: flex;
+ flex-direction: column;
+ flex: 1 1 auto;
+ gap: 6px;
+ padding-top: 4px;
+ box-sizing: border-box;
+ min-width: 0;
+ min-height: 0;
+ overflow-y: auto;
+ overflow-x: hidden;
+ overscroll-behavior: contain;
+ }
+ .email-settings-loading,
+ .email-settings-error {
+ font-size: 12px;
+ color: color-mix(in srgb, var(--fg) 65%, transparent);
+ padding: 8px 2px;
+ }
+ .email-settings-loading {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ }
+ .email-settings-loading-css-whirlpool {
+ display: inline-block;
+ width: 14px;
+ height: 14px;
+ box-sizing: border-box;
+ border: 1.5px solid color-mix(in srgb, var(--accent, var(--red)) 28%, transparent);
+ border-top-color: var(--accent, var(--red));
+ border-right-color: color-mix(in srgb, var(--accent, var(--red)) 72%, transparent);
+ border-radius: 50%;
+ animation: whirlpool-spin 0.72s linear infinite;
+ flex: 0 0 auto;
+ }
+ .email-settings-loading-spinner {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 16px;
+ height: 16px;
+ color: var(--accent, var(--red));
+ }
+ .email-settings-section {
+ display: flex;
+ flex-direction: column;
+ flex: 0 0 auto;
+ gap: 7px;
+ margin: 0;
+ padding: 14px 8px 8px;
+ min-width: 0;
+ box-sizing: border-box;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--fg) 3%, transparent);
+ transition: opacity 0.15s ease, background 0.15s ease;
+ }
+ .email-settings-section.is-disabled {
+ opacity: 0.58;
+ background: color-mix(in srgb, var(--fg) 2%, transparent);
+ }
+ .email-settings-section-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ }
+ .email-settings-section-head > div:first-child {
+ min-width: 0;
+ flex: 1 1 auto;
+ }
+ .email-settings-section-head > .email-settings-enabled-control,
+ .email-settings-section-head > button {
+ margin-left: auto;
+ }
+ .email-settings-section-toggle {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ width: 100%;
+ min-width: 0;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: inherit;
+ text-align: left;
+ cursor: pointer;
+ }
+ .email-settings-section-toggle:hover,
+ .email-settings-section-toggle:active {
+ background: transparent;
+ }
+ .email-settings-section-toggle-copy {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ min-width: 0;
+ flex: 1 1 auto;
+ }
+ .email-settings-section-toggle > .email-settings-enabled-control {
+ margin-left: auto;
+ flex: 0 0 auto;
+ }
+ .email-settings-section-chevron {
+ flex: 0 0 auto;
+ color: color-mix(in srgb, var(--fg) 62%, transparent);
+ transition: transform .14s ease, color .14s ease;
+ }
+ .email-settings-section-toggle:hover .email-settings-section-chevron,
+ .email-settings-section-toggle:focus-visible .email-settings-section-chevron {
+ color: var(--accent, var(--red));
+ }
+ .email-settings-section-title {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 14px;
+ line-height: 1;
+ font-weight: 600;
+ letter-spacing: 0;
+ margin: 0;
+ padding: 0;
+ }
+ .email-settings-section-title svg {
+ color: var(--accent, var(--red));
+ opacity: 0.6;
+ flex-shrink: 0;
+ }
+ .email-settings-account-scope {
+ margin-left: 4px;
+ font-size: 11px;
+ font-weight: 500;
+ color: color-mix(in srgb, var(--fg) 60%, transparent);
+ }
+ .email-settings-section-body {
+ display: flex;
+ flex-direction: column;
+ gap: 7px;
+ min-width: 0;
+ width: 100%;
+ }
+ .email-settings-section[open] > .email-settings-section-body {
+ min-height: 0;
+ flex: 0 0 auto;
+ height: auto;
+ max-height: none;
+ overflow: visible;
+ overscroll-behavior: contain;
+ padding: 0 4px 4px 0;
+ scrollbar-width: thin;
+ }
+ .email-settings-section[open] {
+ min-height: 0;
+ flex: 0 0 auto;
+ }
+ .email-settings-auto-reply-section[open],
+ .email-settings-cleanup-section[open]:has(.email-unsub-card) {
+ flex: 1 1 auto;
+ display: grid;
+ grid-template-rows: auto minmax(0, 1fr);
+ align-content: stretch;
+ }
+ .email-settings-auto-reply-section[open] > .email-settings-section-body,
+ .email-settings-cleanup-section[open]:has(.email-unsub-card) > .email-settings-section-body {
+ flex: 0 0 auto;
+ height: 100%;
+ max-height: 100%;
+ overflow-y: auto;
+ }
+ .email-settings-section[open] > .email-settings-section-body > * {
+ flex: 0 0 auto;
+ }
+ .email-settings-section-body-head {
+ display: flex;
+ justify-content: flex-end;
+ }
+ .email-settings-display-heading {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ }
+ .email-settings-display-title {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ }
+ .email-settings-display-title > svg {
+ flex: 0 0 auto;
+ color: var(--accent, var(--red));
+ }
+ .email-settings-display-title-row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ width: 100%;
+ position: relative;
+ top: 10px;
+ padding-bottom: 6px;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 40%, transparent);
+ }
+ .email-settings-display-title-row .email-settings-section-title {
+ flex: 1 1 auto;
+ width: auto;
+ padding-bottom: 0;
+ border-bottom: 0;
+ }
+ .email-settings-style-section .email-settings-section-title {
+ display: flex;
+ width: 100%;
+ position: relative;
+ top: 0;
+ padding-bottom: 8px;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 40%, transparent);
+ }
+ .email-settings-style-section .email-settings-section-head,
+ .email-settings-style-section .email-settings-section-body {
+ position: static;
+ }
+ .email-settings-style-section .email-settings-section-head { margin-top: 8px; }
+ .email-settings-style-section .email-settings-section-body { margin-top: 12px; }
+ .email-settings-style-section .email-settings-section-desc {
+ margin-top: 16px;
+ top: 0;
+ }
+ .email-settings-auto-reply-section .email-settings-section-title,
+ .email-settings-cleanup-section .email-settings-section-title {
+ display: flex;
+ width: 100%;
+ padding-bottom: 6px;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 40%, transparent);
+ }
+ .email-settings-cleanup-section .email-settings-section-title {
+ position: relative;
+ top: 10px;
+ }
+ .email-settings-auto-reply-section .email-settings-section-desc,
+ .email-settings-cleanup-section .email-settings-section-desc {
+ margin-top: 10px;
+ }
+ .email-settings-display-section .email-settings-section-desc,
+ .email-settings-cleanup-section .email-settings-section-desc,
+ .email-settings-inline-images-section .email-settings-section-desc {
+ margin-top: 12px;
+ top: 12px;
+ }
+ .email-settings-auto-reply-title-row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ width: 100%;
+ position: relative;
+ top: 10px;
+ padding-bottom: 6px;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 40%, transparent);
+ }
+ .email-settings-auto-reply-section .email-settings-section-head {
+ margin-top: 8px;
+ }
+ .email-settings-auto-reply-section .email-settings-section-body {
+ margin-top: 8px;
+ }
+ .email-settings-auto-reply-section .email-settings-section-desc {
+ margin-top: 12px;
+ top: 0;
+ }
+ .email-settings-display-section .email-settings-section-desc {
+ margin-top: 10px;
+ top: 10px;
+ }
+ .email-settings-auto-reply-section .email-settings-section-body {
+ margin-top: 14px;
+ }
+ .email-settings-auto-reply-title-row .email-settings-section-title {
+ flex: 1 1 auto;
+ width: auto;
+ padding-bottom: 0;
+ border-bottom: 0;
+ }
+ .email-settings-support-copy {
+ color: color-mix(in srgb, var(--fg) 65%, transparent);
+ font-size: 11px;
+ line-height: 1.3;
+ }
+ .email-settings-clean-btn > svg {
+ color: var(--accent, var(--red));
+ }
+ .email-settings-clean-btn {
+ height: 32px;
+ }
+ .email-unsub-rescan-btn {
+ height: 32px;
+ }
+ .email-settings-clean-actions {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ flex-wrap: wrap;
+ gap: 7px;
+ min-width: 0;
+ margin-left: auto;
+ }
+ .email-settings-clean-status {
+ display: none;
+ font-size: 10.5px !important;
+ flex: 0 1 auto;
+ width: auto !important;
+ max-width: min(52vw, 360px);
+ min-width: 0;
+ overflow: hidden;
+ text-align: right;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ position: relative;
+ top: 2px;
+ }
+ .email-settings-clean-status.is-busy {
+ order: 0;
+ align-self: center;
+ width: auto !important;
+ max-width: 100%;
+ margin-right: auto;
+ text-align: left;
+ }
+ .email-settings-clean-btn {
+ flex: 0 0 auto;
+ }
+ .email-settings-default .cookbook-srv-default-icon > svg {
+ position: relative;
+ top: 3px;
+ }
+ .email-unsub-auto-safe-btn > svg {
+ position: relative;
+ top: 2px;
+ }
+ .email-unsub-auto-safe-btn {
+ height: 29px;
+ }
+ .email-unsub-status,
+ .email-unsub-panel-status {
+ position: relative;
+ top: 2px;
+ }
+ .email-unsub-panel-status {
+ flex: 1 1 220px;
+ min-width: 0;
+ margin-right: auto;
+ overflow: hidden;
+ color: color-mix(in srgb, var(--fg) 68%, transparent);
+ font-size: 11px;
+ line-height: 1.3;
+ text-align: left;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .email-unsub-panel-status.is-error {
+ color: var(--red, #e57373);
+ }
+ .email-unsub-card .email-tag {
+ color: var(--accent, var(--red));
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 42%, var(--border));
+ background: color-mix(in srgb, var(--accent, var(--red)) 10%, transparent);
+ }
+ .email-unsub-duplicate-badge {
+ position: relative;
+ top: 2px;
+ }
+ .email-unsub-accent-icon {
+ color: var(--accent, var(--red));
+ flex-shrink: 0;
+ }
+ .email-unsub-card {
+ position: relative;
+ transition: opacity .16s ease;
+ }
+ .email-unsub-card-details {
+ display: flex;
+ flex-direction: column;
+ gap: 7px;
+ }
+ .email-unsub-card-toggle {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex: 0 0 auto;
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: color-mix(in srgb, var(--fg) 62%, transparent);
+ cursor: pointer;
+ }
+ .email-unsub-card-toggle:hover,
+ .email-unsub-card-toggle:focus-visible {
+ color: var(--accent, var(--red));
+ }
+ .email-unsub-card-toggle > svg {
+ transition: transform .14s ease;
+ }
+ .email-unsub-done-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ }
+ .email-unsub-done-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ flex: 0 0 auto;
+ padding: 3px 6px;
+ position: relative;
+ top: -6px;
+ }
+ .email-unsub-card-details .email-unsub-done-btn {
+ top: 0;
+ }
+ .email-unsub-done-btn > svg {
+ color: var(--accent, var(--red));
+ }
+ .email-unsub-ignore-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex: 0 0 auto;
+ width: 22px;
+ height: 22px;
+ padding: 0;
+ position: absolute;
+ top: 5px;
+ right: 6px;
+ color: color-mix(in srgb, var(--fg) 58%, transparent);
+ }
+ .email-unsub-card-details .email-unsub-ignore-btn {
+ position: static;
+ }
+ .email-unsub-ignore-btn:hover {
+ color: var(--accent, var(--red));
+ }
+ .email-unsub-remaining-actions {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ flex-wrap: wrap;
+ }
+ .email-unsub-remaining-actions button {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ position: relative;
+ top: -2px;
+ }
+ .email-unsub-remaining-actions svg {
+ flex: 0 0 auto;
+ }
+ .email-unsub-link-btn {
+ position: relative;
+ top: 2px;
+ }
+ .email-unsub-status.is-error {
+ color: var(--accent, var(--red)) !important;
+ }
+ .email-settings-section-desc {
+ position: relative;
+ top: 8px;
+ margin-top: 4px;
+ font-size: 10.5px;
+ line-height: 1.25;
+ color: color-mix(in srgb, var(--fg) 55%, transparent);
+ }
+ .email-settings-inline-images-section .email-settings-section-desc {
+ margin-bottom: 4px;
+ }
+ .email-settings-inline-images-spacer {
+ height: 12px;
+ }
+ .email-settings-display-spacer {
+ height: 10px;
+ }
+ .email-settings-display-section .email-settings-section-desc {
+ margin-top: 10px;
+ top: 10px;
+ }
+ .email-settings-display-section,
+ .email-settings-inline-images-section {
+ padding-bottom: 18px;
+ }
+ .email-settings-cleanup-section .email-settings-section-desc {
+ margin-top: 14px;
+ top: 14px;
+ }
+ .email-settings-auto-reply-section .email-settings-section-desc {
+ margin-top: 12px;
+ top: 10px;
+ }
+ .email-settings-toggle,
+ .email-settings-check {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 12px;
+ line-height: 1.25;
+ }
+ .email-settings-toggle {
+ flex-shrink: 0;
+ }
+ .email-settings-enabled-control {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ flex-shrink: 0;
+ }
+ .email-settings-enabled-state {
+ font-size: 10px;
+ font-weight: 700;
+ color: color-mix(in srgb, var(--fg) 50%, transparent);
+ }
+ .email-settings-section.is-enabled .email-settings-enabled-state {
+ color: var(--accent, var(--red));
+ }
+ .email-settings-section.is-disabled .email-settings-enabled-state {
+ color: color-mix(in srgb, var(--fg) 50%, transparent);
+ }
+ .email-settings-display-section.is-enabled .email-settings-enabled-state {
+ color: var(--accent, var(--red));
+ }
+ .email-settings-check {
+ min-height: 24px;
+ padding: 3px 0;
+ }
+ .email-settings-check > span:first-child {
+ min-width: 0;
+ margin-right: auto;
+ }
+ .email-settings-check-spacer {
+ flex: 1;
+ }
+ .email-settings-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 7px;
+ min-width: 0;
+ }
+ .email-settings-grid label,
+ .email-settings-field {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ min-width: 0;
+ }
+ .email-settings-grid span,
+ .email-settings-field > span {
+ font-size: 10px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0;
+ color: color-mix(in srgb, var(--fg) 56%, transparent);
+ }
+ .email-settings-page input[type="date"],
+ .email-settings-page input[type="datetime-local"],
+ .email-settings-page select,
+ .email-settings-page textarea {
+ width: 100%;
+ min-width: 0;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--panel, var(--bg));
+ color: var(--fg);
+ font: inherit;
+ font-size: 12px;
+ }
+ .email-settings-page input[type="date"],
+ .email-settings-page input[type="datetime-local"],
+ .email-settings-page select {
+ height: 28px;
+ padding: 0 7px;
+ }
+ .email-settings-page textarea {
+ resize: vertical;
+ min-height: 72px;
+ padding: 7px;
+ line-height: 1.35;
+ }
+ .email-settings-static-value {
+ min-height: 28px;
+ display: flex;
+ align-items: center;
+ padding: 0 7px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--panel, var(--bg)) 74%, transparent);
+ color: color-mix(in srgb, var(--fg) 72%, transparent);
+ font-size: 12px;
+ }
+ .email-settings-actions {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-top: 2px;
+ }
+
+ /* Email Settings actions use the same quiet outlined treatment everywhere:
+ the Settings links, the modal settings page, and unsubscribe actions. */
+ [data-settings-panel="email"] #set-email-open-integrations,
+ [data-settings-panel="email"] #set-email-open-tasks,
+ [data-settings-panel="email"] .email-settings-section button.memory-toolbar-btn,
+ #email-lib-settings-page .email-settings-section button.memory-toolbar-btn {
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ font-family: inherit;
+ font-weight: 400;
+ }
+ [data-settings-panel="email"] #set-email-open-integrations:hover,
+ [data-settings-panel="email"] #set-email-open-tasks:hover,
+ [data-settings-panel="email"] .email-settings-section button.memory-toolbar-btn:hover,
+ #email-lib-settings-page .email-settings-section button.memory-toolbar-btn:hover {
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ border-color: var(--fg);
+ color: var(--fg);
+ }
+ [data-settings-panel="email"] #set-email-open-integrations > svg,
+ [data-settings-panel="email"] #set-email-open-tasks > svg {
+ color: var(--accent, var(--red));
+ opacity: 1 !important;
+ }
+ [data-settings-panel="email"] .email-style-settings-extract,
+ [data-settings-panel="email"] .email-style-settings-save,
+ #email-lib-settings-page .email-style-settings-extract,
+ #email-lib-settings-page .email-style-settings-save {
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ font-weight: 400;
+ }
+ [data-settings-panel="email"] .email-style-settings-extract:hover,
+ [data-settings-panel="email"] .email-style-settings-save:hover,
+ #email-lib-settings-page .email-style-settings-extract:hover,
+ #email-lib-settings-page .email-style-settings-save:hover {
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ border-color: var(--fg);
+ color: var(--fg);
+ }
+ .email-settings-status,
+ .email-style-settings-status {
+ margin-right: auto;
+ font-size: 11px;
+ color: color-mix(in srgb, var(--fg) 62%, transparent);
+ }
+ .email-settings-status.is-success,
+ .email-style-settings-status.is-success {
+ color: var(--color-success, #4caf50);
+ position: relative;
+ top: 2px;
+ }
+ .email-settings-status.is-error,
+ .email-style-settings-status.is-error {
+ color: var(--accent, var(--red));
+ position: relative;
+ top: 2px;
+ }
+ .email-settings-save,
+ .email-style-settings-save {
+ height: 28px;
+ min-width: 64px;
+ justify-content: center;
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ }
+ .email-settings-save {
+ height: 32px;
+ }
+ .email-style-settings-extract {
+ height: 32px;
+ }
+ .email-style-settings-save {
+ height: 32px;
+ }
+ .email-settings-save svg,
+ .email-style-settings-save svg {
+ color: var(--accent, var(--red));
+ flex-shrink: 0;
+ }
+ .email-style-settings-extract svg {
+ color: var(--accent, var(--red));
+ position: relative;
+ top: 2px;
+ }
+ .email-settings-task-setting {
+ color: color-mix(in srgb, var(--fg) 72%, transparent);
+ }
+ .email-settings-inline-link {
+ appearance: none;
+ border: 0;
+ padding: 0;
+ background: transparent;
+ color: var(--accent, var(--red));
+ font: inherit;
+ text-decoration: underline;
+ cursor: pointer;
+ }
+ .email-style-extract-help {
+ width: 18px;
+ height: 18px;
+ min-width: 18px;
+ padding: 0;
+ border-radius: 999px;
+ border: 1px solid color-mix(in srgb, var(--fg) 18%, transparent);
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ color: color-mix(in srgb, var(--fg) 68%, transparent);
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ font: inherit;
+ font-size: 11px;
+ font-weight: 700;
+ line-height: 1;
+ cursor: help;
+ }
+ .email-style-extract-help:hover {
+ color: var(--fg);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 38%, var(--border));
+ background: color-mix(in srgb, var(--accent, var(--red)) 10%, transparent);
+ }
+ @media (max-width: 420px) {
+ .email-settings-grid {
+ grid-template-columns: 1fr;
+ }
+ }
+
+
+ /* ── Notes ── */
+ /* Notes panel — body-level flex sibling of chat-container */
+ body.notes-view .chat-container { flex: 1; min-width: 0; }
+
+ /* Mobile: notes panel takes over full screen */
+ @media (max-width: 768px) {
+ body.notes-view .notes-pane {
+ position: fixed;
+ inset: 0;
+ max-width: 100%;
+ width: 100% !important;
+ /* Desktop sets height: min(80vh, 820px) which wins over inset:0's bottom:0
+ and leaves a gap at the bottom of the viewport. Force full height here. */
+ height: 100dvh !important;
+ max-height: 100dvh !important;
+ z-index: 170;
+ /* Bottom-sheet treatment like the document editor: stroked, rounded top,
+ slides up from the bottom. */
+ border: 1px solid var(--border);
+ border-bottom: none;
+ border-radius: 14px 14px 0 0;
+ /* Pane itself never scrolls — its inner .notes-pane-body is the scroller.
+ Two nested scrollers caused the body's flex:1 to lose its height bound
+ on Firefox mobile and the last row got clipped off-screen. */
+ overflow: hidden;
+ animation: sheet-enter 0.25s cubic-bezier(0.2, 0.8, 0.2, 1) both;
+ transform-origin: bottom center;
+ }
+ /* Required for the flex:1 body to actually constrain to remaining pane
+ height instead of expanding to its content (default min-height:auto on
+ flex items). Without this both grid and list views overflow the viewport
+ bottom on phones. */
+ body.notes-view .notes-pane-body {
+ min-height: 0;
+ -webkit-overflow-scrolling: touch;
+ }
+ body.notes-view #notes-divider {
+ display: none;
+ }
+ body.notes-view .notes-mobile-grabber {
+ display: block;
+ flex-shrink: 0;
+ height: 18px;
+ position: relative;
+ background: var(--bg);
+ touch-action: none;
+ cursor: grab;
+ }
+ body.notes-view .notes-mobile-grabber::before {
+ content: '';
+ position: absolute;
+ top: 7px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 36px;
+ height: 4px;
+ background: var(--fg);
+ opacity: 0.25;
+ border-radius: 2px;
+ }
+ body.notes-view .chat-container {
+ display: none;
+ }
+ body.notes-view .mobile-new-chat-btn,
+ body.notes-view .hamburger-btn {
+ display: none !important;
+ }
+ }
+ /* ── Mobile notes UX ────────────────────────────────────
+ Tiles become read-only previews on touch ≤768px wide.
+ Tap opens a fullscreen overlay where editing happens; long-press
+ toggles drag-to-reorder. Wired up in static/js/notes.js. */
+ body.notes-mobile-mode .note-card-corner,
+ body.notes-mobile-mode .note-card-corner-edit,
+ body.notes-mobile-mode .note-card-corner-archive,
+ body.notes-mobile-mode .note-card-corner-copy,
+ body.notes-mobile-mode .note-card-corner-trash,
+ body.notes-mobile-mode .note-card-corner-unarchive,
+ body.notes-mobile-mode .note-card-corner-done,
+ body.notes-mobile-mode .note-card-edit-corner,
+ body.notes-mobile-mode .note-card-done,
+ body.notes-mobile-mode .note-card-actions,
+ body.notes-mobile-mode .note-cl-quickadd,
+ body.notes-mobile-mode .note-card .note-checkbox-rm,
+ /* Panel-fullscreen toggle is redundant on mobile — the panel always
+ fills the viewport already. */
+ body.notes-mobile-mode #notes-fullscreen-toggle {
+ display: none !important;
+ }
+
+ /* Header toggle icons (archive view, list/grid switch) — defaults are
+ tuned for the dense desktop header; on mobile bump them slightly so
+ they read as tap targets without dominating the header. */
+ body.notes-mobile-mode #notes-archive-toggle,
+ body.notes-mobile-mode #notes-view-toggle {
+ width: 30px;
+ height: 30px;
+ padding: 6px;
+ }
+ body.notes-mobile-mode #notes-archive-toggle svg,
+ body.notes-mobile-mode #notes-view-toggle svg {
+ width: 17px;
+ height: 17px;
+ }
+ /* The whole card is the tap target on mobile — bigger feedback */
+ body.notes-mobile-mode .note-card {
+ cursor: pointer;
+ -webkit-tap-highlight-color: transparent;
+ transition: transform 0.12s ease, box-shadow 0.12s ease;
+ }
+
+ /* Drag-to-reorder mode — desaturate the grid and sweep a subtle
+ shimmer across every tile so it's obvious you're in rearrange mode
+ (the Google Keep "active edit" cue). Also disable scroll inside the
+ panel so the drag works smoothly. */
+ body.notes-drag-mode .notes-pane-body {
+ overflow: hidden;
+ touch-action: none;
+ }
diff --cc static/css/15-notes.css
index 000000000,3c4103273..28b53e920
mode 000000,100644..100644
--- a/static/css/15-notes.css
+++ b/static/css/15-notes.css
@@@ -1,0 -1,4062 +1,4035 @@@
+ /* 15-notes - part of the former static/style.css.
+ *
+ * The stylesheet is split by area, but the split is mechanical: rules were
+ * moved verbatim and NOT regrouped. The numeric prefix is the load order, and
+ * that order is what preserves the cascade. A rule sits in the file its
+ * original position fell into, so an area's rules are not all in its file and
+ * a file is not only that area's rules.
+ *
+ * Do not reorder the <link> tags in static/index.html, and do not move a rule
+ * between files: with 1,151 redeclarations and 1,886 !important in this
+ * cascade, either can change which declaration wins.
+ *
+ * static/index.html and the PRECACHE list in static/sw.js must agree on this
+ * order. tests/test_static_stylesheet_manifest.py and
+ * tests/test_css_computed_style_snapshot.py fail if that drifts.
+ */
+ body.notes-drag-mode .note-card {
+ cursor: grab;
+ transform: scale(0.985);
+ filter: saturate(0.7);
+ opacity: 0.92;
+ position: relative;
+ overflow: hidden;
+ transition: transform 0.22s cubic-bezier(0.2, 0.7, 0.3, 1),
+ filter 0.18s ease,
+ opacity 0.18s ease;
+ }
+ @media (max-width: 768px) {
+ body.notes-drag-mode .note-card {
+ filter: none;
+ opacity: 0.96;
+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent, var(--red)) 28%, transparent);
+ }
+ body.notes-drag-mode .note-card::after {
+ display: none;
+ }
+ }
+ /* Placeholder — same footprint as the lifted card, dotted outline so
+ the drop target is visible while the card follows the finger. */
+ .note-card-placeholder {
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ border: 2px dashed color-mix(in srgb, var(--fg) 25%, transparent);
+ border-radius: 8px;
+ box-sizing: border-box;
+ flex-shrink: 0;
+ transition: width 0.18s ease, height 0.18s ease;
+ }
+
+
+ /* ── Fullscreen single-note edit overlay ──────────────── */
+ .note-fullscreen-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 10500;
+ background: var(--bg);
+ display: flex;
+ flex-direction: column;
+ opacity: 0;
+ /* Bigger zoom range so the transition reads as a real "tile expands
+ into a page" motion. transform-origin is set per-tile by JS. */
+ transform: scale(0.45);
+ transform-origin: center center;
+ transition: opacity 0.28s ease, transform 0.32s cubic-bezier(0.18, 0.74, 0.24, 1.06);
+ will-change: transform, opacity;
+ }
+ .note-fullscreen-overlay.open {
+ opacity: 1;
+ transform: scale(1);
+ }
+ .note-fullscreen-overlay.closing {
+ opacity: 0;
+ transform: scale(0.7);
+ transition: opacity 0.22s ease, transform 0.22s cubic-bezier(0.4, 0, 0.6, 1);
+ }
+ .note-fullscreen-header {
+ flex-shrink: 0;
+ padding: 8px 12px;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ border-bottom: 1px solid var(--border);
+ }
+ .note-fullscreen-actions {
+ margin-left: auto;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ /* Compact the relocated Archive/Delete buttons so two of them fit
+ alongside the back chevron without crowding. */
+ .note-fullscreen-actions .note-form-text-btn {
+ padding: 8px 12px;
+ font-size: 12px;
+ border-radius: 8px;
+ }
+ .note-fullscreen-actions .note-form-text-btn svg {
+ width: 14px;
+ height: 14px;
+ margin-right: 4px;
+ }
+ .note-fullscreen-back {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 40px; height: 40px;
+ background: none;
+ border: none;
+ color: var(--fg);
+ border-radius: 8px;
+ cursor: pointer;
+ -webkit-tap-highlight-color: transparent;
+ }
+ .note-fullscreen-back:active {
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
+ .note-fullscreen-body {
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+ padding: 8px 14px 24px;
+ }
+ /* The reused .note-form inside the fullscreen overlay should breathe —
+ it was originally sized to slot into a grid cell. */
+ .note-fullscreen-body .note-form {
+ max-width: 720px;
+ margin: 0 auto;
+ border: none;
+ box-shadow: none;
+ background: transparent;
+ }
+
+ /* Bigger touch targets inside the fullscreen overlay. The default form
+ is tuned for the grid-card context (tiny icons fit a 200px wide
+ tile); on a phone-sized full-bleed page we want chunky thumb-sized
+ controls. */
+ .note-fullscreen-back svg {
+ width: 28px;
+ height: 28px;
+ }
+ .note-fullscreen-overlay .note-form-type-pill svg {
+ width: 16px;
+ height: 16px;
+ }
+ .note-fullscreen-overlay .note-cl-row {
+ padding: 8px 0;
+ gap: 8px;
+ align-items: center;
+ }
+ .note-fullscreen-overlay .note-cl-grip {
+ font-size: 22px;
+ line-height: 1;
+ padding: 6px 8px;
+ opacity: 0.5;
+ cursor: grab;
+ touch-action: none;
+ user-select: none;
+ /* Pull 4px toward the left edge of the row. */
+ margin-left: -4px;
+ }
+ .note-fullscreen-overlay .note-cl-dot {
+ width: 16px;
+ height: 16px;
+ border-width: 2px;
+ border-radius: 50%;
+ flex-shrink: 0;
+ position: relative;
+ /* Generous invisible tap target around the visible dot */
+ }
+ /* Filled checkmark glyph when the row is marked done — gives a clear
+ visual cue beyond the colored fill. Nudged up 2px so it sits
+ centered in the smaller dot. */
+ .note-fullscreen-overlay .note-cl-row.done .note-cl-dot::after {
+ content: '';
+ position: absolute;
+ left: 2px; top: 1px;
+ width: 8px; height: 4px;
+ border-left: 2px solid #fff;
+ border-bottom: 2px solid #fff;
+ transform: rotate(-45deg);
+ }
+ .note-fullscreen-overlay .note-cl-rm {
+ width: 40px;
+ height: 40px;
+ font-size: 28px;
+ line-height: 1;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0.7;
+ /* Nudge 4px further toward the right edge of the row. */
+ margin-right: -4px;
+ }
+ /* Lifted row + placeholder while dragging a checklist item. Mirrors
+ the card-drag look so the two interactions feel consistent. */
+ .note-cl-row-dragging {
+ box-shadow: 0 12px 28px rgba(0,0,0,0.4);
+ background: var(--bg);
+ border-radius: 8px;
+ opacity: 0.98;
+ }
+ .note-cl-row-placeholder {
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ border: 2px dashed color-mix(in srgb, var(--fg) 22%, transparent);
+ border-radius: 6px;
+ margin: 4px 0;
+ box-sizing: border-box;
+ transition: height 0.16s ease;
+ }
+ .note-fullscreen-overlay .note-form-text-btn {
+ padding: 10px 16px;
+ font-size: 14px;
+ }
+ .note-fullscreen-overlay .note-form-text-btn svg {
+ width: 16px;
+ height: 16px;
+ }
+ /* + Add and the camera/photo button share a row inside checklists, so
+ they're both within thumb reach when editing items. The whole row
+ reads as a single dashed "tap to add" surface — tapping ANYWHERE
+ on it triggers + Add (the photo button stays its own target). */
+ .note-fullscreen-overlay .note-cl-add-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ margin-top: 10px;
+ padding: 4px 8px 4px 4px;
+ border: 1px solid color-mix(in srgb, var(--fg) 22%, transparent);
+ border-radius: 10px;
+ cursor: pointer;
+ transition: background 0.12s ease, border-color 0.12s ease;
+ }
+ .note-fullscreen-overlay .note-cl-add-row:active {
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ border-color: color-mix(in srgb, var(--fg) 36%, transparent);
+ }
+ .note-fullscreen-overlay .note-cl-add-row .note-cl-add {
+ flex: 1;
+ justify-content: flex-start;
+ background: transparent;
+ border: none;
+ }
+ .note-fullscreen-overlay .note-cl-add-row .note-form-photo-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ width: auto;
+ height: 36px;
+ padding: 0 12px 0 10px;
+ border-radius: 8px;
+ /* No border / no background — the surrounding +Add row provides the
+ bordered container, the camera is just an icon inside it. */
+ border: none;
+ background: transparent;
+ }
+
+ /* Read-mode overlay shown over the textarea for plain notes. Renders
+ linkified content so URLs are tappable. Click anywhere off a link
+ to flip to edit mode (focuses the underlying textarea). */
+ .note-form-content-reader {
+ font-size: 15px;
+ line-height: 1.55;
+ padding: 10px 6px;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ color: var(--fg);
+ cursor: text;
+ min-height: 40px;
+ }
+
+ /* Per-row read mode for todo items — replaces the bare <input> with a
+ clickable linkified span when the value contains a URL. */
+ .note-fullscreen-overlay .note-cl-text-reader {
+ flex: 1;
+ padding: 7px 6px;
+ font-size: 14px;
+ line-height: 1.4;
+ min-height: 32px;
+ display: inline-flex;
+ align-items: center;
+ word-break: break-word;
+ color: var(--fg);
+ cursor: text;
+ }
+ .note-fullscreen-overlay .note-cl-row.done .note-cl-text-reader {
+ opacity: 0.5;
+ text-decoration: line-through;
+ }
+ .note-fullscreen-overlay .note-form-icon-btn svg {
+ width: 16px;
+ height: 16px;
+ }
+
+
+ /* Tags input is JS-relocated into the bottom actions row, pinned
+ left of Cancel/Update. Style it as a dashed pill so it reads as
+ metadata rather than another control. */
+ .note-fullscreen-overlay .note-form-actions-group .note-form-label {
+ flex: 1 1 auto;
+ min-width: 0;
+ font-size: 13px;
+ padding: 8px 10px;
+ margin: 0 auto 0 0;
+ background: transparent;
+ border: 1px dashed color-mix(in srgb, var(--fg) 16%, transparent);
+ border-radius: 6px;
+ text-align: left;
+ }
+
+ .note-fullscreen-overlay .note-color-picker { order: 1; }
+ .note-fullscreen-overlay .note-form-type-seg {
+ order: 3;
+ margin-left: auto; /* shove right */
+ /* The overlay enlarges the pills (padding 10px), but the base seg is only
+ 28px tall with overflow:hidden — which clipped them. Grow the track so
+ the bigger touch targets fit. */
+ height: 40px;
+ border-radius: 12px;
+ }
+ .note-fullscreen-overlay .note-form-actions-group {
+ order: 4;
+ width: 100%;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 6px;
+ }
+
+ .notes-mobile-grabber { display: none; }
+ /* Notes panel: mounted like a window, docked to the right on desktop. */
+ .notes-pane-backdrop {
+ position: fixed;
+ inset: 0;
+ z-index: 200;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ backdrop-filter: none;
+ -webkit-backdrop-filter: none;
+ pointer-events: none;
+ animation: notes-backdrop-fade-in 180ms ease both;
+ }
+ .notes-pane-backdrop .notes-pane {
+ pointer-events: auto;
+ }
+ .notes-pane-backdrop:has(.notes-pane.modal-right-docked),
+ .notes-pane-backdrop:has(.notes-pane.modal-left-docked) {
+ background: transparent;
+ backdrop-filter: none;
+ -webkit-backdrop-filter: none;
+ pointer-events: none;
+ }
+ .notes-pane-backdrop:has(.notes-pane.modal-right-docked) .notes-pane,
+ .notes-pane-backdrop:has(.notes-pane.modal-left-docked) .notes-pane {
+ pointer-events: auto;
+ }
+ .notes-pane-backdrop:has(.notes-pane.notes-window-fullscreen) {
+ background: transparent;
+ backdrop-filter: none;
+ -webkit-backdrop-filter: none;
+ }
+ .notes-pane {
+ display: flex;
+ flex-direction: column;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ overflow: hidden;
+ width: min(880px, 92vw);
+ height: min(80vh, 820px);
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.45);
+ box-sizing: border-box;
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+ letter-spacing: -0.015em;
+ /* Smooth open: scale up + fade in from the centre. */
+ animation: notes-pane-enter 200ms cubic-bezier(0.22, 0.61, 0.36, 1) both;
+ transform-origin: center center;
+ will-change: transform, opacity;
+ }
+ .notes-pane.modal-right-docked {
+ border-left: 1px solid var(--border);
+ border-radius: 0;
+ box-shadow: -4px 0 14px rgba(0, 0, 0, 0.18);
+ transition: none !important;
+ }
+ .notes-pane.modal-left-docked {
+ border-right: 1px solid var(--border);
+ border-radius: 0;
+ box-shadow: 4px 0 14px rgba(0, 0, 0, 0.18);
+ transition: none !important;
+ }
+ .notes-pane-header {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ justify-content: space-between;
+ padding: 0 0 6px;
+ margin: 10px 10px 0;
+ border-bottom: 1px solid var(--border);
+ background: inherit;
+ flex-shrink: 0;
+ flex-wrap: nowrap;
+ min-height: 30px;
+ overflow: hidden;
+ }
+
+ /* Archive mode — sepia tint over the panel + a header strip so it's clearly
+ a different view. Active reminders sort + glow rules don't apply here. */
+ .notes-pane-archive {
+ background: color-mix(in srgb, #b48a4a 6%, var(--bg));
+ }
+ .notes-pane-archive .notes-pane-header {
+ background: color-mix(in srgb, #b48a4a 12%, var(--bg));
+ border-bottom-color: color-mix(in srgb, #b48a4a 35%, var(--border));
+ }
+ .notes-pane-archive .notes-pane-body {
+ background: color-mix(in srgb, #b48a4a 4%, var(--bg));
+ }
+ /* Smooth the archive↔active swap so the colour tint eases in/out instead
+ of snapping. Covers the pane, its header, and its body. */
+ .notes-pane,
+ .notes-pane .notes-pane-header,
+ .notes-pane .notes-pane-body {
+ transition: background 0.28s ease, border-color 0.28s ease;
+ }
+ .notes-pane-archive .notes-pane-title::after {
+ content: 'Archive';
+ margin-left: 8px;
+ padding: 2px 8px 2px 22px;
+ font-size: 9px;
+ font-weight: 700;
+ letter-spacing: 1px;
+ text-transform: uppercase;
+ color: #b48a4a;
+ background-color: color-mix(in srgb, #b48a4a 18%, transparent);
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23b48a4a' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='2' y='3' width='20' height='5' rx='1'/%3E%3Cpath d='M4 8v11a2 2 0 002 2h12a2 2 0 002-2V8'/%3E%3Cpath d='M10 12h4'/%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: 6px center;
+ background-size: 11px 11px;
+ border: 1px solid color-mix(in srgb, #b48a4a 45%, transparent);
+ border-radius: 10px;
+ vertical-align: middle;
+ }
+ .notes-pane-archive .note-card {
+ background: color-mix(in srgb, #b48a4a 8%, var(--panel));
+ border-color: color-mix(in srgb, #b48a4a 25%, var(--border));
+ }
+ .notes-pane-header .doc-action-icon-btn {
+ flex-shrink: 0;
+ }
+ .notes-pane-header .notes-pane-title {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ min-width: 0;
+ flex-shrink: 1;
+ }
+ .notes-pane-footer {
+ padding: 6px 8px;
+ border-top: 1px solid var(--border);
+ background: var(--panel);
+ flex-shrink: 0;
+ display: flex;
+ gap: 6px;
+ }
+ .notes-new-btn {
+ background: none;
+ border: 1px dashed color-mix(in srgb, var(--accent) 40%, transparent);
+ color: color-mix(in srgb, var(--fg) 50%, transparent);
+ border-radius: 6px;
+ padding: 6px 0;
+ flex: 1;
+ cursor: pointer;
+ font-size: 11px;
+ font-family: inherit;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ transition: border-color 0.15s, color 0.15s;
+ }
+ .notes-new-btn:hover {
+ border-color: var(--accent);
+ color: var(--fg);
+ }
+ .notes-pane-title {
+ /* Match the other tool headers (.modal-header h4). */
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+ font-size: 1rem;
+ font-weight: 600;
+ letter-spacing: -0.03em;
+ color: var(--red);
+ white-space: nowrap;
+ height: 24px;
+ line-height: 22px;
+ padding: 0 6px;
+ margin: 6px 0 0 0;
+ display: inline-block;
+ vertical-align: middle;
+ /* Optical nudge — sits 1px above its row baseline on desktop, more on mobile
+ where the surrounding controls are taller. Overridden in the mobile
+ media block below. */
+ position: relative;
+ top: -1px;
+ box-sizing: border-box;
+ }
+ @media (max-width: 768px) {
+ .notes-pane-title { top: -4px; }
+ .notes-pane-title svg {
+ position: relative;
+ top: -2px;
+ }
+ /* Mobile header is tight — keep Archive / Toggle View icon-only. */
+ .notes-header-btn-label { display: none; }
+ .notes-header-text-btn { width: 32px !important; padding: 0 !important; }
+ }
+ .notes-header-btn-label {
+ font-size: 11px;
+ font-weight: 500;
+ line-height: 1;
+ letter-spacing: 0.2px;
+ white-space: nowrap;
+ }
+ .notes-header-text-btn {
+ width: auto !important;
+ padding: 0 8px !important;
+ }
+ .notes-pane-body {
+ flex: 1;
+ overflow-y: auto;
+ scroll-behavior: smooth;
+ padding: 10px 8px 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ scrollbar-width: thin;
+ }
+ .notes-pane-body > .doclib-chip-scroll-frame:has(> .notes-labels-bar) {
+ /* The shared Library wrapper grows to fill available flex space. Notes
+ needs this to remain a content-height toolbar or it can create a huge
+ blank gap above the cards after filtering/re-rendering. */
+ flex: 0 0 auto;
+ width: 100%;
+ }
+
+ .note-card.note-card-sliding-out {
+ transform: translateX(120%);
+ opacity: 0;
+ transition: transform 0.32s ease-in, opacity 0.32s ease-in;
+ pointer-events: none;
+ }
+
+ /* ⋯ corner menu button (replaced the copy corner button) */
+ .note-card-corner-menu {
+ background: none;
+ border: none;
+ color: var(--fg);
+ cursor: pointer;
+ padding: 2px;
+ opacity: 0.5;
+ transition: opacity 0.15s;
+ display: inline-flex;
+ }
+ .note-card-corner-menu:hover { opacity: 0.9; }
+ /* Dropdown spawned by the ⋯ menu */
+ .note-corner-menu-dropdown {
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 8px 24px rgba(0,0,0,0.3);
+ padding: 4px;
+ min-width: 168px;
+ font-size: 12px;
+ animation: ncm-pop 0.12s ease-out both;
+ }
+ @keyframes ncm-pop { from { opacity: 0; transform: scale(0.96); } to { opacity: 1; transform: scale(1); } }
+ .note-corner-menu-dropdown .ncm-item {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ width: 100%;
+ background: none;
+ border: none;
+ color: var(--fg);
+ font-family: inherit;
+ font-size: 12px;
+ text-align: left;
+ padding: 8px 10px;
+ border-radius: 6px;
+ cursor: pointer;
+ }
+ .note-corner-menu-dropdown .ncm-item:hover {
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
-.note-checkbox-agent {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 14px;
- height: 14px;
- padding: 0;
- margin: 0 1px;
- border: 0;
- background: transparent;
- color: var(--accent, var(--red));
- box-shadow: none;
- cursor: pointer;
- opacity: 0;
- transition: opacity 0.12s, color 0.12s;
-}
-.note-checkbox-agent:hover {
- background: transparent;
- opacity: 1 !important;
-}
-.note-checkbox-agent.is-agent-stream-complete {
- color: #50fa7b;
- opacity: 0.9;
-}
-.note-checkbox-agent svg {
- display: block;
-}
+
+ .note-card {
+ /* Same tint that .doclib-card uses so a default (uncolored) note
+ visually separates from the panel background it sits on. */
+ background: color-mix(in srgb, var(--fg) 3%, transparent);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ /* Extra right padding so the corner buttons (pin / edit / copy / done)
+ never collide with the title, and a min-height so an empty/short
+ note is still tall enough to fit that row of corner controls. */
+ padding: 10px 14px;
+ padding-right: 30px;
+ min-height: 64px;
+ cursor: default;
+ transition: background 0.15s;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ /* Keep drawings/images clipped to the card so they can't spill outside it —
+ but allow a small overhang (the pin bubble sits at right:-8px and would
+ otherwise be cropped). overflow-clip-margin extends the clip-box without
+ letting full images bleed past. */
+ overflow: clip;
+ overflow-clip-margin: 14px;
+ /* Don't shrink inside the flex-column list pane — otherwise cards squish to
+ fit (clipped/too short) and the container never overflows, so it won't
+ scroll. Keeping natural height makes the list overflow → scrollable. */
+ flex-shrink: 0;
+ }
+ .note-card:hover:not([class*="note-color-"]) {
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ }
+ .note-card { position: relative; }
+ .note-card-image { max-width: 100%; }
+
+ /* Mobile: bigger, more legible note cards + a sticky quick-add bar so you can
+ add a to-do without scrolling back up; and keep media inside the card. */
+ @media (max-width: 768px) {
+ .note-card { padding: 14px 16px; padding-right: 34px; min-height: 84px; font-size: 15px; }
+ .note-card-image { max-height: 260px; max-width: 100%; object-fit: cover; }
+ /* Sticky create-todo bar — pin it to the top of the scrolling list pane.
+ Safe now that the cards no longer shrink (the list actually overflows). */
+ .notes-quick-add {
+ position: sticky;
+ top: -8px;
+ z-index: 12;
+ flex-shrink: 0;
+ margin-top: 0;
+ box-shadow: 0 -8px 0 8px var(--panel), 0 8px 0 0 var(--panel);
+ }
+ }
+ .note-card-pinned {
+ border-top: 2px solid color-mix(in srgb, var(--fg) 30%, transparent);
+ }
+ .note-card.note-card-reminder-fired {
+ animation: note-reminder-pulse 1.2s ease-in-out 2;
+ }
+ /* Sticky outside glow — applied to the exact note whose reminder fired.
+ It stays until the user interacts with that card. */
+ .note-card.note-card-reminder-fired-sticky {
+ position: relative;
+ outline: 1px solid color-mix(in srgb, var(--accent, var(--red)) 36%, transparent);
+ outline-offset: 2px;
+ animation: note-reminder-glow 1.6s ease-in-out infinite;
+ }
+
+ /* Hover-only buttons (Google Keep style) */
+ .note-card-select,
+ .note-card-pin {
+ position: absolute;
+ top: -8px;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ width: 18px;
+ height: 18px;
+ padding: 0;
+ cursor: pointer;
+ display: none;
+ align-items: center;
+ justify-content: center;
+ color: var(--fg);
+ opacity: 0.7;
+ z-index: 2;
+ transition: opacity 0.15s, transform 0.15s, background 0.15s;
+ }
+ /* Pencil + checkmark glyphs both have empty space along the top of their
+ 24×24 viewBox, so flex-centering leaves them sitting visually high.
+ Nudge the inner SVG down a touch to compensate. */
+ .note-card-edit-corner svg,
+ .note-card-done svg {
+ position: relative;
+ top: 0.5px;
+ }
+ .note-card-edit-corner {
+ position: absolute;
+ /* Both Edit + Done at top-right: Edit on the left (right:40px),
+ Done on the right (right:6px). */
+ top: 6px; right: 40px;
+ width: 28px; height: 28px;
+ /* Fully invisible at rest. Materializes (with a solid panel fill blocking
+ any text underneath) only when the card is hovered or the button is
+ focused. Same rule on touch — opacity stays 0 until the card is tapped
+ to expose actions. */
+ background: transparent;
+ border: 1px solid transparent;
+ border-radius: 50%;
+ cursor: pointer; padding: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--fg); opacity: 0;
+ touch-action: manipulation;
+ transition: opacity 0.15s, background 0.15s, border-color 0.15s;
+ z-index: 2;
+ }
+ .note-card:hover .note-card-edit-corner {
+ opacity: 0.85;
+ background: var(--panel);
+ border-color: color-mix(in srgb, var(--fg) 18%, transparent);
+ }
+ .note-card-edit-corner:hover,
+ .note-card-edit-corner:focus-visible {
+ opacity: 1 !important;
+ background: color-mix(in srgb, var(--accent) 18%, var(--panel)) !important;
+ border-color: color-mix(in srgb, var(--accent) 50%, var(--border)) !important;
+ }
+ @media (hover: none) {
+ .note-card-edit-corner {
+ opacity: 0.7;
+ background: var(--panel);
+ border-color: color-mix(in srgb, var(--fg) 18%, transparent);
+ }
+ }
+ /* Copy corner — bottom-right counterpart to the edit/done corner buttons.
+ Round, subtle, hover-reveal on desktop and always faintly visible on
+ touch so mobile users can tap it without needing hover. */
+ .note-card-copy-corner {
+ position: absolute;
+ bottom: 6px;
+ right: 6px;
+ top: auto;
+ width: 26px;
+ height: 26px;
+ background: transparent;
+ border: 1px solid transparent;
+ border-radius: 50%;
+ cursor: pointer;
+ padding: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--fg);
+ opacity: 0;
+ touch-action: manipulation;
+ transition: opacity 0.15s, background 0.15s, border-color 0.15s;
+ z-index: 2;
+ }
+ .note-card:hover .note-card-copy-corner {
+ opacity: 0.7;
+ background: var(--panel);
+ border-color: color-mix(in srgb, var(--fg) 18%, transparent);
+ }
+ .note-card-copy-corner:hover,
+ .note-card-copy-corner:focus-visible {
+ opacity: 1 !important;
+ background: color-mix(in srgb, var(--accent, var(--red)) 18%, var(--panel)) !important;
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 50%, var(--border)) !important;
+ }
+ @media (hover: none) {
+ .note-card-copy-corner {
+ opacity: 0.6;
+ background: var(--panel);
+ border-color: color-mix(in srgb, var(--fg) 18%, transparent);
+ }
+ }
+ /* Unarchive corner reuses the pencil's spot in archive view. */
+ .note-card-unarchive-corner:hover,
+ .note-card-unarchive-corner:focus-visible {
+ background: color-mix(in srgb, var(--accent) 22%, transparent) !important;
+ border-color: color-mix(in srgb, var(--accent) 50%, var(--border)) !important;
+ color: var(--accent);
+ }
+
+ /* "Done" pill in the bottom-right of every active note card. Visible-only on
+ hover (and always on touch) so it's clearly readable but doesn't clutter
+ the grid at rest. Distinct from the edit pencil so it's obvious what it
+ does — green checkmark + label, not just an icon. */
+ /* Matches .note-card-edit-corner footprint (22×22 circle), just anchored
+ to the bottom-right corner instead of top-right. */
+ .note-card-done {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ width: 28px;
+ height: 28px;
+ background: transparent;
+ border: 1px solid transparent;
+ border-radius: 50%;
+ cursor: pointer;
+ padding: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--green, #98c379);
+ opacity: 0;
+ touch-action: manipulation;
+ transition: opacity 0.15s, background 0.15s, border-color 0.15s;
+ z-index: 2;
+ }
+ .note-card:hover .note-card-done {
+ opacity: 0.85;
+ background: var(--panel);
+ border-color: color-mix(in srgb, var(--fg) 18%, transparent);
+ }
+ .note-card-done:hover,
+ .note-card-done:focus-visible {
+ opacity: 1 !important;
+ background: color-mix(in srgb, var(--green, #98c379) 22%, var(--panel)) !important;
+ border-color: color-mix(in srgb, var(--green, #98c379) 50%, var(--border)) !important;
+ }
+ @media (hover: none) {
+ .note-card-done {
+ opacity: 0.7;
+ background: var(--panel);
+ border-color: color-mix(in srgb, var(--fg) 18%, transparent);
+ }
+ }
+
+ /* Copy corner — bottom-right of the card. Same opaque-fill pattern as
+ trash/unarchive so the underlying text/image never bleeds through. */
+ .note-card-corner-copy {
+ position: absolute;
+ bottom: 6px;
+ right: 6px;
+ width: 28px;
+ height: 28px;
+ background: var(--panel);
+ border: 1px solid color-mix(in srgb, var(--fg) 18%, transparent);
+ border-radius: 50%;
+ cursor: pointer;
+ padding: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--fg);
+ visibility: hidden;
+ touch-action: manipulation;
+ transition: background 0.15s, border-color 0.15s, color 0.15s;
+ z-index: 2;
+ }
+ .note-card-corner-copy svg { position: relative; top: 1px; opacity: 0.85; transition: opacity 0.15s; }
+ .note-card-corner-copy:hover,
+ .note-card-corner-copy:focus-visible {
+ background: color-mix(in srgb, var(--accent) 18%, var(--panel));
+ border-color: color-mix(in srgb, var(--accent) 50%, var(--border));
+ color: var(--accent);
+ }
+ .note-card-corner-copy:hover svg { opacity: 1; }
+ @media (hover: none) {
+ .note-card-corner-copy { visibility: visible; }
+ .note-card-corner-copy svg { opacity: 0.7; }
+ }
+
+ /* ── Archive view corners — trash (top-left) + unarchive (top-right) ── */
+ /* Background fill stays fully opaque (var(--panel)) so the note text or
+ image behind doesn't bleed through. Visibility is gated by `visibility`
+ + a faded ICON instead of `opacity` on the whole button. */
+ .note-card-corner-trash,
+ .note-card-corner-unarchive {
+ position: absolute;
+ top: 6px;
+ width: 28px;
+ height: 28px;
+ background: var(--panel);
+ border: 1px solid color-mix(in srgb, var(--fg) 18%, transparent);
+ border-radius: 50%;
+ cursor: pointer;
+ padding: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--fg);
+ visibility: hidden;
+ touch-action: manipulation;
+ transition: background 0.15s, border-color 0.15s, color 0.15s;
+ z-index: 2;
+ }
+ .note-card-corner-trash svg,
+ .note-card-corner-unarchive svg { opacity: 0.85; transition: opacity 0.15s; }
+ .note-card-corner-trash:hover,
+ .note-card-corner-trash:focus-visible {
+ background: color-mix(in srgb, var(--red) 18%, var(--panel));
+ border-color: color-mix(in srgb, var(--red) 50%, var(--border));
+ color: var(--red);
+ }
+ .note-card-corner-trash:hover svg,
+ .note-card-corner-unarchive:hover svg { opacity: 1; }
+ .note-card-corner-unarchive:hover,
+ .note-card-corner-unarchive:focus-visible {
+ background: color-mix(in srgb, var(--accent) 18%, var(--panel));
+ border-color: color-mix(in srgb, var(--accent) 50%, var(--border));
+ color: var(--accent);
+ }
+ @media (hover: none) {
+ .note-card-corner-trash,
+ .note-card-corner-unarchive { visibility: visible; }
+ .note-card-corner-trash svg,
+ .note-card-corner-unarchive svg { opacity: 0.7; }
+ }
+
+ /* ─── Auto-AI ✨ chip on note cards ─────────────────────────────────── */
+ .note-card-ai-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ margin-left: 6px;
+ padding: 2px 8px;
+ border-radius: 999px;
+ font-size: 11px;
+ font-weight: 500;
+ font-family: inherit;
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 35%, transparent);
+ color: var(--accent, var(--red));
+ cursor: pointer;
+ transition: background 0.12s, transform 0.12s, box-shadow 0.12s;
+ vertical-align: middle;
+ }
+ .note-card-ai-chip:hover {
+ background: color-mix(in srgb, var(--accent, var(--red)) 22%, transparent);
+ transform: translateY(-1px);
+ box-shadow: 0 2px 6px color-mix(in srgb, var(--accent, var(--red)) 30%, transparent);
+ }
+ .note-card-ai-chip svg {
+ flex-shrink: 0;
+ animation: note-ai-shine 2.4s ease-in-out infinite;
+ }
+ .note-card-ai-solving {
+ cursor: default;
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ border-color: color-mix(in srgb, var(--fg) 18%, transparent);
+ color: color-mix(in srgb, var(--fg) 70%, transparent);
+ }
+ .note-card-ai-solving svg { animation: spin 0.9s linear infinite; filter: none; }
+ .note-card-ai-done { background: color-mix(in srgb, var(--accent, var(--red)) 8%, transparent); }
+ .note-card-ai-done svg { animation: none; }
+ #notes-auto-ai-toggle.active { color: var(--accent, var(--red)); }
+
+ /* ─── AI improve button (note form header) ───────────────────────────── */
+ .note-form-improve-btn {
+ width: 38px !important;
+ height: 38px !important;
+ color: var(--accent, var(--red));
+ }
+ .note-form-improve-btn svg {
+ width: 22px !important;
+ height: 22px !important;
+ animation: note-ai-shine 2.4s ease-in-out infinite;
+ }
+ .note-form-improve-btn.busy svg {
+ animation: spin 0.9s linear infinite;
+ filter: none;
+ }
+
+ .note-card:hover .note-card-select,
+ .note-card:hover .note-card-pin,
+ .note-card-selected .note-card-select,
+ .note-card-pinned .note-card-pin {
+ display: flex;
+ }
+ .note-card-select:hover, .note-card-pin:hover {
+ opacity: 1;
+ transform: scale(1.15);
+ background: color-mix(in srgb, var(--accent) 15%, var(--bg));
+ }
+ .note-card-pin.active {
+ display: flex;
+ background: color-mix(in srgb, var(--accent, var(--red)) 12%, var(--bg));
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 45%, var(--border));
+ color: var(--accent, var(--red));
+ opacity: 1;
+ }
+ .note-card-selected .note-card-select {
+ background: var(--accent);
+ border-color: var(--accent);
+ color: #fff;
+ opacity: 1;
+ }
+
+ /* Select-mode checkbox on cards (mirrors docs library) */
+ .note-card-cb {
+ position: absolute;
+ top: 6px;
+ left: 6px;
+ z-index: 3;
+ margin: 0;
+ }
+ .note-card-selectmode {
+ padding-left: 28px;
+ cursor: pointer;
+ }
+ .note-card-selectmode:hover { background: color-mix(in srgb, var(--fg) 3%, transparent) !important; }
+
+ @media (max-width: 768px) {
+ body.notes-mobile-mode .note-card-selectmode {
+ animation: notes-select-jiggle 0.34s cubic-bezier(0.42, 0, 0.58, 1) infinite;
+ transform-origin: 50% 50%;
+ }
+ body.notes-mobile-mode .note-card-selectmode:nth-child(2n) {
+ animation-delay: -0.08s;
+ }
+ /* Keep the subtle edit-mode cue only on Notes and Gallery. */
+ :is(
+ body.gallery-selecting .gallery-card
+ ) {
+ animation: notes-select-jiggle 0.34s cubic-bezier(0.42, 0, 0.58, 1) infinite;
+ transform-origin: 50% 50%;
+ }
+ :is(
+ body.gallery-selecting .gallery-card:nth-child(2n)
+ ) { animation-delay: -0.11s; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ body.notes-mobile-mode .note-card-selectmode,
+ body.gallery-selecting .gallery-card { animation: none; }
+ }
+
+ /* Bottom action row — hidden everywhere. The archive/delete actions and the
+ color picker now live inside the edit form (click the pencil corner). */
+ .note-card-actions { display: none; }
+ .note-agent-menu {
+ background: var(--panel, var(--bg));
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ box-shadow: 0 4px 16px rgba(0,0,0,0.3);
+ padding: 4px 0;
+ min-width: 140px;
+ font-size: 12px;
+ }
+ .note-card-colors {
+ display: flex;
+ gap: 3px;
+ }
+ /* Re-asserted AFTER the base rule above so the mobile-hide actually
+ wins the cascade — earlier @media (hover:none) block was being
+ overridden because the unconditional display:flex rule came later. */
+ @media (hover: none) {
+ .note-card-colors { display: none; }
+ }
+ .note-card-color-dot {
+ width: 12px;
+ height: 12px;
+ border-radius: 50%;
+ cursor: pointer;
+ border: 1.5px solid color-mix(in srgb, var(--fg) 20%, transparent);
+ transition: transform 0.15s, border-color 0.15s;
+ }
+ .note-card-color-dot:hover {
+ transform: scale(1.25);
+ border-color: var(--fg);
+ }
+ .note-card-color-dot.active {
+ border-color: var(--fg);
+ border-width: 2px;
+ }
+ .note-card-action {
+ background: none;
+ border: none;
+ cursor: pointer;
+ padding: 3px;
+ color: var(--fg);
+ opacity: 0.4;
+ display: flex;
+ align-items: center;
+ border-radius: 3px;
+ transition: opacity 0.15s, background 0.15s;
+ }
+
+ /* Note image */
+ .note-card-image {
+ width: 100%;
+ max-height: 180px;
+ object-fit: cover;
+ border-radius: 4px;
+ margin: 4px 0;
+ display: block;
+ }
+ .note-form-image-wrap {
+ position: relative;
+ margin: 4px 0;
+ }
+ .note-form-image {
+ width: 100%;
+ max-height: 200px;
+ object-fit: cover;
+ border-radius: 4px;
+ display: block;
+ /* Images are draggable=true by default; that catches the mousedown
+ and beats the X button to the click. Disabling drag at the CSS
+ level (the -webkit-user-drag prop) keeps the X button reliably
+ clickable even if the JS forgets to set draggable="false" on the
+ element. Unprefixed user-drag was never standardized — Firefox
+ drops it with a warning. */
+ -webkit-user-drag: none;
+ user-select: none;
+ }
+ .note-form-image-rm {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ z-index: 5;
+ background: rgba(0,0,0,0.65);
+ border: none;
+ color: #fff;
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ cursor: pointer;
+ font-size: 20px;
+ line-height: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .note-form-photo-btn {
+ flex: 0 0 auto;
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ cursor: pointer;
+ border-radius: 4px;
+ width: auto;
+ min-width: 32px;
+ height: 32px;
+ padding: 0 6px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 3px;
+ opacity: 1;
+ transition: opacity 0.15s, border-color 0.15s, background 0.15s;
+ }
+ .note-form-photo-btn:hover { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 8%, transparent); }
+
+ /* Quick-add bar (always at top) */
+ .notes-quick-add {
+ display: flex;
+ align-items: center;
+ transform: translateY(-2px);
+ gap: 4px;
+ background: var(--panel);
+ border: 1px solid color-mix(in srgb, var(--accent, var(--red)) 35%, var(--border));
+ border-radius: 6px;
+ /* Toggle pill sits at the very left of the bar — no inset padding. The
+ pill's own border provides visual breathing room from the wrapper edge. */
+ padding: 4px 6px 4px 4px;
+ margin-top: 2px;
+ margin-bottom: 8px;
+ transition: border-color 0.15s, box-shadow 0.15s, background 0.15s;
+ /* Subtle idle glow so the field reads as "you can type here" without
+ the user having to click it first. Fades out the moment the user
+ hovers or focuses it. */
+ animation: notes-quick-pulse 2.8s ease-in-out infinite;
+ }
+ .notes-quick-add:hover {
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 55%, var(--border));
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent, var(--red)) 18%, transparent);
+ animation: none;
+ }
+ .notes-quick-add:focus-within {
+ border-color: var(--accent, var(--red));
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent, var(--red)) 25%, transparent);
+ background: color-mix(in srgb, var(--fg) 3%, var(--panel));
+ animation: none;
+ }
+ .notes-quick-input {
+ flex: 1;
+ background: transparent;
+ border: none;
+ outline: none;
+ color: var(--fg);
+ caret-color: var(--accent, var(--red));
+ font-family: inherit;
+ font-size: 12px;
+ padding: 6px 0;
+ }
+ .notes-quick-icon {
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.45;
+ cursor: pointer;
+ padding: 5px;
+ border-radius: 4px;
+ display: flex;
+ align-items: center;
+ transition: opacity 0.15s, background 0.15s;
+ }
+ .notes-quick-icon:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
+ /* 2-pill Note/Todo toggle in the quick-add bar — same look as the form's
+ type-seg but slimmer to fit the compact row. */
+ .notes-quick-type-seg {
+ display: inline-flex;
+ height: 28px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ overflow: hidden;
+ position: relative;
+ flex-shrink: 0;
+ /* Negative order pushes the toggle BEFORE the wrapper's ::before caret
+ hint, so the blinking | sits between the toggle and the input rather
+ than at the far-left edge. */
+ order: -1;
+ }
+ .notes-quick-type-seg::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 50%;
+ height: 100%;
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ border-radius: 6px;
+ transition: transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1);
+ z-index: 0;
+ }
+ .notes-quick-type-pill {
+ background: none;
+ border: none;
+ color: color-mix(in srgb, var(--fg) 40%, transparent);
+ cursor: pointer;
+ padding: 0 11px;
+ font-family: inherit;
+ transition: color 0.2s;
+ white-space: nowrap;
+ height: 100%;
+ display: inline-flex;
+ align-items: center;
+ position: relative;
+ z-index: 1;
+ }
+ .notes-quick-type-pill svg {
+ width: 16px;
+ height: 16px;
+ }
+ .notes-quick-type-pill:not(.active):hover {
+ color: color-mix(in srgb, var(--fg) 65%, transparent);
+ }
+ .notes-quick-type-pill.active,
+ .notes-quick-type-pill.active:hover,
+ .notes-quick-type-pill.active:focus {
+ color: var(--fg);
+ cursor: default;
+ }
+ /* Mobile: thumb-sized Note/Todo toggle. The 22px desktop pill is too
+ small to hit reliably on a phone. */
+ @media (max-width: 768px) {
+ .notes-quick-type-seg {
+ height: 36px;
+ border-radius: 10px;
+ }
+ .notes-quick-type-seg::before {
+ border-radius: 9px;
+ }
+ .notes-quick-type-pill {
+ padding: 0 14px;
+ }
+ .notes-quick-type-pill svg {
+ width: 17px;
+ height: 17px;
+ }
+ /* Match the input + photo button heights to the bigger toggle so the
+ row reads as one consistent bar. */
+ .notes-quick-input {
+ height: 36px;
+ font-size: 15px;
+ }
+ .notes-quick-icon {
+ padding: 9px;
+ }
+ .notes-quick-icon svg {
+ width: 18px;
+ height: 18px;
+ }
+ }
+ .notes-empty-msg {
+ text-align: center;
+ /* 0.4 dropped this empty-state text to ~2.8:1; 0.65 keeps it readable
+ (WCAG AA) while staying visibly secondary. */
+ opacity: 0.65;
+ padding: 30px 20px;
+ font-size: 11px;
+ }
+
+ /* Loading skeleton */
+ .notes-skeleton {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ margin-top: 4px;
+ }
+ .notes-skeleton-card {
+ height: 72px;
+ border-radius: 6px;
+ border: 1px solid var(--border);
+ background: linear-gradient(
+ 90deg,
+ color-mix(in srgb, var(--fg) 4%, transparent) 0%,
+ color-mix(in srgb, var(--fg) 10%, transparent) 50%,
+ color-mix(in srgb, var(--fg) 4%, transparent) 100%
+ );
+ background-size: 200% 100%;
+ animation: notes-skeleton-shimmer 1.4s ease-in-out infinite;
+ }
+
+ /* Type toggle (note vs todo) */
+ .note-form-type-row {
+ display: flex;
+ gap: 4px;
+ margin-top: -2px;
+ }
+ /* Reminder bell button */
+ /* Mobile-only: bell icon in the note editor is accent-coloured so it pops as
+ the primary "set a reminder" affordance. The Archive button is hidden — the
+ Update (✓) button morphs into an Archive action when the user opens a note
+ and clicks without making any edits (see notes.js `archive-mode` toggle). */
+ @media (max-width: 768px) {
+ .note-form-remind-btn { color: var(--accent, var(--red)) !important; }
+ .note-form-remind-btn > svg { color: var(--accent, var(--red)); }
+ .note-form-archive-btn { display: none !important; }
+ .notes-pane #notes-archive-toggle { display: none !important; }
+ .note-form-save.archive-mode {
+ color: var(--accent, var(--red)) !important;
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 50%, transparent) !important;
+ background: color-mix(in srgb, var(--accent, var(--red)) 10%, transparent) !important;
+ }
+ }
+ .note-form-remind-btn {
+ flex: 0 0 auto;
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ border-radius: 4px;
+ width: 32px;
+ height: 32px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ opacity: 1;
+ position: relative;
+ top: -2px;
+ transition: opacity 0.15s, border-color 0.15s, background 0.15s, color 0.15s;
+ }
+ .note-form-remind-btn:hover { opacity: 1; border-color: var(--accent); background: color-mix(in srgb, var(--accent) 8%, transparent); }
+ .note-form-remind-btn.has-date { color: var(--accent); border-color: var(--accent); }
+
+ /* Calendar event form + notes form: jingle the little bell when the user
+ picks a reminder. Anchored near the top of the bell so the swing reads
+ as the bell clanging side-to-side. */
+ .cal-remind-bell,
+ .note-form-remind-btn > svg {
+ transform-origin: 50% 4px;
+ transition: transform 0.1s ease;
+ }
+ .cal-remind-bell.jingling,
+ .note-form-remind-btn > svg.jingling {
+ animation: cal-bell-jingle 0.65s cubic-bezier(0.36, 0, 0.66, -0.56) both;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .cal-remind-bell.jingling,
+ .note-form-remind-btn > svg.jingling { animation: none; }
+ }
+
+ /* Reminder tag inside form */
+ .note-form-reminder-tags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ }
+ .note-reminder-tag {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ background: color-mix(in srgb, var(--accent) 14%, transparent);
+ color: var(--accent);
+ border: none;
+ border-radius: 12px;
+ padding: 4px 4px 4px 9px;
+ font-size: 10px;
+ font-family: inherit;
+ cursor: pointer;
+ font-weight: 500;
+ }
+ .note-reminder-tag:hover { background: color-mix(in srgb, var(--accent) 22%, transparent); }
+ .note-reminder-tag-x {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: color-mix(in srgb, var(--accent) 25%, transparent);
+ font-size: 12px;
+ line-height: 1;
+ position: relative;
+ top: -2px;
+ }
+ .note-reminder-tag-x:hover { background: var(--red); color: #fff; }
+
+ /* Reminder tag on card */
+ .note-card-reminder {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ background: color-mix(in srgb, var(--accent) 12%, transparent);
+ color: var(--accent);
+ font-size: 9px;
+ font-weight: 500;
+ padding: 2px 7px;
+ border-radius: 10px;
+ align-self: flex-start;
+ margin-top: 2px;
+ }
+ .note-card-reminder.overdue {
+ background: color-mix(in srgb, var(--red) 18%, transparent);
+ color: var(--red);
+ }
+
+ /* Reminder dropdown menu */
+ .note-reminder-menu {
+ position: fixed;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 6px 24px rgba(0,0,0,0.25);
+ /* Above the fullscreen note overlay (z-index: 10500) — otherwise the
+ reminder picker opens hidden behind it on mobile and reads as
+ "broken". */
+ z-index: 12000;
+ min-width: 220px;
+ padding: 6px 0;
+ font-family: inherit;
+ font-size: 12px;
+ }
+ .note-reminder-menu-title {
+ font-size: 10px;
+ font-weight: 600;
+ text-transform: uppercase;
+ opacity: 0.5;
+ padding: 6px 14px 4px;
+ letter-spacing: 0.5px;
+ }
+ .note-reminder-menu-item {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ width: 100%;
+ background: none;
+ border: none;
+ color: var(--fg);
+ font-family: inherit;
+ font-size: 12px;
+ padding: 7px 14px;
+ cursor: pointer;
+ text-align: left;
+ transition: background 0.1s;
+ }
+ .note-reminder-menu-item:hover { background: color-mix(in srgb, var(--fg) 6%, transparent); }
+ .note-reminder-menu-item.active { color: var(--accent); }
+ .note-reminder-menu-sub {
+ font-size: 10px;
+ opacity: 0.5;
+ margin-left: 12px;
+ }
+ .note-reminder-menu-check { color: var(--accent); font-size: 12px; }
+ .note-reminder-menu-divider {
+ height: 1px;
+ background: var(--border);
+ margin: 4px 0;
+ }
+ .note-reminder-menu-picker {
+ padding: 6px 14px 8px;
+ }
+ .note-reminder-date-input {
+ width: 100%;
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ color: var(--fg);
+ font-family: inherit;
+ font-size: 12px;
+ padding: 6px 8px;
+ outline: none;
+ color-scheme: dark light;
+ box-sizing: border-box;
+ }
+ .note-reminder-date-input:focus { border-color: var(--accent); }
+ .note-reminder-menu-confirm {
+ font-weight: 600;
+ color: var(--accent);
+ justify-content: center;
+ }
+ .note-reminder-menu-confirm.disabled,
+ .note-reminder-menu-confirm[disabled] {
+ opacity: 0.4;
+ cursor: not-allowed;
+ color: var(--fg);
+ }
+ .note-reminder-menu-arrow {
+ opacity: 0.5;
+ margin-left: 8px;
+ font-size: 14px;
+ line-height: 1;
+ }
+ .note-reminder-menu-back {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ width: 100%;
+ background: none;
+ border: none;
+ color: var(--fg);
+ font-family: inherit;
+ font-size: 11px;
+ opacity: 0.7;
+ padding: 6px 12px;
+ cursor: pointer;
+ text-align: left;
+ transition: opacity 0.1s, background 0.1s;
+ }
+ .note-reminder-menu-back:hover { opacity: 1; background: color-mix(in srgb, var(--fg) 6%, transparent); }
+ .note-reminder-menu-arrow-back {
+ font-size: 14px;
+ line-height: 1;
+ }
+ .note-reminder-menu-sublabel {
+ font-size: 10px;
+ opacity: 0.5;
+ padding: 6px 14px 2px;
+ letter-spacing: 0.3px;
+ }
+ .note-reminder-weekday-row {
+ display: flex;
+ gap: 4px;
+ padding: 4px 12px 8px;
+ flex-wrap: wrap;
+ }
+ .note-reminder-day-chip {
+ flex: 1 1 0;
+ min-width: 24px;
+ height: 28px;
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ color: var(--fg);
+ font-family: inherit;
+ font-size: 11px;
+ font-weight: 600;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ transition: background 0.1s, border-color 0.1s, color 0.1s;
+ padding: 0;
+ }
+ .note-reminder-day-chip:hover {
+ background: color-mix(in srgb, var(--accent) 10%, transparent);
+ border-color: color-mix(in srgb, var(--accent) 40%, var(--border));
+ }
+ .note-reminder-day-chip.active {
+ background: var(--accent);
+ border-color: var(--accent);
+ color: #fff;
+ }
+
+ .note-form-type-btn,
+ .note-form-type-toggle {
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ cursor: pointer;
+ border-radius: 4px;
+ width: 32px;
+ height: 32px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 1;
+ transition: opacity 0.15s, background 0.15s, border-color 0.15s;
+ }
+ .note-form-type-toggle:hover { opacity: 1; border-color: var(--accent); background: color-mix(in srgb, var(--accent) 8%, transparent); }
+ .note-form-type-toggle[data-type="todo"] { color: var(--accent); }
+
+ /* Note | Todo | Draw segmented toggle — mirrors .mode-toggle (agent/chat) */
+ .note-form-type-seg {
+ display: inline-flex;
+ height: 32px;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ overflow: hidden;
+ position: relative;
+ flex-shrink: 0;
+ }
+ .note-form-type-pill {
+ background: none;
+ border: none;
+ color: color-mix(in srgb, var(--fg) 40%, transparent);
+ cursor: pointer;
+ padding: 0 12px;
+ font-size: 13px;
+ font-weight: 500;
+ font-family: inherit;
+ transition: color 0.2s;
+ white-space: nowrap;
+ height: 100%;
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ position: relative;
+ z-index: 1;
+ }
+ .note-form-type-pill:not(.active):hover { color: color-mix(in srgb, var(--fg) 60%, transparent); }
+ .note-form-type-pill.active,
+ .note-form-type-pill.active:hover,
+ .note-form-type-pill.active:focus {
+ color: var(--fg);
+ cursor: default;
+ }
+ @media (max-width: 480px) {
+ .note-form-type-pill span { display: none; }
+ .note-form-type-pill { padding: 0 8px; }
+ }
+
+ .note-card-action:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ }
+ .note-card-delete:hover { color: var(--red); }
+
+ /* Tag/label */
+ .note-card-label {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ margin-top: 2px;
+ }
+ .note-card-label-chip {
+ border: 1px solid color-mix(in srgb, var(--accent) 35%, var(--border));
+ background: color-mix(in srgb, var(--accent) 10%, transparent);
+ color: var(--accent);
+ border-radius: 999px;
+ padding: 2px 6px;
+ font: inherit;
+ font-size: 9px;
+ font-weight: 600;
+ line-height: 1.2;
+ cursor: pointer;
+ }
+ .note-card-label-chip:hover {
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
+ border-color: color-mix(in srgb, var(--accent) 60%, var(--border));
+ }
+
+ /* Search bar */
+ .notes-search-bar {
+ padding: 6px 8px;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .notes-select-trigger {
+ position: relative;
+ top: 3px;
+ flex-shrink: 0;
+ background: var(--bg);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ font-family: inherit;
+ font-size: 11px;
+ height: 30px;
+ padding: 0 12px;
+ cursor: pointer;
+ opacity: 0.75;
+ transition: opacity 0.15s, border-color 0.15s, background 0.15s, color 0.15s;
+ }
+ .notes-select-trigger:hover { opacity: 1; border-color: color-mix(in srgb, var(--accent) 50%, var(--border)); }
+ .notes-select-trigger.active {
+ opacity: 1;
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
+ color: var(--accent);
+ border-color: color-mix(in srgb, var(--accent) 50%, var(--border));
+ }
+ .notes-search-bar .memory-search-input {
+ flex: 1;
+ min-width: 0;
+ height: 30px;
+ min-height: 30px;
+ font-size: 11px;
+ padding: 0 10px 0 28px;
+ background-color: var(--bg);
+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23e06c75' stroke-opacity='0.85' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><circle cx='11' cy='11' r='8'/><line x1='21' y1='21' x2='16.65' y2='16.65'/></svg>");
+ background-repeat: no-repeat;
+ background-position: 9px center;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--fg);
+ font-family: inherit;
+ outline: none;
+ transition: border-color 0.15s, background-color 0.15s;
+ }
+ .notes-search-bar .memory-search-input:focus {
+ border-color: var(--red);
+ }
+
+ /* Grid view: true CSS Grid plus JS-computed row spans, so cards masonry-pack
+ vertically without the jumpy rebalancing of CSS columns. */
+ .notes-pane.notes-view-grid .notes-pane-body {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
+ grid-auto-rows: 4px;
+ grid-auto-flow: dense;
+ gap: 0 8px;
+ padding: 10px 8px 8px;
+ overflow-x: hidden;
+ align-items: start;
+ align-content: start;
+ }
+ .notes-pane.notes-view-grid .note-card {
+ margin: 0 0 8px;
+ min-width: 0;
+ max-width: 100%;
+ overflow-wrap: anywhere;
+ word-break: break-word;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .notes-pane.notes-view-grid .note-form,
+ .notes-pane.notes-view-grid .notes-quick-add {
+ grid-column: 1 / -1;
+ margin-bottom: 0;
+ grid-row-end: span 16;
+ }
+ /* Edit form in grid view: span the full row and size naturally — same shape
+ as the new-note form. The earlier max-width: 380px + max-height: 220px
+ inner-scroll combo read as a tiny popup floating in a wider panel and
+ didn't actually fit the form's content. */
+ .notes-pane.notes-view-grid .note-form {
+ width: 100%;
+ max-width: none;
+ margin-left: 0;
+ margin-right: 0;
+ box-sizing: border-box;
+ }
+ /* Pinned section break: the first unpinned card jumps to column 1, leaving
+ any leftover cell in the pinned row empty. Reads as a visual divider
+ between pinned and unpinned without needing a separator element. */
+ .notes-pane.notes-view-grid .note-card-pinned + .note-card:not(.note-card-pinned) {
+ grid-column-start: 1;
+ }
+ /* Mobile: 2-lane masonry via the CSS-Grid row-span trick. Each card spans
+ N tiny rows (4px each) based on its measured height; the grid auto-places
+ cards into the two columns so left/right lanes flow independently — no
+ row alignment between them. JS in notes.js sets `grid-row-end: span N`
+ on every card after render. Pure CSS multi-column was tried but its
+ `column-span: all` interaction with sticky positioning broke clicks on
+ the quick-add bar (Firefox mobile). */
+ @media (max-width: 768px) {
+ .notes-pane.notes-view-grid .notes-pane-body {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-auto-rows: 4px;
+ grid-auto-flow: dense;
+ gap: 0 8px;
+ align-content: start;
+ }
+ .notes-pane.notes-view-grid .note-card {
+ margin: -8px 0 6px;
+ transform: translateY(-12px);
+ /* grid-row-end set inline by JS (_applyMasonry) */
+ }
+ /* Full-width quick-add + edit form. Quick-add stays sticky at top so
+ the user can always reach it; it's NOT inside the masonry pack. */
+ .notes-pane.notes-view-grid .notes-label-toggle,
+ .notes-pane.notes-view-grid .notes-labels-bar,
+ .notes-pane.notes-view-grid .doclib-chip-scroll-frame:has(> .notes-labels-bar),
+ .notes-pane.notes-view-grid .notes-quick-add,
+ .notes-pane.notes-view-grid .note-form {
+ grid-column: 1 / -1;
+ }
+ .notes-pane.notes-view-grid .notes-label-toggle { grid-row: span 8; }
+ .notes-pane.notes-view-grid .notes-labels-bar { grid-row: span 16; }
+ .notes-pane.notes-view-grid .doclib-chip-scroll-frame:has(> .notes-labels-bar) { grid-row: span 16; }
+ .notes-pane.notes-view-grid .notes-quick-add { grid-row: span 12; }
+ .notes-pane.notes-view-grid .note-form {
+ width: 100%;
+ max-width: none;
+ margin-left: 0;
+ margin-right: 0;
+ box-sizing: border-box;
+ grid-row: auto / span 64;
+ }
+ .notes-pane.notes-view-grid .note-form:has(.note-form-type-seg.is-draw) {
+ grid-row: auto / span 152;
+ }
+ .notes-pane.notes-view-grid .note-form.note-form-new {
+ transform: translateY(-28px);
+ }
+ .notes-pane.notes-view-grid .notes-labels-bar {
+ padding-top: 0;
+ margin-top: -6px;
+ margin-bottom: 0;
+ }
+ .notes-pane.notes-view-grid .notes-quick-add {
+ margin-top: -32px;
+ margin-bottom: 4px;
+ }
+ /* Pinned-section break: first unpinned card jumps to column 1. */
+ .notes-pane.notes-view-grid .note-card-pinned + .note-card:not(.note-card-pinned) {
+ grid-column-start: 1;
+ }
+ }
+
+ /* Label filter bar */
+ .notes-label-toggle {
+ align-self: flex-start;
+ margin: -6px 8px 2px;
+ top: 0;
+ }
+ .notes-search-bar .notes-label-toggle {
+ align-self: center;
+ flex: 0 0 auto;
+ height: 30px;
+ margin: 0;
+ top: 4px;
+ padding: 0 10px;
+ border-radius: 6px;
+ font-size: 11px;
+ white-space: nowrap;
+ }
+ .notes-pane-body .doclib-chip-scroll-arrow.right {
+ top: calc(50% - 6px) !important;
+ }
+ .doclib-chip-scroll-frame:has(> #tasks-filter-chips) .doclib-chip-scroll-arrow {
+ top: calc(50% - 9px) !important;
+ }
+
+ @media (max-width: 768px) {
+ #doclib-modal .doclib-lang-chips {
+ position: relative;
+ top: -2px;
+ }
+ #doclib-chats-tidy-btn,
+ #doclib-chats-select-btn,
+ #doclib-arc-select-btn,
+ #doclib-research-tidy-btn,
+ #doclib-research-select-btn,
+ #doclib-tidy-btn,
+ #doclib-select-btn {
+ height: 30px !important;
+ min-height: 30px !important;
+ box-sizing: border-box;
+ }
+ }
+
+ /* Keep filter chips consistent across Skills, Tasks, and the document
+ library. Documents use the shared compact chip treatment as the baseline. */
+ .skills-summary-chip,
+ .memory-cat-chip,
+ .doclib-chip {
+ height: 23px;
+ padding: 0 8px;
+ border: 1px solid color-mix(in srgb, var(--fg) 12%, transparent);
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--fg) 4%, transparent);
+ color: color-mix(in srgb, var(--fg) 70%, transparent);
+ font-size: 10px;
+ line-height: 1;
+ font-family: inherit;
+ text-transform: none;
+ transition: background 0.15s, border-color 0.15s, color 0.15s;
+ }
+ .skills-summary-chip:hover,
+ .memory-cat-chip:hover,
+ .doclib-chip:hover {
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ border-color: color-mix(in srgb, var(--fg) 18%, transparent);
+ color: color-mix(in srgb, var(--fg) 70%, transparent);
+ }
+ .skills-summary-chip.active,
+ .memory-cat-chip.active,
+ .doclib-chip.active {
+ background: color-mix(in srgb, var(--accent, var(--red)) 13%, transparent);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 28%, transparent);
+ color: var(--fg);
+ }
+ .notes-labels-bar {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ padding: 0 8px 0;
+ margin-top: -6px;
+ margin-bottom: -2px;
+ }
+ .notes-label-chip {
+ background: transparent;
+ border: 1px solid var(--border);
+ color: color-mix(in srgb, var(--fg) 60%, transparent);
+ font-size: 10px;
+ padding: 3px 10px;
+ border-radius: 10px;
+ cursor: pointer;
+ font-family: inherit;
+ transition: background 0.15s, color 0.15s, border-color 0.15s;
+ }
+ .notes-label-chip:hover {
+ color: var(--fg);
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ border-color: color-mix(in srgb, var(--accent) 40%, var(--border));
+ }
+ .notes-label-chip.active {
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
+ color: var(--accent);
+ border-color: color-mix(in srgb, var(--accent) 60%, transparent);
+ font-weight: 600;
+ }
+ .notes-label-chip-reminders {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ }
+ .notes-label-chip-count {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 14px;
+ height: 14px;
+ padding: 0 4px;
+ border-radius: 7px;
+ background: color-mix(in srgb, var(--fg) 12%, transparent);
+ color: inherit;
+ font-size: 9px;
+ font-weight: 600;
+ margin-left: 3px;
+ }
+ .notes-label-chip-reminders.active .notes-label-chip-count {
+ background: color-mix(in srgb, var(--accent) 30%, transparent);
+ color: var(--accent);
+ }
+ .notes-label-chip-reminders.active.negated {
+ background: color-mix(in srgb, var(--red, #e55) 14%, transparent);
+ color: var(--red, #e55);
+ border-color: color-mix(in srgb, var(--red, #e55) 50%, transparent);
+ }
+ .notes-label-chip-reminders.active.negated .notes-label-chip-count {
+ background: color-mix(in srgb, var(--red, #e55) 25%, transparent);
+ color: var(--red, #e55);
+ }
+ .notes-label-clear-past {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ color: var(--red, #e55);
+ border-color: color-mix(in srgb, var(--red, #e55) 45%, var(--border));
+ }
+ .notes-label-clear-past:hover {
+ color: var(--red, #e55);
+ background: color-mix(in srgb, var(--red, #e55) 12%, transparent);
+ border-color: color-mix(in srgb, var(--red, #e55) 65%, var(--border));
+ }
+ /* Today + Goals filter chips — share styling, tint with a warm accent so
+ they read as "long-term work" alongside the cool reminder chip. */
+ .notes-label-chip-today,
+ .notes-label-chip-goals {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ }
+ .notes-label-chip-today.active,
+ .notes-label-chip-goals.active {
+ background: color-mix(in srgb, var(--accent-warm) 22%, transparent);
+ color: var(--accent-warm);
+ border-color: color-mix(in srgb, var(--accent-warm) 60%, transparent);
+ }
+ .notes-label-chip-today.active .notes-label-chip-count,
+ .notes-label-chip-goals.active .notes-label-chip-count {
+ background: color-mix(in srgb, var(--accent-warm) 30%, transparent);
+ color: var(--accent-warm);
+ }
+
+ /* ── Goal cards ──────────────────────────────────────────────────────── */
+ /* A goal note is structurally a checklist (note_type='goal') but visually
+ marked with a small Goal pill in the corner + a slightly warmer accent
+ so users can spot it at a glance among regular todos. */
+ .note-card-goal {
+ border-left: 3px solid color-mix(in srgb, var(--accent-warm) 80%, transparent);
+ }
+ .note-goal-pill {
+ position: absolute;
+ top: 6px;
+ left: 8px;
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ padding: 2px 7px 2px 5px;
+ background: color-mix(in srgb, var(--accent-warm) 18%, transparent);
+ color: var(--accent-warm);
+ border-radius: 999px;
+ font-size: 9px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ line-height: 1;
+ z-index: 2;
+ }
+ /* Description blurb above the checklist on goal cards */
+ .note-goal-desc {
+ font-size: 12px;
+ opacity: 0.7;
+ margin: 4px 0 6px;
+ white-space: pre-wrap;
+ line-height: 1.4;
+ }
+
+ /* ── Goal form (Break-down editor) ───────────────────────────────────── */
+ .note-form-goal {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .note-form-goal-desc {
+ width: 100%;
+ box-sizing: border-box;
+ background: transparent;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--fg);
+ font-family: inherit;
+ font-size: 13px;
+ padding: 8px 10px;
+ resize: vertical;
+ min-height: 60px;
+ }
+ .note-form-goal-desc:focus {
+ outline: none;
+ border-color: color-mix(in srgb, var(--accent-warm) 60%, var(--border));
+ }
+ .note-form-goal-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .note-form-goal-ai {
+ display: inline-flex;
+ align-items: center;
+ background: color-mix(in srgb, var(--accent-warm) 16%, transparent);
+ color: var(--accent-warm);
+ border: 1px solid color-mix(in srgb, var(--accent-warm) 45%, transparent);
+ border-radius: 6px;
+ padding: 5px 10px;
+ font-size: 12px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s;
+ }
+ .note-form-goal-ai:hover:not(:disabled) {
+ background: color-mix(in srgb, var(--accent-warm) 26%, transparent);
+ border-color: color-mix(in srgb, var(--accent-warm) 65%, transparent);
+ }
+ .note-form-goal-hint {
+ font-size: 11px;
+ opacity: 0.55;
+ }
+
+ /* ── Today view ──────────────────────────────────────────────────────── */
+ .notes-today-wrap {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ margin: 4px 0 12px;
+ }
+ .notes-today-header {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--accent-warm);
+ padding: 6px 10px 4px;
+ }
+ .notes-today-list {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ .notes-today-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 12px;
+ background: var(--panel, var(--bg));
+ border: 1px solid var(--border);
+ border-left: 3px solid color-mix(in srgb, var(--accent-warm) 70%, transparent);
+ border-radius: 8px;
+ transition: opacity 0.2s, transform 0.2s;
+ }
+ .notes-today-row .note-check-dot {
+ flex-shrink: 0;
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ border: 2px solid color-mix(in srgb, var(--fg) 40%, transparent);
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s;
+ }
+ .notes-today-row .note-check-dot:hover {
+ border-color: var(--accent-warm);
+ background: color-mix(in srgb, var(--accent-warm) 20%, transparent);
+ }
+ .notes-today-row.done .note-check-dot {
+ background: var(--accent-warm);
+ border-color: var(--accent-warm);
+ }
+ .notes-today-text {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+ .notes-today-title {
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--accent-warm);
+ letter-spacing: 0.03em;
+ cursor: pointer;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .notes-today-step {
+ font-size: 14px;
+ color: var(--fg);
+ line-height: 1.35;
+ }
+ .notes-today-progress {
+ flex-shrink: 0;
+ font-size: 10px;
+ font-weight: 600;
+ opacity: 0.6;
+ font-variant-numeric: tabular-nums;
+ }
+ .notes-empty {
+ text-align: center;
+ padding: 32px 16px;
+ font-size: 13px;
+ opacity: 0.55;
+ font-style: italic;
+ }
+
+ /* Bulk action bar */
+ .notes-bulk-info {
+ font-size: 10px;
+ opacity: 0.6;
+ margin-left: 4px;
+ }
+
+ /* Form label input */
+ .note-form-label {
+ background: transparent;
+ border: 1px dashed color-mix(in srgb, var(--border) 60%, transparent);
+ color: var(--fg);
+ font-size: 11px;
+ padding: 3px 6px;
+ border-radius: 4px;
+ outline: none;
+ width: 80px;
+ font-family: inherit;
+ opacity: 0.6;
+ transition: opacity 0.15s, border-color 0.15s;
+ }
+ .note-form-label:hover, .note-form-label:focus { opacity: 1; border-color: var(--border); }
+ @keyframes noteLabelFlash {
+ 0% { background: color-mix(in srgb, var(--accent) 35%, transparent); }
+ 100% { background: transparent; }
+ }
+
+ .note-card-header {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 6px;
+ }
+ .note-card-title {
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .note-content-preview {
+ font-size: 12px;
+ opacity: 0.6;
+ line-height: 1.4;
+ /* Roomy preview: up to ~14 lines. Content is also sliced to 600 chars
+ client-side, so cards still stay reasonable in the list. */
+ max-height: 240px;
+ overflow: hidden;
+ cursor: pointer;
+ white-space: pre-wrap;
+ word-break: break-word;
+ }
+
+ .note-pin-btn {
+ background: none;
+ border: none;
+ cursor: pointer;
+ padding: 2px;
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ }
+ .note-pin-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ border: 1.5px solid color-mix(in srgb, var(--fg) 25%, transparent);
+ transition: all 0.15s;
+ }
+ .note-pin-btn:hover .note-pin-dot { border-color: var(--fg); }
+ .note-pin-btn.active .note-pin-dot {
+ background: var(--accent);
+ border-color: var(--accent);
+ }
+ .note-x-btn {
+ background: none;
+ border: none;
+ cursor: pointer;
+ padding: 2px;
+ flex-shrink: 0;
+ color: var(--fg);
+ opacity: 0.25;
+ display: flex;
+ align-items: center;
+ transition: opacity 0.15s, color 0.15s;
+ }
+ .note-x-btn:hover {
+ opacity: 0.9;
+ color: var(--red);
+ }
+ /* Inline due date next to title */
+ .note-due-inline {
+ font-size: 9px;
+ padding: 1px 6px;
+ border-radius: 3px;
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ color: color-mix(in srgb, var(--fg) 60%, transparent);
+ opacity: 0.7;
+ white-space: nowrap;
+ flex-shrink: 0;
+ align-self: center;
+ }
+ .note-due-inline.note-due-overdue {
+ background: color-mix(in srgb, var(--red) 18%, transparent);
+ color: var(--red);
+ opacity: 1;
+ font-weight: 600;
+ }
+ .note-card:active { cursor: grabbing; }
+ /* Dragged card = "drop preview" — it already sits at the swap-target slot,
+ so making it the most visible card on screen tells the user exactly where
+ the note will land on release. */
+ .note-card.dragging {
+ opacity: 0.92;
+ cursor: grabbing;
+ transform: scale(1.03) rotate(-0.6deg);
+ box-shadow: 0 14px 32px rgba(0,0,0,0.4), 0 0 0 2px var(--accent, var(--red));
+ border-color: var(--accent, var(--red)) !important;
+ background: color-mix(in srgb, var(--accent, var(--red)) 6%, var(--panel)) !important;
+ z-index: 10;
+ position: relative;
+ /* Let elementFromPoint see THROUGH the dragged card so the swap detector
+ can find the sibling underneath the finger. Without this, in single-row
+ (list view) the dragged card follows the finger and forever occludes
+ anything else, so no swap ever fires. The body-level touchmove listener
+ still receives events regardless. */
+ pointer-events: none;
+ }
+ .notes-pane-body.drag-active .note-card:not(.dragging) {
+ transition: transform 0.22s cubic-bezier(0.34, 1.2, 0.64, 1), border-color 0.15s, opacity 0.15s;
+ opacity: 0.78;
+ }
+ .notes-pane-body.drag-active .note-card:not(.dragging):hover {
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 50%, var(--border));
+ opacity: 1;
+ }
+
+ /* Checklist drag grip */
+ .note-cl-grip {
+ cursor: grab;
+ opacity: 0.2;
+ font-size: 9px;
+ letter-spacing: -2px;
+ user-select: none;
+ flex-shrink: 0;
+ width: 14px;
+ height: 14px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ transition: opacity 0.15s;
+ }
+ .note-cl-row.dragging {
+ opacity: 0.4;
+ background: color-mix(in srgb, var(--accent) 8%, transparent);
+ border-radius: 4px;
+ }
+ .note-cl-row.drop-before {
+ box-shadow: 0 -2px 0 0 var(--accent);
+ }
+ .note-cl-row.drop-after {
+ box-shadow: 0 2px 0 0 var(--accent);
+ }
+
+ .note-card-footer {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-top: 2px;
+ }
+
+ .note-delete-btn {
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.2;
+ cursor: pointer;
+ padding: 2px;
+ transition: opacity 0.15s;
+ }
+ .note-delete-btn:hover { opacity: 0.8; color: var(--red); }
+ .note-archive-btn {
+ background: none; border: none; color: var(--fg); opacity: 0.2; cursor: pointer; padding: 2px; transition: opacity 0.15s;
+ }
+
+ /* Checklist preview — cap height so cards with 30 items don't push the
+ grid layout into oblivion; the inner list scrolls inside the card. */
+ .note-checklist-preview {
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+ min-height: 18px;
+ max-height: 240px;
+ overflow-y: auto;
+ /* Let wheel/touch scrolling continue into the Notes pane when this nested
+ checklist is already at its top or bottom. */
+ overscroll-behavior-y: auto;
+ /* Card has padding-right:30px reserved for the top-corner edit/done/pin
+ buttons — but those sit above the checklist, not next to it. Pull the
+ checklist back into that reserved gutter so todo text can extend
+ further right. The copy button (bottom-right, 28×28) only appears on
+ hover; leave just enough room (last row) so it doesn't hide the final
+ item's tail. */
+ margin-right: -22px;
+ padding-right: 4px;
+ }
+ .note-cl-quickadd {
+ /* In flow now (was position:absolute), rendered AFTER the reminder badge
+ so the "+ Add item" input sits underneath the reminder instead of
+ overlapping it. Slight right inset keeps clear of the bottom-right
+ copy button on hover. */
+ display: block;
+ padding-top: 2px;
+ padding-right: 32px;
+ margin-top: 2px;
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.15s;
+ }
+ .note-cl-quickadd-input {
+ width: 100%;
+ background: transparent;
+ border: none;
+ border-top: 1px dashed color-mix(in srgb, var(--border) 60%, transparent);
+ color: var(--fg);
+ font-size: 11px;
+ font-family: inherit;
+ padding: 4px 2px 2px;
+ outline: none;
+ opacity: 0.6;
+ transition: opacity 0.15s, border-color 0.15s;
+ }
+ .note-cl-quickadd-input:focus { opacity: 1; border-top-color: var(--border); }
+ .note-checkbox {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 11px;
+ cursor: pointer;
+ /* Vertical padding stays 0 so short single-line rows pack tightly.
+ Left padding bumped so the dot's hover-scale (1.15x) doesn't clip
+ against the card edge. */
+ padding: 0 4px 0 8px;
+ line-height: 1.25;
+ border-radius: 4px;
+ user-select: none;
+ -webkit-tap-highlight-color: transparent;
+ }
+ .note-checkbox:hover {
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ }
+ .note-check-text { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
+ .note-link {
+ color: var(--accent-primary, var(--red));
+ text-decoration: underline;
+ word-break: break-all;
+ }
+ .note-link:hover { opacity: 0.8; }
+ .note-checkbox-edit, .note-checkbox-rm {
+ flex: 0 0 auto;
+ background: transparent;
+ border: none;
+ color: var(--fg);
+ opacity: 0;
+ cursor: pointer;
+ padding: 2px;
+ border-radius: 3px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ margin-left: 2px;
+ transition: opacity 0.12s, background 0.12s, color 0.12s;
+ }
+ .note-checkbox-rm:hover { opacity: 1 !important; color: var(--red); background: color-mix(in srgb, var(--red) 12%, transparent); }
+ .note-checkbox-edit:hover { opacity: 1 !important; color: var(--accent, var(--blue)); background: color-mix(in srgb, var(--accent, var(--blue)) 12%, transparent); }
+ .note-check-text[contenteditable="true"] {
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ outline: 1px solid var(--accent, var(--blue));
+ border-radius: 2px;
+ cursor: text;
+ padding: 0 2px;
+ margin: 0 -2px;
+ }
+ .note-check-dot {
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ border: 1.75px solid color-mix(in srgb, var(--fg) 35%, transparent);
+ /* Solid panel fill so the dot reads as a tappable target even when an
+ image or colored card background sits behind it. */
+ background: var(--panel);
+ flex-shrink: 0;
+ position: relative;
+ /* Anchor the hover/active scale to the LEFT edge so the dot grows
+ rightward only. Default center origin pushed the scaled dot off the
+ left of the card (the parent .note-checklist-preview has overflow:auto
+ and clips horizontally as a side-effect of overflow-y:auto). */
+ transform-origin: left center;
+ transition: background 0.2s, border-color 0.2s, transform 0.15s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ .notes-select-mode .note-checkbox:hover { background: transparent; }
+ .notes-select-mode .note-checkbox:hover .note-check-dot { transform: none; border-color: color-mix(in srgb, var(--fg) 35%, transparent); }
+ .note-checkbox:hover .note-check-dot {
+ border-color: var(--accent);
+ transform: scale(1.15);
+ }
+ .note-checkbox.done .note-check-dot {
+ background: var(--accent);
+ border-color: var(--accent);
+ animation: note-check-pop 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ .note-check-text {
+ transition: opacity 0.25s;
+ line-height: 1.3;
+ padding-right: 4px;
+ word-break: break-word;
+ }
+
+ /* Due date badge */
+ .note-due-badge {
+ font-size: 10px;
+ padding: 1px 6px;
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ color: var(--fg);
+ opacity: 0.6;
+ }
+ .note-due-overdue {
+ background: color-mix(in srgb, var(--red) 20%, transparent);
+ color: var(--red);
+ opacity: 1;
+ font-weight: 600;
+ }
+
+ /* Color classes — theme-aware via color-mix with --panel */
+ .note-color-red { background: color-mix(in srgb, var(--red) 18%, var(--panel)); border-color: color-mix(in srgb, var(--red) 30%, var(--border)); }
+ .note-color-orange { background: color-mix(in srgb, #d19a66 18%, var(--panel)); border-color: color-mix(in srgb, #d19a66 30%, var(--border)); }
+ .note-color-yellow { background: color-mix(in srgb, var(--hl-string) 18%, var(--panel)); border-color: color-mix(in srgb, var(--hl-string) 30%, var(--border)); }
+ .note-color-green { background: color-mix(in srgb, #98c379 18%, var(--panel)); border-color: color-mix(in srgb, #98c379 30%, var(--border)); }
+ .note-color-blue { background: color-mix(in srgb, var(--hl-function) 18%, var(--panel)); border-color: color-mix(in srgb, var(--hl-function) 30%, var(--border)); }
+ .note-color-purple { background: color-mix(in srgb, var(--hl-keyword) 18%, var(--panel)); border-color: color-mix(in srgb, var(--hl-keyword) 30%, var(--border)); }
+
+
+ /* Standard notes use a small identity palette when no color was selected.
+ The variation is deliberately limited to the card tint, top edge, and
+ title accent so the notes still read as one collection. */
+ .note-card.note-standard {
+ border-top-width: 3px;
+ background: color-mix(in srgb, var(--note-accent) 7%, var(--panel));
+ border-color: color-mix(in srgb, var(--note-accent) 24%, var(--border));
+ box-shadow: inset 0 2px 0 0 color-mix(in srgb, var(--note-accent) 72%, transparent);
+ }
+ .note-card.note-standard:hover {
+ background: color-mix(in srgb, var(--note-accent) 11%, var(--panel));
+ }
+ .note-card.note-standard .note-card-title {
+ color: color-mix(in srgb, var(--note-accent) 82%, var(--fg));
+ }
+ .note-card.note-standard .note-card-label-chip {
+ border-color: color-mix(in srgb, var(--note-accent) 38%, var(--border));
+ background: color-mix(in srgb, var(--note-accent) 10%, transparent);
+ color: color-mix(in srgb, var(--note-accent) 86%, var(--fg));
+ }
+
+ /* Color picker dots */
+ .note-color-picker {
+ display: flex;
+ gap: 5px;
+ align-items: center;
+ }
+ .note-color-dot {
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ cursor: pointer;
+ border: 2px solid transparent;
+ transition: border-color 0.15s, transform 0.15s;
+ flex-shrink: 0;
+ }
+ .note-color-dot:hover { transform: scale(1.15); }
+ .note-color-dot.active {
+ border-color: var(--fg);
+ }
+
+ /* Note form */
+ .note-form {
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 12px 14px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ margin-bottom: 10px;
+ transition: background 0.2s, border-color 0.2s;
+ /* Container so the action buttons can collapse to icons when the note
+ card is narrow (see .note-form-collapsible). */
+ container-type: inline-size;
+ container-name: noteform;
+ }
+ @media (max-width: 768px) {
+ .notes-pane:not(.notes-view-grid) .note-form.note-form-new {
+ transform: translateY(6px);
+ }
+ }
+ /* Label sits after the icon in each action button */
+ .note-form-text-btn .nft-label { margin-left: 5px; }
+ /* Never let the action buttons spill outside the card */
+ .note-form-actions-group { flex-wrap: wrap; row-gap: 6px; }
+ /* When the note card is narrow, collapse Archive / Delete / Cancel to
+ icon-only (their text label hides; tooltip via title= remains). The
+ Save/Update button is NOT collapsible — it always keeps its label and
+ stays last. */
+ @container noteform (max-width: 360px) {
+ .note-form-collapsible .nft-label { display: none; }
+ .note-form-collapsible { padding-left: 9px; padding-right: 9px; }
+ }
+ .note-form.note-color-red { background: color-mix(in srgb, var(--red) 18%, var(--panel)) !important; border-color: color-mix(in srgb, var(--red) 30%, var(--border)) !important; }
+ .note-form.note-color-orange { background: color-mix(in srgb, #d19a66 18%, var(--panel)) !important; border-color: color-mix(in srgb, #d19a66 30%, var(--border)) !important; }
+ .note-form.note-color-yellow { background: color-mix(in srgb, var(--hl-string) 18%, var(--panel)) !important; border-color: color-mix(in srgb, var(--hl-string) 30%, var(--border)) !important; }
+ .note-form.note-color-green { background: color-mix(in srgb, #98c379 18%, var(--panel)) !important; border-color: color-mix(in srgb, #98c379 30%, var(--border)) !important; }
+ .note-form.note-color-blue { background: color-mix(in srgb, var(--hl-function) 18%, var(--panel)) !important; border-color: color-mix(in srgb, var(--hl-function) 30%, var(--border)) !important; }
+ .note-form.note-color-purple { background: color-mix(in srgb, var(--hl-keyword) 18%, var(--panel)) !important; border-color: color-mix(in srgb, var(--hl-keyword) 30%, var(--border)) !important; }
+ .note-form-header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding-right: 0;
+ }
+ .note-form-header .note-form-remind-btn {
+ margin-right: -7px; /* align bell center with X-button column on todo rows */
+ position: relative;
+ top: -2px;
+ }
+ .note-form-title {
+ flex: 1;
+ min-width: 0;
+ background: transparent;
+ border: none;
+ border-bottom: 1px solid var(--border);
+ color: var(--fg);
+ font-size: 14px;
+ font-weight: 600;
+ padding: 4px 0;
+ outline: none;
+ }
+ .note-form-title:focus { border-color: var(--fg); }
+ .note-form-header { position: relative; }
+ .note-form-header .note-form-due {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ opacity: 0;
+ pointer-events: none;
+ border: 0;
+ padding: 0;
+ margin: 0;
+ right: 0;
+ bottom: 0;
+ }
+ .note-form-due-btn {
+ flex: 0 0 auto;
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ border-radius: 4px;
+ width: 26px;
+ height: 26px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ opacity: 0.85;
+ transition: opacity 0.15s, border-color 0.15s, background 0.15s;
+ }
+ .note-form-due-btn:hover { opacity: 1; border-color: var(--accent); background: color-mix(in srgb, var(--accent) 8%, transparent); }
+ .note-form-due-btn.has-date {
+ opacity: 1;
+ border-style: solid;
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
+ border-color: color-mix(in srgb, var(--accent) 50%, var(--border));
+ }
+
+ .note-type-toggle {
+ display: flex;
+ gap: 4px;
+ }
+ .note-type-btn {
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ font-size: 11px;
+ padding: 3px 10px;
+ border-radius: 4px;
+ cursor: pointer;
+ opacity: 0.5;
+ transition: opacity 0.15s, background 0.15s;
+ }
+ .note-type-btn.active {
+ opacity: 1;
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ }
+
+ .note-form-content {
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ font-size: 12px;
+ padding: 8px;
+ border-radius: 4px;
+ resize: vertical;
+ /* Roomier default so editing a note isn't cramped; JS auto-grow takes
+ it further as you type. */
+ min-height: 120px;
+ line-height: 1.5;
+ font-family: inherit;
+ outline: none;
+ }
+ .note-form-content:focus { border-color: var(--fg); }
+
+ .note-form-meta {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-wrap: wrap;
+ }
+ .note-form-meta .note-color-picker { gap: 3px; }
+ .note-form-actions-group {
+ display: flex;
+ gap: 6px;
+ align-items: center;
+ /* Take the full width of the meta row so Archive/Delete can sit on the
+ LEFT side and the spacer pushes Cancel + Update to the right edge. */
+ flex: 1 1 auto;
+ flex-shrink: 0;
+ flex-wrap: nowrap;
+ }
+ .note-form-actions-spacer { flex: 1 1 auto; }
+ /* Unified text+icon action button — used for Archive, Delete, Cancel, Update
+ so all 4 read as a matched set. Matches the existing .note-form-save
+ sizing/padding via the rules at ~25023. */
+ .note-form-text-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: color-mix(in srgb, var(--fg) 6%, transparent);
+ border: 1px solid var(--border);
+ color: var(--fg);
+ border-radius: 6px;
+ padding: 5px 12px;
+ font-size: 12px;
+ font-family: inherit;
+ font-weight: 500;
+ cursor: pointer;
+ transition: background 0.12s, border-color 0.12s, color 0.12s;
+ white-space: nowrap;
+ }
+ .note-form-text-btn:hover {
+ background: color-mix(in srgb, var(--fg) 14%, transparent);
+ border-color: color-mix(in srgb, var(--fg) 28%, var(--border));
+ }
+ .note-form-text-btn.note-form-save {
+ background: color-mix(in srgb, var(--accent, var(--red)) 18%, transparent);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 45%, var(--border));
+ color: var(--accent, var(--red));
+ font-weight: 600;
+ }
+ .note-form-text-btn.note-form-save:hover {
+ background: color-mix(in srgb, var(--accent, var(--red)) 28%, transparent);
+ }
+ .note-form-text-btn.danger:hover {
+ background: color-mix(in srgb, var(--red) 14%, transparent);
+ border-color: color-mix(in srgb, var(--red) 45%, var(--border));
+ color: var(--red);
+ }
+ .note-form-icon-btn {
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ cursor: pointer;
+ border-radius: 4px;
+ width: 38px;
+ height: 38px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0.65;
+ transition: opacity 0.15s, border-color 0.15s, background 0.15s, color 0.15s;
+ }
+ /* Force the inner icons to render at the inline-attribute size — some other
+ stylesheets clamp `svg { width: ... }` globally and that shrinks them. */
+ .note-form-icon-btn svg { width: 31px !important; height: 31px !important; }
+ .note-form-icon-btn:hover { opacity: 1; border-color: var(--accent); background: color-mix(in srgb, var(--accent) 8%, transparent); }
+ .note-form-delete-btn:hover { color: var(--red); border-color: color-mix(in srgb, var(--red) 50%, var(--border)); background: color-mix(in srgb, var(--red) 8%, transparent); }
+
+ /* Draw mode — canvas + small toolbar */
+ .note-form-draw-wrap {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ position: relative;
+ }
+ /* X overlay on the canvas — appears only when a photo is loaded as the
+ background (via _wireCanvas). Clicking it restores the theme surface. */
+ .note-form-draw-bg-rm {
+ position: absolute;
+ top: 8px;
+ right: 8px;
+ z-index: 3;
+ width: 28px;
+ height: 28px;
+ border: none;
+ border-radius: 50%;
+ background: rgba(0, 0, 0, 0.6);
+ color: #fff;
+ font-size: 18px;
+ line-height: 1;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .note-form-draw-bg-rm:hover { background: rgba(0, 0, 0, 0.8); }
+ /* Draw mode hides the note's background-color picker and the standalone
+ image preview — they don't make sense alongside a canvas. Uses :has() so
+ it kicks in whenever the type-seg flips to .is-draw, in addition to the
+ JS that sets display:none. */
+ .note-form:has(.note-form-type-seg.is-draw) .note-color-picker,
+ .note-form:has(.note-form-type-seg.is-draw) .note-form-image-wrap {
+ display: none !important;
+ }
+ .note-form-canvas {
+ background: var(--panel, var(--bg));
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ touch-action: none;
+ max-width: 100%;
+ cursor: crosshair;
+ }
+ .note-form-draw-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-wrap: wrap;
+ }
+ .note-form-draw-tool {
+ display: inline-flex;
+ align-items: center;
+ height: 26px;
+ }
+ /* Color picker rendered as a flat circular swatch — the native chrome around
+ <input type=color> would clash with the rest of the toolbar. */
+ .note-form-draw-color {
+ appearance: none;
+ -webkit-appearance: none;
+ width: 24px;
+ height: 24px;
+ border-radius: 50%;
+ border: 1px solid color-mix(in srgb, var(--fg) 25%, transparent);
+ background: none;
+ cursor: pointer;
+ padding: 0;
+ overflow: hidden;
+ box-sizing: border-box;
+ flex: 0 0 24px;
+ }
+ .note-form-draw-size-wrap { width: 110px; display: inline-flex; align-items: center; }
+ .note-form-photo-plus {
+ font-size: 16px;
+ line-height: 1;
+ font-weight: 600;
+ opacity: 0.8;
+ }
+ /* Mirrors .gallery-editor-container input[type=range] — slim pill track that
+ grows on interaction, red circular thumb. */
+ .note-form-draw-size {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 100%;
+ height: 4px;
+ background: color-mix(in srgb, var(--fg) 25%, transparent);
+ border-radius: 999px;
+ accent-color: var(--red);
+ cursor: pointer;
+ transition: height 0.15s ease;
+ }
+ /* Brush | Eraser segmented toggle — sliding pill, same recipe as Note/Todo. */
+ .note-form-draw-be {
+ display: inline-flex;
+ height: 32px;
+ /* Accent-colored box around the whole control so it's instantly readable
+ as "switch is on", and the sliding pill inside indicates which side. */
+ border: 2px solid var(--accent);
+ border-radius: 10px;
+ overflow: hidden;
+ position: relative;
+ flex-shrink: 0;
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
+ }
+ .note-form-draw-be-btn {
+ background: none;
+ border: none;
+ color: color-mix(in srgb, var(--fg) 50%, transparent);
+ cursor: pointer;
+ padding: 0 8px;
+ width: 34px;
+ height: 100%;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ z-index: 1;
+ transition: color 0.18s;
+ }
+ .note-form-draw-be-btn:hover { color: var(--fg); }
+ /* Active side picks up the theme accent so brush vs eraser is unmistakable. */
+ .note-form-draw-be-btn.active { color: var(--accent-primary, var(--red)); }
+
+ .note-form-draw-text,
+ .note-form-draw-line,
+ .note-form-draw-circle,
+ .note-form-draw-undo {
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ cursor: pointer;
+ border-radius: 4px;
+ height: 32px;
+ width: 34px;
+ font-family: inherit;
+ font-size: 14px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0.7;
+ position: relative;
+ transition: opacity 0.15s, border-color 0.15s, background 0.15s;
+ }
+ .note-form-draw-text { font-weight: 700; font-family: Georgia, serif; font-size: 16px; }
+ .note-form-draw-undo.has-undo {
+ opacity: 1;
+ color: var(--accent-primary, var(--red));
+ border-color: color-mix(in srgb, var(--accent-primary, var(--red)) 55%, var(--border));
+ background: color-mix(in srgb, var(--accent-primary, var(--red)) 12%, transparent);
+ }
+ .note-form-draw-undo:disabled {
+ opacity: 0.35;
+ cursor: default;
+ }
+ /* Size badge in the bottom-right of T — empty until a size is chosen. */
+ .note-form-draw-text-badge {
+ position: absolute;
+ right: 3px;
+ bottom: 1px;
+ font-family: inherit;
+ font-weight: 700;
+ font-size: 8px;
+ line-height: 1;
+ letter-spacing: 0.3px;
+ /* Bare --accent is undefined here, was rendering invisible — use the
+ defined accent so the S/M/L size badge actually shows in theme colour. */
+ color: var(--accent-primary, var(--red));
+ }
+ .note-form-draw-shape-badge {
+ position: absolute;
+ right: 3px;
+ bottom: 1px;
+ font-family: inherit;
+ font-weight: 700;
+ font-size: 8px;
+ line-height: 1;
+ letter-spacing: 0.3px;
+ color: var(--accent-primary, var(--red));
+ }
+ .note-form-draw-text:hover,
+ .note-form-draw-line:hover,
+ .note-form-draw-circle:hover,
+ .note-form-draw-undo:hover {
+ opacity: 1;
+ border-color: var(--accent);
+ background: color-mix(in srgb, var(--accent) 8%, transparent);
+ }
+ .note-form-draw-text.active,
+ .note-form-draw-line.active,
+ .note-form-draw-circle.active {
+ opacity: 1;
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
+ color: var(--accent);
+ border-color: color-mix(in srgb, var(--accent) 50%, var(--border));
+ }
+ .note-form-due {
+ background: transparent;
+ border: 1px dashed color-mix(in srgb, var(--border) 60%, transparent);
+ color: var(--fg);
+ font-size: 11px;
+ padding: 3px 6px;
+ border-radius: 4px;
+ outline: none;
+ opacity: 0.4;
+ transition: opacity 0.15s, border-color 0.15s;
+ }
+ .note-form-due:hover, .note-form-due:focus { opacity: 0.9; border-color: var(--border); }
+
+ .note-form-actions {
+ display: flex;
+ gap: 6px;
+ justify-content: flex-end;
+ }
+ .note-form-save,
+ .note-form-cancel,
+ .note-form-archive {
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--fg);
+ font-size: 11px;
+ padding: 4px 12px;
+ border-radius: 4px;
+ cursor: pointer;
+ transition: background 0.15s;
+ }
+ .note-form-save { background: color-mix(in srgb, var(--fg) 12%, transparent); font-weight: 600; }
+ .note-form-save:hover { background: color-mix(in srgb, var(--fg) 20%, transparent); }
+ .note-form-cancel:hover { background: color-mix(in srgb, var(--fg) 8%, transparent); }
+ .note-form-archive:hover { background: color-mix(in srgb, var(--fg) 8%, transparent); }
+
+ /* Checklist inputs in form */
+ .note-checklist-inputs {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .note-cl-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .note-cl-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ border: 1.5px solid color-mix(in srgb, var(--fg) 30%, transparent);
+ flex-shrink: 0;
+ cursor: pointer;
+ transition: all 0.15s;
+ }
+ .note-cl-dot:hover { border-color: var(--fg); transform: scale(1.2); }
+ .note-cl-row.done .note-cl-dot {
+ background: var(--accent);
+ border-color: var(--accent);
+ }
+ .note-cl-row.done .note-cl-text {
+ opacity: 0.4;
+ background: linear-gradient(currentColor, currentColor) no-repeat;
+ background-size: 0 1px;
+ background-position: 0 calc(50% - 1px);
+ animation: cl-strike 0.32s ease-out forwards;
+ transition: opacity 0.2s ease;
+ }
+ /* Draws the strikethrough line left-to-right when the row is marked
+ done, instead of snapping it in full-width on the same frame. */
+ @keyframes cl-strike {
+ to { background-size: 100% 1px; }
+ }
+ .note-cl-text {
+ background: transparent;
+ border: none;
+ border-bottom: 1px solid var(--border);
+ color: var(--fg);
+ font-size: 12px;
+ padding: 3px 0 3px 3px;
+ flex: 1 1 auto;
+ width: auto;
+ min-width: 0;
+ outline: none;
+ }
+ .note-cl-text:focus { border-color: var(--fg); }
+ .note-cl-rm {
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.3;
+ cursor: pointer;
+ font-size: 14px;
+ padding: 0;
+ width: 24px;
+ height: 14px;
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ line-height: 1;
+ }
+ .note-cl-rm:hover { opacity: 0.8; color: var(--red); }
+ .note-cl-add {
+ background: none;
+ border: none;
+ color: var(--fg);
+ opacity: 0.4;
+ cursor: pointer;
+ font-size: 11px;
+ padding: 4px 0;
+ text-align: left;
+ }
+
+ /* ── Calendar ── */
+ .cal-modal-content { width:min(680px, 94vw); max-height:88vh; overflow-x:hidden; position:relative; }
+ #calendar-modal .cal-modal-content { animation: none; }
+ /* Was overflow-y:auto with grid + day-detail flowing naturally. Now uses a
+ true splitter layout: the body is a flex column that doesn't scroll
+ itself; the grid takes the remaining space and scrolls if needed; the
+ day-detail has an explicit height (driven by the splitter drag via
+ --cal-detail-h) and shrinks the grid visually as it grows. */
+ #cal-body { display:flex; flex-direction:column; gap:8px; overflow:hidden; padding:0; min-height:0; }
+ #cal-body > .cal-grid { flex: 1 1 auto; min-height: 120px; overflow-y: auto; overflow-x: hidden; }
+ @media (max-width: 768px) {
+ /* Let the calendar pane shrink to nothing on mobile so the day-detail
+ splitter can be dragged all the way to the top, hiding the calendar
+ entirely. Without min-height:0 the grid (or the week-wrap below)
+ refuses to shrink past its built-in floor. */
+ #cal-body > .cal-grid,
+ #cal-body > .cal-wk-wrap {
+ min-height: 0;
+ max-height: none;
+ }
+ /* Let the week grid fill the calendar pane and scroll its hours internally
+ instead of overflowing #cal-body (which clips it and feels cramped). */
+ #cal-body > .cal-wk-wrap {
+ flex: 1 1 auto;
+ overflow: auto;
+ }
+ }
+ .cal-toolbar { display:flex; align-items:center; gap:6px; margin-bottom:7px; flex-wrap:wrap; line-height:1; max-width:100%; row-gap:6px; }
+
+ /* Quick-add bar: natural-language event creation. Sits directly under
+ the toolbar; focused with `Q`; opens the bespoke form pre-filled. */
+ .cal-quickadd-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0 0 8px;
+ padding: 1px 10px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--fg) 3%, var(--bg));
+ transition: border-color 0.15s, background 0.15s;
+ position: relative;
+ }
+ /* Two-tone placeholder hint: "Quick add" in accent, the example in grey, both
+ at one low opacity. Overlays the (empty) input; hidden once the user types. */
+ .cal-quickadd-hint {
+ position: absolute;
+ left: 10px;
+ right: 10px;
+ top: 50%;
+ transform: translateY(-50%);
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ font-size: 12px;
+ color: var(--fg);
+ opacity: 0.5;
+ pointer-events: none;
+ white-space: nowrap;
+ overflow: hidden;
+ }
+ .cal-quickadd-hint .qa-hint-accent { color: var(--accent, var(--red)); }
+ /* ↵ enter glyph in the hint — makes it obvious the field submits on Enter. */
+ .cal-quickadd-hint .qa-hint-enter { margin-left: auto; flex: 0 0 auto; color: var(--accent, var(--red)); opacity: 0.8; }
+ /* Cycling example text fades out before swap, then fades back in. */
+ .cal-quickadd-hint .qa-hint-example {
+ display: block;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-style: italic;
+ transition: opacity 0.18s ease;
+ }
+ .cal-quickadd-hint .qa-hint-example.qa-hint-fade { opacity: 0; }
+ .cal-title-hint {
+ position: absolute;
+ left: 0;
+ top: 50%;
+ transform: translateY(calc(-50% - 2px));
+ display: none;
+ align-items: center;
+ gap: 7px;
+ font-size: 18px;
+ line-height: 1.2;
+ white-space: nowrap;
+ pointer-events: none;
+ color: color-mix(in srgb, var(--fg) 42%, transparent);
+ }
+ .cal-hero-title:placeholder-shown ~ .cal-title-hint { display: inline-flex; }
+ .cal-title-hint .cal-title-enter-ico { color: var(--accent, var(--red)); flex-shrink: 0; }
+ /* Pure-CSS toggle: hide the hint as soon as the field has real text (no
+ per-keystroke JS, so typing never triggers a re-render / focus loss). */
+ .cal-quickadd-input:not(:placeholder-shown) ~ .cal-quickadd-hint { display: none; }
+ .cal-quickadd-row:focus-within {
+ border-color: color-mix(in srgb, var(--accent, var(--fg)) 55%, var(--border));
+ background: color-mix(in srgb, var(--fg) 5%, var(--bg));
+ }
+ .cal-quickadd-icon {
+ color: color-mix(in srgb, var(--accent, var(--fg)) 80%, transparent);
+ display: inline-flex;
+ align-items: center;
+ flex-shrink: 0;
+ opacity: 0.7;
+ }
+ .cal-quickadd-input {
+ flex: 1;
+ min-width: 0;
+ background: transparent;
+ border: none;
+ outline: none;
+ color: var(--fg);
+ font-family: inherit;
+ font-size: 12px;
+ height: 22px;
+ padding: 0;
+ }
+ .cal-quickadd-status {
+ font-size: 10px;
+ opacity: 0.55;
+ font-variant-numeric: tabular-nums;
+ }
+ .cal-toolbar > *, .cal-toolbar-nav > *, .cal-toolbar-right > * { vertical-align:middle; }
+ .cal-toolbar-nav { display:inline-flex; align-items:center; gap:4px; flex-wrap:wrap; }
+ .cal-toolbar-right {
+ display: inline-flex;
+ align-items: center;
+ justify-content: flex-start;
+ gap: 6px;
+ flex: 1 1 100%;
+ width: 100%;
+ margin-left: 0;
+ margin-top: 6px;
+ flex-wrap: wrap;
+ }
+ .cal-title { font-size:13px; font-weight:600; white-space:nowrap; height:24px; line-height:30px; padding:0 6px; display:inline-block; vertical-align:middle; box-sizing:border-box; }
+ .cal-toolbar-clock {
+ margin-left: 8px;
+ color: var(--accent, var(--red));
+ font-size: 11px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ }
+ button.cal-nav { background:color-mix(in srgb, var(--fg) 6%, transparent); border:1px solid var(--border); color:var(--fg); border-radius:5px; padding:0 8px; height:24px; line-height:22px; cursor:pointer; font-size:11px; font-family:inherit; box-sizing:border-box; vertical-align:middle; }
+ button.cal-nav:hover { background:color-mix(in srgb, var(--fg) 12%, transparent); }
+ button.cal-nav.cal-toolbar-arrow {
+ display: none;
+ align-items: center;
+ justify-content: center;
+ width: 24px;
+ padding: 0;
+ border: 1px solid color-mix(in srgb, var(--fg) 14%, transparent);
+ border-radius: 50%;
+ background: color-mix(in srgb, var(--bg) 86%, var(--fg) 14%);
+ color: var(--accent, var(--red));
+ box-shadow: 0 6px 18px rgba(0,0,0,0.16);
+ font-size: 18px;
+ line-height: 1;
+ opacity: 0.84;
+ }
+ .cal-toolbar-arrow-glyph {
+ position: relative;
+ top: -1px;
+ line-height: 1;
+ }
+ @media (max-width: 768px) {
+ button.cal-nav.cal-toolbar-arrow { display: inline-flex !important; }
+ .cal-toolbar-nav {
+ flex: 1 1 100%;
+ width: 100%;
+ min-width: 0;
+ }
+ #cal-next { margin-left: auto; }
+ }
+ .cal-week-start-toggle {
+ display: inline-flex;
+ align-items: center;
+ gap: 0;
+ width: max-content;
+ padding: 0;
+ height: 24px;
+ box-sizing: border-box;
+ border: 1px solid var(--border);
+ border-radius: 5px;
+ background: color-mix(in srgb, var(--fg) 4%, transparent);
+ }
+ .cal-week-start-btn {
+ box-sizing: border-box;
+ height: 22px !important;
+ min-height: 22px !important;
+ margin-top: 0 !important;
+ padding: 0 7px;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ background: transparent;
+ color: color-mix(in srgb, var(--fg) 68%, transparent);
+ cursor: pointer;
+ font-family: inherit;
+ font-size: 10px;
+ line-height: 20px;
+ transition: background 0.12s ease, border-color 0.12s ease, color 0.12s ease;
+ }
+ .cal-settings-actions {
+ display: flex;
+ justify-content: flex-end;
+ width: 100%;
+ }
+ #cal-settings-panel .cal-week-start-toggle {
+ display: flex;
+ margin-left: auto;
+ }
+ .cal-settings-sync-status {
+ position: relative;
+ top: 2px;
+ font-size: 11px;
+ opacity: 0.6;
+ }
+ .cal-settings-sync-status.is-error {
+ color: var(--red);
+ opacity: 1;
+ }
+ .cal-week-start-btn:hover {
+ color: var(--fg);
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ }
+ .cal-week-start-btn.active,
+ .cal-week-start-btn.active:hover {
+ color: var(--fg);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 40%, var(--border));
+ background: color-mix(in srgb, var(--accent, var(--red)) 16%, transparent);
+ }
+ .cal-side-nav {
+ position: absolute;
+ top: var(--cal-side-nav-y, 50%);
+ transform: translateY(-50%);
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ border: 1px solid color-mix(in srgb, var(--fg) 14%, transparent);
+ background: color-mix(in srgb, var(--bg) 86%, var(--fg) 14%);
+ color: var(--accent, var(--red));
+ box-shadow: 0 6px 18px rgba(0,0,0,0.16);
+ cursor: pointer;
+ z-index: 6;
+ opacity: 0;
+ pointer-events: none;
+ font-family: inherit;
+ font-size: 24px;
+ line-height: 28px;
+ padding: 0 0 3px;
+ transition: opacity 0.12s ease, background 0.12s ease, transform 0.12s ease;
+ }
+ .cal-modal-content:hover .cal-side-nav,
+ .cal-side-nav:focus-visible {
+ opacity: 0.84;
+ pointer-events: auto;
+ }
+ .cal-side-nav:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--bg) 76%, var(--fg) 24%);
+ transform: translateY(-50%) scale(1.04);
+ }
+ button.cal-today-btn { font-size:10px; opacity:0.5; }
+ button.cal-add-btn { background:var(--accent); color:#fff; border:none; border-radius:50%; width:24px; height:24px; line-height:22px; font-size:18px; cursor:pointer; flex-shrink:0; padding:0; box-sizing:border-box; font-family:inherit; vertical-align:middle; text-align:center; }
+ button.cal-add-btn.cal-add-btn-text {
+ width:auto; min-width:0;
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ color: var(--fg);
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ padding: 0 10px 0 6px;
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ height: 24px;
+ line-height: 1;
+ margin-top: 0;
+ transition: background 0.15s, border-color 0.15s;
+ }
+ button.cal-add-btn.cal-add-btn-text:hover {
+ background: color-mix(in srgb, var(--fg) 14%, transparent);
+ border-color: var(--accent);
+ opacity: 1;
+ }
+ .cal-add-plus {
+ font-size: 16px;
+ line-height: 1;
+ color: var(--accent, var(--red));
+ font-weight: 500;
+ display: inline-block;
+ transition: transform 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
+ padding-bottom: 2px;
+ }
+ button.cal-add-btn.cal-add-btn-text:hover .cal-add-plus {
+ transform: rotate(180deg);
+ }
+ .cal-add-label { font-size:11px; font-weight:600; line-height:1; opacity:0.85; }
+ /* Small variant of the toolbar's +New button. Inherits the .cal-add-btn-text
+ styles (pill with "+" + "New" + spring-rotate on the +), so the
+ animation is identical. Just shrunk a bit. */
+ button.cal-add-btn.cal-add-btn-text.cal-add-btn-sm {
+ height: 20px;
+ border-radius: 10px;
+ /* At rest: tight, equal padding around the "+" so it sits centred
+ with no trailing gap. On hover the right pad and the flex gap grow
+ to make room for the revealed "New". */
+ padding: 0 5px;
+ gap: 0;
+ transition: padding 0.25s ease, gap 0.25s ease, background 0.15s, border-color 0.15s;
+ }
+ /* Don't touch .cal-add-plus on the small variant — the toolbar +New is
+ the reference and we want the same rotation centre / motion. The label
+ is shrunk and hidden until hover so the pill is compact at rest. */
+ button.cal-add-btn.cal-add-btn-text.cal-add-btn-sm .cal-add-label {
+ font-size: 10px;
+ max-width: 0;
+ margin-left: 0;
+ opacity: 0;
+ overflow: hidden;
+ white-space: nowrap;
+ transition: max-width 0.25s ease, opacity 0.18s ease, margin-left 0.25s ease;
+ }
+ button.cal-add-btn.cal-add-btn-text.cal-add-btn-sm:hover .cal-add-label {
+ max-width: 40px;
+ margin-left: 3px;
+ opacity: 0.85;
+ }
+ .cal-add-btn:hover { opacity:0.85; }
+
+ /* Mobile: bump the +New pill and the +/- zoom buttons up to a tap-friendly
+ size so they're easy to hit with a thumb. */
+ @media (max-width: 768px) {
+ /* Toolbar +New (relocated by JS into the quickadd row on mobile) */
+ button.cal-add-btn.cal-add-btn-text {
+ height: 36px;
+ border-radius: 18px;
+ padding: 0 14px 0 12px;
+ gap: 6px;
+ flex-shrink: 0;
+ }
+ /* Day-detail +New: just a "+" on mobile — drop the label entirely. */
+ button.cal-add-btn.cal-add-btn-text.cal-add-btn-sm {
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ padding: 0;
+ gap: 0;
+ justify-content: center;
+ }
+ button.cal-add-btn.cal-add-btn-text.cal-add-btn-sm .cal-add-label {
+ display: none;
+ }
+ button.cal-add-btn.cal-add-btn-text.cal-add-btn-sm .cal-add-plus {
+ font-size: 18px;
+ padding-bottom: 0;
+ }
+ .cal-add-plus { font-size: 22px; padding-bottom: 1px; }
+ .cal-add-label { font-size: 13px; }
+ .cal-wk-zoom {
+ width: 36px;
+ height: 36px;
+ font-size: 20px;
+ border-radius: 8px;
+ opacity: 0.85;
+ }
+ /* The +New button sits as a sibling of the quickadd row inside a flex
+ wrapper, so it's clearly outside the input's bordered box. The row
+ itself keeps its own styling. */
+ .cal-quickadd-wrap {
+ display: flex;
+ align-items: stretch;
+ gap: 8px;
+ margin: 0 0 8px;
+ }
+ .cal-quickadd-wrap > #cal-quickadd-row {
+ flex: 1;
+ min-width: 0;
+ margin: 0;
+ }
+ .cal-quickadd-wrap > .cal-add-btn-text {
+ align-self: stretch;
+ flex-shrink: 0;
+ }
+ /* Nudge the "+" glyph up one pixel on the round day-detail button so it
+ sits visually centred inside the circle. */
+ button.cal-add-btn.cal-add-btn-text.cal-add-btn-sm .cal-add-plus {
+ transform: translateY(-1px);
+ }
+ /* Event form: bigger Create / Cancel buttons so they're easy to tap. */
+ .cal-form-actions button.cal-btn {
+ height: 44px;
+ padding: 0 20px;
+ font-size: 14px;
+ border-radius: 8px;
+ min-width: 96px;
+ }
+ /* Left-align the day/month + tags row in the day-detail panel and
+ the calendar/category chip row so they sit flush against the
+ left edge on a narrow screen. */
+ .cal-detail-header {
+ justify-content: flex-start;
+ gap: 12px;
+ }
+ .cal-filters {
+ justify-content: flex-start;
+ }
+ }
+
+ /* Refresh button spin — driven by JS toggling .cal-syncing on the button.
+ transform-box + transform-origin keep the rotation pivoted at the SVG's
+ own centre so it spins in place instead of orbiting / drifting up. */
+ #cal-sync svg,
+ #email-lib-refresh-btn svg { display: block; transform-box: fill-box; transform-origin: 50% 50%; }
+ /* Brief checkmark flash after a refresh completes. Lasts ~900ms in JS;
+ the small bounce + accent color give a clear "done" cue. */
+ #cal-sync.cal-sync-done svg,
+ #email-lib-refresh-btn.email-lib-refresh-done svg {
+ color: var(--accent, #2ea043);
+ animation: refresh-check-pop 0.32s ease-out;
+ }
+ @keyframes refresh-check-pop {
+ 0% { transform: scale(0.55); opacity: 0.4; }
+ 60% { transform: scale(1.18); opacity: 1; }
+ 100% { transform: scale(1); opacity: 1; }
+ }
+ #cal-sync.cal-syncing svg,
+ #email-lib-refresh-btn.email-lib-refreshing svg { animation: spin 0.6s linear infinite; }
+ .email-undone-toggle.active,
+ .email-attach-toggle.active {
+ background: color-mix(in srgb, var(--accent, var(--red)) 18%, transparent);
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 50%, transparent);
+ color: var(--accent, var(--red));
+ font-weight: 600;
+ }
+ /* Hide the gallery-style reader-btn labels on desktop — only the mobile
+ @media block re-displays them under each icon. Desktop keeps compact
+ icon-only reader buttons. */
+ .reader-btn-label {
+ display: inline-block;
+ font-size: 9px;
+ font-weight: 500;
+ line-height: 1;
+ letter-spacing: 0.02em;
+ white-space: nowrap;
+ opacity: 0.85;
+ }
+
+ /* Inline attachment-filter toggle nested inside the search input. The
+ input has padding-right:34px set inline so its text doesn't slide
+ under the button. */
+ .email-search-wrap { display: flex; align-items: center; }
+ /* Keep the email search input and the adjacent "Select" button identical in
+ height regardless of base-vs-mobile overrides — pin both explicitly. */
+ .email-search-row .memory-search-input {
+ height: 32px;
+ min-height: 32px;
+ box-sizing: border-box;
+ }
+ .email-search-row .email-search-select-btn {
+ height: 32px;
+ min-height: 32px;
+ box-sizing: border-box;
+ margin-top: 6px;
+ flex-shrink: 0;
+ }
+ /* Select moved into the dropdown row — dock it to the right and match the
+ selects' vertical nudge (.memory-sort-select has top:3px). */
+ .memory-category-filters .email-filter-select-btn,
+ .memory-category-filters .email-filter-refresh-btn {
+ position: relative;
+ top: 3px;
+ flex-shrink: 0;
+ }
+ .memory-category-filters .email-filter-refresh-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0 8px;
+ }
+ .memory-category-filters .email-reminders-clear-btn {
+ position: relative;
+ top: -2px;
+ flex-shrink: 0;
+ }
+ .email-attach-toggle-inline {
+ position: absolute !important;
+ right: 4px !important;
+ top: 50%;
+ transform: translateY(calc(-50% - 5px));
+ width: 26px !important;
+ height: 26px !important;
+ padding: 0 !important;
+ display: inline-flex !important;
+ align-items: center !important;
+ justify-content: center !important;
+ border-radius: 6px !important;
+ background: transparent !important;
+ border: none !important;
+ opacity: 0.55;
+ }
+ .email-attach-toggle-inline:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--fg) 10%, transparent) !important;
+ }
+ .email-attach-toggle-inline.active {
+ opacity: 1;
+ background: color-mix(in srgb, var(--accent, var(--red)) 16%, transparent) !important;
+ color: var(--accent, var(--red)) !important;
+ }
+ /* Inline undone-toggle nested inside the search input, sits LEFT of the
+ attach toggle. Same visual treatment. */
+ .email-undone-toggle-inline {
+ position: absolute !important;
+ right: 34px !important;
+ top: 50%;
+ transform: translateY(calc(-50% - 3px));
+ width: 26px !important;
+ height: 26px !important;
+ padding: 0 !important;
+ display: inline-flex !important;
+ align-items: center !important;
+ justify-content: center !important;
+ border-radius: 6px !important;
+ background: transparent !important;
+ border: none !important;
+ opacity: 0.55;
+ }
+ .email-reminder-toggle-inline {
+ position: absolute !important;
+ right: 64px !important;
+ top: 50%;
+ transform: translateY(calc(-50% - 3px));
+ width: 26px !important;
+ height: 26px !important;
+ padding: 0 !important;
+ display: inline-flex !important;
+ align-items: center !important;
+ justify-content: center !important;
+ border-radius: 6px !important;
+ background: transparent !important;
+ border: none !important;
+ opacity: 0.55;
+ }
+ .email-reminder-toggle-inline:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--fg) 10%, transparent) !important;
+ }
+ .email-reminder-toggle-inline.active {
+ opacity: 1;
+ background: color-mix(in srgb, var(--accent, var(--red)) 16%, transparent) !important;
+ color: var(--accent, var(--red)) !important;
+ }
+ .email-undone-toggle-inline:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--fg) 10%, transparent) !important;
+ }
+ .email-undone-toggle-inline.active {
+ opacity: 1;
+ background: color-mix(in srgb, var(--accent, var(--red)) 16%, transparent) !important;
+ color: var(--accent, var(--red)) !important;
+ }
+ /* Round (circular) toggles in the search bar, matching the app's default icon
+ buttons. Always fully visible (not dimmed until hover). */
+ .email-attach-toggle-inline,
+ .email-undone-toggle-inline,
+ .email-reminder-toggle-inline { border-radius: 50% !important; opacity: 1 !important; }
+ .email-search-options-btn {
+ position: absolute !important;
+ right: 5px !important;
+ top: 50% !important;
+ transform: translateY(calc(-50% - 5px));
+ width: 26px !important;
+ height: 26px !important;
+ min-width: 26px !important;
+ padding: 0 !important;
+ display: inline-flex !important;
+ align-items: center !important;
+ justify-content: center !important;
+ border-radius: 999px !important;
+ background: transparent !important;
+ border: 0 !important;
+ color: inherit !important;
+ opacity: 0.7;
+ z-index: 2;
+ }
+ .email-search-options-btn:hover,
+ .email-search-options-btn.active {
+ opacity: 1;
+ background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent) !important;
+ color: var(--accent, var(--red)) !important;
+ }
+ .email-search-options-menu {
+ position: absolute;
+ top: calc(100% + 2px);
+ right: 0;
+ z-index: 75;
+ min-width: 140px;
+ padding: 4px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--panel, var(--bg));
+ box-shadow: 0 8px 24px rgba(0,0,0,0.3);
+ }
+ .email-search-options-title {
+ padding: 5px 9px 4px;
+ color: var(--fg-muted, var(--fg));
+ font-size: 10px;
+ font-weight: 600;
+ opacity: 0.65;
+ white-space: nowrap;
+ }
+ .email-search-options-menu button {
+ width: 100%;
+ border: 0;
+ background: transparent;
+ color: var(--fg);
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ height: auto;
+ min-height: 0;
+ padding: 6px 8px;
+ border-radius: 8px;
+ font-family: inherit;
+ font-size: 11px;
+ font-weight: 400;
+ line-height: normal;
+ letter-spacing: normal;
+ text-align: left;
+ cursor: pointer;
+ }
+ .email-search-options-menu button:hover,
+ .email-search-options-menu button.active {
+ background: color-mix(in srgb, var(--accent, var(--red)) 10%, transparent);
+ color: var(--accent, var(--red));
+ }
+ .email-search-option-icon {
+ width: 14px;
+ height: 14px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex: 0 0 auto;
+ opacity: 0.5;
+ }
+ .email-search-option-icon svg { width: 14px; height: 14px; }
+ .email-search-date-panel {
+ width: 220px;
+ padding: 6px 7px 5px;
+ border-top: 1px solid color-mix(in srgb, var(--border) 65%, transparent);
+ }
+ .email-search-date-panel input {
+ width: 100%;
+ height: 26px;
+ box-sizing: border-box;
+ padding: 2px 6px;
+ border: 1px solid var(--border);
+ border-radius: 5px;
+ outline: none;
+ background: var(--bg);
+ color: var(--fg);
+ font: inherit;
+ }
+ .email-search-date-panel input:focus { border-color: var(--accent, var(--red)); }
+ .email-search-date-actions { display: flex; justify-content: flex-end; gap: 5px; }
+ .email-search-options-menu .email-search-date-actions [data-email-date-apply] {
+ color: var(--accent, var(--red));
+ background: color-mix(in srgb, var(--accent, var(--red)) 12%, transparent);
+ }
+ @media (max-width: 768px) {
+ .email-search-options-menu button {
+ min-height: 44px;
+ padding: 12px 12px !important;
+ font-size: 14px !important;
+ gap: 10px !important;
+ }
+ .email-search-options-menu .email-search-option-icon {
+ width: 18px;
+ height: 18px;
+ }
+ .email-search-options-menu .email-search-option-icon svg {
+ width: 16px;
+ height: 16px;
+ }
+ }
+ /* Mobile: enlarge the icons inside the inline search-bar toggles
+ (done / attachment / reminders) — buttons themselves stay the same,
+ only the SVG glyph scales up so it's tappable + visible. */
+ @media (max-width: 768px) {
+ .email-filter-btn {
+ height: 30px;
+ min-height: 30px;
+ font-size: 12px;
+ top: -6px;
+ padding: 0 9px;
+ }
+ .email-folder-btn {
+ top: -4px;
+ }
+
+ #email-lib-folder,
+ .memory-category-filters .email-filter-select-btn,
+ .memory-category-filters .email-filter-refresh-btn,
+ .memory-category-filters .email-filter-settings-btn {
+ height: 30px !important;
+ min-height: 30px !important;
+ box-sizing: border-box;
+ }
+
+ .memory-category-filters .email-filter-refresh-btn,
+ .memory-category-filters .email-filter-settings-btn {
+ width: 30px;
+ padding: 0 !important;
+ }
+ .memory-category-filters .email-filter-settings-btn > svg {
+ width: 15px;
+ height: 15px;
+ }
+
+ .email-search-row .memory-search-input {
+ height: 38px;
+ min-height: 38px;
+ }
+
+ #email-lib-chip-bar {
+ padding-right: 42px !important;
+ padding-left: 30px !important;
+ gap: 5px !important;
+ }
+
+ .email-lib-chip-bar-icon {
+ width: 14px !important;
+ height: 14px !important;
+ left: 9px !important;
+ }
+
+ #email-lib-search {
+ font-size: 14px !important;
+ min-width: 88px !important;
+ top: 0 !important;
+ }
+
+ #email-lib-search::placeholder {
+ font-size: 14px !important;
+ }
+
+ #email-lib-chip-bar.has-email-lib-pills #email-lib-search {
+ min-width: 24px !important;
+ flex: 1 1 24px !important;
+ }
+
+ .email-lib-pill {
+ min-height: 24px !important;
+ height: 24px !important;
+ line-height: 24px !important;
+ font-size: 12px !important;
+ padding: 0 6px 0 8px !important;
+ max-width: 180px !important;
+ }
+
+ .email-lib-pill svg {
+ width: 14px !important;
+ height: 14px !important;
+ }
+
+ .email-lib-pill-x {
+ font-size: 13px !important;
+ top: -4.5px !important;
+ }
+
+ .email-lib-filter-pill {
+ min-height: 24px !important;
+ height: 24px !important;
+ line-height: 24px !important;
+ gap: 4px !important;
+ padding: 0 6px 0 8px !important;
+ }
+
+ .email-lib-filter-pill .email-lib-pill-icon {
+ width: 17px !important;
+ height: 17px !important;
+ }
+
+ .email-lib-filter-pill svg {
+ width: 18px !important;
+ height: 18px !important;
+ }
+
+ .email-lib-filter-pill .email-lib-pill-x {
+ font-size: 13px !important;
+ top: -4.5px !important;
+ }
+
+ .email-tags-toggle-inline {
+ right: 6px;
+ height: 28px !important;
+ min-width: 42px;
+ padding: 0 8px !important;
+ font-size: 11px !important;
+ transform: translateY(calc(-50% - 3px));
+ }
+
+ .email-attach-toggle-inline {
+ right: 56px !important;
+ width: 32px !important;
+ height: 32px !important;
+ transform: translateY(calc(-50% - 3px));
+ }
+
+ .email-undone-toggle-inline {
+ right: 92px !important;
+ width: 32px !important;
+ height: 32px !important;
+ transform: translateY(calc(-50% - 3px));
+ }
+
+ .email-reminder-toggle-inline {
+ right: 128px !important;
+ width: 32px !important;
+ height: 32px !important;
+ transform: translateY(calc(-50% - 3px));
+ }
+
+ .email-attach-toggle-inline svg,
+ .email-undone-toggle-inline svg,
+ .email-reminder-toggle-inline svg,
+ .email-filter-refresh-btn svg {
+ width: 16px !important;
+ height: 16px !important;
+ }
+ }
+ .email-accounts-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 0 0 6px;
+ }
+ .email-accounts-row .doclib-desc { flex-shrink: 0; }
+ /* Only the direct-child compose button gets pushed right; nested chips
+ inside #email-lib-accounts pack to the left as normal flex items. */
+ .email-accounts-row > .memory-toolbar-btn { flex-shrink: 0; margin-left: auto; }
+ .email-account-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ }
+ .email-account-chip.email-account-has-unread {
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 42%, var(--border));
+ background: color-mix(in srgb, var(--accent, var(--red)) 10%, transparent);
+ color: color-mix(in srgb, var(--accent, var(--red)) 86%, var(--fg));
+ }
+ .email-account-unread-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 999px;
+ background: var(--accent, var(--red));
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);
+ flex: 0 0 auto;
+ }
+ .email-account-chip-label {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .email-account-unread-count {
+ font-size: 9px;
+ line-height: 1;
+ font-weight: 700;
+ color: var(--accent, var(--red));
+ opacity: 0.9;
+ position: relative;
+ top: 0;
+ }
+ .email-account-away-label {
+ color: var(--accent, var(--red));
+ font-size: 9px;
+ font-weight: 700;
+ line-height: 1;
+ flex: 0 0 auto;
+ }
+ .email-accounts-loading-whirlpool {
+ width: 14px;
+ height: 14px;
+ margin: 3px 4px 0 1px;
+ display: inline-flex;
+ flex: 0 0 auto;
+ }
+ .email-accounts-loading-label {
+ font-size: 10px;
+ opacity: 0.55;
+ position: relative;
+ top: 2px;
+ white-space: nowrap;
+ }
+ .email-loading-with-label {
+ /* Fill the email list grid so the spinner lands in the middle of the
+ email window rather than the top of the empty list section. */
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ text-align: center;
+ pointer-events: none;
+ }
+ .date-section-header {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding: 8px 9px 4px;
+ color: color-mix(in srgb, var(--fg) 58%, transparent);
+ font-size: 10px;
+ font-weight: 700;
+ letter-spacing: 0;
+ line-height: 1.2;
+ text-transform: uppercase;
+ user-select: none;
+ }
+ .date-section-header::after {
+ content: '';
+ flex: 1 1 auto;
+ height: 1px;
+ background: color-mix(in srgb, var(--border) 72%, transparent);
+ }
+ #session-list .date-section-header {
+ padding-left: 10px;
+ padding-right: 8px;
+ cursor: pointer;
+ }
+ #session-list .date-section-header.collapsed {
+ color: color-mix(in srgb, var(--fg) 36%, transparent);
+ }
+ #session-list .date-section-header.collapsed::after {
+ opacity: 0.45;
+ }
+ #session-list .date-section-header:focus-visible {
+ outline: 1px solid color-mix(in srgb, var(--accent) 45%, transparent);
+ outline-offset: 2px;
+ border-radius: 5px;
+ }
+ /* Bootstrap row shown while the session list hydrates, and on load failure.
+ Reads as a normal list row but is not selectable. */
+ .session-list-bootstrap {
+ cursor: default;
+ pointer-events: none;
+ }
+ #email-lib-grid .date-section-header {
+ padding: 10px 5px 3px;
+ }
+ #email-lib-modal .email-lib-sync-status {
+ flex: 0 0 auto;
+ min-height: 14px;
+ padding: 1px 4px 0;
+ font-size: 10.5px;
+ line-height: 1.2;
+ text-align: center;
+ opacity: 0.58;
+ color: var(--muted-text, currentColor);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ position: relative;
+ top: 4px;
+ }
diff --cc static/css/documents-gallery-editor.css
index 000000000,cc37362bb..702bb331a
mode 000000,100644..100644
--- a/static/css/documents-gallery-editor.css
+++ b/static/css/documents-gallery-editor.css
@@@ -1,0 -1,960 +1,980 @@@
+ /* Document library and editor, image gallery, image editor.
+ *
+ * This is an eagerly loaded tail segment of the app stylesheet cascade. The
+ * former static/style.css now lives in the numbered 00-17 fragments; these
+ * three pre-existing panel files follow those fragments without changing
+ * their relative order. Nothing here is lazy-loaded.
+ *
+ * LOAD ORDER IS PART OF THE CONTRACT. static/index.html and the PRECACHE list
+ * in static/sw.js must agree:
+ * 1. static/css/00-tokens.css through static/css/17-research.css,
+ * in numeric order
+ * 2. static/css/documents-gallery-editor.css
+ * 3. static/css/email-calendar-notes-tasks.css
+ * 4. static/css/cookbook-research-memory-settings.css
+ *
+ * Rules in this file retain their existing cascade position. Shared rules
+ * formerly kept in static/style.css now live in the numbered fragments.
+ */
+
+ /* Document library search-term highlight — clear, high-contrast. */
+ mark.doclib-search-hl {
+ background: var(--accent, #e8a830);
+ color: var(--bg, #1a1a1a);
+ border-radius: 2px;
+ padding: 0 2px;
+ font-weight: 600;
+ }
+ /* Research bulk bar — right-align the action buttons (keep All + count on
+ the left). Cancel now lives on the Select toggle, so Archive anchors. */
+ #doclib-research-bulk #doclib-research-bulk-archive {
+ margin-left: auto;
+ }
+ /* Drafts bulk bar defaults to justify-content:flex-end (whole row hugs the
+ right). Reset it so All + count sit on the left and only the action button
+ is pushed right — matching every other bulk bar. */
+ #gallery-editor-drafts-bulk {
+ justify-content: flex-start;
+ }
+ .doc-divider.doc-divider-handle-idle .doc-divider-collapse {
+ opacity: 0;
+ pointer-events: none;
+ }
+ .doc-divider:hover .doc-divider-collapse { opacity: 0.92; }
+ /* Smooth entrance — slide in from the left + fade up so it doesn't snap into
+ place when fullscreen activates. The chevron's vertical centering uses
+ translateY(-50%), so the animation has to keep that part. */
+ @keyframes doc-fs-chevron-in {
+ from { opacity: 0; transform: translateY(-50%) translateX(-18px); }
+ to { opacity: 0.85; transform: translateY(-50%) translateX(0); }
+ }
+ .doc-editor-pane.doc-pane-leaving {
+ pointer-events: none;
+ }
+ @keyframes doc-pane-leave {
+ from { transform: translateX(0); opacity: 1; }
+ to { transform: translateX(24px); opacity: 0; }
+ }
+ .doc-tab-scroll.is-at-left {
+ -webkit-mask-image: linear-gradient(to right, #000 0, #000 calc(100% - 18px), transparent 100%);
+ mask-image: linear-gradient(to right, #000 0, #000 calc(100% - 18px), transparent 100%);
+ }
+ .doc-tab-scroll.is-at-right {
+ -webkit-mask-image: linear-gradient(to right, transparent 0, #000 18px, #000 100%);
+ mask-image: linear-gradient(to right, transparent 0, #000 18px, #000 100%);
+ }
+ .doc-tab-scroll.is-at-left.is-at-right {
+ -webkit-mask-image: none;
+ mask-image: none;
+ }
+ .doc-tab-scroll::-webkit-scrollbar { display: none; }
+ #doc-tab-right,
+ #doc-tab-left {
+ position: relative;
+ top: 3px;
+ }
+ /* Ghost tab shown in the empty state (new, not-yet-saved document). Muted +
+ italic so it reads as a placeholder, and non-interactive so clicking it
+ can't hit the tab handlers (it has no data-doc-id). */
+ .doc-tab.doc-tab-ghost {
+ /* New, not-yet-saved doc tab. It already carries .active, so it shows the
+ accent underline like any active tab — that's all we want. The old dashed
+ border + italic/dim "pending" styling looked weird, so they're gone. */
+ pointer-events: none;
+ }
+ .doc-tab.active::after {
+ content: '';
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ height: 2px;
+ background: var(--red);
+ }
+ @keyframes doc-stream-pulse {
+ 0%, 100% { opacity: 0.5; }
+ 50% { opacity: 1; }
+ }
+ .doc-updated-flash {
+ animation: doc-update-flash 0.6s ease-out;
+ }
+ @keyframes doc-update-flash {
+ 0% { box-shadow: inset 0 0 0 2px var(--accent); }
+ 100% { box-shadow: inset 0 0 0 2px transparent; }
+ }
+ .doc-langpicker-trigger.doc-langpicker-email-compact {
+ width: 28px;
+ min-width: 28px;
+ padding: 0 0 0 6px;
+ justify-content: flex-start;
+ gap: 0;
+ }
+ /* The "T" icon stays centered in the fixed-size button so it grows
+ symmetrically (from the center) instead of jumping around as the size
+ changes. The S/M/L letter is pinned to the bottom-right corner, absolutely
+ positioned so it never shifts the icon either. */
+ #doc-fontsize-btn { transform: translateY(-1px); }
+ #doc-fontsize-btn svg { flex: 0 0 auto; }
+ .doc-overflow-wrapper { order: -1; }
+ .doc-overflow-toggle { opacity: 0.5; }
+ .doc-md-toolbar.md-preview-active,
+ .doc-md-toolbar.md-write-active {
+ overflow: visible;
+ -webkit-mask-image: none;
+ mask-image: none;
+ z-index: 3;
+ }
+ .doc-md-toolbar #doc-render-view-toggle .md-view-opt {
+ height: 28px;
+ }
+ /* Some toolbar buttons baked in svg{opacity:0.7} via inline styles, which
+ compounded with the button's own opacity to look almost invisible.
+ Force the inline svg opacity back to 1 inside the toolbar — the button
+ wrapper's 0.85 is the only fade we need. */
+ .doc-md-toolbar button svg[style*="opacity"] { opacity: 1 !important; }
+ /* No black tap-flash / focus background on the doc toolbar + tab controls —
+ they're icon buttons, the opacity change is the only feedback we want. */
+ .doc-md-toolbar button,
+ .doc-tab-new,
+ .doc-tab-arrow,
+ .doc-tab-play {
+ -webkit-tap-highlight-color: transparent;
+ }
+ /* Pull the icon down toward the "sign" label so they read as one unit. */
+ #doc-pdf-add-sign-btn svg { transform: translateY(2px); }
+ .doc-outline-count {
+ opacity: 0.48;
+ font-variant-numeric: tabular-nums;
+ }
+ .doc-outline-target {
+ animation: doc-outline-target-flash 1.05s ease-out;
+ }
+ @keyframes doc-outline-target-flash {
+ 0%, 28% { background-color: color-mix(in srgb, var(--accent, var(--red)) 24%, transparent); }
+ 100% { background-color: transparent; }
+ }
+ .doc-rich-slash-count {
+ opacity: 0.48;
+ font-variant-numeric: tabular-nums;
+ }
+ .doc-rich-slash-label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ /* Find marks live in the syntax-highlight overlay, which sits at
+ z-index:0 under a transparent textarea — so they're always visible
+ through the text layer. The previous color-mix variant could
+ compute to near-invisible on themes with dark/desaturated accents;
+ forced solid colors + !important so it ALWAYS pops. */
+ mark.doc-find-mark {
+ background: var(--accent) !important;
+ color: var(--bg) !important;
+ border-radius: 2px;
+ padding: 0 1px;
+ box-shadow: 0 0 0 1px var(--accent);
+ }
+ .doc-editor-highlight::-webkit-scrollbar { display: none; }
+ /* Arrow pointing toward the editor */
+ .doc-suggestion-card::before {
+ content: '';
+ position: absolute;
+ top: 16px;
+ left: -10px;
+ width: 18px;
+ height: 18px;
+ background: var(--panel);
+ border-left: 2px solid var(--accent);
+ border-bottom: 2px solid var(--accent);
+ transform: rotate(45deg);
+ z-index: 1;
+ }
+ .doc-suggestion-close::before {
+ content: '';
+ width: 10px;
+ height: 10px;
+ display: block;
+ background: currentColor;
+ -webkit-mask: url("data:image/svg+xml,%3Csvg width='10' height='10' viewBox='0 0 10 10' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M2 2L8 8M8 2L2 8' stroke='black' stroke-width='1.8' stroke-linecap='round'/%3E%3C/svg%3E") center / contain no-repeat;
+ mask: url("data:image/svg+xml,%3Csvg width='10' height='10' viewBox='0 0 10 10' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M2 2L8 8M8 2L2 8' stroke='black' stroke-width='1.8' stroke-linecap='round'/%3E%3C/svg%3E") center / contain no-repeat;
+ }
+ .doc-suggestion-accept:hover {
+ filter: brightness(1.15);
+ }
+ .doc-editor-wrap.animating::after {
+ content: '';
+ position: absolute;
+ top: 6px; right: 8px;
+ width: 6px; height: 6px;
+ border-radius: 50%;
+ background: var(--red);
+ animation: doc-pulse 0.8s ease-in-out infinite;
+ z-index: 3;
+ pointer-events: none;
+ }
+ @keyframes doc-pulse {
+ 0%, 100% { opacity: 0.3; transform: scale(0.8); }
+ 50% { opacity: 1; transform: scale(1.2); }
+ }
+ .doc-diff-content { }
+ @media (hover: none) {
+ .doc-preview-hover-edit {
+ opacity: 1;
+ pointer-events: auto;
+ transform: none;
+ }
+ }
+ #doclib-research-search { position: relative; top: -1.5px; }
+ /* Restore sits on the right of the Delete in archive previews. */
+ .doclib-chat-restore-btn { margin-left: auto; }
+ /* Delete + Archive pin to the left of the actions row; the
+ `margin-right: auto` on the last left-side button (Archive) pushes
+ Copy + Open to the right. Delete sits furthest left. */
+ .doclib-chat-archive-btn { margin-right: auto; }
+ @keyframes doclib-expand {
+ from { opacity: 0.5; transform: translateY(4px); }
+ to { opacity: 1; transform: translateY(0); }
+ }
+ /* Hide the section headers while a card is expanded (full-screen reader). */
+ .doclib-grid:has(.doclib-card-expanded) > .skills-section-header { display: none; }
+ .skill-card:not(.doclib-card-expanded) .skill-card-tags { display: none; }
+ .doclib-chip-scroll-frame > .chip-scroll-strip:empty {
+ display: none;
+ }
+ .skill-card.doclib-card-expanded .skill-kebab-btn { display: none; }
+ .skill-card.doclib-card-expanded .skill-chevron-up { display: inline-flex; }
+ /* Size the expanded skill card to its content (footer sits right under the
+ preview) but cap at the modal height so a long SKILL.md scrolls instead
+ of overflowing. The inherited `.doclib-card-expanded { flex: 1 }` forced
+ the card to fill the whole modal, which left a big empty void between a
+ short skill's text and the footer. */
+ .skill-card.doclib-card-expanded {
+ flex: 0 1 auto !important;
+ max-height: 100% !important;
+ }
+ .doclib-inline-load-more::before {
+ display: none;
+ }
+ #doclib-selected-count {
+ color: color-mix(in srgb, var(--fg) 50%, transparent);
+ font-size: 10px;
+ }
+ .gallery-modal-content:has(#gallery-editor-container[style*="flex"]) .gallery-editor-landing {
+ width: 100%;
+ min-height: 0;
+ box-sizing: border-box;
+ }
+ #gallery-bulk-count,
+ #gallery-editor-drafts-bulk-count {
+ top: -1px !important;
+ }
+ #gallery-select-btn { position: relative; top: 4px !important; font-size: 12px; padding: 10px 11px 12px; min-width: 76px; justify-content: center; }
+ #gallery-albums-search { top: -4px; }
+ #gallery-albums-select-btn { top: -4px !important; }
+ #gallery-bulk-delete,
+ #gallery-albums-bulk-delete,
+ #gallery-editor-drafts-bulk-delete {
+ color: var(--color-error, #f44) !important;
+ }
+ .gallery-detail-image video {
+ max-width: 100%;
+ max-height: 70vh;
+ display: block;
+ }
+ .gallery-card:hover .gallery-fav-btn { opacity: 1; }
+ .gallery-card:hover .gallery-dl-btn { opacity: 1; }
+ @media (hover: none) {
+ .gallery-dl-btn { opacity: 0.55; }
+ }
+ /* Space the user's tag chips off the "add tag" input below them. */
+ #gallery-user-tag-chips { margin-bottom: 4px; }
+ .gallery-user-chip:hover .gallery-tag-x { opacity: 0.85; }
+ @keyframes gallery-skeleton-shimmer {
+ 0% { background-position: 200% 0; }
+ 100% { background-position: -200% 0; }
+ }
+ .gallery-card:hover .gallery-card-overlay,
+ .gallery-card.gallery-card-focus .gallery-card-overlay {
+ opacity: 1;
+ }
+ /* Strong accent ring on the whole photo when selected. Paint it as a
+ foreground pseudo-element so the thumbnail cannot cover the feedback. */
+ .gallery-card:has(.gallery-select-dot.selected) {
+ border-color: var(--accent-primary, var(--red));
+ }
+ .gallery-card:has(.gallery-select-dot.selected)::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ z-index: 3;
+ border: 3px solid var(--accent-primary, var(--red));
+ border-radius: inherit;
+ box-sizing: border-box;
+ pointer-events: none;
+ }
+ .gallery-card:has(.gallery-select-dot.selected) .gallery-select-dot {
+ z-index: 4;
+ }
+ .gallery-detail-action.danger:hover {
+ border-color: var(--color-error, #e55);
+ }
+ .gallery-detail-image img,
+ .gallery-detail-image video,
+ .gallery-detail-img-frame img,
+ .gallery-detail-img-frame video {
+ max-width: 100%;
+ max-height: 100%;
+ border-radius: 6px;
+ object-fit: contain;
+ display: block;
+ }
+ .gallery-detail-image:hover .gallery-detail-nav { opacity: 0.85; }
+ @media (min-width: 769px) {
+ .gallery-modal-content:has(#gallery-detail[style*="flex"]) {
+ height: 92vh;
+ }
+ .gallery-modal-content:has(#gallery-detail[style*="flex"]) > .modal-body,
+ .gallery-images-container:has(> #gallery-detail[style*="flex"]),
+ #gallery-images-container:has(> #gallery-detail[style*="flex"]) > #gallery-detail {
+ height: 100%;
+ min-height: 0;
+ }
+ }
+ .gallery-detail-image:hover .gallery-detail-rotate { opacity: 0.85; }
+ .gallery-detail-nav-disabled {
+ opacity: 0 !important;
+ pointer-events: none;
+ }
+ @media (hover: none) {
+ .gallery-detail-nav { opacity: 0.7; }
+ }
+ .gallery-detail-inline-link:hover { text-decoration: underline; }
+ .gallery-detail-section {
+ margin-bottom: 12px;
+ }
+ .gallery-tag-input-wrap .gallery-tag-input { padding-right: 24px; }
+ .gallery-name-wrap:focus-within .gallery-name-enter { display: inline-flex; }
+ .gallery-name-wrap:focus-within .gallery-detail-name-input { padding-right: 28px; }
+ .gallery-album-cover img {
+ width: 100%; height: 100%;
+ object-fit: cover;
+ display: block;
+ }
+ .gallery-editor-landing p {
+ margin: 0;
+ opacity: 0.6;
+ font-size: 13px;
+ max-width: 320px;
+ }
+ .gallery-editor-landing-actions .gallery-select-btn:hover { opacity: 1; }
+ /* Saved-project selection uses the same bulk-bar rhythm as Photos. */
+ #gallery-editor-drafts-bulk {
+ margin-top: 0;
+ }
+ .gallery-editor-draft-card.selected {
+ outline: 2px solid var(--accent, var(--red));
+ outline-offset: -2px;
+ }
+ .gallery-editor-draft-card.select-mode { cursor: pointer; }
+ .gallery-drafts-view-toggle button svg {
+ display: block;
+ position: static;
+ transform: none;
+ }
+ .gallery-editor-drafts-grid.list-view {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .gallery-editor-drafts-grid.list-view .gallery-editor-draft-card {
+ display: grid;
+ grid-template-columns: 44px minmax(0, 1fr) 24px;
+ align-items: center;
+ gap: 9px;
+ min-height: 48px;
+ padding: 4px 6px;
+ }
+ .gallery-editor-drafts-grid.list-view .gallery-editor-draft-delete-x { display: none; }
+ .gallery-editor-draft-card:focus-visible {
+ outline: 2px solid var(--accent, var(--red));
+ outline-offset: 2px;
+ }
+ .gallery-editor-draft-card:hover .gallery-editor-draft-delete { opacity: 1; }
+ .ge-topbar.ge-topbar-menu-open { z-index: 10006; }
+ /* Toolbar (left) */
+ @keyframes ge-layer-action-flash {
+ from { box-shadow: inset 0 0 0 2px var(--red); background-color: color-mix(in srgb, var(--red) 24%, transparent); }
+ to { box-shadow: inset 0 0 0 2px transparent; }
+ }
+ .ge-layer-action-flash { animation: ge-layer-action-flash 650ms ease-out; }
+ @media (prefers-reduced-motion: reduce) {
+ .ge-layer-action-flash { animation-duration: 1ms; }
+ }
+ .ge-tool-btn .ge-tool-label {
+ max-width: 100%;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .ge-tool-btn:hover::after {
+ content: '';
+ position: absolute;
+ inset: 0 2px 0 -2px;
+ background: color-mix(in srgb, var(--fg) 8%, transparent);
+ border-radius: 6px;
+ z-index: -1;
+ pointer-events: none;
+ }
+ .ge-tool-btn.active::before {
+ content: '';
+ position: absolute;
+ /* Highlight pill shifted 2 px left of the button bounds so it sits
+ under the icon + label (which are also nudged left). Same total
+ width as before — just slid. */
+ inset: 0 2px 0 -2px;
+ background: color-mix(in srgb, var(--red) 18%, transparent);
+ border-radius: 6px;
+ z-index: 0;
+ pointer-events: none;
+ }
+ .ge-btn-ai:hover .ge-btn-ai-mark { opacity: 1; }
+ .ge-tool-btn.has-selection .ge-tool-clear { display: inline-flex; }
+ .ge-canvas-area.ge-rulers-visible {
+ padding: 18px 0 0 18px;
+ box-sizing: border-box;
+ }
+ .ge-main-canvas {
+ touch-action: none;
+ }
+ .ge-canvas-area.ge-pan-ready,
+ .ge-canvas-area.ge-pan-ready .ge-main-canvas {
+ cursor: grab !important;
+ }
+ .ge-canvas-area.ge-panning,
+ .ge-canvas-area.ge-panning .ge-main-canvas {
+ cursor: grabbing !important;
+ user-select: none;
+ }
+ .ge-ai-command-collapsed .ge-ai-command-toggle {
+ display: inline-flex;
+ }
+ .ge-ai-command-collapsed .ge-ai-command-head,
+ .ge-ai-command-collapsed .ge-ai-command-form,
+ .ge-ai-command-collapsed .ge-ai-command-suggestions,
+ .ge-ai-command-collapsed .ge-ai-command-status {
+ display: none;
+ }
+ @media (hover: none) {
+ .ge-ai-command-collapsed {
+ bottom: 8px;
+ opacity: 0.72;
+ }
+ }
+ .ge-ai-command-clear[hidden] {
+ display: none;
+ }
+ .ge-ai-command-busy .ge-ai-command-run::after {
+ content: '';
+ width: 12px;
+ height: 12px;
+ border: 2px solid color-mix(in srgb, #fff 42%, transparent);
+ border-top-color: #fff;
+ border-radius: 50%;
+ animation: ge-ai-command-spin 0.7s linear infinite;
+ }
+ @keyframes ge-ai-command-spin {
+ to { transform: rotate(360deg); }
+ }
+ .ge-ai-command-suggestions[hidden] {
+ display: none;
+ }
+ .ge-ai-command-status:empty {
+ display: none;
+ }
+ /* Each shortcut row: key chips + description. The key chips are usually
+ chained with "+" so we use a small horizontal gap between siblings,
+ plus a larger left margin on the trailing text via the kbd:last-of-type
+ sibling rule — keeps "Ctrl+Shift+D Deselect" readable instead of glued. */
+ .ge-shortcuts-col > div {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 4px;
+ padding: 4px 0;
+ opacity: 0.85;
+ line-height: 1.5;
+ }
+ /* Push the description text away from the last kbd by adding margin
+ to any text node that follows a kbd. Flex+wrap handles wrap on narrow. */
+ .ge-shortcuts-col > div kbd + kbd { margin-left: 0; }
+ .ge-shortcuts-col > div kbd:last-of-type { margin-right: 6px; }
+ .ge-shortcuts-card kbd,
+ #ge-shortcuts-popover kbd {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 10px;
+ font-weight: 600;
+ padding: 2px 6px;
+ border: 1px solid color-mix(in srgb, var(--accent, #cc6a3a) 55%, transparent);
+ border-bottom-width: 2px;
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--accent, #cc6a3a) 14%, transparent);
+ color: var(--accent, #cc6a3a);
+ min-width: 18px;
+ line-height: 1.4;
+ }
+ .ge-quick-mask-bar[hidden] { display: none; }
+ .ge-marquee-dimensions[hidden] { display: none; }
+ .ge-layer-geometry-section .ge-section-title {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ }
+ .ge-layer-geometry-grid input::-webkit-inner-spin-button,
+ .ge-layer-geometry-grid input::-webkit-outer-spin-button { appearance: none; }
+ #ge-brush-controls select,
+ #ge-eyedropper-section select {
+ height: 26px;
+ min-width: 0;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--fg);
+ font: inherit;
+ }
+ .ge-gradient-extra-stop .ge-text-field { min-width: 0; }
+ .ge-shape-gradient-add-stop { align-self: flex-start; }
+ .ge-text-font-field { grid-column: span 1; }
+ #ge-text-rasterize { align-self: flex-end; }
+ .ge-shape-types .ge-text-toggle { flex: 1 1 25%; }
+ #ge-shape-rasterize { align-self: flex-end; }
+ .ge-direct-text-editor:focus { outline: 1px solid color-mix(in srgb, var(--red) 55%, transparent); }
+ .ge-transform-popup.ge-transform-popup-dragging .ge-transform-popup-head { cursor: grabbing; }
+ /* Force the title to take all middle space so the [_][×] cluster
+ stays pinned to the right edge. */
+ .ge-transform-popup-head .ge-adj-title { flex: 1 1 auto !important; }
+ .ge-transform-popup-minimised .ge-transform-popup-body,
+ .ge-transform-popup-minimised .ge-transform-popup-hint {
+ display: none;
+ }
+ .ge-transform-popup-input::-webkit-outer-spin-button,
+ .ge-transform-popup-input::-webkit-inner-spin-button {
+ -webkit-appearance: none;
+ appearance: none;
+ margin: 0;
+ display: none;
+ }
+ .ge-transform-position-field .ge-transform-popup-input { width: 68px; }
+ .ge-transform-input-locked {
+ opacity: 0.4;
+ cursor: not-allowed;
+ }
+ .ge-transform-input-locked + .ge-transform-spin { display: none; }
+ .ge-transform-preserve-field[hidden] { display: none; }
+ /* Hide the controls wrapper entirely when every tool section inside is
+ hidden — otherwise the padding + border draws an empty band above the
+ layers panel even when no tool needs sliders/buttons. */
+ .ge-controls:not(:has(> *:not([style*="display: none"]):not([style*="display:none"]))) {
+ display: none;
+ }
+ /* Strip the native <input type="color"> chrome (border + padding around
+ the swatch in each engine) so the visible color fills the circle. */
+ .ge-color-picker::-webkit-color-swatch-wrapper { padding: 0; }
+ .ge-color-picker::-webkit-color-swatch {
+ border: none;
+ border-radius: 50%;
+ }
+ .ge-color-picker::-moz-color-swatch {
+ border: none;
+ border-radius: 50%;
+ }
+ .ge-color-picker.cp-swatch-input::selection { background: transparent; }
+ .ge-size-slider::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 9px; height: 9px;
+ border-radius: 50%;
+ background: var(--red);
+ border: none; cursor: pointer;
+ }
+ .ge-size-slider:hover::-webkit-slider-thumb,
+ .ge-size-slider.is-using::-webkit-slider-thumb,
+ .ge-size-slider:active::-webkit-slider-thumb {
+ width: 16px; height: 16px;
+ }
+ .ge-size-slider::-moz-range-thumb {
+ width: 9px; height: 9px;
+ border-radius: 50%;
+ background: var(--red);
+ border: none; cursor: pointer;
+ }
+ .ge-size-slider:hover::-moz-range-thumb,
+ .ge-size-slider.is-using::-moz-range-thumb,
+ .ge-size-slider:active::-moz-range-thumb {
+ width: 16px; height: 16px;
+ }
+ .ge-eraser-row label > span[id$="-label"]:hover {
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ }
+ .ge-eraser-row > span[id$="-label"].ge-slider-value:hover {
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ opacity: 1;
+ }
+ .ge-merge-menu[hidden] { display: none; }
+ /* Inpaint Brush size slider — slightly larger thumb than the rest of
+ the panel since it's the primary interactive control. */
+ #ge-inpaint-brush-slider::-webkit-slider-thumb { width: 12px; height: 12px; }
+ #ge-inpaint-brush-slider:hover::-webkit-slider-thumb,
+ #ge-inpaint-brush-slider.is-using::-webkit-slider-thumb,
+ #ge-inpaint-brush-slider:active::-webkit-slider-thumb { width: 18px; height: 18px; }
+ #ge-inpaint-brush-slider::-moz-range-thumb { width: 12px; height: 12px; }
+ #ge-inpaint-brush-slider:hover::-moz-range-thumb,
+ #ge-inpaint-brush-slider.is-using::-moz-range-thumb,
+ #ge-inpaint-brush-slider:active::-moz-range-thumb { width: 18px; height: 18px; }
+ .ge-adj-popup .ge-adj-title { flex: 1 1 auto; }
+ .ge-adj-popup .ge-adj-head:active { cursor: grabbing; }
+ .ge-fx-dock-label { overflow: hidden; text-overflow: ellipsis; }
+ .ge-history-head:active { cursor: grabbing; }
+ @keyframes ge-canvas-spin { to { transform: rotate(360deg); } }
+ .ge-inline-swatch::-webkit-color-swatch-wrapper { padding: 0; }
+ .ge-inline-swatch::-webkit-color-swatch { border: none; border-radius: 2px; }
+ .ge-inline-swatch::-moz-color-swatch { border: none; border-radius: 2px; }
+ .ge-adj-cb-row .ge-adj-cb-dot {
+ width: 10px; height: 10px; border-radius: 50%;
+ display: inline-block; flex-shrink: 0;
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--fg) 20%, transparent);
+ }
+ .ge-adj-cb-tone-picker {
+ margin: 0 0 8px;
+ }
+ .ge-adj-hist-details {
+ margin-bottom: 8px;
+ }
+ .ge-adj-hist-details > summary {
+ font-size: 11px;
+ color: var(--fg-muted);
+ cursor: pointer;
+ padding: 4px 0;
+ list-style: none;
+ user-select: none;
+ }
+ .ge-adj-hist-details > summary::-webkit-details-marker { display: none; }
+ .ge-adj-hist-details > summary::before {
+ content: '▸ ';
+ display: inline-block;
+ transition: transform 0.12s;
+ }
+ .ge-mask-sub-item.active .ge-layer-name { opacity: 1; font-style: normal; font-weight: 600; }
+ .ge-mask-sub-item.active .ge-mask-inline-thumb { opacity: 1; }
+ /* Opacity preview — translucent disk */
+ #ge-eraser-preview-opacity { opacity: 0.5; }
+ /* Flow preview — dotted ring to suggest discrete stamping */
+ #ge-eraser-preview-flow {
+ background: none;
+ border: 2px dotted var(--fg);
+ opacity: 0.7;
+ width: 12px;
+ height: 12px;
+ }
+ /* Softness preview — blurred edge */
+ #ge-eraser-preview-softness {
+ background: radial-gradient(circle, var(--fg) 0%, var(--fg) 30%, transparent 75%);
+ opacity: 0.7;
+ }
+ /* Wand feather preview — solid disk that visibly softens at its edge
+ as the user drags the Feather slider. JS sets --feather-blur. */
+ #ge-wand-feather-preview {
+ filter: blur(var(--feather-blur, 0px));
+ opacity: 0.8;
+ }
+ .ge-mask-vis-btn.visible:hover { opacity: 1; }
+ .ge-topbar .ge-btn,
+ .ge-topbar .ge-btn-sm { text-transform: uppercase; }
+ .ge-stacked-btn .ge-stacked-glyph {
+ font-size: 14px;
+ line-height: 1;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ height: 14px;
+ }
+ .ge-layer-selection-bar[hidden] { display: none; }
+ .ge-layer-selection-bar .ge-icon-btn:hover { opacity: 1; }
+ .ge-save-menu[hidden] { display: none; }
+ .ge-stacked-btn .ge-stacked-glyph .ge-save-state-icon[hidden] { display: none !important; }
+ .ge-stacked-btn .ge-stacked-glyph .ge-save-state-icon:not([hidden]) { display: block; }
+ .ge-resize-menu[hidden],
+ .ge-edge-menu[hidden],
+ .ge-view-menu[hidden],
+ .ge-image-menu[hidden],
+ .ge-selection-menu[hidden],
+ .ge-filter-menu[hidden] { display: none; }
+ .ge-selection-save-row .ge-icon-btn { width: 28px; height: 27px; }
+ .ge-export-matte .ge-color-picker { width: 28px; height: 28px; }
+ .ge-export-footer > div { display: flex; gap: 6px; }
+ .ge-export-estimate { opacity: 0.6; font-variant-numeric: tabular-nums; }
+ .ge-canvas-prompt-custom-label { margin-top: 14px; }
+ .ge-canvas-anchor::after {
+ content: '';
+ position: absolute;
+ inset: 6px;
+ border-radius: 1px;
+ background: color-mix(in srgb, var(--fg) 38%, transparent);
+ }
+ .ge-canvas-anchor.active::after { background: var(--red); }
+ .ge-canvas-lock-option input { accent-color: var(--red); }
+ .ge-canvas-preset-icon { margin-bottom: 1px; }
+ /* Center grip dots so the handle reads as draggable. */
+ .ge-panel-resize::before {
+ content: '';
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ width: 2px;
+ height: 24px;
+ background: color-mix(in srgb, var(--fg) 35%, transparent);
+ border-radius: 2px;
+ }
+ .ge-slider-bubble[hidden] { display: none; }
+ /* Tail pointing DOWN at the slider (bubble sits above). */
+ .ge-slider-bubble::after {
+ content: '';
+ position: absolute;
+ left: 50%;
+ bottom: -4px;
+ transform: translateX(-50%);
+ width: 8px;
+ height: 8px;
+ background: var(--red);
+ clip-path: polygon(0 0, 100% 0, 50% 100%);
+ }
+ .ge-layer-thumb canvas {
+ display: block;
+ border-radius: 4px;
+ }
+ .ge-layers-merge-menu[hidden] { display: none; }
+ .ge-layer-item:not(.active) .ge-layer-inline-thumb { opacity: 0.86; }
+ .ge-layer-opacity-row .ge-layer-lock-btn { flex: 0 0 24px; width: 24px; }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-controls {
+ grid-column: 1 / -1;
+ grid-row: 3;
+ }
+ .ge-layer-item.grouped { padding-left: calc(20px + (var(--layer-group-depth, 1) - 1) * 14px); }
+ .ge-layer-vis.visible:hover { opacity: 1; }
+ .ge-layer-item.clipped .ge-layer-name {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ }
+ /* Shrink the slider thumb — the native default is ~16-20 px which looks
+ massive next to a 3 px track in the compact layer row. */
+ .ge-layer-opacity::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 9px;
+ height: 9px;
+ border-radius: 50%;
+ background: var(--red);
+ border: none;
+ cursor: pointer;
+ /* Match the track: shrink only after a 0.5s grace period. */
+ transition: width 0.12s ease 0.5s, height 0.12s ease 0.5s;
+ }
+ .ge-layer-opacity::-moz-range-thumb {
+ width: 9px;
+ height: 9px;
+ border-radius: 50%;
+ background: var(--red);
+ border: none;
+ cursor: pointer;
+ transition: width 0.12s ease 0.5s, height 0.12s ease 0.5s;
+ }
+ .ge-layer-opacity:hover::-webkit-slider-thumb,
+ .ge-layer-opacity:active::-webkit-slider-thumb,
+ .ge-layer-opacity.dragging::-webkit-slider-thumb,
+ .ge-layer-opacity:hover::-moz-range-thumb,
+ .ge-layer-opacity:active::-moz-range-thumb,
+ .ge-layer-opacity.dragging::-moz-range-thumb {
+ transition: width 0.12s ease 0s, height 0.12s ease 0s;
+ }
+ .ge-layer-controls .ge-mask-density {
+ width: 26px;
+ min-width: 24px;
+ height: 4px;
+ flex: 0 0 26px;
+ align-self: center;
+ }
+ .ge-mask-properties > summary {
- width: 30px;
- height: 30px;
++ box-sizing: border-box;
++ width: 22px;
++ height: 22px;
++ padding: 0;
++ min-height: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ list-style: none;
+ cursor: pointer;
+ color: var(--fg);
- border: 1px solid transparent;
++ opacity: 0.4;
++ background: none;
++ border: none;
+ border-radius: 4px;
++ transition: opacity 0.1s;
+ }
+ .ge-mask-properties > summary::-webkit-details-marker { display: none; }
++.ge-mask-properties > summary > svg { width: 12px; height: 12px; flex: none; }
+ .ge-mask-sub-item:has(.ge-mask-properties[open]) {
+ position: relative;
+ z-index: 50;
+ }
+ .ge-mask-property-row output { text-align: right; opacity: .7; }
+ .ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item) > .ge-layer-controls,
+ .ge-layers-list > .ge-layer-group-row > .ge-layer-controls {
+ display: none;
+ }
++.ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item).active > .ge-layer-controls,
++.ge-layers-list > .ge-layer-item:not(.ge-adj-sub-item):not(.ge-mask-sub-item).active-parent > .ge-layer-controls,
++.ge-layers-list > .ge-layer-group-row.active > .ge-layer-controls {
++ display: flex;
++ flex-wrap: wrap;
++ justify-content: flex-end;
++ width: 100%;
++ max-width: 100%;
++ min-width: 0;
++ box-sizing: border-box;
++ padding-top: 4px;
++ border-top: 1px solid color-mix(in srgb, var(--border) 75%, transparent);
++}
+ .ge-layer-tools[hidden] { display: none; }
+ .ge-layer-tools .ge-layer-btn { min-width: 26px; }
+ @media (max-width: 700px) {
+ /* Preserve the compact grip while giving long-press reorder a usable
+ touch target. */
+ .ge-layer-drag {
+ width: 28px;
+ min-height: 30px;
+ margin-left: -6px;
+ margin-right: -4px;
+ }
+ }
+ .ge-layer-align-menu .ge-layer-lock-option { grid-template-columns: minmax(0, 1fr); }
+ .ge-crop-apply input[type="number"]::-webkit-outer-spin-button,
+ .ge-crop-apply input[type="number"]::-webkit-inner-spin-button {
+ -webkit-appearance: none;
+ margin: 0;
+ }
+ .ge-brush-cursor::after {
+ content: '';
+ position: absolute;
+ top: 50%; left: 50%;
+ width: 3px; height: 3px;
+ margin: -1.5px 0 0 -1.5px;
+ background: rgba(255,255,255,0.8);
+ border-radius: 50%;
+ }
+ /* Marks remain solid so they pop through the otherwise-invisible
+ overlay; outlined extra-bright for the currently-focused one. */
+ body.doc-find-active mark.doc-find-mark {
+ background: var(--accent) !important;
+ color: var(--bg) !important;
+ }
+ body.doc-find-active mark.doc-find-mark.current {
+ background: var(--accent) !important;
+ box-shadow: 0 0 0 2px var(--fg) !important;
+ outline: 1px solid var(--fg) !important;
+ }
+ .doc-email-header:not(.doc-email-header-collapsed) .doc-email-collapse-summary {
+ opacity: 0.45;
+ }
+ .doc-email-header.doc-email-header-collapsed {
+ gap: 0;
+ padding-top: 5px;
+ padding-bottom: 5px;
+ }
+ .doc-email-header.doc-email-header-collapsed .doc-email-fields {
+ display: none;
+ }
+ /* Documents footer — X + Undo stay on the LEFT, Copy/Export group pushed
+ to the RIGHT. Email composer keeps its original flex-end layout. */
+ #doc-actions-footer {
+ justify-content: flex-start;
+ }
+ .doc-save-button[data-save-state="dirty"] .doc-save-state-dirty,
+ .doc-save-button[data-save-state="saving"] .doc-save-state-saving,
+ .doc-save-button[data-save-state="saved"] .doc-save-state-saved,
+ .doc-save-button[data-save-state="error"] .doc-save-state-error { display: block; }
+ .doc-save-button[data-save-state="saving"] .doc-save-state-saving {
+ animation: doc-save-spin 800ms linear infinite;
+ }
+ @keyframes doc-save-spin { to { transform: rotate(360deg); } }
+ @media (prefers-reduced-motion: reduce) {
+ .doc-save-button[data-save-state="saving"] .doc-save-state-saving { animation: none; }
+ }
+ .doc-stats-popover[hidden] { display: none; }
+ .doc-stats-row strong {
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ }
+ .doc-email-richbody:empty::before {
+ content: "Write your email\2026";
+ opacity: 0.4;
+ pointer-events: none;
+ }
+ @media (max-width: 768px) {
+ .doc-rich-empty-import {
+ top: 106px;
+ }
+ }
+ .doc-email-richbody.richtext-mode:empty::before {
+ content: "Start writing\2026";
+ }
+ .doc-email-richbody.richtext-mode ul,
+ .doc-email-richbody.richtext-mode ol {
+ padding-left: 1.75em;
+ }
+ .doc-email-richbody.richtext-mode ul:not(.rich-checklist) > li,
+ .doc-email-richbody.richtext-mode ol > li {
+ padding-inline-start: 0.2em;
+ }
+ .doc-email-richbody.richtext-mode pre code {
+ padding: 0;
+ border: 0;
+ background: transparent;
+ font: inherit;
+ }
+ .doc-email-richbody figure.richtext-image .richtext-image-caption {
+ margin-top: 6px;
+ max-width: 100%;
+ color: color-mix(in srgb, var(--fg) 68%, transparent);
+ font-size: 0.84em;
+ line-height: 1.4;
+ text-align: center;
+ overflow-wrap: anywhere;
+ }
+ .doc-email-richbody a { color: var(--accent, #4af); }
+ .doc-email-richbody blockquote {
+ margin: 6px 0; padding-left: 10px;
+ border-left: 3px solid var(--border); opacity: 0.8;
+ }
+ .doc-email-richbody p { margin: 0.5em 0; }
+ #doc-email-more-btn svg { opacity: 0.8; }
+ @media (min-width: 769px) {
+ #doc-email-header #doc-email-collapse-btn.doc-email-collapse-btn {
+ display: none !important;
+ }
+ #doc-email-header.doc-email-header-collapsed .doc-email-fields {
+ display: flex !important;
+ }
+ }
+ .doclib-section-title-icon {
+ width: 14px;
+ height: 14px;
+ margin-right: 6px;
+ color: var(--accent, var(--red));
+ vertical-align: -2px;
+ }
diff --cc static/css/email-calendar-notes-tasks.css
index 000000000,7a19b6021..25cd2f19f
mode 000000,100644..100644
--- a/static/css/email-calendar-notes-tasks.css
+++ b/static/css/email-calendar-notes-tasks.css
@@@ -1,0 -1,1571 +1,1570 @@@
+ /* Email, calendar, notes and tasks panels.
+ *
+ * This is an eagerly loaded tail segment of the app stylesheet cascade. The
+ * former static/style.css now lives in the numbered 00-17 fragments; these
+ * three pre-existing panel files follow those fragments without changing
+ * their relative order. Nothing here is lazy-loaded.
+ *
+ * LOAD ORDER IS PART OF THE CONTRACT. static/index.html and the PRECACHE list
+ * in static/sw.js must agree:
+ * 1. static/css/00-tokens.css through static/css/17-research.css,
+ * in numeric order
+ * 2. static/css/documents-gallery-editor.css
+ * 3. static/css/email-calendar-notes-tasks.css
+ * 4. static/css/cookbook-research-memory-settings.css
+ *
+ * Rules in this file retain their existing cascade position. Shared rules
+ * formerly kept in static/style.css now live in the numbered fragments.
+ */
+
+ @keyframes email-notif-breathe {
+ 0%, 100% {
+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent, var(--red)) 60%, transparent);
+ opacity: 0.85;
+ }
+ 50% {
+ box-shadow: 0 0 6px 2px color-mix(in srgb, var(--accent, var(--red)) 55%, transparent);
+ opacity: 1;
+ }
+ }
+ .memory-item.task-paused:hover {
+ opacity: 0.85 !important;
+ filter: saturate(0.9);
+ }
+ .email-folder-picker .email-folder-select-control {
+ padding-left: 26px;
+ }
+ /* Email bulk-select mode owns the whole card. Sender names and tags must not
+ open search/filter actions until Select is cancelled. */
+ #email-lib-grid.email-selecting .email-meta-sender,
+ #email-lib-grid.email-selecting .email-card-tags,
+ #email-lib-grid.email-selecting .email-card-favorite,
+ #email-lib-grid.email-selecting .email-card-nav-arrows,
+ #email-lib-grid.email-selecting .email-card-status,
+ #email-lib-grid.email-selecting .email-card-actions {
+ pointer-events: none !important;
+ }
+ .email-reader-actions-inline > .email-reader-more-wrap { order: 5; }
+ /* ── Tasks ── */
+ #tool-tasks-btn.task-failure-pending,
+ #rail-tasks.task-failure-pending {
+ color: var(--red, #f87171);
+ }
+ #tool-tasks-btn.task-completion-pending,
+ #rail-tasks.task-completion-pending {
+ color: var(--accent, var(--green, #86efac));
+ }
+ #tool-tasks-btn.task-failure-pending::after,
+ #rail-tasks.task-failure-pending::after,
+ #tool-tasks-btn.task-completion-pending::after,
+ #rail-tasks.task-completion-pending::after {
+ content: '';
+ width: 7px;
+ height: 7px;
+ border-radius: 999px;
+ background: var(--red, #f87171);
+ box-shadow: 0 0 7px var(--red, #f87171), 0 0 3px var(--red, #f87171);
+ flex: 0 0 auto;
+ }
+ #tool-tasks-btn.task-completion-pending::after,
+ #rail-tasks.task-completion-pending::after {
+ background: var(--accent, var(--green, #86efac));
+ box-shadow: 0 0 7px var(--accent, var(--green, #86efac)), 0 0 3px var(--accent, var(--green, #86efac));
+ }
+ #tool-tasks-btn.task-failure-pending.task-completion-pending,
+ #rail-tasks.task-failure-pending.task-completion-pending {
+ color: var(--red, #f87171);
+ }
+ #tool-tasks-btn.task-failure-pending.task-completion-pending::after,
+ #rail-tasks.task-failure-pending.task-completion-pending::after {
+ background: var(--red, #f87171);
+ box-shadow: 0 0 7px var(--red, #f87171), 0 0 3px var(--red, #f87171);
+ }
+ #rail-tasks.task-failure-pending::after,
+ #rail-tasks.task-completion-pending::after {
+ position: absolute;
+ right: 8px;
+ top: 8px;
+ }
+ .tasks-activity-card,
+ .tasks-activity-list {
+ min-height: 0;
+ }
+ .tasks-activity-list {
+ overflow-y: auto;
+ -webkit-overflow-scrolling: touch;
+ }
+ .task-log-row.task-log-row-error .task-log-task-icon svg {
+ opacity: 0.82 !important;
+ }
+ .task-log-running-inline .task-log-running-label { font-weight: 500; }
+ .task-log-running-elapsed {
+ margin-left: 6px;
+ opacity: 0.6;
+ font-variant-numeric: tabular-nums;
+ }
+ .task-log-time {
+ opacity: 0.5;
+ font-variant-numeric: tabular-nums;
+ }
+ @keyframes task-log-pulse {
+ 0%, 100% { box-shadow: 0 0 0 0 color-mix(in srgb, #60a5fa 60%, transparent); }
+ 50% { box-shadow: 0 0 0 4px color-mix(in srgb, #60a5fa 0%, transparent); }
+ }
+ .task-log-row-body li { margin: 2px 0; }
+ .task-log-row-body hr {
+ border: none;
+ border-top: 1px solid color-mix(in srgb, var(--fg) 12%, transparent);
+ margin: 8px 0;
+ }
+ .task-log-row-toggle::before {
+ color: color-mix(in srgb, var(--accent, var(--fg)) 80%, transparent);
+ opacity: 0.8;
+ }
+ .task-log-row-toggle:hover::before { opacity: 1; }
+ /* A <select>'s closed width otherwise grows to its widest option (the long
+ action descriptions), overflowing the modal — clip it to the field width. */
+ select.task-form-input { text-overflow: ellipsis; }
+ .task-form-textarea { resize: vertical; min-height: 60px; }
+ .task-form-notif-switch::after {
+ content: "";
+ position: absolute;
+ width: 10px;
+ height: 10px;
+ left: 3px;
+ top: 2px;
+ border-radius: 50%;
+ background: color-mix(in srgb, var(--fg) 62%, transparent);
+ transition: transform 0.15s, background 0.15s;
+ }
+ .task-form-notif-toggle input:checked + .task-form-notif-switch::after {
+ transform: translateX(13px);
+ background: var(--accent, var(--red));
+ }
+ .email-list { overflow-y: auto; max-height: 400px; }
+ .email-item:hover .email-menu-btn { opacity: 0.5; }
+ .email-item-spam { opacity: 0.4; }
+ /* Auto-done flash: when a row gets marked done because the user just sent
+ a reply, briefly tint the whole row with the accent and pop the check
+ so the state change is hard to miss. Self-removes after ~1.2s. */
+ @keyframes email-auto-done-row {
+ 0% { background: color-mix(in srgb, var(--accent, var(--red)) 22%, transparent); }
+ 60% { background: color-mix(in srgb, var(--accent, var(--red)) 14%, transparent); }
+ 100% { background: transparent; }
+ }
+ @keyframes email-auto-done-check {
+ 0% { transform: scale(1); box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent, var(--red)) 45%, transparent); }
+ 40% { transform: scale(1.4); box-shadow: 0 0 0 6px color-mix(in srgb, var(--accent, var(--red)) 0%, transparent); }
+ 100% { transform: scale(1); }
+ }
+ .email-item.email-auto-done-flash { animation: email-auto-done-row 1.2s ease-out; }
+ .email-item.email-auto-done-flash .email-done-check { animation: email-auto-done-check 0.6s ease-out; }
+ /* Email titles that carry a cached AI summary get a thin underline-dot hint
+ so the user knows a hover-preview is available. */
+ .memory-item-title.email-card-has-summary {
+ cursor: help;
+ text-decoration: underline dotted color-mix(in srgb, var(--accent) 60%, transparent) 1px;
+ text-underline-offset: 3px;
+ }
+ #email-lib-grid .doclib-card.email-card-unread:not(.email-card-expanded) {
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 58%, var(--border)) !important;
+ box-shadow:
+ 0 0 0 1px color-mix(in srgb, var(--accent, var(--red)) 24%, transparent),
+ 0 0 10px -4px color-mix(in srgb, var(--accent, var(--red)) 55%, transparent);
+ }
+ #email-lib-grid .doclib-card.email-card-unread:not(.email-card-expanded):hover {
+ border-color: color-mix(in srgb, var(--accent, var(--red)) 76%, var(--border)) !important;
+ box-shadow:
+ 0 0 0 1px color-mix(in srgb, var(--accent, var(--red)) 32%, transparent),
+ 0 0 12px -3px color-mix(in srgb, var(--accent, var(--red)) 65%, transparent);
+ }
+ .email-card-favorite.active:hover,
+ .email-card-favorite.active:focus-visible { opacity: 1; }
+ .email-card-favorite:active { transform: scale(0.88); }
+ .email-card-favorite svg { pointer-events: none; }
+ .email-card-done.just-checked {
+ animation: check-pop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ /* Reverse animation when un-checking — shrink-and-fade so the click is
+ obviously felt even when hover styling otherwise keeps the icon visible. */
+ .email-card-done.just-unchecked {
+ animation: check-unpop 0.42s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ .email-card-reader-loading .spinner-whirlpool,
+ .email-card-reader-loading .ai-spinner-whirlpool {
+ opacity: 0.85;
+ }
+ .email-skeleton-row.compact { min-height: 42px; opacity: 0.72; }
+ .email-skeleton-line.title { width: min(88%, 520px); height: 9px; }
+ .email-skeleton-line.meta { width: min(72%, 420px); height: 7px; opacity: 0.78; }
+ .email-skeleton-line.date { width: 72px; height: 7px; flex: 0 0 auto; opacity: 0.72; }
+ @keyframes email-skeleton-shimmer {
+ 0% { background-position: 120% 0; opacity: 0.68; }
+ 50% { opacity: 1; }
+ 100% { background-position: -120% 0; opacity: 0.68; }
+ }
+ @keyframes email-search-progress-pulse {
+ 0%, 100% { transform: scale(0.9); opacity: 0.55; box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent-primary, var(--red)) 35%, transparent); }
+ 50% { transform: scale(1.1); opacity: 1; box-shadow: 0 0 0 5px transparent; }
+ }
+ @keyframes email-inline-image-spin {
+ to { transform: rotate(360deg); }
+ }
+ @keyframes email-card-unread-breathe {
+ 0%, 100% {
+ box-shadow: 0 0 0 0 color-mix(in srgb, currentColor 0%, transparent);
+ opacity: 0.85;
+ transform: scale(1);
+ }
+ 50% {
+ /* currentColor here is unreliable (background, not color) — use a
+ subtle white-tinted halo so the glow shows on any sender hue. */
+ box-shadow: 0 0 6px 2px rgba(255, 255, 255, 0.18);
+ opacity: 1;
+ transform: scale(1.15);
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .email-card-unread-dot { animation: none; }
+ }
+ #email-lib-pills::-webkit-scrollbar { display: none; }
+ .email-reader-meta-details[hidden] { display: none; }
+ .email-reader-header > .email-reader-meta {
+ flex: 1; min-width: 0;
+ opacity: 0.85; line-height: 1.7; font-size: 11px;
+ }
+ /* When rendering HTML emails, override pre-wrap so layout works */
+ .email-reader-body.html-body {
+ white-space: normal;
+ }
+ .email-reader-body .email-inline-image-placeholder.is-error {
+ border-color: color-mix(in srgb, var(--red, #ff5555) 45%, var(--border));
+ }
+ .email-inline-image-placeholder.is-loading .email-inline-image-icon {
+ width: 16px;
+ height: 16px;
+ border: 2px solid color-mix(in srgb, var(--fg) 20%, transparent);
+ border-top-color: var(--accent, var(--red));
+ border-radius: 50%;
+ animation: email-inline-image-spin 0.75s linear infinite;
+ }
+ .email-inline-image-frame.is-loading {
+ animation: email-skeleton-shimmer 1.35s ease-in-out infinite;
+ }
+ .email-inline-image-frame .email-inline-image-loaded.is-visible {
+ opacity: 1;
+ }
+ /* Preserve highlights — sender's intent (snark, callouts) gets through, but
+ rendered with a theme-aware accent so it stays legible in any theme. The
+ sanitizer rewrites `<span style="background:yellow">…</span>` to <mark>. */
+ .email-reader-body mark {
+ background: color-mix(in srgb, var(--accent, var(--red)) 22%, transparent);
+ color: inherit;
+ padding: 0 2px;
+ border-radius: 2px;
+ }
+ .email-summary-toggle:hover { opacity: 1; }
+ .email-summary-panel.collapsed .email-summary-header { margin-bottom: 0; }
+ .email-summary-panel.collapsed .email-summary-content { display: none; }
+ .email-summary-panel.collapsed .email-summary-chevron { transform: rotate(-90deg); }
+ .email-translation-panel { margin-top: 0; }
+ .email-attachments-download-all.is-loading {
+ opacity: 0.82;
+ pointer-events: none;
+ }
+ .email-reader-atts-wrap.collapsed > .email-reader-atts,
+ .email-reader-atts-wrap.collapsed > .email-reader-atts-hidden-note { display: none; }
+ .email-reader-atts-wrap.collapsed .email-summary-chevron { transform: rotate(-90deg); }
+ .email-thread-turn-body .email-thread-turn .email-fold-summary {
+ padding: 5px 10px;
+ }
+ .email-thread-turn-body .email-thread-turn .email-thread-turn-body {
+ padding: 6px 10px 2px;
+ font-size: 11px;
+ }
+ .email-quote-fold .email-fold-summary::-webkit-details-marker,
+ .email-quote-fold .email-fold-summary::marker { display: none; content: none; }
+ .email-quote-fold .email-fold-summary:hover { opacity: 1; }
+ .email-quote-fold[open] .email-summary-chevron { transform: rotate(180deg); }
+ /* Suppress the global `summary::before { content: '▶' }` rule from
+ leaking the chevron-emoji onto our header — we use the trailing SVG
+ chevron only. */
+ .email-sig-fold .email-fold-summary::before,
+ .email-quote-fold .email-fold-summary::before { content: none !important; }
+ .email-sig-fold .email-fold-summary::-webkit-details-marker,
+ .email-sig-fold .email-fold-summary::marker { display: none; content: none; }
+ .email-sig-fold .email-fold-summary:hover { opacity: 1; }
+ .email-sig-fold[open] .email-summary-chevron { transform: rotate(180deg); }
+ .email-bubble-row.email-bubble-mine {
+ flex-direction: row-reverse;
+ justify-content: flex-start;
+ }
+ .email-bubble-row.email-bubble-theirs {
+ /* Avatar lives at the END of the row (right side) so the bubble has
+ the full left edge to start from — gives bigger reading width and
+ a cleaner left margin. */
+ flex-direction: row-reverse;
+ justify-content: flex-end;
+ }
+ .email-bubble-mine .email-bubble-head { justify-content: flex-end; }
+ .email-bubble-body *:not(code):not(pre):not(kbd):not(samp) {
+ line-height: inherit !important;
+ }
+ .email-bubble-body img {
+ max-width: 100%;
+ height: auto;
+ }
+ .email-bubble-body table {
+ max-width: 100%;
+ }
+ .email-bubble-body .email-sig-fold .email-fold-summary,
+ .email-bubble-body .email-quote-fold .email-fold-summary {
+ padding: 4px 0;
+ }
+ .email-sender-clickable { cursor: pointer; }
+ .email-sender-clickable:hover { text-decoration: underline; }
+ .email-filter-chip-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .email-filter-chip-clear:hover { opacity: 1; }
+ @media (max-width: 768px) {
+ .email-search-row {
+ flex-wrap: wrap;
+ }
+ }
+ .email-tags-collapsed .email-tag-extra { display: none; }
+ .email-tags-expanded .email-tag-extra { display: inline-flex; align-items: center; }
+ .email-card-tags.email-tags-mini:not(.email-tags-expanded) > .email-tags-more:not(.email-tags-more-single) {
+ display: none;
+ }
+ .email-card-tags.email-tags-mini:not(.email-tags-expanded) .email-tags-more-single {
+ display: inline-flex;
+ }
+ .email-card-tags.email-tags-expanded .email-tags-more-single {
+ display: none;
+ }
+ .email-tags-more:hover { opacity: 0.92; }
+ .email-tag-clickable:hover {
+ filter: brightness(1.12);
+ }
+ @keyframes email-spin { to { transform: rotate(360deg); } }
+ /* Compose + button: show on section hover, spin on button hover */
+ #email-compose-btn {
+ opacity: 0.4 !important;
+ transition: opacity 0.15s ease;
+ }
+ /* Satisfying send effect: email slides out to the right and fades */
+ .email-send-fx {
+ animation: email-send-slide 0.5s cubic-bezier(0.4, 0, 0.2, 1) forwards;
+ pointer-events: none;
+ }
+ @keyframes email-send-slide {
+ 0% {
+ transform: translateX(0);
+ opacity: 1;
+ filter: blur(0);
+ }
+ 60% {
+ filter: blur(1px);
+ }
+ 100% {
+ transform: translateX(110%);
+ opacity: 0;
+ filter: blur(3px);
+ }
+ }
+ .email-lib-unread-badge:hover { filter: brightness(1.08); }
+ .email-lib-auto-reply-badge:hover {
+ filter: brightness(1.08);
+ }
+ .email-card-nav-btn:disabled {
+ opacity: 0.25;
+ cursor: default;
+ pointer-events: none;
+ }
+ .email-send-btn:disabled { opacity: 0.5; cursor: not-allowed; }
+ .email-draft-btn:disabled { opacity: 0.5; cursor: not-allowed; }
+ .email-attachment-chip .att-size { opacity: 0.5; font-size: 10px; flex-shrink: 0; }
+ .email-attachment-chip-muted { opacity: 0.65; }
+ .email-attachment-chip-muted:hover { opacity: 1; }
+ .email-attachment-open.is-loading {
+ pointer-events: none;
+ opacity: 0.82;
+ }
+ .email-attachment-open.is-loading .spinner-whirlpool,
+ .email-attachment-open.is-loading .ai-spinner-whirlpool {
+ width: 12px !important;
+ height: 12px !important;
+ margin: 0 !important;
+ position: relative;
+ top: 0;
+ }
+ .email-compose-chip .att-size { opacity: 0.5; font-size: 10px; flex-shrink: 0; }
+ .email-odysseus-attach-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ }
+ .email-odysseus-attach-selected:disabled {
+ opacity: 0.45;
+ cursor: default;
+ }
+ .email-odysseus-attach-selected.is-loading {
+ opacity: 0.72;
+ pointer-events: none;
+ }
+ @media (max-width: 768px) {
+ .email-odysseus-attach-menu {
+ left: 8px !important;
+ right: 8px;
+ bottom: 8px;
+ top: auto !important;
+ width: auto;
+ max-height: 58vh;
+ }
+ .email-odysseus-attach-list {
+ max-height: calc(58vh - 88px);
+ }
+ }
+ .email-ai-reply-btn:disabled { opacity: 0.5; cursor: not-allowed; }
+ #email-lib-settings-btn { top: -1px; }
+ #email-lib-settings-btn svg { position: relative; top: 2px; }
+ /* New (Compose) button gets a slightly taller, slightly lower variant
+ on desktop so it reads as the primary action of the row. Scoped to
+ desktop so the mobile touch-friendly variant (further down) stays in
+ charge for ≤768px. */
+ @media (min-width: 769px) {
+ #email-lib-compose-btn { height: 28px; top: 0; }
+ }
+ /* Envelope icon picks up the user's accent so the primary action is
+ easy to spot at any size. The SVG already uses stroke=currentColor,
+ so a color: rule on the svg propagates. */
+ #email-lib-compose-btn svg { color: var(--accent, var(--red)); }
+ @media (max-width: 768px) {
+ /* On mobile they're 1px higher than desktop. */
+ #email-lib-select-btn, #email-lib-refresh-btn, #email-lib-settings-btn { top: -3px; }
+ #email-lib-settings-btn { top: -2px; }
+ }
+ .email-settings-page-host > .email-settings-body {
+ overflow: visible;
+ }
+ .email-settings-page-head:empty {
+ display: none;
+ }
+ .email-settings-section > summary {
+ list-style: none;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ user-select: none;
+ }
+ .email-settings-section > summary::-webkit-details-marker {
+ display: none;
+ }
+ .email-settings-section > summary::before {
+ content: none;
+ display: none;
+ }
+ .email-settings-section > .email-settings-section-body {
+ padding: 0;
+ font-size: inherit;
+ line-height: normal;
+ animation: none;
+ }
+ .email-settings-section-toggle:focus-visible {
+ outline: 1px solid var(--accent, var(--red));
+ outline-offset: 3px;
+ border-radius: 3px;
+ }
+ .email-settings-section.is-expanded .email-settings-section-chevron {
+ transform: rotate(180deg);
+ }
+ .email-settings-section[open] .email-settings-section-chevron {
+ transform: rotate(180deg);
+ }
+ .email-settings-section-body > .email-settings-enabled-control {
+ align-self: flex-end;
+ }
+ .email-settings-auto-reply-section > summary,
+ .email-settings-cleanup-section > summary {
+ padding-bottom: 6px;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 40%, transparent);
+ }
+ .email-settings-auto-reply-title-row {
+ top: 0;
+ }
+ .email-settings-clean-actions:has(.email-settings-clean-status.is-busy) {
+ flex-direction: row;
+ align-items: center;
+ }
+ .email-settings-clean-status:not(:empty) {
+ display: inline-flex;
+ align-items: center;
+ }
+ .email-unsub-card.is-expanded .email-unsub-card-toggle > svg {
+ transform: rotate(180deg);
+ }
+ .email-unsub-card.is-unsubscribed {
+ opacity: .58;
+ }
+ .email-settings-grid > label > span:first-child,
+ .email-settings-field > span {
+ color: var(--accent, var(--red));
+ }
+ @media (max-width: 768px) {
+ .email-settings-section[open] > .email-settings-section-body {
+ height: auto;
+ max-height: none;
+ }
+ .email-settings-auto-reply-section[open] > .email-settings-section-body,
+ .email-settings-cleanup-section[open]:has(.email-unsub-card) > .email-settings-section-body {
+ height: 100%;
+ max-height: 100%;
+ }
+ }
+ /* On mobile, the "New" (compose) button deserves a touch-friendly size
+ so it stands out from the smaller toolbar buttons next to it. Lift
+ it slightly visually with a bigger SVG, padding, and font. */
+ @media (max-width: 768px) {
+ #email-lib-compose-btn {
+ padding: 8px 14px !important;
+ font-size: 13px !important;
+ min-height: 36px;
+ border-radius: 8px;
+ font-weight: 600;
+ top: -2px;
+ }
+ #email-lib-compose-btn svg {
+ width: 14px !important;
+ height: 14px !important;
+ margin-right: 5px !important;
+ }
+ }
+ /* Checklist rows stay tappable on mobile; only destructive hover affordances
+ stay hidden. Select mode below still disables checklist toggling. */
+ body.notes-mobile-mode .note-card .note-checkbox-rm {
+ pointer-events: none;
+ }
+ body.notes-mobile-mode .note-card .note-checkbox {
+ pointer-events: auto;
+ user-select: none;
+ -webkit-user-select: none;
+ -webkit-touch-callout: none;
+ touch-action: manipulation;
+ }
+ body.notes-mobile-mode .note-card .note-check-dot,
+ body.notes-mobile-mode .note-card .note-checkbox-dot,
+ body.notes-mobile-mode .note-card .note-cl-dot {
+ opacity: 0.55;
+ cursor: pointer !important;
+ }
+ body.notes-mobile-mode .note-card:active {
+ transform: scale(0.985);
+ }
+ body.notes-drag-mode .note-card::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ background: linear-gradient(
+ 115deg,
+ transparent 30%,
+ color-mix(in srgb, var(--fg) 14%, transparent) 50%,
+ transparent 70%
+ );
+ background-size: 250% 100%;
+ animation: notes-drag-shimmer 2.1s linear infinite;
+ border-radius: inherit;
+ z-index: 1;
+ mix-blend-mode: overlay;
+ }
+ @keyframes notes-drag-shimmer {
+ 0% { background-position: 250% 0; }
+ 100% { background-position: -150% 0; }
+ }
+ /* The grabbed card lifts above its siblings; suppress the shimmer on
+ it so it reads as the "live" element being moved. */
+ body.notes-drag-mode .note-card.note-card-dragging {
+ transform: scale(1.06);
+ box-shadow: 0 16px 40px rgba(0,0,0,0.45);
+ opacity: 1;
+ filter: none;
+ z-index: 10001;
+ cursor: grabbing;
+ transition: box-shadow 0.18s ease;
+ }
+ body.notes-drag-mode .note-card.note-card-dragging::after { display: none; }
+ body.notes-drag-mode .note-card .note-card-pin {
+ visibility: hidden !important;
+ opacity: 0 !important;
+ pointer-events: none !important;
+ }
+ body.notes-drag-mode .note-card-pinned .note-card-pin,
+ body.notes-drag-mode .note-card-pin.active,
+ body.notes-drag-mode .note-card-pin svg {
+ visibility: hidden !important;
+ opacity: 0 !important;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ body.notes-drag-mode .note-card::after { animation: none; }
+ }
+ .note-fullscreen-overlay .note-form-type-pill {
+ padding: 10px 16px;
+ font-size: 14px;
+ }
+ .note-fullscreen-overlay .note-cl-grip:active { cursor: grabbing; opacity: 0.9; }
+ .note-fullscreen-overlay .note-cl-dot::before {
+ content: '';
+ position: absolute;
+ inset: -12px;
+ }
+ .note-fullscreen-overlay .note-cl-text {
+ font-size: 14px;
+ padding: 7px 6px;
+ min-height: 32px;
+ }
+ .note-fullscreen-overlay .note-cl-rm:active { opacity: 1; }
+ /* + Add (new checklist item) was tiny — bump for thumbs */
+ .note-fullscreen-overlay .note-cl-add {
+ display: inline-flex;
+ align-items: center;
+ padding: 10px 18px;
+ font-size: 15px;
+ font-weight: 600;
+ border-radius: 8px;
+ letter-spacing: -0.01em;
+ opacity: 0.85;
+ }
+ .note-fullscreen-overlay .note-cl-add:active { opacity: 1; }
+ .note-fullscreen-overlay .note-cl-add-row .note-cl-add { margin: 0; }
+ .note-fullscreen-overlay .note-cl-add-row .note-form-photo-btn::before {
+ content: '+';
+ font-size: 17px;
+ font-weight: 600;
+ line-height: 1;
+ opacity: 0.85;
+ }
+ .note-fullscreen-overlay .note-cl-add-row .note-form-photo-btn svg {
+ width: 16px;
+ height: 16px;
+ }
+ .note-form-content-reader a {
+ color: var(--accent, var(--red));
+ text-decoration: underline;
+ text-underline-offset: 2px;
+ }
+ .note-form-content-reader a:active { opacity: 0.7; }
+ .note-fullscreen-overlay .note-cl-text-reader a {
+ color: var(--accent, var(--red));
+ text-decoration: underline;
+ text-underline-offset: 2px;
+ }
+ .note-fullscreen-overlay .note-cl-text-reader a:active { opacity: 0.7; }
+ /* Reminder bell + other header icon-buttons. Tightened down 2px so
+ the bell sits more proportionally next to the title field. */
+ .note-fullscreen-overlay .note-form-icon-btn {
+ width: 36px;
+ height: 36px;
+ }
+ /* The plain-note textarea was rows="4" — fine for an in-grid card but
+ cramped in fullscreen. Let it grow to fill the available height so
+ writing feels like a real notepad, not a tweet box. The read-mode
+ reader inherits the same minimum so the layout doesn't jump when
+ the user taps to edit. */
+ .note-fullscreen-overlay .note-form-content,
+ .note-fullscreen-overlay .note-form-content-reader {
+ min-height: 55vh;
+ font-size: 15px;
+ line-height: 1.55;
+ }
+ /* Reorganized meta-row layout for fullscreen: color picker pinned to
+ the LEFT, type-toggle (Note/Todo/Draw) shoved to the RIGHT, with
+ the photo button next to the color picker. Tags are moved up into
+ the form header (next to the reminder bell) via JS. */
+ .note-fullscreen-overlay .note-form-meta {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ padding-top: 8px;
+ }
+ .note-fullscreen-overlay .note-form-photo-btn { order: 2; }
+ .note-fullscreen-overlay .note-form-actions-group .note-form-cancel,
+ .note-fullscreen-overlay .note-form-actions-group .note-form-save {
+ flex: 0 0 auto;
+ }
+ @keyframes notes-backdrop-fade-in {
+ from { opacity: 0; }
+ to { opacity: 1; }
+ }
+ @keyframes notes-pane-enter {
+ from { transform: scale(0.96); opacity: 0; }
+ to { transform: scale(1); opacity: 1; }
+ }
+ .notes-pane.notes-pane-leaving {
+ animation: notes-pane-leave 160ms cubic-bezier(0.4, 0, 1, 1) both;
+ pointer-events: none;
+ }
+ @keyframes notes-pane-leave {
+ from { transform: scale(1); opacity: 1; }
+ to { transform: scale(0.96); opacity: 0; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .notes-pane,
+ .notes-pane.notes-pane-leaving { animation: none; }
+ }
+ /* Hide the "Add a to-do…" quick-add bar in archive view — you can't add
+ new items from the archive. */
+ .notes-pane-archive .notes-quick-add { display: none !important; }
-.note-checkbox:hover .note-checkbox-agent { opacity: 0.55; }
+ @keyframes note-reminder-pulse {
+ 0%, 100% {
+ box-shadow:
+ inset 0 2px 0 0 color-mix(in srgb, var(--fg) 14%, transparent),
+ 0 0 0 0 color-mix(in srgb, var(--accent, var(--red)) 0%, transparent);
+ }
+ 50% {
+ box-shadow:
+ inset 0 2px 0 0 color-mix(in srgb, var(--fg) 14%, transparent),
+ 0 0 0 5px color-mix(in srgb, var(--accent, var(--red)) 26%, transparent),
+ 0 0 18px color-mix(in srgb, var(--accent, var(--red)) 30%, transparent);
+ }
+ }
+ @keyframes note-reminder-glow {
+ 0%, 100% {
+ box-shadow:
+ inset 0 2px 0 0 color-mix(in srgb, var(--fg) 14%, transparent),
+ 0 0 0 3px color-mix(in srgb, var(--accent, var(--red)) 14%, transparent),
+ 0 0 14px color-mix(in srgb, var(--accent, var(--red)) 18%, transparent);
+ }
+ 50% {
+ box-shadow:
+ inset 0 2px 0 0 color-mix(in srgb, var(--fg) 14%, transparent),
+ 0 0 0 6px color-mix(in srgb, var(--accent, var(--red)) 22%, transparent),
+ 0 0 26px color-mix(in srgb, var(--accent, var(--red)) 30%, transparent);
+ }
+ }
+ .note-card-selected {
+ outline: 2px solid var(--accent);
+ outline-offset: -2px;
+ }
+ .note-card-select { left: -8px; }
+ .note-card-pin { right: -8px; }
+ /* Pin button on mobile — only reveal once the user has long-pressed to
+ enter rearrange (drag) mode. Outside drag mode the card stays clean. */
+ body.notes-mobile-mode.notes-drag-mode .note-card-pin {
+ display: flex !important;
+ opacity: 0.7;
+ }
+ body.notes-mobile-mode.notes-drag-mode .note-card-pin.active {
+ opacity: 1;
+ }
+ /* Edit + Done are now side-by-side at top-right by default — title-only
+ fallback no longer needed. */
+ .note-card-selectmode .note-card-done { display: none !important; }
+ .note-card:hover .note-card-corner-copy { visibility: visible; }
+ /* Copy stays on every active card regardless of body shape — Edit + Done
+ live at the top-right pair, so the bottom-right copy slot is always
+ free. Hidden only in select mode. */
+ .note-card-selectmode .note-card-corner-copy { display: none !important; }
+ .note-card-corner-trash { left: 6px; }
+ .note-card-corner-unarchive { right: 6px; }
+ .note-card:hover .note-card-corner-trash,
+ .note-card:hover .note-card-corner-unarchive { visibility: visible; }
+ @keyframes note-ai-shine {
+ 0%, 100% { opacity: 0.85; filter: drop-shadow(0 0 0 transparent); }
+ 50% { opacity: 1; filter: drop-shadow(0 0 4px color-mix(in srgb, var(--accent, var(--red)) 60%, transparent)); }
+ }
+ .note-form-improve-btn:disabled,
+ .note-form-improve-btn.busy {
+ opacity: 0.6;
+ cursor: wait;
+ }
+ /* In select mode the whole card is a checkbox — kill every hover affordance
+ that would otherwise suggest "preview" or "open" so users know exactly
+ what their tap will do (toggle selection). */
+ .note-card-selectmode .note-card-pin,
+ .note-card-selectmode .note-card-actions { pointer-events: none; opacity: 0.4; }
+ .note-card-selectmode .note-card-edit-corner,
+ .note-card-selectmode .note-card-pin {
+ display: none !important;
+ }
+ .note-card-selectmode .note-card-title:hover { opacity: 1 !important; }
+ .note-card-selectmode .note-card-edit-corner,
+ .note-card-selectmode:hover .note-card-edit-corner { opacity: 0 !important; }
+ /* The familiar home-screen edit-mode cue: mobile note cards gently jiggle
+ while Select mode is active, making it clear that the bar is now selecting
+ items rather than opening them. */
+ @keyframes notes-select-jiggle {
+ 0%, 100% { transform: rotate(-0.3deg) translateY(0); }
+ 50% { transform: rotate(0.3deg) translateY(-0.25px); }
+ }
+ .note-card-action svg { transform: translateY(2px); }
+ @keyframes notes-quick-pulse {
+ 0%, 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent, var(--red)) 0%, transparent); }
+ 50% { box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent, var(--red)) 14%, transparent); }
+ }
+ .notes-quick-input::placeholder {
+ color: color-mix(in srgb, var(--fg) 45%, transparent);
+ }
+ /* Blinking text caret hint before the placeholder so empty + unfocused
+ reads as a live input. Sits on the wrapper because <input> elements
+ can't carry ::before. The pseudo-element is ALWAYS rendered (so its
+ width is reserved and the placeholder doesn't jump left when the
+ hint hides); only the colour/animation toggle, not the layout. */
+ .notes-quick-add::before {
+ content: '|';
+ color: var(--accent, var(--red));
+ margin-right: 6px;
+ font-weight: 500;
+ font-size: 13px;
+ animation: notes-quick-caret 1s steps(2, jump-none) infinite;
+ pointer-events: none;
+ }
+ /* Hide visually (keep space) on hover, focus, or once the input has any
+ text — prevents the layout shift the user reported when the hint
+ collapsed and the placeholder slid left. */
+ .notes-quick-add:hover::before,
+ .notes-quick-add:focus-within::before,
+ .notes-quick-add:not(:has(.notes-quick-input:placeholder-shown))::before {
+ visibility: hidden;
+ animation: none;
+ }
+ @keyframes notes-quick-caret {
+ 0%, 49% { opacity: 1; }
+ 50%, 100%{ opacity: 0; }
+ }
+ .notes-quick-type-seg.is-todo::before { transform: translateX(100%); }
+ .notes-skeleton-card.short { height: 46px; }
+ @keyframes notes-skeleton-shimmer {
+ 0% { background-position: 200% 0; }
+ 100% { background-position: -200% 0; }
+ }
+ @keyframes cal-bell-jingle {
+ 0% { transform: rotate(0deg); }
+ 15% { transform: rotate(-22deg); }
+ 30% { transform: rotate(18deg); }
+ 45% { transform: rotate(-14deg); }
+ 60% { transform: rotate(10deg); }
+ 75% { transform: rotate(-6deg); }
+ 88% { transform: rotate(3deg); }
+ 100% { transform: rotate(0deg); }
+ }
+ .note-form-reminder-tags:empty { display: none; }
+ .note-reminder-day-chip.wide { padding: 0 6px; }
+ .note-form-type-seg::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ /* 3 pills now (note / todo / draw) — Goal was removed. Slider takes
+ 1/3 of the track and translates by full multiples of itself. */
+ width: 33.3333%;
+ height: 100%;
+ background: color-mix(in srgb, var(--fg) 10%, transparent);
+ border-radius: 9px;
+ transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
+ z-index: 0;
+ }
+ .note-form-type-seg.is-todo::before { transform: translateX(100%); }
+ .note-form-type-seg.is-draw::before { transform: translateX(200%); }
+ /* Bulk-bar appears under the search bar — inset its sides to match the
+ search bar's own 8px horizontal padding so the two visually align. */
+ #notes-bulk-bar.memory-bulk-bar {
+ margin: 0 8px 4px;
+ position: relative;
+ top: 4px;
+ }
+ #tasks-filter-chips {
+ top: 0 !important;
+ }
+ .note-card-goal .note-card-header {
+ /* Goal cards reserve space for the pill so the title doesn't collide. */
+ padding-left: 56px;
+ }
+ /* In select mode the left-side checkbox takes the pill's spot — drop it
+ so the row stays legible. */
+ .note-card-selectmode.note-card-goal .note-goal-pill { display: none; }
+ .note-card-selectmode.note-card-goal .note-card-header { padding-left: 0; }
+ .note-form-goal-ai:disabled,
+ .note-form-goal-ai.busy {
+ opacity: 0.6;
+ cursor: wait;
+ }
+ /* Fresh goal form: hide the title input + tag input + reminder button so the
+ user only sees the single "what do you want to achieve?" textarea. */
+ .note-form-goal-fresh ~ .note-form-actions-group { display: none; }
+ .note-form:has(.note-form-goal-fresh) .note-form-title,
+ .note-form:has(.note-form-goal-fresh) .note-form-label,
+ .note-form:has(.note-form-goal-fresh) .note-form-remind-btn,
+ .note-form-bespoke:has(.note-form-goal-fresh) .note-form-title,
+ .note-form-bespoke:has(.note-form-goal-fresh) .note-form-label,
+ .note-form-bespoke:has(.note-form-goal-fresh) .note-form-remind-btn {
+ display: none !important;
+ }
+ .note-form-goal-fresh .note-form-goal-desc {
+ font-size: 15px;
+ min-height: 90px;
+ padding: 12px 14px;
+ }
+ .note-form-goal-fresh.building .note-form-goal-desc {
+ opacity: 0.55;
+ pointer-events: none;
+ }
+ .note-form-goal-fresh.building::after {
+ content: 'AI is planning your goal…';
+ display: block;
+ text-align: center;
+ font-size: 12px;
+ opacity: 0.7;
+ margin-top: 6px;
+ animation: note-goal-pulse 1.4s ease-in-out infinite;
+ }
+ @keyframes note-goal-pulse {
+ 0%, 100% { opacity: 0.5; }
+ 50% { opacity: 1; }
+ }
+ .notes-today-row.done {
+ opacity: 0.35;
+ transform: scale(0.98);
+ }
+ .notes-today-title:hover { text-decoration: underline; }
+ .notes-bulk-btn {
+ opacity: 0.6;
+ }
+ .notes-bulk-btn:hover { opacity: 1; }
+ .note-form-label.flash-once {
+ animation: noteLabelFlash 0.6s ease-out;
+ }
+ .note-form-label:not([value=""]) { opacity: 0.9; border-style: solid; }
+ .note-card-title:hover { opacity: 0.7; }
+ .note-card-title.empty::before {
+ content: 'No title';
+ font-weight: 500;
+ opacity: 0.3;
+ font-style: italic;
+ }
+ /* Note card drag */
+ .note-card { cursor: grab; }
+ .note-cl-row:hover .note-cl-grip { opacity: 0.6; }
+ .note-archive-btn:hover { opacity: 0.7; }
+ .note-checklist-preview > .note-checkbox:last-child .note-check-text {
+ /* Reserve room on the LAST row only for the bottom-right copy button so it
+ doesn't cover the final item's tail. Applied to the text — not to the
+ row — so the X delete button still reaches the same edge it does on
+ every other row. */
+ padding-right: 30px;
+ }
+ .note-card.doclib-card-expanded .note-checklist-preview {
+ /* When the card is the expanded one in the grid, let the list use the
+ whole available height instead of the compact cap. */
+ max-height: none;
+ }
+ .note-checklist-preview:empty::before {
+ content: 'No todos';
+ font-size: 10px;
+ opacity: 0.3;
+ font-style: italic;
+ }
+ .note-card:hover .note-cl-quickadd,
+ .note-cl-quickadd:focus-within {
+ opacity: 1;
+ pointer-events: auto;
+ }
+ .note-cl-quickadd-input::placeholder { color: var(--fg); opacity: 0.5; }
+ .note-card-selectmode .note-cl-quickadd { display: none !important; }
+ .note-checkbox-rm { margin-left: auto; }
+ .note-checkbox-edit { margin-left: auto; }
+ .note-checkbox:hover .note-checkbox-edit,
+ .note-checkbox:hover .note-checkbox-rm { opacity: 0.55; }
+ .note-card-selectmode .note-checkbox-edit,
+ .note-card-selectmode .note-checkbox-rm { display: none; }
+ .note-check-dot::after {
+ content: '';
+ position: absolute;
+ left: 50%;
+ top: 45%;
+ width: 7px;
+ height: 3.5px;
+ border-left: 1.75px solid #fff;
+ border-bottom: 1.75px solid #fff;
+ transform: translate(-50%, -50%) rotate(-45deg) scale(0);
+ transform-origin: center;
+ transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+ .notes-select-mode .note-checkbox { cursor: default; pointer-events: none; }
+ .note-checkbox:active .note-check-dot {
+ transform: scale(0.9);
+ }
+ .note-checkbox.done .note-check-dot::after {
+ transform: translate(-50%, -50%) rotate(-45deg) scale(1);
+ }
+ @keyframes note-check-pop {
+ 0% { transform: scale(1); }
+ 40% { transform: scale(1.35); }
+ 100% { transform: scale(1); }
+ }
+ .note-checkbox.done .note-check-text {
+ position: relative;
+ opacity: 0.4;
+ }
+ .note-checkbox.done .note-check-text::after {
+ content: '';
+ position: absolute;
+ left: 0;
+ right: 0;
+ top: calc(50% - 1px);
+ height: 1px;
+ background: currentColor;
+ animation: note-strike 0.3s ease-out forwards;
+ transform-origin: left center;
+ }
+ @keyframes note-strike {
+ 0% { transform: scaleX(0); }
+ 100% { transform: scaleX(1); }
+ }
+ /* 3D top-edge highlight — an inset 2px stripe inside every note card that
+ reads as a lifted "glassy" lip. Each colored note gets a stronger stripe
+ in its own hue so the colour reads even before you focus on the card. */
+ .note-card { box-shadow: inset 0 2px 0 0 color-mix(in srgb, var(--fg) 14%, transparent); }
+ .note-color-red { box-shadow: inset 0 2px 0 0 color-mix(in srgb, var(--red) 55%, transparent); }
+ .note-color-orange { box-shadow: inset 0 2px 0 0 color-mix(in srgb, #d19a66 60%, transparent); }
+ .note-color-yellow { box-shadow: inset 0 2px 0 0 color-mix(in srgb, var(--hl-string) 60%, transparent); }
+ .note-color-green { box-shadow: inset 0 2px 0 0 color-mix(in srgb, #98c379 60%, transparent); }
+ .note-color-blue { box-shadow: inset 0 2px 0 0 color-mix(in srgb, var(--hl-function) 60%, transparent); }
+ .note-color-purple { box-shadow: inset 0 2px 0 0 color-mix(in srgb, var(--hl-keyword) 60%, transparent); }
+ .note-card.note-standard-v0 { --note-accent: #db8576; }
+ .note-card.note-standard-v1 { --note-accent: #d2a45f; }
+ .note-card.note-standard-v2 { --note-accent: #72ad8d; }
+ .note-card.note-standard-v3 { --note-accent: #72a5cf; }
+ .note-card.note-standard-v4 { --note-accent: #aa86c7; }
+ .note-type-btn:hover { opacity: 0.8; }
+ .note-form-meta .note-form-label {
+ width: 112px;
+ flex: 0 1 140px;
+ }
+ /* After attachColorPicker swaps the input to type=text + .cp-swatch-input,
+ re-pin the swatch to a 24px circle (otherwise it inherits text-input
+ sizing and becomes a giant rectangle). */
+ .note-form-draw-color.cp-swatch-input {
+ width: 24px !important;
+ height: 24px !important;
+ min-width: 24px !important;
+ max-width: 24px !important;
+ border-radius: 50%;
+ padding: 0;
+ box-sizing: border-box;
+ }
+ .note-form-draw-color::-webkit-color-swatch-wrapper { padding: 0; border-radius: 50%; }
+ .note-form-draw-color::-webkit-color-swatch { border: none; border-radius: 50%; }
+ .note-form-draw-color::-moz-color-swatch { border: none; border-radius: 50%; }
+ .note-form-draw-size:hover,
+ .note-form-draw-size:focus,
+ .note-form-draw-size:active { height: 10px; }
+ .note-form-draw-size::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 12px; height: 12px;
+ border-radius: 50%;
+ background: var(--red);
+ border: none;
+ cursor: pointer;
+ transition: width 0.12s ease, height 0.12s ease;
+ }
+ .note-form-draw-size::-moz-range-thumb {
+ width: 12px; height: 12px;
+ border-radius: 50%;
+ background: var(--red);
+ border: none;
+ cursor: pointer;
+ transition: width 0.12s ease, height 0.12s ease;
+ }
+ .note-form-draw-size:hover::-webkit-slider-thumb,
+ .note-form-draw-size:focus::-webkit-slider-thumb,
+ .note-form-draw-size:active::-webkit-slider-thumb { width: 18px; height: 18px; }
+ .note-form-draw-size:hover::-moz-range-thumb,
+ .note-form-draw-size:focus::-moz-range-thumb,
+ .note-form-draw-size:active::-moz-range-thumb { width: 18px; height: 18px; }
+ .note-form-draw-be::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 50%;
+ height: 100%;
+ background: var(--accent);
+ border-radius: 9px;
+ transition: transform 0.28s cubic-bezier(0.34, 1.56, 0.64, 1);
+ z-index: 0;
+ }
+ .note-form-draw-be.is-eraser::before { transform: translateX(100%); }
+ .note-form-draw-be-btn:focus { outline: none; }
+ .note-form-draw-text-badge:empty { display: none; }
+ .note-form-draw-shape-badge:empty { display: none; }
+ /* Reflect the chosen size in the icon itself, so the user sees at a glance
+ which size (S/M/L) is active without needing the tiny badge. */
+ .note-form-draw-line.size-s svg line,
+ .note-form-draw-circle.size-s svg circle { stroke-width: 1.2; }
+ .note-form-draw-line.size-m svg line,
+ .note-form-draw-circle.size-m svg circle { stroke-width: 3; }
+ .note-form-draw-line.size-l svg line,
+ .note-form-draw-circle.size-l svg circle { stroke-width: 5; }
+ .note-form-draw-text.size-s { font-size: 13px; }
+ .note-form-draw-text.size-m { font-size: 18px; }
+ .note-form-draw-text.size-l { font-size: 23px; line-height: 1; }
+ /* Narrow widths: shrink the tag input to make room for the action group;
+ the hashtag-in-content shortcut still works, so the input can be tiny. */
+ @media (max-width: 600px) {
+ .note-form-meta .note-form-label { width: 78px; flex-shrink: 1; min-width: 0; }
+ }
+ .note-form-due:not([value=""]) { opacity: 0.85; border-style: solid; }
+ .note-cl-add:hover { opacity: 0.7; }
+ /* Matching ↵ hint at the right of the event title while it's empty; hidden once
+ editing (the ✓ Done button takes over then). */
+ /* Title placeholder overlay: the prompt text with a ↵ enter glyph right after
+ it (accent), so it's clear the field submits on Enter. Shown only while the
+ title is empty; the native placeholder is hidden in favour of this. */
+ .cal-hero-title::placeholder { color: transparent; }
+ .cal-quickadd-input::placeholder { color: transparent; }
+ button.cal-nav.cal-toolbar-arrow:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--bg) 76%, var(--fg) 24%);
+ }
+ .cal-side-nav-prev { left: 8px; }
+ .cal-side-nav-next { right: 8px; }
+ .cal-navigation-hidden .cal-side-nav {
+ display: none !important;
+ }
+ #cal-add { margin-left: auto; }
+ /* Mobile tap-spin: a gentle quarter-turn nudge before the form opens.
+ `.cal-add-plus` has a `padding-bottom: 2px` (and a translateY on the
+ small variant) that offsets the glyph for optical centering — those
+ shift the rotation pivot off the visual centre. Force the box to
+ match the glyph and pin the transform-origin during the spin. */
+ .cal-add-plus.cal-add-spinning {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0;
+ width: 1em;
+ height: 1em;
+ line-height: 1;
+ transform-origin: 50% 50%;
+ animation: cal-add-spin 0.28s ease-out forwards;
+ }
+ @keyframes cal-add-spin {
+ 0% { transform: rotate(0deg); }
+ 100% { transform: rotate(90deg); }
+ }
+ button.cal-add-btn.cal-add-btn-text.cal-add-btn-sm:hover {
+ padding: 0 8px 0 5px;
+ gap: 3px;
+ }
+ .email-reminder-toggle-inline:hover svg {
+ animation: none !important;
+ transform: none !important;
+ }
+ .email-search-options-menu[hidden],
+ .email-search-options-menu button.hidden {
+ display: none !important;
+ }
+ .email-search-date-panel[hidden] { display: none !important; }
+ .email-search-date-panel label {
+ display: grid;
+ grid-template-columns: 38px 1fr;
+ align-items: center;
+ gap: 6px;
+ margin: 0 0 6px;
+ color: color-mix(in srgb, var(--fg) 72%, transparent);
+ font-size: 10px;
+ }
+ .email-lib-filter-pill-icon-only .email-lib-filter-pill-label { display: none; }
+ .email-lib-filter-pill.email-lib-filter-pill-icon-only { padding-left: 5px !important; }
+ .email-search-options-menu .email-search-date-actions button {
+ width: auto;
+ min-width: 48px;
+ justify-content: center;
+ padding: 5px 8px;
+ }
+ .email-attach-toggle:not(.email-attach-toggle-inline):hover svg {
+ animation: email-undone-jiggle 0.45s ease-in-out;
+ transform-origin: 50% 50%;
+ }
+ @keyframes email-undone-jiggle {
+ 0% { transform: rotate(0deg); }
+ 20% { transform: rotate(-14deg); }
+ 40% { transform: rotate(10deg); }
+ 60% { transform: rotate(-6deg); }
+ 80% { transform: rotate(3deg); }
+ 100% { transform: rotate(0deg); }
+ }
+ .email-undone-toggle:not(.email-undone-toggle-inline):hover svg,
+ .email-compose-jiggle:hover svg {
+ animation: email-undone-jiggle 0.45s ease-in-out;
+ transform-origin: 50% 50%;
+ }
+ /* Account chips collapse to a single horizontally-scrollable strip
+ at every breakpoint, instead of stacking onto multiple rows when
+ there are several accounts. The compose "New" button stays outside
+ the scroller (it's a sibling of #email-lib-accounts inside
+ .email-accounts-row) so it remains pinned on the right. */
+ #email-lib-accounts {
+ justify-content: flex-start;
+ flex-wrap: nowrap;
+ overflow-x: auto;
+ overflow-y: hidden;
+ scrollbar-width: none;
+ -ms-overflow-style: none;
+ scroll-snap-type: x proximity;
+ -webkit-overflow-scrolling: touch;
+ }
+ #email-lib-accounts::-webkit-scrollbar { display: none; height: 0; }
+ #email-lib-accounts > * { flex-shrink: 0; scroll-snap-align: start; }
+ .email-account-chip.email-account-has-unread:not(.active) {
+ border-color: var(--border);
+ background: transparent;
+ color: var(--fg);
+ }
+ #email-lib-grid { position: relative; }
+ #email-lib-grid .date-section-header.email-date-gap-break {
+ margin-top: 12px;
+ padding-top: 16px;
+ }
+ #email-lib-modal.email-reading .email-lib-sync-status {
+ display: none;
+ }
+ button.cal-view-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ border: none;
+ color: var(--fg);
+ font-size: 11px;
+ font-family: inherit;
+ font-weight: 500;
+ padding: 2px 12px 2px 12px;
+ margin: 0;
+ cursor: pointer;
+ opacity: 0.45;
+ line-height: 1;
+ height: 24px;
+ box-sizing: border-box;
+ }
+ .cal-s-color::-webkit-color-swatch-wrapper { padding: 0; border-radius: 50%; }
+ .cal-s-color::-webkit-color-swatch { border: none; border-radius: 50%; }
+ .cal-s-color::-moz-color-swatch { border: none; border-radius: 50%; }
+ .cal-filter-item.cal-filter-off { opacity:0.25; text-decoration:line-through; }
+ .cal-filter-item.cal-filter-important.cal-filter-active { background:color-mix(in srgb, #e5a33a 18%, transparent); border-color:#e5a33a; }
+ .cal-week-row > .cal-day { padding-top: calc(4px + var(--bars, 0) * 12px); }
+ @keyframes cal-slide-from-right {
+ from { opacity:0; transform:translateX(20px); }
+ to { opacity:1; transform:translateX(0); }
+ }
+ @keyframes cal-slide-from-left {
+ from { opacity:0; transform:translateX(-20px); }
+ to { opacity:1; transform:translateX(0); }
+ }
+ @keyframes cal-event-enter {
+ from { opacity:0; transform:translateY(3px) scale(0.985); }
+ to { opacity:1; transform:translateY(0) scale(1); }
+ }
+ .cal-slide-in-right { animation: cal-slide-from-right 0.22s cubic-bezier(0.25, 0.8, 0.25, 1); }
+ .cal-slide-in-left { animation: cal-slide-from-left 0.22s cubic-bezier(0.25, 0.8, 0.25, 1); }
+ .cal-day.cal-today .cal-day-num { color:var(--bg); font-weight:800; background:var(--accent, var(--red)); border-radius:10px; padding:1px 6px; display:inline-block; opacity:1; line-height:1.3; }
+ /* Selected day — same square geometry as `.cal-today` so the two read as
+ peers, but rendered as an outline + softer fill instead of a solid
+ accent block. Today wins when both classes are on the same cell. */
+ .cal-day.cal-selected:not(.cal-today) {
+ box-shadow: inset 0 0 0 2px color-mix(in srgb, var(--accent, var(--fg)) 65%, transparent);
+ background: color-mix(in srgb, var(--accent, var(--fg)) 12%, var(--bg));
+ border-radius: 8px;
+ }
+ .cal-day.cal-weekend:not(.cal-today) { background:color-mix(in srgb, var(--fg) 2.5%, var(--bg)); }
+ .cal-day.cal-empty-day::after {
+ content:'';
+ position:absolute;
+ left:8px;
+ right:8px;
+ bottom:8px;
+ height:1px;
+ background:color-mix(in srgb, var(--fg) 7%, transparent);
+ opacity:0.55;
+ pointer-events:none;
+ }
+ .cal-day.cal-other { opacity:0.34; }
+ .cal-event-row::after {
+ content:'';
+ width:3px;
+ height:11px;
+ margin-left:auto;
+ opacity:0;
+ flex:0 0 auto;
+ border-left:1px solid color-mix(in srgb, var(--fg) 34%, transparent);
+ border-right:1px solid color-mix(in srgb, var(--fg) 34%, transparent);
+ transition:opacity 0.15s;
+ }
+ .cal-event-row:hover::after { opacity:0.75; }
+ .cal-dragging { opacity:0.3; }
+ #cal-body.cal-events-full > :is(.cal-grid, .cal-wk-wrap) {
+ display: none;
+ }
+ #cal-body.cal-events-full > .cal-day-detail {
+ height: auto;
+ min-height: 0;
+ flex: 1 1 auto;
+ }
+ #cal-body.cal-calendar-full > .cal-day-detail {
+ display: none;
+ }
+ .cal-event-link-target {
+ animation: cal-event-link-target-flash 2.2s ease-out;
+ box-shadow:
+ inset 0 0 0 2px color-mix(in srgb, var(--accent, var(--red)) 88%, transparent),
+ 0 0 0 3px color-mix(in srgb, var(--accent, var(--red)) 20%, transparent),
+ 0 8px 20px color-mix(in srgb, var(--accent, var(--red)) 18%, transparent) !important;
+ }
+ @keyframes cal-event-link-target-flash {
+ 0%, 28% {
+ filter: brightness(1.18) saturate(1.12);
+ transform: translateY(-1px);
+ }
+ 100% {
+ filter: none;
+ transform: none;
+ }
+ }
+ .cal-event-loc a, .cal-event-time a { color:inherit; text-decoration:underline; text-decoration-color:color-mix(in srgb, currentColor 40%, transparent); }
+ .cal-event-loc a:hover, .cal-event-time a:hover { opacity:1; text-decoration-color:currentColor; }
+ #cal-settings > svg {
+ top: 3px !important;
+ }
+ .cal-wk-col.cal-wk-today .cal-wk-col-head { background: color-mix(in srgb, var(--accent, var(--red)) 12%, var(--bg)); }
+ .cal-wk-col.cal-wk-today .cal-wk-dn,
+ .cal-wk-col.cal-wk-today .cal-wk-dt { color: var(--accent, var(--red)); font-weight: 700; }
+ /* Sunday: a softer rest-day tint so the week edge reads visually, even
+ when today is mid-week. Falls back gracefully under the .cal-wk-today
+ rules above (today on a Sunday still gets the accent treatment). */
+ .cal-wk-col.cal-wk-sun .cal-wk-col-head { background: color-mix(in srgb, var(--fg) 7%, var(--bg)); }
+ .cal-wk-col.cal-wk-sun .cal-wk-grid { background: color-mix(in srgb, var(--fg) 2.5%, var(--bg)); }
+ .cal-wk-col.cal-wk-sun .cal-wk-allday { background: color-mix(in srgb, var(--fg) 3%, var(--bg)); }
+ .cal-wk-col.cal-wk-sun .cal-wk-dn,
+ .cal-wk-col.cal-wk-sun .cal-wk-dt { color: color-mix(in srgb, var(--fg) 60%, transparent); }
+ .cal-wk-dt { font-variant-numeric: tabular-nums; opacity: 0.5; }
+ .cal-wk-allday::-webkit-scrollbar { display: none; }
+ .cal-wk-now::before {
+ content: '';
+ position: absolute;
+ left: -3px;
+ top: -4px;
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--accent, var(--red, #f87171));
+ box-shadow:0 0 0 3px color-mix(in srgb, var(--accent, var(--red)) 18%, transparent);
+ }
+ .cal-wk-now::after {
+ content:'now';
+ position:absolute;
+ right:4px;
+ top:-10px;
+ padding:1px 5px;
+ border-radius:7px;
+ font-size:8px;
+ line-height:1.2;
+ font-weight:800;
+ text-transform:uppercase;
+ color:var(--bg);
+ background:var(--accent, var(--red));
+ box-shadow:0 1px 4px color-mix(in srgb, #000 22%, transparent);
+ }
+ @keyframes cal-wk-hover-label-reveal {
+ 0%, 35% { opacity: 0; }
+ 100% { opacity: 1; }
+ }
+ .cal-wk-block:hover .cal-wk-block-resize::after {
+ content: '';
+ position: absolute;
+ left: 30%;
+ right: 30%;
+ bottom: 1px;
+ height: 2px;
+ border-radius: 2px;
+ background: color-mix(in srgb, var(--fg) 35%, transparent);
+ }
+ .cal-wk-block::after {
+ content:'';
+ position:absolute;
+ top:6px;
+ right:5px;
+ width:3px;
+ height:14px;
+ opacity:0;
+ border-left:1px solid color-mix(in srgb, var(--fg) 35%, transparent);
+ border-right:1px solid color-mix(in srgb, var(--fg) 35%, transparent);
+ transition:opacity 0.15s;
+ }
+ .cal-wk-block:hover::after { opacity:0.75; }
+ .cal-wk-block-resize:hover::after {
+ background: color-mix(in srgb, var(--fg) 65%, transparent);
+ }
+ /* Body of a block while it's being repositioned: lifted shadow + above
+ siblings so the drop target reads clearly. */
+ .cal-wk-block-ghost {
+ z-index: 6 !important;
+ box-shadow: 0 4px 12px color-mix(in srgb, var(--fg) 24%, transparent) !important;
+ cursor: grabbing;
+ }
+ .cal-wk-block { cursor: grab; }
+ .cal-wk-block:active { cursor: grabbing; }
+ .cal-wk-slot-selected-label {
+ pointer-events: none;
+ }
+ .cal-wk-slot-resize::after {
+ content: '';
+ position: absolute;
+ left: 18%;
+ right: 18%;
+ top: 6px;
+ height: 3px;
+ border-radius: 2px;
+ background: var(--accent, var(--fg));
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--bg) 75%, transparent);
+ }
+ .cal-wk-col.cal-wk-slot-day-selected .cal-wk-col-head {
+ color: var(--accent, var(--fg));
+ box-shadow: inset 0 -2px 0 color-mix(in srgb, var(--accent, var(--fg)) 70%, transparent);
+ }
+ .cal-year-month:hover .cal-year-month-title { opacity:1; color:var(--accent); }
+ .cal-year-day { cursor:pointer; opacity:0.5; }
+ .cal-search-input.cal-day-search:focus { width:100%; }
+ .cal-agenda-day::before {
+ content:'';
+ position:absolute;
+ left:4px;
+ top:22px;
+ bottom:-12px;
+ width:1px;
+ background:color-mix(in srgb, var(--fg) 12%, transparent);
+ }
+ .cal-agenda-day::after {
+ content:'';
+ position:absolute;
+ left:1px;
+ top:12px;
+ width:7px;
+ height:7px;
+ border-radius:50%;
+ background:color-mix(in srgb, var(--fg) 22%, var(--bg));
+ box-shadow:0 0 0 3px var(--bg);
+ }
+ .cal-agenda-day.is-today::after { background:var(--accent, var(--red)); }
+ .cal-agenda-day.is-today .cal-agenda-date { opacity: 1; color: var(--accent, var(--red)); border-bottom-color: color-mix(in srgb, var(--accent, var(--red)) 35%, var(--border)); }
+ .cal-agenda-event:hover .cal-event-more,
+ .cal-event-item:hover .cal-event-more { opacity:0.6; }
+ button.cal-event-more {
+ background:transparent;
+ border:none;
+ color:var(--fg);
+ width:20px; height:20px;
+ cursor:pointer;
+ padding:0;
+ display:inline-flex;
+ align-items:center;
+ justify-content:center;
+ font-family:inherit;
+ flex-shrink:0;
+ margin-left:auto;
+ align-self:center;
+ transform:translateY(-4px);
+ transition:opacity 0.15s;
+ }
+ button.cal-event-more:hover { opacity:1 !important; }
+ /* Day-detail "+ New" button nudged down 2px. */
+ #cal-add-day { position: relative; top: 2px; }
+ /* Accent the native date/time picker glyphs. We recolor the webkit indicator
+ by masking an accent fill through a calendar/clock SVG (same technique as the
+ mono icon picker). accent-color covers the spinner parts where supported. */
+ .cal-form-bespoke input[type="date"],
+ .cal-form-bespoke input[type="time"],
+ .cal-form-bespoke input[type="datetime-local"] { accent-color: var(--accent, var(--red)); }
+ .cal-form-bespoke input[type="date"]::-webkit-datetime-edit-month-field,
+ .cal-form-bespoke input[type="date"]::-webkit-datetime-edit-day-field {
+ color: var(--accent, var(--red));
+ font-weight: 600;
+ }
+ .cal-form-bespoke input[type="date"]::-webkit-datetime-edit-year-field {
+ color: var(--fg);
+ font-weight: 400;
+ }
+ .cal-form-bespoke input[type="date"]::-webkit-calendar-picker-indicator,
+ .cal-form-bespoke input[type="time"]::-webkit-calendar-picker-indicator,
+ .cal-form-bespoke input[type="datetime-local"]::-webkit-calendar-picker-indicator {
+ background-color: var(--accent, var(--red));
+ background-image: none;
+ cursor: pointer;
+ width: 14px; height: 14px;
+ }
+ .cal-form-bespoke input[type="date"]::-webkit-calendar-picker-indicator,
+ .cal-form-bespoke input[type="datetime-local"]::-webkit-calendar-picker-indicator {
+ -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='18' height='18' rx='2'/%3E%3Cline x1='16' y1='2' x2='16' y2='6'/%3E%3Cline x1='8' y1='2' x2='8' y2='6'/%3E%3Cline x1='3' y1='10' x2='21' y2='10'/%3E%3C/svg%3E") center/contain no-repeat;
+ mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='18' height='18' rx='2'/%3E%3Cline x1='16' y1='2' x2='16' y2='6'/%3E%3Cline x1='8' y1='2' x2='8' y2='6'/%3E%3Cline x1='3' y1='10' x2='21' y2='10'/%3E%3C/svg%3E") center/contain no-repeat;
+ }
+ .cal-form-bespoke input[type="time"]::-webkit-calendar-picker-indicator {
+ -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'/%3E%3Cpolyline points='12 6 12 12 16 14'/%3E%3C/svg%3E") center/contain no-repeat;
+ mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'/%3E%3Cpolyline points='12 6 12 12 16 14'/%3E%3C/svg%3E") center/contain no-repeat;
+ }
+ /* Title underline + clock focus ring + primary button track --ev-color
+ when set; default to --accent / --fg otherwise. */
+ .cal-form-bespoke .cal-input.cal-hero-title:focus { border-bottom-color: var(--ev-color, var(--accent, color-mix(in srgb, var(--fg) 60%, transparent))); }
+ .cal-form-bespoke[style*="--ev-color"] .cal-input.cal-hero-title { border-bottom-color: color-mix(in srgb, var(--ev-color) 35%, var(--border)); }
+ .cal-form-bespoke .cal-hero-time:focus-visible,
+ .cal-form-bespoke .cal-hero-date:focus-visible { outline-color: var(--ev-color, var(--accent, color-mix(in srgb, var(--fg) 50%, transparent))); }
+ /* Custom-BG events paint the form card with the uploaded image. Make sure
+ the action row + buttons stay clearly readable on top of it. */
+ .cal-form-bespoke.cal-form-bg-image .cal-form-actions {
+ position: relative;
+ z-index: 2;
+ /* Solid backing strip so the Save/Cancel/Delete buttons don't fade into
+ the photo behind them. */
+ background: color-mix(in srgb, var(--panel) 92%, transparent);
+ margin: 8px -14px -14px;
+ padding: 10px 14px;
+ border-top: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
+ border-radius: 0 0 8px 8px;
+ }
+ .cal-form-today span { letter-spacing: 0.04em; text-transform: none; opacity: 0.85; font-weight: 500; }
+ .cal-hero-time .cal-hero-clock,
+ .cal-hero-time .cal-hero-ampm { line-height: 1; }
+ .cal-hero-time:focus-visible { outline: 2px solid var(--accent, color-mix(in srgb, var(--fg) 50%, transparent)); outline-offset: 2px; }
+ .cal-hero-date:focus-visible { outline: 2px solid var(--accent, color-mix(in srgb, var(--fg) 50%, transparent)); outline-offset: 2px; }
+ .cal-input.cal-hero-title:focus {
+ border-color: transparent;
+ border-bottom-color: var(--accent, color-mix(in srgb, var(--fg) 60%, transparent));
+ }
+ .cal-form-bespoke.is-expanded .cal-form-details {
+ max-height: 720px;
+ opacity: 1;
+ margin-top: 4px;
+ }
+ .cal-form-bespoke .cal-form-actions { margin-top: 8px; justify-content: flex-end; }
+ .cal-form-bespoke .cal-form-row { margin-bottom: 8px; }
+ .cal-loc-input-wrap > input { height: 100%; }
+ .cal-loc-input-wrap > input::placeholder { color: transparent; }
+ .cal-loc-hint svg { color: var(--accent, var(--red)); }
+ .cal-loc-input-wrap > input:placeholder-shown ~ .cal-loc-hint { display: inline-flex; }
+ .cal-loc-map.is-disabled { opacity: 0.3; pointer-events: none; cursor: default; }
+ select.cal-input { appearance:auto; }
+ textarea.cal-input { resize:vertical; font-family:inherit; }
+ button.cal-btn.cal-btn-danger { color:var(--accent, var(--red)); border-color:var(--accent, var(--red)); background:transparent; }
+ button.cal-btn.cal-btn-danger:hover { background:var(--accent, var(--red)); color:var(--bg); }
+ /* Brief outline flash on a note card when it's the target of a
+ #note-<id> link click from chat — same pattern as the cookbook
+ task flash, just scoped to .note-card. */
+ .note-card-flash {
+ animation: note-card-flash-anim 1.6s ease-out;
+ }
+ @keyframes note-card-flash-anim {
+ 0% { box-shadow: 0 0 0 2px var(--accent, var(--red)); }
+ 100% { box-shadow: 0 0 0 2px transparent; }
+ }
diff --cc static/js/emailLibrary.js
index f20a7a978,b87e25e6c..06c7994b2
--- a/static/js/emailLibrary.js
+++ b/static/js/emailLibrary.js
@@@ -1,11389 -1,26 +1,27 @@@
- /**
- * emailLibrary.js — Email library popup modal.
- * Similar pattern to documentLibrary.js. Shows emails in a grid with search/filter.
- */
-
- import spinnerModule from './spinner.js';
- import { styledConfirm, showToast, emptyStateIcon } from './ui.js?v=20260916largetoolscroll1';
- import { folderDisplayName, sortedFolders } from './emailInbox.js?v=20260914aireply4';
- import settingsModule from './settings.js?v=20260912writingstyle3';
- import * as Modals from './modalManager.js';
- import { topPortalZ } from './toolWindowZOrder.js';
- import { makeWindowDraggable } from './windowDrag.js';
- import { orderActionMenuItems, actionMenuRank, SELECT_MENU_ICON } from './actionMenuOrder.js';
- import {
- _esc, _escLinkify, _extractName, _parseTurnMeta,
- _formatBubbleDate, _formatRecipients, _senderColor, _initials,
- _sanitizeHtml, _renderEmailSummaryError,
- _TALON_WROTE, _TALON_FROM, _TALON_SENT, _TALON_SUBJ, _TALON_TO,
- _TALON_ORIG_RE, _SIG_BLOAT_MIN_CHARS,
- } from './emailLibrary/utils.js';
- import {
- _looksLikeSignature, _harvestAttribution, _extractTurnMetaFromBlockquote,
- _foldSummary, _extractQuoteMeta, _peelSigNameLine, _isBloatedSig,
- _tryFoldHintSig, _foldSignature, _SIG_ICON, _QUOTE_ICON,
- } from './emailLibrary/signatureFold.js';
- import { state } from './emailLibrary/state.js';
- import { getSettings } from './appConfig.js';
- import { collapseSidebarToRail } from './modalSnap.js';
- import { emailApiUrl } from './emailShared.js';
- import {
- bindMenuDismiss,
- dismissOrRemove,
- dismissTopMenu,
- bindExpandedCardDismiss,
- unbindExpandedCardDismiss,
- } from './escMenuStack.js';
-
- const API_BASE = window.location.origin;
- let _emailUnreadChipClickWired = false;
- let _libLoadSeq = 0;
- let _emailMailboxGeneration = 0;
- let _emailCardOpenSeq = 0;
- let _emailReadMutationSeq = 0;
- const _emailReadMutations = new Map();
- let _libFolderSeq = 0;
- let _libSearchSeq = 0;
- let _libSearchHadResults = false;
- let _libSearchInFlight = false;
- let _activeEmailReaderForSelectAll = null;
- let _libAccountsLoadedAt = 0;
- const _LIB_ACCOUNTS_TTL_MS = 5 * 60 * 1000;
- let _accountUnreadSeq = 0;
- let _accountUnreadState = new Map(); // account_id -> { unreadCount, maxUid }
- let _autoReplyRefreshSeq = 0;
-
- function _hasActiveEmailSearchResults() {
- if (!_libSearchHadResults) return false;
- if (String(state._libSearch || '').trim()) return true;
- return (state._libSearchPills || []).some(p => p?.type === 'text' || p?.type === 'contact');
- }
-
- function _emailInlineImagesStorageKey(accountId = state._libAccountId) {
- return `odysseus.email.viewInlineImages.${String(accountId || 'default')}`;
- }
-
- function _readEmailInlineImagesPreference(accountId = state._libAccountId) {
- try {
- const stored = localStorage.getItem(_emailInlineImagesStorageKey(accountId));
- return stored === null ? true : stored !== '0';
- } catch (_) {
- return true;
- }
- }
-
- function _writeEmailInlineImagesPreference(enabled, accountId = state._libAccountId) {
- try {
- localStorage.setItem(_emailInlineImagesStorageKey(accountId), enabled ? '1' : '0');
- } catch (_) {}
- }
-
- async function _disableInlineImages(accountId = state._libAccountId) {
- state._libViewInlineImages = false;
- _writeEmailInlineImagesPreference(false, accountId);
- document.querySelectorAll('#email-settings-view-inline-images').forEach(toggle => {
- toggle.checked = true;
- toggle.dispatchEvent(new Event('change', { bubbles: true }));
- });
- try {
- const res = await fetch(emailApiUrl('/api/email/config', {
- account_id: accountId || undefined,
- }), {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- credentials: 'include',
- body: JSON.stringify({ email_view_inline_images: false }),
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- } catch (err) {
- console.error('Failed to disable inline images:', err);
- }
- }
-
- const _EMAIL_SETTINGS_ICON = `<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 15.5A3.5 3.5 0 1 0 12 8a3.5 3.5 0 0 0 0 7.5Z"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06A2 2 0 1 1 7.04 4.3l.06.06A1.65 1.65 0 0 0 8.92 4a1.65 1.65 0 0 0 1-1.51V2a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82 1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z"/></svg>`;
- const _EMAIL_SAVE_ICON = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2Z"/><path d="M17 21v-8H7v8"/><path d="M7 3v5h8"/></svg>';
- const _EMAIL_SAVED_ICON = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>';
-
- function _setEmailSaveIcon(button, saved) {
- if (!button) return;
- const icon = button.querySelector('svg');
- if (icon) icon.outerHTML = saved ? _EMAIL_SAVED_ICON : _EMAIL_SAVE_ICON;
- button.classList.toggle('is-saved', !!saved);
- }
- const _DEFAULT_AUTO_REPLY_SUBJECT = '(Away) {subject}';
- const _DEFAULT_AUTO_REPLY_MESSAGE = "Thanks for your email. I'm away and may be slower to reply.";
-
- function _normalizeEmailStateFlags(em) {
- if (!em || typeof em !== 'object') return em;
- const flags = String(em.flags || '');
- const answered = !!(
- em.is_answered ||
- em.is_done ||
- em.done ||
- em.answered ||
- flags.includes('\\Answered')
- );
- // Once the normalized field exists, it is the source of truth. Some
- // cached/fixture rows also retain legacy aliases such as `favorite`; OR-ing
- // those aliases on every render would resurrect a favorite immediately
- // after the user turns it off.
- const flagged = Object.prototype.hasOwnProperty.call(em, 'is_flagged')
- ? !!em.is_flagged
- : !!(
- em.is_favorite ||
- em.favorite ||
- em.flagged ||
- em.starred ||
- flags.includes('\\Flagged')
- );
- const read = !!(
- em.is_read ||
- em.read ||
- flags.includes('\\Seen')
- );
- em.is_answered = answered;
- em.is_done = answered;
- em.is_flagged = flagged;
- em.is_read = read;
- return em;
- }
-
- function _normalizeAutoReplyConfig(cfg = {}) {
- const normalized = Object.prototype.hasOwnProperty.call(cfg, 'enabled');
- return {
- enabled: normalized ? !!cfg.enabled : !!cfg.email_auto_reply,
- start: String(normalized ? (cfg.start || '') : (cfg.email_auto_reply_start || '')),
- end: String(normalized ? (cfg.end || '') : (cfg.email_auto_reply_end || '')),
- subject: String(normalized ? (cfg.subject || _DEFAULT_AUTO_REPLY_SUBJECT) : (cfg.email_auto_reply_subject || _DEFAULT_AUTO_REPLY_SUBJECT)),
- message: String(normalized ? (cfg.message || '') : (cfg.email_auto_reply_message || '')),
- cooldown: String(normalized ? (cfg.cooldown || 'period') : (cfg.email_auto_reply_cooldown || 'period')),
- scope: String(normalized ? (cfg.scope || 'all') : (cfg.email_auto_reply_scope || 'all')),
- accountId: String(normalized ? (cfg.accountId || '') : (cfg.email_auto_reply_account_id || '')),
- excludeAutomated: normalized ? cfg.excludeAutomated !== false : cfg.email_auto_reply_exclude_automated !== false,
- pauseNotifications: normalized ? !!cfg.pauseNotifications : !!cfg.email_auto_reply_pause_notifications,
- viewInlineImages: normalized ? cfg.viewInlineImages !== false : cfg.email_view_inline_images !== false,
- };
- }
-
- function _autoReplyDateValue(value) {
- const s = String(value || '').trim();
- const m = s.match(/^(\d{4}-\d{2}-\d{2})/);
- return m ? m[1] : '';
- }
-
- function _todayDateInputValue() {
- const now = new Date();
- const pad = value => String(value).padStart(2, '0');
- return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
- }
-
- const _AUTO_REPLY_CALENDAR_KEY_PREFIX = 'odysseus.email.autoReplyCalendarEvent.';
- const _autoReplyCalendarSyncs = new Map();
-
- function _autoReplyCalendarKey(accountId) {
- return `${_AUTO_REPLY_CALENDAR_KEY_PREFIX}${String(accountId || '').trim()}`;
- }
-
- function _readAutoReplyCalendarUid(accountId) {
- if (!accountId) return '';
- try { return String(localStorage.getItem(_autoReplyCalendarKey(accountId)) || ''); } catch (_) { return ''; }
- }
-
- function _writeAutoReplyCalendarUid(accountId, uid) {
- if (!accountId) return;
- try {
- if (uid) localStorage.setItem(_autoReplyCalendarKey(accountId), uid);
- else localStorage.removeItem(_autoReplyCalendarKey(accountId));
- } catch (_) {}
- }
-
- function _addLocalCalendarDays(value, days) {
- const match = String(value || '').match(/^(\d{4})-(\d{2})-(\d{2})$/);
- if (!match) return '';
- const date = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]) + days);
- const pad = n => String(n).padStart(2, '0');
- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
- }
-
- function _autoReplyCalendarPayload(cfg, accountId = state._libAccountId) {
- const start = _autoReplyDateValue(cfg?.start) || _todayDateInputValue();
- let end = _autoReplyDateValue(cfg?.end) || start;
- if (end < start) end = start;
- return {
- summary: 'Email Auto Reply (away)',
- dtstart: start,
- dtend: _addLocalCalendarDays(end, 1),
- all_day: true,
- description: `Odysseus email auto reply - account:${String(accountId || '')}`,
- };
- }
-
- async function _findAutoReplyCalendarEventUids(cfg, accountId) {
- const start = _autoReplyDateValue(cfg?.start) || _todayDateInputValue();
- const end = _autoReplyDateValue(cfg?.end) || start;
- const startYear = Number(start.slice(0, 4)) || new Date().getFullYear();
- const endYear = Math.max(startYear, Number(end.slice(0, 4)) || startYear);
- try {
- const response = await fetch(`${API_BASE}/api/calendar/events?start=${startYear - 1}-01-01&end=${endYear + 2}-01-01`, {
- credentials: 'same-origin',
- });
- if (!response.ok) return [];
- const data = await response.json().catch(() => ({}));
- const marker = `Odysseus email auto reply - account:${String(accountId || '')}`;
- return (data.events || [])
- .filter(ev => String(ev?.description || '').startsWith(marker))
- .map(ev => String(ev?.uid || '').trim())
- .filter(Boolean);
- } catch (_) {
- return [];
- }
- }
-
- async function _syncAutoReplyCalendarEventNow(cfg, accountId) {
- accountId = String(accountId || '').trim();
- if (!accountId) return false;
- let uid = _readAutoReplyCalendarUid(accountId);
- const headers = { 'Content-Type': 'application/json' };
- const request = (url, options = {}) => fetch(url, {
- credentials: 'same-origin',
- ...options,
- headers: { ...headers, ...(options.headers || {}) },
- });
-
- if (!cfg?.enabled) {
- const knownUids = new Set(uid ? [uid] : []);
- (await _findAutoReplyCalendarEventUids(cfg, accountId)).forEach(foundUid => knownUids.add(foundUid));
- for (const eventUid of knownUids) {
- const response = await request(`${API_BASE}/api/calendar/events/${encodeURIComponent(eventUid)}`, { method: 'DELETE' });
- if (!response.ok && response.status !== 404) throw new Error(`Calendar HTTP ${response.status}`);
- }
- _writeAutoReplyCalendarUid(accountId, '');
- return true;
- }
-
- const payload = _autoReplyCalendarPayload(cfg, accountId);
- if (!uid) {
- uid = (await _findAutoReplyCalendarEventUids(cfg, accountId))[0] || '';
- if (uid) _writeAutoReplyCalendarUid(accountId, uid);
- }
- if (uid) {
- const response = await request(`${API_BASE}/api/calendar/events/${encodeURIComponent(uid)}`, {
- method: 'PUT', body: JSON.stringify(payload),
- });
- if (response.ok) return true;
- if (response.status !== 404) throw new Error(`Calendar HTTP ${response.status}`);
- _writeAutoReplyCalendarUid(accountId, '');
- }
-
- const response = await request(`${API_BASE}/api/calendar/events`, {
- method: 'POST', body: JSON.stringify(payload),
- });
- const data = await response.json().catch(() => ({}));
- if (!response.ok || !data.uid) throw new Error(`Calendar HTTP ${response.status}`);
- _writeAutoReplyCalendarUid(accountId, data.uid);
- return true;
- }
-
- function _syncAutoReplyCalendarEvent(cfg) {
- const accountId = String(state._libAccountId || '').trim();
- if (!accountId) return Promise.resolve(false);
- const previous = _autoReplyCalendarSyncs.get(accountId) || Promise.resolve();
- const next = previous.catch(() => {}).then(() => _syncAutoReplyCalendarEventNow(cfg, accountId));
- _autoReplyCalendarSyncs.set(accountId, next);
- return next.finally(() => {
- if (_autoReplyCalendarSyncs.get(accountId) === next) _autoReplyCalendarSyncs.delete(accountId);
- });
- }
-
- function _isAutoReplyActiveForCurrentAccount(cfg) {
- cfg = _normalizeAutoReplyConfig(cfg || {});
- if (!cfg.enabled) return false;
- if (cfg.scope === 'account' && cfg.accountId && cfg.accountId !== String(state._libAccountId || '')) return false;
- const today = new Date().toISOString().slice(0, 10);
- const start = _autoReplyDateValue(cfg.start);
- const end = _autoReplyDateValue(cfg.end);
- if (start && today < start) return false;
- if (end && today > end) return false;
- return true;
- }
-
- function _syncEmailAutoReplyTitle(active) {
- const titleText = document.getElementById('email-lib-title-text');
- const statusDot = document.getElementById('email-lib-auto-reply-status-dot');
- const badge = document.getElementById('email-lib-auto-reply-badge');
- if (titleText) titleText.textContent = active ? 'Auto Reply - Active' : 'Email';
- if (statusDot) statusDot.style.display = active ? 'inline-block' : 'none';
- if (badge) {
- badge.style.display = 'none';
- badge.textContent = 'Auto Reply';
- }
- }
-
- async function _fetchEmailSettingsConfig() {
- const res = await fetch(emailApiUrl('/api/email/config', {
- account_id: state._libAccountId || undefined,
- }), { credentials: 'include' });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const normalized = _normalizeAutoReplyConfig(await res.json());
- state._libViewInlineImages = normalized.viewInlineImages;
- _writeEmailInlineImagesPreference(state._libViewInlineImages);
- return normalized;
- }
-
- async function _fetchEmailWritingStyle() {
- const res = await fetch(emailApiUrl('/api/email/style', {
- account_id: state._libAccountId || undefined,
- }), { credentials: 'include' });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const data = await res.json().catch(() => ({}));
- return String(data.style || '');
- }
-
- function _emailSettingsLoadingHtml(label = 'Loading') {
- const wp = spinnerModule.createWhirlpool(16);
- const host = document.createElement('span');
- host.className = 'email-settings-loading-spinner';
- host.appendChild(wp.element);
- const wrap = document.createElement('div');
- wrap.className = 'email-settings-loading';
- wrap.appendChild(host);
- const text = document.createElement('span');
- text.textContent = label;
- wrap.appendChild(text);
- return wrap.outerHTML;
- }
-
- function _emailSettingsFormHtml(cfg) {
- const activeAccount = state._libAccounts?.find(a => a && a.id === state._libAccountId);
- const accountAddress = activeAccount
- ? String(activeAccount.from_address || activeAccount.imap_user || activeAccount.email || '').trim()
- : '';
- const accountScope = accountAddress
- ? ` <span class="email-settings-account-scope">(${_esc(accountAddress)})</span>`
- : '';
- return `
- <div class="admin-card email-settings-section email-settings-auto-reply-section">
- <div class="email-settings-section-head">
- <div>
- <div class="email-settings-auto-reply-title-row">
- <div class="email-settings-section-title"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg><span>Auto Reply${accountScope}</span></div>
- <div class="email-settings-enabled-control">
- <span class="email-settings-enabled-state"></span>
- <label class="email-settings-toggle admin-switch">
- <input type="checkbox" id="email-auto-reply-enabled" ${cfg.enabled ? 'checked' : ''}>
- <span class="admin-slider"></span>
- </label>
- </div>
- </div>
- <div class="email-settings-section-desc">Holiday or away replies for incoming mail.</div>
- </div>
- </div>
- <div id="email-settings-auto-reply-body" class="email-settings-section-body">
- <div class="email-settings-grid">
- <label><span>Start date</span><input type="date" id="email-auto-reply-start" value="${_esc(_autoReplyDateValue(cfg.start))}"></label>
- <label><span>End date</span><input type="date" id="email-auto-reply-end" value="${_esc(_autoReplyDateValue(cfg.end))}"></label>
- </div>
- <label class="email-settings-field">
- <span>Subject</span>
- <input type="text" id="email-auto-reply-subject" value="${_esc(cfg.subject || _DEFAULT_AUTO_REPLY_SUBJECT)}" placeholder="${_esc(_DEFAULT_AUTO_REPLY_SUBJECT)}">
- </label>
- <label class="email-settings-field">
- <span>Message</span>
- <textarea id="email-auto-reply-message" rows="4">${_esc(cfg.message || _DEFAULT_AUTO_REPLY_MESSAGE)}</textarea>
- </label>
- <label class="email-settings-field">
- <span>Send to same sender</span>
- <select id="email-auto-reply-cooldown">
- <option value="period" ${cfg.cooldown === 'period' ? 'selected' : ''}>Once while active</option>
- <option value="1d" ${cfg.cooldown === '1d' ? 'selected' : ''}>Every day</option>
- <option value="3d" ${cfg.cooldown === '3d' ? 'selected' : ''}>Every 3 days</option>
- <option value="7d" ${cfg.cooldown === '7d' ? 'selected' : ''}>Every 7 days</option>
- </select>
- </label>
- <label class="email-settings-check">
- <span>Pause email notifications while active</span>
- <span class="email-settings-check-spacer"></span>
- <span class="admin-switch"><input type="checkbox" id="email-auto-reply-pause" ${cfg.pauseNotifications ? 'checked' : ''}><span class="admin-slider"></span></span>
- </label>
- </div>
- </div>
- `;
- }
-
- function _emailCleanupSettingsHtml() {
- const activeAccount = state._libAccounts?.find(a => a && a.id === state._libAccountId);
- const accountAddress = activeAccount
- ? String(activeAccount.from_address || activeAccount.imap_user || activeAccount.email || '').trim()
- : '';
- const accountScope = accountAddress
- ? ` <span class="email-settings-account-scope">(${_esc(accountAddress)})</span>`
- : '';
- return `
- <div class="admin-card email-settings-section email-settings-cleanup-section">
- <div class="email-settings-section-head">
- <div>
- <span class="email-settings-section-title"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg><span>Newsletter Unsubscribe${accountScope}</span></span>
- <div class="email-settings-section-desc">Find newsletter and ad emails with unsubscribe options.</div>
- </div>
- </div>
- <div id="email-settings-cleanup-body" class="email-settings-section-body">
- <div class="email-settings-clean-actions">
- <span class="email-unsub-status email-settings-clean-status" style="font-size:12px;color:color-mix(in srgb,var(--fg) 68%,transparent);"></span>
- <button type="button" class="memory-toolbar-btn email-settings-clean-btn">
- <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" style="vertical-align:-1px;margin-right:2px;color:var(--accent,var(--red));"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>
- <span>Clean</span>
- </button>
- <button type="button" class="memory-toolbar-btn email-settings-save">
- <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2Z"/><path d="M17 21v-8H7v8"/><path d="M7 3v5h8"/></svg>
- Save
- </button>
- </div>
- </div>
- </div>
- `;
- }
-
- function _emailDisplaySettingsHtml(cfg = {}) {
- return `
- <div class="admin-card email-settings-section email-settings-display-section">
- <div class="email-settings-section-head">
- <div>
- <div class="email-settings-display-title-row">
- <div class="email-settings-section-title"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20.59 13.41 11 3.83A2 2 0 0 0 9.59 3H4a1 1 0 0 0-1 1v5.59A2 2 0 0 0 3.59 11l9.59 9.59a2 2 0 0 0 2.82 0l4.59-4.59a2 2 0 0 0 0-2.82Z"/><path d="M7 7h.01"/></svg><span>Show Email Tags</span></div>
- <span class="email-settings-enabled-control">
- <span class="email-settings-enabled-state email-settings-display-enabled-state"></span>
- <label class="email-settings-toggle admin-switch">
- <input type="checkbox" id="email-settings-show-tags" ${state._libShowTags ? 'checked' : ''}>
- <span class="admin-slider"></span>
- </label>
- </span>
- </div>
- <div class="email-settings-section-desc email-settings-support-copy">Choose which labels appear on email cards. <span class="email-settings-display-task-note">Turn off tagging in <button type="button" class="email-settings-inline-link" data-open-email-tasks>Tasks</button></span></div>
- </div>
- </div>
- <div class="email-settings-display-spacer" aria-hidden="true"></div>
- </div>
- <div class="admin-card email-settings-section email-settings-inline-images-section">
- <div class="email-settings-section-head">
- <div>
- <div class="email-settings-display-title-row">
- <div class="email-settings-section-title"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg><span>Hide Inline Images</span></div>
- <span class="email-settings-enabled-control">
- <span class="email-settings-enabled-state email-settings-inline-images-enabled-state"></span>
- <label class="email-settings-toggle admin-switch">
- <input type="checkbox" id="email-settings-view-inline-images" ${cfg.viewInlineImages === false ? 'checked' : ''}>
- <span class="admin-slider"></span>
- </label>
- </span>
- </div>
- <div class="email-settings-section-desc email-settings-support-copy">Keep images embedded in email bodies hidden until you load them.</div>
- </div>
- </div>
- <div class="email-settings-inline-images-spacer" aria-hidden="true"></div>
- </div>
- `;
- }
-
- function _emailSettingsAccountSelectHtml() {
- const accounts = Array.isArray(state._libAccounts)
- ? state._libAccounts
- .filter(a => a && a.enabled !== false)
- .slice()
- .sort((a, b) => Number(!!b.is_default) - Number(!!a.is_default))
- : [];
- if (!accounts.length) return '';
- const nameCounts = new Map();
- accounts.forEach(a => {
- const name = String(a.name || '').trim();
- if (name) nameCounts.set(name, (nameCounts.get(name) || 0) + 1);
- });
- const opts = accounts.map(a => {
- const name = String(a.name || '').trim();
- const address = String(a.from_address || a.imap_user || '').trim();
- const label = name && nameCounts.get(name) > 1 && address
- ? `${name} · ${address}`
- : (name || address || 'account');
- const suffix = a.is_default ? ' · (default)' : '';
- return `<option value="${_esc(a.id || '')}" ${state._libAccountId === a.id ? 'selected' : ''}>${_esc(label + suffix)}</option>`;
- }).join('');
- const selected = accounts.find(a => a.id === state._libAccountId) || accounts[0];
- const active = !!selected?.is_default;
- const icon = active
- ? '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><polyline points="8 12 11 15 16 9"/></svg>'
- : '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/></svg>';
- const defaultTitle = active ? 'Default account' : 'Make this the default account';
- return `<div class="email-settings-account-picker" style="margin-left:auto;display:inline-flex;align-items:center;gap:8px;">`
- + `<span class="cookbook-srv-default email-settings-default${active ? ' active' : ''}" role="button" tabindex="0" aria-pressed="${active ? 'true' : 'false'}" data-email-default-id="${_esc(selected?.id || '')}" title="${defaultTitle}"><span class="cookbook-srv-default-icon" aria-hidden="true">${icon}</span><span class="cookbook-srv-default-label">default</span></span>`
- + `<select id="email-settings-account-select" class="memory-toolbar-btn" title="Active email for all email settings" style="height:28px;max-width:240px;position:relative;top:-2px;">${opts}</select>`
- + `</div>`;
- }
-
- function _syncEmailSettingsAccountPicker(page) {
- const select = page?.querySelector('#email-settings-account-select');
- const selected = (state._libAccounts || []).find(a => a && a.id === state._libAccountId);
- if (select && selected) {
- [...select.options]
- .sort((a, b) => {
- const aAccount = (state._libAccounts || []).find(account => account && account.id === a.value);
- const bAccount = (state._libAccounts || []).find(account => account && account.id === b.value);
- return Number(!!bAccount?.is_default) - Number(!!aAccount?.is_default);
- })
- .forEach(option => select.appendChild(option));
- select.value = selected.id;
- [...select.options].forEach(option => {
- const account = (state._libAccounts || []).find(a => a && a.id === option.value);
- if (!account) return;
- const label = account.name || account.from_address || account.imap_user || 'account';
- option.textContent = label + (account.is_default ? ' · (default)' : '');
- });
- }
- const toggle = page?.querySelector('.email-settings-default');
- if (!toggle || !selected) return;
- const active = !!selected.is_default;
- toggle.classList.toggle('active', active);
- toggle.setAttribute('aria-pressed', active ? 'true' : 'false');
- toggle.dataset.emailDefaultId = selected.id || '';
- toggle.title = active ? 'Default account' : 'Make this the default account';
- toggle.querySelector('.cookbook-srv-default-icon').innerHTML = active
- ? '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><polyline points="8 12 11 15 16 9"/></svg>'
- : '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/></svg>';
- }
-
- function _emailWritingStyleHtml(style) {
- return `
- <div class="admin-card email-settings-section email-settings-style-section">
- <div class="email-settings-section-head">
- <div>
- <div class="email-settings-section-title"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg><span>Email Reply Writing Style</span></div>
- <div class="email-settings-section-desc email-settings-support-copy">Used when Odysseus drafts replies for you.</div>
- </div>
- </div>
- <div id="email-settings-style-body" class="email-settings-section-body">
- <label class="email-settings-field">
- <span>Writing style</span>
- <textarea id="email-writing-style-text" rows="6">${_esc(style)}</textarea>
- </label>
- <div class="email-settings-actions">
- <button type="button" class="memory-toolbar-btn email-style-settings-extract">
- <svg class="email-unsub-accent-icon" width="11" height="11" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>
- Extract
- </button>
- <button class="email-style-extract-help" aria-label="What does Extract do?" title="Extract analyzes sent emails from the selected account and saves a writing-style prompt for AI replies.">?</button>
- <button type="button" class="memory-toolbar-btn email-style-settings-save">
- <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2Z"/><path d="M17 21v-8H7v8"/><path d="M7 3v5h8"/></svg>
- Save
- </button>
- </div>
- </div>
- </div>
- `;
- }
-
- async function _showEmailSettingsPage() {
- const modal = document.getElementById('email-lib-modal');
- const page = document.getElementById('email-lib-settings-page');
- const btn = document.getElementById('email-lib-settings-btn');
- if (!modal || !page) return;
- modal.classList.add('email-settings-mode');
- page.hidden = false;
- page.scrollTop = 0;
- page.querySelector('.email-settings-body')?.scrollTo(0, 0);
- const headerBackBtn = document.getElementById('email-settings-header-back');
- if (headerBackBtn) headerBackBtn.style.display = 'inline-flex';
- btn?.classList.add('active');
- btn?.setAttribute('aria-expanded', 'true');
- page.innerHTML = `
- <div class="email-settings-page-head">
- <h2 class="email-settings-title">${_EMAIL_SETTINGS_ICON}<span>Email Settings</span></h2>
- </div>
- <div class="email-settings-body">
- ${_emailSettingsLoadingHtml()}
- </div>
- `;
- let cfg;
- let writingStyle = '';
- try {
- await _loadAccounts().catch(() => {});
- const head = page.querySelector('.email-settings-page-head');
- const accountSelectHtml = _emailSettingsAccountSelectHtml();
- const oldPicker = page.querySelector('.email-settings-account-picker');
- if (oldPicker) oldPicker.remove();
- const title = head?.querySelector('.email-settings-title');
- if (title && accountSelectHtml) title.insertAdjacentHTML('beforeend', accountSelectHtml);
- [cfg, writingStyle] = await Promise.all([
- _fetchEmailSettingsConfig(),
- _fetchEmailWritingStyle().catch(() => ''),
- ]);
- } catch (err) {
- page.querySelector('.email-settings-body').innerHTML = `<div class="email-settings-error">Could not load settings.</div>`;
- return;
- }
- page.querySelector('.email-settings-body').innerHTML = _emailWritingStyleHtml(writingStyle) + _emailDisplaySettingsHtml(cfg) + _emailCleanupSettingsHtml() + _emailSettingsFormHtml(cfg);
- page.querySelector('.email-settings-body')?.scrollTo(0, 0);
- state._libAutoReplyActive = _isAutoReplyActiveForCurrentAccount(cfg);
- state._libAutoReplyDraftActive = null;
- _syncEmailAutoReplyTitle(state._libAutoReplyActive);
- _renderAccountsStrip();
- _syncAutoReplyCalendarEvent(cfg).catch((err) => console.warn('Failed to reconcile auto-reply calendar event:', err));
- page.querySelector('#email-settings-account-select')?.addEventListener('change', async (ev) => {
- state._libAccountId = ev.currentTarget.value || null;
- state._libAutoReplyDraftActive = null;
- _publishActiveAccount();
- _syncEmailSettingsAccountPicker(page);
- _renderAccountsStrip();
- _resetEmailListForFreshLoad();
- _loadEmails({ useCache: true });
- _loadFolders({ resetMissing: true }).catch(() => {});
- page.querySelector('.email-unsubscribe-inline-panel')?.remove();
- const body = page.querySelector('.email-settings-body');
- if (body) body.innerHTML = _emailSettingsLoadingHtml();
- try {
- const [nextCfg, nextStyle] = await Promise.all([
- _fetchEmailSettingsConfig(),
- _fetchEmailWritingStyle().catch(() => ''),
- ]);
- if (body) body.innerHTML = _emailWritingStyleHtml(nextStyle) + _emailDisplaySettingsHtml(nextCfg) + _emailCleanupSettingsHtml() + _emailSettingsFormHtml(nextCfg);
- state._libAutoReplyActive = _isAutoReplyActiveForCurrentAccount(nextCfg);
- state._libAutoReplyDraftActive = null;
- _syncEmailAutoReplyTitle(state._libAutoReplyActive);
- _renderAccountsStrip();
- _syncAutoReplyCalendarEvent(nextCfg).catch((err) => console.warn('Failed to reconcile auto-reply calendar event:', err));
- _bindEmailSettingsPageControls(page);
- } catch (_) {
- if (body) body.innerHTML = `<div class="email-settings-error">Could not load settings.</div>`;
- }
- });
- page.querySelector('.email-settings-default')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- const acctId = ev.currentTarget.dataset.emailDefaultId;
- const account = (state._libAccounts || []).find(a => a && a.id === acctId);
- if (!acctId || account?.is_default) return;
- try {
- const response = await fetch(`${API_BASE}/api/email/accounts/${encodeURIComponent(acctId)}/set-default`, {
- method: 'POST', credentials: 'same-origin',
- });
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
- for (const a of state._libAccounts) a.is_default = a.id === acctId;
- _syncEmailSettingsAccountPicker(page);
- _renderAccountsStrip();
- } catch (err) {
- console.error('Set default account failed:', err);
- }
- });
- page.querySelector('.email-settings-default')?.addEventListener('keydown', (ev) => {
- if (ev.key !== 'Enter' && ev.key !== ' ') return;
- ev.preventDefault();
- ev.currentTarget.click();
- });
- _bindEmailSettingsPageControls(page);
- }
-
- function _bindEmailSettingsPageControls(page) {
- page.querySelector('.email-settings-clean-btn')?.addEventListener('click', (ev) => {
- // Clean is an explicit fresh scan action; do not reopen stale cached
- // candidates when the user asks to clean again.
- _openUnsubscribeReviewModal(ev.currentTarget, { forceRescan: true });
- });
- const showTagsToggle = page.querySelector('#email-settings-show-tags');
- const syncDisplayTagsState = () => {
- const section = page.querySelector('.email-settings-display-section');
- const stateLabel = page.querySelector('.email-settings-display-enabled-state');
- const enabled = !!showTagsToggle?.checked;
- section?.classList.toggle('is-disabled', !enabled);
- section?.classList.toggle('is-enabled', enabled);
- if (stateLabel) stateLabel.textContent = enabled ? 'Show' : 'Hide';
- };
- showTagsToggle?.addEventListener('change', (ev) => {
- state._libShowTags = !!ev.target.checked;
- localStorage.setItem('odysseus.email.showTags', state._libShowTags ? '1' : '0');
- _renderGrid();
- document.dispatchEvent(new CustomEvent('odysseus:email-tags-toggle', { detail: { show: state._libShowTags } }));
- if (state._libShowTags && !_loadedEmailsHaveVisibleTags()) _notifyNoLoadedEmailTags();
- syncDisplayTagsState();
- });
- syncDisplayTagsState();
- const inlineImagesToggle = page.querySelector('#email-settings-view-inline-images');
- const syncInlineImagesState = () => {
- const section = page.querySelector('.email-settings-inline-images-section');
- const stateLabel = page.querySelector('.email-settings-inline-images-enabled-state');
- const hidden = !!inlineImagesToggle?.checked;
- section?.classList.toggle('is-disabled', !hidden);
- section?.classList.toggle('is-enabled', hidden);
- if (stateLabel) stateLabel.textContent = hidden ? 'Hide' : 'Show';
- };
- inlineImagesToggle?.addEventListener('change', async (ev) => {
- const hidden = !!ev.target.checked;
- const enabled = !hidden;
- const previous = state._libViewInlineImages;
- state._libViewInlineImages = enabled;
- _writeEmailInlineImagesPreference(enabled);
- syncInlineImagesState();
- try {
- const res = await fetch(emailApiUrl('/api/email/config', {
- account_id: state._libAccountId || undefined,
- }), {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- credentials: 'include',
- body: JSON.stringify({ email_view_inline_images: enabled }),
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- document.querySelectorAll('.email-card-reader').forEach(reader => _wireEmailInlineImages(reader));
- } catch (err) {
- state._libViewInlineImages = previous;
- _writeEmailInlineImagesPreference(previous);
- ev.target.checked = previous === false;
- syncInlineImagesState();
- showToast?.('Failed to save inline image setting');
- console.error('Failed to save inline image setting:', err);
- }
- });
- syncInlineImagesState();
- page.querySelector('[data-open-email-tasks]')?.addEventListener('click', _openTasksForEmailTags);
- const autoReplyStart = page.querySelector('#email-auto-reply-start');
- const seedAutoReplyStartDate = () => {
- if (autoReplyStart && !autoReplyStart.value) autoReplyStart.value = _todayDateInputValue();
- };
- // Empty native date inputs can open on an arbitrary browser baseline date.
- // Seed only the draft field when the picker is opened, leaving saved settings
- // unchanged until the user explicitly presses Save.
- autoReplyStart?.addEventListener('pointerdown', seedAutoReplyStartDate);
- autoReplyStart?.addEventListener('focus', seedAutoReplyStartDate);
- const enabledToggle = page.querySelector('#email-auto-reply-enabled');
- const syncEnabledState = () => {
- const section = page.querySelector('.email-settings-auto-reply-section');
- const stateLabel = section?.querySelector('.email-settings-enabled-state');
- const enabled = !!enabledToggle?.checked;
- section?.classList.toggle('is-disabled', !enabled);
- section?.classList.toggle('is-enabled', enabled);
- if (stateLabel) stateLabel.textContent = enabled ? 'Enabled' : 'Disabled';
- };
- const saveAutoReplySettings = async ({ quiet = false } = {}) => {
- const saveBtn = page.querySelector('.email-settings-save');
- const status = page.querySelector('.email-settings-status');
- if (saveBtn && !quiet) saveBtn.disabled = true;
- _setEmailSaveIcon(saveBtn, false);
- if (status) {
- status.classList.remove('is-success', 'is-error');
- status.textContent = 'Saving…';
- }
- const payload = {
- email_auto_reply: !!page.querySelector('#email-auto-reply-enabled')?.checked,
- email_auto_reply_start: page.querySelector('#email-auto-reply-start')?.value || '',
- email_auto_reply_end: page.querySelector('#email-auto-reply-end')?.value || '',
- email_auto_reply_subject: page.querySelector('#email-auto-reply-subject')?.value || '',
- email_auto_reply_message: page.querySelector('#email-auto-reply-message')?.value || '',
- email_auto_reply_cooldown: page.querySelector('#email-auto-reply-cooldown')?.value || 'period',
- email_auto_reply_scope: 'account',
- email_auto_reply_account_id: state._libAccountId || '',
- email_auto_reply_pause_notifications: !!page.querySelector('#email-auto-reply-pause')?.checked,
- };
- try {
- const res = await fetch(emailApiUrl('/api/email/config', {
- account_id: state._libAccountId || undefined,
- }), {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- credentials: 'include',
- body: JSON.stringify(payload),
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const savedCfg = {
- enabled: !!payload.email_auto_reply,
- start: payload.email_auto_reply_start,
- end: payload.email_auto_reply_end,
- };
- let calendarSynced = true;
- try {
- await _syncAutoReplyCalendarEvent(savedCfg);
- } catch (calendarErr) {
- calendarSynced = false;
- console.warn('Failed to sync auto-reply calendar event:', calendarErr);
- }
- if (status) {
- status.classList.add('is-success');
- status.textContent = 'Saved';
- }
- _setEmailSaveIcon(saveBtn, true);
- if (!quiet) showToast?.('Email settings saved');
- if (!calendarSynced) showToast?.('Saved, but the calendar event could not be updated');
- state._libAutoReplyActive = _isAutoReplyActiveForCurrentAccount(savedCfg);
- state._libAutoReplyDraftActive = null;
- _syncEmailAutoReplyTitle(state._libAutoReplyActive);
- _renderAccountsStrip();
- _refreshUnreadBadge({ preserveAutoReplyTitle: true }).catch(() => {});
- setTimeout(() => { _setEmailSaveIcon(saveBtn, false); if (status) status.textContent = ''; }, quiet ? 900 : 1400);
- return true;
- } catch (err) {
- if (status) {
- status.classList.add('is-error');
- status.textContent = 'Save failed';
- }
- showToast?.('Failed to save email settings');
- return false;
- } finally {
- if (saveBtn) saveBtn.disabled = false;
- }
- };
- enabledToggle?.addEventListener('change', () => {
- syncEnabledState();
- // Invalidate any config read that started before this toggle. Its stale
- // result must not overwrite the title we are about to render.
- _autoReplyRefreshSeq += 1;
- const active = _isAutoReplyActiveForCurrentAccount({
- email_auto_reply: !!enabledToggle.checked,
- email_auto_reply_start: autoReplyStart?.value || '',
- email_auto_reply_end: page.querySelector('#email-auto-reply-end')?.value || '',
- email_auto_reply_scope: 'account',
- email_auto_reply_account_id: state._libAccountId || '',
- });
- state._libAutoReplyActive = active;
- state._libAutoReplyDraftActive = active;
- _syncEmailAutoReplyTitle(active);
- _renderAccountsStrip();
- saveAutoReplySettings({ quiet: true });
- });
- syncEnabledState();
- page.querySelector('.email-settings-save')?.addEventListener('click', async () => {
- await saveAutoReplySettings();
- });
- page.querySelector('.email-style-settings-save')?.addEventListener('click', async () => {
- const saveBtn = page.querySelector('.email-style-settings-save');
- const status = page.querySelector('.email-style-settings-status');
- saveBtn.disabled = true;
- _setEmailSaveIcon(saveBtn, false);
- if (status) {
- status.classList.remove('is-success', 'is-error');
- status.textContent = 'Saving…';
- }
- try {
- const res = await fetch(emailApiUrl('/api/email/style', {
- account_id: state._libAccountId || undefined,
- }), {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- credentials: 'include',
- body: JSON.stringify({ style: page.querySelector('#email-writing-style-text')?.value || '' }),
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- if (status) {
- status.classList.add('is-success');
- status.textContent = 'Saved';
- }
- _setEmailSaveIcon(saveBtn, true);
- showToast?.('Email writing style saved');
- setTimeout(() => { _setEmailSaveIcon(saveBtn, false); if (status) status.textContent = ''; }, 1400);
- } catch (err) {
- if (status) {
- status.classList.add('is-error');
- status.textContent = 'Save failed';
- }
- showToast?.('Failed to save email writing style');
- } finally {
- saveBtn.disabled = false;
- }
- });
- page.querySelector('.email-style-settings-extract')?.addEventListener('click', async () => {
- const extractBtn = page.querySelector('.email-style-settings-extract');
- const saveBtn = page.querySelector('.email-style-settings-save');
- const status = page.querySelector('.email-style-settings-status');
- const styleEl = page.querySelector('#email-writing-style-text');
- extractBtn.disabled = true;
- if (saveBtn) saveBtn.disabled = true;
- let wp = null;
- if (status) {
- status.innerHTML = '';
- try {
- wp = spinnerModule.createWhirlpool(14);
- wp.element.style.cssText = 'display:inline-block;vertical-align:-3px;margin-right:6px;';
- status.appendChild(wp.element);
- status.appendChild(document.createTextNode('Analyzing sent emails…'));
- } catch (_) {
- status.textContent = 'Analyzing sent emails…';
- }
- }
- try {
- const res = await fetch(emailApiUrl('/api/email/extract-style', {
- account_id: state._libAccountId || undefined,
- }), {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- credentials: 'include',
- body: JSON.stringify({ sample_count: 15 }),
- });
- const data = await res.json().catch(() => ({}));
- if (!res.ok || !data.success || !data.style) throw new Error(data.error || `HTTP ${res.status}`);
- if (styleEl) styleEl.value = data.style;
- if (status) status.textContent = 'Extracted';
- showToast?.('Email writing style extracted');
- setTimeout(() => { if (status) status.textContent = ''; }, 1800);
- } catch (err) {
- if (status) status.textContent = err?.message || 'Extract failed';
- showToast?.('Failed to extract email writing style');
- } finally {
- if (wp && wp.destroy) { try { wp.destroy(); } catch (_) {} }
- extractBtn.disabled = false;
- if (saveBtn) saveBtn.disabled = false;
- }
- });
- }
-
- function _hideEmailSettingsPage() {
- const modal = document.getElementById('email-lib-modal');
- const page = document.getElementById('email-lib-settings-page');
- const btn = document.getElementById('email-lib-settings-btn');
- const headerBackBtn = document.getElementById('email-settings-header-back');
- modal?.classList.remove('email-settings-mode');
- if (page) page.hidden = true;
- if (headerBackBtn) headerBackBtn.style.display = 'none';
- btn?.classList.remove('active');
- btn?.setAttribute('aria-expanded', 'false');
- }
-
- function _isEmailTypingTarget(t) {
- return !!(t && (
- t.tagName === 'INPUT' ||
- t.tagName === 'TEXTAREA' ||
- t.tagName === 'SELECT' ||
- t.isContentEditable
- ));
- }
-
- function _selectEmailReaderContents(reader) {
- if (!reader || !reader.isConnected) return false;
- const hiddenModal = reader.closest('.modal.hidden');
- if (hiddenModal) return false;
- const range = document.createRange();
- range.selectNodeContents(reader);
- const sel = window.getSelection();
- sel?.removeAllRanges();
- sel?.addRange(range);
- return true;
- }
-
- function _markEmailReaderActive(reader) {
- if (!reader) return;
- _activeEmailReaderForSelectAll = reader;
- if (reader.dataset.selectAllWired === '1') return;
- reader.dataset.selectAllWired = '1';
- reader.addEventListener('pointerdown', () => { _activeEmailReaderForSelectAll = reader; }, true);
- reader.addEventListener('focusin', () => { _activeEmailReaderForSelectAll = reader; }, true);
- }
-
- function _emailReaderLoadErrorHtml(message) {
- return `
- <div class="email-reader-load-error">
- <div class="email-reader-load-error-title">Could not load email</div>
- <div class="email-reader-load-error-msg">${_esc(message || 'Failed to load email')}</div>
- <button type="button" class="memory-toolbar-btn email-reader-retry-btn">Retry</button>
- </div>`;
- }
-
- function _showEmailReaderLoadError(reader, message, onRetry) {
- if (!reader) return;
- reader.classList.remove('email-card-reader-loading');
- reader.classList.add('email-card-reader-error');
- reader.style.minHeight = '';
- reader.innerHTML = _emailReaderLoadErrorHtml(message);
- const retry = reader.querySelector('.email-reader-retry-btn');
- retry?.addEventListener('click', (ev) => {
- ev.preventDefault();
- ev.stopPropagation();
- onRetry?.();
- });
- _markEmailReaderActive(reader);
- }
-
- function _openCalendarEventFromEmail(uid) {
- const target = String(uid || '').trim();
- if (!target) return;
- import('./calendar.js?v=20260914emailsource11').then(mod => {
- const open = mod.openCalendarTo || (mod.default && mod.default.openCalendarTo);
- if (open) open(target);
- }).catch(() => {});
- }
-
- function _applyTagFilterFromPill(tag) {
- const normalized = String(tag || '').trim().toLowerCase().replace(/_/g, '-');
- if (!normalized || normalized === 'calendar') return;
- const value = `filter:tag:${normalized}`;
- const existingIdx = Array.isArray(state._libSearchPills)
- ? state._libSearchPills.findIndex(p => p?.type === 'filter' && p.value === value)
- : -1;
- if (existingIdx >= 0) {
- _removeSearchPillAt(existingIdx);
- return;
- }
- _addSearchPill({
- type: 'filter',
- value,
- label: normalized.replace(/-/g, ' '),
- });
- }
-
- document.addEventListener('odysseus:email-filter-tag', (e) => {
- _applyTagFilterFromPill(e.detail?.tag);
- });
-
- function _emailTagPillHtml(tag, em) {
- const normalized = String(tag || '').trim().toLowerCase().replace(/_/g, '-');
- if (!normalized) return '';
- const eventUid = normalized === 'calendar' && Array.isArray(em?.calendar_event_uids)
- ? String(em.calendar_event_uids[0] || '').trim()
- : '';
- if (normalized === 'calendar') {
- if (!eventUid) return '';
- return `<button type="button" class="email-tag email-tag-${_esc(normalized)} email-tag-clickable" data-calendar-event-uid="${_esc(eventUid)}" title="Open calendar event">${_esc(normalized)}</button>`;
- }
- return `<button type="button" class="email-tag email-tag-${_esc(normalized)} email-tag-clickable" data-email-filter-tag="${_esc(normalized)}" title="Show ${_esc(normalized)} emails">${_esc(normalized)}</button>`;
- }
-
- function _emailTagGroupHtml(tags, em) {
- const visible = (Array.isArray(tags) ? tags : [])
- .map(t => _emailTagPillHtml(t, em))
- .filter(Boolean);
- if (!visible.length) return '';
- // A lone tag is already the most useful compact representation. Never
- // replace it with a misleading "+1" overflow control.
- if (visible.length === 1) return visible[0];
- // Two tags still fit as useful labels. Overflow starts at three so the UI
- // never renders a low-value "+1" control.
- if (visible.length === 2) return visible.join('');
- const extra = visible.slice(1).map(html => `<span class="email-tag-extra">${html}</span>`).join('');
- const additionalCount = visible.length - 1;
- const mini = `<button type="button" class="email-tags-more email-tags-more-single" data-email-tags-more aria-expanded="false" title="Show all tags"><span>+${additionalCount}</span></button>`;
- return `${visible[0]}${extra}<button type="button" class="email-tags-more" data-email-tags-more aria-expanded="false" title="Show all tags"><span data-email-tags-count-normal>+${additionalCount}</span><span data-email-tags-count-mini>+${additionalCount}</span><svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"></polyline></svg></button>${mini}`;
- }
-
- function _fitEmailCardTags(titleRow) {
- const tagWrap = titleRow?.querySelector('.email-card-tags');
- const title = titleRow?.querySelector('.memory-item-title');
- const status = titleRow?.querySelector('.email-card-status');
- if (!tagWrap || !title || !status) return;
- tagWrap.classList.remove('email-tags-mini');
- tagWrap.style.setProperty('--email-status-width', `${status.offsetWidth}px`);
- const minimumTitleWidth = Math.max(96, Math.min(160, titleRow.clientWidth * 0.45));
- const availableForTags = Math.max(0, titleRow.clientWidth - status.offsetWidth - minimumTitleWidth - 12);
- const hasOverflowControl = !!tagWrap.querySelector('[data-email-tags-more]');
- tagWrap.classList.toggle('email-tags-mini', hasOverflowControl && tagWrap.scrollWidth > availableForTags);
- }
-
- const _emailTagFitObserver = typeof ResizeObserver === 'function'
- ? new ResizeObserver(entries => {
- for (const entry of entries) _fitEmailCardTags(entry.target);
- })
- : null;
-
- const _DONE_RESPONSE_TAGS = new Set(['urgent', 'reply-soon', 'action-needed']);
-
- function _visibleEmailTagsForRender(em) {
- const tags = Array.isArray(em?.tags) ? em.tags : [];
- if (!em?.is_answered) return tags;
- return tags.filter(t => !_DONE_RESPONSE_TAGS.has(String(t || '').trim().toLowerCase().replace(/_/g, '-')));
- }
-
- function _clearDoneResponseTagsLocal(em) {
- if (!em || !Array.isArray(em.tags)) return;
- em.tags = em.tags.filter(t => !_DONE_RESPONSE_TAGS.has(String(t || '').trim().toLowerCase().replace(/_/g, '-')));
- }
-
- function _loadedEmailsHaveVisibleTags() {
- return (state._libEmails || []).some(em =>
- _visibleEmailTagsForRender(em).length > 0 || !!em?.is_spam_verdict
- );
- }
-
- async function _openTasksForEmailTags() {
- try {
- const mod = await import('./tasks.js?v=20260914taskmodel1');
- const openTasks = mod.openTasks || mod.default?.openTasks;
- if (typeof openTasks === 'function') {
- openTasks(null, { filter: 'Email', focusAction: 'check_email_urgency' });
- return;
- }
- } catch (_) {}
- document.getElementById('tool-tasks-btn')?.click();
- }
-
- function _notifyNoLoadedEmailTags() {
- const count = (state._libEmails || []).length;
- const msg = count
- ? `No tags found in the ${count} loaded emails.`
- : 'No email tags loaded yet.';
- showToast(`${msg} Turn on email tagging in Tasks.`, {
- duration: 6500,
- action: 'Open Tasks',
- onAction: _openTasksForEmailTags,
- });
- }
-
- // Stash the email identity (uid + folder + account) on the reader element
- // so chat submits and other code paths can ask "what email is the user
- // currently looking at?" without re-deriving from the DOM hierarchy.
- function _stampReaderContext(reader, em, folder, account) {
- if (!reader || !em) return;
- reader.dataset.emailUid = String(em.uid || '');
- reader.dataset.emailFolder = String(folder || state._libFolder || 'INBOX');
- reader.dataset.emailAccount = String(account || state._libAccountId || '');
- if (em.subject) reader.dataset.emailSubject = String(em.subject);
- if (em.from_address || em.from_name) {
- reader.dataset.emailFrom = String(em.from_address || em.from_name);
- }
- }
-
- // Returns { uid, folder, account, subject, from } for the email the user
- // is most likely referring to — the last reader they interacted with, then
- // any open reader-modal as a fallback. Returns null when no email reader
- // is open. Exported below for chat.js to read on submit.
- function _getActiveEmailContext() {
- const candidates = [];
- if (_activeEmailReaderForSelectAll && _activeEmailReaderForSelectAll.isConnected) {
- candidates.push(_activeEmailReaderForSelectAll);
- }
- // Visible reader-tab modals (popped-out windows).
- document.querySelectorAll('.modal[id^="email-reader-"]:not(.hidden):not(.modal-minimized) .email-card-reader').forEach(el => candidates.push(el));
- // Expanded inline reader in the library list.
- document.querySelectorAll('#email-lib-modal:not(.hidden) .doclib-card.email-card-expanded .email-card-reader').forEach(el => candidates.push(el));
- for (const r of candidates) {
- const uid = r?.dataset?.emailUid;
- if (uid) {
- return {
- uid,
- folder: r.dataset.emailFolder || 'INBOX',
- account: r.dataset.emailAccount || '',
- subject: r.dataset.emailSubject || '',
- from: r.dataset.emailFrom || '',
- };
- }
- }
- return null;
- }
-
- // Frontend reads via the global so chat.js doesn't need a separate import
- // path (emailLibrary loads lazily in some entry points).
- try { window.__odysseusGetActiveEmailContext = _getActiveEmailContext; } catch (_) {}
-
- const _COPY_EMAIL_ICON = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
-
- function _decodeAttrValue(v) {
- const tmp = document.createElement('textarea');
- tmp.innerHTML = v || '';
- return tmp.value;
- }
-
- function _emailAddressFromRecipientText(text) {
- const raw = String(text || '').trim();
- const angle = raw.match(/<\s*([^<>@\s]+@[^<>\s]+)\s*>/);
- if (angle) return angle[1].trim();
- const any = raw.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i);
- return any ? any[0].trim() : raw;
- }
-
- function _splitRecipientList(raw) {
- const out = [];
- let cur = '';
- let quote = false;
- let angle = false;
- const s = String(raw || '');
- for (let i = 0; i < s.length; i += 1) {
- const ch = s[i];
- if (ch === '"' && s[i - 1] !== '\\') quote = !quote;
- else if (ch === '<' && !quote) angle = true;
- else if (ch === '>' && !quote) angle = false;
-
- if (ch === ',' && !quote && !angle) {
- const part = cur.trim();
- if (part) out.push(part);
- cur = '';
- continue;
- }
- cur += ch;
- }
- const tail = cur.trim();
- if (tail) out.push(tail);
- return out;
- }
-
- async function _copyTextToClipboard(text) {
- const value = String(text || '');
- if (!value) return false;
- try {
- if (navigator.clipboard?.writeText) {
- await navigator.clipboard.writeText(value);
- return true;
- }
- } catch (_) {}
- try {
- const ta = document.createElement('textarea');
- ta.value = value;
- ta.setAttribute('readonly', '');
- ta.style.position = 'fixed';
- ta.style.left = '-9999px';
- ta.style.top = '0';
- document.body.appendChild(ta);
- ta.select();
- const ok = document.execCommand('copy');
- ta.remove();
- return !!ok;
- } catch (_) {
- return false;
- }
- }
-
- function _wireMetaToggle(root) {
- const toggle = root && root.querySelector('.email-reader-meta-toggle');
- const details = root && root.querySelector('.email-reader-meta-details');
- if (!toggle || !details) return;
- const meta = details.closest('.email-reader-meta');
- toggle.addEventListener('click', (ev) => {
- ev.stopPropagation();
- const open = details.hasAttribute('hidden');
- if (open) details.removeAttribute('hidden');
- else details.setAttribute('hidden', '');
- toggle.setAttribute('aria-expanded', String(open));
- toggle.classList.toggle('open', open);
- if (meta) meta.classList.toggle('email-reader-meta-expanded', open);
- });
- }
-
- function _recipientMetaToggleHtml(data = {}) {
- const ccCount = _splitRecipientList(data.cc || '').length;
- if (ccCount) {
- return `<button class="email-reader-meta-toggle email-reader-cc-toggle" type="button" aria-expanded="false" title="Show Cc recipients"><span>Cc +${ccCount}</span><svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg></button>`;
- }
- if (!data.to) return '';
- return `<button class="email-reader-meta-toggle" type="button" aria-expanded="false" title="Show recipients"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg></button>`;
- }
-
- function _recipientChipHtml(full, label, extraClass = '') {
- const fullText = String(full || '').trim();
- const addr = _emailAddressFromRecipientText(fullText);
- const labelText = String(label || addr || fullText || '').trim();
- const cls = `recipient-chip${extraClass ? ` ${extraClass}` : ''}`;
- return `<span class="${cls}" data-full="${_esc(fullText || labelText)}" data-email="${_esc(addr)}" title="Click for details"><span class="recipient-chip-label">${_esc(labelText)}</span><button type="button" class="recipient-chip-copy" title="Copy email" aria-label="Copy email" hidden>${_COPY_EMAIL_ICON}</button></span>`;
- }
-
- let _recipientChipPopoverCtl = null;
- function _closeRecipientChipPopover() {
- try { _recipientChipPopoverCtl?.abort(); } catch {}
- _recipientChipPopoverCtl = null;
- document.querySelector('.recipient-chip-popover')?.remove();
- document.querySelectorAll('.recipient-chip.popover-open').forEach(chip => {
- chip.classList.remove('popover-open');
- });
- }
-
- function _showRecipientChipPopover(chip) {
- if (!chip) return false;
- _closeRecipientChipPopover();
- const full = _decodeAttrValue(chip.dataset.full || '').trim();
- const email = chip.dataset.email || _emailAddressFromRecipientText(full);
- const name = chip.dataset.name || chip.querySelector('.recipient-chip-label')?.textContent?.trim() || '';
- const detail = full || email || name;
- if (!detail) return true;
-
- chip.classList.add('popover-open');
- const pop = document.createElement('div');
- pop.className = 'recipient-chip-popover';
- pop.setAttribute('role', 'dialog');
- pop.setAttribute('aria-label', 'Sender details');
- pop.innerHTML = `
- <div class="recipient-chip-popover-main">
- ${name && detail !== name ? `<div class="recipient-chip-popover-name">${_esc(name)}</div>` : ''}
- <div class="recipient-chip-popover-detail">${_esc(detail)}</div>
- </div>
- ${email ? `<button type="button" class="recipient-chip-popover-copy" title="Copy email" aria-label="Copy email">${_COPY_EMAIL_ICON}</button>` : ''}
- `;
- document.body.appendChild(pop);
-
- const rect = chip.getBoundingClientRect();
- const margin = 10;
- const maxLeft = Math.max(margin, window.innerWidth - pop.offsetWidth - margin);
- let left = Math.min(Math.max(margin, rect.left), maxLeft);
- let top = rect.bottom + 6;
- if (top + pop.offsetHeight + margin > window.innerHeight) {
- top = Math.max(margin, rect.top - pop.offsetHeight - 6);
- }
- pop.style.left = `${Math.round(left)}px`;
- pop.style.top = `${Math.round(top)}px`;
-
- const ctl = new AbortController();
- _recipientChipPopoverCtl = ctl;
- pop.querySelector('.recipient-chip-popover-copy')?.addEventListener('click', async (ev) => {
- ev.preventDefault();
- ev.stopPropagation();
- try {
- const copied = await _copyTextToClipboard(email);
- if (!copied) throw new Error('copy failed');
- ev.currentTarget.classList.add('copied');
- showToast?.('Email copied');
- setTimeout(_closeRecipientChipPopover, 650);
- } catch (_) {
- showToast?.('Copy failed');
- }
- }, { signal: ctl.signal });
- setTimeout(() => {
- document.addEventListener('pointerdown', (ev) => {
- if (pop.contains(ev.target) || chip.contains(ev.target)) return;
- _closeRecipientChipPopover();
- }, { signal: ctl.signal, capture: true });
- }, 0);
- document.addEventListener('keydown', (ev) => {
- if (ev.key === 'Escape') _closeRecipientChipPopover();
- }, { signal: ctl.signal });
- window.addEventListener('resize', _closeRecipientChipPopover, { signal: ctl.signal });
- window.addEventListener('scroll', _closeRecipientChipPopover, { signal: ctl.signal, capture: true });
- return true;
- }
-
- function _wireRecipientChips(root) {
- if (!root || root.dataset.recipientChipsWired === '1') return;
- root.dataset.recipientChipsWired = '1';
- root.addEventListener('click', async (ev) => {
- const copyBtn = ev.target.closest?.('.recipient-chip-copy');
- if (copyBtn && root.contains(copyBtn)) {
- ev.stopPropagation();
- ev.preventDefault();
- const chip = copyBtn.closest('.recipient-chip');
- const email = chip?.dataset.email || _emailAddressFromRecipientText(_decodeAttrValue(chip?.dataset.full || ''));
- if (!email) return;
- try {
- const copied = await _copyTextToClipboard(email);
- if (!copied) throw new Error('copy failed');
- copyBtn.classList.add('copied');
- copyBtn.title = 'Copied';
- showToast?.('Email copied');
- setTimeout(() => {
- copyBtn.classList.remove('copied');
- copyBtn.title = 'Copy email';
- }, 900);
- } catch (_) {
- showToast?.('Copy failed');
- }
- return;
- }
-
- const chip = ev.target.closest?.('.recipient-chip');
- if (!chip || !root.contains(chip)) return;
- ev.stopPropagation();
- ev.preventDefault();
- if (_showRecipientChipPopover(chip)) return;
- const label = chip.querySelector('.recipient-chip-label');
- const copy = chip.querySelector('.recipient-chip-copy');
- if (chip.classList.contains('expanded')) {
- chip.classList.remove('expanded');
- if (label) label.textContent = chip.dataset.name || label.textContent;
- if (copy) copy.hidden = true;
- } else {
- if (!chip.dataset.name && label) chip.dataset.name = label.textContent.trim();
- chip.classList.add('expanded');
- const expandedText = _decodeAttrValue(chip.dataset.full || '').trim()
- || chip.dataset.name
- || chip.dataset.email
- || label?.textContent?.trim()
- || '';
- if (label && expandedText) label.textContent = expandedText;
- if (copy) copy.hidden = false;
- }
- });
- }
-
- function _emailReaderForSelectAllTarget(target) {
- if (_isEmailTypingTarget(target)) return null;
- const direct = target?.closest?.('.email-card-reader, #email-lib-modal .doclib-card.doclib-card-expanded');
- if (direct) return direct.querySelector?.('.email-card-reader') || direct;
- const expanded = document.querySelector('#email-lib-modal:not(.hidden) .doclib-card.doclib-card-expanded .email-card-reader');
- if (expanded) return expanded;
- return _activeEmailReaderForSelectAll;
- }
-
- document.addEventListener('keydown', (e) => {
- if (!(e.ctrlKey || e.metaKey) || String(e.key || '').toLowerCase() !== 'a') return;
- const reader = _emailReaderForSelectAllTarget(e.target);
- if (!_selectEmailReaderContents(reader)) return;
- e.preventDefault();
- e.stopPropagation();
- e.stopImmediatePropagation?.();
- }, true);
-
- function _emailReadContextKey(context) {
- return [context.accountId, context.folder, context.uid].map(value => String(value || '')).join('\u0000');
- }
-
- function _emailReadContextIsCurrent(context) {
- if (!context) return true;
- return (
- String(state._libAccountId || '') === context.accountId &&
- String(state._libFolder || 'INBOX') === context.libraryFolder &&
- _emailMailboxGeneration === context.mailboxGeneration
- );
- }
-
- function _emailMatchesReadContext(email, context) {
- if (String(email?.uid || '') !== context.uid) return false;
- const accountId = String(email?.account_id || context.accountId);
- const folder = String(email?.folder || context.folder);
- return accountId === context.accountId && folder === context.folder;
- }
-
- function _syncEmailReadState(uid, isRead = true, context = null) {
- if (uid == null) return;
- const uidStr = String(uid);
- const read = !!isRead;
- if (context && (!_emailReadContextIsCurrent(context) || uidStr !== context.uid)) return;
- const match = (state._libEmails || []).find(x => (
- context ? _emailMatchesReadContext(x, context) : String(x.uid) === uidStr
- ));
- if (match) match.is_read = read;
-
- document.querySelectorAll('.doclib-card[data-uid="' + CSS.escape(uidStr) + '"]').forEach(card => {
- if (context && (
- String(card.dataset.emailAccount || '') !== context.accountId ||
- String(card.dataset.emailFolder || '') !== context.folder
- )) return;
- card.classList.toggle('email-card-unread', !read);
- const titleRow = card.querySelector('.email-card-titlerow');
- if (read) {
- card.querySelectorAll('.email-card-unread-dot, [data-unread-dot]').forEach(n => n.remove());
- if (titleRow) {
- titleRow.querySelectorAll('span').forEach(s => {
- const st = s.getAttribute('style') || '';
- if (/width:\s*6px/.test(st) && /border-radius:\s*50%/.test(st)) s.remove();
- });
- }
- return;
- }
-
- if (!titleRow || titleRow.querySelector('.email-card-unread-dot, [data-unread-dot]')) return;
- const isSentFolder = /sent/i.test(state._libFolder || '');
- if (isSentFolder) return;
- const senderName = match ? (match.from_name || match.from_address || '') : '';
- const dot = document.createElement('span');
- dot.className = 'email-card-unread-dot';
- dot.style.cssText = `width:6px;height:6px;border-radius:50%;background:${_senderColor(senderName)};flex-shrink:0;margin-left:2px;`;
- const done = titleRow.querySelector('.email-card-done');
- const navArrows = titleRow.querySelector('.email-card-nav-arrows');
- if (done) done.insertAdjacentElement('afterend', dot);
- else if (navArrows) titleRow.insertBefore(dot, navArrows);
- else titleRow.appendChild(dot);
- });
- }
-
- function _syncEmailDoneState(uid, isDone = true, context = null) {
- if (uid == null) return;
- const uidStr = String(uid);
- const done = !!isDone;
- const match = (state._libEmails || []).find(x => (
- context ? _emailMatchesReadContext(x, context) : String(x.uid) === uidStr
- ));
- if (match) {
- match.is_answered = done;
- match.is_done = done;
- }
- document.querySelectorAll('.doclib-card[data-uid="' + CSS.escape(uidStr) + '"]').forEach(card => {
- if (context && (
- String(card.dataset.emailAccount || '') !== context.accountId ||
- String(card.dataset.emailFolder || '') !== context.folder
- )) return;
- card.classList.toggle('email-card-answered', done);
- const check = card.querySelector('.email-card-done');
- if (check) {
- check.classList.toggle('active', done);
- check.title = done ? 'Mark not done' : 'Mark done';
- }
- if (done) {
- card.querySelectorAll('.email-tag-urgent, .email-tag-reply-soon, .email-tag-action-needed').forEach(n => n.remove());
- }
- });
- }
-
- // When a reply is sent (from the doc editor), the source email is marked
- // \Answered server-side and an `email-answered` event fires. Reflect that live
- // so the email shows as done without waiting for a manual refresh.
- window.addEventListener('email-answered', (e) => {
- const uid = e.detail && e.detail.uid;
- if (uid == null) return;
- const em = (state._libEmails || []).find(x => String(x.uid) === String(uid));
- if (em) {
- em.is_answered = true;
- em.is_done = true;
- em.is_read = true;
- _clearDoneResponseTagsLocal(em);
- }
- _syncEmailDoneState(uid, true);
- _syncEmailReadState(uid, true);
- document.querySelectorAll('.doclib-card[data-uid="' + CSS.escape(String(uid)) + '"]').forEach(card => {
- card.classList.add('email-card-answered');
- card.classList.remove('email-card-unread');
- card.querySelectorAll('.email-tag-urgent, .email-tag-reply-soon, .email-tag-action-needed').forEach(n => n.remove());
- const check = card.querySelector('.email-card-done');
- if (check) check.classList.add('active');
- });
- });
-
- function _toggleUnreadEmails() {
- if (state._libFolder === '__scheduled__') state._libFolder = 'INBOX';
- state._libFilter = state._libFilter === 'unread' ? 'all' : 'unread';
- _syncUnreadWindowGlow();
- const folderEl = document.getElementById('email-lib-folder');
- const filterEl = document.getElementById('email-lib-filter');
- if (folderEl) folderEl.value = state._libFolder || 'INBOX';
- if (filterEl) filterEl.value = state._libFilter;
- _syncSearchOptionsMenu();
- _renderSearchPills();
- _loadEmailsFresh();
- }
-
- function _syncUnreadTabBadge(count) {
- const label = count > 999 ? '999+ unread' : `${count} unread`;
- document.querySelectorAll('.minimized-dock-chip[data-modal-id="email-lib-modal"]').forEach(chip => {
- if (count > 0) {
- chip.dataset.emailUnreadLabel = label;
- chip.title = `Open ${label}`;
- } else {
- delete chip.dataset.emailUnreadLabel;
- chip.title = 'Restore Email';
- }
- });
- }
-
- function _syncCurrentAccountUnreadCount(count) {
- const accountId = String(state._libAccountId || '');
- if (!accountId) return;
- const nextCount = Math.max(0, Number(count) || 0);
- const prev = _accountUnreadState.get(accountId) || {};
- _accountUnreadState.set(accountId, {
- ...prev,
- unreadCount: nextCount,
- });
- _renderAccountsStrip();
- }
-
- function _syncUnreadWindowGlow() {
- document.getElementById('email-lib-modal')?.classList.toggle('email-lib-unread-active', state._libFilter === 'unread');
- }
-
- function _syncReminderClearButton() {
- document.getElementById('email-reminders-clear-btn')?.classList.toggle('hidden', state._libFilter !== 'reminders');
- }
-
- function _syncSearchOptionsMenu() {
- const btn = document.getElementById('email-search-options-btn');
- const menu = document.getElementById('email-search-options-menu');
- const hasDate = !!(state._libDateFrom || state._libDateTo);
- const hasActive = state._libFilter === 'undone' || state._libFilter === 'reminders' || !!state._libHasAttachments || hasDate;
- btn?.classList.toggle('active', hasActive);
- menu?.querySelector('[data-email-search-option="undone"]')?.classList.toggle('active', state._libFilter === 'undone');
- menu?.querySelector('[data-email-search-option="reminders"]')?.classList.toggle('active', state._libFilter === 'reminders');
- menu?.querySelector('[data-email-search-option="attachments"]')?.classList.toggle('active', !!state._libHasAttachments);
- menu?.querySelector('[data-email-search-option="date"]')?.classList.toggle('active', hasDate);
- }
-
- function _setEmailListFilter(value) {
- const filterEl = document.getElementById('email-lib-filter');
- state._libFilter = state._libFilter === value ? 'all' : value;
- if (filterEl) filterEl.value = state._libFilter;
- _syncUnreadWindowGlow();
- _syncReminderClearButton();
- _renderFilterPickerCurrent();
- _syncSearchOptionsMenu();
- _renderSearchPills();
- _loadEmailsFresh();
- }
-
- function _toggleEmailAttachmentFilter() {
- state._libHasAttachments = !state._libHasAttachments;
- _syncReminderClearButton();
- _syncSearchOptionsMenu();
- _renderSearchPills();
- _loadEmailsFresh();
- }
-
- function _renderAccountsLoading() {
- const strip = document.getElementById('email-lib-accounts');
- if (!strip) return;
- strip.style.display = 'flex';
- strip.innerHTML = '';
- try {
- const wp = spinnerModule.createWhirlpool(14);
- wp.element.classList.add('email-accounts-loading-whirlpool');
- strip.appendChild(wp.element);
- } catch (_) {}
- }
-
- function _syncEmailReminderBellVisibility(enabled) {
- const item = document.querySelector('#email-search-options-menu [data-email-search-option="reminders"]');
- item?.classList.toggle('hidden', !enabled);
- _syncSearchOptionsMenu();
- }
-
- async function _loadEmailReminderBellVisibility() {
- try {
- const settings = await getSettings();
- _syncEmailReminderBellVisibility(settings.reminder_channel === 'email');
- } catch (_) {
- _syncEmailReminderBellVisibility(false);
- }
- }
- // Live-update the bell when the reminder channel changes in Settings,
- // so the user doesn't have to reopen Email to see the change apply.
- window.addEventListener('odysseus-reminder-channel-changed', (e) => {
- const ch = e?.detail?.channel;
- _syncEmailReminderBellVisibility(ch === 'email');
- });
-
- function _readCssPx(name) {
- const v = getComputedStyle(document.documentElement).getPropertyValue(name);
- const n = parseFloat(v);
- return Number.isFinite(n) ? n : 0;
- }
-
- function _emailSplitLeftEdge() {
- return _readCssPx('--icon-rail-w') + _readCssPx('--sidebar-w');
- }
-
- function _setEmailDocumentSplit(leftEdge, emailWidth) {
- if (window.innerWidth <= 768) return;
- // Zero gap so the doc-pane sits flush against the email's right edge.
- // modalSnap.js's left-dock path publishes the same vars with 0 gap — both
- // systems agree on flush so handoffs between them don't cause the doc to
- // "jump" sideways. The 1px modal border on each side is the visual seam.
- const splitGap = 0;
- const left = Math.max(0, Math.round(leftEdge || 0));
- const width = Math.max(320, Math.round(emailWidth || 420));
- const x = left + width + splitGap;
- document.body.classList.add('email-doc-split-active');
- document.documentElement.style.setProperty('--email-doc-split-left-x', `${left}px`);
- document.documentElement.style.setProperty('--email-doc-split-email-w', `${width}px`);
- document.documentElement.style.setProperty('--email-doc-split-right-x', `${x}px`);
- }
-
- function _measureEmailDocumentSplit(modal) {
- if (window.innerWidth <= 768 || !document.body.classList.contains('email-doc-split-active')) return;
- const content = modal?.querySelector?.('.modal-content');
- const rect = content?.getBoundingClientRect?.();
- if (!rect || !rect.width) return;
- const splitGap = 0;
- document.documentElement.style.setProperty('--email-doc-split-right-x', `${Math.ceil(rect.right + splitGap)}px`);
- try {
- modal.style.setProperty('z-index', '150', 'important');
- if (content) {
- content.style.setProperty('position', 'absolute', 'important');
- content.style.setProperty('left', '0px', 'important');
- content.style.setProperty('right', 'auto', 'important');
- content.style.setProperty('width', `${Math.ceil(rect.width)}px`, 'important');
- content.style.setProperty('max-width', `${Math.ceil(rect.width)}px`, 'important');
- }
- const docPane = document.getElementById('doc-editor-pane');
- if (docPane) {
- docPane.style.setProperty('position', 'fixed', 'important');
- docPane.style.setProperty('left', `${Math.ceil(rect.right + splitGap)}px`, 'important');
- docPane.style.setProperty('right', '0px', 'important');
- docPane.style.setProperty('top', '0px', 'important');
- docPane.style.setProperty('bottom', '0px', 'important');
- docPane.style.setProperty('width', 'auto', 'important');
- docPane.style.setProperty('max-width', 'none', 'important');
- docPane.style.setProperty('height', '100vh', 'important');
- docPane.style.setProperty('z-index', '260', 'important');
- }
- } catch (_) {}
- }
-
- function _scheduleEmailDocumentSplitMeasure(modal) {
- requestAnimationFrame(() => {
- _measureEmailDocumentSplit(modal);
- requestAnimationFrame(() => _measureEmailDocumentSplit(modal));
- });
- setTimeout(() => _measureEmailDocumentSplit(modal), 260);
- setTimeout(() => _measureEmailDocumentSplit(modal), 700);
- }
-
- function _clearEmailDocumentSplit() {
- document.body.classList.remove('email-doc-split-active');
- document.documentElement.style.removeProperty('--email-doc-split-left-x');
- document.documentElement.style.removeProperty('--email-doc-split-email-w');
- document.documentElement.style.removeProperty('--email-doc-split-right-x');
- const docPane = document.getElementById('doc-editor-pane');
- if (!docPane) return;
- [
- 'position', 'left', 'right', 'top', 'bottom', 'width', 'max-width',
- 'height', 'z-index', 'transform',
- ].forEach(prop => docPane.style.removeProperty(prop));
- }
-
- // Compute the left-edge x assuming the wide sidebar has collapsed to the
- // rail. Used by the "try collapsing the sidebar first" path so we can decide
- // whether collapsing recovers enough room before minimizing email.
- function _emailSplitLeftEdgeIfSidebarCollapsed() {
- return _readCssPx('--icon-rail-w');
- }
-
- function _hasDesktopRoomForEmailAndDocument(modal, opts = {}) {
- if (window.innerWidth <= 768) return false;
- if (window.innerWidth >= 1100) return true;
- const content = modal?.querySelector?.('.modal-content');
- const rect = content?.getBoundingClientRect?.();
- const isFullscreen = modal?.classList?.contains('email-lib-fullscreen')
- || modal?.classList?.contains('email-window-fullscreen');
- const emailWidth = isFullscreen
- ? Math.min(440, Math.max(360, Math.round(window.innerWidth * 0.30)))
- : Math.max(360, Math.round(rect?.width || 440));
- // Relaxed thresholds — the old 560 + 72 forced an unnecessary tab-down
- // on ~1200–1300px viewports where there was visually plenty of room.
- const docMinWidth = 460;
- const breathingRoom = 40;
- const leftEdgeNow = isFullscreen ? _emailSplitLeftEdge() : Math.max(0, Math.round(rect?.left || _emailSplitLeftEdge()));
- const leftEdge = opts.assumeSidebarCollapsed ? _emailSplitLeftEdgeIfSidebarCollapsed() : leftEdgeNow;
- return (window.innerWidth - leftEdge - emailWidth) >= (docMinWidth + breathingRoom);
- }
-
- function _prepareEmailWindowForDocument(modal) {
- if (window.innerWidth <= 768) return true;
- if (!modal) return false;
- // Try to make breathing room by collapsing the wide sidebar to the rail
- // when there isn't enough horizontal space for both panes. The
- // route-collapse marker that collapseSidebarToRail() sets means the
- // sidebar will auto-restore when the doc closes. Crucially, we no
- // longer fall back to clearing the split when even that isn't enough —
- // the user opted out of auto-tab-down, so we proceed with the dock
- // even if it's cramped.
- if (!_hasDesktopRoomForEmailAndDocument(modal)) {
- const sidebar = document.getElementById('sidebar');
- const sidebarWasOpen = sidebar && !sidebar.classList.contains('hidden');
- if (sidebarWasOpen && _hasDesktopRoomForEmailAndDocument(modal, { assumeSidebarCollapsed: true })) {
- try { collapseSidebarToRail(); } catch (_) {}
- }
- }
- if (modal.classList.contains('modal-left-docked')) {
- const content = modal.querySelector('.modal-content');
- const rect = content?.getBoundingClientRect?.();
- if (content?._leftDockNavObs) {
- try { content._leftDockNavObs.navObs.disconnect(); } catch (_) {}
- try { content._leftDockNavObs.bodyObs && content._leftDockNavObs.bodyObs.disconnect(); } catch (_) {}
- try { content._leftDockNavObs.disconnectDocObs && content._leftDockNavObs.disconnectDocObs(); } catch (_) {}
- try { window.removeEventListener('resize', content._leftDockNavObs.reanchor); } catch (_) {}
- delete content._leftDockNavObs;
- }
- modal.classList.remove('modal-left-docked');
- modal.classList.add('email-snap-left');
- document.body.classList.remove('left-dock-active');
- document.documentElement.style.removeProperty('--left-dock-w');
- if (content) {
- delete content._dockSide;
- content.style.position = 'fixed';
- content.style.left = Math.round(rect?.left || _emailSplitLeftEdge()) + 'px';
- content.style.top = '0';
- content.style.right = 'auto';
- content.style.bottom = '0';
- content.style.width = Math.round(rect?.width || 440) + 'px';
- content.style.maxWidth = Math.round(rect?.width || 440) + 'px';
- content.style.height = '100vh';
- content.style.maxHeight = '100vh';
- content.style.borderRadius = '0';
- content.style.transform = 'none';
- content.style.margin = '0';
- }
- }
- if (modal.classList.contains('email-snap-left') || modal.classList.contains('modal-left-docked')) {
- const rect = modal.querySelector('.modal-content')?.getBoundingClientRect?.();
- _setEmailDocumentSplit(rect?.left || _emailSplitLeftEdge(), rect?.width || 420);
- _scheduleEmailDocumentSplitMeasure(modal);
- return false;
- }
- // If Email is fullscreen and there is room, park it left instead of
- // minimizing so the document/compose pane can open beside it.
- _snapEmailModalToLeftSidebar(modal);
- return false;
- }
-
- function _wireUnreadTabClick() {
- if (_emailUnreadChipClickWired) return;
- _emailUnreadChipClickWired = true;
- document.addEventListener('click', (e) => {
- const chip = e.target?.closest?.('.minimized-dock-chip[data-modal-id="email-lib-modal"][data-email-unread-label]');
- if (!chip || e.target?.classList?.contains('minimized-dock-x')) return;
- setTimeout(_toggleUnreadEmails, 0);
- });
- }
-
- async function _deleteEmailAndAdvance(em, card, opts = {}) {
- if (!em || em.uid == null) return;
- if (opts.confirm !== false) {
- const subject = em.subject || '(no subject)';
- const ok = await styledConfirm(`Delete "${subject}"?`, { confirmText: 'Delete', cancelText: 'Cancel', danger: true });
- if (!ok) return;
- }
- const busy = _showEmailDeleteOverlay(card);
- await busy?.ready;
- const wasExpanded = !!card?.classList?.contains('doclib-card-expanded');
- const sibling = wasExpanded
- ? (_findSiblingEmailCard(card, +1) || _findSiblingEmailCard(card, -1))
- : null;
- const nextUid = sibling ? sibling.dataset.uid : null;
- try {
- const response = await fetch(`${API_BASE}/api/email/delete/${encodeURIComponent(em.uid)}?${_emailMutationQuery(em)}`, { method: 'DELETE' });
- await _requireSuccessfulEmailMutation(response, 'Failed to delete email');
- } catch (err) {
- console.error('Failed to delete email:', err);
- busy?.remove?.();
- showToast('Failed to delete email');
- return;
- }
- busy?.remove?.();
- await _animateEmailCardRemoval([em.uid]);
- state._libEmails = state._libEmails.filter(e => String(e.uid) !== String(em.uid));
- state._selectedUids.delete(em.uid);
- _updateBulkBar();
- _renderGrid();
- _libCacheWriteBack();
- showToast('Moved to Trash');
- if (!wasExpanded || !nextUid) return;
- const grid = document.getElementById('email-lib-grid');
- const nextCard = grid?.querySelector(`.doclib-card[data-uid="${CSS.escape(String(nextUid))}"]`);
- const nextEm = state._libEmails.find(e => String(e.uid) === String(nextUid));
- if (nextCard && nextEm) {
- await _toggleCardPreview(nextCard, nextEm);
- nextCard.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
- } else {
- document.getElementById('email-lib-modal')?.classList.remove('email-reading');
- }
- }
-
- function _showEmailDeleteOverlay(target) {
- if (!target) return null;
- const wp = spinnerModule.createWhirlpool(18);
- const overlay = document.createElement('div');
- overlay.className = 'email-delete-overlay';
- overlay.appendChild(wp.element);
- const prevPos = target.style.position;
- const prevPointerEvents = target.style.pointerEvents;
- if (getComputedStyle(target).position === 'static') target.style.position = 'relative';
- target.style.pointerEvents = 'none';
- target.classList.add('email-delete-busy');
- target.appendChild(overlay);
- const ready = new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
- return {
- ready,
- remove() {
- try { wp.destroy?.(); } catch (_) {}
- overlay.remove();
- target.classList.remove('email-delete-busy');
- target.style.pointerEvents = prevPointerEvents;
- target.style.position = prevPos;
- }
- };
- }
-
- function _animateEmailCardRemoval(uids, opts = {}) {
- const uidSet = new Set((uids || []).map(uid => String(uid)));
- if (!uidSet.size) return Promise.resolve();
- const grid = document.getElementById('email-lib-grid');
- if (!grid) return Promise.resolve();
- const cards = Array.from(grid.querySelectorAll('.doclib-card[data-uid]'))
- .filter(card => uidSet.has(String(card.dataset.uid)));
- if (!cards.length) return Promise.resolve();
- const duration = Number(opts.duration || 230);
-
- for (const card of cards) {
- const rect = card.getBoundingClientRect();
- card.style.setProperty('--email-remove-h', `${Math.max(rect.height, card.scrollHeight)}px`);
- card.style.maxHeight = 'var(--email-remove-h)';
- card.style.overflow = 'hidden';
- card.classList.add('email-card-removing');
- }
-
- return new Promise(resolve => {
- window.setTimeout(resolve, duration + 35);
- });
- }
-
-
- function _selectedEmailExportPayload() {
- const selected = new Set(Array.from(state._selectedUids || []).map(uid => String(uid)));
- return (state._libEmails || [])
- .filter(em => selected.has(String(em.uid)))
- .map(em => ({
- uid: String(em.uid || ''),
- folder: String(em.folder || state._libFolder || 'INBOX'),
- account_id: String(em.account_id || state._libAccountId || ''),
- subject: String(em.subject || ''),
- date: (() => {
- const parsed = em.date_epoch ? new Date(Number(em.date_epoch) * 1000) : new Date(em.date || '');
- return Number.isFinite(parsed.getTime()) ? parsed.toISOString().slice(0, 10) : '';
- })(),
- }))
- .filter(em => em.uid);
- }
-
- function _downloadBlob(blob, filename) {
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = filename || 'selected-email-attachments.zip';
- document.body.appendChild(a);
- a.click();
- a.remove();
- setTimeout(() => URL.revokeObjectURL(url), 1500);
- }
-
- function _filenameFromContentDisposition(header) {
- const value = String(header || '');
- const utf = value.match(/filename\*=UTF-8''([^;]+)/i);
- if (utf) {
- try { return decodeURIComponent(utf[1]); } catch (_) {}
- }
- const quoted = value.match(/filename="([^"]+)"/i);
- if (quoted) return quoted[1];
- const bare = value.match(/filename=([^;]+)/i);
- return bare ? bare[1].trim() : '';
- }
-
- async function _exportSelectedAttachments() {
- const messages = _selectedEmailExportPayload();
- if (!messages.length) {
- showToast('Select emails first');
- return;
- }
- const actionsBtn = document.getElementById('email-lib-bulk-actions');
- const deleteBtn = document.getElementById('email-lib-bulk-delete');
- const cancelBtn = document.getElementById('email-lib-bulk-cancel');
- const selectAll = document.getElementById('email-lib-select-all');
- const countEl = document.getElementById('email-lib-selected-count');
- const originalActionsHtml = actionsBtn?.innerHTML || '';
- const originalCountText = countEl?.textContent || '';
- let busySpinner = null;
- try {
- if (actionsBtn) {
- actionsBtn.disabled = true;
- actionsBtn.classList.add('email-bulk-loading');
- actionsBtn.innerHTML = '<span class="email-bulk-loading-label">Exporting</span>';
- busySpinner = spinnerModule.create('', 'clean', 'whirlpool');
- const spEl = busySpinner.createElement();
- spEl.classList.add('email-bulk-whirlpool');
- actionsBtn.appendChild(spEl);
- busySpinner.start();
- }
- if (deleteBtn) deleteBtn.disabled = true;
- if (cancelBtn) cancelBtn.disabled = true;
- if (selectAll) selectAll.disabled = true;
- if (countEl) countEl.textContent = `Exporting attachments from ${messages.length}…`;
- const res = await fetch(`${API_BASE}/api/email/attachments-download-bulk`, {
- method: 'POST',
- credentials: 'same-origin',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- messages,
- category: String(state._libFilter || '').replace(/^tag:/, ''),
- }),
- });
- if (!res.ok) {
- let detail = '';
- try {
- const data = await res.json();
- detail = data?.detail || data?.error || '';
- } catch (_) {}
- throw new Error(detail || `HTTP ${res.status}`);
- }
- const blob = await res.blob();
- const filename = _filenameFromContentDisposition(res.headers.get('Content-Disposition')) || 'selected-email-attachments.zip';
- _downloadBlob(blob, filename);
- showToast(`Exported attachments from ${messages.length} selected email${messages.length === 1 ? '' : 's'}`);
- } catch (err) {
- console.error('Failed to export selected email attachments:', err);
- showToast(err?.message || 'Failed to export attachments');
- } finally {
- if (busySpinner) busySpinner.destroy();
- if (actionsBtn) {
- actionsBtn.disabled = false;
- actionsBtn.classList.remove('email-bulk-loading');
- actionsBtn.innerHTML = originalActionsHtml || actionsBtn.innerHTML;
- }
- if (deleteBtn) deleteBtn.disabled = false;
- if (cancelBtn) cancelBtn.disabled = false;
- if (selectAll) selectAll.disabled = false;
- if (countEl) countEl.textContent = originalCountText;
- _updateBulkBar();
- }
- }
-
- // URL-suffix helper — appends &account_id=... when an account is actively selected.
- // Every email route call in this file goes through here so switching accounts
- // is a single-variable flip.
- // Open the Settings modal and activate a specific tab. Used by empty-state
- // "Set up at: Settings › X" links across email/calendar/etc.
- function _openSettingsTab(tab) {
- if (tab === 'integrations' && window.adminModule && typeof window.adminModule.open === 'function') {
- window.adminModule.open('integrations');
- return;
- }
- if (settingsModule && typeof settingsModule.open === 'function') {
- settingsModule.open(tab || 'services');
- return;
- }
- const modal = document.getElementById('settings-modal');
- if (!modal) return;
- modal.classList.remove('hidden');
- const tabBtn = modal.querySelector(`[data-settings-tab="${tab || 'services'}"]`);
- if (tabBtn) tabBtn.click();
- }
-
- function _openGlobalEmailSettings(focus) {
- const host = document.getElementById('settings-email-preferences');
- if (host && focus) host.dataset.emailSettingsFocus = focus;
- _openSettingsTab('email');
- setTimeout(() => {
- const section = focus === 'show-tags'
- ? document.querySelector('#settings-email-preferences .email-settings-display-section')
- : document.querySelector(`#settings-email-preferences .email-settings-${focus || 'style'}-section`);
- if (section) {
- section.scrollIntoView?.({ block: 'nearest' });
- }
- }, 0);
- }
-
- function _emailSetupHintHtml() {
- return '<div style="margin-top:6px;opacity:0.72;font-size:11px;">' +
- 'Setup: <a href="#" data-open-settings="integrations" style="color:var(--accent,var(--red));text-decoration:underline;">Settings &rsaquo; Integrations</a>' +
- '</div>';
- }
-
- function _wireEmailSetupHint(root) {
- root?.querySelectorAll?.('[data-open-settings]').forEach(link => {
- if (link.dataset.emailSetupBound === '1') return;
- link.dataset.emailSetupBound = '1';
- link.addEventListener('click', (e) => {
- e.preventDefault();
- _openSettingsTab(link.dataset.openSettings || 'integrations');
- });
- });
- }
-
- function _acct() {
- return state._libAccountId ? `&account_id=${encodeURIComponent(state._libAccountId)}` : '';
- }
-
- function _emailMutationQuery(em, fallbackFolder = state._libFolder) {
- const folder = String(em?.folder || fallbackFolder || 'INBOX');
- const accountId = em?.account_id || state._libAccountId || '';
- const params = new URLSearchParams({ folder });
- if (accountId) params.set('account_id', String(accountId));
- if (em?.message_id) params.set('message_id', String(em.message_id));
- return params.toString();
- }
-
- async function _requireSuccessfulEmailMutation(response, fallback = 'Email operation failed') {
- const data = await response.json().catch(() => null);
- if (!response.ok || data?.success !== true) {
- throw new Error(data?.error || `${fallback} (${response.status})`);
- }
- return data;
- }
-
- function _unsubscribeMethodLabel(method) {
- if (!method) return 'No unsubscribe method';
- if (method.kind === 'mailto') return 'Request Unsubscribe';
- if (method.kind === 'url') return 'Link Unsubscribe';
- return method.target || method.kind || 'Unsubscribe';
- }
-
- function _unsubscribeFolderLabel(folder) {
- const value = String(folder || 'INBOX').trim();
- return value.toUpperCase() === 'INBOX' ? 'Inbox' : value;
- }
-
- function _setUnsubButtonBusy(btn, label) {
- if (!btn) return null;
- const previous = btn.innerHTML;
- const previousDisplay = btn.style.display;
- const previousAlignItems = btn.style.alignItems;
- const previousJustifyContent = btn.style.justifyContent;
- const previousGap = btn.style.gap;
- const previousWhiteSpace = btn.style.whiteSpace;
- btn.disabled = true;
- btn.style.display = 'inline-flex';
- btn.style.alignItems = 'center';
- btn.style.justifyContent = 'center';
- btn.style.gap = '5px';
- btn.style.whiteSpace = 'nowrap';
- btn.innerHTML = '';
- const sp = spinnerModule.createWhirlpool(14);
- sp.element.style.position = 'relative';
- sp.element.style.top = '-2px';
- sp.element.style.flexShrink = '0';
- sp.element.style.margin = '0';
- sp.element.style.display = 'inline-flex';
- btn.appendChild(sp.element);
- const text = document.createElement('span');
- text.textContent = label || 'Working';
- text.className = 'email-unsub-busy-label';
- text.style.whiteSpace = 'nowrap';
- text.style.display = 'inline-block';
- btn.appendChild(text);
- const restore = () => {
- btn.disabled = false;
- btn.innerHTML = previous;
- btn.style.display = previousDisplay;
- btn.style.alignItems = previousAlignItems;
- btn.style.justifyContent = previousJustifyContent;
- btn.style.gap = previousGap;
- btn.style.whiteSpace = previousWhiteSpace;
- };
- restore.setLabel = (next) => { text.textContent = next || label || 'Working'; };
- return restore;
- }
-
- const _UNSUB_EMAIL_ICON = '<svg class="email-unsub-accent-icon" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></svg>';
- const _UNSUB_CHECK_ICON = '<svg class="email-unsub-accent-icon" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>';
- const _UNSUB_CLOSE_ICON = '<svg class="email-unsub-accent-icon" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
- const _UNSUB_AGENT_ICON = '<svg class="email-unsub-agent-icon email-unsub-accent-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 8V4H8"/><rect x="4" y="8" width="16" height="12" rx="2"/><path d="M2 14h2M20 14h2M15 13v2M9 13v2"/></svg>';
- const _UNSUB_TRASH_ICON = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6M14 11v6"/></svg>';
- const _UNSUB_REFRESH_ICON = '<svg class="email-unsub-accent-icon" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 0 1 15.3-6.4L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15.3 6.4L3 16"/><path d="M3 21v-5h5"/></svg>';
- const _UNSUB_EXTERNAL_ICON = '<svg class="email-unsub-accent-icon" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>';
-
- function _setUnsubStatusBusy(statusEl, label) {
- if (!statusEl) return null;
- statusEl.classList.remove('is-error');
- statusEl.classList.add('is-busy');
- statusEl.innerHTML = '';
- statusEl.style.display = 'inline-flex';
- statusEl.style.alignItems = 'center';
- statusEl.style.gap = '6px';
- statusEl.style.justifyContent = 'flex-end';
- statusEl.style.width = '100%';
- const text = document.createElement('span');
- text.textContent = label || 'Scanning…';
- statusEl.appendChild(text);
- const sp = spinnerModule.createWhirlpool(14);
- sp.element.style.position = 'relative';
- sp.element.style.top = '0';
- sp.element.style.flexShrink = '0';
- sp.element.style.margin = '0';
- sp.element.style.display = 'inline-flex';
- statusEl.appendChild(sp.element);
- return (next) => {
- statusEl.style.display = '';
- statusEl.style.alignItems = '';
- statusEl.style.gap = '';
- statusEl.style.justifyContent = '';
- statusEl.style.width = '';
- statusEl.classList.remove('is-busy');
- statusEl.textContent = next || '';
- };
- }
-
- function _askAgentToUnsubscribe(candidate) {
- const methods = Array.isArray(candidate?.methods) ? candidate.methods : [];
- const recommended = candidate?.recommended_method;
- const method = (recommended && typeof recommended === 'object')
- ? recommended
- : methods.find(m => m.kind === 'url') || methods[0] || null;
- const url = method?.kind === 'url' ? method.target : '';
- const methodIndex = Math.max(0, methods.findIndex(m => (
- m === method || (m?.kind === method?.kind && m?.target === method?.target)
- )));
- const uid = candidate?.uid || '';
- const reviewedUids = _unsubscribeCandidateUids(candidate);
- const folder = candidate?.folder || state._libFolder || 'INBOX';
- const account = state._libAccountId || '';
- const prompt = url
- ? `The user explicitly clicked Agent Unsubscribe for this reviewed email. Use the private_browser tool to open this exact unsubscribe URL and complete only the unsubscribe flow. Do not use web_search, web_fetch, bash, or scan_email_unsubscribes. After the page confirms a successful unsubscribe, use bulk_email action=delete on these exact reviewed UID(s) so they are not rediscovered. If the page is ambiguous or unsubscribe fails, stop and report that clearly so the user can choose Spam + delete; do not delete a different message.\n\nEmail UID(s): ${reviewedUids.join(', ') || uid}\nFolder: ${folder}\nAccount: ${account || '(default)'}\nExact unsubscribe URL: ${url}`
- : `The user explicitly clicked Agent Unsubscribe for this reviewed email. Use unsubscribe_email directly for the already-reviewed candidate below. Do not call scan_email_unsubscribes again.\n\nEmail UID: ${uid}\nFolder: ${folder}\nAccount: ${account || '(default)'}\nReviewed method_index: ${methodIndex}`;
- return _submitAgentUnsubscribePrompt(prompt);
- }
-
- function _submitAgentUnsubscribePrompt(prompt) {
- const input = document.getElementById('message') || document.getElementById('message-input');
- const form = document.getElementById('chat-form');
- if (!input || !form) {
- showToast?.('Chat composer not found');
- return false;
- }
- input.value = prompt;
- input.dispatchEvent(new Event('input', { bubbles: true }));
- input.focus();
- // Match the working slash-command path. The app-level submit guard can
- // still be settling when this is called from a modal button.
- setTimeout(() => {
- if (!document.body.contains(input) || !document.body.contains(form)) return;
- try {
- form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
- } catch (err) {
- console.error('agent unsubscribe submit failed', err);
- showToast?.('Could not start agent unsubscribe');
- }
- }, 350);
- return true;
- }
-
- function _agentUnsubscribeGroups(candidates) {
- const groups = new Map();
- (candidates || []).forEach(candidate => {
- const urlMethod = (candidate?.methods || []).find(method => method?.kind === 'url');
- const sender = String(candidate?.from_address || '').trim();
- const key = sender ? `sender:${sender.toLowerCase()}` : `uid:${_unsubscribeCandidateUids(candidate).join(',')}`;
- let group = groups.get(key);
- if (!group) {
- group = {
- subject: String(candidate?.subject || '(no subject)'),
- sender,
- uids: [],
- url: String(urlMethod?.target || ''),
- subjects: [],
- };
- groups.set(key, group);
- }
- _unsubscribeCandidateUids(candidate).forEach(uid => {
- if (!group.uids.includes(uid)) group.uids.push(uid);
- });
- const subject = String(candidate?.subject || '').trim();
- if (subject && !group.subjects.includes(subject)) group.subjects.push(subject);
- if (!group.url && urlMethod?.target) group.url = String(urlMethod.target);
- });
- return Array.from(groups.values());
- }
-
- function _askAgentToUnsubscribeAll(candidates) {
- const reviewed = _agentUnsubscribeGroups(candidates)
- .filter(item => item.uids.length || item.url);
- if (!reviewed.length) {
- showToast?.('No remaining unsubscribe candidates');
- return false;
- }
- const account = state._libAccountId || '';
- const lines = reviewed.map((item, index) => (
- `${index + 1}. ${item.sender || '(unknown sender)'} | ${item.subjects.slice(0, 3).join(' / ') || item.subject} | UID(s): ${item.uids.join(', ') || '(none)'} | URL: ${item.url || '(none)'}`
- )).join('\n');
- const prompt = `The user explicitly chose Agent Unsubscribe All for these already-reviewed unsubscribe candidates. They are grouped by sender: open at most one unsubscribe flow per sender and never repeat an unsubscribe attempt for the same sender. Use the private_browser tool for each exact unsubscribe URL. Do not use web_search, web_fetch, bash, or scan_email_unsubscribes. If a page is ambiguous or unsubscribe fails, skip that sender and report it. After a successful unsubscribe, use bulk_email action=delete only for that sender group's exact reviewed UID(s), so those messages are not rediscovered. Do not delete any other messages. Report successful, skipped, and failed senders clearly.\n\nFolder: ${state._libFolder || 'INBOX'}\nAccount: ${account || '(default)'}\n\nReviewed sender groups (${reviewed.length}):\n${lines}`;
- return _submitAgentUnsubscribePrompt(prompt);
- }
-
- function _unsubscribeCandidateUids(candidate) {
- const out = [];
- const seen = new Set();
- const add = (uid) => {
- const val = String(uid || '').trim();
- if (!val || seen.has(val)) return;
- seen.add(val);
- out.push(val);
- };
- add(candidate?.uid);
- (candidate?.duplicate_uids || []).forEach(add);
- return out;
- }
-
- function _unsubscribeHandledStorageKey() {
- return `odysseus.email.unsubscribeHandled.${String(state._libAccountId || 'default')}`;
- }
-
- function _unsubscribeScanStorageKey() {
- const account = String(state._libAccountId || 'default');
- const folder = String(state._libFolder || 'INBOX');
- return `odysseus.email.unsubscribeScan.v2.${account}.${folder}`;
- }
-
- function _readUnsubscribeScanCache() {
- try {
- const parsed = JSON.parse(localStorage.getItem(_unsubscribeScanStorageKey()) || 'null');
- return parsed && Array.isArray(parsed.candidates) ? parsed : null;
- } catch (_) {
- return null;
- }
- }
-
- function _writeUnsubscribeScanCache(data, scanLimit) {
- if (!data || !Array.isArray(data.candidates)) return;
- try {
- localStorage.setItem(_unsubscribeScanStorageKey(), JSON.stringify({
- candidates: data.candidates,
- scanned: Number(data.scanned || 0),
- raw_total: Number(data.raw_total || data.candidates.length || 0),
- scanLimit: scanLimit == null ? 180 : Number(scanLimit),
- scanMode: Number(scanLimit || 0) > 0 ? 'limited' : 'whole-folder',
- savedAt: Date.now(),
- }));
- } catch (_) {}
- }
-
- function _readHandledUnsubscribeState() {
- try {
- const parsed = JSON.parse(localStorage.getItem(_unsubscribeHandledStorageKey()) || '{}');
- return {
- uids: new Set(Array.isArray(parsed.uids) ? parsed.uids.map(String) : []),
- senders: new Set(Array.isArray(parsed.senders) ? parsed.senders.map(v => String(v).toLowerCase()) : []),
- ignoredUids: new Set(Array.isArray(parsed.ignoredUids) ? parsed.ignoredUids.map(String) : []),
- ignoredSenders: new Set(Array.isArray(parsed.ignoredSenders) ? parsed.ignoredSenders.map(v => String(v).toLowerCase()) : []),
- };
- } catch (_) {
- return { uids: new Set(), senders: new Set(), ignoredUids: new Set(), ignoredSenders: new Set() };
- }
- }
-
- function _rememberUnsubscribeHandled(candidates) {
- const current = _readHandledUnsubscribeState();
- (candidates || []).forEach(candidate => {
- _unsubscribeCandidateUids(candidate).forEach(uid => current.uids.add(String(uid)));
- const sender = String(candidate?.from_address || '').trim().toLowerCase();
- if (sender) current.senders.add(sender);
- });
- try {
- localStorage.setItem(_unsubscribeHandledStorageKey(), JSON.stringify({
- uids: Array.from(current.uids).slice(-2000),
- senders: Array.from(current.senders).slice(-500),
- ignoredUids: Array.from(current.ignoredUids).slice(-2000),
- ignoredSenders: Array.from(current.ignoredSenders).slice(-500),
- }));
- } catch (_) {}
- }
-
- function _rememberUnsubscribeIgnored(candidate) {
- const current = _readHandledUnsubscribeState();
- _unsubscribeCandidateUids(candidate).forEach(uid => current.ignoredUids.add(String(uid)));
- const sender = String(candidate?.from_address || '').trim().toLowerCase();
- if (sender) current.ignoredSenders.add(sender);
- try {
- localStorage.setItem(_unsubscribeHandledStorageKey(), JSON.stringify({
- uids: Array.from(current.uids).slice(-2000),
- senders: Array.from(current.senders).slice(-500),
- ignoredUids: Array.from(current.ignoredUids).slice(-2000),
- ignoredSenders: Array.from(current.ignoredSenders).slice(-500),
- }));
- } catch (_) {}
- }
-
- function _filterHandledUnsubscribeCandidates(candidates) {
- const handled = _readHandledUnsubscribeState();
- return (candidates || []).flatMap(candidate => {
- const sender = String(candidate?.from_address || '').trim().toLowerCase();
- if (sender && (handled.senders.has(sender) || handled.ignoredSenders.has(sender))) return [];
- const remainingUids = _unsubscribeCandidateUids(candidate)
- .filter(uid => !handled.uids.has(String(uid)) && !handled.ignoredUids.has(String(uid)));
- if (!remainingUids.length) return [];
- if (remainingUids.length === _unsubscribeCandidateUids(candidate).length) return [candidate];
- return [{
- ...candidate,
- uid: remainingUids[0],
- duplicate_uids: remainingUids.slice(1),
- duplicate_count: remainingUids.length,
- }];
- });
- }
-
- function _dedupeUnsubscribeCandidatesForDisplay(candidates) {
- const out = [];
- const seen = new Map();
- (candidates || []).forEach(c => {
- const method = c?.recommended_method || {};
- const urlMethod = (c?.methods || []).find(m => m?.kind === 'url');
- // One sender address should produce one review action, even when every
- // message carries a different tokenized unsubscribe URL.
- const sender = String(c?.from_address || '').trim().toLowerCase();
- const key = sender || String(c?.list_id || urlMethod?.target || method.target || c?.uid || '').trim().toLowerCase();
- if (!key || !seen.has(key)) {
- if (key) seen.set(key, c);
- out.push(c);
- return;
- }
- const existing = seen.get(key);
- existing.duplicate_count = Number(existing.duplicate_count || 1) + Number(c.duplicate_count || 1);
- const uidSet = new Set(_unsubscribeCandidateUids(existing));
- _unsubscribeCandidateUids(c).forEach(uid => uidSet.add(uid));
- existing.duplicate_uids = Array.from(uidSet);
- });
- return out;
- }
-
- function _markUnsubscribeCardDone(modal, idx, label = 'Unsubscribed') {
- const card = modal?.querySelector?.(`.email-unsub-card[data-idx="${idx}"]`);
- if (!card) return;
- card.classList.add('is-unsubscribed');
- if (!card.querySelector('.email-unsub-done-badge')) {
- const badgeHost = card.querySelector('.email-unsub-subject-line') || card.querySelector('.email-unsub-card-top');
- badgeHost?.insertAdjacentHTML('beforeend', `<span class="email-tag email-unsub-done-badge">${_UNSUB_CHECK_ICON}<span>${_esc(label)}</span></span>`);
- }
- card.querySelectorAll('.email-unsub-link-btn, .email-unsub-agent-btn, .email-unsub-send-btn, .email-unsub-done-btn, .email-unsub-ignore-btn').forEach(el => {
- if (el.tagName === 'A') {
- el.setAttribute('aria-disabled', 'true');
- el.style.pointerEvents = 'none';
- } else {
- el.disabled = true;
- }
- el.style.opacity = '0.55';
- });
- }
-
- function _agentToolArgs(data) {
- const candidates = [data?.args, data?.tool_args, data?.command];
- for (const value of candidates) {
- if (value && typeof value === 'object' && !Array.isArray(value)) return value;
- if (typeof value !== 'string' || !value.trim()) continue;
- try {
- const parsed = JSON.parse(value);
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
- } catch (_) {
- // Some tool cards prefix the JSON with a display label. Recover the
- // object so email mutations still reconcile from the streamed event.
- const start = value.indexOf('{');
- const end = value.lastIndexOf('}');
- if (start >= 0 && end > start) {
- try {
- const parsed = JSON.parse(value.slice(start, end + 1));
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
- } catch (_) {}
- }
- }
- }
- return {};
- }
-
- function _agentBrowserUnsubscribeSucceeded(data) {
- const tool = String(data?.tool || '').toLowerCase();
- if (!tool.includes('private_browser')) return false;
- const output = String(data?.output || '');
- if (/\b(?:not|never|failed|unable|could not|cannot|can't)\b[^.!?\n]{0,50}\bunsubscrib/i.test(output)) {
- return false;
- }
- return /\b(?:already\s+unsubscribed|you(?:'re|\s+are)\s+(?:now\s+)?unsubscribed|successfully\s+unsubscribed|unsubscribed\s+(?:successfully|from)|unsubscription\s+(?:successful|complete)|removed\s+from\s+(?:the\s+)?(?:mailing|email)\s+list)\b/i.test(output);
- }
-
- function _agentBrowserCandidate(run, args) {
- const url = String(args?.url || '').trim();
- if (url && Array.isArray(run?.candidates)) {
- const matched = run.candidates.find(candidate => (
- (candidate?.methods || []).some(method => method?.kind === 'url' && String(method.target || '') === url)
- ));
- if (matched) return matched;
- }
- return run?.activeCandidate || null;
- }
-
- function _trackAgentBrowserUnsubscribe(data) {
- const modal = document.getElementById('email-unsubscribe-review-modal');
- const run = modal?._agentUnsubscribeRun;
- if (!run) return;
- const args = _agentToolArgs(data);
- const action = String(args.action || data?.action || '').toLowerCase();
- const candidate = _agentBrowserCandidate(run, args);
- if (action === 'open' && candidate) run.activeCandidate = candidate;
- if (!candidate || !_agentBrowserUnsubscribeSucceeded(data)) return;
- run.cleanupInFlight ||= new Set();
- if (run.cleanupInFlight.has(candidate) || run.completed.has(candidate)) return;
- run.cleanupInFlight.add(candidate);
- _deleteAfterUnsubscribe([candidate]).then(result => {
- if (Number(result?.failed || 0) > 0 || Number(result?.changed || 0) <= 0) {
- run.failed ||= new Set();
- run.failed.add(candidate);
- run.restoreBusy?.setLabel?.(`Unsubscribed, delete failed (${run.completed.size} / ${run.total})`);
- modal.querySelector('.email-unsub-status')?.replaceChildren(document.createTextNode(
- 'Unsubscribe succeeded, but the matching email could not be moved to Trash. Review it below.',
- ));
- return;
- }
- const idx = run.candidates.indexOf(candidate);
- run.completed.add(candidate);
- _markUnsubscribeCardDone(modal, idx, 'Unsubscribed');
- run.restoreBusy?.setLabel?.(`Unsubscribed ${run.completed.size} / ${run.total}`);
- }).catch(error => {
- run.failed ||= new Set();
- run.failed.add(candidate);
- run.restoreBusy?.setLabel?.(`Unsubscribed, delete failed (${run.completed.size} / ${run.total})`);
- modal.querySelector('.email-unsub-status')?.replaceChildren(document.createTextNode(
- `Unsubscribe succeeded, but delete failed: ${error?.message || 'mail server error'}`,
- ));
- });
- }
-
- function _agentDeletedEmailUids(data) {
- const tool = String(data?.tool || '').toLowerCase();
- const args = _agentToolArgs(data);
- const action = String(args.action || data.action || '').toLowerCase();
- const output = String(data?.output || '').toLowerCase();
- const failed = /\b(?:failed|error|could not|unable|not found)\b/.test(output);
- const isBulkDelete = tool.includes('bulk_email')
- && ['delete', 'trash', 'move_to_trash'].includes(action);
- const isSingleDelete = tool.endsWith('delete_email')
- && !tool.includes('bulk_email');
- const isSuccessfulMailtoUnsubscribe = tool.includes('unsubscribe_email')
- && !failed
- && /(?:source email moved to trash|deleted|unsubscribe email sent)/.test(output);
- if (!isBulkDelete && !isSingleDelete && !isSuccessfulMailtoUnsubscribe) return [];
- if ((isBulkDelete || isSingleDelete) && failed) return [];
- const values = [
- ...(Array.isArray(args.uids) ? args.uids : []),
- ...(Array.isArray(data.deleted_uids) ? data.deleted_uids : []),
- ...(Array.isArray(data.cleaned_uids) ? data.cleaned_uids : []),
- ];
- if (args.uid != null) values.push(args.uid);
- if (data.uid != null) values.push(data.uid);
- return Array.from(new Set(values.map(uid => String(uid || '').trim()).filter(Boolean)));
- }
-
- function _handleAgentEmailToolOutput(event) {
- const data = event?.detail || {};
- _trackAgentBrowserUnsubscribe(data);
- const ok = data.exit_code == null ? data.success !== false : data.exit_code === 0;
- if (!ok) return;
- const deletedUids = new Set(_agentDeletedEmailUids(data));
- if (!deletedUids.size) return;
-
- state._libEmails = (state._libEmails || []).filter(email => !deletedUids.has(String(email?.uid || '')));
- try { _libCacheWriteBack(); } catch (_) {}
- try { _renderGrid(); } catch (_) {}
-
- const modal = document.getElementById('email-unsubscribe-review-modal');
- const completed = [];
- (modal?._unsubscribeCandidates || []).forEach((candidate, idx) => {
- const remaining = _unsubscribeCandidateUids(candidate)
- .filter(uid => !deletedUids.has(String(uid)));
- if (remaining.length === _unsubscribeCandidateUids(candidate).length) return;
- if (!remaining.length) {
- completed.push(candidate);
- _markUnsubscribeCardDone(modal, idx, 'Agent done');
- return;
- }
- candidate.uid = remaining[0];
- candidate.duplicate_uids = remaining.slice(1);
- candidate.duplicate_count = remaining.length;
- });
- const run = modal?._agentUnsubscribeRun;
- if (run && completed.length) {
- completed.forEach(candidate => run.completed.add(candidate));
- run.restoreBusy?.setLabel?.(`Unsubscribed ${run.completed.size} / ${run.total}`);
- }
- if (completed.length) _rememberUnsubscribeHandled(completed);
- const visible = (modal?._unsubscribeCandidates || []).filter(candidate => (
- _unsubscribeCandidateUids(candidate).some(uid => !deletedUids.has(String(uid)))
- ));
- if (modal && !visible.length) {
- if (run) {
- run.restoreBusy?.setLabel?.(`Unsubscribed ${run.total} / ${run.total}`);
- run.restoreBusy = null;
- modal._agentUnsubscribeRun = null;
- }
- modal.querySelector('.email-unsub-list')?.style.setProperty('display', 'none');
- modal.querySelector('.email-unsub-followup')?.remove();
- modal.querySelector('.email-unsub-status')?.replaceChildren(document.createTextNode('Agent unsubscribe cleanup completed.'));
- }
- }
-
- window.addEventListener('odysseus:agent-tool-output', _handleAgentEmailToolOutput);
-
- function _handleAgentUnsubscribeTerminal(event) {
- const modal = document.getElementById('email-unsubscribe-review-modal');
- const run = modal?._agentUnsubscribeRun;
- if (!run) return;
- const detail = event?.detail?.data || {};
- (Array.isArray(detail.tool_events) ? detail.tool_events : []).forEach(_trackAgentBrowserUnsubscribe);
- const completed = run.completed.size;
- const remaining = Math.max(0, run.total - completed);
- const failure = detail.failure || (detail.failed ? { message: 'The agent run failed before all unsubscribe flows completed.' } : null);
- run.restoreBusy?.();
- modal._agentUnsubscribeRun = null;
- modal.querySelector('.email-unsub-status')?.replaceChildren(document.createTextNode(
- failure
- ? `Agent unsubscribe failed: ${completed} / ${run.total} completed. ${remaining} still need review. ${failure.message || ''}`.trim()
- : remaining
- ? `Agent unsubscribe finished: ${completed} / ${run.total} completed. ${remaining} still need review.`
- : `Agent unsubscribe finished: ${completed} / ${run.total} completed.`,
- ));
- // A tool result can arrive just after the final browser step. Re-fetch once
- // the run is over so an old mailbox page or server-side list cache cannot
- // leave deleted messages visible until the next manual refresh.
- if (!failure && typeof refreshEmailLibrary === 'function') {
- setTimeout(() => refreshEmailLibrary().catch(() => {}), 0);
- }
- }
-
- window.addEventListener('odysseus:agent-terminal', _handleAgentUnsubscribeTerminal);
-
- async function _runUnsubscribeCleanup(modal, candidates, action, btn) {
- const uids = [];
- const seen = new Set();
- (candidates || []).forEach(c => {
- _unsubscribeCandidateUids(c).forEach(uid => {
- if (seen.has(uid)) return;
- seen.add(uid);
- uids.push(uid);
- });
- });
- if (!uids.length) {
- showToast?.('No emails to update');
- return;
- }
- const busyLabel = action === 'junk'
- ? 'Marking spam'
- : action === 'junk_delete' ? 'Spam + delete' : 'Deleting';
- const restoreBusy = _setUnsubButtonBusy(btn, busyLabel);
- try {
- const r = await fetch(emailApiUrl('/api/email/unsubscribe/cleanup', {
- account_id: state._libAccountId || undefined,
- }), {
- method: 'POST',
- credentials: 'same-origin',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- action,
- uids,
- folder: state._libFolder || 'INBOX',
- account_id: state._libAccountId || '',
- }),
- });
- const d = await r.json().catch(() => ({}));
- if (!d.success) throw new Error(d.error || 'Cleanup failed');
- const removed = new Set(uids.map(uid => String(uid)));
- state._libEmails = state._libEmails.filter(e => !removed.has(String(e.uid)));
- try { _libCacheWriteBack(); } catch (_) {}
- try { _renderGrid(); } catch (_) {}
- _rememberUnsubscribeHandled(candidates);
- modal.querySelector('.email-unsub-followup')?.remove();
- showToast?.(action === 'junk'
- ? `Marked ${d.changed || 0} email${Number(d.changed || 0) === 1 ? '' : 's'} as spam`
- : action === 'junk_delete'
- ? `Marked ${d.changed || 0} email${Number(d.changed || 0) === 1 ? '' : 's'} as spam and deleted ${d.changed || 0}`
- : `Deleted ${d.changed || 0} email${Number(d.changed || 0) === 1 ? '' : 's'}`);
- } catch (err) {
- console.error(err);
- showToast?.(err?.message || 'Cleanup failed');
- } finally {
- restoreBusy?.();
- }
- }
-
- async function _deleteAfterUnsubscribe(candidates) {
- const groups = new Map();
- (candidates || []).forEach(c => {
- const sender = String(c?.from_address || '').trim();
- const key = sender.toLowerCase() || `uids:${_unsubscribeCandidateUids(c).join(',')}`;
- if (!groups.has(key)) groups.set(key, { sender, uids: [] });
- const group = groups.get(key);
- const seen = new Set(group.uids);
- _unsubscribeCandidateUids(c).forEach(uid => {
- if (!seen.has(uid)) {
- seen.add(uid);
- group.uids.push(uid);
- }
- });
- });
- if (!groups.size) return { success: true, changed: 0, failed: 0, cleaned_uids: [] };
- const result = { success: true, changed: 0, failed: 0, cleaned_uids: [] };
- for (const group of groups.values()) {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 30000);
- let r;
- try {
- r = await fetch(emailApiUrl('/api/email/unsubscribe/cleanup', {
- account_id: state._libAccountId || undefined,
- }), {
- method: 'POST',
- credentials: 'same-origin',
- headers: { 'Content-Type': 'application/json' },
- signal: controller.signal,
- body: JSON.stringify({
- action: 'delete',
- scope: group.sender ? 'sender_unsubscribe' : '',
- sender: group.sender,
- uids: group.sender ? [] : group.uids,
- folder: state._libFolder || 'INBOX',
- account_id: state._libAccountId || '',
- }),
- });
- } catch (err) {
- if (err?.name === 'AbortError') throw new Error('Deleting timed out; the mail server did not respond');
- throw err;
- } finally {
- clearTimeout(timeout);
- }
- const d = await r.json().catch(() => ({}));
- if (!d.success) throw new Error(d.error || 'Could not move unsubscribed emails to Trash');
- result.changed += Number(d.changed || 0);
- result.failed += Number(d.failed || 0);
- result.cleaned_uids.push(...(d.cleaned_uids || []));
- }
- const removed = new Set(result.cleaned_uids.map(uid => String(uid)));
- state._libEmails = state._libEmails.filter(e => !removed.has(String(e.uid)));
- try { _libCacheWriteBack(); } catch (_) {}
- try { _renderGrid(); } catch (_) {}
- _rememberUnsubscribeHandled(candidates);
- return result;
- }
-
- function _showUnsubscribeCleanupPrompt(modal, candidates, options = {}) {
- if (!modal || !Array.isArray(candidates) || !candidates.length) return;
- modal.querySelector('.email-unsub-followup')?.remove();
- const count = candidates.reduce((sum, c) => sum + _unsubscribeCandidateUids(c).length, 0);
- const heading = options.heading || `Done. Mark all ${count} of these email${count === 1 ? '' : 's'} as spam?`;
- const rows = candidates.map(c => {
- const uids = _unsubscribeCandidateUids(c);
- return `
- <div style="display:flex;gap:8px;align-items:center;min-width:0;">
- <div style="min-width:0;flex:1;">
- <div style="font-weight:650;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${_esc(c.subject || '(no subject)')}</div>
- <div style="font-size:11px;color:color-mix(in srgb,var(--fg) 62%,transparent);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${_esc(c.from_name || c.from_address || '')} · ${_esc(c.from_address || '')}</div>
- </div>
- ${uids.length > 1 ? `<span class="email-tag">x${uids.length}</span>` : ''}
- </div>`;
- }).join('');
- const box = document.createElement('div');
- box.className = 'email-unsub-followup';
- box.style.cssText = 'border:1px solid color-mix(in srgb,var(--accent,var(--red)) 35%,var(--border));border-radius:8px;padding:10px;background:color-mix(in srgb,var(--accent,var(--red)) 8%,transparent);display:flex;flex-direction:column;gap:8px;';
- box.innerHTML = `
- <div style="display:flex;gap:8px;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;">
- <div style="font-size:12px;font-weight:700;">${_esc(heading)}</div>
- <div style="display:flex;gap:6px;flex-wrap:wrap;">
- <button type="button" class="memory-toolbar-btn email-unsub-clean-spam" style="display:inline-flex;align-items:center;gap:4px;">${_UNSUB_CHECK_ICON}<span>Mark as spam</span></button>
- <button type="button" class="memory-toolbar-btn email-unsub-clean-junk-delete" style="display:inline-flex;align-items:center;gap:4px;color:var(--red);">${_UNSUB_TRASH_ICON}<span>Spam + delete</span></button>
- <button type="button" class="memory-toolbar-btn email-unsub-clean-delete" style="display:inline-flex;align-items:center;gap:4px;color:var(--red);">${_UNSUB_TRASH_ICON}<span>Delete</span></button>
- <button type="button" class="memory-toolbar-btn email-unsub-clean-keep" style="display:inline-flex;align-items:center;gap:4px;">${_UNSUB_CHECK_ICON}<span>Keep</span></button>
- ${options.scanFurther ? '<button type="button" class="memory-toolbar-btn email-unsub-scan-further">Scan further</button>' : ''}
- </div>
- </div>
- <div style="display:flex;flex-direction:column;gap:5px;font-size:12px;">${rows}</div>`;
- const body = modal.querySelector('.modal-body');
- const list = modal.querySelector('.email-unsub-list');
- body?.insertBefore(box, list || null);
- box.querySelector('.email-unsub-clean-spam')?.addEventListener('click', (e) => {
- _runUnsubscribeCleanup(modal, candidates, 'junk', e.currentTarget);
- });
- box.querySelector('.email-unsub-clean-junk-delete')?.addEventListener('click', async (e) => {
- const ok = await styledConfirm(`Mark ${count} reviewed email${count === 1 ? '' : 's'} as spam and delete ${count === 1 ? 'it' : 'them'}?`, {
- confirmText: 'Spam + delete',
- cancelText: 'Cancel',
- danger: true,
- });
- if (ok) _runUnsubscribeCleanup(modal, candidates, 'junk_delete', e.currentTarget);
- });
- box.querySelector('.email-unsub-clean-delete')?.addEventListener('click', async (e) => {
- const ok = await styledConfirm(`Delete ${count} reviewed email${count === 1 ? '' : 's'}?`, {
- confirmText: 'Delete',
- cancelText: 'Cancel',
- danger: true,
- });
- if (ok) _runUnsubscribeCleanup(modal, candidates, 'delete', e.currentTarget);
- });
- box.querySelector('.email-unsub-clean-keep')?.addEventListener('click', () => box.remove());
- box.querySelector('.email-unsub-scan-further')?.addEventListener('click', () => {
- const nextAnchor = options.scanAnchor;
- modal.remove();
- if (nextAnchor) setTimeout(() => _openUnsubscribeReviewModal(nextAnchor), 0);
- });
- }
-
- function _showUnsubscribeScanFurtherPrompt(modal, anchor, heading) {
- if (!modal || !anchor) return;
- modal.querySelector('.email-unsub-followup')?.remove();
- const box = document.createElement('div');
- box.className = 'email-unsub-followup';
- box.style.cssText = 'border:1px solid color-mix(in srgb,var(--accent,var(--red)) 35%,var(--border));border-radius:8px;padding:10px;background:color-mix(in srgb,var(--accent,var(--red)) 8%,transparent);display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;';
- box.innerHTML = `<span style="font-size:12px;font-weight:700;">${_esc(heading)}</span><button type="button" class="memory-toolbar-btn email-unsub-scan-further">Scan further</button>`;
- const body = modal.querySelector('.modal-body');
- const list = modal.querySelector('.email-unsub-list');
- body?.insertBefore(box, list || null);
- box.querySelector('.email-unsub-scan-further')?.addEventListener('click', () => {
- modal.remove();
- setTimeout(() => _openUnsubscribeReviewModal(anchor), 0);
- });
- }
-
- function _showUnsubscribeRemainingPrompt(modal, candidates) {
- if (!modal || !Array.isArray(candidates) || !candidates.length) return;
- modal.querySelector('.email-unsub-followup')?.remove();
- const remaining = new Set(candidates);
- modal.querySelectorAll('.email-unsub-card').forEach(card => {
- const idx = Number(card.dataset.idx || -1);
- card.hidden = !remaining.has(modal._unsubscribeCandidates?.[idx]);
- });
- const box = document.createElement('div');
- box.className = 'email-unsub-followup email-unsub-remaining-followup';
- box.style.cssText = 'border:1px solid color-mix(in srgb,var(--accent,var(--red)) 35%,var(--border));border-radius:8px;padding:10px;background:color-mix(in srgb,var(--accent,var(--red)) 8%,transparent);display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;';
- box.innerHTML = `
- <span style="font-size:12px;font-weight:700;">${candidates.length} unsubscribe${candidates.length === 1 ? '' : 's'} still need review</span>
- <span class="email-unsub-remaining-actions">
- <button type="button" class="memory-toolbar-btn email-unsub-clean-remaining-btn">${_UNSUB_TRASH_ICON}<span>Spam + delete remaining</span></button>
- <button type="button" class="memory-toolbar-btn email-unsub-agent-all-btn">${_UNSUB_AGENT_ICON}<span>Agent Unsubscribe All</span></button>
- </span>`;
- const body = modal.querySelector('.modal-body');
- const list = modal.querySelector('.email-unsub-list');
- body?.insertBefore(box, list || null);
- box.querySelector('.email-unsub-clean-remaining-btn')?.addEventListener('click', async (event) => {
- const count = candidates.reduce((sum, candidate) => sum + _unsubscribeCandidateUids(candidate).length, 0);
- const ok = await styledConfirm(
- `Mark ${count} remaining email${count === 1 ? '' : 's'} as spam and delete ${count === 1 ? 'it' : 'them'}?`,
- { confirmText: 'Spam + delete', cancelText: 'Cancel', danger: true },
- );
- if (ok) _runUnsubscribeCleanup(modal, candidates, 'junk_delete', event.currentTarget);
- });
- box.querySelector('.email-unsub-agent-all-btn')?.addEventListener('click', (event) => {
- const button = event.currentTarget;
- if (modal._agentUnsubscribeRun) return;
- const total = candidates.length;
- const restoreBusy = _setUnsubButtonBusy(button, `Completed 0 / ${total}`);
- modal._agentUnsubscribeRun = {
- total,
- candidates: candidates.slice(),
- completed: new Set(),
- cleanupInFlight: new Set(),
- restoreBusy,
- };
- if (!_askAgentToUnsubscribeAll(candidates)) {
- restoreBusy?.();
- modal._agentUnsubscribeRun = null;
- }
- });
- }
-
- async function _openUnsubscribeReviewModal(anchor, options = {}) {
- const existing = document.getElementById('email-unsubscribe-review-modal');
- if (existing) {
- existing.scrollIntoView?.({ behavior: 'smooth', block: 'nearest' });
- existing.querySelector('.email-unsub-status')?.scrollIntoView?.({ behavior: 'smooth', block: 'nearest' });
- return;
- }
- const modal = document.createElement('div');
- const scanFolderLabel = _unsubscribeFolderLabel(state._libFolder);
- modal.className = 'modal';
- modal.id = 'email-unsubscribe-review-modal';
- const settingsPage = anchor?.closest?.('#email-lib-settings-page, .email-settings-page-host');
- const inlineHost = settingsPage?.querySelector?.('.email-settings-cleanup-section');
- const inlineMode = !!inlineHost;
- if (inlineMode) {
- modal.className = 'email-unsubscribe-inline-panel';
- modal.style.cssText = 'display:none;margin-top:10px;';
- modal.innerHTML = `
- <div class="modal-body" style="display:flex;flex-direction:column;gap:10px;overflow:visible;">
- <div class="email-unsub-actions" style="display:none;gap:7px;justify-content:flex-end;align-items:center;flex-wrap:wrap;">
- <span class="email-unsub-panel-status" aria-live="polite"></span>
- <button type="button" class="memory-toolbar-btn email-unsub-rescan-btn" style="display:inline-flex;align-items:center;gap:4px;">${_UNSUB_REFRESH_ICON}<span>Rescan</span></button>
- <button type="button" class="memory-toolbar-btn email-unsub-delete-all-btn" style="display:inline-flex;align-items:center;gap:4px;">${_UNSUB_TRASH_ICON}<span>Delete all</span></button>
- <button type="button" class="memory-toolbar-btn email-unsub-auto-safe-btn" style="display:none;align-items:center;gap:4px;">${_UNSUB_CHECK_ICON}<span>Auto Unsubscribe All</span></button>
- </div>
- <div class="email-unsub-list" style="display:none;flex-direction:column;gap:8px;"></div>
- </div>`;
- inlineHost.appendChild(modal);
- } else {
- modal.style.display = 'block';
- modal.innerHTML = `
- <div class="modal-content doclib-modal-content" style="width:min(680px,92vw);background:var(--bg);">
- <div class="modal-header">
- <h4>
- <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:5px;"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>
- Unsubscribe review
- </h4>
- </div>
- <div class="modal-body" style="display:flex;flex-direction:column;gap:10px;max-height:min(72vh,620px);overflow:auto;">
- <div class="email-unsub-status" style="font-size:10.5px;color:color-mix(in srgb,var(--fg) 68%,transparent);">Scanning ${_esc(scanFolderLabel)} headers…</div>
- <div class="email-unsub-actions" style="display:none;gap:7px;justify-content:flex-end;align-items:center;flex-wrap:wrap;">
- <span class="email-unsub-panel-status" aria-live="polite"></span>
- <button type="button" class="memory-toolbar-btn email-unsub-rescan-btn" style="display:inline-flex;align-items:center;gap:4px;">${_UNSUB_REFRESH_ICON}<span>Rescan</span></button>
- <button type="button" class="memory-toolbar-btn email-unsub-delete-all-btn" style="display:inline-flex;align-items:center;gap:4px;">${_UNSUB_TRASH_ICON}<span>Delete all</span></button>
- <button type="button" class="memory-toolbar-btn email-unsub-auto-safe-btn" style="display:none;align-items:center;gap:4px;">${_UNSUB_CHECK_ICON}<span>Auto Unsubscribe All</span></button>
- </div>
- <div class="email-unsub-list" style="display:none;flex-direction:column;gap:8px;"></div>
- </div>
- </div>`;
- document.body.appendChild(modal);
- }
- const close = () => modal.remove();
- if (!inlineMode) modal.addEventListener('click', (e) => { if (e.target === modal) close(); });
- const statusEl = inlineMode
- ? inlineHost.querySelector('.email-settings-clean-status')
- : modal.querySelector('.email-unsub-status');
- const panelStatusEl = modal.querySelector('.email-unsub-panel-status');
- const listEl = modal.querySelector('.email-unsub-list');
- const cachedScan = options.forceRescan ? null : _readUnsubscribeScanCache();
- const usingCachedScan = !!cachedScan;
- let finishScanStatus = _setUnsubStatusBusy(
- statusEl,
- usingCachedScan ? 'Loading last unsubscribe scan…' : `Scanning ${scanFolderLabel} headers…`,
- );
- const showFinalStatus = (message, isError = false) => {
- const actionsEl = modal.querySelector('.email-unsub-actions');
- if (actionsEl) actionsEl.style.display = 'flex';
- if (inlineMode && panelStatusEl) {
- finishScanStatus?.('');
- panelStatusEl.classList.toggle('is-error', isError);
- panelStatusEl.textContent = message || '';
- modal.style.display = 'block';
- return;
- }
- statusEl?.classList.toggle('is-error', isError);
- finishScanStatus?.(message);
- };
- const finishScanError = (message) => {
- showFinalStatus(message || 'Failed to scan email headers', true);
- };
- try {
- const scanUnsubscribeHeaders = (maxScan) => fetch(emailApiUrl('/api/email/unsubscribe/scan', {
- folder: state._libFolder || 'INBOX',
- limit: 500,
- max_scan: maxScan,
- account_id: state._libAccountId || undefined,
- }), { credentials: 'same-origin' });
- const readScanResponse = async (response) => {
- const payload = await response.json().catch(() => ({}));
- if (!response.ok) {
- throw new Error(
- payload?.error || payload?.detail || `Email scan failed (HTTP ${response.status})`,
- );
- }
- return payload;
- };
- // Keep the review request below the app's 45s hard deadline. The old
- // whole-folder request made Gmail scans time out before any cards loaded.
- let scanLimit = 500;
- let res;
- let data = cachedScan;
- if (!data) {
- res = await scanUnsubscribeHeaders(scanLimit);
- data = await readScanResponse(res);
- } else {
- scanLimit = Number(data.scanLimit || scanLimit);
- }
- if (!data || (!data.success && !usingCachedScan)) {
- finishScanError(data?.error || 'Failed to scan email headers');
- return;
- }
- let candidates = _filterHandledUnsubscribeCandidates(
- _dedupeUnsubscribeCandidatesForDisplay(data.candidates || []),
- );
- if (!usingCachedScan && !candidates.length && scanLimit > 0 && Number(data.scanned || 0) >= scanLimit) {
- const searchMore = await styledConfirm(
- `No unsubscribe candidates found in ${scanLimit} recent emails. Search more?`,
- { title: 'Search more?', confirmText: 'Search more', cancelText: 'No' },
- );
- if (searchMore) {
- scanLimit = 0;
- finishScanStatus = _setUnsubStatusBusy(statusEl, `Scanning ${scanLimit} recent ${scanFolderLabel} headers…`);
- res = await scanUnsubscribeHeaders(scanLimit);
- data = await readScanResponse(res);
- if (!data.success) {
- finishScanError(data.error || 'Failed to scan email headers');
- return;
- }
- candidates = _filterHandledUnsubscribeCandidates(
- _dedupeUnsubscribeCandidatesForDisplay(data.candidates || []),
- );
- }
- }
- if (!usingCachedScan) _writeUnsubscribeScanCache(data, scanLimit);
- const rawTotal = Number(data.raw_total || candidates.length || 0);
- const scanPrefix = usingCachedScan ? 'Last scan: ' : '';
- const scanSuffix = usingCachedScan ? ' Rescan for fresh results.' : '';
- const scanScope = scanLimit > 0 ? `${data.scanned || 0} recent emails` : `all ${data.scanned || 0} emails`;
- const finalStatus = candidates.length
- ? `${scanPrefix}Found ${candidates.length} unsubscribe target${candidates.length === 1 ? '' : 's'} from ${scanScope}${rawTotal > candidates.length ? `, collapsed from ${rawTotal} matching emails` : ''}.${scanSuffix} Review before sending unsubscribe.`
- : `${scanPrefix}No unsubscribe candidates found in ${scanScope}.${scanSuffix}`;
- showFinalStatus(finalStatus);
- modal.querySelector('.email-unsub-actions').style.display = 'flex';
- modal.querySelector('.email-unsub-delete-all-btn').style.display = candidates.length ? 'inline-flex' : 'none';
- modal.querySelector('.email-unsub-auto-safe-btn').style.display = candidates.length ? 'inline-flex' : 'none';
- listEl.style.display = candidates.length ? 'flex' : 'none';
- listEl.innerHTML = candidates.map((c, idx) => {
- const method = c.recommended_method || null;
- const reasons = (c.reasons || []).map(r => `<span class="email-tag">${_esc(r)}</span>`).join('');
- const urlMethod = (c.methods || []).find(m => m.kind === 'url');
- const duplicateCount = Number(c.duplicate_count || 1);
- const duplicateBadge = duplicateCount > 1 ? `<span class="email-tag email-unsub-duplicate-badge">x${duplicateCount}</span>` : '';
- const deleteLabel = duplicateCount > 1 ? 'Delete all' : 'Delete';
- const deleteTitle = duplicateCount > 1
- ? 'Delete all unsubscribe emails from this sender'
- : 'Delete matching unsubscribe emails from this sender';
- return `
- <div class="email-unsub-card" data-idx="${idx}" style="border:1px solid var(--border);border-radius:8px;padding:10px;background:color-mix(in srgb,var(--fg) 3%,transparent);display:flex;flex-direction:column;gap:7px;">
- <div class="email-unsub-card-top" style="display:flex;gap:8px;align-items:center;padding-right:0;">
- <div class="email-unsub-card-summary" style="min-width:0;flex:1;">
- <div class="email-unsub-subject-line" style="display:flex;align-items:center;gap:6px;min-width:0;">
- <div style="font-weight:700;font-size:13px;min-width:0;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${_esc(c.subject || '(no subject)')}</div>
- </div>
- <div class="email-unsub-card-subtitle" style="font-size:11px;color:color-mix(in srgb,var(--fg) 62%,transparent);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${_esc(c.from_name || c.from_address || '')} · ${_esc(c.from_address || '')}</div>
- </div>
- <button type="button" class="email-unsub-card-toggle" data-idx="${idx}" aria-expanded="false" aria-controls="email-unsub-details-${idx}" title="Show unsubscribe details" aria-label="Show unsubscribe details">
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"></polyline></svg>
- </button>
- </div>
- <div id="email-unsub-details-${idx}" class="email-unsub-card-details" hidden>
- <div class="email-unsub-detail-head" style="display:flex;gap:7px;align-items:center;flex-wrap:wrap;">
- <span class="email-tag email-tag-spam" style="flex:0 0 auto;">score ${_esc(c.score || 0)}</span>
- ${duplicateBadge}
- <span style="flex:1 1 auto;min-width:8px;"></span>
- <button type="button" class="memory-toolbar-btn email-unsub-done-btn" data-idx="${idx}" title="${deleteTitle}" aria-label="${deleteLabel} unsubscribe emails">${_UNSUB_TRASH_ICON}<span>${deleteLabel}</span></button>
- <button type="button" class="memory-toolbar-btn email-unsub-ignore-btn" data-idx="${idx}" title="Ignore this unsubscribe candidate" aria-label="Ignore this unsubscribe candidate">${_UNSUB_CLOSE_ICON}</button>
- </div>
- <div class="email-unsub-reasons" style="display:flex;flex-wrap:wrap;gap:4px;">${reasons}</div>
- <div class="email-unsub-actions-row" style="display:flex;gap:7px;align-items:center;justify-content:flex-end;flex-wrap:wrap;">
- ${c.can_execute ? `<button type="button" class="memory-toolbar-btn email-unsub-send-btn" data-idx="${idx}" style="display:inline-flex;align-items:center;gap:4px;">${_UNSUB_EMAIL_ICON}<span>${_esc(_unsubscribeMethodLabel(method))}</span></button>` : ''}
- ${urlMethod ? `<button type="button" class="memory-toolbar-btn email-unsub-agent-btn" data-idx="${idx}" style="display:inline-flex;align-items:center;gap:6px;"><svg class="email-unsub-agent-icon email-unsub-accent-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 8V4H8"/><rect x="4" y="8" width="16" height="12" rx="2"/><path d="M2 14h2M20 14h2M15 13v2M9 13v2"/></svg><span>Agent Unsubscribe</span></button>` : ''}
- ${urlMethod ? `<a class="memory-toolbar-btn email-unsub-link-btn" href="${_esc(urlMethod.target)}" target="_blank" rel="noopener noreferrer" style="text-decoration:none;display:inline-flex;align-items:center;gap:4px;">${_UNSUB_EXTERNAL_ICON}<span>Link Unsubscribe</span></a>` : ''}
- </div>
- </div>
- </div>`;
- }).join('');
- modal._unsubscribeCandidates = candidates;
- listEl.querySelectorAll('.email-unsub-card-toggle').forEach(btn => {
- btn.addEventListener('click', () => {
- const card = btn.closest('.email-unsub-card');
- const details = card?.querySelector('.email-unsub-card-details');
- if (!details) return;
- const isOpen = !details.hidden;
- details.hidden = isOpen;
- card.classList.toggle('is-expanded', !isOpen);
- btn.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
- btn.setAttribute('aria-label', isOpen ? 'Show unsubscribe details' : 'Hide unsubscribe details');
- btn.title = isOpen ? 'Show unsubscribe details' : 'Hide unsubscribe details';
- });
- });
- modal.querySelector('.email-unsub-rescan-btn')?.addEventListener('click', () => {
- modal.remove();
- setTimeout(() => _openUnsubscribeReviewModal(anchor, { forceRescan: true }), 0);
- });
- modal.querySelector('.email-unsub-delete-all-btn')?.addEventListener('click', async (event) => {
- const allCandidates = modal._unsubscribeCandidates || [];
- const count = allCandidates.reduce((sum, candidate) => sum + _unsubscribeCandidateUids(candidate).length, 0);
- if (!count) {
- finishScanStatus?.('No unsubscribe emails to delete.');
- return;
- }
- const ok = await styledConfirm(
- `Delete all ${count} reviewed unsubscribe email${count === 1 ? '' : 's'}?`,
- { confirmText: 'Delete all', cancelText: 'Cancel', danger: true },
- );
- if (!ok) return;
- const restoreBusy = _setUnsubButtonBusy(event.currentTarget, 'Deleting all');
- try {
- const result = await _deleteAfterUnsubscribe(allCandidates);
- if (Number(result?.failed || 0) > 0 || Number(result?.changed || 0) <= 0) {
- throw new Error('Could not move the reviewed emails to Trash');
- }
- allCandidates.forEach((candidate, idx) => _markUnsubscribeCardDone(modal, idx, 'Deleted'));
- modal.querySelector('.email-unsub-list')?.style.setProperty('display', 'none');
- finishScanStatus?.(`Deleted ${result.changed} reviewed email${result.changed === 1 ? '' : 's'}`);
- } catch (error) {
- finishScanStatus?.(error?.message || 'Delete all failed');
- } finally {
- restoreBusy?.();
- }
- });
- modal.querySelector('.email-unsub-auto-safe-btn')?.addEventListener('click', async () => {
- const safeCandidates = (modal._unsubscribeCandidates || [])
- .map((c, idx) => ({ c, idx }))
- .filter(item => item.c && item.c.can_execute);
- if (!safeCandidates.length) {
- finishScanStatus?.(`No automatic unsubscribe actions found. ${modal._unsubscribeCandidates?.length || 0} link${(modal._unsubscribeCandidates?.length || 0) === 1 ? '' : 's'} still need review.`);
- _showUnsubscribeRemainingPrompt(modal, modal._unsubscribeCandidates || []);
- return;
- }
- const ok = await styledConfirm(`Send unsubscribe emails for ${safeCandidates.length} target${safeCandidates.length === 1 ? '' : 's'}?`, {
- confirmText: 'Auto Unsubscribe All',
- cancelText: 'Cancel',
- });
- if (!ok) return;
- const btn = modal.querySelector('.email-unsub-auto-safe-btn');
- const restoreBusy = _setUnsubButtonBusy(btn, `Unsubscribing 0/${safeCandidates.length}`);
- let sent = 0;
- let failed = 0;
- const sentCandidates = [];
- const failedCandidates = [];
- try {
- for (const item of safeCandidates) {
- const c = item.c;
- try {
- restoreBusy?.setLabel?.(`Unsubscribing ${sent + failed + 1}/${safeCandidates.length}`);
- const r = await fetch(emailApiUrl('/api/email/unsubscribe/execute', {
- account_id: state._libAccountId || undefined,
- }), {
- method: 'POST',
- credentials: 'same-origin',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- uid: c.uid,
- folder: c.folder || state._libFolder || 'INBOX',
- account_id: state._libAccountId || '',
- method_index: 0,
- move_to_spam: false,
- }),
- });
- const d = await r.json().catch(() => ({}));
- if (!d.success) throw new Error(d.error || 'Unsubscribe failed');
- sent += 1;
- sentCandidates.push(c);
- const rowBtn = modal.querySelector(`.email-unsub-send-btn[data-idx="${item.idx}"]`);
- if (rowBtn) {
- rowBtn.disabled = true;
- rowBtn.innerHTML = `${_UNSUB_CHECK_ICON}<span>Sent</span>`;
- rowBtn.style.display = 'inline-flex';
- rowBtn.style.alignItems = 'center';
- rowBtn.style.gap = '4px';
- }
- _markUnsubscribeCardDone(modal, item.idx);
- } catch (err) {
- failed += 1;
- failedCandidates.push(c);
- console.error(err);
- }
- }
- } finally {
- restoreBusy?.();
- }
- let deleteFailed = false;
- let cleanupResult = { success: true, changed: 0, failed: 0, cleaned_uids: [] };
- if (sentCandidates.length) {
- try {
- cleanupResult = await _deleteAfterUnsubscribe(sentCandidates);
- deleteFailed = Number(cleanupResult.failed || 0) > 0;
- const cleaned = new Set((cleanupResult.cleaned_uids || []).map(uid => String(uid)));
- (modal._unsubscribeCandidates || []).forEach((candidate, candidateIdx) => {
- if (_unsubscribeCandidateUids(candidate).some(uid => cleaned.has(String(uid)))) {
- _markUnsubscribeCardDone(modal, candidateIdx);
- }
- });
- } catch (err) {
- deleteFailed = true;
- console.error(err);
- }
- }
- const handled = new Set();
- sentCandidates.forEach(c => _unsubscribeCandidateUids(c).forEach(uid => handled.add(String(uid))));
- (cleanupResult.cleaned_uids || []).forEach(uid => handled.add(String(uid)));
- const remainingCandidates = (modal._unsubscribeCandidates || []).filter(c => (
- !_unsubscribeCandidateUids(c).some(uid => handled.has(String(uid)))
- ));
- finishScanStatus?.(
- `Auto unsubscribe finished: ${sent} unsubscribed${failed ? `, ${failed} failed` : ''}${remainingCandidates.length ? `, ${remainingCandidates.length} still need review` : ''}.`,
- );
- if (sent && !failed && !deleteFailed) {
- showToast?.(`Unsubscribed and deleted ${sent} email${sent === 1 ? '' : 's'}`);
- } else if (sent || failed) {
- showToast?.(deleteFailed
- ? `Unsubscribed ${sent}, but some emails could not be deleted`
- : `Sent ${sent}, failed ${failed}`);
- }
- if (remainingCandidates.length) {
- _showUnsubscribeRemainingPrompt(modal, remainingCandidates);
- } else {
- _showUnsubscribeScanFurtherPrompt(
- modal,
- anchor,
- `Finished this batch: ${sent} unsubscribed. Search older emails?`,
- );
- }
- });
- listEl.querySelectorAll('.email-unsub-done-btn').forEach(btn => {
- btn.addEventListener('click', async () => {
- const idx = Number(btn.dataset.idx || 0);
- const c = modal._unsubscribeCandidates?.[idx];
- if (!c) return;
- const sender = c.from_name || c.from_address || 'this sender';
- const ok = await styledConfirm(
- `Delete matching unsubscribe emails from ${sender}?`,
- { confirmText: 'Delete', cancelText: 'Cancel', danger: true },
- );
- if (!ok) return;
- const restoreBusy = _setUnsubButtonBusy(btn, 'Deleting');
- try {
- await _deleteAfterUnsubscribe([c]);
- restoreBusy?.();
- _markUnsubscribeCardDone(modal, idx, 'Deleted');
- showToast?.('Matching emails deleted');
- } catch (err) {
- restoreBusy?.();
- showToast?.(err?.message || 'Could not delete matching emails');
- }
- });
- });
- listEl.querySelectorAll('.email-unsub-ignore-btn').forEach(btn => {
- btn.addEventListener('click', () => {
- const idx = Number(btn.dataset.idx || 0);
- const c = modal._unsubscribeCandidates?.[idx];
- if (!c) return;
- _rememberUnsubscribeIgnored(c);
- btn.closest('.email-unsub-card')?.remove();
- const remaining = listEl.querySelectorAll('.email-unsub-card:not([hidden])').length;
- if (!remaining) {
- listEl.style.display = 'none';
- modal.querySelector('.email-unsub-auto-safe-btn').style.display = 'none';
- finishScanStatus?.('No unsubscribe candidates left in this review.');
- } else {
- finishScanStatus?.(`${remaining} unsubscribe candidate${remaining === 1 ? '' : 's'} still need review.`);
- }
- });
- });
- listEl.querySelectorAll('.email-unsub-agent-btn').forEach(btn => {
- btn.addEventListener('click', () => {
- const idx = Number(btn.dataset.idx || 0);
- const c = modal._unsubscribeCandidates?.[idx];
- if (!c) return;
- if (modal._agentUnsubscribeRun) return;
- const restoreBusy = _setUnsubButtonBusy(btn, 'Starting');
- modal._agentUnsubscribeRun = {
- total: 1,
- candidates: [c],
- completed: new Set(),
- cleanupInFlight: new Set(),
- restoreBusy,
- };
- if (!_askAgentToUnsubscribe(c)) {
- restoreBusy?.();
- modal._agentUnsubscribeRun = null;
- }
- });
- });
- listEl.querySelectorAll('.email-unsub-send-btn').forEach(btn => {
- btn.addEventListener('click', async () => {
- const idx = Number(btn.dataset.idx || 0);
- const c = modal._unsubscribeCandidates?.[idx];
- if (!c) return;
- const ok = await styledConfirm(`Send unsubscribe email to ${_unsubscribeMethodLabel(c.recommended_method)}?`, {
- confirmText: 'Unsubscribe',
- cancelText: 'Cancel',
- });
- if (!ok) return;
- btn.disabled = true;
- btn.textContent = 'Sending…';
- try {
- const r = await fetch(emailApiUrl('/api/email/unsubscribe/execute', {
- account_id: state._libAccountId || undefined,
- }), {
- method: 'POST',
- credentials: 'same-origin',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- uid: c.uid,
- folder: c.folder || state._libFolder || 'INBOX',
- account_id: state._libAccountId || '',
- method_index: 0,
- move_to_spam: false,
- }),
- });
- const d = await r.json().catch(() => ({}));
- if (!d.success) throw new Error(d.error || 'Unsubscribe failed');
- btn.innerHTML = `${_UNSUB_CHECK_ICON}<span>Sent</span>`;
- btn.style.display = 'inline-flex';
- btn.style.alignItems = 'center';
- btn.style.gap = '4px';
- _markUnsubscribeCardDone(modal, idx);
- try {
- await _deleteAfterUnsubscribe([c]);
- showToast('Unsubscribed and deleted email');
- } catch (deleteErr) {
- console.error(deleteErr);
- showToast('Unsubscribed, but email could not be deleted');
- _showUnsubscribeCleanupPrompt(modal, [c], {
- heading: 'The unsubscribe request was sent. Mark this email as spam and delete it?',
- });
- }
- } catch (err) {
- console.error(err);
- btn.disabled = false;
- btn.innerHTML = `${_UNSUB_EMAIL_ICON}<span>${_esc(_unsubscribeMethodLabel(c.recommended_method))}</span>`;
- btn.style.display = 'inline-flex';
- btn.style.alignItems = 'center';
- btn.style.gap = '4px';
- showToast(err?.message || 'Unsubscribe failed');
- }
- });
- });
- } catch (err) {
- console.error(err);
- finishScanError('Failed to scan email headers');
- }
- }
-
- function _rememberedEmailAccountId() {
- try {
- return String(localStorage.getItem(_LIB_LAST_ACCOUNT_KEY) || '').trim();
- } catch (_) {
- return '';
- }
- }
-
- // Per-(account, folder, filter, attachments) cache of the most recent
- // first-page list response. Lets open-after-refresh paint the previous
- // list instantly while the network refresh runs behind it. Search results
- // and __scheduled__ are deliberately not cached.
- const _libListCache = new Map();
- const _LIB_CACHE_MAX = 24;
- const _LIB_INITIAL_PAGE_SIZE = 100;
- const _LIB_SESSION_CACHE_PREFIX = 'odysseus.email.list.';
- const _LIB_SESSION_CACHE_TTL_MS = 10 * 60 * 1000;
- const _LIB_PERSIST_CACHE_PREFIX = 'odysseus.email.list.v2.';
- const _LIB_PERSIST_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
- const _LIB_PERSIST_CACHE_MAX = 12;
- const _LIB_LAST_ACCOUNT_KEY = 'odysseus.email.lastAccountId';
- const _LIB_PREWARM_COOLDOWN_MS = 5 * 60 * 1000;
- let _libPrewarmDelayTimer = null;
- let _libPrewarmIdleHandle = null;
- let _libPrewarmPromise = null;
- let _libPrewarmResolve = null;
- let _libPrewarmAbortController = null;
- let _libPrewarmDetachPriorityListeners = null;
- let _libPrewarmGeneration = 0;
- let _libLastPrewarmAt = 0;
- let _libUnreadPrewarmKey = '';
- let _libUnreadPrewarmAt = 0;
- let _libRenderedViewKey = '';
- let _libSyncStatus = {
- updatedAt: '',
- source: '',
- warming: false,
- loading: false,
- };
- let _libSyncTicker = null;
-
- function _libSyncDateFrom(value) {
- if (!value) return null;
- const d = new Date(value);
- return Number.isFinite(d.getTime()) ? d : null;
- }
-
- function _libRelativeTime(value) {
- const d = _libSyncDateFrom(value);
- if (!d) return '';
- const seconds = Math.max(0, Math.floor((Date.now() - d.getTime()) / 1000));
- if (seconds < 45) return 'just now';
- const minutes = Math.floor(seconds / 60);
- if (minutes < 60) return `${minutes}m ago`;
- const hours = Math.floor(minutes / 60);
- if (hours < 24) return `${hours}h ago`;
- const days = Math.floor(hours / 24);
- return `${days}d ago`;
- }
-
- function _renderEmailSyncStatus() {
- const el = document.getElementById('email-lib-sync-status');
- if (!el) return;
- const parts = [];
- const rel = _libRelativeTime(_libSyncStatus.updatedAt);
- if (rel) parts.push(`Last: ${rel}`);
- if (_libSyncStatus.loading) {
- if (state._libEmails.length) parts.push('Updating...');
- el.textContent = parts.join(' · ');
- el.style.visibility = parts.length ? 'visible' : 'hidden';
- return;
- }
- el.textContent = parts.join(' · ');
- el.style.visibility = parts.length ? 'visible' : 'hidden';
- }
-
- function _setEmailSyncStatus(next = {}) {
- if (Object.prototype.hasOwnProperty.call(next, 'updatedAt')) {
- const updatedAt = next.updatedAt || '';
- if (!updatedAt) {
- _libSyncStatus.updatedAt = _libSyncStatus.updatedAt || '';
- } else if (_libSyncDateFrom(updatedAt)) {
- _libSyncStatus.updatedAt = updatedAt;
- }
- }
- if (Object.prototype.hasOwnProperty.call(next, 'source')) {
- _libSyncStatus.source = next.source || '';
- }
- if (Object.prototype.hasOwnProperty.call(next, 'warming')) {
- _libSyncStatus.warming = Boolean(next.warming);
- }
- if (Object.prototype.hasOwnProperty.call(next, 'loading')) {
- _libSyncStatus.loading = Boolean(next.loading);
- }
- _renderEmailSyncStatus();
- }
-
- function _libCacheKeyFor(accountId, folder, filter, hasAttachments) {
- return [
- accountId || '',
- folder || '',
- filter || '',
- hasAttachments ? 1 : 0,
- state._libDateFrom || '',
- state._libDateTo || '',
- ].join('|');
- }
- function _libCacheKey() {
- return _libCacheKeyFor(
- state._libAccountId || '',
- state._libFolder || '',
- state._libFilter || '',
- state._libHasAttachments
- );
- }
- function _libSessionCacheKey(key) {
- return _LIB_SESSION_CACHE_PREFIX + encodeURIComponent(String(key || ''));
- }
- function _libPersistCacheKey(key) {
- return _LIB_PERSIST_CACHE_PREFIX + encodeURIComponent(String(key || ''));
- }
- function _libSessionCacheGet(key) {
- try {
- const raw = sessionStorage.getItem(_libSessionCacheKey(key));
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (!parsed || !parsed.savedAt || (Date.now() - parsed.savedAt) > _LIB_SESSION_CACHE_TTL_MS) {
- sessionStorage.removeItem(_libSessionCacheKey(key));
- return null;
- }
- return parsed.value || null;
- } catch (_) {
- return null;
- }
- }
- function _libPersistCacheGet(key) {
- try {
- const storageKey = _libPersistCacheKey(key);
- const raw = localStorage.getItem(storageKey);
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (!parsed || !parsed.savedAt || (Date.now() - parsed.savedAt) > _LIB_PERSIST_CACHE_TTL_MS) {
- localStorage.removeItem(storageKey);
- return null;
- }
- return parsed.value || null;
- } catch (_) {
- return null;
- }
- }
- function _libSessionCachePut(key, value) {
- try {
- sessionStorage.setItem(_libSessionCacheKey(key), JSON.stringify({ savedAt: Date.now(), value }));
- } catch (_) {}
- }
- function _libPrunePersistCache() {
- try {
- const entries = [];
- for (let i = 0; i < localStorage.length; i++) {
- const key = localStorage.key(i);
- if (!key || !key.startsWith(_LIB_PERSIST_CACHE_PREFIX)) continue;
- let savedAt = 0;
- try {
- savedAt = Number(JSON.parse(localStorage.getItem(key) || '{}')?.savedAt || 0);
- } catch (_) {}
- entries.push({ key, savedAt });
- }
- entries.sort((a, b) => b.savedAt - a.savedAt);
- for (const stale of entries.slice(_LIB_PERSIST_CACHE_MAX)) {
- localStorage.removeItem(stale.key);
- }
- } catch (_) {}
- }
- function _libPersistCachePut(key, value) {
- try {
- localStorage.setItem(_libPersistCacheKey(key), JSON.stringify({ savedAt: Date.now(), value }));
- _libPrunePersistCache();
- } catch (_) {
- try { localStorage.removeItem(_libPersistCacheKey(key)); } catch {}
- }
- }
- function _looksLikeFixtureEmailRow(row) {
- if (!row || typeof row !== 'object') return false;
- const account = String(row.account || row._account || row.account_id || row._account_id || '').toLowerCase();
- const from = `${row.from || ''} ${row.from_name || ''} ${row.from_address || ''}`.toLowerCase();
- const subject = String(row.subject || '').toLowerCase();
- const messageId = String(row.message_id || '').toLowerCase();
- return account.includes('fixture')
- || from.includes('fixture@example')
- || from.includes('older fixture')
- || subject === 'older inbox message'
- || messageId.includes('fixture-email-');
- }
- function _libCacheHasFixtureRows(value) {
- return Boolean(value && Array.isArray(value.emails) && value.emails.some(_looksLikeFixtureEmailRow));
- }
- function _libDropCacheKey(key) {
- _libListCache.delete(key);
- try { sessionStorage.removeItem(_libSessionCacheKey(key)); } catch (_) {}
- try { localStorage.removeItem(_libPersistCacheKey(key)); } catch (_) {}
- }
- function _libCacheGet(key) {
- const memory = _libListCache.get(key);
- if (memory) {
- if (_libCacheHasFixtureRows(memory)) {
- _libDropCacheKey(key);
- return null;
- }
- return memory;
- }
- const stored = _libSessionCacheGet(key) || _libPersistCacheGet(key);
- if (stored) {
- if (_libCacheHasFixtureRows(stored)) {
- _libDropCacheKey(key);
- return null;
- }
- _libListCache.set(key, stored);
- return stored;
- }
- return null;
- }
- function _libCachePut(key, value) {
- if (_libCacheHasFixtureRows(value)) {
- _libDropCacheKey(key);
- return;
- }
- // Re-insert to bump LRU recency.
- _libListCache.delete(key);
- _libListCache.set(key, value);
- _libSessionCachePut(key, value);
- _libPersistCachePut(key, value);
- if (_libListCache.size > _LIB_CACHE_MAX) {
- const oldest = _libListCache.keys().next().value;
- _libListCache.delete(oldest);
- }
- }
-
- function _resetBulkSelectionForContextChange({ rerender = false } = {}) {
- const hadSelection = !!(state._selectedUids && state._selectedUids.size);
- const wasSelectMode = !!state._selectMode;
- if (state._selectedUids) state._selectedUids.clear();
- state._selectMode = false;
- if (hadSelection || wasSelectMode) {
- _updateBulkBar();
- if (rerender) _renderGrid();
- }
- }
-
- function _resetEmailListForFreshLoad({ useCache = true, refreshAfterCache = false } = {}) {
- _exitEmailReaderModeForList();
- _resetBulkSelectionForContextChange();
- state._libOffset = 0;
- _emailMailboxGeneration += 1;
- _libLoadSeq += 1;
- const ck = _libCacheKey();
- const cached = useCache ? _libCacheGet(ck) : null;
- if (cached && Array.isArray(cached.emails) && cached.emails.length) {
- state._libEmails = cached.emails.slice();
- state._libTotal = cached.total || state._libEmails.length;
- state._libJustOpened = false;
- _renderGrid();
- const stats = document.getElementById('email-lib-stats');
- if (stats) stats.textContent = `${state._libTotal} emails`;
- _setEmailSyncStatus({ updatedAt: cached.sync?.updated_at || '', source: cached.sync?.source || 'client_cache', loading: refreshAfterCache });
- _libRenderedViewKey = ck;
- return;
- }
- if (state._libEmails.length && _libRenderedViewKey === ck) {
- _renderGrid();
- _setEmailSyncStatus({ loading: false });
- return;
- }
- state._libEmails = [];
- state._libTotal = 0;
- _libRenderedViewKey = ck;
- const grid = document.getElementById('email-lib-grid');
- if (grid) _renderEmailLoading(grid);
- const stats = document.getElementById('email-lib-stats');
- if (stats) stats.textContent = 'Loading...';
- _setEmailSyncStatus({ loading: true });
- }
-
- function _exitEmailReaderModeForList() {
- const modal = document.getElementById('email-lib-modal');
- modal?.classList.remove('email-reading');
- modal?.style.removeProperty('--email-reading-modal-min-h');
- const grid = document.getElementById('email-lib-grid');
- grid?.querySelectorAll('.email-card-expanded, .doclib-card-expanded').forEach(card => {
- unbindExpandedCardDismiss(card);
- card.classList.remove('email-card-expanded');
- card.classList.remove('doclib-card-expanded');
- card.style.minHeight = '';
- card.querySelector('.email-card-reader')?.remove();
- });
- }
-
- function _loadEmailsFresh({ force = true, useCache = true, refreshAfterCache = true, showRefreshSpinner = false } = {}) {
- const refreshBtn = showRefreshSpinner ? document.getElementById('email-lib-refresh-btn') : null;
- refreshBtn?.classList.add('email-lib-refreshing');
- const resolvedFolder = _resolveEmailFolderAlias(state._libFolder);
- if (resolvedFolder && resolvedFolder !== state._libFolder) {
- state._libFolder = resolvedFolder;
- const folderSel = document.getElementById('email-lib-folder');
- if (folderSel) folderSel.value = resolvedFolder;
- _renderFolderPicker();
- }
- _resetEmailListForFreshLoad({ useCache, refreshAfterCache });
- return _loadEmails({ force, useCache }).finally(() => {
- refreshBtn?.classList.remove('email-lib-refreshing');
- });
- }
-
- async function _refreshEmailLibraryFromUi(btn = null) {
- btn?.classList.add('email-lib-refreshing');
- state._libOffset = 0;
- // Don't wipe state._libEmails — _loadEmails will paint the current
- // list while the forced refetch runs, so the grid doesn't blank out
- // mid-refresh. `force: true` adds the cache-buster so the server's
- // 8s list cache is bypassed for an actually-fresh result.
- try {
- await _loadEmails({ force: true });
- } finally {
- btn?.classList.remove('email-lib-refreshing');
- // Flash a checkmark for ~900ms so the user gets a clear "done" cue.
- if (btn) {
- const orig = btn.innerHTML;
- btn.classList.add('email-lib-refresh-done');
- btn.innerHTML = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;"><polyline points="20 6 9 17 4 12"/></svg>';
- setTimeout(() => {
- if (btn.classList.contains('email-lib-refresh-done')) {
- btn.classList.remove('email-lib-refresh-done');
- btn.innerHTML = orig;
- }
- }, 900);
- }
- }
- }
-
- // Refresh the currently visible mailbox after another surface sends a message.
- // Keep the user's folder, filters, and scroll context intact.
- export async function refreshEmailLibrary() {
- if (!state._libOpen) return false;
- await _loadEmailsFresh({
- force: true,
- useCache: false,
- refreshAfterCache: false,
- showRefreshSpinner: true,
- });
- return true;
- }
-
- function _initMobileEmailPullRefresh() {
- const grid = document.getElementById('email-lib-grid');
- const modal = document.getElementById('email-lib-modal');
- const host = modal?.querySelector('.admin-card');
- if (!grid || !host || grid.dataset.pullRefreshBound === '1') return;
- if (!('ontouchstart' in window || navigator.maxTouchPoints > 0)) return;
- grid.dataset.pullRefreshBound = '1';
-
- const THRESHOLD = 72;
- const MAX_PULL = 104;
- let startY = 0;
- let pullY = 0;
- let tracking = false;
- let refreshing = false;
-
- const indicator = document.createElement('div');
- indicator.className = 'chat-pull-refresh email-pull-refresh';
- indicator.setAttribute('aria-hidden', 'true');
- indicator.innerHTML = '<div class="chat-pull-refresh-spinner"></div>';
- host.prepend(indicator);
- const spinnerMount = indicator.querySelector('.chat-pull-refresh-spinner');
- try {
- const spinner = spinnerModule.createWhirlpool(18);
- spinnerMount.replaceChildren(spinner.element);
- } catch (_) {}
-
- function setPull(px, active = false) {
- pullY = Math.max(0, Math.min(MAX_PULL, px));
- const pct = Math.min(1, pullY / THRESHOLD);
- indicator.style.setProperty('--pull-refresh-y', `${pullY}px`);
- indicator.style.setProperty('--pull-refresh-progress', `${pct}`);
- indicator.classList.toggle('is-visible', active || refreshing || pullY > 2);
- indicator.classList.toggle('is-ready', pct >= 1 && !refreshing);
- indicator.classList.toggle('is-refreshing', refreshing);
- }
-
- async function runRefresh() {
- if (refreshing) return;
- refreshing = true;
- setPull(THRESHOLD, true);
- try {
- await _refreshEmailLibraryFromUi(document.getElementById('email-lib-refresh-btn'));
- } catch (err) {
- console.warn('email pull refresh failed:', err);
- } finally {
- refreshing = false;
- setPull(0, false);
- }
- }
-
- grid.addEventListener('touchstart', (e) => {
- if (refreshing || window.innerWidth > 768) return;
- if (grid.scrollTop > 0) return;
- if (e.target?.closest?.('button, input, textarea, select, a, .email-card-reader, .doclib-card-expanded')) return;
- tracking = true;
- startY = e.touches[0].clientY;
- setPull(0, false);
- }, { passive: true });
-
- grid.addEventListener('touchmove', (e) => {
- if (!tracking || refreshing) return;
- const dy = e.touches[0].clientY - startY;
- if (dy <= 0) {
- setPull(0, false);
- return;
- }
- if (grid.scrollTop <= 0) {
- e.preventDefault();
- setPull(dy * 0.62, true);
- }
- }, { passive: false });
-
- grid.addEventListener('touchend', () => {
- if (!tracking) return;
- tracking = false;
- if (pullY >= THRESHOLD) runRefresh();
- else setPull(0, false);
- }, { passive: true });
-
- grid.addEventListener('touchcancel', () => {
- tracking = false;
- if (!refreshing) setPull(0, false);
- }, { passive: true });
- }
-
- function _isChatInteractionBusy() {
- try {
- if (window.__odysseusChatBusy) return true;
- const until = Number(window.__odysseusChatBusyUntil || 0);
- return until > Date.now();
- } catch (_) {
- return false;
- }
- }
-
- function _canRunEmailPrewarm() {
- if (state._libOpen || state._libLoading || _libSearchInFlight) return false;
- if (document.visibilityState && document.visibilityState !== 'visible') return false;
- return !_isChatInteractionBusy();
- }
-
- function _isEmailPrewarmTemporarilyBlocked() {
- if (state._libOpen || state._libLoading || _libSearchInFlight) return false;
- if (document.visibilityState && document.visibilityState !== 'visible') return false;
- return _isChatInteractionBusy();
- }
-
- function _isEmailPrewarmCurrent(generation, signal) {
- return generation === _libPrewarmGeneration
- && !signal?.aborted
- && _canRunEmailPrewarm();
- }
-
- function _settleEmailPrewarm(generation, value = false) {
- if (generation !== _libPrewarmGeneration) return;
- const resolve = _libPrewarmResolve;
- const detachPriorityListeners = _libPrewarmDetachPriorityListeners;
- _libPrewarmDelayTimer = null;
- _libPrewarmIdleHandle = null;
- _libPrewarmPromise = null;
- _libPrewarmResolve = null;
- _libPrewarmAbortController = null;
- _libPrewarmDetachPriorityListeners = null;
- detachPriorityListeners?.();
- resolve?.(value);
- }
-
- function _cancelEmailPrewarm() {
- const resolve = _libPrewarmResolve;
- const detachPriorityListeners = _libPrewarmDetachPriorityListeners;
- _libPrewarmGeneration += 1;
- if (_libPrewarmDelayTimer !== null) {
- clearTimeout(_libPrewarmDelayTimer);
- }
- if (_libPrewarmIdleHandle !== null && typeof window.cancelIdleCallback === 'function') {
- try { window.cancelIdleCallback(_libPrewarmIdleHandle); } catch (_) {}
- }
- try { _libPrewarmAbortController?.abort(); } catch (_) {}
- _libPrewarmDelayTimer = null;
- _libPrewarmIdleHandle = null;
- _libPrewarmPromise = null;
- _libPrewarmResolve = null;
- _libPrewarmAbortController = null;
- _libPrewarmDetachPriorityListeners = null;
- detachPriorityListeners?.();
- resolve?.(false);
- }
-
- function _scheduleEmailPrewarm(task, { delay = 0 } = {}) {
- if (_libPrewarmPromise) return _libPrewarmPromise;
- // Do not disguise a timer as idle work. Browsers without the genuine idle
- // callback simply skip this optional optimization and load on demand.
- if (typeof window.requestIdleCallback !== 'function') return Promise.resolve(false);
-
- const generation = ++_libPrewarmGeneration;
- _libPrewarmPromise = new Promise(resolve => { _libPrewarmResolve = resolve; });
- const promise = _libPrewarmPromise;
- let attemptPending = false;
- let retryRequested = false;
-
- function clearScheduledAttempt() {
- if (_libPrewarmDelayTimer !== null) clearTimeout(_libPrewarmDelayTimer);
- if (_libPrewarmIdleHandle !== null && typeof window.cancelIdleCallback === 'function') {
- try { window.cancelIdleCallback(_libPrewarmIdleHandle); } catch (_) {}
- }
- _libPrewarmDelayTimer = null;
- _libPrewarmIdleHandle = null;
- }
-
- function scheduleIdleRetry(delay = 500) {
- if (generation !== _libPrewarmGeneration) return;
- retryRequested = true;
- if (attemptPending || _libPrewarmDelayTimer !== null || _libPrewarmIdleHandle !== null) return;
- if (document.visibilityState && document.visibilityState !== 'visible') return;
- _libPrewarmDelayTimer = setTimeout(requestIdle, Math.max(50, Number(delay) || 500));
- }
-
- function handlePriorityChange() {
- if (generation !== _libPrewarmGeneration) return;
- if (_canRunEmailPrewarm()) {
- scheduleIdleRetry(50);
- return;
- }
-
- const priorityBlocked = _isChatInteractionBusy()
- || (document.visibilityState && document.visibilityState !== 'visible');
- if (!priorityBlocked) return;
-
- retryRequested = true;
- clearScheduledAttempt();
- const controller = _libPrewarmAbortController;
- _libPrewarmAbortController = null;
- try { controller?.abort(); } catch (_) {}
- // A hidden page waits for visibilitychange. Chat priority also retains the
- // timer fallback for busy-until windows whose final transition has no event.
- if (!document.visibilityState || document.visibilityState === 'visible') {
- scheduleIdleRetry();
- }
- }
-
- window.addEventListener('odysseus:chat-busy-change', handlePriorityChange);
- document.addEventListener('visibilitychange', handlePriorityChange);
- _libPrewarmDetachPriorityListeners = () => {
- window.removeEventListener('odysseus:chat-busy-change', handlePriorityChange);
- document.removeEventListener('visibilitychange', handlePriorityChange);
- };
-
- function requestIdle() {
- if (generation !== _libPrewarmGeneration) return;
- _libPrewarmDelayTimer = null;
- try {
- _libPrewarmIdleHandle = window.requestIdleCallback((deadline) => {
- if (generation !== _libPrewarmGeneration) return;
- _libPrewarmIdleHandle = null;
- const hasIdleBudget = Boolean(
- deadline
- && !deadline.didTimeout
- && typeof deadline.timeRemaining === 'function'
- && deadline.timeRemaining() > 0
- );
- if (!_canRunEmailPrewarm()) {
- if (_isEmailPrewarmTemporarilyBlocked()) {
- scheduleIdleRetry();
- } else {
- _settleEmailPrewarm(generation, false);
- }
- return;
- }
- if (!hasIdleBudget) {
- scheduleIdleRetry();
- return;
- }
- if (generation !== _libPrewarmGeneration) {
- _settleEmailPrewarm(generation, false);
- return;
- }
- const controller = new AbortController();
- _libPrewarmAbortController = controller;
- attemptPending = true;
- retryRequested = false;
- Promise.resolve()
- .then(() => task({ signal: controller.signal, generation }))
- .then(value => {
- if (controller !== _libPrewarmAbortController || controller.signal.aborted) return;
- _settleEmailPrewarm(generation, Boolean(value));
- })
- .catch(() => {
- if (controller !== _libPrewarmAbortController || controller.signal.aborted) return;
- _settleEmailPrewarm(generation, false);
- })
- .finally(() => {
- attemptPending = false;
- if (generation !== _libPrewarmGeneration) return;
- if (retryRequested) scheduleIdleRetry();
- });
- });
- } catch (_) {
- _settleEmailPrewarm(generation, false);
- }
- }
-
- const wait = Math.max(0, Number(delay) || 0);
- if (wait > 0) _libPrewarmDelayTimer = setTimeout(requestIdle, wait);
- else requestIdle();
- return promise;
- }
-
- export function prewarmEmailLibrary({ delay = 2500 } = {}) {
- if (_libPrewarmPromise) return _libPrewarmPromise;
- const elapsed = Date.now() - _libLastPrewarmAt;
- if (elapsed >= 0 && elapsed < _LIB_PREWARM_COOLDOWN_MS) return Promise.resolve(false);
- return _scheduleEmailPrewarm(_prewarmEmailViews, { delay });
- }
-
- function _chooseEmailPrewarmAccountId(accounts) {
- const enabled = Array.isArray(accounts) ? accounts.filter(a => a && a.enabled !== false) : [];
- const remembered = _rememberedEmailAccountId();
- const current = String(state._libAccountId || '').trim();
- const chosen = enabled.find(a => String(a.id || '') === remembered)
- || enabled.find(a => String(a.id || '') === current)
- || enabled.find(a => a.is_default)
- || enabled[0]
- || null;
- return String(chosen?.id || '').trim();
- }
-
- async function _ensureEmailAccountsForPrewarm({ signal, generation } = {}) {
- if (!_isEmailPrewarmCurrent(generation, signal)) return null;
- const accountsFresh = _libAccountsLoadedAt && (Date.now() - _libAccountsLoadedAt) < _LIB_ACCOUNTS_TTL_MS;
- if (!(Array.isArray(state._libAccounts) && state._libAccounts.length && accountsFresh)) {
- try {
- const accountsRes = await fetch(`${API_BASE}/api/email/accounts`, {
- credentials: 'same-origin',
- signal,
- });
- if (!_isEmailPrewarmCurrent(generation, signal)) return null;
- if (accountsRes.ok) {
- const accountsData = await accountsRes.json().catch(() => ({}));
- if (!_isEmailPrewarmCurrent(generation, signal)) return null;
- if (Array.isArray(accountsData.accounts)) {
- state._libAccounts = accountsData.accounts;
- _libAccountsLoadedAt = Date.now();
- }
- }
- } catch (err) {
- if (err?.name === 'AbortError') return null;
- }
- }
-
- const accountId = _chooseEmailPrewarmAccountId(state._libAccounts);
- if (!_isEmailPrewarmCurrent(generation, signal)) return null;
- if (!accountId) return null;
- return accountId;
- }
-
- export function prewarmUnreadEmails({ limit = 8, maxUid = 0 } = {}) {
- return _scheduleEmailPrewarm(
- context => _prewarmUnreadEmailsNow({ limit, maxUid }, context),
- { delay: 0 }
- );
- }
-
- async function _prewarmUnreadEmailsNow({ limit = 8, maxUid = 0 } = {}, { signal, generation } = {}) {
- if (!_isEmailPrewarmCurrent(generation, signal)) return false;
- const accountId = await _ensureEmailAccountsForPrewarm({ signal, generation });
- if (accountId === null || !_isEmailPrewarmCurrent(generation, signal)) return false;
- const n = Math.max(1, Math.min(20, Number(limit) || 8));
- const key = `${accountId}|${maxUid || 0}|${n}`;
- if (_libUnreadPrewarmKey === key && (Date.now() - _libUnreadPrewarmAt) < 60 * 1000) return true;
- try {
- const folder = 'INBOX';
- const res = await fetch(emailApiUrl('/api/email/list', {
- folder,
- limit: n,
- offset: 0,
- filter: 'unread',
- account_id: accountId || undefined,
- }), {
- credentials: 'same-origin',
- signal,
- });
- if (!_isEmailPrewarmCurrent(generation, signal) || !res.ok) return false;
- const data = await res.json().catch(() => null);
- if (!_isEmailPrewarmCurrent(generation, signal)) return false;
- if (!data || data.error || !Array.isArray(data.emails) || !data.emails.length) return false;
- const sync = data.sync || {};
- _libCachePut(_libCacheKeyFor(accountId, folder, 'unread', false), {
- emails: data.emails,
- total: data.total || data.emails.length,
- sync,
- });
- _libUnreadPrewarmKey = key;
- _libUnreadPrewarmAt = Date.now();
- return true;
- } catch (_) {
- return false;
- }
- }
-
- async function _prewarmEmailViews({ signal, generation } = {}) {
- if (!_isEmailPrewarmCurrent(generation, signal)) return false;
- _setEmailSyncStatus({ warming: true });
- const folder = 'INBOX';
- const filter = 'all';
- try {
- const accountId = await _ensureEmailAccountsForPrewarm({ signal, generation });
- if (accountId === null || !_isEmailPrewarmCurrent(generation, signal)) return false;
- const ck = _libCacheKeyFor(accountId, folder, filter, false);
- if (_libCacheGet(ck)) {
- _libLastPrewarmAt = Date.now();
- return true;
- }
-
- // One optional first-page request only. Folder metadata, unread state, and
- // other accounts remain demand-driven so startup cannot fan out into IMAP.
- const res = await fetch(emailApiUrl('/api/email/list', {
- folder,
- limit: _LIB_INITIAL_PAGE_SIZE,
- offset: 0,
- filter,
- account_id: accountId || undefined,
- }), {
- credentials: 'same-origin',
- signal,
- });
- if (!_isEmailPrewarmCurrent(generation, signal) || !res.ok) return false;
- const data = await res.json().catch(() => null);
- if (!_isEmailPrewarmCurrent(generation, signal)) return false;
- if (!data || data.error || !Array.isArray(data.emails)) return false;
- const sync = data.sync || {};
- _libCachePut(ck, {
- emails: data.emails,
- total: data.total || 0,
- sync,
- });
- _libLastPrewarmAt = Date.now();
- _setEmailSyncStatus({
- updatedAt: sync.updated_at || new Date().toISOString(),
- source: sync.source || '',
- warming: true,
- });
- return true;
- } catch (_) {
- return false;
- } finally {
- _setEmailSyncStatus({ warming: false });
- }
- }
- function _libCacheWriteBack() {
- // After a local mutation that already updated state._libEmails
- // (delete / archive / bulk), sync the change into the cache so the
- // next reopen doesn't briefly show the pre-mutation state before the
- // refetch wins. Skipped during search (results aren't the real list)
- // and on the scheduled virtual folder.
- if (state._libSearch) return;
- if (state._libFolder === '__scheduled__') return;
- const ck = _libCacheKey();
- if (_libListCache.has(ck)) {
- _libCachePut(ck, {
- emails: state._libEmails.slice(),
- total: state._libTotal,
- sync: {
- updated_at: _libSyncStatus.updatedAt || new Date().toISOString(),
- source: _libSyncStatus.source || 'local',
- },
- });
- }
- }
-
- // Expose the active account id to other modules (document.js uses this when sending).
- // Simple global rather than cross-module import to keep coupling minimal.
- function _publishActiveAccount() {
- try { window.__odysseusActiveEmailAccount = state._libAccountId || null; } catch (_) {}
- try {
- if (state._libAccountId) localStorage.setItem(_LIB_LAST_ACCOUNT_KEY, state._libAccountId);
- } catch (_) {}
- // Publish the active account's own address so reply-all can exclude us from
- // the recipient list. This global was read in emailInbox.js but never set.
- try {
- const accts = state._libAccounts || [];
- const active = accts.find(a => a && a.id === state._libAccountId)
- || accts.find(a => a && a.is_default)
- || accts[0];
- window._myEmailAddress = (active && (active.from_address || active.imap_user)) || '';
- // Also publish every configured address so reply-all can exclude all of
- // the user's own mailboxes, not just the active one (multi-account users
- // were getting their other addresses added to Cc).
- const all = [];
- for (const a of accts) {
- if (a && a.from_address) all.push(a.from_address);
- if (a && a.imap_user) all.push(a.imap_user);
- }
- window._myEmailAddresses = all;
- } catch (_) {}
- }
-
- export function initEmailLibrary(config) {
- state._docModule = config.documentModule;
- const onEmailClick = config.onEmailClick;
- state._onEmailClick = typeof onEmailClick === 'function' ? (options = {}) => {
- const accountId = String(state._libAccountId || '');
- const libraryFolder = String(state._libFolder || 'INBOX');
- const messageFolder = String(options.email?.folder || libraryFolder);
- const mailboxGeneration = _emailMailboxGeneration;
- const mailboxContext = Object.freeze({
- accountId,
- libraryFolder,
- messageFolder,
- mailboxGeneration,
- isCurrent: () => (
- String(state._libAccountId || '') === accountId &&
- String(state._libFolder || 'INBOX') === libraryFolder &&
- _emailMailboxGeneration === mailboxGeneration
- ),
- });
- return onEmailClick({ ...options, mailboxContext });
- } : null;
- }
-
- export function isOpen() { return state._libOpen; }
-
- export async function openEmailFromTool(target, isCurrent = () => true) {
- const response = await fetch(`${API_BASE}/api/email/accounts`, { credentials: 'same-origin' });
- if (!response.ok) throw new Error('Could not load email accounts');
- const data = await response.json();
- const key = String(target.account || '').trim().toLowerCase();
- const matches = (data.accounts || []).filter(account =>
- [account.id, account.from_address, account.imap_user, account.name]
- .some(value => value && String(value).trim().toLowerCase() === key));
- if (matches.length !== 1) throw new Error('Could not uniquely identify the email account');
- if (!/^\d+$/.test(String(target.uid || ''))) throw new Error('Invalid email message ID');
- if (!isCurrent()) return;
- openEmailLibrary({ uid: String(target.uid), folder: target.folder || 'INBOX', account_id: matches[0].id });
- }
-
- export function openEmailLibrary(opts = {}) {
- // Foreground email always wins: cancel a delayed/idle callback and abort the
- // one optional request if it has already started. Generation checks make a
- // non-abortable response harmless if it races this transition.
- _cancelEmailPrewarm();
- // Preserve a valid inbox snapshot while rebuilding the modal. Reader
- // failures and mobile draft transitions can reopen this window before the
- // next list request has completed; clearing the snapshot here made that
- // normal recovery path look like an empty inbox.
- const previousLibraryWasOpen = state._libOpen;
- const previousAccountId = state._libAccountId || '';
- const previousFolder = state._libFolder || 'INBOX';
- const previousFilter = state._libFilter || 'all';
- const previousSearch = state._libSearch || '';
- const previousEmails = Array.isArray(state._libEmails) ? state._libEmails.slice() : [];
-
- // Force-clean any stale DOM state from previous attempts
- const existing = document.getElementById('email-lib-modal');
- if (existing) existing.remove();
- if (state._libEscHandler) {
- document.removeEventListener('keydown', state._libEscHandler, true);
- state._libEscHandler = null;
- }
- if (state._libInnerEscHandler) {
- window.removeEventListener('keydown', state._libInnerEscHandler, true);
- state._libInnerEscHandler = null;
- }
- _emailMailboxGeneration += 1;
- state._libOpen = true;
- // On mobile the sidebar overlays content — close it so the email view isn't
- // opened behind it (same pattern as session-switch/delete).
- if (window.innerWidth <= 768) {
- const _sb = document.getElementById('sidebar');
- if (_sb) _sb.classList.add('hidden');
- const _bd = document.getElementById('sidebar-backdrop');
- if (_bd) _bd.classList.remove('visible');
- // Email was opened last → bring the email windows IN FRONT of any open doc
- // (they alternate: whichever was opened last wins). The doc stays open
- // behind it; reopening the doc flips it back on top.
- document.body.classList.add('email-front');
- }
- state._libOffset = 0;
- state._libSearch = '';
- state._libSearchDraft = '';
- // Reset select-mode on each open so the toolbar Select button
- // never opens already-toggled-on after a previous session.
- state._selectMode = false;
- if (state._selectedUids) state._selectedUids.clear();
- state._libSearchPills = [];
- _libSuggestionCache = null;
- state._libFilter = 'all';
- state._libHasAttachments = false;
- // Animate the very first card render with a domino cascade (same as the
- // sidebar section-domino-in keyframe). Reset by _renderGrid after the
- // animation is queued so subsequent filter/sort re-renders are instant.
- state._libJustOpened = true;
- if (Object.prototype.hasOwnProperty.call(opts, 'account_id')) {
- state._libAccountId = opts.account_id || null;
- _publishActiveAccount();
- } else if (!state._libAccountId) {
- const rememberedAccount = _rememberedEmailAccountId();
- if (rememberedAccount) {
- state._libAccountId = rememberedAccount;
- _publishActiveAccount();
- }
- }
- state._libViewInlineImages = _readEmailInlineImagesPreference();
- if (opts.folder) state._libFolder = opts.folder;
- state._libPendingExpandUid = opts.uid || null;
-
- const sameMailbox = previousLibraryWasOpen
- && previousAccountId === (state._libAccountId || '')
- && previousFolder === (state._libFolder || 'INBOX')
- && previousFilter === 'all'
- && !previousSearch
- && previousEmails.length > 0;
- state._libEmails = sameMailbox ? previousEmails : [];
- state._libTotal = sameMailbox ? Math.max(state._libTotal || 0, previousEmails.length) : 0;
-
- const modal = document.createElement('div');
- modal.className = 'modal';
- modal.id = 'email-lib-modal';
- modal.innerHTML = `
- <div class="modal-content doclib-modal-content" style="width:min(720px, 92vw);background:var(--bg);">
- <div class="modal-header">
- <h4>
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;">
- <rect x="2" y="4" width="20" height="16" rx="2"/>
- <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/>
- </svg>
- <span id="email-lib-title-text">Email</span>
- <span id="email-lib-auto-reply-status-dot" class="email-lib-auto-reply-status-dot" aria-label="Auto Reply active" title="Auto Reply active" style="display:none"></span>
- <span id="email-lib-auto-reply-badge" class="email-lib-auto-reply-badge" role="button" tabindex="0" title="Auto Reply is active" style="display:none">Auto Reply</span>
- <span id="email-lib-unread-badge" class="email-lib-unread-badge" role="button" tabindex="0" title="Show unread emails" style="display:none"></span>
- <span id="email-lib-stats" class="memory-count" style="font-size:0.6em;opacity:0.6;font-weight:normal;margin-left:8px;position:relative;top:-2px"></span>
- </h4>
- <div class="email-lib-header-actions" style="display:flex;align-items:center;gap:8px;">
- <button class="email-settings-header-back" id="email-settings-header-back" type="button" title="Back" aria-label="Back" style="display:none;">
- <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5"/><path d="M12 19l-7-7 7-7"/></svg>
- <span>Back</span>
- </button>
- <button class="close-btn" id="email-lib-close">\u2716</button>
- </div>
- </div>
- <div class="modal-body" style="display:flex;flex-direction:column;gap:10px;overflow:hidden;">
- <div class="admin-card" style="flex:1;flex-direction:column;display:flex;overflow:hidden;">
- <div class="email-accounts-row">
- <div id="email-lib-accounts" style="display:flex;gap:4px;flex:1;min-width:0;"></div>
- <button class="memory-toolbar-btn email-compose-jiggle" id="email-lib-compose-btn">
- <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:-2px;margin-right:3px;"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>
- New
- </button>
- </div>
- <div class="memory-toolbar">
- <div class="memory-category-filters">
- <div class="email-folder-picker" id="email-folder-picker" style="flex:1;min-width:0;position:relative;">
- <select class="memory-sort-select email-folder-select-control" id="email-lib-folder" style="display:none;">
- <option value="INBOX">Inbox</option>
- </select>
- <button type="button" class="email-filter-btn email-folder-btn" id="email-folder-btn" aria-haspopup="listbox" aria-expanded="false">
- <span class="email-filter-current"><span class="email-filter-icon email-folder-current-icon"></span><span class="email-filter-label email-folder-label">Inbox</span></span>
- <svg class="email-filter-caret" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
- </button>
- <div class="email-filter-menu email-folder-menu" id="email-folder-menu" role="listbox" hidden></div>
- </div>
- <!-- Hidden native select kept as the source of truth — all
- existing change handlers still fire via the custom picker
- dispatching 'change' on it. -->
- <select class="memory-sort-select" id="email-lib-filter" style="display:none;">
- <option value="all">All</option>
- <option value="unread">Unread</option>
- <option value="favorites">Favorites</option>
- <option value="undone">Undone</option>
- <option value="reminders">Reminders</option>
- <option value="unanswered">Unanswered</option>
- <option value="pending_30d">Pending · 30d</option>
- <option value="stale_30d">Stale · &gt;30d</option>
- <optgroup label="Tags">
- <option value="tag:urgent">Urgent</option>
- <option value="tag:reply-soon">Reply soon</option>
- <option value="tag:bills">Bills</option>
- <option value="tag:receipt">Receipt</option>
- <option value="tag:travel">Travel</option>
- <option value="tag:spam">Spam</option>
- </optgroup>
- </select>
- <div class="email-filter-picker" id="email-filter-picker" style="flex:1;min-width:0;position:relative;">
- <button type="button" class="email-filter-btn" id="email-filter-btn" aria-haspopup="listbox" aria-expanded="false">
- <span class="email-filter-current"><span class="email-filter-icon"></span><span class="email-filter-label">All</span></span>
- <svg class="email-filter-caret" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
- </button>
- <div class="email-filter-menu" id="email-filter-menu" role="listbox" hidden></div>
- </div>
- <button class="memory-toolbar-btn email-filter-select-btn" id="email-lib-select-btn"><svg class="memory-select-btn-icon" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:3px;"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="3" fill="currentColor" stroke="none"/></svg>Select</button>
- <button class="memory-toolbar-btn email-filter-refresh-btn" id="email-lib-refresh-btn" title="Refresh">
- <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;"><path d="M1 4v6h6"/><path d="M23 20v-6h-6"/><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/></svg>
- </button>
- <button class="memory-toolbar-btn email-filter-settings-btn" id="email-lib-settings-btn" title="Email settings" aria-label="Email settings" aria-expanded="false">
- ${_EMAIL_SETTINGS_ICON}
- </button>
- <button class="memory-toolbar-btn email-reminders-clear-btn hidden" id="email-reminders-clear-btn" title="Permanently delete Odysseus reminder emails">
- <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;"><path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6l-1 14H6L5 6"/></svg>
- Clear
- </button>
- </div>
- <div class="email-search-row" style="display:flex;gap:6px;align-items:flex-start;">
- <div class="email-search-wrap" style="position:relative;flex:1;min-width:140px;">
- <div class="email-lib-chip-bar memory-search-input" id="email-lib-chip-bar" style="width:100%;padding-right:36px;padding-left:26px;display:flex;align-items:center;flex-wrap:nowrap;gap:4px;cursor:text;min-height:30px;position:relative;">
- <svg class="email-lib-chip-bar-icon" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="position:absolute;left:8px;top:50%;transform:translateY(-50%);pointer-events:none;color:var(--accent, var(--red));"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35"/></svg>
- <span id="email-lib-pills" style="display:flex;align-items:center;gap:4px;min-width:0;max-width:calc(100% - 70px);overflow-x:auto;overflow-y:hidden;scrollbar-width:none;flex:0 1 auto;"></span>
- <input type="text" id="email-lib-search" placeholder="Search by name or text" autocomplete="off" style="flex:1;min-width:80px;border:0;outline:none;background:transparent;color:inherit;font:inherit;padding:0;position:relative;top:-1px;" />
- <button type="button" class="memory-toolbar-btn email-search-options-btn" id="email-search-options-btn" title="Search options" aria-label="Search options" aria-expanded="false">
- <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><circle cx="5" cy="12" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="19" cy="12" r="2"/></svg>
- </button>
- </div>
- <div id="email-lib-suggest" style="display:none;position:absolute;top:calc(100% + 2px);left:0;right:0;z-index:60;background:var(--panel,var(--bg));border:1px solid var(--border);border-radius:6px;box-shadow:0 6px 18px rgba(0,0,0,0.25);max-height:240px;overflow-y:auto;"></div>
- <div class="email-search-options-menu" id="email-search-options-menu" hidden>
- <div class="email-search-options-title">Filter by...</div>
- <button type="button" class="dropdown-item-compact" data-email-search-option="undone"><span class="dropdown-icon email-search-option-icon"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></span><span>Not done</span></button>
- <button type="button" class="dropdown-item-compact hidden" data-email-search-option="reminders"><span class="dropdown-icon email-search-option-icon"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.268 21a2 2 0 0 0 3.464 0"/><path d="M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"/></svg></span><span>Reminders</span></button>
- <button type="button" class="dropdown-item-compact" data-email-search-option="attachments"><span class="dropdown-icon email-search-option-icon"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 17.93 8.8l-8.59 8.57a2 2 0 0 1-2.83 2.83l8.49-8.48"/></svg></span><span>Attachments</span></button>
- <button type="button" class="dropdown-item-compact" data-email-search-option="date"><span class="dropdown-icon email-search-option-icon"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="17" rx="2"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg></span><span>Date range</span></button>
- <div class="email-search-date-panel" hidden>
- <label><span>From</span><input type="date" id="email-search-date-from"></label>
- <label><span>To</span><input type="date" id="email-search-date-to"></label>
- <div class="email-search-date-actions"><button type="button" data-email-date-clear>Clear</button><button type="button" data-email-date-apply>Apply</button></div>
- </div>
- </div>
- </div>
- </div>
- </div>
- <div id="email-lib-bulk" class="memory-bulk-bar hidden" style="margin-bottom:5px;">
- <label class="memory-bulk-check-all" style="position:relative;top:0px;" title="Select all emails currently loaded in this view"><input type="checkbox" id="email-lib-select-all"> All in view</label>
- <span id="email-lib-selected-count" style="position:relative;top:1px;">0 Selected</span>
- <button class="memory-toolbar-btn" id="email-lib-bulk-actions" style="position:relative;top:-2px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>Actions <span style="opacity:0.55;font-size:9px;">▼</span></button>
- <button class="memory-toolbar-btn" id="email-lib-bulk-delete" style="position:relative;top:-2px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>Delete</button>
- <button class="memory-toolbar-btn" id="email-lib-bulk-cancel" title="Cancel (Esc)" style="margin-left:4px;padding:3px 6px;position:relative;top:-2px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
- </div>
- <div id="email-lib-grid" class="doclib-grid"></div>
- <div id="email-lib-sync-status" class="email-lib-sync-status" aria-live="polite"></div>
- <div id="email-lib-settings-page" class="email-settings-page" hidden></div>
- <button class="email-lib-fab" id="email-lib-fab" type="button" aria-label="New email">
- <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="4.5" width="19" height="15" rx="2.5"/><path d="M3 6.5l9 6 9-6"/></svg>
- <span class="email-lib-fab-label">New</span>
- </button>
- </div>
- </div>
- </div>
- `;
-
- document.body.appendChild(modal);
- modal.style.display = 'block';
- _syncEmailAutoReplyTitle(!!state._libAutoReplyActive);
- _refreshUnreadBadge({ syncAutoReplyTitle: true }).catch(() => {});
- document.getElementById('email-lib-grid')?.scrollTo(0, 0);
- modal.querySelector('.email-settings-body')?.scrollTo(0, 0);
- _renderEmailSyncStatus();
- if (_libSyncTicker) clearInterval(_libSyncTicker);
- _libSyncTicker = setInterval(_renderEmailSyncStatus, 30000);
- // Make modal background non-blocking so user can interact with rest of the app
- modal.style.cssText += 'pointer-events:none;background:transparent;';
-
- // Register so the chip carries the right label/icon. restoreFn left
- // empty — just unminimizing the modal is enough; whatever email was
- // expanded inside stays expanded.
- try {
- Modals.register('email-lib-modal', {
- label: 'Email',
- icon: 'M2 4h20v16H2zM22 7l-9.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7',
- closeFn: () => {
- const m = document.getElementById('email-lib-modal');
- if (m) m.classList.add('hidden');
- },
- restoreFn: () => {
- // Reopened last → bring the email windows in front of any open doc.
- document.body.classList.add('email-front');
- // Mobile: tapping the library chip chips down any open email
- // reader so the library is the only visible window. Pairs with
- // the per-reader restoreFn that chips the library down when a
- // reader is brought up.
- if (window.innerWidth <= 768) {
- document.querySelectorAll('.modal[id^="email-reader-"]').forEach(other => {
- try {
- if (Modals.isRegistered(other.id) && !Modals.isMinimized(other.id)) {
- Modals.minimize(other.id);
- }
- } catch {}
- });
- }
- },
- });
- } catch (_) {}
- _wireUnreadTabClick();
- const unreadBadge = document.getElementById('email-lib-unread-badge');
- unreadBadge?.addEventListener('click', (e) => {
- e.stopPropagation();
- if (unreadBadge.dataset.mode === 'away') {
- _openGlobalEmailSettings('auto-reply');
- return;
- }
- _toggleUnreadEmails();
- });
- unreadBadge?.addEventListener('keydown', (e) => {
- if (e.key !== 'Enter' && e.key !== ' ') return;
- e.preventDefault();
- if (unreadBadge.dataset.mode === 'away') {
- _openGlobalEmailSettings('auto-reply');
- return;
- }
- _toggleUnreadEmails();
- });
- const autoReplyBadge = document.getElementById('email-lib-auto-reply-badge');
- const openAutoReplySettings = (e) => {
- e.stopPropagation();
- _openGlobalEmailSettings('auto-reply');
- };
- autoReplyBadge?.addEventListener('click', openAutoReplySettings);
- autoReplyBadge?.addEventListener('keydown', (e) => {
- if (e.key !== 'Enter' && e.key !== ' ') return;
- e.preventDefault();
- openAutoReplySettings(e);
- });
- const content = modal.querySelector('.modal-content');
- if (content) {
- const isMobile = window.innerWidth <= 768;
- if (isMobile) {
- // Bottom-anchored sheet on mobile
- content.style.position = 'fixed';
- content.style.pointerEvents = 'auto';
- content.style.left = '0';
- content.style.right = '0';
- content.style.bottom = '0';
- content.style.top = 'auto';
- content.style.transform = 'none';
- } else {
- // Center on screen using fixed positioning + computed offsets
- content.style.position = 'fixed';
- content.style.pointerEvents = 'auto';
- // Wait a frame for size to stabilize, then center. Center against the
- // modal's max-height (85vh) — NOT the live offsetHeight, which is tiny
- // while the email list is still loading and put the window ~1/3 down
- // (then it grew off the bottom as the list filled in).
- requestAnimationFrame(() => {
- const w = content.offsetWidth;
- const refH = window.innerHeight * 0.85;
- content.style.left = Math.max(20, (window.innerWidth - w) / 2) + 'px';
- content.style.top = Math.max(20, (window.innerHeight - refH) / 2) + 'px';
- content.style.transform = 'none';
- });
- }
- }
-
- // Wire events
- document.getElementById('email-lib-close').addEventListener('click', closeEmailLibrary);
- document.getElementById('email-settings-header-back')?.addEventListener('click', _hideEmailSettingsPage);
-
- // Clicking the modal header (anywhere except buttons/inputs) collapses
- // any currently-expanded email card and returns to the inbox list view.
- // Acts as a "back to email menu" gesture.
- const libHeader = modal.querySelector('.modal-header');
- if (libHeader) {
- libHeader.style.cursor = 'pointer';
- libHeader.addEventListener('click', (ev) => {
- if (ev.target.closest('button, input, select, a')) return;
- const g = document.getElementById('email-lib-grid');
- if (!g) return;
- g.querySelectorAll('.doclib-card.doclib-card-expanded').forEach(c => {
- const uid = c.dataset.uid;
- const liveEm = state._libEmails.find(e => String(e.uid) === String(uid));
- if (liveEm) _toggleCardPreview(c, liveEm);
- });
- });
- }
-
- // Drag-to-top edge → snap to fullscreen (Aero Snap). Dragging away from
- // the top edge while fullscreen unsnaps back to a centered window.
- _makeDraggable(content, modal, 'email-lib-fullscreen');
-
- document.getElementById('email-lib-folder').addEventListener('change', (e) => {
- state._libFolder = _resolveEmailFolderAlias(e.target.value);
- if (e.target.value !== state._libFolder) e.target.value = state._libFolder;
- _renderFolderPicker();
- _renderSearchPills();
- _loadEmailsFresh();
- });
- document.getElementById('email-lib-filter').addEventListener('change', (e) => {
- state._libFilter = e.target.value;
- _syncUnreadWindowGlow();
- _syncReminderClearButton();
- _renderSearchPills();
- _loadEmailsFresh();
- _syncSearchOptionsMenu();
- // Mirror the picker label/icon.
- _renderFilterPickerCurrent();
- });
- _initFilterPicker();
- _initFolderPicker();
- const searchOptionsBtn = document.getElementById('email-search-options-btn');
- const searchOptionsMenu = document.getElementById('email-search-options-menu');
- searchOptionsBtn?.addEventListener('click', (ev) => {
- ev.preventDefault();
- ev.stopPropagation();
- const shouldOpen = !!searchOptionsMenu?.hidden;
- if (searchOptionsMenu) searchOptionsMenu.hidden = !shouldOpen;
- searchOptionsBtn.setAttribute('aria-expanded', String(shouldOpen));
- _syncSearchOptionsMenu();
- });
- searchOptionsMenu?.addEventListener('click', (ev) => {
- const item = ev.target.closest('[data-email-search-option]');
- if (!item) return;
- ev.preventDefault();
- ev.stopPropagation();
- const opt = item.dataset.emailSearchOption;
- if (opt === 'attachments') _toggleEmailAttachmentFilter();
- else if (opt === 'undone' || opt === 'reminders') _setEmailListFilter(opt);
- else if (opt === 'date') {
- const panel = searchOptionsMenu.querySelector('.email-search-date-panel');
- panel.hidden = !panel.hidden;
- const from = panel.querySelector('#email-search-date-from');
- const to = panel.querySelector('#email-search-date-to');
- if (from) from.value = state._libDateFrom || '';
- if (to) to.value = state._libDateTo || '';
- }
- searchOptionsMenu.hidden = false;
- searchOptionsBtn?.setAttribute('aria-expanded', 'true');
- });
- searchOptionsMenu?.querySelector('[data-email-date-apply]')?.addEventListener('click', (ev) => {
- ev.preventDefault(); ev.stopPropagation();
- const nextFrom = searchOptionsMenu.querySelector('#email-search-date-from')?.value || '';
- const nextTo = searchOptionsMenu.querySelector('#email-search-date-to')?.value || '';
- if (nextFrom && nextTo && nextFrom > nextTo) {
- showToast('From date must be before To date');
- return;
- }
- state._libDateFrom = nextFrom;
- state._libDateTo = nextTo;
- _syncSearchOptionsMenu();
- _renderSearchPills();
- _loadEmailsFresh({ useCache: false });
- searchOptionsMenu.querySelector('.email-search-date-panel').hidden = true;
- });
- searchOptionsMenu?.querySelector('[data-email-date-clear]')?.addEventListener('click', (ev) => {
- ev.preventDefault(); ev.stopPropagation();
- state._libDateFrom = '';
- state._libDateTo = '';
- _syncSearchOptionsMenu();
- _renderSearchPills();
- _loadEmailsFresh({ useCache: false });
- searchOptionsMenu.querySelector('.email-search-date-panel').hidden = true;
- });
- if (state._emailSearchOptionsDismiss) {
- document.removeEventListener('click', state._emailSearchOptionsDismiss);
- }
- state._emailSearchOptionsDismiss = (ev) => {
- if (!searchOptionsMenu || searchOptionsMenu.hidden) return;
- if (ev.target.closest('#email-search-options-menu, #email-search-options-btn')) return;
- searchOptionsMenu.hidden = true;
- searchOptionsBtn?.setAttribute('aria-expanded', 'false');
- };
- document.addEventListener('click', state._emailSearchOptionsDismiss);
- _syncSearchOptionsMenu();
- document.getElementById('email-reminders-clear-btn')?.addEventListener('click', async () => {
- const ok = await styledConfirm('Permanently delete all Odysseus reminder emails?', {
- confirmText: 'Delete',
- cancelText: 'Cancel',
- danger: true,
- });
- if (!ok) return;
- try {
- const res = await fetch(`${API_BASE}/api/email/odysseus/reminders?permanent=1${_acct()}`, {
- method: 'DELETE',
- credentials: 'same-origin',
- });
- const data = await res.json().catch(() => ({}));
- showToast(`Deleted ${data.deleted || 0} reminder email${(data.deleted || 0) === 1 ? '' : 's'}`);
- if ((data.deleted || 0) > 0) {
- const visibleUids = Array.from(document.querySelectorAll('#email-lib-grid .doclib-card[data-uid]'))
- .map(card => card.dataset.uid)
- .filter(Boolean);
- await _animateEmailCardRemoval(visibleUids);
- }
- state._libFilter = 'all';
- const filterEl = document.getElementById('email-lib-filter');
- if (filterEl) filterEl.value = 'all';
- _renderFilterPickerCurrent();
- _syncSearchOptionsMenu();
- _syncReminderClearButton();
- _renderSearchPills();
- _loadEmailsFresh();
- } catch (err) {
- console.error(err);
- showToast('Failed to clear reminder emails');
- }
- });
- // The old "sort" dropdown (Latest / Unread first / Favorites first) was merged
- // into the filter dropdown above — "Favorites" is now a filter (server-side
- // \Flagged search). _libSort stays at its 'recent' default so the grid keeps
- // the API's newest-first order.
-
- // Chip-bar search: pills represent contact + free-text filters; the live
- // input below drives the autocomplete dropdown. Old behavior — instant
- // local filter on every keystroke + server-side IMAP search after 350ms
- // — is replaced by deterministic local filtering against the snapshot.
- _initEmailSearchChipBar();
-
- document.getElementById('email-lib-refresh-btn').addEventListener('click', async () => {
- await _refreshEmailLibraryFromUi(document.getElementById('email-lib-refresh-btn'));
- });
- _initMobileEmailPullRefresh();
- document.getElementById('email-lib-settings-btn')?.addEventListener('click', (ev) => {
- ev.preventDefault();
- ev.stopPropagation();
- _openGlobalEmailSettings('show-tags');
- });
-
-
- const _composeNew = () => {
- // Desktop: keep Email open when there is enough room for it plus the
- // compose/document pane. Mobile still tabs down so the doc owns the screen.
- if (_prepareEmailWindowForDocument(document.getElementById('email-lib-modal'))) {
- if (!Modals.minimize('email-lib-modal')) closeEmailLibrary();
- }
- if (state._onEmailClick) state._onEmailClick({ compose: true });
- if (document.body.classList.contains('email-doc-split-active')) {
- _scheduleEmailDocumentSplitMeasure(document.getElementById('email-lib-modal'));
- }
- };
- document.getElementById('email-lib-compose-btn').addEventListener('click', _composeNew);
-
- // Mobile FAB: same action as the (desktop) New button, plus collapse-to-icon
- // while the list scrolls and spring back out to "New" when scrolling stops.
- const _fab = document.getElementById('email-lib-fab');
- if (_fab) {
- _fab.addEventListener('click', _composeNew);
- const _grid = document.getElementById('email-lib-grid');
- if (_grid) {
- let _fabIdle = null;
- _grid.addEventListener('scroll', () => {
- _fab.classList.add('collapsed');
- clearTimeout(_fabIdle);
- _fabIdle = setTimeout(() => _fab.classList.remove('collapsed'), 280);
- _positionFab(); // Firefox's toolbar shows/hides on scroll
- }, { passive: true });
- }
-
- // Keep the FAB above the browser's bottom toolbar. env(safe-area-inset)
- // doesn't cover Firefox-for-Android's URL bar, and its 100dvh handling is
- // unreliable, so measure how far the panel extends below the *visible*
- // (visualViewport) area and lift the button by that much.
- function _positionFab() {
- if (!_fab.isConnected) { // modal was rebuilt/closed — stop listening
- window.visualViewport?.removeEventListener('resize', _positionFab);
- window.visualViewport?.removeEventListener('scroll', _positionFab);
- window.removeEventListener('resize', _positionFab);
- return;
- }
- const card = _fab.parentElement; // .admin-card (positioned)
- const vh = window.visualViewport ? window.visualViewport.height : window.innerHeight;
- const overflowBelow = card ? Math.max(0, Math.round(card.getBoundingClientRect().bottom - vh)) : 0;
- _fab.style.bottom = `calc(18px + env(safe-area-inset-bottom, 0px) + ${overflowBelow}px)`;
- }
- if (window.visualViewport) {
- window.visualViewport.addEventListener('resize', _positionFab);
- window.visualViewport.addEventListener('scroll', _positionFab);
- }
- window.addEventListener('resize', _positionFab);
- // Run after layout settles (modal opens with an animation).
- requestAnimationFrame(() => requestAnimationFrame(_positionFab));
- setTimeout(_positionFab, 300);
-
- // Reveal the FAB with a scale-from-center pop only AFTER the email list has
- // rendered (the window is "fully loaded") — position it first while it's
- // still invisible so it never flashes at the top and slides down.
- let _revealed = false;
- const _revealFab = () => {
- if (_revealed || !_fab.isConnected) return;
- _revealed = true;
- _positionFab();
- // The FAB is an absolute child of .modal-content, which slides up on open
- // (sheet-enter). Wait until that entrance finishes before popping the FAB
- // in, otherwise it rides the slide ("swipes down with the window").
- const content = _fab.closest('.modal-content');
- const pop = () => { _positionFab(); requestAnimationFrame(() => _fab.classList.add('fab-revealed')); };
- if (!content || content.classList.contains('sheet-ready')) {
- pop();
- } else {
- let done = false;
- const onEnd = () => {
- if (done) return; done = true;
- content.removeEventListener('animationend', onEnd);
- pop();
- };
- content.addEventListener('animationend', onEnd);
- setTimeout(onEnd, 450); // fallback if animationend doesn't fire
- }
- };
- if (_grid) {
- if (_grid.children.length) {
- _revealFab();
- } else {
- const _gobs = new MutationObserver(() => {
- if (_grid.children.length) { _gobs.disconnect(); _revealFab(); }
- });
- _gobs.observe(_grid, { childList: true });
- // Safety net — never leave the FAB hidden if the list stays empty.
- setTimeout(() => { _gobs.disconnect(); _revealFab(); }, 1600);
- }
- } else {
- setTimeout(_revealFab, 400);
- }
- }
-
- // Select mode toggle — icon + label swap matches the brain memories
- // select button (dot+Select ↔ X+Cancel).
- const _SELECT_BTN_DOT_SVG = '<svg class="memory-select-btn-icon" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:3px;"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="3" fill="currentColor" stroke="none"/></svg>';
- const _SELECT_BTN_X_SVG = '<svg class="memory-select-btn-icon" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" style="vertical-align:-2px;margin-right:3px;"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
- const _setSelectBtnState = (on) => {
- const btn = document.getElementById('email-lib-select-btn');
- if (!btn) return;
- if (on) { btn.classList.add('active'); btn.innerHTML = _SELECT_BTN_X_SVG + 'Cancel'; }
- else { btn.classList.remove('active'); btn.innerHTML = _SELECT_BTN_DOT_SVG + 'Select'; }
- };
- document.getElementById('email-lib-select-btn').addEventListener('click', () => {
- state._selectMode = !state._selectMode;
- state._selectedUids.clear();
- _setSelectBtnState(state._selectMode);
- _updateBulkBar();
- _renderGrid();
- });
- document.getElementById('email-lib-select-all').addEventListener('change', (e) => {
- if (e.target.checked) {
- state._libEmails.forEach(em => state._selectedUids.add(em.uid));
- } else {
- state._selectedUids.clear();
- }
- _updateBulkBar();
- _renderGrid();
- });
-
- // Bulk cancel — wired with the same teardown a fresh Cancel-via-toggle does.
- // Lets the global Esc handler (keyboard-shortcuts.js) close select mode by
- // clicking the visible [id$="-bulk-cancel"] button.
- document.getElementById('email-lib-bulk-cancel')?.addEventListener('click', () => {
- state._selectMode = false;
- state._selectedUids.clear();
- _setSelectBtnState(false);
- _updateBulkBar();
- _renderGrid();
- });
-
- // Bulk actions
- document.getElementById('email-lib-bulk-actions').addEventListener('click', (e) => {
- e.stopPropagation();
- if (state._selectedUids.size === 0) {
- showToast('Select emails first');
- return;
- }
- _showBulkActionsMenu(e.currentTarget);
- });
- document.getElementById('email-lib-bulk-delete')?.addEventListener('click', (e) => {
- e.stopPropagation();
- if (state._selectedUids.size === 0) {
- showToast('Select emails first');
- return;
- }
- _bulkAction('delete');
- });
-
- const selectExpandedEmailText = () => {
- const expanded = document.querySelector('#email-lib-modal .doclib-card.doclib-card-expanded');
- const reader = expanded?.querySelector('.email-card-reader') || expanded;
- return _selectEmailReaderContents(reader);
- };
-
- // ESC to close + Arrow nav + Delete on the selected / currently-expanded email.
- state._libEscHandler = (e) => {
- const modal = document.getElementById('email-lib-modal');
- if (!modal || modal.classList.contains('hidden')) return;
- if ((e.ctrlKey || e.metaKey) && String(e.key || '').toLowerCase() === 'a') {
- const t = e.target;
- if (_isEmailTypingTarget(t)) return;
- if (selectExpandedEmailText()) {
- e.preventDefault();
- e.stopPropagation();
- e.stopImmediatePropagation?.();
- }
- return;
- }
- if (e.key === 'Escape') {
- e.preventDefault();
- e.stopPropagation();
- e.stopImmediatePropagation?.();
- if (modal.classList.contains('email-settings-mode')) {
- _hideEmailSettingsPage();
- return;
- }
- if (state._selectMode) {
- state._selectMode = false;
- state._selectedUids.clear();
- _setSelectBtnState(false);
- _updateBulkBar();
- _renderGrid();
- return;
- }
- const expanded = modal.querySelector('.doclib-card.doclib-card-expanded');
- if (expanded) {
- _exitEmailReaderModeForList();
- expanded.focus?.({ preventScroll: true });
- return;
- }
- if (modal.classList.contains('email-reading')) {
- _exitEmailReaderModeForList();
- return;
- }
- closeEmailLibrary();
- return;
- }
- // Don't hijack arrows / delete while the user is typing somewhere.
- const t = e.target;
- if (_isEmailTypingTarget(t)) return;
- const isDeleteKey = e.key === 'Delete' || e.key === 'Backspace';
- if (isDeleteKey && state._selectMode && state._selectedUids.size > 0) {
- e.preventDefault();
- _bulkAction('delete');
- return;
- }
- const expanded = document.querySelector('#email-lib-modal .doclib-card.doclib-card-expanded');
- if (!expanded) return;
- if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
- const dir = e.key === 'ArrowLeft' ? '-1' : '1';
- const btn = expanded.querySelector(`.email-card-nav-btn[data-nav-dir="${dir}"]`);
- if (btn) { e.preventDefault(); btn.click(); }
- } else if (isDeleteKey) {
- const em = state._libEmails.find(x => String(x.uid) === String(expanded.dataset.uid));
- if (em) {
- e.preventDefault();
- _deleteEmailAndAdvance(em, expanded);
- }
- }
- };
- document.addEventListener('keydown', state._libEscHandler, true);
-
- // The global UI Escape arbiter is a document-level capture listener and can
- // close the hovered modal before this library handler sees the event. Give
- // email's inner layers a window-level first pass so Escape closes exactly
- // one inner state before the library itself is dismissed.
- state._libInnerEscHandler = (e) => {
- if (e.key !== 'Escape') return;
- const modal = document.getElementById('email-lib-modal');
- if (!modal || modal.classList.contains('hidden')) return;
- if (dismissTopMenu()) {
- e.preventDefault();
- e.stopPropagation();
- e.stopImmediatePropagation?.();
- return;
- }
- if (modal.classList.contains('email-settings-mode')) {
- e.preventDefault();
- e.stopPropagation();
- e.stopImmediatePropagation?.();
- _hideEmailSettingsPage();
- return;
- }
- if (state._selectMode) {
- e.preventDefault();
- e.stopPropagation();
- e.stopImmediatePropagation?.();
- state._selectMode = false;
- state._selectedUids.clear();
- _setSelectBtnState(false);
- _updateBulkBar();
- _renderGrid();
- return;
- }
- const expanded = modal.querySelector('.doclib-card.doclib-card-expanded');
- if (expanded || modal.classList.contains('email-reading')) {
- e.preventDefault();
- e.stopPropagation();
- e.stopImmediatePropagation?.();
- _exitEmailReaderModeForList();
- }
- };
- window.addEventListener('keydown', state._libInnerEscHandler, true);
-
- const grid = document.getElementById('email-lib-grid');
- if (grid && !grid.children.length) _renderEmailLoading(grid);
- if (Array.isArray(state._libAccounts) && state._libAccounts.length) {
- _renderAccountsStrip();
- } else {
- _renderAccountsLoading();
- }
- const fastAccountAtOpen = state._libAccountId || '';
- if (fastAccountAtOpen) {
- _loadEmails({ useCache: true });
- }
- // If we already know the previous/default account, paint that inbox first
- // from the durable index and validate accounts in parallel. Cold refreshes
- // otherwise waited on `/accounts` before even trying the cheap indexed list.
- (async () => {
- await _loadAccounts();
- _refreshUnreadBadge().catch(() => {});
- _loadFolders();
- _loadEmailReminderBellVisibility();
- if (!fastAccountAtOpen || fastAccountAtOpen !== (state._libAccountId || '')) {
- _loadEmails({ useCache: true });
- }
- })();
- }
-
- async function _loadAccounts({ force = false } = {}) {
- const hasCachedAccounts = Array.isArray(state._libAccounts) && state._libAccounts.length;
- const accountsFresh = _libAccountsLoadedAt && (Date.now() - _libAccountsLoadedAt) < _LIB_ACCOUNTS_TTL_MS;
- if (!force && hasCachedAccounts && accountsFresh) {
- if (!state._libAccountId) {
- const def = state._libAccounts.find(a => a.is_default) || state._libAccounts[0];
- state._libAccountId = def?.id || null;
- _publishActiveAccount();
- }
- state._libViewInlineImages = _readEmailInlineImagesPreference();
- _renderAccountsStrip();
- return;
- }
- try {
- const r = await fetch(`${API_BASE}/api/email/accounts`, { credentials: 'same-origin' });
- if (!r.ok) return;
- const d = await r.json();
- state._libAccounts = d.accounts || [];
- _libAccountsLoadedAt = Date.now();
- } catch (_) {
- if (!hasCachedAccounts) state._libAccounts = [];
- }
- // The 'Default' chip is gone — pick an explicit account so the email
- // list and any per-email actions (open in new tab, mark read, etc.)
- // always carry an account_id and can't desync from the server's
- // is_default state.
- if (state._libAccountId && state._libAccounts.length && !state._libAccounts.some(a => a && a.id === state._libAccountId)) {
- state._libAccountId = null;
- }
- if (!state._libAccountId && state._libAccounts.length) {
- const def = state._libAccounts.find(a => a.is_default) || state._libAccounts[0];
- state._libAccountId = def.id;
- _publishActiveAccount();
- }
- state._libViewInlineImages = _readEmailInlineImagesPreference();
- _renderAccountsStrip();
- _refreshAccountUnreadHighlights().catch(() => {});
- }
-
- function _renderAccountsStrip() {
- const strip = document.getElementById('email-lib-accounts');
- if (!strip) return;
- strip.style.display = 'flex';
- const esc = s => String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
- // The 'Default' chip caused desync bugs (changing the server-side
- // default via the dot while still on the cached 'default' view would
- // open the wrong account's emails). Each account renders as its own
- // chip; the active one is selected explicitly via _loadAccounts.
- let html = '';
- // Keep the server default first; unread status remains the only dot on a
- // mailbox chip, while the explicit default control lives in Settings.
- const accounts = (state._libAccounts || []).slice().sort((a, b) => Number(!!b.is_default) - Number(!!a.is_default));
- const nameCounts = new Map();
- accounts.forEach(a => {
- const name = String(a.name || '').trim();
- if (name) nameCounts.set(name, (nameCounts.get(name) || 0) + 1);
- });
- for (const a of accounts) {
- const active = state._libAccountId === a.id ? ' active' : '';
- const accountAddress = a.from_address || a.imap_user || '';
- const accountName = String(a.name || '').trim();
- const accountLabel = accountName && nameCounts.get(accountName) > 1 && accountAddress
- ? `${accountName} · ${accountAddress}`
- : (accountName || accountAddress || 'account');
- const unread = _accountUnreadState.get(String(a.id || '')) || {};
- const unreadCount = Number(unread.unreadCount || 0);
- const unreadClass = unreadCount > 0 ? ' email-account-has-unread' : '';
- const unreadTitle = unreadCount > 0 ? ` · ${unreadCount > 999 ? '999+' : unreadCount} unread` : '';
- const away = state._libAutoReplyActive && state._libAccountId === a.id;
- const label = away ? (accountAddress || accountLabel) : accountLabel;
- const awayLabel = away ? '<span class="email-account-away-label">(AWAY)</span>' : '';
- const unreadDot = unreadCount > 0
- ? `<span class="email-account-unread-dot" aria-hidden="true"></span>`
- : '';
- html += `<span class="gallery-chip-wrap" style="position:relative;display:inline-flex;align-items:center;">`
- + `<button class="memory-toolbar-btn gallery-chip email-account-chip${active}${unreadClass}" data-acc-id="${esc(a.id)}" title="${esc(a.from_address || a.imap_user || '')}${away ? ' · auto reply active' : ''}${unreadTitle}" style="padding-right:24px;">${unreadDot}${awayLabel}<span class="email-account-chip-label">${esc(label)}</span>${unreadCount > 0 ? `<span class="email-account-unread-count">${unreadCount > 999 ? '999+' : unreadCount}</span>` : ''}</button>`
- + `</span>`;
- }
- strip.innerHTML = html;
- strip.querySelectorAll('button[data-acc-id]').forEach(btn => {
- btn.addEventListener('click', async () => {
- const nextAccountId = btn.dataset.accId || null;
- if ((state._libAccountId || null) === nextAccountId) return;
- // Tag filters belong to the current mailbox account. Keeping one while
- // switching accounts can show an empty or misleading result set.
- if (String(state._libFilter || '').startsWith('tag:')) {
- state._libFilter = 'all';
- const filterEl = document.getElementById('email-lib-filter');
- if (filterEl) filterEl.value = 'all';
- }
- state._libSearchPills = (state._libSearchPills || []).filter((pill) => {
- const value = String(pill?.value || pill?.text || '');
- return pill?.type !== 'filter' || !value.includes('tag:');
- });
- state._libAccountId = nextAccountId;
- state._libViewInlineImages = _readEmailInlineImagesPreference(nextAccountId);
- _publishActiveAccount();
- _renderAccountsStrip();
- _renderFilterPickerCurrent();
- _syncSearchOptionsMenu();
- _renderSearchPills();
- _loadEmailsFresh({ force: true, useCache: true, refreshAfterCache: true, showRefreshSpinner: true });
- _loadFolders({ resetMissing: true }).catch(() => {});
- _refreshUnreadBadge({ syncAutoReplyTitle: true }).catch(() => {});
- _refreshAccountUnreadHighlights().catch(() => {});
- });
- });
- // Idempotent — wire wheel + grab-drag scroll once per strip element.
- if (!strip._scrollWired) {
- strip._scrollWired = true;
- // Vertical wheel → horizontal scroll. Only intercept when there's
- // actually horizontal overflow to scroll through, otherwise let the
- // page do its normal vertical scroll.
- strip.addEventListener('wheel', (e) => {
- if (strip.scrollWidth <= strip.clientWidth) return;
- if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return;
- e.preventDefault();
- strip.scrollLeft += e.deltaY;
- }, { passive: false });
- // Click-and-drag scroll. Track mousedown, then mousemove deltas
- // bump scrollLeft. Cancel a chip click if the user actually dragged
- // more than a few pixels.
- let dragging = false;
- let startX = 0;
- let startScroll = 0;
- let moved = 0;
- strip.style.cursor = 'grab';
- strip.addEventListener('mousedown', (e) => {
- if (e.button !== 0) return;
- dragging = true;
- moved = 0;
- startX = e.pageX;
- startScroll = strip.scrollLeft;
- strip.style.cursor = 'grabbing';
- strip.style.userSelect = 'none';
- });
- window.addEventListener('mousemove', (e) => {
- if (!dragging) return;
- const dx = e.pageX - startX;
- moved = Math.max(moved, Math.abs(dx));
- strip.scrollLeft = startScroll - dx;
- });
- window.addEventListener('mouseup', () => {
- if (!dragging) return;
- dragging = false;
- strip.style.cursor = 'grab';
- strip.style.userSelect = '';
- });
- // Swallow chip clicks fired after a real drag — the user meant to scroll,
- // not select.
- strip.addEventListener('click', (e) => {
- if (moved > 5) { e.stopPropagation(); e.preventDefault(); moved = 0; }
- }, true);
- }
- _publishActiveAccount();
- }
-
- async function _refreshAccountUnreadHighlights() {
- const accounts = Array.isArray(state._libAccounts) ? state._libAccounts.slice() : [];
- if (!accounts.length) return;
- const seq = ++_accountUnreadSeq;
- const next = new Map();
- await Promise.all(accounts.map(async (a) => {
- const id = String(a && a.id || '');
- if (!id) return;
- try {
- const res = await fetch(emailApiUrl('/api/email/unread-state', {
- folder: 'INBOX',
- account_id: id,
- }), { credentials: 'same-origin' });
- if (!res.ok) return;
- const data = await res.json().catch(() => ({}));
- next.set(id, {
- unreadCount: Number(data.unread_count || 0),
- maxUid: Number(data.max_uid || 0),
- });
- } catch (_) {}
- }));
- if (seq !== _accountUnreadSeq) return;
- _accountUnreadState = next;
- _renderAccountsStrip();
- }
-
- export async function mountEmailSettings(host) {
- if (!host) return;
- host.classList.add('email-settings-page');
- const head = host.querySelector('.email-settings-page-head');
- const body = host.querySelector('.email-settings-body');
- const defaultCard = document.getElementById('settings-email-default-card');
- const defaultHost = document.getElementById('settings-email-default-host');
- if (!head || !body) return;
-
- const render = async () => {
- body.innerHTML = _emailSettingsLoadingHtml();
- try {
- await _loadAccounts().catch(() => {});
- const multipleAccounts = (state._libAccounts || []).filter(a => a && a.enabled !== false).length > 1;
- if (defaultCard) defaultCard.hidden = !multipleAccounts;
- if (defaultHost) defaultHost.innerHTML = multipleAccounts ? _emailSettingsAccountSelectHtml() : '';
- head.innerHTML = '';
- const [cfg, writingStyle] = await Promise.all([
- _fetchEmailSettingsConfig(),
- _fetchEmailWritingStyle().catch(() => ''),
- ]);
- body.innerHTML = _emailWritingStyleHtml(writingStyle)
- + _emailDisplaySettingsHtml(cfg)
- + _emailCleanupSettingsHtml()
- + _emailSettingsFormHtml(cfg);
- state._libAutoReplyActive = _isAutoReplyActiveForCurrentAccount(cfg);
- state._libAutoReplyDraftActive = null;
- _syncEmailAutoReplyTitle(state._libAutoReplyActive);
- _syncAutoReplyCalendarEvent(cfg).catch((err) => console.warn('Failed to reconcile auto-reply calendar event:', err));
- const focus = host.dataset.emailSettingsFocus;
- if (focus) {
- const section = focus === 'show-tags'
- ? body.querySelector('.email-settings-display-section')
- : body.querySelector(`.email-settings-${focus}-section`);
- if (section) {
- section.scrollIntoView?.({ block: 'nearest' });
- }
- delete host.dataset.emailSettingsFocus;
- }
- _bindEmailSettingsPageControls(host, defaultHost);
- defaultHost?.querySelector('.email-settings-default')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- const acctId = ev.currentTarget.dataset.emailDefaultId;
- const account = (state._libAccounts || []).find(a => a && a.id === acctId);
- if (!acctId || account?.is_default) return;
- try {
- const response = await fetch(`${API_BASE}/api/email/accounts/${encodeURIComponent(acctId)}/set-default`, {
- method: 'POST', credentials: 'same-origin',
- });
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
- for (const a of state._libAccounts) a.is_default = a.id === acctId;
- _syncEmailSettingsAccountPicker(defaultHost);
- _renderAccountsStrip();
- } catch (err) {
- console.error('Set default account failed:', err);
- }
- });
- defaultHost?.querySelector('.email-settings-default')?.addEventListener('keydown', (ev) => {
- if (ev.key !== 'Enter' && ev.key !== ' ') return;
- ev.preventDefault();
- ev.currentTarget.click();
- });
- defaultHost?.querySelector('#email-settings-account-select')?.addEventListener('change', async (ev) => {
- state._libAccountId = ev.currentTarget.value || null;
- _publishActiveAccount();
- _renderAccountsStrip();
- await render();
- });
- } catch (_) {
- body.innerHTML = '<div class="email-settings-error">Could not load settings.</div>';
- }
- };
- await render();
- }
-
- export async function openEmailLibrarySettings() {
- openEmailLibrary();
- await _showEmailSettingsPage();
- }
-
- export function closeEmailLibrary() {
- _cancelEmailPrewarm();
- const modal = document.getElementById('email-lib-modal');
- if (modal) modal.remove();
- if (_libSyncTicker) {
- clearInterval(_libSyncTicker);
- _libSyncTicker = null;
- }
- _clearEmailDocumentSplit();
- if (state._libEscHandler) {
- document.removeEventListener('keydown', state._libEscHandler, true);
- state._libEscHandler = null;
- }
- if (state._libInnerEscHandler) {
- window.removeEventListener('keydown', state._libInnerEscHandler, true);
- state._libInnerEscHandler = null;
- }
- if (state._emailSearchOptionsDismiss) {
- document.removeEventListener('click', state._emailSearchOptionsDismiss);
- state._emailSearchOptionsDismiss = null;
- }
- state._libOpen = false;
- // If the /email route collapsed the wide sidebar to make room for
- // the fullscreen modal, re-expand it now that the modal is gone.
- try { window._restoreSidebarIfRouteCollapsed?.(); } catch (_) {}
- }
-
- // Make a modal draggable by its header. If `modal` and `fsClass` are
- // provided, dragging to the top edge of the viewport snaps to fullscreen
- // (Aero Snap). Dragging away from the top while fullscreen unsnaps.
- function _makeDraggable(content, modal, fsClass) {
- if (!content) return;
- const header = content.querySelector('.modal-header');
- if (!header) return;
- // Per-modal fullscreen behavior — caller supplies fsClass, we apply
- // the same inline-style fullscreen pattern email-lib + email-window
- // both use. exitFullscreen restores the default windowed size
- // (min(720px, 92vw) × 85vh) and centers around the cursor.
- const enterFullscreen = () => {
- if (!fsClass || modal.classList.contains(fsClass)) return;
- modal.classList.add(fsClass);
- content.style.position = 'fixed';
- content.style.left = '0';
- content.style.top = '0';
- content.style.right = '0';
- content.style.bottom = '0';
- content.style.width = '100vw';
- content.style.maxWidth = '100vw';
- content.style.height = '100vh';
- content.style.maxHeight = '100vh';
- content.style.borderRadius = '0';
- content.style.transform = 'none';
- };
- const exitFullscreen = (cx, cy) => {
- if (!fsClass || !modal.classList.contains(fsClass)) return;
- modal.classList.remove(fsClass);
- content.style.width = 'min(720px, 92vw)';
- content.style.maxWidth = '';
- content.style.height = '';
- content.style.maxHeight = '85vh';
- content.style.borderRadius = '';
- content.style.right = '';
- content.style.bottom = '';
- const w = Math.min(720, window.innerWidth * 0.92);
- content.style.left = Math.max(8, cx - w / 2) + 'px';
- content.style.top = Math.max(8, cy - 20) + 'px';
- };
- makeWindowDraggable(modal, {
- content,
- header,
- fsClass,
- skipSelector: '.close-btn, .modal-close',
- enableLeftDock: true, // park the email on the left while replying on the right
- onDragStart: ({ rect }) => {
- if (!modal.classList.contains('email-snap-left')) return;
- modal.classList.remove('email-snap-left');
- _clearEmailDocumentSplit();
- content.style.position = 'fixed';
- content.style.left = `${Math.round(rect.left)}px`;
- content.style.top = `${Math.round(rect.top)}px`;
- content.style.right = '';
- content.style.bottom = '';
- content.style.width = `${Math.max(420, Math.round(rect.width || 560))}px`;
- content.style.maxWidth = '';
- content.style.height = `${Math.max(320, Math.round(rect.height || 620))}px`;
- content.style.maxHeight = '85vh';
- content.style.borderRadius = '';
- content.style.transform = 'none';
- content.style.margin = '0';
- },
- onEnterFullscreen: fsClass ? enterFullscreen : null,
- onExitFullscreen: fsClass ? exitFullscreen : null,
- });
- }
-
- // When the user clicks Reply on a fullscreened email view, dock the email
- // modal to the left as a narrow sidebar so the doc panel (which opens on
- // the right side of the chat area) is visible side-by-side. Only triggers
- // when the viewport is wide enough to make a true split worthwhile. Returns
- // true if the snap was applied, false otherwise.
- function _snapEmailModalToLeftSidebar(modal) {
- if (!modal) return false;
- if (window.innerWidth < 900) return false;
- // "Open in new tab" reader modals (id="email-view-…") are explicitly
- // floating windows the user already positioned. Replying from one
- // shouldn't yank it to the left edge — leave it on top in its current
- // spot. Reply still opens the compose document; the user can drag the
- // reader away or close it themselves.
- if ((modal.id || '').startsWith('email-view-')) return false;
- const content = modal.querySelector('.modal-content');
- if (!content) return false;
- // Only dock if currently fullscreen — for a manually-sized window the
- // user already chose its layout; don't surprise them by snapping it.
- const wasLibFs = modal.classList.contains('email-lib-fullscreen');
- const wasWinFs = modal.classList.contains('email-window-fullscreen');
- if (!wasLibFs && !wasWinFs) return false;
- modal.classList.remove('email-lib-fullscreen');
- modal.classList.remove('email-window-fullscreen');
- modal.classList.add('email-snap-left');
- const W = Math.min(440, Math.max(360, Math.round(window.innerWidth * 0.30)));
- const left = _emailSplitLeftEdge();
- content.style.position = 'fixed';
- content.style.left = '0';
- content.style.top = '0';
- content.style.right = '';
- content.style.bottom = '0';
- content.style.width = W + 'px';
- content.style.maxWidth = W + 'px';
- content.style.height = '100vh';
- content.style.maxHeight = '100vh';
- content.style.borderRadius = '0';
- content.style.transform = 'none';
- content.style.margin = '0';
- _setEmailDocumentSplit(left, W);
- _scheduleEmailDocumentSplitMeasure(modal);
- return true;
- }
-
- async function _loadFolders({ resetMissing = false, live = false } = {}) {
- const seq = ++_libFolderSeq;
- const accountAtStart = state._libAccountId || '';
- try {
- const res = await fetch(emailApiUrl('/api/email/folders', {
- account_id: accountAtStart || undefined,
- cached_only: live ? undefined : 1,
- }));
- let data = await res.json();
- if (seq !== _libFolderSeq || accountAtStart !== (state._libAccountId || '')) return;
- const sel = document.getElementById('email-lib-folder');
- if (!sel || !data.folders) return;
- state._libFolders = data.folders;
- const resolvedFolder = _resolveEmailFolderAlias(state._libFolder);
- if (resolvedFolder !== state._libFolder && data.folders.includes(resolvedFolder)) {
- state._libFolder = resolvedFolder;
- }
- if (resetMissing && state._libFolder !== '__scheduled__' && !data.folders.includes(state._libFolder)) {
- state._libFolder = data.folders.includes('INBOX') ? 'INBOX' : (data.folders[0] || 'INBOX');
- state._libFilter = 'all';
- state._libSearch = '';
- state._libHasAttachments = false;
- _libListCache.clear();
- const searchEl = document.getElementById('email-lib-search');
- const filterEl = document.getElementById('email-lib-filter');
- const attachEl = document.getElementById('email-attachments-btn');
- if (searchEl) searchEl.value = '';
- if (filterEl) filterEl.value = 'all';
- if (attachEl) attachEl.classList.remove('active');
- _syncUnreadWindowGlow();
- _syncReminderClearButton();
- }
- sel.innerHTML = '';
- const folderHeader = document.createElement('option');
- folderHeader.disabled = true;
- folderHeader.textContent = '─────────';
- sel.appendChild(folderHeader);
- const { priority, others } = sortedFolders(data.folders);
- for (const f of priority) {
- const opt = document.createElement('option');
- opt.value = f;
- opt.textContent = folderDisplayName(f);
- if (f === state._libFolder) opt.selected = true;
- sel.appendChild(opt);
- }
- for (const f of others) {
- const opt = document.createElement('option');
- opt.value = f;
- opt.textContent = folderDisplayName(f);
- if (f === state._libFolder) opt.selected = true;
- sel.appendChild(opt);
- }
- if (!data.folders.some(f => /trash|bin|deleted/i.test(String(f)))) {
- const trashOpt = document.createElement('option');
- trashOpt.value = 'Trash';
- trashOpt.textContent = 'Trash';
- if (String(state._libFolder).toLowerCase() === 'trash') trashOpt.selected = true;
- sel.appendChild(trashOpt);
- }
- // Some providers omit Drafts from the folder discovery response even
- // though IMAP APPEND can still write to the standard Drafts mailbox.
- // Keep it available beside the provider-discovered folders.
- const hasDraftsFolder = data.folders.some(f => String(f).toLowerCase().includes('draft'));
- if (!hasDraftsFolder) {
- const draftOpt = document.createElement('option');
- draftOpt.value = 'Drafts';
- draftOpt.textContent = 'Drafts';
- if (String(state._libFolder).toLowerCase() === 'drafts') draftOpt.selected = true;
- sel.appendChild(draftOpt);
- }
- // Scheduled (special virtual folder)
- const schedOpt = document.createElement('option');
- schedOpt.value = '__scheduled__';
- schedOpt.textContent = 'Scheduled';
- if (state._libFolder === '__scheduled__') schedOpt.selected = true;
- sel.appendChild(schedOpt);
- sel.value = state._libFolder;
- _renderFolderPicker();
- } catch (e) {}
- }
-
- function _crossFolderCandidates() {
- const available = Array.isArray(state._libFolders) ? state._libFolders.filter(Boolean) : [];
- const lower = new Map(available.map(f => [String(f).toLowerCase(), f]));
- const pick = (patterns, fallback) => {
- for (const p of patterns) {
- const direct = lower.get(String(p).toLowerCase());
- if (direct) return direct;
- }
- const match = available.find(f => patterns.some(p => String(f).toLowerCase().includes(String(p).toLowerCase())));
- return match || fallback;
- };
- const candidates = [
- pick(['INBOX'], 'INBOX'),
- pick(['[Gmail]/Sent Mail', 'Sent Mail', 'Sent Items', 'INBOX.Sent', 'Sent'], '[Gmail]/Sent Mail'),
- pick(['Archive', '[Gmail]/All Mail', 'All Mail'], '[Gmail]/All Mail'),
- ];
- return Array.from(new Set(candidates.filter(Boolean)));
- }
-
- function _findEmailFolder(patterns, fallback) {
- const available = Array.isArray(state._libFolders) ? state._libFolders.filter(Boolean) : [];
- const lower = new Map(available.map(f => [String(f).toLowerCase(), f]));
- for (const p of patterns) {
- const direct = lower.get(String(p).toLowerCase());
- if (direct) return direct;
- }
- return available.find(f => patterns.some(p => String(f).toLowerCase().includes(String(p).toLowerCase()))) || fallback;
- }
-
- function _resolveEmailFolderAlias(folder) {
- const raw = String(folder || '').trim();
- const key = raw.toLowerCase();
- if (!raw || key === 'inbox' || raw === '__scheduled__') return raw || 'INBOX';
- if (key === 'sent' || key === 'sent mail' || key === 'sent items') {
- return _findEmailFolder(['[Gmail]/Sent Mail', '[Google Mail]/Sent Mail', 'Sent Mail', 'Sent Items', 'INBOX.Sent', 'Sent'], raw);
- }
- if (key === 'archive' || key === 'archives' || key === 'all mail' || key === 'archive / all mail') {
- return _findEmailFolder(['[Gmail]/All Mail', '[Google Mail]/All Mail', 'All Mail', 'Archive', 'Archives'], raw);
- }
- if (key === 'starred' || key === 'favorites' || key === 'flagged') {
- return _findEmailFolder(['[Gmail]/Starred', '[Google Mail]/Starred', 'Starred', 'Flagged'], raw);
- }
- if (key === 'junk' || key === 'spam') {
- return _findEmailFolder(['[Gmail]/Spam', '[Google Mail]/Spam', 'Spam', 'Junk'], raw);
- }
- if (key === 'trash' || key === 'bin' || key === 'deleted') {
- return _findEmailFolder(['[Gmail]/Trash', '[Google Mail]/Trash', '[Gmail]/Bin', 'Trash', 'Bin', 'Deleted Messages', 'Deleted Items'], raw);
- }
- if (key === 'draft' || key === 'drafts') {
- return _findEmailFolder(['[Gmail]/Drafts', '[Google Mail]/Drafts', 'Drafts', 'Draft', 'INBOX.Drafts'], raw);
- }
- return raw;
- }
-
- function _sentFolderName() {
- return _findEmailFolder(['[Gmail]/Sent Mail', 'Sent Mail', 'Sent Items', 'INBOX.Sent', 'Sent'], 'Sent');
- }
-
- function _deriveSearchScope(rawQuery) {
- const original = String(rawQuery || '').trim();
- const tokens = original.split(/\s+/).filter(Boolean);
- let scope = 'all';
- const kept = [];
- let forced = '';
- for (const token of tokens) {
- const t = token.toLowerCase().replace(/^#+/, '').replace(/:$/, '');
- if (['sent', 'sentmail', 'sent-mail', 'outbox'].includes(t)) {
- forced = 'sent';
- continue;
- }
- if (['inbox'].includes(t)) {
- forced = 'inbox';
- continue;
- }
- kept.push(token);
- }
- if (forced) scope = forced;
- let folder = 'INBOX';
- let serverScope = 'all';
- if (scope === 'sent') {
- folder = _sentFolderName();
- serverScope = 'folder';
- } else if (scope === 'inbox') {
- folder = 'INBOX';
- serverScope = 'folder';
- } else if (scope === 'current') {
- folder = state._libFolder || 'INBOX';
- serverScope = 'folder';
- }
- return {
- scope,
- folder,
- serverScope,
- q: forced ? kept.join(' ').trim() : original,
- forced,
- };
- }
-
- // Snapshot of state._libEmails taken right before search starts so we
- // can both filter locally and restore on clear without re-fetching.
- let _libPreSearchEmails = null;
- let _libPreSearchTotal = 0;
- let _libServerSearchEmails = null;
- let _libServerSearchTotal = 0;
-
- // Cached contact suggestions for the chip-input autocomplete. Built on
- // first focus / first keystroke from contacts + currently-loaded senders.
- let _libSuggestionCache = null;
- let _libSuggestionFocusIdx = 0;
-
- async function _buildSuggestionSource() {
- // Combine the contacts list with senders/recipients visible in the
- // loaded email list. Dedup by lowercased email address; prefer
- // contact-supplied display names where present.
- const map = new Map();
- const _add = (name, email) => {
- const key = String(email || '').trim().toLowerCase();
- if (!key) return;
- const prev = map.get(key);
- if (!prev || (name && !prev.name)) {
- map.set(key, { name: (name || '').trim(), email: key });
- }
- };
- // 1) Senders / recipients already in the loaded grid.
- for (const em of (state._libEmails || [])) {
- _add(em.from_name, em.from_address);
- const _parse = (s) => String(s || '').split(',').forEach(seg => {
- const m = seg.match(/^\s*"?([^"<]*)"?\s*<?([^>]+)>?\s*$/);
- if (m) _add(m[1], m[2]);
- });
- _parse(em.to);
- _parse(em.cc);
- }
- // 2) Address book — best-effort.
- try {
- const r = await fetch(`${API_BASE}/api/contacts/list`, { credentials: 'same-origin' });
- if (r.ok) {
- const d = await r.json();
- for (const c of (d.contacts || [])) {
- const email = c.email || (c.emails && c.emails[0]) || '';
- _add(c.name || c.full_name, email);
- }
- }
- } catch (_) {}
- return Array.from(map.values()).filter(x => x.email);
- }
-
- function _scoreSuggestion(s, needle) {
- // Crude relevance: startsWith on name or email wins big; substring is fine.
- const n = (s.name || '').toLowerCase();
- const e = (s.email || '').toLowerCase();
- if (n.startsWith(needle) || e.startsWith(needle)) return 3;
- if (n.includes(needle) || e.includes(needle)) return 2;
- return 0;
- }
-
- function _formatEmailSuggestionDate(em) {
- let d = null;
- if (em && em.date) {
- const parsed = new Date(em.date);
- if (Number.isFinite(parsed.getTime())) d = parsed;
- }
- if (!d && em && em.date_epoch) {
- const parsed = new Date(Number(em.date_epoch) * 1000);
- if (Number.isFinite(parsed.getTime())) d = parsed;
- }
- if (!d) return '';
- const now = new Date();
- const opts = d.getFullYear() === now.getFullYear()
- ? { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }
- : { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' };
- return d.toLocaleDateString(undefined, opts);
- }
-
- // Filter / attachment suggestions surfaced inside the same chip-bar
- // dropdown. Typing 'attachment', 'unread', 'urgent' etc. surfaces the
- // corresponding filter row with its icon; picking it pins a filter
- // pill that drives state._libFilter or the has-attachments toggle.
- const _LIB_FILTER_OPTIONS = [
- { value: 'filter:has-attachments', label: 'Has attachments', keywords: ['attachment', 'attachments', 'has attachment', 'attach'] },
- { value: 'filter:unread', label: 'Unread', keywords: ['unread', 'new', 'unseen'] },
- { value: 'filter:favorites', label: 'Favorites', keywords: ['favorite', 'favorites', 'starred', 'star', 'flagged'] },
- { value: 'filter:undone', label: 'Undone', keywords: ['undone', 'pending', 'todo'] },
- { value: 'filter:reminders', label: 'Reminders', keywords: ['reminder', 'reminders'] },
- { value: 'filter:unanswered', label: 'Unanswered', keywords: ['unanswered', 'unreplied', 'no reply'] },
- { value: 'filter:pending_30d', label: 'Pending · 30d', keywords: ['pending 30d', 'pending', 'recent pending'] },
- { value: 'filter:stale_30d', label: 'Stale · >30d', keywords: ['stale', 'old', 'stale 30d'] },
- { value: 'filter:tag:urgent', label: 'Urgent', keywords: ['urgent', 'critical'] },
- { value: 'filter:tag:reply-soon', label: 'Reply soon', keywords: ['reply soon', 'reply', 'follow up'] },
- { value: 'filter:tag:bills', label: 'Bills', keywords: ['bill', 'bills', 'billing'] },
- { value: 'filter:tag:receipt', label: 'Receipt', keywords: ['receipt', 'receipts', 'purchase'] },
- { value: 'filter:tag:travel', label: 'Travel', keywords: ['travel', 'trip', 'booking'] },
- { value: 'filter:tag:spam', label: 'Spam', keywords: ['spam', 'junk'] },
- ];
-
- function _libFilterIconFor(value) {
- // value is 'filter:<X>' — strip prefix and reuse the existing icon map.
- const v = String(value || '').replace(/^filter:/, '');
- if (v === 'has-attachments') return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 17.93 8.8l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>';
- if (v === 'date-range') return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="17" rx="2"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>';
- return _EMAIL_FILTER_ICONS[v] || _EMAIL_FILTER_ICONS['all'];
- }
-
- function _scoreFilterOption(opt, needle) {
- for (const kw of opt.keywords) {
- if (kw === needle) return 4;
- if (kw.startsWith(needle)) return 3;
- if (kw.includes(needle)) return 2;
- }
- if (opt.label.toLowerCase().includes(needle)) return 2;
- return 0;
- }
-
- function _filterSuggestions(needle, limit = 10) {
- const n = String(needle || '').trim().toLowerCase();
- if (!n) return [];
- // Filter / attachment matches first — typing 'unread' should surface
- // the filter row before contact suggestions, since 'unread' isn't a
- // person.
- const filterMatches = _LIB_FILTER_OPTIONS
- .map(opt => ({ s: { kind: 'filter', value: opt.value, label: opt.label, icon: _libFilterIconFor(opt.value) }, score: _scoreFilterOption(opt, n) }))
- .filter(x => x.score > 0);
- const src = _libSuggestionCache || [];
- const contactMatches = src
- .map(s => ({ s: { kind: 'contact', ...s }, score: _scoreSuggestion(s, n) }))
- .filter(x => x.score > 0);
- // Email subject / sender-name matches — use the snapshot (unfiltered
- // list) when available so suggestions don't shrink as pills narrow the
- // visible grid. Cap to 4 so contacts + filters stay visible.
- const emails = _libPreSearchEmails || state._libEmails || [];
- const emailMatches = [];
- for (const em of emails) {
- const subj = String(em.subject || '').toLowerCase();
- const fromN = String(em.from_name || '').toLowerCase();
- let score = 0;
- if (subj.startsWith(n) || fromN.startsWith(n)) score = 3;
- else if (subj.includes(n) || fromN.includes(n)) score = 1;
- if (score > 0) {
- emailMatches.push({
- s: {
- kind: 'email',
- uid: em.uid,
- subject: em.subject || '(no subject)',
- from_name: em.from_name || em.from_address || '',
- date_label: _formatEmailSuggestionDate(em),
- },
- score,
- });
- }
- if (emailMatches.length >= 4) break;
- }
- return filterMatches.concat(contactMatches).concat(emailMatches)
- .sort((a, b) => b.score - a.score)
- .slice(0, limit)
- .map(x => x.s);
- }
-
- function _exactTypedFilterSuggestion(value) {
- const needle = String(value || '').trim().toLowerCase();
- if (!needle) return null;
- // Keep automatic conversion deliberately exact. A query such as
- // "attachment invoice" should remain a text search, while the common
- // one-word shortcut should become the existing filter pill.
- const option = _LIB_FILTER_OPTIONS.find(opt => (
- opt.value === 'filter:has-attachments' && opt.keywords.includes(needle)
- ));
- return option
- ? { kind: 'filter', value: option.value, label: option.label, icon: _libFilterIconFor(option.value) }
- : null;
- }
-
- function _emailMatchesPill(em, pill) {
- if (!pill) return false;
- if (pill.type === 'contact') {
- const target = (pill.email || '').toLowerCase();
- if (!target) return false;
- if (String(em.from_address || '').toLowerCase() === target) return true;
- if (String(em.to || '').toLowerCase().includes(target)) return true;
- if (String(em.cc || '').toLowerCase().includes(target)) return true;
- return false;
- }
- if (pill.type === 'filter') {
- // Filter pills delegate to the server-side filter (state._libFilter)
- // or the has-attachments toggle. The list is already pre-filtered by
- // those when this runs, so the pill is effectively always-true here
- // — it lives in the pill bar purely as a visible affordance.
- return true;
- }
- // text pill — broad local-match
- const q = (pill.text || '').toLowerCase();
- if (!q) return true;
- return _matchesQuery(em, q);
- }
-
- function _matchesQuery(em, q) {
- const needle = q.toLowerCase();
- const dateNeedle = _formatEmailSuggestionDate(em).toLowerCase();
- const dateOnlyNeedle = dateNeedle.replace(/\s+\d{1,2}:\d{2}\s*(am|pm)?$/i, '');
- const rawDate = String(em.date || em.date_display || '').toLowerCase();
- return (
- String(em.subject || '').toLowerCase().includes(needle) ||
- String(em.from_name || '').toLowerCase().includes(needle) ||
- String(em.from_address || '').toLowerCase().includes(needle) ||
- String(em.to || '').toLowerCase().includes(needle) ||
- String(em.cc || '').toLowerCase().includes(needle) ||
- String(em.snippet || em.preview || '').toLowerCase().includes(needle) ||
- dateNeedle.includes(needle) ||
- dateOnlyNeedle.includes(needle) ||
- rawDate.includes(needle)
- );
- }
-
- // Apply the active pill filter to the snapshot. Each pill is OR-ed; an
- // email shows up if ANY pill matches (a contact pill matches by from/to/cc
- // equality, a text pill matches by the broad _matchesQuery substring).
- function _applyPillFilter() {
- _exitEmailReaderModeForList();
- const pills = state._libSearchPills || [];
- const draft = (state._libSearchDraft || '').trim();
- const noPills = pills.length === 0;
- const noDraft = draft.length === 0;
- // First time we apply with anything active: snapshot the loaded list.
- if (!noPills || draft.length >= 1) {
- if (!_libPreSearchEmails) {
- _libPreSearchEmails = (state._libEmails || []).slice();
- _libPreSearchTotal = state._libTotal;
- }
- }
- if (noPills && noDraft) {
- if (_libPreSearchEmails) {
- state._libEmails = _libPreSearchEmails;
- state._libTotal = _libPreSearchTotal;
- _libPreSearchEmails = null;
- _libPreSearchTotal = 0;
- }
- _renderGrid();
- return;
- }
- const source = _libServerSearchEmails || _libPreSearchEmails || state._libEmails || [];
- // If the active server search covers a piece of text (either the live
- // draft OR an Enter-committed text pill), skip the local re-filter for
- // it — _emailMatchesPill only checks subject/from_name/from_address/
- // snippet (no BODY), so it was dropping legitimate server hits where
- // the match was in body text. Real pills (contact, filter chips) still
- // apply, and other text pills with different strings still apply.
- const libSearchLower = (_libSearchHadResults ? (state._libSearch || '').trim().toLowerCase() : '');
- const hasRefinementBase = !!(_libServerSearchEmails && pills.length > 1);
- const serverHandledDraft = !hasRefinementBase && !!(libSearchLower && draft && libSearchLower === draft.toLowerCase());
- const draftPill = (!serverHandledDraft && draft.length >= 1) ? { type: 'text', text: draft } : null;
- // Filter out text pills whose text matches the active server search —
- // those were the trigger for the IMAP query and don't need re-checking.
- const effectiveBasePills = (libSearchLower && !hasRefinementBase)
- ? pills.filter(p => !(p.type === 'text' && (p.text || '').toLowerCase() === libSearchLower))
- : pills;
- const effective = draftPill ? effectiveBasePills.concat([draftPill]) : effectiveBasePills;
- // AND across pills — "alice + bob" should mean both alice AND bob are
- // somewhere on the email (from/to/cc), not "from alice OR from bob".
- const filtered = source.filter(em => effective.every(p => _emailMatchesPill(em, p)));
- state._libEmails = filtered;
- _renderGrid();
- }
- // Back-compat shim: older call sites still expect _localSearchFilter.
- function _localSearchFilter(query) {
- state._libSearchDraft = String(query || '');
- _applyPillFilter();
- }
-
- // Render the active pills inside the chip bar. Each pill carries a × to
- // remove individually. Backspace on empty input also pops the last one.
- function _emailFilterLabelFor(value) {
- const v = String(value || '');
- if (v === 'has-attachments') return 'Attachments';
- const sel = document.getElementById('email-lib-filter');
- const opt = sel?.querySelector?.(`option[value="${CSS.escape(v)}"]`);
- if (opt) return opt.textContent || v;
- const match = _LIB_FILTER_OPTIONS.find(o => o.value === `filter:${v}`);
- return match?.label || v;
- }
-
- function _activeEmailFilterPills() {
- const active = [];
- if (state._libHasAttachments) {
- active.push({ value: 'has-attachments', label: _emailFilterLabelFor('has-attachments') });
- }
- const filter = String(state._libFilter || 'all');
- if (filter && filter !== 'all') {
- active.push({ value: filter, label: _emailFilterLabelFor(filter) });
- }
- if (state._libDateFrom || state._libDateTo) {
- const range = state._libDateFrom && state._libDateTo
- ? `${state._libDateFrom} – ${state._libDateTo}`
- : state._libDateFrom ? `From ${state._libDateFrom}` : `Through ${state._libDateTo}`;
- active.push({ value: 'date-range', label: range });
- }
- return active;
- }
-
- function _clearActiveEmailFilterPill(value) {
- _resetBulkSelectionForContextChange({ rerender: true });
- const v = String(value || '');
- if (v === 'has-attachments') {
- state._libHasAttachments = false;
- } else if (v === 'date-range') {
- state._libDateFrom = '';
- state._libDateTo = '';
- } else if (state._libFilter === v) {
- state._libFilter = 'all';
- const sel = document.getElementById('email-lib-filter');
- if (sel) sel.value = 'all';
- }
- _syncUnreadWindowGlow();
- _syncReminderClearButton();
- _renderFilterPickerCurrent();
- _syncSearchOptionsMenu();
- _renderSearchPills();
- _loadEmailsFresh();
- }
-
- function _renderSearchPills() {
- const wrap = document.getElementById('email-lib-pills');
- if (!wrap) return;
- const pills = (state._libSearchPills || []).filter(p => p.type !== 'filter');
- state._libSearchPills = pills;
- const folderSelect = document.getElementById('email-lib-folder');
- const folder = String(folderSelect?.value || state._libFolder || 'INBOX');
- const showingFolderPill = folder && folder !== 'INBOX' && folder !== '__scheduled__';
- const filterPills = _activeEmailFilterPills();
- const chipBar = document.getElementById('email-lib-chip-bar');
- const input = document.getElementById('email-lib-search');
- const visiblePillCount = pills.length + filterPills.length + (showingFolderPill ? 1 : 0);
- if (chipBar) chipBar.classList.toggle('has-email-lib-pills', visiblePillCount > 0);
- if (input) input.placeholder = visiblePillCount > 0 ? '' : 'Search by name or text';
- const esc = s => String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
- const folderLabel = folderDisplayName(folder);
- const folderPill = showingFolderPill
- ? `<span class="email-lib-pill email-lib-folder-pill" data-folder-pill="${esc(folder)}" title="${esc(folderLabel)}" style="display:inline-flex;align-items:center;gap:3px;padding:0 5px 0 7px;border-radius:999px;background:color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);color:var(--accent, var(--red));font-size:11px;line-height:20px;height:20px;font-weight:600;max-width:170px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:0;">
- <span style="overflow:hidden;text-overflow:ellipsis;">${esc(folderLabel)}</span>
- <button type="button" class="email-lib-folder-pill-x" title="Back to Inbox" style="background:transparent;border:0;color:inherit;cursor:pointer;font-size:12px;line-height:1;padding:0 2px;opacity:0.7;position:relative;top:-4px;">×</button>
- </span>`
- : '';
- const filterPillHtml = filterPills.map(p => {
- const titleAttr = esc(p.label);
- return `<span class="email-lib-pill email-lib-filter-pill" data-email-filter-pill="${esc(p.value)}" title="${titleAttr}" style="display:inline-flex;align-items:center;gap:3px;padding:0 5px 0 7px;border-radius:999px;background:color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);color:var(--accent, var(--red));font-size:11px;line-height:20px;height:20px;font-weight:600;max-width:170px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:0;">
- <span class="email-lib-pill-icon" style="display:inline-flex;align-items:center;width:13px;height:13px;flex-shrink:0;">${_libFilterIconFor(`filter:${p.value}`)}</span>
- <span class="email-lib-filter-pill-label" style="overflow:hidden;text-overflow:ellipsis;">${esc(p.label)}</span>
- <button type="button" class="email-lib-filter-pill-x" data-email-filter-pill="${esc(p.value)}" title="Remove" style="background:transparent;border:0;color:inherit;cursor:pointer;font-size:12px;line-height:1;padding:0 2px;opacity:0.7;position:relative;top:-4px;">×</button>
- </span>`;
- }).join('');
- wrap.innerHTML = folderPill + filterPillHtml + pills.map((p, i) => {
- const label = p.type === 'contact' ? (p.name || p.email || '?') : (p.text || '');
- return `<span class="email-lib-pill" data-pill-idx="${i}" style="display:inline-flex;align-items:center;gap:3px;padding:0 5px 0 7px;border-radius:999px;background:color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);color:var(--accent, var(--red));font-size:11px;line-height:20px;height:20px;font-weight:600;max-width:170px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:0;">
- <span style="overflow:hidden;text-overflow:ellipsis;">${esc(label)}</span>
- <button type="button" class="email-lib-pill-x" data-pill-idx="${i}" title="Remove" style="background:transparent;border:0;color:inherit;cursor:pointer;font-size:12px;line-height:1;padding:0 2px;opacity:0.7;position:relative;top:-4px;">×</button>
- </span>`;
- }).join('');
- requestAnimationFrame(() => {
- if (wrap.scrollWidth <= wrap.clientWidth) return;
- for (const value of ['has-attachments', 'reminders']) {
- const pill = wrap.querySelector(`.email-lib-filter-pill[data-email-filter-pill="${value}"]`);
- if (!pill) continue;
- pill.classList.add('email-lib-filter-pill-icon-only');
- if (wrap.scrollWidth <= wrap.clientWidth) break;
- }
- });
- wrap.querySelectorAll('.email-lib-filter-pill[data-email-filter-pill="date-range"]').forEach(pill => {
- pill.style.cursor = 'pointer';
- pill.addEventListener('click', (ev) => {
- if (ev.target.closest('.email-lib-filter-pill-x')) return;
- const menu = document.getElementById('email-search-options-menu');
- const trigger = document.getElementById('email-search-options-btn');
- const panel = menu?.querySelector('.email-search-date-panel');
- if (!menu || !panel) return;
- menu.hidden = false;
- panel.hidden = false;
- trigger?.setAttribute('aria-expanded', 'true');
- const from = panel.querySelector('#email-search-date-from');
- const to = panel.querySelector('#email-search-date-to');
- if (from) from.value = state._libDateFrom || '';
- if (to) to.value = state._libDateTo || '';
- from?.focus();
- });
- });
- wrap.querySelectorAll('.email-lib-pill-x').forEach(btn => {
- btn.addEventListener('click', (e) => {
- e.stopPropagation();
- const idx = Number(btn.dataset.pillIdx);
- if (Number.isFinite(idx)) _removeSearchPillAt(idx);
- });
- });
- wrap.querySelectorAll('.email-lib-filter-pill-x').forEach(btn => {
- btn.addEventListener('click', (e) => {
- e.stopPropagation();
- _clearActiveEmailFilterPill(btn.dataset.emailFilterPill || '');
- });
- });
- wrap.querySelectorAll('.email-lib-folder-pill-x').forEach(btn => {
- btn.addEventListener('click', (e) => {
- e.stopPropagation();
- _resetBulkSelectionForContextChange({ rerender: true });
- const folders = Array.isArray(state._libFolders) ? state._libFolders : [];
- state._libFolder = folders.includes('INBOX') ? 'INBOX' : (folders.find(f => !/sent/i.test(String(f || ''))) || 'INBOX');
- const folderSel = document.getElementById('email-lib-folder');
- if (folderSel) folderSel.value = state._libFolder;
- _renderFolderPicker();
- _renderSearchPills();
- _loadEmailsFresh();
- });
- });
- }
-
- function _applyFilterPillSideEffect(pill) {
- // Filter pills drive the existing has-attachments toggle / filter
- // dropdown so the server returns the right list. Only one filter
- // pill is active at a time (see _addSearchPill).
- const sel = document.getElementById('email-lib-filter');
- if (pill.value === 'filter:has-attachments') {
- if (!state._libHasAttachments) {
- state._libHasAttachments = true;
- _syncSearchOptionsMenu();
- }
- if (sel && sel.value !== 'all') { sel.value = 'all'; sel.dispatchEvent(new Event('change')); }
- return;
- }
- // Any other filter pill — set the dropdown value, clear attachments
- if (state._libHasAttachments) {
- state._libHasAttachments = false;
- _syncSearchOptionsMenu();
- }
- if (sel) {
- const v = pill.value.replace(/^filter:/, '');
- if (sel.value !== v) { sel.value = v; sel.dispatchEvent(new Event('change')); }
- }
- }
-
- function _clearFilterPillSideEffect() {
- const sel = document.getElementById('email-lib-filter');
- if (state._libHasAttachments) {
- state._libHasAttachments = false;
- _syncSearchOptionsMenu();
- }
- if (sel && sel.value !== 'all') {
- sel.value = 'all'; sel.dispatchEvent(new Event('change'));
- }
- }
-
- function _addSearchPill(pill) {
- if (!pill) return;
- _resetBulkSelectionForContextChange({ rerender: true });
- if (!Array.isArray(state._libSearchPills)) state._libSearchPills = [];
- // Dedup by email (contact), text (text pill), or filter value.
- if (pill.type === 'contact') {
- const key = (pill.email || '').toLowerCase();
- if (!key) return;
- if (state._libSearchPills.some(p => p.type === 'contact' && (p.email || '').toLowerCase() === key)) return;
- } else if (pill.type === 'text') {
- const t = (pill.text || '').toLowerCase();
- if (!t) return;
- if (state._libSearchPills.some(p => p.type === 'text' && (p.text || '').toLowerCase() === t)) return;
- } else if (pill.type === 'filter') {
- // Filter state renders as a synthetic pill from state._libFilter /
- // state._libHasAttachments. Do not store a duplicate search pill.
- state._libSearchPills = state._libSearchPills.filter(p => p.type !== 'filter');
- _applyFilterPillSideEffect(pill);
- _renderSearchPills();
- return;
- }
- state._libSearchPills.push(pill);
- _renderSearchPills();
- _applyPillFilter();
- }
-
- function _searchQueryFromPills() {
- const parts = [];
- for (const p of state._libSearchPills || []) {
- if (p.type === 'text' && p.text) parts.push(String(p.text).trim());
- else if (p.type === 'contact' && (p.email || p.name)) parts.push(String(p.email || p.name).trim());
- }
- return parts.filter(Boolean).join(' ').trim();
- }
-
- function _removeSearchPillAt(idx) {
- if (!Array.isArray(state._libSearchPills)) return;
- _resetBulkSelectionForContextChange({ rerender: true });
- const removed = state._libSearchPills[idx];
- state._libSearchPills.splice(idx, 1);
- if (removed && removed.type === 'filter') _clearFilterPillSideEffect();
- _renderSearchPills();
- // Pill cleared all the way: if we got into search-result mode via the
- // IMAP search, the pre-search snapshot is now those results too (set
- // in _doSearch). Restoring from it would leave the user staring at
- // the same results with the pill bar empty. Re-fetch the real inbox
- // so removing the last pill genuinely "goes back".
- const noPillsLeft = (state._libSearchPills || []).length === 0
- && !(state._libSearchDraft || '').trim();
- if (noPillsLeft && _libSearchHadResults) {
- _libSearchHadResults = false;
- _libPreSearchEmails = null;
- _libPreSearchTotal = 0;
- _libServerSearchEmails = null;
- _libServerSearchTotal = 0;
- state._libSearch = '';
- state._libOffset = 0;
- const _searchInput = document.getElementById('email-lib-search');
- if (_searchInput) _searchInput.value = '';
- _loadEmails({ useCache: true });
- return;
- }
- const remainingQuery = _searchQueryFromPills();
- if (remainingQuery.length >= 2) {
- state._libSearch = remainingQuery;
- const _searchInput = document.getElementById('email-lib-search');
- if (_searchInput) _searchInput.value = '';
- state._libSearchDraft = '';
- _doSearch();
- return;
- }
- if ((state._libSearchPills || []).length && _libSearchHadResults) {
- _libSearchHadResults = false;
- _libPreSearchEmails = null;
- _libPreSearchTotal = 0;
- _libServerSearchEmails = null;
- _libServerSearchTotal = 0;
- state._libSearch = '';
- state._libOffset = 0;
- _loadEmails({ useCache: true });
- return;
- }
- _applyPillFilter();
- }
-
- // Render the autocomplete dropdown below the input. focusIdx highlights
- // the active row; Tab autocompletes / Enter accepts that row.
- function _renderSearchSuggestions(items) {
- const menu = document.getElementById('email-lib-suggest');
- if (!menu) return;
- if (!items.length) { menu.style.display = 'none'; menu.innerHTML = ''; return; }
- const esc = s => String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
- menu.innerHTML = items.map((s, i) => {
- const highlight = i === _libSuggestionFocusIdx ? 'background:color-mix(in srgb, var(--fg) 8%, transparent);' : '';
- if (s.kind === 'filter') {
- return `<div class="email-lib-suggest-item" data-idx="${i}" style="display:flex;align-items:center;gap:8px;padding:6px 10px;cursor:pointer;font-size:12px;${highlight}">
- <span style="display:inline-flex;align-items:center;width:13px;height:13px;color:var(--accent, var(--red));flex-shrink:0;">${s.icon}</span>
- <span style="font-weight:600;">${esc(s.label)}</span>
- </div>`;
- }
- if (s.kind === 'email') {
- return `<div class="email-lib-suggest-item" data-idx="${i}" style="display:flex;align-items:center;gap:6px;padding:6px 10px;cursor:pointer;font-size:12px;${highlight}">
- <span style="display:inline-flex;align-items:center;width:13px;height:13px;color:var(--fg-muted, var(--fg));opacity:0.55;flex-shrink:0;"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><polyline points="2 6 12 13 22 6"/></svg></span>
- <span style="font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${esc(s.subject)}</span>
- ${s.from_name ? `<span style="opacity:0.55;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">— ${esc(s.from_name)}</span>` : ''}
- ${s.date_label ? `<span style="margin-left:auto;opacity:0.48;font-size:11px;white-space:nowrap;flex-shrink:0;">${esc(s.date_label)}</span>` : ''}
- </div>`;
- }
- return `<div class="email-lib-suggest-item" data-idx="${i}" style="display:flex;align-items:center;gap:6px;padding:6px 10px;cursor:pointer;font-size:12px;${highlight}">
- <span style="font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${esc(s.name || s.email)}</span>
- ${s.name ? `<span style="opacity:0.55;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${esc(s.email)}</span>` : ''}
- </div>`;
- }).join('');
- menu.style.display = '';
- menu.querySelectorAll('.email-lib-suggest-item').forEach(row => {
- row.addEventListener('mousedown', (e) => {
- // mousedown (not click) so we beat the input blur handler that hides the menu.
- e.preventDefault();
- const idx = Number(row.dataset.idx);
- const item = items[idx];
- if (item) _acceptSuggestion(item);
- });
- });
- }
-
- function _hideSearchSuggestions() {
- const menu = document.getElementById('email-lib-suggest');
- if (menu) { menu.style.display = 'none'; menu.innerHTML = ''; }
- _libSuggestionFocusIdx = 0;
- }
-
- function _acceptSuggestion(s) {
- const input = document.getElementById('email-lib-search');
- if (s.kind === 'filter') {
- _addSearchPill({ type: 'filter', value: s.value, label: s.label });
- } else if (s.kind === 'email') {
- // Clear the draft + dropdown and open the matching card directly.
- if (input) input.value = '';
- state._libSearchDraft = '';
- _hideSearchSuggestions();
- _applyPillFilter();
- const grid = document.getElementById('email-lib-grid');
- const card = grid?.querySelector(`.doclib-card[data-uid="${CSS.escape(String(s.uid))}"]`);
- const em = (state._libEmails || []).find(x => String(x.uid) === String(s.uid))
- || (_libPreSearchEmails || []).find(x => String(x.uid) === String(s.uid));
- if (card && em) {
- card.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
- _toggleCardPreview(card, em);
- }
- return;
- } else {
- _addSearchPill({ type: 'contact', name: s.name, email: s.email });
- // Same as the text-pill path in the Enter handler: trigger the IMAP
- // search so unloaded emails (older than the current page) show up
- // when picking a contact. The local pill filter then narrows the
- // search results to that contact's address.
- const _q = (s.email || s.name || '').trim();
- if (_q && _q.length >= 2) {
- state._libSearch = _q;
- _doSearch();
- }
- }
- if (input) input.value = '';
- state._libSearchDraft = '';
- _hideSearchSuggestions();
- _applyPillFilter();
- if (input) input.focus();
- }
-
- async function _initEmailSearchChipBar() {
- const bar = document.getElementById('email-lib-chip-bar');
- const input = document.getElementById('email-lib-search');
- if (!bar || !input) return;
- state._libSearchPills = state._libSearchPills || [];
- state._libSearchDraft = '';
- _renderSearchPills();
-
- // Lazy-load suggestion source on first focus / keystroke.
- const _ensureSuggestionCache = async () => {
- if (_libSuggestionCache) return;
- _libSuggestionCache = await _buildSuggestionSource();
- };
-
- // Click anywhere in the bar lands the cursor in the input field.
- bar.addEventListener('click', (e) => {
- if (e.target.closest('.email-lib-pill-x')) return;
- input.focus();
- });
-
- let _itemsRef = [];
- const _refreshSuggestions = async () => {
- await _ensureSuggestionCache();
- _itemsRef = _filterSuggestions(input.value);
- // Default to no focused suggestion — text typing should feel like
- // regular search; the user has to ArrowDown / Tab explicitly to
- // pick a contact. Enter without a focused row commits as text.
- _libSuggestionFocusIdx = -1;
- _renderSearchSuggestions(_itemsRef);
- };
-
- input.addEventListener('focus', _refreshSuggestions);
- // Debounced IMAP search — fires ~500ms after the user stops typing so
- // searches for names/text not in the current inbox page actually surface
- // hits, instead of just locally filtering the visible window.
- //
- // Live local filtering on EVERY keystroke was clobbering server hits:
- // _emailMatchesPill / _matchesQuery check subject/from_name/from_address/
- // snippet but never body, so intermediate text like "sam" reduced the
- // 61 server results to whatever matched just those four fields (often
- // 0). User saw "no emails" while typing. So local filter is gone from
- // the typing path — debounced server search drives the grid. Pill
- // add/remove still re-runs the local filter through _applyPillFilter
- // directly.
- let _libSearchTypingTimer = null;
- input.addEventListener('input', async () => {
- _resetBulkSelectionForContextChange({ rerender: true });
- state._libSearchDraft = input.value;
- await _refreshSuggestions();
- if (_libSearchTypingTimer) clearTimeout(_libSearchTypingTimer);
- const v = input.value.trim();
- if (v.length >= 2) {
- _libSearchTypingTimer = setTimeout(() => {
- const cur = (input.value || '').trim();
- if (cur === v && cur.length >= 2) {
- state._libSearch = cur;
- _doSearch();
- }
- }, 500);
- } else if (!v && _libSearchHadResults) {
- // Cleared the input → restore the inbox the same way the pill-clear
- // path does. Otherwise the stale search results stayed up after the
- // user backspaced everything out.
- _libSearchHadResults = false;
- _libPreSearchEmails = null;
- _libPreSearchTotal = 0;
- state._libSearch = '';
- state._libOffset = 0;
- _loadEmails({ useCache: true });
- }
- });
- input.addEventListener('keydown', (e) => {
- const menu = document.getElementById('email-lib-suggest');
- const menuOpen = menu && menu.style.display !== 'none';
- if (e.key === 'Backspace' && !input.value && (state._libSearchPills || []).length) {
- e.preventDefault();
- _removeSearchPillAt(state._libSearchPills.length - 1);
- return;
- }
- if (e.key === 'ArrowDown' && menuOpen) {
- e.preventDefault();
- // -1 → 0 → 1 → … → length-1, then wraps back to -1 (no selection)
- const next = _libSuggestionFocusIdx + 1;
- _libSuggestionFocusIdx = next >= _itemsRef.length ? -1 : next;
- _renderSearchSuggestions(_itemsRef);
- return;
- }
- if (e.key === 'ArrowUp' && menuOpen) {
- e.preventDefault();
- // -1 → length-1 → length-2 → … → 0 → -1
- const next = _libSuggestionFocusIdx - 1;
- _libSuggestionFocusIdx = next < -1 ? _itemsRef.length - 1 : next;
- _renderSearchSuggestions(_itemsRef);
- return;
- }
- if (e.key === 'Tab' && menuOpen) {
- // Tab autocompletes the FIRST suggestion (most-relevant), regardless
- // of whether the user arrowed down yet — matches the user's mental
- // model of "type a name and tab to pick".
- const pick = _libSuggestionFocusIdx >= 0 ? _itemsRef[_libSuggestionFocusIdx] : _itemsRef[0];
- if (pick) { e.preventDefault(); _acceptSuggestion(pick); return; }
- }
- if (e.key === 'Enter') {
- e.preventDefault();
- // Only commit a contact if the user explicitly focused one. Plain
- // Enter should default to a text pill so regular text search works
- // without forcing a contact pick.
- if (menuOpen && _libSuggestionFocusIdx >= 0 && _itemsRef[_libSuggestionFocusIdx]) {
- _acceptSuggestion(_itemsRef[_libSuggestionFocusIdx]);
- return;
- }
- const v = input.value.trim();
- if (v) {
- const typedFilter = _exactTypedFilterSuggestion(v);
- if (typedFilter) {
- _acceptSuggestion(typedFilter);
- return;
- }
- _addSearchPill({ type: 'text', text: v });
- input.value = '';
- state._libSearchDraft = '';
- _hideSearchSuggestions();
- // Pill-only filtering used to only check emails already loaded into
- // state._libEmails (the visible page of the inbox). Searches for
- // names/text that aren't in the current page returned "no emails"
- // even when matches existed on the server. Trigger the IMAP
- // search so state._libEmails is replaced with the actual hits,
- // then the pill filter narrows to matches.
- state._libSearch = v;
- _doSearch();
- }
- return;
- }
- if (e.key === 'Escape') {
- if (menuOpen) {
- // Just close the dropdown — let the modal Esc handler run on the
- // next Esc to actually dismiss the library.
- e.preventDefault();
- e.stopPropagation();
- _hideSearchSuggestions();
- } else {
- // Blur first so the modal Esc handler doesn't get suppressed by
- // any IME / typing-target check, and let the event propagate.
- try { input.blur(); } catch (_) {}
- }
- }
- });
- }
-
- // Click-to-add: clicking a recipient-chip in the email reader OR a
- // .email-meta-sender in the library list drops the person into the
- // library search as a contact pill so the user can pivot to "everything
- // from / to this person" in one tap.
- window.addEventListener('click', (e) => {
- const lib = document.getElementById('email-lib-modal');
- // 1) Recipient chips inside the email reader area
- const chip = e.target.closest && e.target.closest('.recipient-chip');
- if (chip && chip.closest('.email-reader-header, .email-card-reader, .email-reader-tab-modal')) {
- // Don't pivot to library search for chips in the From / To / Cc
- // meta — clicking those should just toggle the expanded address
- // view via the per-reader handler.
- if (chip.closest('.email-reader-meta')) return;
- const email = (chip.dataset && chip.dataset.email) || '';
- const name = (chip.dataset && chip.dataset.name) || (chip.textContent || '').trim();
- if (!email) return;
- e.preventDefault();
- e.stopPropagation();
- try { window.openEmailLibrary && window.openEmailLibrary(); } catch (_) {}
- _addSearchPill({ type: 'contact', name, email });
- return;
- }
- // 2) Sender name in a library list card row (only when the library is open)
- if (lib && !lib.classList.contains('hidden')) {
- const senderEl = e.target.closest && e.target.closest('.email-meta-sender');
- if (senderEl && senderEl.closest('#email-lib-grid')) {
- if (state._selectMode) return;
- const email = (senderEl.dataset && senderEl.dataset.email) || '';
- const name = (senderEl.dataset && senderEl.dataset.name) || (senderEl.textContent || '').trim();
- if (!email) return;
- e.preventDefault();
- e.stopPropagation();
- _addSearchPill({ type: 'contact', name, email });
- }
- }
- }, true);
-
- async function _doSearch() {
- _exitEmailReaderModeForList();
- _resetBulkSelectionForContextChange({ rerender: true });
- const seq = ++_libSearchSeq;
- const derived = _deriveSearchScope(state._libSearch);
- const q = derived.q;
- if (q.length < 2 && !derived.forced) {
- // Empty or too short — restore the normal folder if a previous search
- // had replaced the grid contents.
- if (_libSearchHadResults) {
- _libSearchHadResults = false;
- state._libOffset = 0;
- await _loadEmails({ useCache: true });
- return;
- }
- _renderGrid();
- return;
- }
- const accountAtStart = state._libAccountId || '';
- const folderAtStart = derived.folder || state._libFolder || 'INBOX';
- const serverScopeAtStart = derived.serverScope || 'all';
- // No grid-blanking spinner — the local filter already painted something
- // useful. Surface progress in the stats badge instead so the user knows
- // the server search is still grinding.
- const stats = document.getElementById('email-lib-stats');
- const originalStatsText = stats?.textContent || '';
- if (stats) stats.textContent = 'Searching…';
- _libSearchInFlight = true;
- _setEmailSyncStatus({ loading: true });
- // Force a re-render so the "Searching…" empty-state shows (and any
- // existing "No emails" gets replaced) while the fetch is in flight.
- _renderGrid();
-
- const stillCurrent = () => (
- seq === _libSearchSeq &&
- q === _deriveSearchScope(state._libSearch).q &&
- accountAtStart === (state._libAccountId || '') &&
- folderAtStart === (_deriveSearchScope(state._libSearch).folder || state._libFolder || 'INBOX') &&
- // A local/index result can be opened while the slower provider search is
- // still running. Do not let that second response re-render the grid and
- // destroy the reader the user just opened.
- !document.querySelector('#email-lib-grid .email-card-expanded')
- );
- const searchUrl = (localOnly = false) => {
- const params = new URLSearchParams({
- folder: folderAtStart,
- q,
- limit: '100',
- scope: serverScopeAtStart,
- });
- if (accountAtStart) params.set('account_id', accountAtStart);
- if (localOnly) params.set('local_only', '1');
- return `${API_BASE}/api/email/search?${params.toString()}`;
- };
- const folderListUrl = () => {
- const params = new URLSearchParams({
- folder: folderAtStart,
- limit: '100',
- offset: '0',
- filter: state._libFilter || 'all',
- });
- if (accountAtStart) params.set('account_id', accountAtStart);
- return `${API_BASE}/api/email/list?${params.toString()}`;
- };
- const mergeSearchResults = (painted, incoming) => {
- const byKey = new Map();
- const out = [];
- const add = (em) => {
- if (!em) return;
- const key = `${em.account_id || accountAtStart || ''}:${em.folder || folderAtStart || ''}:${em.uid || em.message_id || JSON.stringify(em)}`;
- if (byKey.has(key)) return;
- byKey.set(key, em);
- out.push(em);
- };
- (painted || []).forEach(add);
- const additions = [];
- const addIncoming = (em) => {
- if (!em) return;
- const key = `${em.account_id || accountAtStart || ''}:${em.folder || folderAtStart || ''}:${em.uid || em.message_id || JSON.stringify(em)}`;
- if (byKey.has(key)) return;
- byKey.set(key, em);
- additions.push(em);
- };
- (incoming || []).forEach(addIncoming);
- additions.sort((a, b) => {
- const ad = Number(a?.date_epoch || 0);
- const bd = Number(b?.date_epoch || 0);
- if (bd !== ad) return bd - ad;
- return String(b?.date || '').localeCompare(String(a?.date || ''));
- });
- return out.concat(additions);
- };
- let paintedInterimResults = false;
- const paintSearchData = (data, interim = false) => {
- if (!stillCurrent()) return false;
- if (data.error) throw new Error(data.error);
- let results = data.emails || [];
- if (!interim && paintedInterimResults) {
- results = mergeSearchResults(state._libEmails || [], results);
- }
- if (!interim && paintedInterimResults && results.length === 0) {
- if (stats) {
- const count = state._libTotal || (state._libEmails || []).length;
- stats.textContent = `${count} cached match${count === 1 ? '' : 'es'}`;
- }
- _setEmailSyncStatus({
- updatedAt: data.sync?.updated_at || '',
- source: data.sync?.source || data.source || '',
- loading: false,
- });
- return true;
- }
- _libSearchHadResults = true;
- const pills = state._libSearchPills || [];
- const preservingBase = !!(_libServerSearchEmails && pills.length > 1);
- if (!preservingBase) {
- _libServerSearchEmails = results.slice();
- _libServerSearchTotal = Math.max(Number(data.total || 0), results.length);
- _libPreSearchEmails = results.slice();
- _libPreSearchTotal = _libServerSearchTotal;
- state._libEmails = results;
- state._libTotal = _libServerSearchTotal;
- } else {
- state._libEmails = _libServerSearchEmails.slice();
- state._libTotal = _libServerSearchTotal;
- }
- if (pills.length) {
- _applyPillFilter();
- if (!(state._libEmails || []).length && !preservingBase) state._libEmails = results;
- }
- _renderGrid();
- const count = Math.max(Number(data.total || 0), results.length);
- if (stats) {
- if (interim) {
- stats.textContent = `${count} cached match${count === 1 ? '' : 'es'} · searching…`;
- } else {
- const source = data.source === 'index' ? ' cached' : '';
- stats.textContent = `${count}${source} match${count === 1 ? '' : 'es'}`;
- }
- }
- _setEmailSyncStatus({
- updatedAt: interim ? '' : (data.sync?.updated_at || ''),
- source: data.sync?.source || data.source || '',
- loading: interim,
- });
- if (interim && results.length) paintedInterimResults = true;
- return true;
- };
-
- try {
- if (q.length < 2 && derived.forced) {
- const res = await fetch(folderListUrl());
- const data = await res.json();
- if (!stillCurrent()) return;
- paintSearchData({
- emails: (data.emails || []).map(em => ({ ...em, folder: folderAtStart })),
- total: data.total || (data.emails || []).length,
- source: 'folder',
- sync: { source: 'folder' },
- }, false);
- return;
- }
- const fullSearchPromise = fetch(searchUrl(false)).then(res => res.json());
- const localSearchPromise = fetch(searchUrl(true)).then(res => res.json());
- try {
- const localData = await localSearchPromise;
- if (!stillCurrent()) return;
- if (!localData.error && (localData.emails || []).length) {
- paintSearchData(localData, true);
- }
- } catch (_) {
- if (!stillCurrent()) return;
- }
-
- const data = await fullSearchPromise;
- if (!stillCurrent()) return;
- paintSearchData(data, false);
- } catch (e) {
- if (stats) stats.textContent = originalStatsText || 'Search failed';
- try { console.error('[email-search] fetch failed:', e); } catch {}
- } finally {
- _libSearchInFlight = false;
- _setEmailSyncStatus({ loading: false });
- // If the full search was intentionally ignored because its result landed
- // after the user opened a reader, finish the progress label without
- // touching the grid or collapsing that reader.
- const openReader = document.querySelector('#email-lib-grid .email-card-expanded');
- if (openReader && stats && /searching/i.test(stats.textContent || '')) {
- const count = state._libTotal || (state._libEmails || []).length;
- stats.textContent = `${count} cached match${count === 1 ? '' : 'es'}`;
- }
- }
- }
-
- // Custom dropdown for the email filter (All/Unread/Favorites/...). Replaces
- // the native <select> so each row can carry an SVG icon. The hidden
- // <select id="email-lib-filter"> stays as the value source — clicking a
- // menu item updates its value and dispatches 'change', so every existing
- // listener keeps working.
- const _EMAIL_FILTER_ICONS = {
- 'all': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>',
- 'unread': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><line x1="8" y1="16" x2="16" y2="8"/><line x1="8" y1="8" x2="16" y2="16"/></svg>',
- 'favorites': '<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>',
- 'undone': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="3"/></svg>',
- 'reminders': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.268 21a2 2 0 0 0 3.464 0"/><path d="M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"/></svg>',
- 'unanswered': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg>',
- 'pending_30d': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>',
- 'stale_30d': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="10" y1="14" x2="14" y2="18"/><line x1="14" y1="14" x2="10" y2="18"/></svg>',
- 'tag:urgent': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
- 'tag:reply-soon':'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/><circle cx="18" cy="6" r="2" fill="currentColor" stroke="none"/></svg>',
- 'tag:spam': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>',
- };
-
- function _filterIcon(value) {
- return _EMAIL_FILTER_ICONS[value] || _EMAIL_FILTER_ICONS['all'];
- }
-
- function _folderIcon(value) {
- const v = String(value || '').toLowerCase();
- if (value === '__scheduled__') {
- return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>';
- }
- if (v.includes('sent')) {
- return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>';
- }
- if (v.includes('star') || v.includes('favorite')) {
- return '<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>';
- }
- if (v.includes('archive') || v.includes('all mail')) {
- return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="5" rx="1"/><path d="M5 9v10h14V9"/><path d="M10 13h4"/></svg>';
- }
- if (v.includes('junk') || v.includes('spam')) {
- return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>';
- }
- if (v.includes('trash') || v.includes('bin')) {
- return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>';
- }
- if (v.includes('draft')) {
- return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>';
- }
- if (v === 'inbox' || v.includes('inbox')) {
- return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11Z"/></svg>';
- }
- return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>';
- }
-
- function _renderFolderPicker() {
- const sel = document.getElementById('email-lib-folder');
- const btn = document.getElementById('email-folder-btn');
- const menu = document.getElementById('email-folder-menu');
- if (!sel || !btn || !menu) return;
- const value = sel.value || state._libFolder || 'INBOX';
- const selectedOpt = [...sel.options].find(o => o.value === value && !o.disabled);
- const label = selectedOpt?.textContent || folderDisplayName(value);
- const iconWrap = btn.querySelector('.email-folder-current-icon');
- const labelEl = btn.querySelector('.email-folder-label');
- if (iconWrap) iconWrap.innerHTML = _folderIcon(value);
- if (labelEl) labelEl.textContent = label;
- const esc = s => String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
- const rows = [];
- for (const opt of sel.children) {
- if (opt.disabled) {
- rows.push('<div class="email-filter-group email-folder-group">Folders</div>');
- continue;
- }
- rows.push(`<button type="button" role="option" class="email-filter-item email-folder-item" data-value="${esc(opt.value)}">
- <span class="email-filter-item-icon">${_folderIcon(opt.value)}</span>
- <span class="email-filter-item-label">${esc(opt.textContent || folderDisplayName(opt.value))}</span>
- </button>`);
- }
- menu.innerHTML = rows.join('');
- }
-
- function _initFolderPicker() {
- const sel = document.getElementById('email-lib-folder');
- const picker = document.getElementById('email-folder-picker');
- const btn = document.getElementById('email-folder-btn');
- const menu = document.getElementById('email-folder-menu');
- if (!sel || !picker || !btn || !menu || picker._wired) return;
- picker._wired = true;
- let dismiss = () => {};
- const finishClose = () => {
- menu.hidden = true;
- btn.setAttribute('aria-expanded', 'false');
- dismiss = () => {};
- };
- const open = () => {
- const filterMenu = document.getElementById('email-filter-menu');
- const filterBtn = document.getElementById('email-filter-btn');
- filterMenu?._dismiss?.();
- if (filterMenu && !filterMenu.hidden) filterMenu.hidden = true;
- if (filterBtn) filterBtn.setAttribute('aria-expanded', 'false');
- _renderFolderPicker();
- menu.hidden = false;
- btn.setAttribute('aria-expanded', 'true');
- dismiss = bindMenuDismiss(menu, finishClose, e => !picker.contains(e.target));
- };
- btn.addEventListener('click', (e) => {
- e.stopPropagation();
- if (menu.hidden) open(); else dismiss();
- });
- menu.addEventListener('click', (e) => {
- const item = e.target.closest('.email-folder-item');
- if (!item) return;
- sel.value = item.dataset.value;
- sel.dispatchEvent(new Event('change', { bubbles: true }));
- dismiss();
- });
- document.addEventListener('click', (e) => {
- if (!menu.hidden && !picker.contains(e.target)) dismiss();
- });
- _renderFolderPicker();
- }
-
- function _renderFilterPickerCurrent() {
- const sel = document.getElementById('email-lib-filter');
- const btn = document.getElementById('email-filter-btn');
- if (!sel || !btn) return;
- const value = sel.value || 'all';
- const opt = sel.querySelector(`option[value="${CSS.escape(value)}"]`);
- const label = opt ? opt.textContent : value;
- const iconWrap = btn.querySelector('.email-filter-icon');
- const labelEl = btn.querySelector('.email-filter-label');
- if (iconWrap) iconWrap.innerHTML = _filterIcon(value);
- if (labelEl) labelEl.textContent = label;
- }
-
- function _initFilterPicker() {
- const sel = document.getElementById('email-lib-filter');
- const picker = document.getElementById('email-filter-picker');
- const btn = document.getElementById('email-filter-btn');
- const menu = document.getElementById('email-filter-menu');
- if (!sel || !picker || !btn || !menu || picker._wired) return;
- picker._wired = true;
-
- // Build menu from the hidden <select> contents (preserves optgroup labels).
- const items = [];
- for (const child of sel.children) {
- if (child.tagName === 'OPTGROUP') {
- items.push({ group: child.label });
- for (const o of child.children) {
- items.push({ value: o.value, label: o.textContent, group: child.label });
- }
- } else if (child.tagName === 'OPTION') {
- items.push({ value: child.value, label: child.textContent });
- }
- }
- menu.innerHTML = '<div class="email-filter-menu-title">Filter by...</div>' + items.map(it => {
- if (!it.value) {
- return `<div class="email-filter-group">${it.group}</div>`;
- }
- return `<button type="button" role="option" class="email-filter-item" data-value="${it.value}">
- <span class="email-filter-item-icon">${_filterIcon(it.value)}</span>
- <span class="email-filter-item-label">${it.label}</span>
- </button>`;
- }).join('');
-
- let dismiss = () => {};
- const finishClose = () => {
- menu.hidden = true;
- btn.setAttribute('aria-expanded', 'false');
- dismiss = () => {};
- };
- const open = () => {
- const folderMenu = document.getElementById('email-folder-menu');
- const folderBtn = document.getElementById('email-folder-btn');
- folderMenu?._dismiss?.();
- if (folderMenu && !folderMenu.hidden) folderMenu.hidden = true;
- if (folderBtn) folderBtn.setAttribute('aria-expanded', 'false');
- menu.hidden = false;
- btn.setAttribute('aria-expanded', 'true');
- dismiss = bindMenuDismiss(menu, finishClose, e => !picker.contains(e.target));
- };
- btn.addEventListener('click', (e) => {
- e.stopPropagation();
- if (menu.hidden) open(); else dismiss();
- });
- menu.addEventListener('click', (e) => {
- const item = e.target.closest('.email-filter-item');
- if (!item) return;
- sel.value = item.dataset.value;
- sel.dispatchEvent(new Event('change', { bubbles: true }));
- dismiss();
- });
- document.addEventListener('click', (e) => {
- if (!menu.hidden && !picker.contains(e.target)) dismiss();
- });
- _renderFilterPickerCurrent();
- }
-
- function _renderEmailLoading(grid) {
- if (!grid) return null;
- grid.innerHTML = '';
- const wrap = document.createElement('div');
- wrap.className = 'email-list-skeleton';
- wrap.setAttribute('aria-label', 'Loading emails');
- wrap.innerHTML = Array.from({ length: 8 }, (_, idx) => `
- <div class="email-skeleton-row${idx % 3 === 2 ? ' compact' : ''}">
- <span class="email-skeleton-dot"></span>
- <div class="email-skeleton-lines">
- <span class="email-skeleton-line title"></span>
- <span class="email-skeleton-line meta"></span>
- </div>
- <span class="email-skeleton-line date"></span>
- </div>
- `).join('');
- grid.appendChild(wrap);
- return null;
- }
-
- function _emailReaderSkeletonHtml() {
- return `
- <div class="email-reader-skeleton" aria-label="Loading email">
- <div class="email-reader-skeleton-header">
- <span class="email-skeleton-line chip"></span>
- <span class="email-skeleton-line chip short"></span>
- <span class="email-skeleton-line action"></span>
- <span class="email-skeleton-line action"></span>
- <span class="email-skeleton-line action"></span>
- </div>
- <div class="email-reader-skeleton-atts">
- <span class="email-skeleton-line attachment"></span>
- <span class="email-skeleton-line attachment short"></span>
- </div>
- <div class="email-reader-skeleton-body">
- <span class="email-skeleton-line body wide"></span>
- <span class="email-skeleton-line body"></span>
- <span class="email-skeleton-line body medium"></span>
- <span class="email-skeleton-line body gap"></span>
- <span class="email-skeleton-line body wide"></span>
- <span class="email-skeleton-line body medium"></span>
- <span class="email-skeleton-line body"></span>
- <span class="email-skeleton-line body wide"></span>
- <span class="email-skeleton-line body medium"></span>
- <span class="email-skeleton-line body gap"></span>
- <span class="email-skeleton-line body"></span>
- <span class="email-skeleton-line body wide"></span>
- <span class="email-skeleton-line body short"></span>
- </div>
- </div>
- `;
- }
-
- function _appendEmailSearchProgressRow(grid) {
- if (!grid || !_libSearchInFlight || grid.querySelector('.email-search-progress-row')) return;
- const row = document.createElement('div');
- row.className = 'email-search-progress-row';
- row.innerHTML = `
- <span class="email-search-progress-dot"></span>
- <span>Searching more mail...</span>
- `;
- grid.appendChild(row);
- }
-
- // Refreshes the small accent-pill in the modal title with the unread count
- // for the current folder. When the inbox is currently filtered to unread, the
- // pill flips to show the total-emails count + "all" label, because clicking
- // it would toggle the filter off — so the label needs to advertise the
- // action, not the now-current view. Uses the cheap unread-state endpoint for
- // the normal badge; silent on failure.
- async function _refreshUnreadBadge({ unreadCountOverride = null, preserveAutoReplyTitle = false, syncAutoReplyTitle = false } = {}) {
- const badge = document.getElementById('email-lib-unread-badge');
- if (!badge) return;
- const refreshSeq = ++_autoReplyRefreshSeq;
- const accountAtStart = String(state._libAccountId || '');
- try {
- const folder = state._libFolder || 'INBOX';
- const autoReplyBadge = document.getElementById('email-lib-auto-reply-badge');
- if (folder === '__scheduled__') {
- badge.style.display = 'none';
- if (syncAutoReplyTitle && !preserveAutoReplyTitle) _syncEmailAutoReplyTitle(false);
- return;
- }
- const cfg = await _fetchEmailSettingsConfig().catch(() => null);
- // Several mailbox/account refreshes can overlap while the settings page
- // is saving. Do not let an older response restore the previous account's
- // Auto Reply state after the current account has already changed.
- if (refreshSeq !== _autoReplyRefreshSeq || accountAtStart !== String(state._libAccountId || '')) return;
- if (!cfg) return;
- const awayActive = _isAutoReplyActiveForCurrentAccount(cfg);
- if (!preserveAutoReplyTitle) {
- const awayChanged = state._libAutoReplyActive !== awayActive;
- state._libAutoReplyActive = awayActive;
- if (awayChanged) _renderAccountsStrip();
- if (syncAutoReplyTitle && typeof state._libAutoReplyDraftActive !== 'boolean') {
- _syncEmailAutoReplyTitle(awayActive);
- }
- }
- if (autoReplyBadge) {
- autoReplyBadge.title = awayActive ? 'Auto Reply is active - open settings' : 'Auto Reply is off';
- }
- let n;
- if (unreadCountOverride !== null && unreadCountOverride !== undefined) {
- n = Math.max(0, Number(unreadCountOverride) || 0);
- } else {
- const res = await fetch(emailApiUrl('/api/email/unread-state', {
- folder,
- account_id: state._libAccountId || undefined,
- }));
- const data = await res.json();
- n = data.unread_count || 0;
- }
- _syncUnreadTabBadge(n);
- if (folder === 'INBOX') _syncCurrentAccountUnreadCount(n);
- badge.classList.remove('email-lib-away-badge');
- if (state._libFilter === 'unread') {
- // Currently viewing unread — show what the click will take you to.
- try {
- const allRes = await fetch(`${API_BASE}/api/email/list?folder=${encodeURIComponent(folder)}${_acct()}&limit=1&filter=all`);
- const allData = await allRes.json();
- const t = allData.total || 0;
- badge.textContent = `${t} all`;
- badge.title = 'Show all emails';
- badge.dataset.mode = 'unread';
- badge.style.display = '';
- } catch (_) {
- badge.textContent = 'Show all';
- badge.title = 'Show all emails';
- badge.dataset.mode = 'unread';
- badge.style.display = '';
- }
- } else if (n > 0) {
- badge.textContent = n > 999 ? '999+ unread' : `${n} unread`;
- badge.title = 'Show unread emails';
- badge.dataset.mode = 'unread';
- badge.style.display = '';
- } else {
- delete badge.dataset.mode;
- badge.style.display = 'none';
- }
- } catch (_) { _syncUnreadTabBadge(0); }
- }
-
- async function _loadEmails({ force = false, useCache = true } = {}) {
- const seq = ++_libLoadSeq;
- state._libLoading = true;
- const accountAtStart = state._libAccountId || '';
- const folderAtStart = state._libFolder;
- const filterAtStart = state._libFilter;
- const offsetAtStart = state._libOffset;
- const searchAtStart = state._libSearch;
- const hasAttachmentsAtStart = state._libHasAttachments;
- const dateFromAtStart = state._libDateFrom || '';
- const dateToAtStart = state._libDateTo || '';
-
- const grid = document.getElementById('email-lib-grid');
- if (!grid) { if (seq === _libLoadSeq) state._libLoading = false; return; }
-
- // SWR: when loading the first page of a real folder with no search,
- // paint the cached list immediately (no spinner, no blank grid) and
- // then quietly refetch behind it. Pagination, search, and the
- // scheduled virtual folder skip the cache and use the old spinner
- // path. `force` (Refresh button) can still consult the cache for
- // perceptual continuity, but adds a cache-buster so the server's 8s
- // list cache is bypassed too. Account/folder/filter changes pass
- // `useCache: false` so stale rows from the previous view never flash.
- const cacheable =
- offsetAtStart === 0 &&
- !searchAtStart &&
- folderAtStart !== '__scheduled__';
- const ck = cacheable ? _libCacheKey() : null;
- const cachedCandidate = (useCache && cacheable) ? _libCacheGet(ck) : null;
- // Do not paint a cached empty result while a forced refresh is already
- // underway. A transient provider failure can cache an empty tag filter;
- // rendering it first flashes "No emails" before the fresh rows arrive.
- const cached = cachedCandidate
- && Array.isArray(cachedCandidate.emails)
- && cachedCandidate.emails.length
- ? cachedCandidate
- : null;
- let paintedExisting = Boolean(cached || state._libEmails.length);
- const paintData = (data, { cacheSource = false } = {}) => {
- state._libEmails = data.emails || [];
- state._libTotal = data.total || 0;
- _libRenderedViewKey = ck || '';
- const sync = data.sync || {};
- const _activePills = (state._libSearchPills || []).length > 0
- || (state._libSearchDraft || '').length > 0;
- if (_activePills) {
- _libPreSearchEmails = state._libEmails.slice();
- _libPreSearchTotal = state._libTotal;
- _applyPillFilter();
- } else {
- _renderGrid();
- }
- const stats = document.getElementById('email-lib-stats');
- if (stats) stats.textContent = `${state._libTotal} emails`;
- _setEmailSyncStatus({
- updatedAt: sync.updated_at || '',
- source: sync.source || (cacheSource ? 'client_cache' : ''),
- loading: false,
- });
- if (cacheable && !cacheSource) {
- _libCachePut(ck, { emails: state._libEmails.slice(), total: state._libTotal, sync });
- }
- };
-
- let sp = null;
- if (cached) {
- // Suppress the open-cascade animation when we're painting from
- // cache — the data was already on screen a moment ago, so sliding
- // each card in fresh feels janky. Also prevents the cascade from
- // re-firing when the bg refetch lands within the 900ms cleanup
- // window and appends new card nodes into the still-classed grid.
- state._libJustOpened = false;
- const grid2 = document.getElementById('email-lib-grid');
- if (grid2) grid2.classList.remove('email-lib-just-opened');
- paintData(cached, { cacheSource: true });
- paintedExisting = true;
- if (force) _setEmailSyncStatus({ loading: true });
- if (!force) return;
- } else if (state._libEmails.length && cacheable) {
- _renderGrid();
- _setEmailSyncStatus({ loading: true });
- paintedExisting = true;
- } else {
- sp = _renderEmailLoading(grid);
- }
-
- try {
- _syncUnreadWindowGlow();
- if (folderAtStart === '__scheduled__') {
- await _loadScheduled(grid, sp);
- } else {
- const accountQS = accountAtStart ? `&account_id=${encodeURIComponent(accountAtStart)}` : '';
- const attQS = hasAttachmentsAtStart ? '&has_attachments=1' : '';
- const dateQS = `${dateFromAtStart ? `&date_from=${encodeURIComponent(dateFromAtStart)}` : ''}${dateToAtStart ? `&date_to=${encodeURIComponent(dateToAtStart)}` : ''}`;
- if (!cached && cacheable && !force) {
- const ctrl = new AbortController();
- const timer = setTimeout(() => ctrl.abort(), 450);
- try {
- const fastRes = await fetch(`${API_BASE}/api/email/list?folder=${encodeURIComponent(folderAtStart)}${accountQS}&limit=${_LIB_INITIAL_PAGE_SIZE}&offset=${offsetAtStart}&filter=${filterAtStart}${attQS}&cached_only=1`, {
- signal: ctrl.signal,
- });
- const fastData = await fastRes.json().catch(() => null);
- if (seq === _libLoadSeq
- && accountAtStart === (state._libAccountId || '')
- && fastData
- && !fastData.error
- && Array.isArray(fastData.emails)
- && fastData.emails.length) {
- if (sp) { sp.destroy(); sp = null; }
- state._libJustOpened = false;
- grid.classList.remove('email-lib-just-opened');
- paintData(fastData);
- paintedExisting = true;
- if (!force) return;
- }
- } catch (_) {
- // Cold index miss/timeout: leave the spinner and continue to IMAP.
- } finally {
- clearTimeout(timer);
- }
- }
- // `refresh=1` is the explicit manual-refresh contract: the server
- // evicts its list cache, drops the pooled IMAP handle, and refetches
- // visible rows instead of trusting the durable index. `&_=...` remains
- // as a browser/proxy cache-buster.
- const buster = force ? `&refresh=1&_=${Date.now()}` : '';
- const res = await fetch(`${API_BASE}/api/email/list?folder=${encodeURIComponent(folderAtStart)}${accountQS}&limit=${_LIB_INITIAL_PAGE_SIZE}&offset=${offsetAtStart}&filter=${filterAtStart}${attQS}${dateQS}${buster}`);
- const data = await res.json();
- if (seq !== _libLoadSeq || accountAtStart !== (state._libAccountId || '')) return;
- if (data.error) throw new Error(data.error);
- const sync = data.sync || {};
- if (sp) sp.destroy();
- paintData({ emails: data.emails || [], total: data.total || 0, sync });
- if (filterAtStart === 'unread') {
- _refreshUnreadBadge({ unreadCountOverride: data.total || 0 });
- } else {
- _refreshUnreadBadge();
- _refreshAccountUnreadHighlights().catch(() => {});
- }
- }
- } catch (e) {
- if (seq !== _libLoadSeq || accountAtStart !== (state._libAccountId || '')) return;
- if (sp) sp.destroy();
- // If we already painted the cached list, leave it on screen — beats
- // wiping it for "Failed to load" when there's still readable content.
- if (!paintedExisting) {
- const msg = e && e.message ? `Failed to load: ${e.message}` : 'Failed to load';
- grid.innerHTML = `<div class="email-loading">${_esc(msg)}${_emailSetupHintHtml()}</div>`;
- _wireEmailSetupHint(grid);
- }
- } finally {
- if (seq === _libLoadSeq) state._libLoading = false;
- }
- }
-
- async function _loadScheduled(grid, sp) {
- const res = await fetch(`${API_BASE}/api/email/scheduled`);
- const data = await res.json();
- if (sp) sp.destroy();
- const items = data.scheduled || [];
- grid.innerHTML = '';
- const stats = document.getElementById('email-lib-stats');
- if (stats) stats.textContent = `${items.length} scheduled`;
- _setEmailSyncStatus({
- updatedAt: new Date().toISOString(),
- source: 'local',
- loading: false,
- });
-
- if (items.length === 0) {
- grid.innerHTML = '<div class="email-loading">No scheduled emails</div>';
- return;
- }
-
- for (const it of items) {
- const card = document.createElement('div');
- card.className = 'doclib-card memory-item';
-
- const sendDate = new Date(it.send_at);
- const dateStr = sendDate.toLocaleString([], {
- month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'
- });
-
- const content = document.createElement('div');
- content.style.cssText = 'flex:1;min-width:0;';
- const subject = it.subject || '(no subject)';
- const toDisplay = it.to || '(no recipient)';
-
- content.innerHTML = `
- <div style="display:flex;align-items:center;gap:6px;">
- <span class="memory-item-title">${_esc(subject)}</span>
- ${it.status === 'failed' ? '<span style="font-size:9px;color:var(--red);border:1px solid var(--red);padding:1px 4px;border-radius:4px;">FAILED</span>' : '<span style="font-size:9px;opacity:0.6;border:1px solid var(--border);padding:1px 4px;border-radius:4px;">PENDING</span>'}
- </div>
- <div style="font-size:10px;opacity:0.7;margin-top:2px;">
- To: ${_esc(toDisplay)} · Sends ${_esc(dateStr)}
- </div>
- ${it.error ? `<div style="font-size:10px;color:var(--red);margin-top:2px;">${_esc(it.error)}</div>` : ''}
- `;
- card.appendChild(content);
-
- // Cancel button
- const cancelBtn = document.createElement('button');
- cancelBtn.className = 'memory-item-btn';
- cancelBtn.title = 'Cancel scheduled send';
- cancelBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
- cancelBtn.addEventListener('click', async (e) => {
- e.stopPropagation();
- const { styledConfirm } = await import('./ui.js?v=20260916largetoolscroll1');
- const ok = await styledConfirm(`Cancel scheduled email "${subject}"?`, { confirmText: 'Cancel Send', cancelText: 'Keep', danger: true });
- if (!ok) return;
- try {
- await fetch(`${API_BASE}/api/email/scheduled/${it.id}`, { method: 'DELETE' });
- _loadEmails();
- } catch (err) { console.error(err); }
- });
- const actionsWrap = document.createElement('div');
- actionsWrap.className = 'memory-item-actions';
- actionsWrap.appendChild(cancelBtn);
- card.appendChild(actionsWrap);
-
- grid.appendChild(card);
- }
- }
-
- function _emailDateBucketLabel(value) {
- if (!value) return 'Older';
- const d = new Date(value);
- if (Number.isNaN(d.getTime())) return 'Older';
- const dayStart = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
- const now = new Date();
- const today = dayStart(now);
- const day = dayStart(d);
- const diff = Math.round((today - day) / 86400000);
- if (diff === 0) return 'Today';
- if (diff === 1) return 'Yesterday';
- if (diff > 1 && diff < 7) return d.toLocaleDateString([], { weekday: 'long' });
- if (diff >= 365) {
- const years = Math.floor(diff / 365);
- return `${years} ${years === 1 ? 'year' : 'years'} ago`;
- }
- if (diff >= 180) return '6 months ago';
- if (diff >= 30) return `${Math.floor(diff / 30) * 30} days ago`;
- const sameYear = d.getFullYear() === now.getFullYear();
- return d.toLocaleDateString([], sameYear ? { month: 'long', day: 'numeric' } : { month: 'long', day: 'numeric', year: 'numeric' });
- }
-
- function _createEmailDateHeader(label, timelineBreak = false) {
- const el = document.createElement('div');
- el.className = 'date-section-header email-date-section-header' + (timelineBreak ? ' email-date-gap-break' : '');
- el.textContent = label;
- return el;
- }
-
- // Add breathing room only for an unexpected hole in an otherwise dense
- // timeline. A uniformly sparse archive should remain compact, even when its
- // dates are months apart.
- function _emailTimelineGapThreshold(items) {
- const dates = items.map(em => new Date(em?.date).getTime()).filter(Number.isFinite);
- const gaps = [];
- for (let i = 1; i < dates.length; i++) {
- const gap = Math.abs(dates[i - 1] - dates[i]) / 86400000;
- if (gap > 0) gaps.push(gap);
- }
- if (!gaps.length) return 90;
- gaps.sort((a, b) => a - b);
- const middle = Math.floor(gaps.length / 2);
- const median = gaps.length % 2 ? gaps[middle] : (gaps[middle - 1] + gaps[middle]) / 2;
- return Math.max(90, median * 2.5);
- }
-
- function _dateGroupEmailsWithPinned(items, mode = 'recent') {
- const ordered = [];
- let groupLabel = null;
- let groupItems = [];
- const priority = (em) => {
- if (mode === 'unread') return Number(!em?.is_read);
- return Number(!!em?.is_flagged);
- };
- const flushGroup = () => {
- if (!groupItems.length) return;
- ordered.push(...groupItems.map((em, idx) => ({ em, idx }))
- .sort((a, b) => priority(b.em) - priority(a.em) || a.idx - b.idx)
- .map(item => item.em));
- groupItems = [];
- };
- for (const em of items) {
- const label = _emailDateBucketLabel(em?.date);
- if (label !== groupLabel) {
- flushGroup();
- groupLabel = label;
- }
- groupItems.push(em);
- }
- flushGroup();
- return ordered;
- }
-
- function _renderGrid() {
- const grid = document.getElementById('email-lib-grid');
- if (!grid) return;
- const modal = document.getElementById('email-lib-modal');
- // A background mailbox refresh must not destroy the reader currently being
- // viewed. Clearing the grid here removes the expanded card while leaving
- // `.email-reading` on the modal, which produces a headerless full email
- // list. Explicit folder/account/search changes call the reset helper first.
- if (grid.querySelector('.doclib-card-expanded, .email-card-expanded')) return;
- if (modal?.classList.contains('email-reading')) {
- modal.classList.remove('email-reading');
- modal.style.removeProperty('--email-reading-modal-min-h');
- }
- grid.innerHTML = '';
-
- let filtered = state._libEmails;
- try { console.log('[email-search] _renderGrid: state._libEmails.length=', (state._libEmails || []).length, 'pills=', (state._libSearchPills || []).length, 'draft=', JSON.stringify(state._libSearchDraft || ''), 'libSearch=', JSON.stringify(state._libSearch || '')); } catch {}
- _syncSearchOptionsMenu();
-
- // 'recent' is the default order from the API. Date stays the primary
- // grouping; unread/favorite priorities float inside each date section.
- filtered = _dateGroupEmailsWithPinned([...filtered], state._libSort);
-
- if (filtered.length === 0) {
- // Active search — don't flash "No emails": the IMAP fetch is still
- // running. Show a "Searching…" placeholder until _doSearch resolves
- // and renders again. Without this the user saw an empty state
- // smiley for ~500ms between the optimistic pill-filter clear and
- // the server response landing.
- if (_libSearchInFlight) {
- _renderEmailLoading(grid);
- return;
- }
- // Inbox-zero is a win — pair the message with a small smiley so the
- // empty state reads as "all caught up", not "something's broken".
- const _smileyIco = '<span style="vertical-align:-3px;margin-left:6px;">' + emptyStateIcon('smiley') + '</span>';
- // Only show the "Set up at Settings › Integrations" hint when the inbox
- // is TRULY empty — no filter, no search, no source emails. A sub-filter
- // (reminders, unread, etc.) that happens to be empty isn't a setup
- // problem; the link there reads as nonsense.
- const _isTrulyEmpty = (
- state._libEmails.length === 0
- && (!state._libFilter || state._libFilter === 'all')
- && !(state._libSearch || '').trim()
- );
- if (_isTrulyEmpty) {
- grid.innerHTML =
- '<div class="email-loading" style="display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;text-align:center;">' +
- '<span>No emails' + _smileyIco + '</span>' +
- '<span style="opacity:0.7;font-size:11px;">' +
- 'Set up at: <a href="#" data-open-settings="integrations" style="color:var(--accent,var(--red));text-decoration:underline;">Settings &rsaquo; Integrations</a>' +
- '</span>' +
- '</div>';
- const _link = grid.querySelector('[data-open-settings]');
- if (_link) _link.addEventListener('click', (e) => {
- e.preventDefault();
- _openSettingsTab(_link.dataset.openSettings || 'integrations');
- });
- } else {
- grid.innerHTML =
- '<div class="email-loading" style="display:flex;align-items:center;justify-content:center;gap:8px;flex-wrap:wrap;">' +
- '<span>No emails' + _smileyIco + '</span>' +
- '</div>';
- }
- return;
- }
-
- // Cascade-on-open: fire the same domino-in animation the sidebar
- // section uses. Only on the FIRST grid render after the library is
- // opened — subsequent re-renders (filter/sort/search) need to be
- // instant.
- if (state._libJustOpened) {
- grid.classList.add('email-lib-just-opened');
- state._libJustOpened = false;
- // Strip the class after the cascade so it doesn't restrict later
- // animations (e.g. the FLIP reflow when archiving). Worst-case
- // duration matches the longest delay in the keyframe set below.
- setTimeout(() => grid.classList.remove('email-lib-just-opened'), 900);
- }
- let lastDateLabel = null;
- const timelineGapThreshold = _emailTimelineGapThreshold(filtered);
- let previousEmailTime = null;
- for (const em of filtered) {
- const dateLabel = _emailDateBucketLabel(em?.date);
- if (dateLabel !== lastDateLabel) {
- const emailTime = new Date(em?.date).getTime();
- const gapDays = Number.isFinite(previousEmailTime) && Number.isFinite(emailTime)
- ? Math.abs(previousEmailTime - emailTime) / 86400000
- : 0;
- const timelineBreak = gapDays > 90 && gapDays > timelineGapThreshold;
- grid.appendChild(_createEmailDateHeader(dateLabel, timelineBreak));
- lastDateLabel = dateLabel;
- }
- grid.appendChild(_createCard(em));
- const emailTime = new Date(em?.date).getTime();
- if (Number.isFinite(emailTime)) previousEmailTime = emailTime;
- }
- _appendEmailSearchProgressRow(grid);
-
- // If a deep-link asked us to expand a specific email, do it when the card
- // exists. Keep the UID through cached paints so a later fresh load can
- // still expand a newly-sent message that was absent from the cache.
- if (state._libPendingExpandUid) {
- const target = filtered.find(e => String(e.uid) === String(state._libPendingExpandUid));
- const wantUid = state._libPendingExpandUid;
- if (target) {
- const cards = grid.querySelectorAll('.doclib-card');
- const targetCard = Array.from(cards).find(c => c.dataset.uid === String(wantUid));
- if (targetCard) {
- state._libPendingExpandUid = null;
- requestAnimationFrame(() => _toggleCardPreview(targetCard, target));
- }
- }
- }
- }
-
- function _createCard(em) {
- _normalizeEmailStateFlags(em);
- const card = document.createElement('div');
- let cls = 'doclib-card memory-item';
- if (em.is_answered) cls += ' email-card-answered';
- else if (!em.is_read) cls += ' email-card-unread';
- card.className = cls;
- card.dataset.uid = String(em.uid);
- card.dataset.emailAccount = String(em.account_id || state._libAccountId || '');
- const cardFolder = _hasActiveEmailSearchResults()
- ? (em.folder || state._libFolder || 'INBOX')
- : (state._libFolder || em.folder || 'INBOX');
- card.dataset.emailFolder = String(cardFolder);
- if (state._selectMode && state._selectedUids.has(em.uid)) card.classList.add('selected');
-
- // Checkbox in select mode
- if (state._selectMode) {
- const cb = document.createElement('input');
- cb.type = 'checkbox';
- cb.className = 'memory-select-cb';
- cb.checked = state._selectedUids.has(em.uid);
- cb.addEventListener('click', e => e.stopPropagation());
- cb.addEventListener('change', () => {
- if (cb.checked) state._selectedUids.add(em.uid);
- else state._selectedUids.delete(em.uid);
- card.classList.toggle('selected', cb.checked);
- _updateBulkBar();
- });
- card.appendChild(cb);
- }
-
- // In Sent results, show the recipient(s) — the sender is always you and
- // hides the actually useful info. Search results can be stamped with their
- // real folder while the visible folder selector still says INBOX, so the
- // selected mailbox remains authoritative for normal folder views.
- const isSentFolderEarly = /sent/i.test(cardFolder);
- let senderName;
- let senderAddress;
- if (isSentFolderEarly) {
- senderName = _formatRecipients(em.to) || em.to || '(no recipient)';
- // First address out of em.to for click-to-pill targeting.
- const _firstTo = String(em.to || '').split(',')[0] || '';
- const _m = _firstTo.match(/<([^>]+)>/);
- senderAddress = (_m ? _m[1] : _firstTo).trim();
- } else {
- senderName = em.from_name || em.from_address;
- senderAddress = em.from_address || '';
- }
- const color = _senderColor(senderName);
-
- let dateStr = '';
- if (em.date) {
- try {
- const d = new Date(em.date);
- const now = new Date();
- const sameYear = d.getFullYear() === now.getFullYear();
- const dateOpts = sameYear
- ? { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }
- : { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' };
- dateStr = d.toLocaleString([], dateOpts);
- } catch (_) {}
- }
-
- const content = document.createElement('div');
- content.style.cssText = 'flex:1;min-width:0;';
-
- const titleRow = document.createElement('div');
- titleRow.className = 'email-card-titlerow';
- titleRow.style.cssText = 'display:flex;align-items:center;gap:6px;';
-
- const titleEl = document.createElement('span');
- titleEl.className = 'memory-item-title';
- titleEl.textContent = em.subject || '(no subject)';
- // Hover preview: surface the cached AI summary directly on the title via
- // a native browser tooltip — no need to open the email to skim it.
- if (em.cached_summary) {
- titleEl.title = em.cached_summary;
- titleEl.classList.add('email-card-has-summary');
- }
- titleRow.appendChild(titleEl);
- const cardChevron = document.createElement('span');
- cardChevron.className = 'doclib-card-chevron';
- cardChevron.setAttribute('aria-hidden', 'true');
- cardChevron.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>';
-
- const isSentFolder = /sent/i.test(cardFolder);
- const statusCluster = document.createElement('span');
- statusCluster.className = 'email-card-status';
- statusCluster.setAttribute('aria-label', 'Email status');
-
- if (em.has_attachments) {
- const att = document.createElement('span');
- att.className = 'email-card-attachment';
- att.title = 'Has attachments';
- att.style.cssText = 'opacity:0.6;flex-shrink:0;display:inline-flex;';
- att.innerHTML = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 17.93 8.8l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>';
- statusCluster.appendChild(att);
- }
-
- const tags = state._libShowTags ? _visibleEmailTagsForRender(em) : [];
- if (state._libShowTags && (tags.length || em.is_spam_verdict)) {
- const tagWrap = document.createElement('span');
- tagWrap.className = 'email-tags email-card-tags' + (tags.length > 2 ? ' email-tags-collapsed' : '');
- tagWrap.innerHTML = _emailTagGroupHtml(tags, em);
- if (em.is_spam_verdict) {
- tagWrap.insertAdjacentHTML('beforeend', '<span class="email-tag email-tag-spam">spam</span>');
- }
- let moreBtn = tagWrap.querySelector('[data-email-tags-more]');
- if (moreBtn) {
- const tintSource = tagWrap.querySelector('.email-tag');
- requestAnimationFrame(() => {
- if (tintSource?.isConnected) moreBtn.style.setProperty('--email-tags-more-color', getComputedStyle(tintSource).color);
- });
- }
- tagWrap.addEventListener('click', (ev) => {
- if (state._selectMode) return;
- const calBtn = ev.target.closest('[data-calendar-event-uid]');
- const tagBtn = ev.target.closest('[data-email-filter-tag]');
- const moreBtn = ev.target.closest('[data-email-tags-more]');
- if (!calBtn && !tagBtn && !moreBtn) return;
- ev.preventDefault();
- ev.stopPropagation();
- if (moreBtn) {
- const expanded = tagWrap.classList.toggle('email-tags-expanded');
- moreBtn.setAttribute('aria-expanded', expanded ? 'true' : 'false');
- const pills = tagWrap.querySelectorAll(':scope > .email-tag, :scope > .email-tag-extra');
- if (expanded) {
- tagWrap.style.flexWrap = 'wrap';
- pills.forEach(pill => { pill.style.display = 'inline-flex'; });
- moreBtn.style.display = 'inline-flex';
- } else {
- tagWrap.style.flexWrap = '';
- pills.forEach(pill => { pill.style.display = ''; });
- moreBtn.style.display = '';
- requestAnimationFrame(() => _fitEmailCardTags(titleRow));
- }
- } else if (calBtn) _openCalendarEventFromEmail(calBtn.dataset.calendarEventUid);
- else _applyTagFilterFromPill(tagBtn.dataset.emailFilterTag);
- });
- titleRow.appendChild(tagWrap);
- }
-
- // Keep the status controls in one right-aligned cluster. Favorite is always
- // present as an outline so it is discoverable before activation.
- if (!isSentFolder) {
- const doneCheck = document.createElement('span');
- doneCheck.className = 'email-card-done' + (em.is_answered ? ' active' : '');
- doneCheck.title = em.is_answered ? 'Mark not done' : 'Mark done';
- doneCheck.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
- const _toggleDone = async (e) => {
- if (e) e.stopPropagation();
- // Use the visible class as source of truth — em.is_answered could
- // be stale from a background sync, which would leave the user
- // clicking and seeing no UI change.
- const wasActive = doneCheck.classList.contains('active');
- const newState = !wasActive;
- em.is_answered = newState;
- doneCheck.classList.toggle('active', newState);
- doneCheck.title = newState ? 'Mark not done' : 'Mark done';
- // Animate in both directions so the user gets explicit feedback when
- // un-checking too — without this the hover state and the active state
- // look identical, so the click felt like a no-op.
- doneCheck.classList.remove('just-checked', 'just-unchecked');
- void doneCheck.offsetWidth; // restart animation
- doneCheck.classList.add(newState ? 'just-checked' : 'just-unchecked');
- setTimeout(() => doneCheck.classList.remove('just-checked', 'just-unchecked'), 500);
- if (newState) {
- _clearDoneResponseTagsLocal(em);
- titleRow.querySelectorAll('.email-tag-urgent, .email-tag-reply-soon, .email-tag-action-needed').forEach(n => n.remove());
- _syncEmailReadState(em.uid, true);
- }
- try {
- if (newState) {
- await fetch(`${API_BASE}/api/email/mark-answered/${em.uid}?folder=${encodeURIComponent(cardFolder)}${_acct()}`, { method: 'POST' });
- await fetch(`${API_BASE}/api/email/mark-read/${em.uid}?folder=${encodeURIComponent(cardFolder)}${_acct()}`, { method: 'POST' });
- } else {
- await fetch(`${API_BASE}/api/email/clear-answered/${em.uid}?folder=${encodeURIComponent(cardFolder)}${_acct()}`, { method: 'POST' });
- }
- } catch (err) { console.error(err); }
- };
- doneCheck.addEventListener('click', _toggleDone);
- statusCluster.appendChild(doneCheck);
- }
-
- const favoriteToggle = document.createElement('button');
- favoriteToggle.type = 'button';
- favoriteToggle.className = 'email-card-favorite' + (em.is_flagged ? ' active' : '');
- favoriteToggle.title = em.is_flagged ? 'Unfavorite' : 'Favorite';
- favoriteToggle.setAttribute('aria-label', favoriteToggle.title);
- favoriteToggle.setAttribute('aria-pressed', em.is_flagged ? 'true' : 'false');
- favoriteToggle.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="' + (em.is_flagged ? 'currentColor' : 'none') + '" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>';
- favoriteToggle.addEventListener('click', async (e) => {
- e.preventDefault();
- e.stopPropagation();
- const next = !em.is_flagged;
- const favoritesView = state._libFilter === 'favorites';
- const previousIndex = state._libEmails.findIndex(item => item === em);
- em.is_flagged = next;
- // The Favorites mailbox is already a server-filtered snapshot. Remove an
- // unfavorited row locally so the click has immediate, visible feedback.
- if (favoritesView && !next) {
- state._libEmails = state._libEmails.filter(item => item !== em);
- }
- _renderGrid();
- try {
- const res = await fetch(`${API_BASE}/api/email/flag/${em.uid}?folder=${encodeURIComponent(cardFolder)}${_acct()}&on=${next ? 'true' : 'false'}`, { method: 'POST' });
- const data = await res.json().catch(() => null);
- if (!res.ok || data?.success === false) throw new Error(data?.error || `HTTP ${res.status}`);
- _libCacheWriteBack();
- } catch (err) {
- em.is_flagged = !next;
- if (favoritesView && !next && previousIndex >= 0) {
- state._libEmails.splice(previousIndex, 0, em);
- }
- _renderGrid();
- console.error('Failed to toggle favorite:', err);
- }
- });
- const doneControl = statusCluster.querySelector('.email-card-done');
- if (doneControl) statusCluster.insertBefore(favoriteToggle, doneControl);
- else statusCluster.appendChild(favoriteToggle);
-
- if (!isSentFolder && !em.is_read) {
- const dot = document.createElement('span');
- dot.className = 'email-card-unread-dot';
- dot.style.cssText = `width:6px;height:6px;border-radius:50%;background:${color};flex-shrink:0;margin-left:2px;`;
- statusCluster.appendChild(dot);
- }
- titleRow.appendChild(statusCluster);
- requestAnimationFrame(() => _fitEmailCardTags(titleRow));
- _emailTagFitObserver?.observe(titleRow);
-
- // Prev/next arrows — visible only when this card is the expanded one
- // (CSS-gated so collapsed cards stay clean). Click navigates by collapsing
- // this card and expanding the neighbour.
- const navArrows = document.createElement('span');
- navArrows.className = 'email-card-nav-arrows';
- navArrows.innerHTML = `
- <button type="button" class="email-card-nav-btn" data-nav-dir="-1" title="Previous email"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg></button>
- <button type="button" class="email-card-nav-btn" data-nav-dir="1" title="Next email"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg></button>
- `;
- navArrows.addEventListener('click', async (ev) => {
- const btn = ev.target.closest('.email-card-nav-btn');
- if (!btn || btn.disabled) return;
- ev.stopPropagation();
- const card = navArrows.closest('.doclib-card');
- if (!card) return;
- const dir = parseInt(btn.dataset.navDir, 10);
- const sibling = _findSiblingEmailCard(card, dir);
- if (!sibling) return;
- const nextEm = state._libEmails.find(e => String(e.uid) === String(sibling.dataset.uid));
- if (!nextEm) return;
- await _toggleCardPreview(card, em);
- await _toggleCardPreview(sibling, nextEm);
- sibling.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
- });
- // Keep navigation in the same status row as Favorite and Done. The
- // per-card `.memory-item-actions` menu
- // at the bottom of the card stays visible while expanded (see the CSS
- // override below), so duplicating it in the header was redundant.
- statusCluster.appendChild(navArrows);
-
- content.appendChild(titleRow);
-
- const meta = document.createElement('div');
- meta.className = 'memory-item-meta';
- meta.style.cssText = 'font-size:10px;opacity:0.7;margin-top:2px;';
- const showFolderChip = !!(_libSearchHadResults && cardFolder);
- const prettyFolder = folderDisplayName(cardFolder);
- const sentChip = isSentFolderEarly ? '<span class="email-sent-chip" title="Sent email">Sent</span>' : '';
- const folderChip = showFolderChip && !isSentFolderEarly
- ? `<span class="email-folder-chip" title="${_esc(cardFolder)}">${_esc(prettyFolder)}</span>`
- : '';
- const senderPrefix = isSentFolderEarly ? 'to ' : '';
- meta.innerHTML = `${sentChip}<span class="email-meta-sender" data-email="${_esc(senderAddress || '')}" data-name="${_esc(senderName || '')}"><span style="opacity:0.55">${senderPrefix}</span><span style="color:${color};font-weight:600">${_esc(senderName)}</span></span><span class="email-meta-sep"> · </span><span class="email-meta-date-group"><span class="email-meta-date">${_esc(dateStr)}</span>${folderChip}</span>`;
- content.appendChild(meta);
-
- card.appendChild(content);
-
- // Per-card menu button (... menu)
- if (!state._selectMode) {
- const actionsWrap = document.createElement('div');
- actionsWrap.className = 'memory-item-actions';
- const menuBtn = document.createElement('button');
- menuBtn.className = 'memory-item-btn';
- menuBtn.title = 'Actions';
- menuBtn.style.position = 'relative';
- menuBtn.style.top = '-1px';
- menuBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg>';
- menuBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- _showCardMenu(em, menuBtn);
- });
- actionsWrap.appendChild(menuBtn);
- card.appendChild(actionsWrap);
- card.appendChild(cardChevron);
-
- // Long-press anywhere on the row opens the same actions menu — matches
- // the chats / archive / research / documents tabs' long-press UX.
- let _hold = null, _holdStart = null;
- const _cancelHold = () => { if (_hold) { clearTimeout(_hold); _hold = null; } _holdStart = null; };
- card.addEventListener('pointerdown', (e) => {
- if (card.classList.contains('email-card-expanded') || card.classList.contains('doclib-card-expanded')) return;
- if (e.target.closest('button, .email-card-done, .recipient-chip, .memory-select-cb, .email-card-nav-btn')) return;
- _holdStart = { x: e.clientX, y: e.clientY };
- _hold = setTimeout(() => {
- _hold = null;
- if (card.classList.contains('email-card-expanded') || card.classList.contains('doclib-card-expanded')) return;
- card._suppressNextClick = true;
- setTimeout(() => { card._suppressNextClick = false; }, 400);
- if (navigator.vibrate) try { navigator.vibrate(15); } catch {}
- if (window.innerWidth <= 768 && ('ontouchstart' in window || navigator.maxTouchPoints > 0)) {
- const selectBtn = document.getElementById('email-lib-select-btn');
- if (selectBtn) {
- if (!selectBtn.classList.contains('active')) selectBtn.click();
- setTimeout(() => document.querySelector(`#email-lib-grid .doclib-card[data-uid="${CSS.escape(String(em.uid))}"] .memory-select-cb`)?.click(), 40);
- return;
- }
- }
- _showCardMenu(em, menuBtn);
- }, 500);
- });
- card.addEventListener('pointermove', (e) => {
- if (!_holdStart) return;
- if (Math.hypot(e.clientX - _holdStart.x, e.clientY - _holdStart.y) > 10) _cancelHold();
- });
- card.addEventListener('pointerup', _cancelHold);
- card.addEventListener('pointercancel', _cancelHold);
- }
-
- // Click handler — toggle preview expansion
- card.addEventListener('click', async (e) => {
- if (card._suppressNextClick) { card._suppressNextClick = false; return; }
- if (state._selectMode) {
- if (state._selectedUids.has(em.uid)) state._selectedUids.delete(em.uid);
- else state._selectedUids.add(em.uid);
- card.classList.toggle('selected', state._selectedUids.has(em.uid));
- const cb = card.querySelector('.memory-select-cb');
- if (cb) cb.checked = state._selectedUids.has(em.uid);
- _updateBulkBar();
- return;
- }
- if (e.shiftKey) {
- e.preventDefault();
- await _openEmailAsTab(em, cardFolder);
- return;
- }
- if (/draft/i.test(String(state._libFolder || '')) && state._docModule?.openEmailDraft) {
- try {
- await _openDraftInComposer(em);
- } catch (err) {
- console.error('Failed to open email draft:', err);
- showToast(`Could not open draft: ${err.message || err}`);
- }
- return;
- }
- await _toggleCardPreview(card, em);
- });
-
- return card;
- }
-
- function _findSiblingEmailCard(card, dir) {
- const grid = card.closest('.doclib-grid');
- if (!grid) return null;
- const cards = [...grid.querySelectorAll('.doclib-card[data-uid]')];
- const idx = cards.indexOf(card);
- if (idx === -1) return null;
- return cards[idx + dir] || null;
- }
-
- function _syncCardNavArrows(card) {
- const prev = card.querySelector('.email-card-nav-btn[data-nav-dir="-1"]');
- const next = card.querySelector('.email-card-nav-btn[data-nav-dir="1"]');
- if (prev) prev.disabled = !_findSiblingEmailCard(card, -1);
- if (next) next.disabled = !_findSiblingEmailCard(card, 1);
- }
-
- async function _openDraftInComposer(em) {
- if (!state._docModule?.openEmailDraft) return false;
- const folder = em?.folder || state._libFolder || 'Drafts';
- const account = state._libAccountId ? `&account_id=${encodeURIComponent(state._libAccountId)}` : '';
- const res = await fetch(`${API_BASE}/api/email/read/${encodeURIComponent(em.uid)}?folder=${encodeURIComponent(folder)}${account}&mark_seen=false`);
- if (!res.ok) throw new Error(`Draft load failed: HTTP ${res.status}`);
- const data = await res.json();
- if (data.error) throw new Error(data.error);
- await state._docModule.openEmailDraft({ ...em, ...data });
- return true;
- }
-
- const _emailReadPrefetching = new Set();
- let _emailReadPrefetchTimer = null;
-
- function _prefetchAdjacentEmails(card, count = 1) {
- if (!card || state._libFolder === '__scheduled__') return;
- const grid = card.closest('.doclib-grid');
- if (!grid) return;
- const cards = [...grid.querySelectorAll('.doclib-card[data-uid]')];
- const idx = cards.indexOf(card);
- if (idx === -1) return;
- const targets = [];
- for (let i = 1; i <= count; i++) {
- if (cards[idx + i]) targets.push(cards[idx + i]);
- }
- if (targets.length < count) {
- for (let i = 1; targets.length < count && cards[idx - i]; i++) targets.push(cards[idx - i]);
- }
- const target = targets.find(t => t?.dataset?.uid);
- const uid = target?.dataset?.uid;
- if (!uid) return;
- // Use the email's actual folder when it was stamped by the search
- // endpoint; otherwise default to the currently-selected folder.
- const _emFold = (() => {
- const emObj = (state._libEmails || []).find(e => String(e.uid) === String(uid));
- return (emObj && emObj.folder) || state._libFolder || 'INBOX';
- })();
- const key = `${state._libAccountId || ''}|${_emFold}|${uid}`;
- if (_emailReadPrefetching.has(key) || _emailReadPrefetching.size > 0) return;
- if (_emailReadPrefetchTimer) clearTimeout(_emailReadPrefetchTimer);
- _emailReadPrefetchTimer = setTimeout(() => {
- _emailReadPrefetchTimer = null;
- if (document.hidden) return;
- _emailReadPrefetching.add(key);
- fetch(`${API_BASE}/api/email/read/${encodeURIComponent(uid)}?folder=${encodeURIComponent(_emFold)}${_acct()}&mark_seen=false`)
- .catch(() => {})
- .finally(() => _emailReadPrefetching.delete(key));
- }, 2500);
- }
-
- async function _toggleCardPreview(card, em) {
- _normalizeEmailStateFlags(em);
- const accountAtStart = state._libAccountId || '';
- const libraryFolderAtStart = state._libFolder || 'INBOX';
- // Prefer the per-email folder stamped by the search endpoint (results
- // from "All Mail" carry folder="[Gmail]/All Mail"). Falls back to the
- // currently-selected folder for normal inbox cards.
- const folderAtStart = _hasActiveEmailSearchResults()
- ? ((em && em.folder) || libraryFolderAtStart)
- : libraryFolderAtStart;
- const uidAtStart = String(em?.uid || card?.dataset?.uid || '');
- const wasReadAtStart = !!em?.is_read;
- const openGeneration = ++_emailCardOpenSeq;
- const readContext = Object.freeze({
- accountId: String(accountAtStart),
- libraryFolder: String(libraryFolderAtStart),
- folder: String(folderAtStart),
- uid: uidAtStart,
- mailboxGeneration: _emailMailboxGeneration,
- });
- const readContextKey = _emailReadContextKey(readContext);
- const isCurrentOpen = () => (
- openGeneration === _emailCardOpenSeq &&
- _emailReadContextIsCurrent(readContext) &&
- accountAtStart === (state._libAccountId || '') &&
- libraryFolderAtStart === (state._libFolder || 'INBOX') &&
- uidAtStart === String(card?.dataset?.uid || '') &&
- card.isConnected &&
- card.classList.contains('email-card-expanded')
- );
- const grid = card.closest('.doclib-grid');
- const gridRect = grid?.getBoundingClientRect?.();
- const modal = document.getElementById('email-lib-modal');
- const modalContent = card.closest('.modal-content');
- const modalRect = modalContent?.getBoundingClientRect?.();
- const currentRect = card.getBoundingClientRect();
- const stableOpenHeight = Math.max(
- currentRect.height || 0,
- (modalRect?.height || 0) - 84,
- Math.min(Math.max(260, window.innerHeight * 0.56), gridRect?.height || window.innerHeight)
- );
-
- // Already expanded — collapse
- if (card.classList.contains('email-card-expanded')) {
- unbindExpandedCardDismiss(card);
- card.classList.remove('email-card-expanded');
- card.classList.remove('doclib-card-expanded');
- card.style.minHeight = '';
- modal?.classList.remove('email-reading');
- modal?.style.removeProperty('--email-reading-modal-min-h');
- const reader = card.querySelector('.email-card-reader');
- if (reader) reader.remove();
- return;
- }
-
- // Every authoritative open supersedes any older optimistic mutation for the
- // same immutable mailbox identity. Carry the original unread state forward
- // so a close/reopen followed by failure still rolls back exactly once, while
- // a late failure from the superseded request cannot undo a newer success.
- const previousMutation = _emailReadMutations.get(readContextKey);
- const readMutation = {
- generation: ++_emailReadMutationSeq,
- rollbackUnread: !wasReadAtStart || !!previousMutation?.rollbackUnread,
- };
- _emailReadMutations.set(readContextKey, readMutation);
- const restoreUnreadState = () => {
- if (_emailReadMutations.get(readContextKey)?.generation !== readMutation.generation) return;
- _emailReadMutations.delete(readContextKey);
- if (readMutation.rollbackUnread) _syncEmailReadState(uidAtStart, false, readContext);
- };
- const commitReadState = () => {
- // A successful STORE/mark_seen is authoritative for this immutable
- // mailbox identity even when a newer open is still pending. Retire that
- // newer rollback token too, otherwise its later failure could restore an
- // unread state that no longer exists at the provider.
- _emailReadMutations.delete(readContextKey);
- _syncEmailReadState(uidAtStart, true, readContext);
- };
-
- // Collapse any other expanded card
- if (grid) {
- grid.querySelectorAll('.email-card-expanded').forEach(c => {
- unbindExpandedCardDismiss(c);
- c.classList.remove('email-card-expanded');
- c.classList.remove('doclib-card-expanded');
- c.style.minHeight = '';
- const r = c.querySelector('.email-card-reader');
- if (r) r.remove();
- });
- }
-
- card.classList.add('email-card-expanded');
- card.classList.add('doclib-card-expanded');
- bindExpandedCardDismiss(card, () => _toggleCardPreview(card, em));
- card.style.minHeight = `${Math.round(stableOpenHeight)}px`;
- // Pull the card into view in case the user clicked an email further up
- // the list whose top is partially scrolled off the viewport. Wait for
- // the layout to settle (minHeight just changed) before scrolling so
- // the browser scrolls toward the post-expansion position.
- requestAnimationFrame(() => {
- try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (_) {}
- });
- if (!wasReadAtStart) {
- // Keep the current optimistic visual update, but let the read request below
- // own the provider-side \Seen transition. A failure restores unread state.
- _syncEmailReadState(uidAtStart, true, readContext);
- }
- // Class hook on the modal so the header-hide / padding rules work on
- // browsers without :has() support (Firefox mobile) — the :has() versions
- // below stay as the desktop path.
- if (modal && modalRect?.height) {
- modal.style.setProperty('--email-reading-modal-min-h', `${Math.round(modalRect.height)}px`);
- }
- modal?.classList.add('email-reading');
-
- // Show loading reader with whirlpool spinner
- const reader = document.createElement('div');
- reader.className = 'email-card-reader email-card-reader-loading';
- reader.style.minHeight = `${Math.max(180, Math.round(stableOpenHeight - 70))}px`;
- reader.innerHTML = _emailReaderSkeletonHtml();
- card.appendChild(reader);
- _markEmailReaderActive(reader);
- const showFailedReader = (message) => {
- try {
- _showEmailReaderLoadError(reader, message, () => {
- try { reader.remove(); } catch (_) {}
- card.classList.remove('email-card-expanded', 'doclib-card-expanded');
- card.style.minHeight = '';
- setTimeout(() => { _toggleCardPreview(card, em); }, 0);
- });
- showToast(message || 'Failed to load email');
- } catch (_) {}
- };
-
- let authoritativeReadSucceeded = false;
- try {
- const accountQueryAtStart = accountAtStart ? `&account_id=${encodeURIComponent(accountAtStart)}` : '';
- const res = await fetch(`${API_BASE}/api/email/read/${encodeURIComponent(uidAtStart)}?folder=${encodeURIComponent(folderAtStart)}${accountQueryAtStart}&mark_seen=true`);
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- let data = await res.json();
- if (data.error) {
- restoreUnreadState();
- if (isCurrentOpen()) showFailedReader(`Failed to load email: ${data.error}`);
- return;
- }
- data = _normalizeEmailStateFlags({ ...em, ...data });
- Object.assign(em, data);
- _syncEmailDoneState(uidAtStart, data.is_answered, readContext);
- if (data.mark_seen_failed) {
- // The body is authoritative even when the provider refused the \Seen
- // transition. Render the message and roll the unread marker back so the
- // list keeps telling the truth, rather than refusing to open a message
- // we successfully read.
- restoreUnreadState();
- } else {
- authoritativeReadSucceeded = true;
- commitReadState();
- }
- if (!isCurrentOpen()) return;
- _stampReaderContext(reader, { ...em, ...data }, state._libFolder, state._libAccountId);
-
- // Build the attachments wrap using the shared helper so the signature-
- // image filter (small inline PNGs/JPGs, Outlook image001 placeholders,
- // logo/banner files) is applied here too. Falls back to '' when every
- // attachment is filtered out.
- const attsHtml = _buildAttsHtmlFor(em.uid, data);
-
- // Format date nicely (compact): "Mar 21, 2026 14:32"
- let dateDisplay = data.date || '';
- try {
- if (data.date) {
- const d = new Date(data.date);
- if (!isNaN(d.getTime())) {
- dateDisplay = d.toLocaleString([], {
- month: 'short', day: 'numeric', year: 'numeric',
- hour: '2-digit', minute: '2-digit',
- });
- }
- }
- } catch (_) {}
-
- // Build recipient chip group from a comma-separated address list
- const buildRecipients = (str) => {
- if (!str) return '';
- const addrs = _splitRecipientList(str);
- if (addrs.length === 0) return '';
- return addrs.map(a => {
- const name = _extractName(a);
- return _recipientChipHtml(a, name);
- }).join('');
- };
-
- // Build the From chip too — single chip with name, click reveals address
- const fromChip = _recipientChipHtml(`${data.from_name || ''} <${data.from_address || ''}>`, data.from_name || data.from_address, 'from-chip');
-
- reader.innerHTML = `
- <div class="email-reader-header">
- <div class="email-reader-meta">
- <div class="email-reader-meta-row email-reader-meta-from">
- <strong>From:</strong>
- <span class="recipient-chips">${fromChip}${_recipientMetaToggleHtml(data)}</span>
- </div>
- ${(data.to || data.cc) ? `<div class="email-reader-meta-details" hidden>
- ${data.to ? `<div class="email-reader-meta-row"><strong>To:</strong><span class="recipient-chips">${buildRecipients(data.to)}</span></div>` : ''}
- ${data.cc ? `<div class="email-reader-meta-row"><strong>Cc:</strong><span class="recipient-chips">${buildRecipients(data.cc)}</span></div>` : ''}
- </div>` : ''}
- <div class="email-reader-actions-inline">
- <button class="memory-toolbar-btn reader-icon-btn" data-act="ai-reply" title="${data.cached_ai_reply ? 'AI Reply (cached draft ready)' : 'AI Reply (suggest a draft)'}">${_aiReplyIcon(data)}<span class="reader-btn-label">AI reply</span></button>
- <button class="memory-toolbar-btn reader-icon-btn" data-act="reply" title="Reply"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg><span class="reader-btn-label">Reply</span></button>
- ${_hasMultipleRecipients(data) ? `<button class="memory-toolbar-btn reader-icon-btn" data-act="reply-all" title="Reply All"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="7 17 2 12 7 7"/><polyline points="12 17 7 12 12 7"/><path d="M22 18v-2a4 4 0 0 0-4-4H7"/></svg><span class="reader-btn-label">Reply all</span></button>` : ''}
- <button class="memory-toolbar-btn reader-icon-btn" data-act="forward" title="Forward"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 17 20 12 15 7"/><path d="M4 18v-2a4 4 0 0 1 4-4h12"/></svg><span class="reader-btn-label">Forward</span></button>
- <div class="email-reader-more-wrap" style="position:relative">
- <button class="memory-toolbar-btn reader-icon-btn" data-act="more" title="More actions"><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg><span class="reader-btn-label">More</span></button>
- </div>
- </div>
- </div>
- </div>
- ${attsHtml}
- <div class="email-reader-body${data.body_html ? ' html-body' : ''}">${_safeRenderEmailBody(data)}</div>
- `;
- _markEmailReaderActive(reader);
- reader.classList.remove('email-card-reader-loading');
- reader.style.minHeight = '';
-
- _wireEmailAttachmentWrap(reader, folderAtStart);
- _wireEmailInlineImages(reader);
- _loadDeferredAttachmentsIntoReader(reader, em.uid, folderAtStart, data, !!em.has_attachments);
- _maybeAutoTranslateEmail(reader);
-
- reader.querySelector('[data-act="reply"]')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- _snapEmailModalToLeftSidebar(ev.currentTarget.closest('.modal'));
- if (state._onEmailClick) await state._onEmailClick({ email: em, emailData: data, mode: 'reply' });
- });
- reader.querySelector('[data-act="reply-all"]')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- _snapEmailModalToLeftSidebar(ev.currentTarget.closest('.modal'));
- if (state._onEmailClick) await state._onEmailClick({ email: em, emailData: data, mode: 'reply-all' });
- });
- reader.querySelector('[data-act="ai-reply"]')?.addEventListener('click', (ev) => _handleAiReplyButton(ev, em, data));
- reader.querySelector('[data-act="forward"]')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- if (state._onEmailClick) await state._onEmailClick({ email: em, emailData: data, mode: 'forward' });
- });
- reader.querySelector('[data-act="more"]')?.addEventListener('click', (ev) => {
- ev.stopPropagation();
- _showReaderMoreMenu(em, card, reader, ev.currentTarget, data);
- });
- reader.querySelector('[data-act="summarize"]')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- await _summarizeEmail(reader, data, ev.currentTarget);
- });
- _wireMetaToggle(reader);
- _wireReaderActionOverflow(reader);
- // Refresh the title-row prev/next arrows for this newly-expanded card.
- _syncCardNavArrows(card);
-
- // Horizontal swipe on the reader switches to prev/next email — but
- // only when the underlying content can't scroll further in the swipe
- // direction. If the email body is wider than the viewport (HTML emails
- // with tables, embedded images), normal horizontal scroll wins; nav
- // only fires once the user has reached an edge.
- {
- let _sx = 0, _sy = 0, _swiping = false, _intent = null;
- let _scrollEl = null;
- let _startScrollLeft = 0;
- const SWIPE_THRESHOLD = 60;
- const VERT_ABORT = 14;
- const findHScroller = (el) => {
- while (el && el !== reader) {
- if (el.scrollWidth - el.clientWidth > 2) return el;
- el = el.parentElement;
- }
- return null;
- };
- reader.addEventListener('touchstart', (ev) => {
- if (ev.touches.length !== 1) { _swiping = false; return; }
- if (ev.target.closest('button, a, .recipient-chip, .email-attachment-chip, .email-reader-more-wrap')) { _swiping = false; return; }
- _sx = ev.touches[0].clientX;
- _sy = ev.touches[0].clientY;
- _scrollEl = findHScroller(ev.target);
- _startScrollLeft = _scrollEl ? _scrollEl.scrollLeft : 0;
- _swiping = true;
- _intent = null;
- }, { passive: true });
- reader.addEventListener('touchmove', (ev) => {
- if (!_swiping) return;
- const dx = ev.touches[0].clientX - _sx;
- const dy = ev.touches[0].clientY - _sy;
- if (!_intent) {
- if (Math.abs(dy) > VERT_ABORT && Math.abs(dy) > Math.abs(dx)) {
- _intent = 'scroll';
- _swiping = false;
- return;
- }
- if (Math.abs(dx) > 12) _intent = 'swipe';
- }
- }, { passive: true });
- reader.addEventListener('touchend', (ev) => {
- if (!_swiping) return;
- _swiping = false;
- const t = (ev.changedTouches && ev.changedTouches[0]) || null;
- if (!t || _intent !== 'swipe') return;
- const dx = t.clientX - _sx;
- const dy = t.clientY - _sy;
- if (Math.abs(dx) < SWIPE_THRESHOLD || Math.abs(dy) > Math.abs(dx)) return;
- // If a horizontally-scrollable element captured the swipe, let it
- // scroll instead of changing email — UNLESS the user was already
- // at the edge (scrollLeft can't move further in that direction).
- if (_scrollEl) {
- const max = _scrollEl.scrollWidth - _scrollEl.clientWidth;
- const atLeftEdge = _scrollEl.scrollLeft <= 2;
- const atRightEdge = _scrollEl.scrollLeft >= max - 2;
- // Swiping LEFT (dx<0) reveals content to the right → if not at
- // right edge, that's a scroll, not a nav.
- if (dx < 0 && !atRightEdge) return;
- // Swiping RIGHT (dx>0) reveals content to the left → if not at
- // left edge, that's a scroll, not a nav.
- if (dx > 0 && !atLeftEdge) return;
- // If the browser already scrolled during this gesture, treat as
- // scroll regardless (the user clearly wanted to pan).
- if (_scrollEl.scrollLeft !== _startScrollLeft) return;
- }
- const dir = dx < 0 ? 1 : -1;
- const navBtn = card.querySelector(`.email-card-nav-btn[data-nav-dir="${dir}"]`);
- if (navBtn && !navBtn.disabled) navBtn.click();
- }, { passive: true });
- }
-
- // If the email has a pre-cached summary, show it immediately. Fold
- // state is persisted via _summaryCollapsedPref inside the renderer.
- if (data.cached_summary) {
- const sumBtn = reader.querySelector('[data-act="summarize"]');
- _showCachedSummary(reader, data.cached_summary, sumBtn);
- }
-
- _wireRecipientChips(reader);
- // Always stop bubbling so the card's click doesn't fire while reading.
- reader.addEventListener('click', (ev) => { ev.stopPropagation(); });
- } catch (e) {
- if (!authoritativeReadSucceeded) restoreUnreadState();
- if (isCurrentOpen()) {
- showFailedReader(e?.message ? `Failed to load email: ${e.message}` : 'Failed to load email');
- }
- }
- }
-
- /**
- * Wrap a probable signature block in a collapsed <details> so it stops
- * eating the whole reader. We try, in priority order:
- * 1. Mail-client signature wrappers — Gmail's `gmail_signature` div is
- * explicit, no guessing required. Same for Apple Mail's data-smartmail.
- * 2. The standard "-- " RFC 3676 sig delimiter.
- * 3. A common closing phrase ("Best regards", "Cheers", etc.) on its own
- * line — fuzzier, but catches sigs without the dash marker.
- * 4. "Sent from my iPhone/Android" / "Get Outlook for ..." mobile-client
- * boilerplate.
- * Anything matched gets wrapped from the marker through end-of-body.
- */
- /**
- * Render the email body with sig/quote folds. If the backend has cached
- * LLM-detected boundary offsets (data.boundaries), use those for an exact
- * fold based on plain-text positions. Otherwise fall back to the regex
- * detectors. The plain-body branch is always preferred when boundaries
- * exist because the offsets are computed against plain text.
- */
- // Global escape hatch — when the server's thread parser misfires (it
- // occasionally splits a single reply into two bogus "turns" by treating a
- // signature/disclaimer as its own message), the user can flip this off to
- // fall back to plain rendering. Survives reloads.
- const _BUBBLES_DISABLED_KEY = 'odysseus.email.bubblesDisabled';
- // Threaded chat-bubble email view is DISABLED for now — too buggy to
- // ship. Force plain-text rendering everywhere by always returning true.
- // Re-enable by restoring the localStorage-backed body + the toggle
- // menu item in the reader's More menu.
- function _bubblesDisabled() {
- return true;
- }
- function _setBubblesDisabled(v) {
- try { localStorage.setItem(_BUBBLES_DISABLED_KEY, v ? '1' : '0'); } catch {}
- }
-
- function _renderEmailBody(data) {
- const plain = (typeof data?.body === 'string' && data.body.length) ? data.body : '';
- const folder = String(data?.folder || '').toLowerCase();
- const isSentFolder = folder.includes('sent');
- const fromAddr = String(data?.from_address || '').toLowerCase().trim();
- const isMine = !!fromAddr && _meEmailAddrs().has(fromAddr);
-
- // Messages authored by the user (Sent folder or self-sent copies in INBOX)
- // are current authored text. Do not let cached boundaries or HTML
- // blockquote parsing hide the whole thing behind "Earlier reply".
- if ((isSentFolder || isMine) && plain) {
- const plainTurns = _renderPlaintextThread(plain);
- if (plainTurns && !/^\s*<details\b/i.test(plainTurns.trim())) {
- return _foldSignature(plainTurns, null);
- }
- return _foldSignature(_escLinkify(plain).replace(/\n/g, '<br>'), null);
- }
-
- // Prefer the normalized plain-text thread when the message contains
- // explicit reply markers. HTML mail from Outlook/Gmail commonly wraps the
- // same quoted message in several nested blockquotes; feeding that markup
- // to the HTML walker creates phantom chains such as "Earlier reply >
- // Earlier reply > sender". The plain representation has the actual quote
- // levels and gives us one stable fold per real quoted message.
- const hasPlainThreadMarkers = plain && (
- /^\s*>/m.test(plain)
- || /^\s*-{5,}\s*(?:Previous message|Original message)\s*-{5,}\s*$/im.test(plain)
- || /^\s*On\s.+?\s(?:wrote|skrev|schrieb|écrit|escribió)\s*:\s*$/im.test(plain)
- );
- if (hasPlainThreadMarkers) {
- const plainThread = _renderPlaintextThread(plain);
- if (plainThread) return _foldSignature(plainThread, data && data.sender_signature || null);
- }
-
- // Prefer the server-cached thread parse — that's the richest structure
- // and the one the chat-bubble layout is built around. Skip when the user
- // has manually disabled bubble rendering.
- if (!_bubblesDisabled() && Array.isArray(data && data.thread_turns) && data.thread_turns.length) {
- return _foldSignature(
- _renderTurnsAsBubbles(data.thread_turns, data),
- data && data.sender_signature || null,
- );
- }
- const b = data && data.boundaries;
- // Use cached boundaries when present AND we have plain-text body to slice
- if (b && plain && (b.sig_start >= 0 || b.quote_start >= 0)) {
- // Pick the EARLIER of the two as the cut for "everything below this is
- // foldable", but render sig and quote with their own labels.
- let sig = (typeof b.sig_start === 'number' && b.sig_start >= 0) ? b.sig_start : -1;
- let quote = (typeof b.quote_start === 'number' && b.quote_start >= 0) ? b.quote_start : -1;
- // Clamp
- if (sig >= plain.length) sig = -1;
- if (quote >= plain.length) quote = -1;
- let head = plain;
- let sigSection = '';
- let quoteSection = '';
- if (sig >= 0 && quote >= 0) {
- const earlier = Math.min(sig, quote);
- head = plain.slice(0, earlier);
- if (sig < quote) {
- sigSection = plain.slice(sig, quote);
- quoteSection = plain.slice(quote);
- } else {
- quoteSection = plain.slice(quote, sig);
- sigSection = plain.slice(sig);
- }
- } else if (sig >= 0) {
- head = plain.slice(0, sig);
- sigSection = plain.slice(sig);
- } else {
- head = plain.slice(0, quote);
- quoteSection = plain.slice(quote);
- }
- const fmt = (s) => _escLinkify(s).replace(/\n/g, '<br>');
- let out = fmt(head);
- if (quoteSection) {
- out += '<details class="email-quote-fold">'
- + _foldSummary('Earlier thread', _QUOTE_ICON, _extractQuoteMeta(quoteSection))
- + fmt(quoteSection) + '</details>';
- }
- if (sigSection) {
- const sigHtml = fmt(sigSection);
- if (_isBloatedSig(sigHtml)) {
- out += '<details class="email-sig-fold">' + _foldSummary('Signature', _SIG_ICON)
- + sigHtml + '</details>';
- } else {
- // Short closing — leave inline; folding would just add chrome.
- out += sigHtml;
- }
- }
- return out;
- }
- // Fallback: client-side parse (HTML or plaintext).
- const hintSig = (data && data.sender_signature) || null;
- const isHtml = !!data.body_html;
- let rendered;
- if (isHtml) {
- rendered = _sanitizeHtml(data.body_html);
- } else {
- const plainTurns = _renderPlaintextThread(data.body || '');
- if (plainTurns) return _foldSignature(plainTurns, hintSig);
- rendered = _escLinkify(data.body || '').replace(/\n/g, '<br>');
- }
- const threaded = _renderThreadStructure(rendered);
- if (threaded) return _prepareEmailInlineImages(_foldSignature(threaded, hintSig));
- return _prepareEmailInlineImages(_foldSignature(_foldQuotedReplies(rendered), hintSig));
- }
-
- function _safeRenderEmailBody(data) {
- try {
- return _prepareEmailInlineImages(_renderEmailBody(data));
- } catch (e) {
- console.error('email body render failed:', e);
- const plain = (typeof data?.body === 'string') ? data.body : '';
- if (plain) return _escLinkify(plain).replace(/\n/g, '<br>');
- if (data?.body_html) return _prepareEmailInlineImages(_sanitizeHtml(data.body_html));
- return '<span style="opacity:.65">No body</span>';
- }
- }
-
- function _prepareEmailInlineImages(html) {
- const raw = String(html || '');
- if (!/<img[\s>]/i.test(raw)) return raw;
- const doc = new DOMParser().parseFromString(`<div>${raw}</div>`, 'text/html');
- const root = doc.body.firstElementChild;
- if (!root) return raw;
- root.querySelectorAll('img').forEach((img, idx) => {
- const src = (img.getAttribute('src') || '').trim();
- const alt = (img.getAttribute('alt') || img.getAttribute('title') || '').trim();
- const isHttp = /^https?:\/\//i.test(src);
- const isCid = /^cid:/i.test(src);
- const cid = isCid ? src.replace(/^cid:/i, '').replace(/^<|>$/g, '').trim() : '';
- const label = alt || (isCid ? 'Inline image' : 'Remote image');
- const ph = doc.createElement('span');
- ph.className = 'email-inline-image-placeholder';
- ph.setAttribute('role', 'group');
- ph.setAttribute('aria-label', label);
- if (src) ph.dataset.emailImgSrc = src;
- if (cid) ph.dataset.emailImgCid = cid;
- ph.innerHTML = `
- <span class="email-inline-image-skeleton">
- <span class="email-inline-image-icon">
- <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/></svg>
- </span>
- </span>
- <span class="email-inline-image-info">
- <span class="email-inline-image-title">${_esc(label)}</span>
- <span class="email-inline-image-sub">${isHttp ? 'Remote image blocked' : isCid ? 'Inline image hidden' : 'Image unavailable'}</span>
- </span>
- <span class="email-inline-image-actions">
- ${isHttp ? `<a class="email-inline-image-btn email-inline-image-download-btn" href="${_esc(src)}" target="_blank" rel="noopener noreferrer" download title="Download" aria-label="Download"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg></a>` : ''}
- ${isCid ? `<button type="button" class="email-inline-image-btn email-inline-image-download-btn" data-email-img-download="${idx}" title="Download" aria-label="Download"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg></button>` : ''}
- </span>
- `;
- img.replaceWith(ph);
- });
- return root.innerHTML;
- }
-
- function _wireEmailInlineImages(reader) {
- if (!reader) return;
- const placeholders = Array.from(reader.querySelectorAll('.email-inline-image-placeholder'));
- const visiblePlaceholders = placeholders.filter(ph => (
- ph.isConnected &&
- (ph.dataset.emailImgSrc || ph.dataset.emailImgCid) &&
- getComputedStyle(ph).display !== 'none'
- ));
- const autoLoadInlineImages = state._libViewInlineImages !== false;
- const manualPlaceholders = autoLoadInlineImages
- ? visiblePlaceholders.filter(ph => !ph.dataset.emailImgCid)
- : visiblePlaceholders;
- const existingBulkBar = reader.querySelector('.email-inline-image-load-all');
- if (!manualPlaceholders.length) existingBulkBar?.remove();
- const loadPlaceholder = (ph) => {
- if (!ph || !ph.isConnected) return;
- const src = (ph.dataset.emailImgSrc || '').trim();
- const cid = (ph.dataset.emailImgCid || '').trim();
- const ctxRoot = reader.dataset?.emailUid
- ? reader
- : ph.closest('[data-email-uid]') || reader.closest?.('[data-email-uid]');
- const folder = ctxRoot?.dataset?.emailFolder || reader.dataset?.emailFolder || state._libFolder || 'INBOX';
- const account = ctxRoot?.dataset?.emailAccount || reader.dataset?.emailAccount || state._libAccountId || '';
- const uid = ctxRoot?.dataset?.emailUid || reader.dataset?.emailUid || '';
- const inlineUrl = () => {
- if (!uid || !cid) return '';
- const params = new URLSearchParams({ cid, folder });
- if (account) params.set('account_id', account);
- return `${API_BASE}/api/email/inline-image/${encodeURIComponent(uid)}?${params.toString()}`;
- };
- const isRemoteImage = /^https?:\/\//i.test(src);
- const isCidImage = !!cid && !isRemoteImage;
- const loadSrc = isRemoteImage ? src : inlineUrl();
- if (!loadSrc || ph.classList.contains('is-loading')) return;
- ph.classList.remove('is-error');
- ph.classList.add('is-loading');
- const sub = ph.querySelector('.email-inline-image-sub');
- if (sub) sub.textContent = 'Loading image...';
- const actions = ph.querySelector('.email-inline-image-actions');
- if (actions) actions.style.display = 'none';
- const img = document.createElement('img');
- img.className = 'email-inline-image-loaded';
- img.alt = ph.querySelector('.email-inline-image-title')?.textContent || 'Loaded email image';
- img.loading = 'eager';
- img.referrerPolicy = 'no-referrer';
- let settled = false;
- let objectUrl = '';
- let frame = null;
- let directFallbackUsed = false;
- const ensureFrame = () => {
- if (frame) return frame;
- frame = document.createElement('span');
- frame.className = 'email-inline-image-frame is-loading';
- frame.appendChild(img);
- if (ph.isConnected) ph.replaceWith(frame);
- return frame;
- };
- const showLoaded = () => {
- if (settled) return;
- settled = true;
- if (frame) frame.classList.remove('is-loading');
- img.classList.add('is-visible');
- };
- const showError = (err) => {
- if (settled) return;
- settled = true;
- if (frame?.isConnected) frame.replaceWith(ph);
- ph.classList.remove('is-loading');
- ph.classList.add('is-error');
- if (sub) sub.textContent = err?.message ? `Image failed: ${err.message}` : 'Image failed to load';
- if (actions) actions.style.display = '';
- if (objectUrl) {
- try { URL.revokeObjectURL(objectUrl); } catch {}
- }
- };
- const loadDirect = () => {
- directFallbackUsed = true;
- ensureFrame();
- img.src = loadSrc;
- if (img.complete && img.naturalWidth > 0) showLoaded();
- };
- img.addEventListener('load', showLoaded, { once: true });
- img.addEventListener('error', () => {
- if (!directFallbackUsed && objectUrl && isCidImage) {
- try { URL.revokeObjectURL(objectUrl); } catch {}
- objectUrl = '';
- loadDirect();
- return;
- }
- showError();
- }, { once: true });
- if (isCidImage || isRemoteImage) {
- loadDirect();
- setTimeout(() => {
- if (!settled && frame) {
- frame.classList.add('is-loading');
- }
- }, 12000);
- return;
- }
- const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), 20000);
- fetch(loadSrc, { credentials: 'same-origin', signal: controller.signal })
- .then(async res => {
- clearTimeout(timeoutId);
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const blob = await res.blob();
- if (!blob || !blob.size) throw new Error('Empty image');
- const type = blob.type && blob.type.startsWith('image/') ? blob.type : 'image/png';
- objectUrl = URL.createObjectURL(blob.type === type ? blob : new Blob([blob], { type }));
- ensureFrame();
- img.src = objectUrl;
- if (img.complete && img.naturalWidth > 0) showLoaded();
- if (!settled && typeof img.decode === 'function') {
- img.decode().then(showLoaded).catch(() => {
- if (img.complete && img.naturalWidth === 0) showError();
- });
- }
- })
- .catch(err => {
- clearTimeout(timeoutId);
- showError(err?.name === 'AbortError' ? new Error('request timed out') : err);
- });
- setTimeout(() => {
- if (!settled && !frame) {
- ph.classList.remove('is-loading');
- if (sub) sub.textContent = 'Still loading...';
- if (actions) actions.style.display = '';
- }
- }, 12000);
- };
- if (manualPlaceholders.length && !reader.querySelector('.email-inline-image-load-all')) {
- const first = manualPlaceholders[0];
- const bar = document.createElement('div');
- bar.className = 'email-inline-image-load-all';
- const label = autoLoadInlineImages
- ? `${manualPlaceholders.length} external image${manualPlaceholders.length === 1 ? '' : 's'} blocked`
- : `${manualPlaceholders.length} hidden inline image${manualPlaceholders.length === 1 ? '' : 's'}`;
- bar.innerHTML = `
- <span>${label}</span>
- <button type="button" data-email-img-dismiss-all>Dismiss</button>
- <button type="button" data-email-img-load-all>Load all</button>
- `;
- bar.querySelector('[data-email-img-load-all]')?.addEventListener('click', ev => {
- ev.preventDefault();
- ev.stopPropagation();
- bar.remove();
- manualPlaceholders.forEach(loadPlaceholder);
- });
- bar.querySelector('[data-email-img-dismiss-all]')?.addEventListener('click', ev => {
- ev.preventDefault();
- ev.stopPropagation();
- bar.remove();
- manualPlaceholders.forEach(ph => ph.remove());
- _disableInlineImages().catch(() => {});
- });
- first.parentNode?.insertBefore(bar, first);
- }
- placeholders.forEach(ph => {
- if (ph.dataset.wired !== '1') {
- ph.dataset.wired = '1';
- const src = (ph.dataset.emailImgSrc || '').trim();
- const cid = (ph.dataset.emailImgCid || '').trim();
- const ctxRoot = reader.dataset?.emailUid
- ? reader
- : ph.closest('[data-email-uid]') || reader.closest?.('[data-email-uid]');
- const folder = ctxRoot?.dataset?.emailFolder || reader.dataset?.emailFolder || state._libFolder || 'INBOX';
- const account = ctxRoot?.dataset?.emailAccount || reader.dataset?.emailAccount || state._libAccountId || '';
- const uid = ctxRoot?.dataset?.emailUid || reader.dataset?.emailUid || '';
- const inlineUrl = () => {
- if (!uid || !cid) return '';
- const params = new URLSearchParams({ cid, folder });
- if (account) params.set('account_id', account);
- return `${API_BASE}/api/email/inline-image/${encodeURIComponent(uid)}?${params.toString()}`;
- };
- ph.querySelector('[data-email-img-download]')?.addEventListener('click', (ev) => {
- ev.preventDefault();
- ev.stopPropagation();
- const url = inlineUrl();
- if (!url) return;
- const a = document.createElement('a');
- a.href = url;
- a.download = 'inline-image';
- document.body.appendChild(a);
- a.click();
- a.remove();
- });
- }
- const cid = (ph.dataset.emailImgCid || '').trim();
- if (autoLoadInlineImages && cid && ph.isConnected && ph.dataset.emailImgAutoRequested !== '1') {
- ph.dataset.emailImgAutoRequested = '1';
- loadPlaceholder(ph);
- }
- });
- }
-
- // ── Chat-bubble rendering for email threads ──
- // Each parsed turn renders as a chat bubble. Bubbles for the active
- // account's outgoing replies align right; everyone else aligns left.
- // Order is reversed so the oldest message sits at the top of the
- // conversation and the newest (the message currently being read) sits
- // at the bottom — matches the mental model people have from chat.
-
- function _meEmailAddrs() {
- const set = new Set();
- for (const a of (state._libAccounts || [])) {
- if (a && a.from_address) set.add(String(a.from_address).toLowerCase().trim());
- if (a && a.imap_user) set.add(String(a.imap_user).toLowerCase().trim());
- }
- return set;
- }
-
- // _parseTurnMeta / _formatBubbleDate / _formatRecipients / _senderColor /
- // _initials live in ./emailLibrary/utils.js
-
- function _renderTurnsAsBubbles(turns, data) {
- if (!Array.isArray(turns) || !turns.length) return '';
- const mineSet = _meEmailAddrs();
- const lvl0Email = String(data && data.from_address || '').toLowerCase().trim();
- const lvl0Mine = !!lvl0Email && mineSet.has(lvl0Email);
- const lvl0Author = (data && (data.from_name || data.from_address)) || '';
- const lvl0Date = _formatBubbleDate(data && data.date);
-
- // Newest reply on top, older history below. Turns come ordered shallow→deep
- // (level 0 = current reply, deeper levels = older quoted material) so we
- // render in source order without reversing.
- const ordered = turns.slice();
-
- // Gather per-turn sender identity + frequency for the no-self case below.
- const turnIdentity = ordered.map((t) => {
- if (t.level === 0) {
- return { email: lvl0Email, author: lvl0Author };
- }
- const p = _parseTurnMeta(t.meta || '');
- return { email: p.email, author: p.author };
- });
- const anyMine = turnIdentity.some(x => x.email && mineSet.has(x.email));
- // When the user isn't a participant in this thread (forwarded chains,
- // historical archives, etc.), assign the two most frequent senders to
- // opposite sides so the conversation still reads side-to-side. Third+
- // parties fall back to hash mod 2.
- const sideForKey = (() => {
- if (anyMine) return null;
- const freq = new Map();
- const firstSeen = new Map();
- turnIdentity.forEach((x, i) => {
- const key = (x.email || x.author || '').toLowerCase();
- if (!key) return;
- freq.set(key, (freq.get(key) || 0) + 1);
- if (!firstSeen.has(key)) firstSeen.set(key, i);
- });
- const sorted = [...freq.entries()]
- .sort((a, b) => (b[1] - a[1]) || (firstSeen.get(a[0]) - firstSeen.get(b[0])));
- const leftKey = sorted[0] && sorted[0][0];
- const rightKey = sorted[1] && sorted[1][0];
- return (key) => {
- if (!key) return 'theirs';
- if (key === leftKey) return 'theirs';
- if (key === rightKey) return 'mine';
- // Stable hash for 3rd+ parties.
- let h = 0;
- for (let i = 0; i < key.length; i++) h = ((h << 5) - h + key.charCodeAt(i)) | 0;
- return (h & 1) ? 'mine' : 'theirs';
- };
- })();
-
- const rows = ordered.map((t, i) => {
- let isMine, author, date;
- if (t.level === 0) {
- isMine = lvl0Mine;
- author = lvl0Author || 'Me';
- date = lvl0Date;
- } else {
- const p = _parseTurnMeta(t.meta || '');
- isMine = !!p.email && mineSet.has(p.email);
- author = p.author || (t.meta || 'Earlier reply');
- date = p.date;
- }
- // No-self fallback: route by per-sender side mapping.
- if (sideForKey) {
- const id = turnIdentity[i];
- const key = (id.email || id.author || '').toLowerCase();
- isMine = sideForKey(key) === 'mine';
- }
- const side = isMine ? 'mine' : 'theirs';
- const initials = _initials(author);
- const color = _senderColor(author || (t.level === 0 ? lvl0Email : ''));
- const head =
- `<div class="email-bubble-head">`
- + `<span class="email-bubble-author" style="color:${color}">${_esc(author)}</span>`
- + (date ? `<span class="email-bubble-date">${_esc(date)}</span>` : '')
- + `</div>`;
- const avatar = `<div class="email-bubble-avatar" aria-hidden="true" style="background:${color}">${_esc(initials)}</div>`;
- return (
- `<div class="email-bubble-row email-bubble-${side}" style="--bubble-accent:${color}">`
- + (isMine ? '' : avatar)
- + `<div class="email-bubble">`
- + head
- + `<div class="email-bubble-body">${_sanitizeHtml(t.body_html || '')}</div>`
- + `</div>`
- + (isMine ? avatar : '')
- + `</div>`
- );
- });
- return `<div class="email-bubbles">${rows.join('')}</div>`;
- }
-
- /**
- * Render server-cached thread turns (list of {level, body_html, meta})
- * into the same nested-card structure the client-side parser produces.
- */
- function _renderTurnsFromServer(turns) {
- if (!Array.isArray(turns) || !turns.length) return '';
- let out = '';
- const stack = []; // [{ level, html }]
- const wrap = (t) =>
- `<details class="email-thread-turn email-quote-fold">`
- + _foldSummary('Earlier reply', _QUOTE_ICON, t.meta || '')
- + `<div class="email-thread-turn-body">${t.html}</div>`
- + '</details>';
-
- for (const t of turns) {
- if (t.level === 0) {
- while (stack.length) {
- const top = stack.pop();
- const w = wrap(top);
- if (stack.length) stack[stack.length - 1].html += w; else out += w;
- }
- out += _sanitizeHtml(t.body_html || '');
- } else {
- while (stack.length && stack[stack.length - 1].level > t.level) {
- const top = stack.pop();
- const w = wrap(top);
- if (stack.length) stack[stack.length - 1].html += w; else out += w;
- }
- if (!stack.length || stack[stack.length - 1].level < t.level) {
- stack.push({ level: t.level, meta: t.meta, html: _sanitizeHtml(t.body_html || '') });
- } else {
- stack[stack.length - 1].html += _sanitizeHtml(t.body_html || '');
- if (t.meta && !stack[stack.length - 1].meta) {
- stack[stack.length - 1].meta = t.meta;
- }
- }
- }
- }
- while (stack.length) {
- const top = stack.pop();
- const w = wrap(top);
- if (stack.length) stack[stack.length - 1].html += w; else out += w;
- }
- // Mark the bottom-most fold for rounded corners.
- const lastIdx = out.lastIndexOf('<details class="email-thread-turn email-quote-fold"');
- if (lastIdx >= 0) {
- out = out.slice(0, lastIdx)
- + out.slice(lastIdx).replace(
- 'email-thread-turn email-quote-fold"',
- 'email-thread-turn email-quote-fold last-fold"'
- );
- }
- return out;
- }
-
- /**
- * Parse an email body's reply chain into a stack of turn-cards.
- * Each turn = { author, date, bodyHtml, nested[] } where the body is
- * everything UP TO the next quote boundary, and `nested` is the sub-thread
- * inside (recursively parsed). Returns null if the email has no quoted
- * thread to parse (single message, no folds needed).
- */
- // ── Talon-inspired multilingual quote-detection patterns ──
- // Sources:
- // github.com/mailgun/talon (HTML/text quote detection)
- // github.com/crisp-oss/email-reply-parser (locale list)
+ // static/js/emailLibrary.js — compatibility wrapper.
//
- // _TALON_* / _SIG_BLOAT_MIN_CHARS live in ./emailLibrary/utils.js
- // _SIG_ICON / _QUOTE_ICON live in ./emailLibrary/signatureFold.js
-
- function _renderThreadStructure(html) {
- if (!html || typeof html !== 'string' || html.length > 200000) return null;
- let doc;
- try { doc = new DOMParser().parseFromString(`<div id="__t">${html}</div>`, 'text/html'); }
- catch { return null; }
- const root = doc.getElementById('__t');
- if (!root) return null;
-
- // Find top-level blockquotes (not nested inside another blockquote).
- const tops = Array.from(root.querySelectorAll('blockquote')).filter(b =>
- !b.parentElement.closest('blockquote')
- );
- if (!tops.length) return null;
-
- // Build the current-message body: everything in root up to the first
- // top-level blockquote, minus the "On <date>, <author> wrote:" attribution
- // line that introduces it.
- const head = doc.createElement('div');
- let cursor = root.firstChild;
- while (cursor && cursor !== tops[0]) {
- const next = cursor.nextSibling;
- head.appendChild(cursor);
- cursor = next;
- }
- // Strip trailing "On <date>, <name> wrote:" / Outlook-style attribution
- // from `head` since the same info will appear in the turn header.
- let attribution = _harvestAttribution(head);
-
- // Recursively parse each top-level blockquote into a turn (and its nested chain).
- const turnsHtml = [];
- for (let i = 0; i < tops.length; i++) {
- const bq = tops[i];
- // The blockquote may have an Outlook-style "From: / Sent: / Subject:"
- // header inside as the first text. Extract that as the turn meta.
- const meta = _extractTurnMetaFromBlockquote(bq) || attribution || _extractQuoteMeta(bq.innerHTML);
- const innerHtml = bq.innerHTML;
-
- // Heuristic: if a blockquote has no detectable attribution (no "From:",
- // no "On <date>... wrote:") AND its content matches signature-style
- // patterns (corporate disclaimer, "registered in", legal notices, just
- // a name + title), treat it as a Signature fold instead of an Earlier
- // Reply. This stops mail clients that wrap signatures in <blockquote>
- // from making the signature appear as a phantom prior email.
- if (!meta && _looksLikeSignature(innerHtml)) {
- turnsHtml.push(
- '<details class="email-sig-fold">'
- + _foldSummary('Signature', _SIG_ICON)
- + `<div class="email-sig-body">${innerHtml}</div>`
- + '</details>'
- );
- attribution = null;
- continue;
- }
-
- // Recursively render the inside of this blockquote (which may contain
- // its own nested blockquotes representing earlier replies).
- const nested = _renderThreadStructure(innerHtml);
- const bodyHtml = nested || innerHtml;
- const isLast = i === tops.length - 1;
- turnsHtml.push(
- `<details class="email-thread-turn email-quote-fold${isLast ? ' last-fold' : ''}">`
- + _foldSummary('Earlier reply', _QUOTE_ICON, meta || '')
- + `<div class="email-thread-turn-body">${bodyHtml}</div>`
- + '</details>'
- );
- // Only the first turn uses the harvested attribution; deeper turns
- // get their own from inside the blockquote.
- attribution = null;
- }
-
- return head.innerHTML + turnsHtml.join('');
- }
-
- // Looks like a signature / corporate disclaimer rather than a quoted email.
- // Used to demote attribution-less blockquotes that some senders wrap their
- // sig+disclaimer in (Outlook, EY, big firms) from "Earlier reply" to a
- // proper Signature fold. Conservative — only fires when there's no quoted
- // reply markers AND it matches strong corporate-noise phrases.
- // _looksLikeSignature / _harvestAttribution / _extractTurnMetaFromBlockquote
- // live in ./emailLibrary/signatureFold.js
-
- /**
- * Wrap any quoted reply chain in a collapsed <details> so deep email threads
- * don't dominate the reader. Detects:
- * - <blockquote> tags (Gmail / native quoted replies)
- * - Outlook-style "From: ... Sent: ... To: ... Subject: ..." headers
- * Each gets its own "Earlier thread" toggle.
- */
- /**
- * Parse a plaintext email body into stacked turn-cards by walking
- * `> ` quote-prefix levels and Outlook-style "On X wrote:" / Original-Message
- * boundaries. Returns rendered HTML, or null when there's no quoted content
- * (caller falls back to flat rendering).
- *
- * Mirrors talon's `extract_from_plain` and email-reply-parser fragments:
- * 1. Lines starting with one or more `>` chars are quoted (level = count of >).
- * 2. Increasing the level opens a deeper turn (nested reply).
- * 3. `-----Original Message-----` and `On <date>, <name> wrote:` start a
- * new turn even without `>`.
- * 4. The leading non-quoted segment is the current message.
- */
- function _renderPlaintextThread(text) {
- if (!text || typeof text !== 'string' || text.length > 200000) return null;
- const lines = text.split(/\r?\n/);
- const levels = lines.map(l => {
- const m = l.match(/^((?:>\s?)+)/);
- return m ? (m[1].match(/>/g) || []).length : 0;
- });
- const hasQuotes = levels.some(l => l > 0);
- const attribLineRe = new RegExp(`(?:^|\\n)\\s*On\\s.+?\\s${_TALON_WROTE}\\s*:\\s*$`, 'im');
- const hasAttrib = attribLineRe.test(text) || _TALON_ORIG_RE.test(text);
- if (!hasQuotes && !hasAttrib) return null;
-
- const turns = [];
- let buf = [];
- let curLevel = 0;
- let pendingMeta = null;
- const flush = () => {
- if (!buf.length) return;
- const t = buf.join('\n').trimEnd();
- if (t || curLevel > 0) turns.push({ level: curLevel, text: t, meta: pendingMeta });
- buf = [];
- pendingMeta = null;
- };
- for (let i = 0; i < lines.length; i++) {
- const lvl = levels[i];
- const raw = lines[i];
- const stripped = lvl > 0 ? raw.replace(/^(?:>\s?)+/, '') : raw;
- const isSeparatorLine = lvl === 0 && /^-{5,}\s*Previous message\s*-{5,}$/i.test(raw.trim());
- const isAttribLine = lvl === 0
- && (new RegExp(`^\\s*On\\s.+?\\s${_TALON_WROTE}\\s*:\\s*$`, 'i').test(raw)
- || _TALON_ORIG_RE.test('\n' + raw));
- if (isSeparatorLine || isAttribLine) {
- flush();
- pendingMeta = isSeparatorLine ? null : (_extractQuoteMeta(raw) || raw.trim());
- curLevel = 1;
- continue;
- }
- if (lvl !== curLevel) {
- flush();
- curLevel = lvl;
- }
- buf.push(stripped);
- }
- flush();
-
- if (!turns.length || (turns.length === 1 && turns[0].level === 0)) return null;
-
- const fmt = s => _escLinkify(s).replace(/\n/g, '<br>');
- let out = '';
- const stack = [];
- const wrapTurn = (t) =>
- `<details class="email-thread-turn email-quote-fold">`
- + _foldSummary('Earlier reply', _QUOTE_ICON, t.meta || '')
- + `<div class="email-thread-turn-body">${t.html}</div>`
- + '</details>';
-
- for (const t of turns) {
- if (t.level === 0) {
- while (stack.length) {
- const top = stack.pop();
- const wrapped = wrapTurn(top);
- if (stack.length) stack[stack.length - 1].html += wrapped; else out += wrapped;
- }
- out += fmt(t.text);
- } else {
- while (stack.length && stack[stack.length - 1].level > t.level) {
- const top = stack.pop();
- const wrapped = wrapTurn(top);
- if (stack.length) stack[stack.length - 1].html += wrapped; else out += wrapped;
- }
- if (!stack.length || stack[stack.length - 1].level < t.level) {
- stack.push({ level: t.level, meta: t.meta, html: fmt(t.text) });
- } else {
- stack[stack.length - 1].html += '<br>' + fmt(t.text);
- if (t.meta && !stack[stack.length - 1].meta) stack[stack.length - 1].meta = t.meta;
- }
- }
- }
- while (stack.length) {
- const top = stack.pop();
- const wrapped = wrapTurn(top);
- if (stack.length) stack[stack.length - 1].html += wrapped; else out += wrapped;
- }
- const lastIdx = out.lastIndexOf('<details class="email-thread-turn email-quote-fold"');
- if (lastIdx >= 0) {
- out = out.slice(0, lastIdx)
- + out.slice(lastIdx).replace(
- 'email-thread-turn email-quote-fold"',
- 'email-thread-turn email-quote-fold last-fold"'
- );
- }
- return out;
- }
-
- // _foldSummary / _extractQuoteMeta / _SIG_ICON / _QUOTE_ICON
- // live in ./emailLibrary/signatureFold.js
-
- function _foldQuotedReplies(html) {
- if (!html || typeof html !== 'string') return html;
- if (html.length > 200000) return html;
- const before = html;
- // Use DOMParser for proper nested-blockquote handling. Regex against HTML
- // mishandles nesting and leaves orphan close tags that the browser
- // re-balances, producing two visually inconsistent fold styles.
- try {
- const doc = new DOMParser().parseFromString(`<div id="__r">${html}</div>`, 'text/html');
- const root = doc.getElementById('__r');
- if (root) {
- // Only fold TOP-LEVEL blockquotes (children of the root that are not
- // already inside another blockquote). The inner blockquote chain stays
- // intact inside the fold and renders with the existing
- // .email-quote-fold blockquote styles, so everything matches.
- const tops = Array.from(root.querySelectorAll('blockquote')).filter(b =>
- !b.parentElement.closest('blockquote')
- );
- if (tops.length) {
- for (const bq of tops) {
- const det = doc.createElement('details');
- det.className = 'email-quote-fold';
- // Build the summary as raw HTML — easier than building DOM by hand.
- const summary = _foldSummary('Earlier thread', _QUOTE_ICON, _extractQuoteMeta(bq.innerHTML));
- det.innerHTML = summary;
- bq.parentNode.insertBefore(det, bq);
- det.appendChild(bq); // move the original blockquote (and any nested ones) into the details
- }
- // Tag only the last fold so CSS can give it rounded bottom corners.
- const allFolds = root.querySelectorAll('.email-quote-fold');
- if (allFolds.length) allFolds[allFolds.length - 1].classList.add('last-fold');
- return root.innerHTML;
- }
- }
- } catch (e) {
- // Fall through to the legacy regex path below if DOMParser fails
- }
- // If DOM-pass already wrapped something, we returned above. Otherwise no
- // blockquotes were found — try the Outlook-header heuristic.
- if (html !== before) return html;
- // Outlook-style quoted-reply header — multilingual. Fold from the first
- // "From: ... Sent: ... Subject: ..." block through end-of-body so all
- // prior thread levels collapse together.
- const FROM = '(?:From|Från|Von|De|De\\s|Da|От|Od|Van)';
- const SENT = '(?:Sent|Skickat|Gesendet|Envoyé|Inviato|Enviado|Verzonden|Отправлено|Wysłane)';
- const SUBJ = '(?:Subject|Ämne|Betreff|Objet|Oggetto|Asunto|Onderwerp|Тема|Temat)';
- const outlookRe = new RegExp(
- `(<br\\s*/?>|</p>|</div>|<p[^>]*>|<div[^>]*>|\\n)\\s*((?:<[^>]+>\\s*)*${FROM}\\s*:\\s*[^<\\n]+(?:<[^>]+>\\s*|\\s)*${SENT}\\s*:[\\s\\S]+?${SUBJ}\\s*:[\\s\\S]+)$`,
- 'i'
- );
- const m = html.match(outlookRe);
- if (m) {
- const idx = html.lastIndexOf(m[0]);
- // Outlook fallback only ever produces ONE fold, so tag it as last.
- html = html.slice(0, idx) + m[1]
- + '<details class="email-quote-fold last-fold">'
- + _foldSummary('Earlier thread', _QUOTE_ICON, _extractQuoteMeta(m[2]))
- + m[2] + '</details>';
- }
- return html;
- }
-
-
- // Global preference: AI summary panels stay collapsed across every email
- // once the user folds one, and stay expanded once they unfold. Stored in
- // localStorage so the choice survives reloads.
- const _SUMMARY_COLLAPSED_KEY = 'odysseus.email.summaryCollapsed';
- function _summaryCollapsedPref() {
- try { return localStorage.getItem(_SUMMARY_COLLAPSED_KEY) === '1'; } catch { return false; }
- }
- function _setSummaryCollapsedPref(v) {
- try { localStorage.setItem(_SUMMARY_COLLAPSED_KEY, v ? '1' : '0'); } catch {}
- }
-
- function _showCachedSummary(reader, summary, btn) {
- const body = reader.querySelector('.email-reader-body');
- if (!body) return;
- if (body.querySelector('.email-summary-panel')) return;
- const panel = document.createElement('div');
- panel.className = 'email-summary-panel';
- if (_summaryCollapsedPref()) panel.classList.add('collapsed');
- panel.innerHTML =
- '<div class="email-summary-header email-summary-toggle" role="button" tabindex="0">'
- + '<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>'
- + '<span>Summary</span>'
- + '<svg class="email-summary-chevron" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="margin-left:auto;transition:transform .15s ease;"><polyline points="6 9 12 15 18 9"/></svg>'
- + '</div>'
- + '<div class="email-summary-content"></div>';
- panel.querySelector('.email-summary-content').textContent = summary;
- body.insertBefore(panel, body.firstChild);
- const toggle = panel.querySelector('.email-summary-toggle');
- // Header click folds/unfolds. Persists so the next email opens in the
- // same state.
- const _flip = () => {
- panel.classList.toggle('collapsed');
- _setSummaryCollapsedPref(panel.classList.contains('collapsed'));
- };
- if (toggle) {
- toggle.addEventListener('click', (ev) => { ev.stopPropagation(); _flip(); });
- toggle.addEventListener('keydown', (ev) => {
- if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); _flip(); }
- });
- }
- if (btn) {
- btn.classList.add('active');
- const label = btn.querySelector('.btn-label');
- if (label) label.textContent = 'Summary';
- }
- }
-
- // Wire click handlers for attachment chips + "open in editor" sub-buttons
- // inside a reader. Safe to call multiple times — uses dataset.wired flag to
- // skip nodes that already have listeners.
- function _wireAttachmentHandlers(reader, folder) {
- const useFolder = folder || state._libFolder;
- // Detect mobile here so the attachment-chip handler doesn't blow up with
- // a ReferenceError when this fn is called from contexts that don't have
- // _isMobileUA in scope (e.g. _openEmailAsTab, _openEmailWindow).
- const _isMobileUA = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
- reader.querySelectorAll('.email-attachments-download-all').forEach(btn => {
- if (btn.dataset.wired === '1') return;
- btn.dataset.wired = '1';
- btn.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- ev.preventDefault();
- if (btn.dataset.downloading === '1') return;
- const uid = btn.dataset.attUid;
- const sourceFolder = btn.dataset.attFolder || useFolder;
- const count = Number(btn.dataset.attCount || 0);
- if (!uid) return;
- const originalHtml = btn.innerHTML;
- const originalTitle = btn.title;
- btn.dataset.downloading = '1';
- btn.classList.add('is-loading');
- try {
- const sp = window.spinnerModule || (await import('./spinner.js')).default;
- const wp = sp.createWhirlpool(12);
- wp.element.style.margin = '0';
- btn.textContent = '';
- btn.appendChild(wp.element);
- const label = document.createElement('span');
- label.textContent = 'All';
- btn.appendChild(label);
- } catch (_) {
- btn.textContent = 'All...';
- }
- try {
- const url = `${API_BASE}/api/email/attachments-download/${encodeURIComponent(uid)}?folder=${encodeURIComponent(sourceFolder)}${_acct()}`;
- const res = await fetch(url, { credentials: 'same-origin' });
- if (!res.ok) {
- const msg = await res.text().catch(() => '');
- console.error('attachments zip download failed', res.status, msg);
- location.href = url;
- return;
- }
- const blob = await res.blob();
- const blobUrl = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = blobUrl;
- a.download = `email-${uid}-attachments.zip`;
- document.body.appendChild(a);
- a.click();
- a.remove();
- setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
- try { uiModule.showToast && uiModule.showToast(`Downloading ${count || 'all'} attachments`); } catch (_) {}
- } catch (e) {
- console.error('attachments zip download error', e);
- try { const { showError } = await import('./ui.js?v=20260916largetoolscroll1'); showError('Could not download attachments'); } catch (_) {}
- } finally {
- delete btn.dataset.downloading;
- btn.classList.remove('is-loading');
- btn.title = originalTitle;
- btn.innerHTML = originalHtml;
- }
- });
- });
- reader.querySelectorAll('.email-attachment-calendar-open').forEach(openBtn => {
- if (openBtn.dataset.wired === '1') return;
- openBtn.dataset.wired = '1';
- openBtn.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- ev.preventDefault();
- if (openBtn.dataset.opening === '1') return;
- const uid = openBtn.dataset.openUid;
- const index = openBtn.dataset.openIndex;
- const name = openBtn.dataset.openName || `calendar-${index}`;
- const sourceFolder = openBtn.dataset.openFolder || useFolder;
- if (!uid || index == null) return;
- openBtn.dataset.opening = '1';
- openBtn.classList.add('is-loading');
- const originalHtml = openBtn.innerHTML;
- try {
- const wp = spinnerModule.createWhirlpool(12);
- wp.element.style.margin = '0';
- openBtn.textContent = '';
- openBtn.appendChild(wp.element);
- const folderQs = encodeURIComponent(sourceFolder);
- const attachmentUrl = `${API_BASE}/api/email/attachment/${encodeURIComponent(uid)}/${encodeURIComponent(index)}?folder=${folderQs}${_acct()}`;
- const attachmentRes = await fetch(attachmentUrl, { credentials: 'same-origin' });
- if (!attachmentRes.ok) throw new Error(`HTTP ${attachmentRes.status}`);
- const blob = await attachmentRes.blob();
- const fd = new FormData();
- fd.append('file', blob, name);
- const importRes = await fetch(`${API_BASE}/api/calendar/import`, {
- method: 'POST', body: fd, credentials: 'same-origin',
- });
- const result = await importRes.json().catch(() => ({}));
- if (!importRes.ok || !result.ok) {
- throw new Error(result.detail || result.error || `HTTP ${importRes.status}`);
- }
- const existingEventUid = Array.isArray(result.event_uids) ? String(result.event_uids[0] || '').trim() : '';
- if (existingEventUid && Number(result.imported || 0) === 0 && Number(result.skipped || 0) > 0) {
- _openCalendarEventFromEmail(existingEventUid);
- }
- try { uiModule.showToast && uiModule.showToast(`${result.imported || 0} event${result.imported === 1 ? '' : 's'} added to ${result.calendar || 'calendar'}`); } catch (_) {}
- window.dispatchEvent(new CustomEvent('calendar-refresh'));
- } catch (e) {
- console.error('calendar attachment import failed', e);
- try {
- const { showError } = await import('./ui.js?v=20260916largetoolscroll1');
- showError(`Couldn't add ${name} to calendar: ${e?.message || 'Import failed'}`);
- } catch (_) {}
- } finally {
- delete openBtn.dataset.opening;
- openBtn.classList.remove('is-loading');
- openBtn.innerHTML = originalHtml;
- }
- });
- });
- reader.querySelectorAll('.email-attachment-open').forEach(openBtn => {
- if (openBtn.dataset.wired === '1') return;
- openBtn.dataset.wired = '1';
- openBtn.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- ev.preventDefault();
- if (openBtn.dataset.opening === '1') return;
- const uid = openBtn.dataset.openUid;
- const index = openBtn.dataset.openIndex;
- const name = openBtn.dataset.openName || `attachment-${index}`;
- const sourceFolder = openBtn.dataset.openFolder || useFolder;
- if (!uid || index == null) return;
- openBtn.dataset.opening = '1';
- openBtn.classList.add('is-loading');
- const origHtml = openBtn.innerHTML;
- const wp = spinnerModule.createWhirlpool(12);
- wp.element.style.margin = '0';
- openBtn.textContent = '';
- openBtn.appendChild(wp.element);
- try {
- const folderQs = encodeURIComponent(sourceFolder);
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 55000);
- let res;
- try {
- res = await fetch(
- `${API_BASE}/api/email/attachment-as-doc/${encodeURIComponent(uid)}/${encodeURIComponent(index)}?folder=${folderQs}${_acct()}`,
- { method: 'POST', credentials: 'same-origin', signal: controller.signal }
- );
- } finally {
- clearTimeout(timeout);
- }
- const json = await res.json().catch(() => ({}));
- if (!res.ok || !json.doc_id) {
- const msg = (json && json.error) || `HTTP ${res.status}`;
- try { const { showError } = await import('./ui.js?v=20260916largetoolscroll1'); showError(`Couldn't open ${name}: ${msg}`); } catch (_) { alert(`Couldn't open ${name}: ${msg}`); }
- return;
- }
- try {
- // Tab the email modal down only when the viewport cannot fit both
- // Email and the document pane. Desktop keeps a side-by-side layout
- // when there is room; mobile still gives the document the screen.
- const ownerModal = openBtn.closest('.modal');
- if (ownerModal && ownerModal.id && _prepareEmailWindowForDocument(ownerModal)) {
- try {
- const ok = Modals.minimize(ownerModal.id);
- if (!ok) ownerModal.classList.add('hidden');
- } catch (_) {
- ownerModal.classList.add('hidden');
- }
- }
- const docMod = await import('./document.js?v=20260916docctx2');
- const load = (docMod && docMod.loadDocument) || (docMod && docMod.default && docMod.default.loadDocument);
- if (typeof load === 'function') {
- await load(json.doc_id);
- } else {
- location.href = `/?doc=${encodeURIComponent(json.doc_id)}`;
- }
- } catch (e) {
- console.error('Open document failed:', e);
- try { const { showError } = await import('./ui.js?v=20260916largetoolscroll1'); showError('Document opened but panel could not mount'); } catch (_) {}
- }
- } catch (e) {
- console.error('attachment-as-doc error', e);
- const msg = e && e.name === 'AbortError'
- ? `Opening ${name} timed out. Try downloading it instead.`
- : `Couldn't open ${name}`;
- try { const { showError } = await import('./ui.js?v=20260916largetoolscroll1'); showError(msg); } catch (_) {}
- } finally {
- delete openBtn.dataset.opening;
- openBtn.classList.remove('is-loading');
- openBtn.innerHTML = origHtml;
- }
- });
- });
-
- reader.querySelectorAll('.email-attachment-download').forEach(downloadBtn => {
- if (downloadBtn.dataset.wired === '1') return;
- downloadBtn.dataset.wired = '1';
- downloadBtn.addEventListener('click', (ev) => {
- ev.stopPropagation();
- ev.preventDefault();
- const chip = downloadBtn.closest('.email-attachment-chip');
- if (!chip) return;
- // Reuse the established attachment download handler below. Marking the
- // chip expanded bypasses its old first-click reveal behavior.
- chip.classList.add('is-expanded');
- chip.dataset.downloadTrigger = 'button';
- chip.click();
- });
- downloadBtn.addEventListener('keydown', (ev) => {
- if (ev.key !== 'Enter' && ev.key !== ' ') return;
- ev.preventDefault();
- downloadBtn.click();
- });
- });
-
- reader.querySelectorAll('.email-attachment-chip').forEach(chip => {
- if (chip.dataset.wired === '1') return;
- chip.dataset.wired = '1';
- chip.addEventListener('click', async (ev) => {
- if (ev.target.closest('.email-attachment-open, .email-attachment-calendar-open, .email-attachment-download')) return;
- ev.stopPropagation();
- ev.preventDefault();
- const uid = chip.dataset.attUid;
- const index = chip.dataset.attIndex;
- const name = chip.dataset.attName || `attachment-${index}`;
- const sourceFolder = chip.dataset.attFolder || useFolder;
- if (!uid || index == null) return;
- if (!chip.classList.contains('is-expanded')) {
- reader.querySelectorAll('.email-attachment-chip.is-expanded').forEach(other => {
- if (other !== chip) other.classList.remove('is-expanded');
- });
- chip.classList.add('is-expanded');
- return;
- }
- const url = `${API_BASE}/api/email/attachment/${encodeURIComponent(uid)}/${encodeURIComponent(index)}?folder=${encodeURIComponent(sourceFolder)}${_acct()}`;
- if (_isMobileUA) {
- delete chip.dataset.downloadTrigger;
- window.open(url, '_blank');
- return;
- }
- // Swap the paperclip icon for a whirlpool spinner while the
- // download is in flight, so large attachments give a clear cue
- // they're loading. Restore on completion.
- const buttonTriggered = chip.dataset.downloadTrigger === 'button';
- const iconSvg = buttonTriggered
- ? chip.querySelector('.email-attachment-download > svg')
- : chip.querySelector(':scope > svg');
- const origIconHtml = iconSvg ? iconSvg.outerHTML : '';
- let _wp = null;
- let _spinnerHost = null;
- try {
- const sp = window.spinnerModule || (await import('./spinner.js')).default;
- _wp = sp.createWhirlpool(12);
- _spinnerHost = document.createElement('span');
- _spinnerHost.className = 'email-attachment-spinner';
- _spinnerHost.style.cssText = 'display:inline-flex;width:12px;height:12px;align-items:center;justify-content:center;flex-shrink:0;position:relative;top:-2px;';
- _spinnerHost.appendChild(_wp.element);
- if (iconSvg) iconSvg.replaceWith(_spinnerHost);
- } catch (_) {}
- const origOpacity = chip.style.opacity;
- chip.style.opacity = '0.85';
- try {
- const res = await fetch(url, { credentials: 'same-origin' });
- if (!res.ok) {
- console.error('attachment download failed', res.status, await res.text().catch(() => ''));
- location.href = url;
- return;
- }
- const blob = await res.blob();
- const blobUrl = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = blobUrl;
- a.download = name;
- document.body.appendChild(a);
- a.click();
- a.remove();
- setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
- } catch (e) {
- console.error('attachment download error', e);
- location.href = url;
- } finally {
- delete chip.dataset.downloadTrigger;
- chip.style.opacity = origOpacity;
- if (_spinnerHost && _spinnerHost.parentNode && origIconHtml) {
- const tmp = document.createElement('div');
- tmp.innerHTML = origIconHtml;
- const restored = tmp.firstChild;
- if (restored) _spinnerHost.replaceWith(restored);
- }
- if (_wp) { try { _wp.destroy(); } catch (_) {} }
- }
- });
- });
- }
-
- // Heuristic: skip "attachments" that are clearly inline images used by
- // signatures / quoted-reply headers (small image files, Outlook-style
- // image001.png placeholders, logo*.png, etc.). They aren't real user-
- // shared attachments and adding them to the chips makes every email look
- // like it has content the user needs to act on.
- function _isLikelySignatureImage(a) {
- if (!a || !a.filename) return false;
- const name = String(a.filename).toLowerCase();
- const isImage = /\.(png|jpe?g|gif|bmp|svg|webp)$/i.test(name);
- if (!isImage) return false;
- const size = Number(a.size) || 0;
- // Outlook / Gmail inline image placeholders always look like this.
- if (/^image\d{3,}\.(png|jpe?g|gif)$/i.test(name)) return true;
- if (/^(signature|logo|sig|footer|banner)[-_\d]*\.(png|jpe?g|gif|svg)$/i.test(name)) return true;
- // Most signature logos / inline thumbnails are < 30 KB. Real user-
- // shared images (screenshots, photos) are typically 50 KB+.
- if (size > 0 && size < 30 * 1024) return true;
- return false;
- }
-
- // Build the attachments header+chips HTML for an email read response. Pulled
- // out so both the initial-open and the swap-reader paths can render it.
- function _buildAttsHtmlFor(uid, data) {
- if (!data) return '';
- const _OPENABLE_RE = /\.(pdf|docx|txt|md|markdown|eml)$/i;
- const _CALENDAR_RE = /\.(calendar|ics|ical)$/i;
- const currentAttachments = Array.isArray(data.attachments) ? data.attachments : [];
- const relatedAttachments = Array.isArray(data.related_attachments) ? data.related_attachments : [];
- if (!currentAttachments.length && !relatedAttachments.length) return '';
- const visible = currentAttachments.filter(a => !_isLikelySignatureImage(a));
- const hidden = currentAttachments.filter(a => _isLikelySignatureImage(a));
- const related = relatedAttachments.filter(a => !_isLikelySignatureImage(a));
- if (!visible.length && !related.length && state._libViewInlineImages === false) return '';
- const renderChip = (a, extraClass = '') => {
- const calendarAttachment = _CALENDAR_RE.test(a.filename || '');
- const openable = _OPENABLE_RE.test(a.filename || '');
- const chipUid = a.source_uid || a.uid || uid;
- const chipFolder = a.source_folder || data.folder || state._libFolder || 'INBOX';
- const openBtn = calendarAttachment
- ? `<span class="email-attachment-calendar-open" role="button" tabindex="0" aria-label="Add to calendar" title="Add to calendar" data-open-uid="${_esc(chipUid)}" data-open-index="${a.index}" data-open-name="${_esc(a.filename)}" data-open-folder="${_esc(chipFolder)}"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="17" rx="2"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/><path d="m8 15 2 2 5-5"/></svg></span>`
- : openable
- ? `<span class="email-attachment-open" role="button" tabindex="0" aria-label="Open in document editor" title="Open in document editor" data-open-uid="${_esc(chipUid)}" data-open-index="${a.index}" data-open-name="${_esc(a.filename)}" data-open-folder="${_esc(chipFolder)}"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="8" y1="13" x2="16" y2="13"/><line x1="8" y1="17" x2="16" y2="17"/><line x1="8" y1="9" x2="10" y2="9"/></svg></span>`
- : '';
- const downloadBtn = `<span class="email-attachment-download" role="button" tabindex="0" aria-label="Download attachment" title="Download attachment"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg></span>`;
- return `<button type="button" class="email-attachment-chip${extraClass}" data-att-uid="${_esc(chipUid)}" data-att-index="${a.index}" data-att-name="${_esc(a.filename)}" data-att-folder="${_esc(chipFolder)}"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 17.93 8.8l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg><span>${_esc(a.filename)}</span><span class="att-size">${Math.round((a.size||0)/1024)} KB</span>${openBtn}${downloadBtn}</button>`;
- };
- const chips = visible.map(a => renderChip(a)).join('');
- const hiddenChips = hidden.map(a => renderChip(a, ' email-attachment-chip-muted')).join('');
- const relatedChips = related.map(a => renderChip(a, ' email-attachment-chip-related')).join('');
- const visibleSection = visible.length
- ? '<div class="email-reader-atts">' + chips + '</div>'
- : '';
- const relatedSection = related.length
- ? '<div class="email-reader-atts-hidden-note">From earlier in this thread</div><div class="email-reader-atts email-reader-atts-related">' + relatedChips + '</div>'
- : '';
- const hiddenSection = hidden.length && state._libViewInlineImages !== false
- ? '<div class="email-reader-atts-hidden-note">Filtered inline images / signature files</div><div class="email-reader-atts email-reader-atts-hidden">' + hiddenChips + '</div>'
- : '';
- const label = visible.length
- ? `Attachments (${visible.length + related.length})`
- : related.length
- ? `Thread attachments (${related.length})`
- : state._libViewInlineImages === false
- ? 'Attachments'
- : `Hidden inline attachments (${hidden.length})`;
- const startCollapsed = !visible.length && !related.length;
- const downloadAllBtn = visible.length > 4
- ? `<button type="button" class="email-attachments-download-all" title="Download all attachments" data-att-uid="${_esc(uid)}" data-att-folder="${_esc(data.folder || state._libFolder || 'INBOX')}" data-att-count="${visible.length}"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg><span>All</span></button>`
- : '';
- return (
- `<div class="email-reader-atts-wrap${startCollapsed ? ' collapsed' : ''}">`
- + '<div class="email-reader-atts-header email-summary-toggle" role="button" tabindex="0">'
- + '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 17.93 8.8l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>'
- + `<span>${label}</span>`
- + downloadAllBtn
- + '<svg class="email-summary-chevron" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="margin-left:auto;transition:transform .15s ease;"><polyline points="6 9 12 15 18 9"/></svg>'
- + '</div>'
- + visibleSection
- + relatedSection
- + hiddenSection
- + '</div>'
- );
- }
-
- async function _ensureEmailAttachmentData(uid, folder, data, knownHasAttachments = false) {
- if (!data) return data;
- const current = Array.isArray(data.attachments) ? data.attachments : [];
- const related = Array.isArray(data.related_attachments) ? data.related_attachments : [];
- const shouldFetch = data.attachments_deferred || (knownHasAttachments && !current.length && !related.length);
- if (!shouldFetch) return data;
- try {
- const metaRes = await fetch(`${API_BASE}/api/email/attachments/${encodeURIComponent(uid)}?folder=${encodeURIComponent(folder || 'INBOX')}${_acct()}`);
- const meta = await metaRes.json().catch(() => ({}));
- if (metaRes.ok && Array.isArray(meta.attachments)) {
- return {
- ...data,
- attachments: meta.attachments,
- related_attachments: related,
- attachments_deferred: false,
- };
- }
- } catch (_) {}
- // Do not full-fetch the message during ordinary open. That can download and
- // parse large MIME bodies immediately after the reader renders, keeping IMAP
- // busy and making the UI feel stuck. Full attachment lookup is still available
- // from explicit attachment/download/forward actions.
- return data;
- }
-
- function _wireEmailAttachmentWrap(reader, folder) {
- if (!reader) return;
- const attsWrap = reader.querySelector('.email-reader-atts-wrap');
- if (attsWrap && !attsWrap.dataset.wired) {
- attsWrap.dataset.wired = '1';
- const attsToggle = attsWrap.querySelector('.email-reader-atts-header');
- if (attsToggle) {
- attsToggle.addEventListener('click', (ev) => {
- ev.stopPropagation();
- attsWrap.classList.toggle('collapsed');
- });
- attsToggle.addEventListener('keydown', (ev) => {
- if (ev.key === 'Enter' || ev.key === ' ') {
- ev.preventDefault();
- attsWrap.classList.toggle('collapsed');
- }
- });
- }
- }
- try { _wireAttachmentHandlers(reader, folder); } catch {}
- }
-
- function _loadDeferredAttachmentsIntoReader(reader, uid, folder, data, knownHasAttachments = false) {
- if (!reader || !uid || !data) return;
- const current = Array.isArray(data.attachments) ? data.attachments : [];
- const related = Array.isArray(data.related_attachments) ? data.related_attachments : [];
- if (!data.attachments_deferred && !(knownHasAttachments && !current.length && !related.length)) return;
- const body = reader.querySelector('.email-reader-body');
- if (!body) return;
- const loading = document.createElement('div');
- loading.className = 'email-reader-atts-wrap email-reader-atts-loading';
- loading.style.cssText = 'min-height:34px;display:flex;flex-direction:row;align-items:center;gap:7px;padding:6px 14px;color:var(--fg);font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.4px;opacity:.7;';
- const loadingSpinner = spinnerModule.createWhirlpool(12);
- loadingSpinner.element.style.margin = '0';
- loading.appendChild(loadingSpinner.element);
- loading.appendChild(document.createTextNode('Loading attachments…'));
- const existingWrap = reader.querySelector('.email-reader-atts-wrap');
- if (existingWrap) existingWrap.replaceWith(loading);
- else body.insertAdjacentElement('beforebegin', loading);
- _ensureEmailAttachmentData(uid, folder, data, knownHasAttachments).then(fullData => {
- if (!reader.isConnected || !fullData) return;
- loading.remove();
- try { loadingSpinner.destroy(); } catch (_) {}
- const visibleCurrent = (fullData.attachments || []).filter(a => !_isLikelySignatureImage(a));
- const matchingEmail = (state._libEmails || []).find(em => (
- String(em.uid) === String(uid)
- && String(em.account_id || state._libAccountId || '') === String(reader.closest('[data-email-account]')?.dataset.emailAccount || state._libAccountId || '')
- ));
- if (matchingEmail) matchingEmail.has_attachments = visibleCurrent.length > 0;
- if (!visibleCurrent.length) {
- reader.closest('.doclib-card')?.querySelector('.email-card-attachment')?.remove();
- }
- const attsHtml = _buildAttsHtmlFor(uid, fullData);
- if (!attsHtml) return;
- const oldWrap = reader.querySelector('.email-reader-atts-wrap');
- if (oldWrap) {
- const tmp = document.createElement('div');
- tmp.innerHTML = attsHtml;
- oldWrap.replaceWith(tmp.firstElementChild);
- } else {
- body.insertAdjacentHTML('beforebegin', attsHtml);
- }
- _wireEmailAttachmentWrap(reader, folder);
- }).catch(() => {
- loading.remove();
- try { loadingSpinner.destroy(); } catch (_) {}
- });
- }
-
- // "Open in new tab" — the email opens in the library (expanded inline)
- // AND a separate floating "email viewer" overlay modal is created. The
- // overlay starts minimized as a chip in the dock; tapping the chip
- // brings the viewer up over the library. Multiple tabs = multiple
- // overlay modals + chips, each independent.
- const _EMAIL_ICON_PATH = 'M2 4h20v16H2zM22 7l-9.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7';
- let _emailTabSeq = 0;
- // Persistent slot numbers per reader modalId. Once a reader is "tab 2"
- // it stays "tab 2" until it's closed — even if tab 1 closes first, the
- // remaining reader doesn't renumber down to 1. New tabs claim the
- // lowest unused slot.
- const _emailReaderSlots = new Map(); // modalId -> slot (1, 2, 3, ...)
- function _allocReaderSlot(modalId) {
- if (_emailReaderSlots.has(modalId)) return _emailReaderSlots.get(modalId);
- const used = new Set(_emailReaderSlots.values());
- let n = 1;
- while (used.has(n)) n++;
- _emailReaderSlots.set(modalId, n);
- return n;
- }
- function _freeReaderSlot(modalId) {
- _emailReaderSlots.delete(modalId);
- }
-
- // JS-driven gate: sets [data-email-tabs="N"] on <body> so CSS can show
- // the per-chip number badge only when 2+ tabs exist.
- function _syncEmailTabsCount() {
- const tabs = document.querySelectorAll('.minimized-dock-chip[data-modal-id^="email-view-"]');
- document.body.dataset.emailTabs = String(tabs.length);
- }
-
- // Recompute the email menu chip's tab-count whenever the dock contents
- // change. Counts "email-view-*" chips both inside #minimized-dock and
- // at body level (free-positioned chips on mobile). Result is written to
- // the email-lib-modal chip's data-tab-count attribute; CSS reads it via
- // attr() to render the badge.
- function _syncEmailTabBadge() {
- const readers = document.querySelectorAll('.minimized-dock-chip[data-modal-id^="email-reader-"]');
- document.body.dataset.emailReaders = String(readers.length);
- // Stamp each chip with its persistent slot number. CSS reads
- // data-tab-num via attr() instead of using a counter so the number
- // stays stable when other tabs close.
- readers.forEach(chip => {
- const slot = _emailReaderSlots.get(chip.dataset.modalId);
- if (slot) chip.dataset.tabNum = String(slot);
- });
- }
- let _emailTabObserverWired = false;
- let _badgeSyncScheduled = false;
- function _ensureEmailTabObserver() {
- if (_emailTabObserverWired) return;
- _emailTabObserverWired = true;
- // Debounce so a burst of mutations (e.g. _renderDock rebuilding the
- // whole dock in one pass) collapses to a single sync per animation
- // frame. Without this the chip badge could flicker as the observer
- // fires repeatedly during dock rerenders.
- const handler = () => {
- if (_badgeSyncScheduled) return;
- _badgeSyncScheduled = true;
- requestAnimationFrame(() => {
- _badgeSyncScheduled = false;
- _syncEmailTabBadge();
- });
- };
- const tryWire = () => {
- const dock = document.getElementById('minimized-dock');
- if (!dock) { setTimeout(tryWire, 200); return; }
- // Only watch what we care about: chip add/remove in the dock.
- const obs = new MutationObserver(handler);
- obs.observe(dock, { childList: true });
- // Watch the library grid so toggling a card expanded/collapsed
- // updates the lib chip's "has-expanded" badge in real time.
- const wireGridObs = () => {
- const grid = document.getElementById('email-lib-grid');
- if (!grid) { setTimeout(wireGridObs, 500); return; }
- const gridObs = new MutationObserver(handler);
- gridObs.observe(grid, { subtree: true, attributes: true, attributeFilter: ['class'] });
- };
- wireGridObs();
- handler();
- };
- tryWire();
- }
- // Hybrid model:
- // - email-lib-modal (the inbox library) is unique. Its chip just
- // restores it.
- // - Each "Open in new tab" creates a separate per-email reader modal
- // (id "email-reader-{uid}-{seq}") with the SAME structure & classes
- // as the library's inline reader, so they look identical. Each
- // reader registers its own dock chip with a number badge.
- async function _openEmailAsTab(em, folder) {
- const useFolder = folder || state._libFolder || 'INBOX';
- _emailTabSeq += 1;
- const modalId = `email-reader-${em.uid}-${_emailTabSeq}`;
- _allocReaderSlot(modalId);
-
- // Build the modal shell. Uses the same doclib-modal-content sizing
- // as the email library so it feels like a sibling window. The reader
- // body inside uses the exact same email-card-reader / email-reader-*
- // classes the inline reader uses → identical styling.
- const modal = document.createElement('div');
- modal.className = 'modal email-reader-tab-modal';
- modal.id = modalId;
- modal.innerHTML = `
- <div class="modal-content doclib-modal-content email-reader-tab-content" style="background:var(--bg);width:min(720px, 92vw);display:flex;flex-direction:column;">
- <div class="modal-header">
- <h4 style="display:flex;align-items:center;gap:6px;min-width:0;flex:1;">
- <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-left:8px;">${_esc(em.subject || '(no subject)')}</span>
- </h4>
- <button class="minimize-btn" type="button" title="Minimize">_</button>
- <button class="close-btn" type="button" title="Close">&#x2716;</button>
- </div>
- <div class="modal-body email-reader-tab-body" style="display:flex;flex-direction:column;overflow:hidden;flex:1;min-height:0;padding:0;">
- <div class="email-card-reader email-card-expanded" style="flex:1;min-height:0;display:flex;flex-direction:column;">
- <div class="email-reader-tab-loading" style="padding:24px;display:flex;justify-content:center;"></div>
- </div>
- </div>
- </div>
- `;
- document.body.appendChild(modal);
- // Inherit display from .modal (flex-center). z-index above the library
- // (which uses default .modal z-index 250) so the new tab sits on top.
- modal.style.zIndex = '270';
- // Opened last → email windows in front of any open doc (alternation flag).
- document.body.classList.add('email-front');
-
- Modals.register(modalId, {
- label: 'Email',
- icon: _EMAIL_ICON_PATH,
- closeFn: () => {
- modal.remove();
- _freeReaderSlot(modalId);
- Promise.resolve().then(_syncEmailTabBadge);
- },
- restoreFn: () => {
- // Reopened last → bring the email windows in front of any open doc.
- document.body.classList.add('email-front');
- // Mobile: only one email window visible at a time. Tapping this
- // chip chips down the library + any other reader, so the user
- // toggles between them via the dock instead of stacking.
- if (window.innerWidth <= 768) {
- try {
- if (Modals.isRegistered('email-lib-modal') && !Modals.isMinimized('email-lib-modal')) {
- Modals.minimize('email-lib-modal');
- }
- } catch {}
- document.querySelectorAll('.modal[id^="email-reader-"]').forEach(other => {
- if (other.id === modalId) return;
- try {
- if (Modals.isRegistered(other.id) && !Modals.isMinimized(other.id)) {
- Modals.minimize(other.id);
- }
- } catch {}
- });
- }
- },
- });
- // Wire the `_` minimize button via modalManager (it sees our .minimize-btn
- // already exists and just binds the click handler).
- try { Modals.injectMinimizeButton(modal, modalId); } catch {}
- // X button fully closes the tab (tears down and unregisters).
- modal.querySelector('.close-btn')?.addEventListener('click', (ev) => {
- ev.stopPropagation();
- Modals.close(modalId);
- });
-
- // Wire dragging on the header (desktop only). Matches the global pattern
- // in app.js initUIVisibility, but that runs once at boot and doesn't see
- // dynamically-created modals — so we replicate it here.
- const content = modal.querySelector('.modal-content');
- const mh = modal.querySelector('.modal-header');
- if (mh && content) {
- let dragX = 0, dragY = 0, startLeft = 0, startTop = 0, dragging = false;
- const startDrag = (clientX, clientY) => {
- dragging = true;
- const rect = content.getBoundingClientRect();
- dragX = clientX; dragY = clientY;
- startLeft = rect.left; startTop = rect.top;
- content.style.position = 'fixed';
- content.style.left = startLeft + 'px';
- content.style.top = startTop + 'px';
- content.style.margin = '0';
- };
- const onDrag = (e) => {
- if (!dragging) return;
- content.style.left = (startLeft + e.clientX - dragX) + 'px';
- content.style.top = (startTop + e.clientY - dragY) + 'px';
- };
- const stopDrag = () => {
- dragging = false;
- document.removeEventListener('mousemove', onDrag);
- document.removeEventListener('mouseup', stopDrag);
- };
- mh.addEventListener('mousedown', (e) => {
- if (e.target.closest('.close-btn, .minimize-btn, .modal-minimize-btn')) return;
- e.preventDefault();
- startDrag(e.clientX, e.clientY);
- document.addEventListener('mousemove', onDrag);
- document.addEventListener('mouseup', stopDrag);
- });
- }
-
- // Open the new tab in front, on top of the email library. The user
- // can tap `_` to tab it down to a chip when they're done reading.
- //
- // Mobile: bottom-sheet windows fill the viewport, so stacking multiple
- // readers on top of each other is confusing — only one window can be
- // meaningfully visible at a time. So when the new tab opens, chip down
- // the library AND any other email-reader-* tab that's currently up.
- // The user gets a stack of mini chips to toggle between them.
- if (window.innerWidth <= 768) {
- try {
- if (Modals.isRegistered('email-lib-modal') && !Modals.isMinimized('email-lib-modal')) {
- Modals.minimize('email-lib-modal');
- }
- } catch {}
- document.querySelectorAll('.modal[id^="email-reader-"]').forEach(other => {
- if (other.id === modalId) return;
- try {
- if (Modals.isRegistered(other.id) && !Modals.isMinimized(other.id)) {
- Modals.minimize(other.id);
- }
- } catch {}
- });
- }
- _ensureEmailTabObserver();
- _syncEmailTabBadge();
-
- // Fetch + render the email body using the exact same template as
- // _toggleCardPreview so the visuals match perfectly.
- const reader = modal.querySelector('.email-card-reader');
- const showFailedTab = (message) => {
- try { showToast(message || 'Failed to load email'); } catch (_) {}
- _showEmailReaderLoadError(reader, message, () => {
- try { Modals.close(modalId); } catch (_) { try { modal.remove(); } catch (_) {} }
- setTimeout(() => { _openEmailAsTab(em, useFolder); }, 0);
- });
- };
- _markEmailReaderActive(reader);
- const loading = modal.querySelector('.email-reader-tab-loading');
- if (loading) loading.remove();
- if (reader) {
- reader.classList.add('email-card-reader-loading');
- reader.innerHTML = _emailReaderSkeletonHtml();
- }
- try {
- const res = await fetch(`${API_BASE}/api/email/read/${em.uid}?folder=${encodeURIComponent(useFolder)}${_acct()}`);
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- let data = await res.json();
- if (data.error) {
- showFailedTab(`Failed to load email: ${data.error}`);
- return;
- }
- data = _normalizeEmailStateFlags({ ...em, ...data });
- Object.assign(em, data);
- _syncEmailDoneState(em.uid, data.is_answered);
- _syncEmailReadState(em.uid, true);
- _stampReaderContext(reader, data, useFolder, state._libAccountId);
- const buildChips = (str) => {
- if (!str) return '';
- return _splitRecipientList(str).map(a => {
- const name = _extractName(a);
- return _recipientChipHtml(a, name);
- }).join('');
- };
- const fromChip = _recipientChipHtml(`${data.from_name || ''} <${data.from_address || ''}>`, data.from_name || data.from_address, 'from-chip');
- let attsHtml = '';
- try { attsHtml = _buildAttsHtmlFor(em.uid, data); } catch {}
- reader.innerHTML = `
- <div class="email-reader-header">
- <div class="email-reader-meta">
- <div class="email-reader-meta-row email-reader-meta-from">
- <strong>From:</strong>
- <span class="recipient-chips">${fromChip}${_recipientMetaToggleHtml(data)}</span>
- </div>
- ${(data.to || data.cc) ? `<div class="email-reader-meta-details" hidden>
- ${data.to ? `<div class="email-reader-meta-row"><strong>To:</strong><span class="recipient-chips">${buildChips(data.to)}</span></div>` : ''}
- ${data.cc ? `<div class="email-reader-meta-row"><strong>Cc:</strong><span class="recipient-chips">${buildChips(data.cc)}</span></div>` : ''}
- </div>` : ''}
- <div class="email-reader-actions-inline">
- <button class="memory-toolbar-btn reader-icon-btn" data-act="ai-reply" title="${data.cached_ai_reply ? 'AI Reply (cached draft ready)' : 'AI Reply'}">${_aiReplyIcon(data)}<span class="reader-btn-label">AI reply</span></button>
- <button class="memory-toolbar-btn reader-icon-btn" data-act="reply" title="Reply"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg><span class="reader-btn-label">Reply</span></button>
- ${_hasMultipleRecipients(data) ? `<button class="memory-toolbar-btn reader-icon-btn" data-act="reply-all" title="Reply All"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="7 17 2 12 7 7"/><polyline points="12 17 7 12 12 7"/><path d="M22 18v-2a4 4 0 0 0-4-4H7"/></svg><span class="reader-btn-label">Reply all</span></button>` : ''}
- <button class="memory-toolbar-btn reader-icon-btn" data-act="forward" title="Forward"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 17 20 12 15 7"/><path d="M4 18v-2a4 4 0 0 1 4-4h12"/></svg><span class="reader-btn-label">Forward</span></button>
- <div class="email-reader-more-wrap" style="position:relative">
- <button class="memory-toolbar-btn reader-icon-btn" data-act="more" title="More actions"><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg><span class="reader-btn-label">More</span></button>
- </div>
- </div>
- </div>
- </div>
- ${attsHtml}
- <div class="email-reader-body${data.body_html ? ' html-body' : ''}">${_safeRenderEmailBody(data)}</div>
- `;
- _markEmailReaderActive(reader);
- reader.classList.remove('email-card-reader-loading');
- _wireRecipientChips(reader);
- _wireEmailAttachmentWrap(reader, useFolder);
- _wireEmailInlineImages(reader);
- _loadDeferredAttachmentsIntoReader(reader, em.uid, useFolder, data, !!em.has_attachments);
- _maybeAutoTranslateEmail(reader);
- reader.querySelector('[data-act="reply"]')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- _snapEmailModalToLeftSidebar(ev.currentTarget.closest('.modal'));
- if (state._onEmailClick) await state._onEmailClick({ email: em, emailData: data, mode: 'reply' });
- });
- reader.querySelector('[data-act="reply-all"]')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- _snapEmailModalToLeftSidebar(ev.currentTarget.closest('.modal'));
- if (state._onEmailClick) await state._onEmailClick({ email: em, emailData: data, mode: 'reply-all' });
- });
- reader.querySelector('[data-act="ai-reply"]')?.addEventListener('click', (ev) => _handleAiReplyButton(ev, em, data));
- reader.querySelector('[data-act="forward"]')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- if (state._onEmailClick) await state._onEmailClick({ email: em, emailData: data, mode: 'forward' });
- });
- reader.querySelector('[data-act="summarize"]')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- try { await _summarizeEmail(reader, data, ev.currentTarget); } catch {}
- });
- _wireMetaToggle(reader);
- _wireReaderActionOverflow(reader);
- reader.querySelector('[data-act="more"]')?.addEventListener('click', (ev) => {
- ev.stopPropagation();
- try { _showReaderMoreMenu(em, modal, reader, ev.currentTarget, data); } catch {}
- });
- } catch (err) {
- showFailedTab(err?.message ? `Failed to load email: ${err.message}` : 'Failed to load email');
- }
- }
-
-
- // "Open in new window" — spawns a floating draggable modal that shows just
- // the email content. Multiple windows can stack; each has its own DOM id
- // and close button. Uses `_makeDraggable` so dragging the header pans the
- // window around. Renders the body via _renderEmailBody for parity with the
- // expanded reader.
- let _emailWindowSeq = 0;
- async function _openEmailWindow(em, folder) {
- const useFolder = folder || state._libFolder || 'INBOX';
- _emailWindowSeq += 1;
- const winId = `email-window-${em.uid}-${_emailWindowSeq}`;
- const modal = document.createElement('div');
- modal.className = 'modal email-window-modal';
- modal.id = winId;
- modal.style.cssText = 'pointer-events:none;background:transparent;';
- modal.innerHTML = `
- <div class="modal-content email-window-content" style="width:min(640px, 92vw);display:flex;flex-direction:column;background:var(--bg);">
- <div class="modal-header">
- <h4 style="display:flex;align-items:center;gap:6px;min-width:0;flex:1;">
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0;"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>
- <span class="email-window-subject" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${_esc(em.subject || '(no subject)')}</span>
- </h4>
- <button class="close-btn" type="button" title="Close">&#x2716;</button>
- </div>
- <div class="modal-body email-window-body" style="overflow:auto;padding:14px 16px;flex:1;min-height:0;">
- <div class="email-window-loading" style="display:flex;justify-content:center;padding:24px;"></div>
- </div>
- </div>
- `;
- document.body.appendChild(modal);
- modal.style.display = 'block';
- const content = modal.querySelector('.modal-content');
- // Position offset from screen center so successive windows cascade.
- const isMobile = window.innerWidth <= 768;
- if (isMobile) {
- content.style.position = 'fixed';
- content.style.pointerEvents = 'auto';
- content.style.left = '0';
- content.style.right = '0';
- content.style.bottom = '0';
- content.style.top = 'auto';
- } else {
- content.style.position = 'fixed';
- content.style.pointerEvents = 'auto';
- requestAnimationFrame(() => {
- const w = content.offsetWidth, h = content.offsetHeight;
- const off = (_emailWindowSeq % 6) * 28;
- content.style.left = Math.max(20, (window.innerWidth - w) / 2 + off) + 'px';
- content.style.top = Math.max(20, (window.innerHeight - h) / 3 + off) + 'px';
- });
- }
- modal.querySelector('.close-btn')?.addEventListener('click', () => modal.remove());
- try { _makeDraggable(content, modal, 'email-window-fullscreen'); } catch {}
-
- // Load + render
- const bodyEl = modal.querySelector('.email-window-body');
- const loading = modal.querySelector('.email-window-loading');
- try {
- if (loading) loading.remove();
- if (bodyEl) {
- bodyEl.classList.add('email-card-reader', 'email-card-reader-loading');
- bodyEl.style.padding = '0';
- bodyEl.innerHTML = _emailReaderSkeletonHtml();
- }
- const res = await fetch(`${API_BASE}/api/email/read/${em.uid}?folder=${encodeURIComponent(useFolder)}${_acct()}`);
- let data = await res.json();
- if (data.error) {
- bodyEl.innerHTML = `<div style="color:var(--red,#e55);padding:16px;">${_esc(data.error)}</div>`;
- return;
- }
- data = _normalizeEmailStateFlags({ ...em, ...data });
- Object.assign(em, data);
- _syncEmailDoneState(em.uid, data.is_answered);
- _syncEmailReadState(em.uid, true);
- const subjEl = modal.querySelector('.email-window-subject');
- if (subjEl && data.subject) subjEl.textContent = data.subject;
- // Build recipient chips the same way the inline reader does so the
- // standalone viewer looks/feels exactly like a real email view.
- const _chipsFor = (addrs) => {
- if (!addrs) return '';
- const list = _splitRecipientList(addrs);
- return list.map(a => {
- const name = _extractName(a);
- return _recipientChipHtml(a, name);
- }).join('');
- };
- const fromChip = _recipientChipHtml(`${data.from_name || ''} <${data.from_address || ''}>`, data.from_name || data.from_address, 'from-chip');
- let attsHtml = '';
- try { attsHtml = _buildAttsHtmlFor(em.uid, data); } catch {}
- // Repurpose bodyEl as a full email-card-reader so the inline reader's
- // CSS applies (sized header, action buttons in two rows, etc.).
- bodyEl.classList.add('email-card-reader');
- bodyEl.classList.remove('email-card-reader-loading');
- _stampReaderContext(bodyEl, { ...em, ...data }, useFolder, state._libAccountId);
- _markEmailReaderActive(bodyEl);
- bodyEl.style.padding = '0';
- bodyEl.innerHTML = `
- <div class="email-reader-header">
- <div class="email-reader-meta">
- <div class="email-reader-meta-row email-reader-meta-from">
- <strong>From:</strong>
- <span class="recipient-chips">${fromChip}${_recipientMetaToggleHtml(data)}</span>
- </div>
- ${(data.to || data.cc) ? `<div class="email-reader-meta-details" hidden>
- ${data.to ? `<div class="email-reader-meta-row"><strong>To:</strong><span class="recipient-chips">${_chipsFor(data.to)}</span></div>` : ''}
- ${data.cc ? `<div class="email-reader-meta-row"><strong>Cc:</strong><span class="recipient-chips">${_chipsFor(data.cc)}</span></div>` : ''}
- </div>` : ''}
- <div class="email-reader-actions-inline">
- <button class="memory-toolbar-btn reader-icon-btn" data-act="ai-reply" title="${data.cached_ai_reply ? 'AI Reply (cached draft ready)' : 'AI Reply (suggest a draft)'}">${_aiReplyIcon(data)}<span class="reader-btn-label">AI reply</span></button>
- <button class="memory-toolbar-btn reader-icon-btn" data-act="reply" title="Reply"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg><span class="reader-btn-label">Reply</span></button>
- ${_hasMultipleRecipients(data) ? `<button class="memory-toolbar-btn reader-icon-btn" data-act="reply-all" title="Reply All"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="7 17 2 12 7 7"/><polyline points="12 17 7 12 12 7"/><path d="M22 18v-2a4 4 0 0 0-4-4H7"/></svg><span class="reader-btn-label">Reply all</span></button>` : ''}
- <button class="memory-toolbar-btn reader-icon-btn" data-act="forward" title="Forward"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 17 20 12 15 7"/><path d="M4 18v-2a4 4 0 0 1 4-4h12"/></svg><span class="reader-btn-label">Forward</span></button>
- <div class="email-reader-more-wrap" style="position:relative">
- <button class="memory-toolbar-btn reader-icon-btn" data-act="more" title="More actions"><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg><span class="reader-btn-label">More</span></button>
- </div>
- </div>
- </div>
- </div>
- ${attsHtml}
- <div class="email-reader-body${data.body_html ? ' html-body' : ''}">${_safeRenderEmailBody(data)}</div>
- `;
- _markEmailReaderActive(bodyEl);
- _wireRecipientChips(bodyEl);
- // Wire all the same action handlers the inline reader has.
- _wireEmailAttachmentWrap(bodyEl, useFolder);
- _wireEmailInlineImages(bodyEl);
- _loadDeferredAttachmentsIntoReader(bodyEl, em.uid, useFolder, data, !!em.has_attachments);
- _maybeAutoTranslateEmail(bodyEl);
- bodyEl.querySelector('[data-act="reply"]')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- _snapEmailModalToLeftSidebar(ev.currentTarget.closest('.modal'));
- if (state._onEmailClick) await state._onEmailClick({ email: em, emailData: data, mode: 'reply' });
- });
- bodyEl.querySelector('[data-act="reply-all"]')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- _snapEmailModalToLeftSidebar(ev.currentTarget.closest('.modal'));
- if (state._onEmailClick) await state._onEmailClick({ email: em, emailData: data, mode: 'reply-all' });
- });
- bodyEl.querySelector('[data-act="ai-reply"]')?.addEventListener('click', (ev) => _handleAiReplyButton(ev, em, data));
- bodyEl.querySelector('[data-act="forward"]')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- if (state._onEmailClick) await state._onEmailClick({ email: em, emailData: data, mode: 'forward' });
- });
- bodyEl.querySelector('[data-act="summarize"]')?.addEventListener('click', async (ev) => {
- ev.stopPropagation();
- try { await _summarizeEmail(bodyEl, data, ev.currentTarget); } catch {}
- });
- _wireMetaToggle(bodyEl);
- _wireReaderActionOverflow(bodyEl);
- bodyEl.querySelector('[data-act="more"]')?.addEventListener('click', (ev) => {
- ev.stopPropagation();
- // Use a synthetic "card" — the more-menu only needs the anchor
- // element and the email data. The card param is mostly used to find
- // the next sibling; the standalone window has none so we just pass
- // bodyEl as a stand-in.
- try { _showReaderMoreMenu(em, modal, bodyEl, ev.currentTarget, data); } catch {}
- });
- } catch (err) {
- bodyEl.innerHTML = `<div style="color:var(--red,#e55);padding:16px;">Failed to load: ${_esc(String(err))}</div>`;
- }
- }
-
- async function _summarizeEmail(reader, data, btn) {
- const body = reader.querySelector('.email-reader-body');
- if (!body) return;
-
- // If a summary panel already exists, toggle: hide/show
- const existing = body.querySelector('.email-summary-panel');
- if (existing) {
- if (existing.style.display === 'none') {
- existing.style.display = '';
- if (btn) {
- btn.classList.add('active');
- btn.querySelector('.btn-label').textContent = 'Summary';
- }
- } else {
- existing.style.display = 'none';
- if (btn) {
- btn.classList.remove('active');
- btn.querySelector('.btn-label').textContent = 'Summary';
- }
- }
- return;
- }
-
- // No panel yet. If the email has no cached AI summary, show a placeholder
- // "not generated — create now?" prompt instead of firing the LLM immediately.
- // This avoids accidental LLM spend and makes the state explicit to the user.
- if (!data.cached_summary) {
- const prompt = document.createElement('div');
- prompt.className = 'email-summary-panel';
- prompt.innerHTML = `
- <div class="email-summary-header">
- <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>
- <span>Summary</span>
- </div>
- <div class="email-summary-content" style="white-space:normal;display:flex;align-items:center;flex-wrap:wrap;gap:6px;"><span style="opacity:0.65">No AI summary generated.</span><button class="memory-toolbar-btn" data-act="summary-generate" style="font-size:10px;margin-left:auto;">Generate now</button></div>`;
- body.insertBefore(prompt, body.firstChild);
- if (btn) {
- btn.classList.add('active');
- const label = btn.querySelector('.btn-label');
- if (label) label.textContent = 'Summary';
- }
- // No Cancel button — toggling the Summary button again hides this panel
- // (handled by the existing-panel branch above), so it'd be redundant.
- prompt.querySelector('[data-act="summary-generate"]').addEventListener('click', async (ev) => {
- ev.stopPropagation();
- prompt.remove();
- await _generateSummary(reader, data, btn);
- });
- return;
- }
-
- // Cached summary exists — show it immediately.
- await _generateSummary(reader, data, btn);
- }
-
- async function _generateSummary(reader, data, btn) {
- const body = reader.querySelector('.email-reader-body');
- if (!body) return;
-
- const panel = document.createElement('div');
- panel.className = 'email-summary-panel';
- panel.innerHTML =
- '<div class="email-summary-header email-summary-toggle" role="button" tabindex="0">'
- + '<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>'
- + '<span>Summary</span>'
- + '<svg class="email-summary-chevron" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="margin-left:auto;transition:transform .15s ease;"><polyline points="6 9 12 15 18 9"/></svg>'
- + '</div>'
- + '<div class="email-summary-content"></div>';
- if (_summaryCollapsedPref()) panel.classList.add('collapsed');
- body.insertBefore(panel, body.firstChild);
- const _genToggle = panel.querySelector('.email-summary-toggle');
- if (_genToggle) {
- const _genFlip = () => {
- panel.classList.toggle('collapsed');
- _setSummaryCollapsedPref(panel.classList.contains('collapsed'));
- };
- _genToggle.addEventListener('click', (ev) => { ev.stopPropagation(); _genFlip(); });
- _genToggle.addEventListener('keydown', (ev) => {
- if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); _genFlip(); }
- });
- }
-
- const sp = spinnerModule.createWhirlpool(18);
- const content = panel.querySelector('.email-summary-content');
- content.appendChild(sp.element);
-
- if (btn) btn.disabled = true;
- try {
- const res = await fetch(`${API_BASE}/api/email/summarize`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- body: data.body,
- subject: data.subject,
- from: `${data.from_name} <${data.from_address}>`,
- // Send identifiers so the backend can fetch the raw message and
- // pull attachment text for the summary (PDFs, invoices, etc.).
- uid: data.uid || '',
- folder: state._libFolder || 'INBOX',
- message_id: data.message_id || '',
- account_id: data.account_id || '',
- }),
- });
- const result = await res.json();
- sp.destroy();
- content.innerHTML = '';
- if (result.success && result.summary) {
- content.textContent = result.summary;
- if (btn) {
- btn.classList.add('active');
- const label = btn.querySelector('.btn-label');
- if (label) label.textContent = 'Summary';
- }
- } else {
- _renderEmailSummaryError(content, result);
- }
- } catch (e) {
- sp.destroy();
- _renderEmailSummaryError(content, null);
- if (uiModule) uiModule.showError?.('Failed to summarize');
- } finally {
- if (btn) btn.disabled = false;
- }
- }
-
- function _emailBodyTextForTranslate(reader) {
- const body = reader?.querySelector?.('.email-reader-body');
- if (!body) return '';
- const clone = body.cloneNode(true);
- clone.querySelectorAll('.email-summary-panel, details.email-quote-fold, details.email-sig-fold').forEach(n => n.remove());
- return (clone.innerText || clone.textContent || '').trim();
- }
-
- async function _translateEmail(reader, language, opts = {}) {
- const body = reader?.querySelector?.('.email-reader-body');
- if (!body) return;
- const existing = body.querySelector('.email-translation-panel');
- if (existing) {
- if (opts.auto && !opts.force) return;
- existing.remove();
- }
- const targetLanguage = language || 'English';
- const sourceText = _emailBodyTextForTranslate(reader);
- if (!sourceText) {
- try { uiModule?.showError?.('No email body to translate'); } catch {}
- return;
- }
-
- body.querySelectorAll('.email-translation-panel').forEach(p => p.remove());
- const panel = document.createElement('div');
- panel.className = 'email-summary-panel email-translation-panel';
- panel.innerHTML =
- '<div class="email-summary-header email-summary-toggle" role="button" tabindex="0">'
- + '<svg class="email-translation-icon" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m5 8 6 6"/><path d="m4 14 6-6 2-3"/><path d="M2 5h12"/><path d="M7 2h1"/><path d="m22 22-5-10-5 10"/><path d="M14 18h6"/></svg>'
- + `<span>Translation · ${_esc(targetLanguage)}</span>`
- + '<svg class="email-summary-chevron" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="margin-left:auto;transition:transform .15s ease;"><polyline points="6 9 12 15 18 9"/></svg>'
- + '</div>'
- + '<div class="email-summary-content email-translation-loading"><span class="email-translation-busy"><span class="email-translation-spinner"></span><span class="email-translation-loading-text">Translating...</span></span></div>';
- body.insertBefore(panel, body.firstChild);
- const translationToggle = panel.querySelector('.email-summary-toggle');
- if (translationToggle) {
- const flip = () => panel.classList.toggle('collapsed');
- translationToggle.addEventListener('click', (ev) => { ev.stopPropagation(); flip(); });
- translationToggle.addEventListener('keydown', (ev) => {
- if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); flip(); }
- });
- }
-
- const content = panel.querySelector('.email-summary-content');
- const sp = spinnerModule.createWhirlpool(18);
- content.querySelector('.email-translation-spinner')?.appendChild(sp.element);
- try {
- const res = await fetch(`${API_BASE}/api/email/translate`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- body: sourceText,
- subject: reader.dataset.emailSubject || '',
- from: reader.dataset.emailFrom || '',
- target_language: targetLanguage,
- auto: !!opts.auto,
- }),
- });
- const result = await res.json().catch(() => ({}));
- sp.destroy();
- content.innerHTML = '';
- if (res.ok && result.success && result.same_language) {
- panel.remove();
- } else if (res.ok && result.success && result.translation) {
- content.textContent = String(result.translation || '')
- .replace(/^\s*<<<TRANSLATION>>>\s*/i, '')
- .replace(/\s*<<<END>>>\s*$/i, '')
- .trim();
- } else {
- panel.remove();
- try { uiModule?.showError?.(result.error || 'Failed to translate'); } catch {}
- }
- } catch (_) {
- sp.destroy();
- panel.remove();
- try { uiModule?.showError?.('Failed to translate'); } catch {}
- }
- }
-
- async function _maybeAutoTranslateEmail(reader) {
- if (reader) reader.dataset.autoTranslateChecked = '1';
- }
-
- // Keep an email ⋮ dropdown inside the viewport: when it would spill past the
- // bottom (e.g. an email low on a phone screen), flip it above the anchor if
- // there's more room up there, and cap height + scroll if it still overflows.
- function _fitEmailDropdown(dropdown, rect) {
- requestAnimationFrame(() => {
- const margin = 8;
- // Horizontal clamp — keep the dropdown inside the viewport regardless of
- // whether it was anchored via left or right. Needed now that some
- // triggers (e.g. the right-aligned bulk "Actions" button) sit close to
- // the right edge, where a left-anchored menu would spill off-screen.
- const dw = dropdown.offsetWidth;
- const curLeft = dropdown.getBoundingClientRect().left;
- if (curLeft + dw > window.innerWidth - margin) {
- dropdown.style.left = Math.max(margin, window.innerWidth - margin - dw) + 'px';
- dropdown.style.right = 'auto';
- } else if (curLeft < margin) {
- dropdown.style.left = margin + 'px';
- dropdown.style.right = 'auto';
- }
- // Vertical fit — flip up or cap+scroll if it doesn't fit below.
- const dh = dropdown.offsetHeight;
- const below = window.innerHeight - rect.bottom - margin;
- const above = rect.top - margin;
- if (dh <= below) return; // fits below as-is
- if (above > below) { // flip upward
- dropdown.style.top = 'auto';
- dropdown.style.bottom = (window.innerHeight - rect.top + 4) + 'px';
- if (dh > above) { dropdown.style.maxHeight = above + 'px'; dropdown.style.overflowY = 'auto'; }
- } else { // keep below, cap + scroll
- dropdown.style.maxHeight = below + 'px';
- dropdown.style.overflowY = 'auto';
- }
- });
- }
-
- function _fitReaderActions(meta) {
- const row = meta?.querySelector(':scope > .email-reader-actions-inline');
- if (!row) return;
- const candidates = row.querySelectorAll(':scope > .reader-icon-btn:not([data-act="more"]), :scope > :not(.email-reader-more-wrap) > .reader-icon-btn');
- candidates.forEach(button => button.classList.remove('reader-action-overflowed'));
- row.classList.remove('email-reader-actions-compact');
- const buttonsWidth = Array.from(row.children).reduce((sum, child) => sum + child.getBoundingClientRect().width, 0)
- + Math.max(0, row.children.length - 1) * 4;
- const compact = buttonsWidth > Math.max(190, meta.clientWidth - 150);
- row.classList.toggle('email-reader-actions-compact', compact);
- if (compact) {
- // Keep the two common drafting actions visible on narrow screens. Put
- // the less frequent recipient variants in More first.
- row.querySelectorAll('[data-act="reply-all"], [data-act="forward"]')
- .forEach(button => button.classList.add('reader-action-overflowed'));
- }
- }
-
- const _readerActionFitObserver = typeof ResizeObserver === 'function'
- ? new ResizeObserver(entries => {
- for (const entry of entries) _fitReaderActions(entry.target);
- })
- : null;
-
- function _wireReaderActionOverflow(reader) {
- const meta = reader?.querySelector('.email-reader-meta');
- if (!meta) return;
- requestAnimationFrame(() => _fitReaderActions(meta));
- _readerActionFitObserver?.observe(meta);
- }
-
- function _showReaderMoreMenu(em, card, reader, anchor, data) {
- // Toggle: if a dropdown for THIS anchor is already open, close it.
- const existing = document.querySelector('.email-card-dropdown');
- if (existing && existing._anchor === anchor) {
- dismissOrRemove(existing);
- return;
- }
- // Otherwise close any other open dropdown (its own teardown clears its
- // anchor's active state) before opening a fresh one.
- document.querySelectorAll('.email-card-dropdown').forEach(dismissOrRemove);
-
- const dropdown = document.createElement('div');
- dropdown.className = 'email-card-dropdown';
- dropdown._anchor = anchor;
- anchor.classList.add('reader-more-active');
- const rect = anchor.getBoundingClientRect();
- dropdown.style.cssText = `position:fixed;z-index:${topPortalZ()};min-width:180px;background:var(--panel,var(--bg));border:1px solid var(--border);border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,0.3);padding:4px;font-size:12px;top:${rect.bottom + 4}px;right:${window.innerWidth - rect.right}px;`;
-
- const _icon = (svg) => `<span class="dropdown-icon">${svg}</span>`;
- const _unreadIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="3" fill="currentColor"/></svg>';
- const _archIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"/><path d="M10 12h4"/></svg>';
- const _spamIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>';
- const _trashIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/></svg>';
- const _deleteForeverIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="14" y2="15"/><line x1="14" y1="11" x2="10" y2="15"/></svg>';
- const _bellIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>';
- const _newTabIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>';
- const _checkIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
- const _translateIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--accent-primary, var(--red))" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m5 8 6 6"/><path d="m4 14 6-6 2-3"/><path d="M2 5h12"/><path d="M7 2h1"/><path d="m22 22-5-10-5 10"/><path d="M14 18h6"/></svg>';
-
- const closeAndRemove = async () => {
- // Pick the next neighbour BEFORE we re-render so we know which email to
- // jump to. Prefer the next card; fall back to the previous one if this
- // was the last card.
- const sibling = _findSiblingEmailCard(card, +1) || _findSiblingEmailCard(card, -1);
- const nextUid = sibling ? sibling.dataset.uid : null;
- await _animateEmailCardRemoval([em.uid]);
- state._libEmails = state._libEmails.filter(e => String(e.uid) !== String(em.uid));
- _renderGrid();
- _libCacheWriteBack();
- if (!nextUid) return;
- // After _renderGrid, the card nodes are fresh — re-resolve and expand.
- const grid = document.getElementById('email-lib-grid');
- const nextCard = grid?.querySelector(`.doclib-card[data-uid="${CSS.escape(String(nextUid))}"]`);
- const nextEm = state._libEmails.find(e => String(e.uid) === String(nextUid));
- if (nextCard && nextEm) {
- _toggleCardPreview(nextCard, nextEm);
- nextCard.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
- }
- };
-
- const _bubblesIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>';
- const _contactIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg>';
- // Three groups separated by dividers:
- // 1. Open / Mark Unread / Remind — the per-email view actions
- // 2. Save sender / Not Done / Archive — non-destructive state changes
- // 3. Move to Spam / Move to Trash / Delete — destructive
- const overflowActions = Array.from(reader.querySelectorAll('.reader-action-overflowed')).map(button => ({
- label: button.querySelector('.reader-btn-label')?.textContent?.trim() || button.title || 'Action',
- icon: button.querySelector('svg')?.outerHTML || '',
- button,
- action: (positionAnchor) => {
- if (button.dataset.act === 'ai-reply') {
- _handleAiReplyButton({
- currentTarget: button,
- stopPropagation() {},
- }, em, data, positionAnchor || button);
- } else {
- button.click();
- }
- },
- }));
- const actions = [
- ...overflowActions,
- ...(overflowActions.length ? [{ separator: true }] : []),
- {
- label: 'Open in new tab',
- icon: _newTabIcon,
- action: async () => {
- const folder = state._libFolder || 'INBOX';
- await _openEmailAsTab(em, folder);
- },
- },
- {
- label: 'Remind to reply',
- icon: _bellIcon,
- submenu: 'remind',
- },
- {
- label: 'Translate',
- icon: _translateIcon,
- submenu: 'translate',
- },
- { separator: true },
- {
- label: em.is_read ? 'Mark as Unread' : 'Mark as Read',
- icon: _unreadIcon,
- action: async () => {
- const newRead = !em.is_read;
- _syncEmailReadState(em.uid, newRead);
- try {
- if (newRead) {
- await fetch(`${API_BASE}/api/email/mark-read/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- } else {
- await fetch(`${API_BASE}/api/email/mark-unread/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- }
- } catch (e) { console.error(e); }
- _renderGrid();
- },
- },
- {
- // Favorite (pin to top). Same bookmark glyph we use for the
- // sidebar-pin / favorites filter so the visual language stays
- // consistent. Toggling updates em.is_flagged and re-sorts via
- // _renderGrid (favorited rows are always pinned at the top).
- label: em.is_flagged ? 'Unfavorite' : 'Favorite (pin to top)',
- icon: '<svg width="14" height="14" viewBox="0 0 24 24" fill="' + (em.is_flagged ? 'currentColor' : 'none') + '" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>',
- action: async () => {
- const next = !em.is_flagged;
- em.is_flagged = next;
- _renderGrid();
- try {
- await fetch(`${API_BASE}/api/email/flag/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}&on=${next ? 'true' : 'false'}`, { method: 'POST' });
- } catch (e) {
- // Roll back the optimistic flip if the server didn't take it.
- em.is_flagged = !next;
- _renderGrid();
- console.error('Failed to toggle favorite:', e);
- }
- },
- },
- {
- label: em.is_answered ? 'Mark as Not Done' : 'Mark as Done',
- icon: _checkIcon,
- action: async () => {
- const newState = !em.is_answered;
- em.is_answered = newState;
- if (newState) {
- _clearDoneResponseTagsLocal(em);
- _syncEmailReadState(em.uid, true);
- }
- try {
- if (newState) {
- await fetch(`${API_BASE}/api/email/mark-answered/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- await fetch(`${API_BASE}/api/email/mark-read/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- } else {
- await fetch(`${API_BASE}/api/email/clear-answered/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- }
- } catch (e) { console.error('Failed to toggle done:', e); }
- _renderGrid();
- },
- },
- {
- label: 'Move to Archive',
- icon: _archIcon,
- action: async () => {
- try {
- await fetch(`${API_BASE}/api/email/archive/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- } catch (e) { console.error(e); }
- await closeAndRemove();
- },
- },
- {
- // Save the sender to CardDAV contacts. Pulls name + address off the
- // list-item (em); falls back to splitting the local-part for a name.
- label: 'Save sender to contacts',
- icon: _contactIcon,
- action: async () => {
- const email = (em.from_address || em.from || '').trim();
- if (!email) {
- import('./ui.js?v=20260916largetoolscroll1').then(m => m.showError && m.showError('No sender address')).catch(() => {});
- return;
- }
- const name = (em.from_name || '').trim() || email.split('@')[0];
- try {
- const r = await fetch(`${API_BASE}/api/contacts/add`, {
- method: 'POST', credentials: 'same-origin',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name, email }),
- });
- const d = await r.json();
- import('./ui.js?v=20260916largetoolscroll1').then(m => {
- if (!m.showToast) return;
- if (d.success && d.message === 'Already exists') m.showToast('Already in contacts');
- else if (d.success) m.showToast('Saved to contacts');
- else m.showError && m.showError('Failed to save contact');
- }).catch(() => {});
- } catch (_) {
- import('./ui.js?v=20260916largetoolscroll1').then(m => m.showError && m.showError('Failed to save contact')).catch(() => {});
- }
- },
- },
- { separator: true },
- {
- label: 'Move to Spam',
- icon: _spamIcon,
- action: async () => {
- try {
- await fetch(`${API_BASE}/api/email/move/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}&dest=Junk`, { method: 'POST' });
- } catch (e) { console.error(e); }
- await closeAndRemove();
- },
- },
- {
- label: 'Move to Trash',
- icon: _trashIcon,
- action: async () => {
- const busy = _showEmailDeleteOverlay(card);
- await busy?.ready;
- try {
- const response = await fetch(`${API_BASE}/api/email/delete/${encodeURIComponent(em.uid)}?${_emailMutationQuery(em)}`, { method: 'DELETE' });
- await _requireSuccessfulEmailMutation(response, 'Failed to delete email');
- } catch (e) {
- console.error(e);
- busy?.remove?.();
- showToast('Failed to delete email');
- return;
- }
- busy?.remove?.();
- await closeAndRemove();
- },
- },
- {
- label: 'Delete Permanently',
- icon: _deleteForeverIcon,
- danger: true,
- action: async () => {
- const subject = em.subject || '(no subject)';
- const ok = await styledConfirm(
- `Permanently delete "${subject}"? This cannot be undone.`,
- { confirmText: 'Delete', cancelText: 'Cancel', danger: true }
- );
- if (!ok) return;
- const busy = _showEmailDeleteOverlay(card);
- await busy?.ready;
- try {
- const response = await fetch(`${API_BASE}/api/email/delete-permanent/${encodeURIComponent(em.uid)}?${_emailMutationQuery(em)}`, { method: 'DELETE' });
- await _requireSuccessfulEmailMutation(response, 'Failed to delete email');
- } catch (e) {
- console.error(e);
- busy?.remove?.();
- showToast('Failed to delete email');
- return;
- }
- busy?.remove?.();
- await closeAndRemove();
- },
- },
- ];
-
- for (const a of actions) {
- if (a.separator) {
- const sep = document.createElement('div');
- sep.className = 'dropdown-divider';
- dropdown.appendChild(sep);
- continue;
- }
- const item = document.createElement('div');
- item.className = 'dropdown-item-compact' + (a.danger ? ' dropdown-item-danger' : '');
- const arrow = a.submenu ? '<span style="margin-left:auto;opacity:0.5;">›</span>' : '';
- item.innerHTML = _icon(a.icon) + `<span>${a.label}</span>${arrow}`;
- item.addEventListener('click', (e) => {
- e.stopPropagation();
- if (a.submenu === 'remind') {
- _showLibRemindSubmenu(em, dropdown);
- return;
- }
- if (a.submenu === 'translate') {
- _showEmailTranslateSubmenu(reader, dropdown);
- return;
- }
- // A hidden overflowed button has a zero-sized client rect. Invoke the
- // AI chooser while the visible More item is still mounted, then close
- // the action menu after the chooser has captured its position.
- if (a.button?.dataset.act === 'ai-reply') {
- a.action(item);
- close();
- return;
- }
- close();
- a.action();
- });
- dropdown.appendChild(item);
- }
- // Mobile-only Cancel item — explicit close for touch users. CSS hides it
- // on desktop where outside-click already dismisses cleanly.
- const _cancelIco = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
- const cancelItem = document.createElement('div');
- cancelItem.className = 'dropdown-item-compact dropdown-cancel-mobile';
- cancelItem.innerHTML = _icon(_cancelIco) + '<span>Cancel</span>';
- cancelItem.addEventListener('click', (e) => {
- e.stopPropagation();
- close();
- });
- dropdown.appendChild(cancelItem);
-
- document.body.appendChild(dropdown);
- _fitEmailDropdown(dropdown, rect);
- const close = bindMenuDismiss(dropdown, () => {
- dropdown.remove();
- anchor.classList.remove('reader-more-active');
- }, (ev) => !dropdown.contains(ev.target) && ev.target !== anchor);
- }
-
- function _showCardMenu(em, anchor) {
- const openMenu = document.querySelector('.email-card-dropdown:not(.email-bulk-menu)');
- if (openMenu && openMenu._emailMenuAnchor === anchor) {
- dismissOrRemove(openMenu);
- return;
- }
- document.querySelectorAll('.email-card-dropdown').forEach(dismissOrRemove);
-
- const dropdown = document.createElement('div');
- dropdown.className = 'email-card-dropdown';
- dropdown._emailMenuAnchor = anchor;
- const rect = anchor.getBoundingClientRect();
- dropdown.style.cssText = `position:fixed;z-index:${topPortalZ()};min-width:140px;background:var(--panel,var(--bg));border:1px solid var(--border);border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,0.3);padding:4px;font-size:12px;top:${rect.bottom + 4}px;right:${window.innerWidth - rect.right}px;`;
-
- const _icon = (svg) => `<span class="dropdown-icon">${svg}</span>`;
- const _replyIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg>';
- const _archIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"/><path d="M10 12h4"/></svg>';
- const _delIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/></svg>';
- const _unreadIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="3" fill="currentColor"/></svg>';
- const _checkIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
- const _cardBellIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>';
-
- const isSentFolder = /sent/i.test(state._libFolder);
-
- const _newTabIcon = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>';
- const actions = [
- { label: 'Open', icon: _replyIcon, action: async () => {
- // Just expand inline (same as tapping the row).
- const card = anchor.closest('.doclib-card');
- if (card && !card.classList.contains('doclib-card-expanded')) {
- await _toggleCardPreview(card, em);
- }
- }},
- { label: 'Open in new tab', icon: _newTabIcon, action: async () => {
- // Open this email as its own in-app modal that registers a dock
- // chip — multiple emails can be opened simultaneously, each gets
- // its own chip in the minimized dock.
- const folder = state._libFolder || 'INBOX';
- await _openEmailAsTab(em, folder);
- }},
- { label: 'Remind to reply', icon: _cardBellIcon, submenu: 'remind' },
- ];
-
- if (!isSentFolder) {
- // Source of truth = the visible "active" class on the card's done
- // check, so the menu label and the actual toggle behaviour can't
- // disagree with what the user sees.
- const _cardForLabel = anchor.closest('.doclib-card');
- const _checkForLabel = _cardForLabel ? _cardForLabel.querySelector('.email-card-done') : null;
- const _currentlyDone = _checkForLabel ? _checkForLabel.classList.contains('active') : !!em.is_answered;
- actions.push({
- label: _currentlyDone ? 'Not Done' : 'Done',
- icon: _checkIcon,
- action: async () => {
- const card = anchor.closest('.doclib-card');
- const check = card ? card.querySelector('.email-card-done') : null;
- const wasActive = check ? check.classList.contains('active') : !!em.is_answered;
- const newState = !wasActive;
- em.is_answered = newState;
- if (newState) {
- _clearDoneResponseTagsLocal(em);
- _syncEmailReadState(em.uid, true); // mark-done implies mark-read
- }
- try {
- if (newState) {
- await fetch(`${API_BASE}/api/email/mark-answered/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- await fetch(`${API_BASE}/api/email/mark-read/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- } else {
- await fetch(`${API_BASE}/api/email/clear-answered/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- }
- } catch (e) { console.error('Failed to toggle done:', e); }
- if (card) {
- if (check) check.classList.toggle('active', newState);
- if (newState) {
- _syncEmailReadState(em.uid, true);
- card.querySelectorAll('.email-tag-urgent, .email-tag-reply-soon, .email-tag-action-needed').forEach(n => n.remove());
- }
- }
- },
- });
- actions.push({
- label: em.is_flagged ? 'Unfavorite' : 'Favorite (pin to top)',
- icon: '<svg width="14" height="14" viewBox="0 0 24 24" fill="' + (em.is_flagged ? 'currentColor' : 'none') + '" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>',
- action: async () => {
- const next = !em.is_flagged;
- em.is_flagged = next;
- _renderGrid();
- try {
- await fetch(`${API_BASE}/api/email/flag/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}&on=${next ? 'true' : 'false'}`, { method: 'POST' });
- } catch (e) {
- em.is_flagged = !next;
- _renderGrid();
- console.error('Failed to toggle favorite:', e);
- }
- },
- });
- actions.push({
- label: 'Archive',
- icon: _archIcon,
- action: async () => {
- await fetch(`${API_BASE}/api/email/archive/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- await _animateEmailCardRemoval([em.uid]);
- state._libEmails = state._libEmails.filter(e => String(e.uid) !== String(em.uid));
- _renderGrid();
- _libCacheWriteBack();
- },
- });
- } else {
- actions.push({
- label: em.is_flagged ? 'Unfavorite' : 'Favorite (pin to top)',
- icon: '<svg width="14" height="14" viewBox="0 0 24 24" fill="' + (em.is_flagged ? 'currentColor' : 'none') + '" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>',
- action: async () => {
- const next = !em.is_flagged;
- em.is_flagged = next;
- _renderGrid();
- try {
- await fetch(`${API_BASE}/api/email/flag/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}&on=${next ? 'true' : 'false'}`, { method: 'POST' });
- } catch (e) {
- em.is_flagged = !next;
- _renderGrid();
- console.error('Failed to toggle favorite:', e);
- }
- },
- });
- actions.push({
- label: 'Archive',
- icon: _archIcon,
- action: async () => {
- await fetch(`${API_BASE}/api/email/archive/${em.uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- await _animateEmailCardRemoval([em.uid]);
- state._libEmails = state._libEmails.filter(e => String(e.uid) !== String(em.uid));
- _renderGrid();
- _libCacheWriteBack();
- },
- });
- }
-
- // "Select" — switch to multi-select mode with THIS email pre-selected so
- // the user can quickly fan-out to neighbours with the bulk bar.
- // Match the chat-sidebar Select icon — a thick bullet character reads
- // much heavier than a small SVG circle. Nudged up 2px so its visual
- // center lines up with the SVG icons above (which sit a bit higher).
- const _selectIcon = SELECT_MENU_ICON;
- actions.push({
- label: 'Select',
- icon: _selectIcon,
- action: () => {
- state._selectMode = true;
- state._selectedUids.add(em.uid);
- _updateBulkBar();
- _renderGrid();
- },
- });
-
- actions.push(
- { label: 'Delete', icon: _delIcon, danger: true, action: async () => {
- const subject = em.subject || '(no subject)';
- const ok = await styledConfirm(`Delete "${subject}"?`, { confirmText: 'Delete', cancelText: 'Cancel', danger: true });
- if (!ok) return;
- const card = document.querySelector(`#email-lib-grid .doclib-card[data-uid="${CSS.escape(String(em.uid))}"]`);
- const busy = _showEmailDeleteOverlay(card);
- await busy?.ready;
- try {
- const response = await fetch(`${API_BASE}/api/email/delete/${encodeURIComponent(em.uid)}?${_emailMutationQuery(em)}`, { method: 'DELETE' });
- await _requireSuccessfulEmailMutation(response, 'Failed to delete email');
- } catch (e) {
- busy?.remove?.();
- showToast(e?.message || 'Could not move email to Trash');
- return;
- }
- busy?.remove?.();
- await _animateEmailCardRemoval([em.uid]);
- state._libEmails = state._libEmails.filter(e => String(e.uid) !== String(em.uid));
- _renderGrid();
- _libCacheWriteBack();
- }},
- );
-
- const orderedActions = orderActionMenuItems(actions);
- let addedActionDivider = false;
- for (const [index, a] of orderedActions.entries()) {
- if (!addedActionDivider && index > 0 && actionMenuRank(a) >= 700) {
- const divider = document.createElement('div');
- divider.className = 'dropdown-divider';
- dropdown.appendChild(divider);
- addedActionDivider = true;
- }
- const item = document.createElement('div');
- item.className = 'dropdown-item-compact' + (a.danger ? ' dropdown-item-danger' : '');
- const arrow = a.submenu ? '<span style="margin-left:auto;opacity:0.5;">›</span>' : '';
- item.innerHTML = _icon(a.icon) + `<span>${a.label}</span>${arrow}`;
- item.addEventListener('click', (e) => {
- e.stopPropagation();
- if (a.submenu === 'remind') {
- _showLibRemindSubmenu(em, dropdown);
- return;
- }
- close();
- a.action();
- });
- dropdown.appendChild(item);
- }
- // Mobile-only Cancel item — explicit close for touch users. CSS hides it
- // on desktop where outside-click already dismisses cleanly.
- const _cancelIco = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
- const cancelItem = document.createElement('div');
- cancelItem.className = 'dropdown-item-compact dropdown-cancel-mobile';
- cancelItem.innerHTML = _icon(_cancelIco) + '<span>Cancel</span>';
- cancelItem.addEventListener('click', (e) => {
- e.stopPropagation();
- close();
- });
- dropdown.appendChild(cancelItem);
-
- document.body.appendChild(dropdown);
- _fitEmailDropdown(dropdown, rect);
- const close = bindMenuDismiss(dropdown, () => {
- dropdown.remove();
- anchor.classList.remove('reader-more-active');
- }, (ev) => !dropdown.contains(ev.target) && ev.target !== anchor);
- }
-
- // Bulk "Actions" dropdown for select mode — Delete is a separate visible button.
- function _showBulkActionsMenu(anchor) {
- document.querySelectorAll('.email-card-dropdown').forEach(dismissOrRemove);
- const dropdown = document.createElement('div');
- dropdown.className = 'email-card-dropdown email-bulk-menu';
- const rect = anchor.getBoundingClientRect();
- dropdown.style.cssText = `position:fixed;z-index:${topPortalZ()};min-width:160px;background:var(--panel,var(--bg));border:1px solid var(--border);border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,0.3);padding:4px;font-size:12px;top:${rect.bottom + 4}px;left:${rect.left}px;`;
- const _readIco = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 2 11 13"/><path d="m22 2-7 20-4-9-9-4 20-7z"/></svg>';
- const _unreadIco = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="3" fill="currentColor"/></svg>';
- const _doneIco = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
- const _exportIco = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>';
- const items = [
- { label: 'Export Attachments', icon: _exportIco, action: () => _exportSelectedAttachments() },
- { label: 'Done', icon: _doneIco, action: () => _bulkAction('done') },
- { label: 'Mark Read', icon: _readIco, action: () => _bulkAction('read') },
- { label: 'Mark Unread', icon: _unreadIco, action: () => _bulkAction('unread') },
- ];
- for (const a of items) {
- const it = document.createElement('div');
- it.className = 'dropdown-item-compact' + (a.danger ? ' dropdown-item-danger' : '');
- it.innerHTML = `<span class="dropdown-icon">${a.icon}</span><span>${a.label}</span>`;
- it.addEventListener('click', (e) => { e.stopPropagation(); close(); a.action(); });
- dropdown.appendChild(it);
- }
- // Mobile-only Cancel — matches the per-card and sidebar dropdowns.
- const _cancelIco2 = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
- const cancelIt = document.createElement('div');
- cancelIt.className = 'dropdown-item-compact dropdown-cancel-mobile';
- cancelIt.innerHTML = `<span class="dropdown-icon">${_cancelIco2}</span><span>Cancel</span>`;
- cancelIt.addEventListener('click', (e) => {
- e.stopPropagation();
- close();
- // Cancel inside the bulk-Actions menu also exits select mode — matches the
- // documents bulk dropdown.
- state._selectMode = false;
- state._selectedUids.clear();
- _updateBulkBar();
- _renderGrid();
- });
- dropdown.appendChild(cancelIt);
- document.body.appendChild(dropdown);
- _fitEmailDropdown(dropdown, rect);
- const close = bindMenuDismiss(dropdown, () => {
- dropdown.remove();
- }, (ev) => !dropdown.contains(ev.target) && ev.target !== anchor);
- }
-
- function _updateBulkBar() {
- const bar = document.getElementById('email-lib-bulk');
- const grid = document.getElementById('email-lib-grid');
- if (grid) grid.classList.toggle('email-selecting', !!state._selectMode);
- const selectBtn = document.getElementById('email-lib-select-btn');
- if (bar) bar.classList.toggle('hidden', !state._selectMode);
- if (selectBtn) {
- selectBtn.textContent = state._selectMode ? 'Cancel' : 'Select';
- selectBtn.classList.toggle('active', state._selectMode);
- }
- const count = document.getElementById('email-lib-selected-count');
- if (count) count.textContent = `${state._selectedUids.size} Selected`;
- const all = document.getElementById('email-lib-select-all');
- if (all) all.checked = state._libEmails.length > 0 && state._libEmails.every(e => state._selectedUids.has(e.uid));
- // When something's selected, brighten Actions to the same full --fg color as
- // the "N Selected" count (the button is a dimmer 60% --fg by default).
- const actions = document.getElementById('email-lib-bulk-actions');
- if (actions) actions.style.color = state._selectedUids.size > 0 ? 'var(--fg)' : '';
- const deleteBtn = document.getElementById('email-lib-bulk-delete');
- if (deleteBtn) deleteBtn.style.color = state._selectedUids.size > 0 ? 'var(--red)' : '';
- }
-
- async function _bulkAction(action) {
- const uids = Array.from(state._selectedUids);
- if (uids.length === 0) return;
- let failedReadSync = 0;
- const failedUids = new Set();
- if (action === 'delete') {
- const ok = await styledConfirm(
- `Delete ${uids.length} selected email${uids.length === 1 ? '' : 's'}?`,
- { confirmText: 'Delete', cancelText: 'Cancel', danger: true },
- );
- if (!ok) return;
- // Deletion is intentionally optimistic. The user should not have to keep
- // the mail window open while IMAP moves a batch; refresh and restore the
- // cards only if the provider rejects the background operation.
- const removed = new Set(uids.map(uid => String(uid)));
- state._libEmails = state._libEmails.filter(e => !removed.has(String(e.uid)));
- state._selectedUids.clear();
- state._selectMode = false;
- _updateBulkBar();
- _renderGrid();
- _libCacheWriteBack();
- showToast(`Moved ${uids.length} email${uids.length === 1 ? '' : 's'} to Trash`);
- fetch(`${API_BASE}/api/email/delete-bulk`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ uids, folder: state._libFolder, account_id: state._libAccountId || null }),
- }).then(async (res) => {
- const data = await res.json().catch(() => null);
- if (!res.ok || data?.success === false || (data?.failed_uids || []).length) {
- throw new Error(data?.error || `${data?.failed_uids?.length || 0} emails could not be deleted`);
- }
- }).catch((error) => {
- console.error('Background bulk email delete failed:', error);
- showToast('Delete failed; restoring mailbox');
- _loadEmailsFresh({ force: true, useCache: false, refreshAfterCache: false }).catch(() => {});
- });
- return;
- }
-
- const deleteBtn = action === 'delete' ? document.getElementById('email-lib-bulk-delete') : null;
- const actionsBtn = document.getElementById('email-lib-bulk-actions');
- const cancelBtn = document.getElementById('email-lib-bulk-cancel');
- const selectAll = document.getElementById('email-lib-select-all');
- const countEl = document.getElementById('email-lib-selected-count');
- const originalDeleteHtml = deleteBtn?.innerHTML || '';
- const originalCountText = countEl?.textContent || '';
- let busySpinner = null;
- // Loading state for every bulk action, not just delete — large
- // selections (e.g. 90+ Dones) used to silently hammer the server
- // with sequential requests and the user got zero feedback. Now the
- // Actions button (or Delete button) shows a whirlpool + verb-ing
- // label, and the count surfaces progress.
- const verbing = {
- delete: 'Deleting',
- archive: 'Archiving',
- done: 'Marking done',
- read: 'Marking read',
- unread: 'Marking unread',
- }[action] || 'Updating';
- const targetBtn = action === 'delete' ? deleteBtn : actionsBtn;
- let originalTargetHtml = '';
- if (targetBtn) {
- originalTargetHtml = targetBtn.innerHTML;
- targetBtn.disabled = true;
- targetBtn.classList.add('email-bulk-loading');
- targetBtn.innerHTML = `<span class="email-bulk-loading-label">${verbing}</span>`;
- busySpinner = spinnerModule.create('', 'clean', 'whirlpool');
- const spEl = busySpinner.createElement();
- spEl.classList.add('email-bulk-whirlpool');
- targetBtn.appendChild(spEl);
- busySpinner.start();
- }
- if (action !== 'delete' && deleteBtn) deleteBtn.disabled = true;
- if (action === 'delete' && actionsBtn) actionsBtn.disabled = true;
- if (cancelBtn) cancelBtn.disabled = true;
- if (selectAll) selectAll.disabled = true;
- if (countEl) countEl.textContent = `${verbing} ${uids.length}…`;
- const deleteOverlays = action === 'delete'
- ? uids.map(uid => {
- const card = document.querySelector(`#email-lib-grid .doclib-card[data-uid="${CSS.escape(String(uid))}"]`);
- return _showEmailDeleteOverlay(card);
- }).filter(Boolean)
- : [];
- if (deleteOverlays.length) {
- await Promise.all(deleteOverlays.map(busy => busy.ready).filter(Boolean));
- }
-
- // Single-uid worker.
- const handleOne = async (uid) => {
- try {
- if (action === 'archive') {
- const res = await fetch(`${API_BASE}/api/email/archive/${uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- const data = await res.json().catch(() => null);
- if (!res.ok || data?.success === false) throw new Error(data?.error || `HTTP ${res.status}`);
- } else if (action === 'delete') {
- // Bulk Delete matches the permanent-delete behavior used by the
- // library and albums. Moving a batch through provider Trash folders
- // is unreliable on several IMAP implementations.
- const res = await fetch(`${API_BASE}/api/email/delete-permanent/${uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'DELETE' });
- const data = await res.json().catch(() => null);
- if (!res.ok || data?.success === false) throw new Error(data?.error || `HTTP ${res.status}`);
- } else if (action === 'done') {
- // uid may come back from the Set as a string while em.uid is
- // numeric (or vice versa) — coerce both sides so the in-memory
- // state actually flips and the post-loop re-render shows the
- // done checkmark.
- const em = state._libEmails.find(e => String(e.uid) === String(uid));
- if (em) {
- em.is_answered = true;
- em.is_read = true;
- _clearDoneResponseTagsLocal(em);
- }
- const ansRes = await fetch(`${API_BASE}/api/email/mark-answered/${uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- const readRes = await fetch(`${API_BASE}/api/email/mark-read/${uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- if (!ansRes.ok || !readRes.ok) throw new Error(`mark-done HTTP ${ansRes.status}/${readRes.status}`);
- } else if (action === 'read' || action === 'unread') {
- const endpoint = action === 'read' ? 'mark-read' : 'mark-unread';
- const res = await fetch(`${API_BASE}/api/email/${endpoint}/${uid}?folder=${encodeURIComponent(state._libFolder)}${_acct()}`, { method: 'POST' });
- let data = null;
- try { data = await res.json(); } catch (_) {}
- if (!res.ok || data?.success === false) {
- throw new Error(data?.error || `HTTP ${res.status}`);
- }
- _syncEmailReadState(uid, action === 'read');
- }
- } catch (e) {
- if (action === 'read' || action === 'unread') failedReadSync += 1;
- failedUids.add(String(uid));
- console.error(`Failed to ${action} ${uid}:`, e);
- }
- };
-
- try {
- // Run in parallel with a concurrency cap so 92 emails don't take
- // 30 seconds sequentially but we also don't open 92 simultaneous
- // connections.
- const CONCURRENCY = 6;
- const queue = uids.slice();
- let inFlight = 0;
- let nextSlot = 0;
- let finishedCount = 0;
- let bulkDeletedUids = null;
- if (action === 'delete') {
- const res = await fetch(`${API_BASE}/api/email/delete-bulk`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ uids, folder: state._libFolder, account_id: state._libAccountId || null }),
- });
- const data = await res.json().catch(() => null);
- if (!res.ok || data?.success === false) throw new Error(data?.error || `HTTP ${res.status}`);
- for (const uid of data?.failed_uids || []) failedUids.add(String(uid));
- bulkDeletedUids = (data?.deleted_uids || []).map(String);
- if (countEl) countEl.textContent = `${verbing} ${bulkDeletedUids.length}/${uids.length}…`;
- } else await new Promise((resolve) => {
- const launch = () => {
- while (inFlight < CONCURRENCY && nextSlot < queue.length) {
- const uid = queue[nextSlot++];
- inFlight++;
- handleOne(uid).finally(() => {
- inFlight--;
- finishedCount++;
- if (countEl) countEl.textContent = `${verbing} ${finishedCount}/${queue.length}…`;
- if (nextSlot >= queue.length && inFlight === 0) resolve();
- else launch();
- });
- }
- if (queue.length === 0) resolve();
- };
- launch();
- });
-
- if (action === 'archive' || action === 'delete') {
- const successfulUids = bulkDeletedUids || uids.filter(uid => !failedUids.has(String(uid)));
- if (action === 'delete') {
- deleteOverlays.forEach(busy => busy.remove?.());
- }
- await _animateEmailCardRemoval(successfulUids);
- const removed = new Set(successfulUids.map(uid => String(uid)));
- state._libEmails = state._libEmails.filter(e => !removed.has(String(e.uid)));
- } else if (action === 'done' && state._libFilter === 'undone') {
- // The undone filter is a "show only not-done" view — after marking
- // selected emails done, they no longer match. Animate them out and
- // drop them from the local list so the view reflects the filter
- // instead of leaving freshly-done cards sitting there.
- await _animateEmailCardRemoval(uids);
- const removed = new Set(uids.map(uid => String(uid)));
- state._libEmails = state._libEmails.filter(e => !removed.has(String(e.uid)));
- }
- } finally {
- deleteOverlays.forEach(busy => busy.remove?.());
- if (busySpinner) busySpinner.destroy();
- // Restore whichever button we hijacked (delete vs actions).
- if (targetBtn) {
- targetBtn.disabled = false;
- targetBtn.classList.remove('email-bulk-loading');
- targetBtn.innerHTML = originalTargetHtml || targetBtn.innerHTML;
- }
- if (deleteBtn && deleteBtn !== targetBtn) {
- deleteBtn.disabled = false;
- deleteBtn.innerHTML = originalDeleteHtml || deleteBtn.innerHTML;
- }
- if (actionsBtn && actionsBtn !== targetBtn) actionsBtn.disabled = false;
- if (cancelBtn) cancelBtn.disabled = false;
- if (selectAll) selectAll.disabled = false;
- if (countEl) countEl.textContent = originalCountText;
- }
- state._selectedUids.clear();
- state._selectMode = false;
- _updateBulkBar();
- _renderGrid();
- if (failedReadSync > 0) {
- showToast(`Failed to update ${failedReadSync} email${failedReadSync === 1 ? '' : 's'}`);
- }
- if (failedUids.size > 0 && (action === 'delete' || action === 'archive')) {
- showToast(`${failedUids.size} email${failedUids.size === 1 ? '' : 's'} could not be ${action === 'delete' ? 'deleted' : 'archived'}`);
- }
- // Sync successful local mutations into the SWR cache so reopen doesn't
- // briefly show the pre-bulk state.
- _libCacheWriteBack();
- }
-
- // _extractName lives in ./emailLibrary/utils.js
-
- function _aiReplyIcon(data) {
- return '<svg class="email-ai-reply-icon" width="14" height="14" viewBox="0 0 24 24" fill="var(--accent-primary, var(--red))" aria-hidden="true"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>';
- }
-
- function _summaryIcon(data) {
- const fill = data?.cached_summary ? 'var(--accent-primary, var(--red))' : 'currentColor';
- return `<svg width="14" height="14" viewBox="0 0 24 24" fill="${fill}"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>`;
- }
-
- async function _emailTranslateLanguage() {
- try {
- const res = await fetch(`${API_BASE}/api/email/config`);
- const cfg = await res.json();
- return cfg?.email_translate_language || 'English';
- } catch (_) {
- return 'English';
- }
- }
-
- async function _runAiReplyFromButton(btn, em, data, mode, noteHint = '') {
- _snapEmailModalToLeftSidebar(btn.closest('.modal'));
- btn.disabled = true;
- const orig = btn.innerHTML;
- let wp = null;
- try {
- wp = spinnerModule.createWhirlpool(14);
- wp.element.style.cssText = 'width:14px;height:14px;display:inline-block;vertical-align:middle;position:relative;top:-2px;';
- btn.innerHTML = '';
- btn.appendChild(wp.element);
- } catch (_) {}
- try {
- if (state._onEmailClick) {
- return await state._onEmailClick({ email: em, emailData: data, mode, noteHint });
- }
- return false;
- } finally {
- try { wp && wp.stop(); } catch (_) {}
- btn.disabled = false;
- btn.innerHTML = orig;
- }
- }
-
- const _AI_REPLY_CONTEXT_DRAFT_PREFIX = 'odysseus:email-ai-reply-context:v2:';
- let _aiReplyChoiceOutsideClose = null;
-
- function _aiReplyContextDraftKey(em, data) {
- const accountId = data?.account_id || em?.account_id || state._libAccountId || '';
- const folder = data?.folder || em?.folder || state._libFolder || 'INBOX';
- const uid = data?.uid || em?.uid || data?.message_id || em?.message_id || '';
- if (!uid) return '';
- return _AI_REPLY_CONTEXT_DRAFT_PREFIX
- + [accountId, folder, uid].map(value => encodeURIComponent(String(value || ''))).join(':');
- }
-
- function _loadAiReplyContextDraft(key) {
- if (!key) return '';
- try { return localStorage.getItem(key) || ''; } catch (_) { return ''; }
- }
-
- function _saveAiReplyContextDraft(key, value) {
- if (!key) return;
- try {
- const text = String(value || '');
- if (text.trim()) localStorage.setItem(key, text);
- else localStorage.removeItem(key);
- } catch (_) {}
- }
-
- function _clearAiReplyContextDraft(key) {
- if (!key) return;
- try { localStorage.removeItem(key); } catch (_) {}
- }
-
- function _closeAiReplyChoice() {
- if (_aiReplyChoiceOutsideClose) {
- document.removeEventListener('click', _aiReplyChoiceOutsideClose, true);
- _aiReplyChoiceOutsideClose = null;
- }
- document.querySelectorAll('.email-ai-reply-choice').forEach(el => {
- const input = el.querySelector('[data-note-input]');
- _saveAiReplyContextDraft(el.dataset.contextDraftKey || '', input?.value || '');
- el.remove();
- });
- }
-
- function _showAiReplyChoice(btn, em, data, positionAnchor = btn) {
- _closeAiReplyChoice();
- const rect = positionAnchor.getBoundingClientRect();
- const menu = document.createElement('div');
- menu.className = 'email-ai-reply-choice';
- /* Clamp width to viewport minus 16px margin so the menu never spills off
- the right edge on narrow mobile screens. */
- const menuMaxW = Math.min(220, window.innerWidth - 16);
- const left = Math.max(8, Math.min(rect.left, window.innerWidth - menuMaxW - 8));
- /* Vertical placement: prefer below the button, but flip above if
- there's not enough room (e.g. button near bottom of viewport).
- Estimated menu height is ~150px (textarea + buttons + padding). */
- const estHeight = 150;
- const spaceBelow = window.innerHeight - rect.bottom - 8;
- const spaceAbove = rect.top - 8;
- let top;
- if (spaceBelow >= estHeight || spaceBelow >= spaceAbove) {
- top = Math.max(8, Math.min(rect.bottom + 6, window.innerHeight - estHeight - 8));
- } else {
- top = Math.max(8, rect.top - estHeight - 6);
- }
- menu.style.cssText = [
- 'position:fixed',
- `left:${left}px`,
- `top:${top}px`,
- `max-width:${menuMaxW}px`,
- `max-height:${window.innerHeight - 16}px`,
- 'overflow:auto',
- 'box-sizing:border-box',
- `z-index:${topPortalZ()}`,
- 'display:flex',
- 'gap:6px',
- 'padding:6px',
- 'background:var(--bg,#111)',
- 'border:1px solid var(--border,#333)',
- 'border-radius:7px',
- 'box-shadow:0 8px 24px rgba(0,0,0,.28)',
- ].join(';');
- menu.innerHTML = `
- <div class="email-ai-reply-row" style="display:flex;flex-direction:column;gap:6px;min-width:180px;">
- <textarea data-note-input rows="2" placeholder="Context (optional)" style="width:100%;box-sizing:border-box;resize:vertical;min-height:42px;font-family:inherit;font-size:11px;padding:5px 6px;border-radius:5px;border:1px solid var(--border,#333);background:var(--bg-elev,#1a1a1a);color:var(--fg);"></textarea>
- <div style="display:flex;align-items:center;gap:4px;">
- <button class="memory-toolbar-btn" data-mode="ai-reply-fast" title="Draft reply" style="display:inline-flex;align-items:center;justify-content:center;gap:5px;flex:1;">
- <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" style="color:var(--accent, var(--red));"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>
- Submit
- </button>
- </div>
- </div>
- `;
- const noteInput = menu.querySelector('[data-note-input]');
- const contextDraftKey = _aiReplyContextDraftKey(em, data);
- menu.dataset.contextDraftKey = contextDraftKey;
- noteInput.value = _loadAiReplyContextDraft(contextDraftKey);
- noteInput.addEventListener('input', () => {
- _saveAiReplyContextDraft(contextDraftKey, noteInput.value || '');
- });
- setTimeout(() => noteInput.focus(), 0);
- menu.addEventListener('click', async (ev) => {
- const choice = ev.target.closest('[data-mode]');
- if (!choice) return;
- ev.preventDefault();
- ev.stopPropagation();
- const mode = choice.getAttribute('data-mode') || 'ai-reply-fast';
- const noteHint = (noteInput.value || '').trim();
- _saveAiReplyContextDraft(contextDraftKey, noteInput.value || '');
- _closeAiReplyChoice();
- const draftOpened = await _runAiReplyFromButton(btn, em, data, mode, noteHint);
- if (draftOpened === true) _clearAiReplyContextDraft(contextDraftKey);
- });
- // Esc closes the popover; ignore plain clicks inside the menu so the
- // textarea stays focused.
- menu.addEventListener('mousedown', (ev) => ev.stopPropagation());
- document.body.appendChild(menu);
- // Outside-click closer: only fires when the click target is OUTSIDE
- // the menu. The original handler closed on any click which made
- // focusing the textarea immediately dismiss the popover.
- const outsideClose = (ev) => {
- if (menu.contains(ev.target)) return;
- document.removeEventListener('click', outsideClose, true);
- if (_aiReplyChoiceOutsideClose === outsideClose) _aiReplyChoiceOutsideClose = null;
- _closeAiReplyChoice();
- };
- _aiReplyChoiceOutsideClose = outsideClose;
- setTimeout(() => {
- if (_aiReplyChoiceOutsideClose === outsideClose) {
- document.addEventListener('click', outsideClose, true);
- }
- }, 0);
- }
-
- function _handleAiReplyButton(ev, em, data, positionAnchor = ev.currentTarget) {
- ev.stopPropagation();
- const btn = ev.currentTarget;
- // First click on a cached email surfaces the cached draft. Second
- // click clears the cache and opens the Fast/Full + context menu so
- // the user can ask for a fresh draft (with new steering).
- if (data?.cached_ai_reply && !btn.dataset.shownOnce) {
- btn.dataset.shownOnce = '1';
- _runAiReplyFromButton(btn, em, data, 'ai-reply');
- return;
- }
- if (data?.cached_ai_reply) {
- data.cached_ai_reply = null;
- btn.dataset.shownOnce = '';
- }
- _showAiReplyChoice(btn, em, data, positionAnchor);
- }
-
- function _hasMultipleRecipients(data) {
- // Count distinct addresses in To + Cc (minus the current user). Empty
- // fallback when the user's address isn't yet known — no exclusion.
- const myAddress = (window._myEmailAddress || '').toLowerCase();
- const extractEmails = (str) => {
- if (!str) return [];
- return str.split(',')
- .map(s => {
- const m = s.match(/<([^>]+)>/);
- return (m ? m[1] : s).trim().toLowerCase();
- })
- .filter(e => e && e !== myAddress);
- };
- const recipients = new Set([
- ...extractEmails(data.to),
- ...extractEmails(data.cc),
- ]);
- // Sender counts as one other person too
- if (data.from_address && data.from_address.toLowerCase() !== myAddress) {
- recipients.add(data.from_address.toLowerCase());
- }
- return recipients.size > 1;
- }
-
- // _esc lives in ./emailLibrary/utils.js
-
- function _showEmailTranslateSubmenu(reader, parentDropdown) {
- parentDropdown.innerHTML = '';
- const header = document.createElement('div');
- header.className = 'dropdown-item-compact';
- header.style.cssText = 'opacity:0.5;font-size:10px;pointer-events:none;text-transform:uppercase;letter-spacing:0.5px;padding-top:6px;';
- header.innerHTML = '<span>Translate to</span>';
- parentDropdown.appendChild(header);
-
- const customRow = document.createElement('div');
- customRow.className = 'dropdown-item-compact email-translate-custom-row';
- customRow.style.cssText = 'display:flex;gap:5px;align-items:center;padding:5px 7px;cursor:default;';
- customRow.innerHTML = `
- <input type="text" class="email-translate-custom-input" placeholder="Write language..." style="min-width:0;width:136px;height:26px;border:1px solid var(--border);border-radius:6px;background:var(--bg);color:var(--fg);font:inherit;font-size:11px;padding:0 7px;">
- <button type="button" class="email-translate-custom-go" style="height:26px;padding:0 8px;border:1px solid var(--border);border-radius:6px;background:color-mix(in srgb, var(--fg) 5%, transparent);color:inherit;font:inherit;font-size:11px;cursor:pointer;">Go</button>
- `;
- parentDropdown.appendChild(customRow);
- const input = customRow.querySelector('.email-translate-custom-input');
- const go = customRow.querySelector('.email-translate-custom-go');
- const runCustom = async () => {
- const language = (input?.value || '').trim();
- if (!language) {
- input?.focus();
- return;
- }
- parentDropdown.remove();
- await _translateEmail(reader, language);
- };
- customRow.addEventListener('click', e => e.stopPropagation());
- go?.addEventListener('click', async e => {
- e.stopPropagation();
- await runCustom();
- });
- input?.addEventListener('keydown', async e => {
- if (e.key === 'Enter') {
- e.preventDefault();
- e.stopPropagation();
- await runCustom();
- }
- });
- _emailTranslateLanguage().then(language => {
- if (input && !input.value) input.value = language || 'English';
- }).catch(() => {});
-
- const languages = ['English', 'Swedish', 'Japanese', 'Spanish', 'French', 'German'];
- for (const language of languages) {
- const item = document.createElement('div');
- item.className = 'dropdown-item-compact';
- item.innerHTML = `<span>${language}</span>`;
- item.addEventListener('click', async (e) => {
- e.stopPropagation();
- parentDropdown.remove();
- await _translateEmail(reader, language);
- });
- parentDropdown.appendChild(item);
- }
- }
-
- // ---- Reminder submenu (used by both email menus) ----
- function _showLibRemindSubmenu(em, parentDropdown) {
- parentDropdown.innerHTML = '';
- const header = document.createElement('div');
- header.className = 'dropdown-item-compact';
- header.style.cssText = 'opacity:0.5;font-size:10px;pointer-events:none;text-transform:uppercase;letter-spacing:0.5px;padding-top:6px;';
- header.innerHTML = '<span>Remind me</span>';
- parentDropdown.appendChild(header);
-
- const now = new Date();
- const laterToday = new Date(now);
- const sixPm = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 18, 0);
- if (sixPm - now < 60*60*1000) laterToday.setTime(now.getTime() + 3*60*60*1000);
- else laterToday.setTime(sixPm.getTime());
- const tomorrow = new Date(now); tomorrow.setDate(tomorrow.getDate()+1); tomorrow.setHours(8,0,0,0);
- const daysUntilMon = (8 - now.getDay()) % 7 || 7;
- const nextWeek = new Date(now); nextWeek.setDate(now.getDate()+daysUntilMon); nextWeek.setHours(8,0,0,0);
-
- const presets = [
- { label: 'Later today', sub: laterToday.toLocaleTimeString([], { hour:'numeric', minute:'2-digit' }), date: laterToday },
- { label: 'Tomorrow', sub: tomorrow.toLocaleTimeString([], { hour:'numeric', minute:'2-digit' }), date: tomorrow },
- { label: 'Next week', sub: nextWeek.toLocaleDateString([], { weekday:'short' }) + ' ' + nextWeek.toLocaleTimeString([], { hour:'numeric', minute:'2-digit' }), date: nextWeek },
- ];
- for (const p of presets) {
- const item = document.createElement('div');
- item.className = 'dropdown-item-compact';
- item.innerHTML = `<span>${p.label}</span><span style="margin-left:auto;opacity:0.5;font-size:10px;">${p.sub}</span>`;
- item.addEventListener('click', async (e) => {
- e.stopPropagation();
- parentDropdown.remove();
- await _createEmailReplyReminder(em, p.date);
- });
- parentDropdown.appendChild(item);
- }
- const customItem = document.createElement('div');
- customItem.className = 'dropdown-item-compact';
- customItem.innerHTML = '<span>Pick date and time…</span>';
- customItem.addEventListener('click', (e) => {
- e.stopPropagation();
- parentDropdown.remove();
- const tmp = document.createElement('input');
- tmp.type = 'datetime-local';
- const def = new Date(tomorrow);
- const pad = n => String(n).padStart(2,'0');
- tmp.value = `${def.getFullYear()}-${pad(def.getMonth()+1)}-${pad(def.getDate())}T${pad(def.getHours())}:${pad(def.getMinutes())}`;
- tmp.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:99999;padding:8px;background:var(--bg);border:1px solid var(--border);border-radius:6px;font-size:13px;';
- document.body.appendChild(tmp);
- tmp.focus();
- if (typeof tmp.showPicker === 'function') { try { tmp.showPicker(); } catch {} }
- tmp.addEventListener('change', async () => {
- if (tmp.value) await _createEmailReplyReminder(em, new Date(tmp.value));
- tmp.remove();
- });
- tmp.addEventListener('blur', () => setTimeout(() => tmp.remove(), 200));
- });
- parentDropdown.appendChild(customItem);
- // "Note" — prompts for free-text and saves it as a note without a
- // due_date, so no timer/reminder fires.
- const noteItem = document.createElement('div');
- noteItem.className = 'dropdown-item-compact';
- noteItem.innerHTML = '<span>Note</span>';
- noteItem.addEventListener('click', (e) => {
- e.stopPropagation();
- parentDropdown.remove();
- _promptEmailNote(em);
- });
- parentDropdown.appendChild(noteItem);
- }
-
- function _promptEmailNote(em) {
- const overlay = document.createElement('div');
- overlay.style.cssText = 'position:fixed;inset:0;z-index:99998;background:rgba(0,0,0,0.45);display:flex;align-items:center;justify-content:center;padding:16px;';
- const card = document.createElement('div');
- card.style.cssText = 'background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:14px;min-width:280px;max-width:min(420px, 92vw);display:flex;flex-direction:column;gap:8px;box-shadow:0 12px 32px rgba(0,0,0,0.4);';
- const subject = em.subject || '(no subject)';
- card.innerHTML = `
- <div style="font-size:11px;opacity:0.6;">Note about ${_esc(subject)}</div>
- <textarea data-note placeholder="Write your note…" rows="4" style="resize:vertical;min-height:80px;font-family:inherit;font-size:12px;padding:7px 8px;border-radius:6px;border:1px solid var(--border);background:var(--bg-elev,#1a1a1a);color:var(--fg);box-sizing:border-box;width:100%;"></textarea>
- <div class="email-note-actions" style="display:flex;gap:6px;justify-content:flex-end;position:relative;top:4px;">
- <button class="memory-toolbar-btn" data-act="cancel"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" aria-hidden="true" style="vertical-align:-1px;margin-right:4px;"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>Cancel</button>
- <button class="memory-toolbar-btn active" data-act="save"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="vertical-align:-1px;margin-right:4px;"><path d="M4 4h16v16H4z"/><path d="M8 8h8M8 12h8M8 16h5"/></svg>Save</button>
- </div>
- `;
- overlay.appendChild(card);
- document.body.appendChild(overlay);
- const ta = card.querySelector('[data-note]');
- setTimeout(() => ta.focus(), 0);
- const close = () => overlay.remove();
- overlay.addEventListener('click', (ev) => { if (ev.target === overlay) close(); });
- card.querySelector('[data-act="cancel"]').addEventListener('click', close);
- card.querySelector('[data-act="save"]').addEventListener('click', async () => {
- const text = (ta.value || '').trim();
- if (!text) { ta.focus(); return; }
- close();
- await _createEmailReplyReminder(em, null, text);
- });
- ta.addEventListener('keydown', (ev) => {
- if (ev.key === 'Escape') close();
- else if ((ev.ctrlKey || ev.metaKey) && ev.key === 'Enter') card.querySelector('[data-act="save"]').click();
- });
- }
-
- async function _createEmailReplyReminder(em, dueDate, customText = '') {
- const pad = n => String(n).padStart(2,'0');
- const iso = dueDate
- ? `${dueDate.getFullYear()}-${pad(dueDate.getMonth()+1)}-${pad(dueDate.getDate())}T${pad(dueDate.getHours())}:${pad(dueDate.getMinutes())}`
- : null;
- const fullFrom = em.from || em.sender || '';
- // Extract just the first name from "First Last <email@x>" or fall back to email local part
- let from = 'someone';
- if (fullFrom) {
- const fullName = _extractName(fullFrom);
- if (fullName) {
- // Strip quotes, take the first whitespace-separated word, capitalize
- const first = fullName.replace(/^["']|["']$/g, '').trim().split(/[\s,]+/)[0] || '';
- if (first) from = first.charAt(0).toUpperCase() + first.slice(1);
- }
- }
- const subject = em.subject || '(no subject)';
- const folder = state._libFolder || 'INBOX';
- const deepLink = `${window.location.origin}/#email=${encodeURIComponent(folder)}:${em.uid}`;
- const itemText = customText || `Reply to ${from}: ${subject}`;
- const payload = {
- title: `Reply: ${subject}`,
- note_type: 'todo',
- items: [
- { text: itemText, checked: false },
- ],
- content: `Open email: ${deepLink}`,
- label: 'email reminder',
- source: 'email',
- };
- if (iso) payload.due_date = iso;
- try {
- const res = await fetch(`${API_BASE}/api/notes`, {
- method: 'POST', credentials: 'same-origin',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload),
- });
- if (!res.ok) throw new Error('Failed');
- const { showToast } = await import('./ui.js?v=20260916largetoolscroll1');
- if (dueDate) {
- const fmt = dueDate.toLocaleString([], { month:'short', day:'numeric', hour:'numeric', minute:'2-digit' });
- showToast(`Todo reminder set for ${fmt}`);
- } else {
- showToast('Reply note saved');
- }
- if ('Notification' in window && Notification.permission === 'default') {
- try { Notification.requestPermission(); } catch {}
- }
- } catch (e) {
- const { showError } = await import('./ui.js?v=20260916largetoolscroll1');
- showError('Failed to create reminder');
- }
- }
-
- // Sanitize untrusted HTML email bodies before injecting via innerHTML.
+ // The email library now lives in `static/js/emailLibrary/`. This file stays at
+ // the old path because five call sites import it, four of them dynamically
+ // with a version query string (`emailInbox.js`, `chatStream.js`,
+ // `chatRenderer.js`, `document.js`, `settings.js`), and `sw.js` caches URLs
+ // verbatim. Re-exporting here means the move needed no coordinated edit to any
+ // of them.
+ //
+ // Importing this module evaluates `emailLibrary/index.js`, so the side effects
+ // the panel relies on — the `window.__odysseusGetActiveEmailContext` bridge,
+ // the agent tool-output listeners — still happen exactly when they used to.
//
- // Denylist sanitizer — has to block every well-known XSS sink:
- // - <script>, <iframe>, <object>, <embed>, <form>, <style>, <link>
- // - SVG entirely (event handlers, <use href="javascript:">, <foreignObject>,
- // <animate>, <set>, etc.). Email clients don't need SVG.
- // - <math> (MathML can carry handlers).
- // - <base href="...">, <meta http-equiv="refresh">, <noscript>, <frame>,
- // <frameset>, <applet>, <portal>.
- // - on* attributes; javascript:/vbscript:/data: URLs in href/src/srcset/
- // formaction/action/background/poster/data attributes.
- // - srcdoc (defensive — iframe is already nuked).
- // - inline `style` declarations containing javascript: or expression().
- // _sanitizeHtml / _escLinkify live in ./emailLibrary/utils.js
+ // New code should import `./emailLibrary/index.js` directly.
+
+ export {
+ refreshEmailLibrary,
+ prewarmEmailLibrary,
+ prewarmUnreadEmails,
+ initEmailLibrary,
+ isOpen,
+ openEmailLibrary,
++ openEmailFromTool,
+ mountEmailSettings,
+ openEmailLibrarySettings,
+ closeEmailLibrary,
+ } from './emailLibrary/index.js';
diff --cc static/js/emailLibrary/index.js
index 000000000,7e48b29ea..82f76b0c5
mode 000000,100644..100644
--- a/static/js/emailLibrary/index.js
+++ b/static/js/emailLibrary/index.js
@@@ -1,0 -1,6179 +1,6193 @@@
+ /**
+ * emailLibrary/index.js — Email library popup modal.
+ * Similar pattern to documentLibrary.js. Shows emails in a grid with search/filter.
+ *
+ * `static/js/emailLibrary.js` re-exports this module's public surface so the
+ * old import path keeps resolving; see the comment there.
+ */
+
+ import spinnerModule from '../spinner.js';
+ import { styledConfirm, showToast, emptyStateIcon } from '../ui.js?v=20260916largetoolscroll1';
+ import { folderDisplayName, sortedFolders } from '../emailInbox.js?v=20260914aireply4';
+ import settingsModule from '../settings.js?v=20260912writingstyle3';
+ import * as Modals from '../modalManager.js';
+ import { makeWindowDraggable } from '../windowDrag.js';
+ import {
+ _esc,
+ _escLinkify,
+ _extractName,
+ _formatRecipients,
+ _senderColor,
+ _sanitizeHtml,
+ } from './utils.js';
+ import { state } from './state.js';
+ import { getSettings } from '../appConfig.js';
+ import { collapseSidebarToRail } from '../modalSnap.js';
+ import { emailApiUrl } from '../emailShared.js';
+ import {
+ bindMenuDismiss,
+ dismissTopMenu,
+ bindExpandedCardDismiss,
+ unbindExpandedCardDismiss,
+ } from '../escMenuStack.js';
+ import { _aiReplyIcon, _handleAiReplyButton, _hasMultipleRecipients } from './aiReply.js';
+ import {
+ _buildAttsHtmlFor,
+ _loadDeferredAttachmentsIntoReader,
+ _wireEmailAttachmentWrap,
+ } from './attachments.js';
+ import { _safeRenderEmailBody, _wireEmailInlineImages } from './bodyRender.js';
+ import {
+ _bulkAction,
+ _showBulkActionsMenu,
+ _showCardMenu,
+ _showReaderMoreMenu,
+ _updateBulkBar,
+ } from './menus.js';
+ import { _emailBodyTextForTranslate, _openEmailAsTab, _summarizeEmail } from './reader.js';
+ import {
+ _EMAIL_SETTINGS_ICON,
+ _bindEmailSettingsPageControls,
+ _emailCleanupSettingsHtml,
+ _emailDisplaySettingsHtml,
+ _emailSettingsAccountSelectHtml,
+ _emailSettingsFormHtml,
+ _emailSettingsLoadingHtml,
+ _emailWritingStyleHtml,
+ _fetchEmailSettingsConfig,
+ _fetchEmailWritingStyle,
+ _hideEmailSettingsPage,
+ _isAutoReplyActiveForCurrentAccount,
+ _readEmailInlineImagesPreference,
+ _showEmailSettingsPage,
+ _syncAutoReplyCalendarEvent,
+ _syncEmailAutoReplyTitle,
+ _syncEmailSettingsAccountPicker,
+ } from './settingsPage.js';
+
+ const API_BASE = window.location.origin;
+ let _emailUnreadChipClickWired = false;
+ let _libLoadSeq = 0;
+ let _emailMailboxGeneration = 0;
+ let _emailCardOpenSeq = 0;
+ let _emailReadMutationSeq = 0;
+ const _emailReadMutations = new Map();
+ let _libFolderSeq = 0;
+ let _libSearchSeq = 0;
+ let _libSearchHadResults = false;
+ let _libSearchInFlight = false;
+ let _activeEmailReaderForSelectAll = null;
+ let _libAccountsLoadedAt = 0;
+ const _LIB_ACCOUNTS_TTL_MS = 5 * 60 * 1000;
+ let _accountUnreadSeq = 0;
+ let _accountUnreadState = new Map(); // account_id -> { unreadCount, maxUid }
+
+ function _hasActiveEmailSearchResults() {
+ if (!_libSearchHadResults) return false;
+ if (String(state._libSearch || '').trim()) return true;
+ return (state._libSearchPills || []).some(p => p?.type === 'text' || p?.type === 'contact');
+ }
+
+
+ export function _normalizeEmailStateFlags(em) {
+ if (!em || typeof em !== 'object') return em;
+ const flags = String(em.flags || '');
+ const answered = !!(
+ em.is_answered ||
+ em.is_done ||
+ em.done ||
+ em.answered ||
+ flags.includes('\\Answered')
+ );
+ // Once the normalized field exists, it is the source of truth. Some
+ // cached/fixture rows also retain legacy aliases such as `favorite`; OR-ing
+ // those aliases on every render would resurrect a favorite immediately
+ // after the user turns it off.
+ const flagged = Object.prototype.hasOwnProperty.call(em, 'is_flagged')
+ ? !!em.is_flagged
+ : !!(
+ em.is_favorite ||
+ em.favorite ||
+ em.flagged ||
+ em.starred ||
+ flags.includes('\\Flagged')
+ );
+ const read = !!(
+ em.is_read ||
+ em.read ||
+ flags.includes('\\Seen')
+ );
+ em.is_answered = answered;
+ em.is_done = answered;
+ em.is_flagged = flagged;
+ em.is_read = read;
+ return em;
+ }
+
+ function _isEmailTypingTarget(t) {
+ return !!(t && (
+ t.tagName === 'INPUT' ||
+ t.tagName === 'TEXTAREA' ||
+ t.tagName === 'SELECT' ||
+ t.isContentEditable
+ ));
+ }
+
+ function _selectEmailReaderContents(reader) {
+ if (!reader || !reader.isConnected) return false;
+ const hiddenModal = reader.closest('.modal.hidden');
+ if (hiddenModal) return false;
+ const range = document.createRange();
+ range.selectNodeContents(reader);
+ const sel = window.getSelection();
+ sel?.removeAllRanges();
+ sel?.addRange(range);
+ return true;
+ }
+
+ export function _markEmailReaderActive(reader) {
+ if (!reader) return;
+ _activeEmailReaderForSelectAll = reader;
+ if (reader.dataset.selectAllWired === '1') return;
+ reader.dataset.selectAllWired = '1';
+ reader.addEventListener('pointerdown', () => { _activeEmailReaderForSelectAll = reader; }, true);
+ reader.addEventListener('focusin', () => { _activeEmailReaderForSelectAll = reader; }, true);
+ }
+
+ function _emailReaderLoadErrorHtml(message) {
+ return `
+ <div class="email-reader-load-error">
+ <div class="email-reader-load-error-title">Could not load email</div>
+ <div class="email-reader-load-error-msg">${_esc(message || 'Failed to load email')}</div>
+ <button type="button" class="memory-toolbar-btn email-reader-retry-btn">Retry</button>
+ </div>`;
+ }
+
+ export function _showEmailReaderLoadError(reader, message, onRetry) {
+ if (!reader) return;
+ reader.classList.remove('email-card-reader-loading');
+ reader.classList.add('email-card-reader-error');
+ reader.style.minHeight = '';
+ reader.innerHTML = _emailReaderLoadErrorHtml(message);
+ const retry = reader.querySelector('.email-reader-retry-btn');
+ retry?.addEventListener('click', (ev) => {
+ ev.preventDefault();
+ ev.stopPropagation();
+ onRetry?.();
+ });
+ _markEmailReaderActive(reader);
+ }
+
+ export function _openCalendarEventFromEmail(uid) {
+ const target = String(uid || '').trim();
+ if (!target) return;
+ import('../calendar.js?v=20260914emailsource11').then(mod => {
+ const open = mod.openCalendarTo || (mod.default && mod.default.openCalendarTo);
+ if (open) open(target);
+ }).catch(() => {});
+ }
+
+ function _applyTagFilterFromPill(tag) {
+ const normalized = String(tag || '').trim().toLowerCase().replace(/_/g, '-');
+ if (!normalized || normalized === 'calendar') return;
+ const value = `filter:tag:${normalized}`;
+ const existingIdx = Array.isArray(state._libSearchPills)
+ ? state._libSearchPills.findIndex(p => p?.type === 'filter' && p.value === value)
+ : -1;
+ if (existingIdx >= 0) {
+ _removeSearchPillAt(existingIdx);
+ return;
+ }
+ _addSearchPill({
+ type: 'filter',
+ value,
+ label: normalized.replace(/-/g, ' '),
+ });
+ }
+
+ document.addEventListener('odysseus:email-filter-tag', (e) => {
+ _applyTagFilterFromPill(e.detail?.tag);
+ });
+
+ function _emailTagPillHtml(tag, em) {
+ const normalized = String(tag || '').trim().toLowerCase().replace(/_/g, '-');
+ if (!normalized) return '';
+ const eventUid = normalized === 'calendar' && Array.isArray(em?.calendar_event_uids)
+ ? String(em.calendar_event_uids[0] || '').trim()
+ : '';
+ if (normalized === 'calendar') {
+ if (!eventUid) return '';
+ return `<button type="button" class="email-tag email-tag-${_esc(normalized)} email-tag-clickable" data-calendar-event-uid="${_esc(eventUid)}" title="Open calendar event">${_esc(normalized)}</button>`;
+ }
+ return `<button type="button" class="email-tag email-tag-${_esc(normalized)} email-tag-clickable" data-email-filter-tag="${_esc(normalized)}" title="Show ${_esc(normalized)} emails">${_esc(normalized)}</button>`;
+ }
+
+ function _emailTagGroupHtml(tags, em) {
+ const visible = (Array.isArray(tags) ? tags : [])
+ .map(t => _emailTagPillHtml(t, em))
+ .filter(Boolean);
+ if (!visible.length) return '';
+ // A lone tag is already the most useful compact representation. Never
+ // replace it with a misleading "+1" overflow control.
+ if (visible.length === 1) return visible[0];
+ // Two tags still fit as useful labels. Overflow starts at three so the UI
+ // never renders a low-value "+1" control.
+ if (visible.length === 2) return visible.join('');
+ const extra = visible.slice(1).map(html => `<span class="email-tag-extra">${html}</span>`).join('');
+ const additionalCount = visible.length - 1;
+ const mini = `<button type="button" class="email-tags-more email-tags-more-single" data-email-tags-more aria-expanded="false" title="Show all tags"><span>+${additionalCount}</span></button>`;
+ return `${visible[0]}${extra}<button type="button" class="email-tags-more" data-email-tags-more aria-expanded="false" title="Show all tags"><span data-email-tags-count-normal>+${additionalCount}</span><span data-email-tags-count-mini>+${additionalCount}</span><svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"></polyline></svg></button>${mini}`;
+ }
+
+ function _fitEmailCardTags(titleRow) {
+ const tagWrap = titleRow?.querySelector('.email-card-tags');
+ const title = titleRow?.querySelector('.memory-item-title');
+ const status = titleRow?.querySelector('.email-card-status');
+ if (!tagWrap || !title || !status) return;
+ tagWrap.classList.remove('email-tags-mini');
+ tagWrap.style.setProperty('--email-status-width', `${status.offsetWidth}px`);
+ const minimumTitleWidth = Math.max(96, Math.min(160, titleRow.clientWidth * 0.45));
+ const availableForTags = Math.max(0, titleRow.clientWidth - status.offsetWidth - minimumTitleWidth - 12);
+ const hasOverflowControl = !!tagWrap.querySelector('[data-email-tags-more]');
+ tagWrap.classList.toggle('email-tags-mini', hasOverflowControl && tagWrap.scrollWidth > availableForTags);
+ }
+
+ const _emailTagFitObserver = typeof ResizeObserver === 'function'
+ ? new ResizeObserver(entries => {
+ for (const entry of entries) _fitEmailCardTags(entry.target);
+ })
+ : null;
+
+ const _DONE_RESPONSE_TAGS = new Set(['urgent', 'reply-soon', 'action-needed']);
+
+ function _visibleEmailTagsForRender(em) {
+ const tags = Array.isArray(em?.tags) ? em.tags : [];
+ if (!em?.is_answered) return tags;
+ return tags.filter(t => !_DONE_RESPONSE_TAGS.has(String(t || '').trim().toLowerCase().replace(/_/g, '-')));
+ }
+
+ export function _clearDoneResponseTagsLocal(em) {
+ if (!em || !Array.isArray(em.tags)) return;
+ em.tags = em.tags.filter(t => !_DONE_RESPONSE_TAGS.has(String(t || '').trim().toLowerCase().replace(/_/g, '-')));
+ }
+
+ export function _loadedEmailsHaveVisibleTags() {
+ return (state._libEmails || []).some(em =>
+ _visibleEmailTagsForRender(em).length > 0 || !!em?.is_spam_verdict
+ );
+ }
+
+ export async function _openTasksForEmailTags() {
+ try {
+ const mod = await import('../tasks.js?v=20260914taskmodel1');
+ const openTasks = mod.openTasks || mod.default?.openTasks;
+ if (typeof openTasks === 'function') {
+ openTasks(null, { filter: 'Email', focusAction: 'check_email_urgency' });
+ return;
+ }
+ } catch (_) {}
+ document.getElementById('tool-tasks-btn')?.click();
+ }
+
+ export function _notifyNoLoadedEmailTags() {
+ const count = (state._libEmails || []).length;
+ const msg = count
+ ? `No tags found in the ${count} loaded emails.`
+ : 'No email tags loaded yet.';
+ showToast(`${msg} Turn on email tagging in Tasks.`, {
+ duration: 6500,
+ action: 'Open Tasks',
+ onAction: _openTasksForEmailTags,
+ });
+ }
+
+ // Stash the email identity (uid + folder + account) on the reader element
+ // so chat submits and other code paths can ask "what email is the user
+ // currently looking at?" without re-deriving from the DOM hierarchy.
+ export function _stampReaderContext(reader, em, folder, account) {
+ if (!reader || !em) return;
+ reader.dataset.emailUid = String(em.uid || '');
+ reader.dataset.emailFolder = String(folder || state._libFolder || 'INBOX');
+ reader.dataset.emailAccount = String(account || state._libAccountId || '');
+ if (em.subject) reader.dataset.emailSubject = String(em.subject);
+ if (em.from_address || em.from_name) {
+ reader.dataset.emailFrom = String(em.from_address || em.from_name);
+ }
+ }
+
+ // Returns { uid, folder, account, subject, from } for the email the user
+ // is most likely referring to — the last reader they interacted with, then
+ // any open reader-modal as a fallback. Returns null when no email reader
+ // is open. Exported below for chat.js to read on submit.
+ function _getActiveEmailContext() {
+ const candidates = [];
+ if (_activeEmailReaderForSelectAll && _activeEmailReaderForSelectAll.isConnected) {
+ candidates.push(_activeEmailReaderForSelectAll);
+ }
+ // Visible reader-tab modals (popped-out windows).
+ document.querySelectorAll('.modal[id^="email-reader-"]:not(.hidden):not(.modal-minimized) .email-card-reader').forEach(el => candidates.push(el));
+ // Expanded inline reader in the library list.
+ document.querySelectorAll('#email-lib-modal:not(.hidden) .doclib-card.email-card-expanded .email-card-reader').forEach(el => candidates.push(el));
+ for (const r of candidates) {
+ const uid = r?.dataset?.emailUid;
+ if (uid) {
+ return {
+ uid,
+ folder: r.dataset.emailFolder || 'INBOX',
+ account: r.dataset.emailAccount || '',
+ subject: r.dataset.emailSubject || '',
+ from: r.dataset.emailFrom || '',
+ };
+ }
+ }
+ return null;
+ }
+
+ // Frontend reads via the global so chat.js doesn't need a separate import
+ // path (emailLibrary loads lazily in some entry points).
+ try { window.__odysseusGetActiveEmailContext = _getActiveEmailContext; } catch (_) {}
+
+ const _COPY_EMAIL_ICON = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
+
+ function _decodeAttrValue(v) {
+ const tmp = document.createElement('textarea');
+ tmp.innerHTML = v || '';
+ return tmp.value;
+ }
+
+ function _emailAddressFromRecipientText(text) {
+ const raw = String(text || '').trim();
+ const angle = raw.match(/<\s*([^<>@\s]+@[^<>\s]+)\s*>/);
+ if (angle) return angle[1].trim();
+ const any = raw.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i);
+ return any ? any[0].trim() : raw;
+ }
+
+ export function _splitRecipientList(raw) {
+ const out = [];
+ let cur = '';
+ let quote = false;
+ let angle = false;
+ const s = String(raw || '');
+ for (let i = 0; i < s.length; i += 1) {
+ const ch = s[i];
+ if (ch === '"' && s[i - 1] !== '\\') quote = !quote;
+ else if (ch === '<' && !quote) angle = true;
+ else if (ch === '>' && !quote) angle = false;
+
+ if (ch === ',' && !quote && !angle) {
+ const part = cur.trim();
+ if (part) out.push(part);
+ cur = '';
+ continue;
+ }
+ cur += ch;
+ }
+ const tail = cur.trim();
+ if (tail) out.push(tail);
+ return out;
+ }
+
+ async function _copyTextToClipboard(text) {
+ const value = String(text || '');
+ if (!value) return false;
+ try {
+ if (navigator.clipboard?.writeText) {
+ await navigator.clipboard.writeText(value);
+ return true;
+ }
+ } catch (_) {}
+ try {
+ const ta = document.createElement('textarea');
+ ta.value = value;
+ ta.setAttribute('readonly', '');
+ ta.style.position = 'fixed';
+ ta.style.left = '-9999px';
+ ta.style.top = '0';
+ document.body.appendChild(ta);
+ ta.select();
+ const ok = document.execCommand('copy');
+ ta.remove();
+ return !!ok;
+ } catch (_) {
+ return false;
+ }
+ }
+
+ export function _wireMetaToggle(root) {
+ const toggle = root && root.querySelector('.email-reader-meta-toggle');
+ const details = root && root.querySelector('.email-reader-meta-details');
+ if (!toggle || !details) return;
+ const meta = details.closest('.email-reader-meta');
+ toggle.addEventListener('click', (ev) => {
+ ev.stopPropagation();
+ const open = details.hasAttribute('hidden');
+ if (open) details.removeAttribute('hidden');
+ else details.setAttribute('hidden', '');
+ toggle.setAttribute('aria-expanded', String(open));
+ toggle.classList.toggle('open', open);
+ if (meta) meta.classList.toggle('email-reader-meta-expanded', open);
+ });
+ }
+
+ export function _recipientMetaToggleHtml(data = {}) {
+ const ccCount = _splitRecipientList(data.cc || '').length;
+ if (ccCount) {
+ return `<button class="email-reader-meta-toggle email-reader-cc-toggle" type="button" aria-expanded="false" title="Show Cc recipients"><span>Cc +${ccCount}</span><svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg></button>`;
+ }
+ if (!data.to) return '';
+ return `<button class="email-reader-meta-toggle" type="button" aria-expanded="false" title="Show recipients"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg></button>`;
+ }
+
+ export function _recipientChipHtml(full, label, extraClass = '') {
+ const fullText = String(full || '').trim();
+ const addr = _emailAddressFromRecipientText(fullText);
+ const labelText = String(label || addr || fullText || '').trim();
+ const cls = `recipient-chip${extraClass ? ` ${extraClass}` : ''}`;
+ return `<span class="${cls}" data-full="${_esc(fullText || labelText)}" data-email="${_esc(addr)}" title="Click for details"><span class="recipient-chip-label">${_esc(labelText)}</span><button type="button" class="recipient-chip-copy" title="Copy email" aria-label="Copy email" hidden>${_COPY_EMAIL_ICON}</button></span>`;
+ }
+
+ let _recipientChipPopoverCtl = null;
+ function _closeRecipientChipPopover() {
+ try { _recipientChipPopoverCtl?.abort(); } catch {}
+ _recipientChipPopoverCtl = null;
+ document.querySelector('.recipient-chip-popover')?.remove();
+ document.querySelectorAll('.recipient-chip.popover-open').forEach(chip => {
+ chip.classList.remove('popover-open');
+ });
+ }
+
+ function _showRecipientChipPopover(chip) {
+ if (!chip) return false;
+ _closeRecipientChipPopover();
+ const full = _decodeAttrValue(chip.dataset.full || '').trim();
+ const email = chip.dataset.email || _emailAddressFromRecipientText(full);
+ const name = chip.dataset.name || chip.querySelector('.recipient-chip-label')?.textContent?.trim() || '';
+ const detail = full || email || name;
+ if (!detail) return true;
+
+ chip.classList.add('popover-open');
+ const pop = document.createElement('div');
+ pop.className = 'recipient-chip-popover';
+ pop.setAttribute('role', 'dialog');
+ pop.setAttribute('aria-label', 'Sender details');
+ pop.innerHTML = `
+ <div class="recipient-chip-popover-main">
+ ${name && detail !== name ? `<div class="recipient-chip-popover-name">${_esc(name)}</div>` : ''}
+ <div class="recipient-chip-popover-detail">${_esc(detail)}</div>
+ </div>
+ ${email ? `<button type="button" class="recipient-chip-popover-copy" title="Copy email" aria-label="Copy email">${_COPY_EMAIL_ICON}</button>` : ''}
+ `;
+ document.body.appendChild(pop);
+
+ const rect = chip.getBoundingClientRect();
+ const margin = 10;
+ const maxLeft = Math.max(margin, window.innerWidth - pop.offsetWidth - margin);
+ let left = Math.min(Math.max(margin, rect.left), maxLeft);
+ let top = rect.bottom + 6;
+ if (top + pop.offsetHeight + margin > window.innerHeight) {
+ top = Math.max(margin, rect.top - pop.offsetHeight - 6);
+ }
+ pop.style.left = `${Math.round(left)}px`;
+ pop.style.top = `${Math.round(top)}px`;
+
+ const ctl = new AbortController();
+ _recipientChipPopoverCtl = ctl;
+ pop.querySelector('.recipient-chip-popover-copy')?.addEventListener('click', async (ev) => {
+ ev.preventDefault();
+ ev.stopPropagation();
+ try {
+ const copied = await _copyTextToClipboard(email);
+ if (!copied) throw new Error('copy failed');
+ ev.currentTarget.classList.add('copied');
+ showToast?.('Email copied');
+ setTimeout(_closeRecipientChipPopover, 650);
+ } catch (_) {
+ showToast?.('Copy failed');
+ }
+ }, { signal: ctl.signal });
+ setTimeout(() => {
+ document.addEventListener('pointerdown', (ev) => {
+ if (pop.contains(ev.target) || chip.contains(ev.target)) return;
+ _closeRecipientChipPopover();
+ }, { signal: ctl.signal, capture: true });
+ }, 0);
+ document.addEventListener('keydown', (ev) => {
+ if (ev.key === 'Escape') _closeRecipientChipPopover();
+ }, { signal: ctl.signal });
+ window.addEventListener('resize', _closeRecipientChipPopover, { signal: ctl.signal });
+ window.addEventListener('scroll', _closeRecipientChipPopover, { signal: ctl.signal, capture: true });
+ return true;
+ }
+
+ export function _wireRecipientChips(root) {
+ if (!root || root.dataset.recipientChipsWired === '1') return;
+ root.dataset.recipientChipsWired = '1';
+ root.addEventListener('click', async (ev) => {
+ const copyBtn = ev.target.closest?.('.recipient-chip-copy');
+ if (copyBtn && root.contains(copyBtn)) {
+ ev.stopPropagation();
+ ev.preventDefault();
+ const chip = copyBtn.closest('.recipient-chip');
+ const email = chip?.dataset.email || _emailAddressFromRecipientText(_decodeAttrValue(chip?.dataset.full || ''));
+ if (!email) return;
+ try {
+ const copied = await _copyTextToClipboard(email);
+ if (!copied) throw new Error('copy failed');
+ copyBtn.classList.add('copied');
+ copyBtn.title = 'Copied';
+ showToast?.('Email copied');
+ setTimeout(() => {
+ copyBtn.classList.remove('copied');
+ copyBtn.title = 'Copy email';
+ }, 900);
+ } catch (_) {
+ showToast?.('Copy failed');
+ }
+ return;
+ }
+
+ const chip = ev.target.closest?.('.recipient-chip');
+ if (!chip || !root.contains(chip)) return;
+ ev.stopPropagation();
+ ev.preventDefault();
+ if (_showRecipientChipPopover(chip)) return;
+ const label = chip.querySelector('.recipient-chip-label');
+ const copy = chip.querySelector('.recipient-chip-copy');
+ if (chip.classList.contains('expanded')) {
+ chip.classList.remove('expanded');
+ if (label) label.textContent = chip.dataset.name || label.textContent;
+ if (copy) copy.hidden = true;
+ } else {
+ if (!chip.dataset.name && label) chip.dataset.name = label.textContent.trim();
+ chip.classList.add('expanded');
+ const expandedText = _decodeAttrValue(chip.dataset.full || '').trim()
+ || chip.dataset.name
+ || chip.dataset.email
+ || label?.textContent?.trim()
+ || '';
+ if (label && expandedText) label.textContent = expandedText;
+ if (copy) copy.hidden = false;
+ }
+ });
+ }
+
+ function _emailReaderForSelectAllTarget(target) {
+ if (_isEmailTypingTarget(target)) return null;
+ const direct = target?.closest?.('.email-card-reader, #email-lib-modal .doclib-card.doclib-card-expanded');
+ if (direct) return direct.querySelector?.('.email-card-reader') || direct;
+ const expanded = document.querySelector('#email-lib-modal:not(.hidden) .doclib-card.doclib-card-expanded .email-card-reader');
+ if (expanded) return expanded;
+ return _activeEmailReaderForSelectAll;
+ }
+
+ document.addEventListener('keydown', (e) => {
+ if (!(e.ctrlKey || e.metaKey) || String(e.key || '').toLowerCase() !== 'a') return;
+ const reader = _emailReaderForSelectAllTarget(e.target);
+ if (!_selectEmailReaderContents(reader)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ e.stopImmediatePropagation?.();
+ }, true);
+
+ function _emailReadContextKey(context) {
+ return [context.accountId, context.folder, context.uid].map(value => String(value || '')).join('\u0000');
+ }
+
+ function _emailReadContextIsCurrent(context) {
+ if (!context) return true;
+ return (
+ String(state._libAccountId || '') === context.accountId &&
+ String(state._libFolder || 'INBOX') === context.libraryFolder &&
+ _emailMailboxGeneration === context.mailboxGeneration
+ );
+ }
+
+ function _emailMatchesReadContext(email, context) {
+ if (String(email?.uid || '') !== context.uid) return false;
+ const accountId = String(email?.account_id || context.accountId);
+ const folder = String(email?.folder || context.folder);
+ return accountId === context.accountId && folder === context.folder;
+ }
+
+ export function _syncEmailReadState(uid, isRead = true, context = null) {
+ if (uid == null) return;
+ const uidStr = String(uid);
+ const read = !!isRead;
+ if (context && (!_emailReadContextIsCurrent(context) || uidStr !== context.uid)) return;
+ const match = (state._libEmails || []).find(x => (
+ context ? _emailMatchesReadContext(x, context) : String(x.uid) === uidStr
+ ));
+ if (match) match.is_read = read;
+
+ document.querySelectorAll('.doclib-card[data-uid="' + CSS.escape(uidStr) + '"]').forEach(card => {
+ if (context && (
+ String(card.dataset.emailAccount || '') !== context.accountId ||
+ String(card.dataset.emailFolder || '') !== context.folder
+ )) return;
+ card.classList.toggle('email-card-unread', !read);
+ const titleRow = card.querySelector('.email-card-titlerow');
+ if (read) {
+ card.querySelectorAll('.email-card-unread-dot, [data-unread-dot]').forEach(n => n.remove());
+ if (titleRow) {
+ titleRow.querySelectorAll('span').forEach(s => {
+ const st = s.getAttribute('style') || '';
+ if (/width:\s*6px/.test(st) && /border-radius:\s*50%/.test(st)) s.remove();
+ });
+ }
+ return;
+ }
+
+ if (!titleRow || titleRow.querySelector('.email-card-unread-dot, [data-unread-dot]')) return;
+ const isSentFolder = /sent/i.test(state._libFolder || '');
+ if (isSentFolder) return;
+ const senderName = match ? (match.from_name || match.from_address || '') : '';
+ const dot = document.createElement('span');
+ dot.className = 'email-card-unread-dot';
+ dot.style.cssText = `width:6px;height:6px;border-radius:50%;background:${_senderColor(senderName)};flex-shrink:0;margin-left:2px;`;
+ const done = titleRow.querySelector('.email-card-done');
+ const navArrows = titleRow.querySelector('.email-card-nav-arrows');
+ if (done) done.insertAdjacentElement('afterend', dot);
+ else if (navArrows) titleRow.insertBefore(dot, navArrows);
+ else titleRow.appendChild(dot);
+ });
+ }
+
+ export function _syncEmailDoneState(uid, isDone = true, context = null) {
+ if (uid == null) return;
+ const uidStr = String(uid);
+ const done = !!isDone;
+ const match = (state._libEmails || []).find(x => (
+ context ? _emailMatchesReadContext(x, context) : String(x.uid) === uidStr
+ ));
+ if (match) {
+ match.is_answered = done;
+ match.is_done = done;
+ }
+ document.querySelectorAll('.doclib-card[data-uid="' + CSS.escape(uidStr) + '"]').forEach(card => {
+ if (context && (
+ String(card.dataset.emailAccount || '') !== context.accountId ||
+ String(card.dataset.emailFolder || '') !== context.folder
+ )) return;
+ card.classList.toggle('email-card-answered', done);
+ const check = card.querySelector('.email-card-done');
+ if (check) {
+ check.classList.toggle('active', done);
+ check.title = done ? 'Mark not done' : 'Mark done';
+ }
+ if (done) {
+ card.querySelectorAll('.email-tag-urgent, .email-tag-reply-soon, .email-tag-action-needed').forEach(n => n.remove());
+ }
+ });
+ }
+
+ // When a reply is sent (from the doc editor), the source email is marked
+ // \Answered server-side and an `email-answered` event fires. Reflect that live
+ // so the email shows as done without waiting for a manual refresh.
+ window.addEventListener('email-answered', (e) => {
+ const uid = e.detail && e.detail.uid;
+ if (uid == null) return;
+ const em = (state._libEmails || []).find(x => String(x.uid) === String(uid));
+ if (em) {
+ em.is_answered = true;
+ em.is_done = true;
+ em.is_read = true;
+ _clearDoneResponseTagsLocal(em);
+ }
+ _syncEmailDoneState(uid, true);
+ _syncEmailReadState(uid, true);
+ document.querySelectorAll('.doclib-card[data-uid="' + CSS.escape(String(uid)) + '"]').forEach(card => {
+ card.classList.add('email-card-answered');
+ card.classList.remove('email-card-unread');
+ card.querySelectorAll('.email-tag-urgent, .email-tag-reply-soon, .email-tag-action-needed').forEach(n => n.remove());
+ const check = card.querySelector('.email-card-done');
+ if (check) check.classList.add('active');
+ });
+ });
+
+ function _toggleUnreadEmails() {
+ if (state._libFolder === '__scheduled__') state._libFolder = 'INBOX';
+ state._libFilter = state._libFilter === 'unread' ? 'all' : 'unread';
+ _syncUnreadWindowGlow();
+ const folderEl = document.getElementById('email-lib-folder');
+ const filterEl = document.getElementById('email-lib-filter');
+ if (folderEl) folderEl.value = state._libFolder || 'INBOX';
+ if (filterEl) filterEl.value = state._libFilter;
+ _syncSearchOptionsMenu();
+ _renderSearchPills();
+ _loadEmailsFresh();
+ }
+
+ function _syncUnreadTabBadge(count) {
+ const label = count > 999 ? '999+ unread' : `${count} unread`;
+ document.querySelectorAll('.minimized-dock-chip[data-modal-id="email-lib-modal"]').forEach(chip => {
+ if (count > 0) {
+ chip.dataset.emailUnreadLabel = label;
+ chip.title = `Open ${label}`;
+ } else {
+ delete chip.dataset.emailUnreadLabel;
+ chip.title = 'Restore Email';
+ }
+ });
+ }
+
+ function _syncCurrentAccountUnreadCount(count) {
+ const accountId = String(state._libAccountId || '');
+ if (!accountId) return;
+ const nextCount = Math.max(0, Number(count) || 0);
+ const prev = _accountUnreadState.get(accountId) || {};
+ _accountUnreadState.set(accountId, {
+ ...prev,
+ unreadCount: nextCount,
+ });
+ _renderAccountsStrip();
+ }
+
+ function _syncUnreadWindowGlow() {
+ document.getElementById('email-lib-modal')?.classList.toggle('email-lib-unread-active', state._libFilter === 'unread');
+ }
+
+ function _syncReminderClearButton() {
+ document.getElementById('email-reminders-clear-btn')?.classList.toggle('hidden', state._libFilter !== 'reminders');
+ }
+
+ function _syncSearchOptionsMenu() {
+ const btn = document.getElementById('email-search-options-btn');
+ const menu = document.getElementById('email-search-options-menu');
+ const hasDate = !!(state._libDateFrom || state._libDateTo);
+ const hasActive = state._libFilter === 'undone' || state._libFilter === 'reminders' || !!state._libHasAttachments || hasDate;
+ btn?.classList.toggle('active', hasActive);
+ menu?.querySelector('[data-email-search-option="undone"]')?.classList.toggle('active', state._libFilter === 'undone');
+ menu?.querySelector('[data-email-search-option="reminders"]')?.classList.toggle('active', state._libFilter === 'reminders');
+ menu?.querySelector('[data-email-search-option="attachments"]')?.classList.toggle('active', !!state._libHasAttachments);
+ menu?.querySelector('[data-email-search-option="date"]')?.classList.toggle('active', hasDate);
+ }
+
+ function _setEmailListFilter(value) {
+ const filterEl = document.getElementById('email-lib-filter');
+ state._libFilter = state._libFilter === value ? 'all' : value;
+ if (filterEl) filterEl.value = state._libFilter;
+ _syncUnreadWindowGlow();
+ _syncReminderClearButton();
+ _renderFilterPickerCurrent();
+ _syncSearchOptionsMenu();
+ _renderSearchPills();
+ _loadEmailsFresh();
+ }
+
+ function _toggleEmailAttachmentFilter() {
+ state._libHasAttachments = !state._libHasAttachments;
+ _syncReminderClearButton();
+ _syncSearchOptionsMenu();
+ _renderSearchPills();
+ _loadEmailsFresh();
+ }
+
+ function _renderAccountsLoading() {
+ const strip = document.getElementById('email-lib-accounts');
+ if (!strip) return;
+ strip.style.display = 'flex';
+ strip.innerHTML = '';
+ try {
+ const wp = spinnerModule.createWhirlpool(14);
+ wp.element.classList.add('email-accounts-loading-whirlpool');
+ strip.appendChild(wp.element);
+ } catch (_) {}
+ }
+
+ function _syncEmailReminderBellVisibility(enabled) {
+ const item = document.querySelector('#email-search-options-menu [data-email-search-option="reminders"]');
+ item?.classList.toggle('hidden', !enabled);
+ _syncSearchOptionsMenu();
+ }
+
+ async function _loadEmailReminderBellVisibility() {
+ try {
+ const settings = await getSettings();
+ _syncEmailReminderBellVisibility(settings.reminder_channel === 'email');
+ } catch (_) {
+ _syncEmailReminderBellVisibility(false);
+ }
+ }
+ // Live-update the bell when the reminder channel changes in Settings,
+ // so the user doesn't have to reopen Email to see the change apply.
+ window.addEventListener('odysseus-reminder-channel-changed', (e) => {
+ const ch = e?.detail?.channel;
+ _syncEmailReminderBellVisibility(ch === 'email');
+ });
+
+ function _readCssPx(name) {
+ const v = getComputedStyle(document.documentElement).getPropertyValue(name);
+ const n = parseFloat(v);
+ return Number.isFinite(n) ? n : 0;
+ }
+
+ function _emailSplitLeftEdge() {
+ return _readCssPx('--icon-rail-w') + _readCssPx('--sidebar-w');
+ }
+
+ function _setEmailDocumentSplit(leftEdge, emailWidth) {
+ if (window.innerWidth <= 768) return;
+ // Zero gap so the doc-pane sits flush against the email's right edge.
+ // modalSnap.js's left-dock path publishes the same vars with 0 gap — both
+ // systems agree on flush so handoffs between them don't cause the doc to
+ // "jump" sideways. The 1px modal border on each side is the visual seam.
+ const splitGap = 0;
+ const left = Math.max(0, Math.round(leftEdge || 0));
+ const width = Math.max(320, Math.round(emailWidth || 420));
+ const x = left + width + splitGap;
+ document.body.classList.add('email-doc-split-active');
+ document.documentElement.style.setProperty('--email-doc-split-left-x', `${left}px`);
+ document.documentElement.style.setProperty('--email-doc-split-email-w', `${width}px`);
+ document.documentElement.style.setProperty('--email-doc-split-right-x', `${x}px`);
+ }
+
+ function _measureEmailDocumentSplit(modal) {
+ if (window.innerWidth <= 768 || !document.body.classList.contains('email-doc-split-active')) return;
+ const content = modal?.querySelector?.('.modal-content');
+ const rect = content?.getBoundingClientRect?.();
+ if (!rect || !rect.width) return;
+ const splitGap = 0;
+ document.documentElement.style.setProperty('--email-doc-split-right-x', `${Math.ceil(rect.right + splitGap)}px`);
+ try {
+ modal.style.setProperty('z-index', '150', 'important');
+ if (content) {
+ content.style.setProperty('position', 'absolute', 'important');
+ content.style.setProperty('left', '0px', 'important');
+ content.style.setProperty('right', 'auto', 'important');
+ content.style.setProperty('width', `${Math.ceil(rect.width)}px`, 'important');
+ content.style.setProperty('max-width', `${Math.ceil(rect.width)}px`, 'important');
+ }
+ const docPane = document.getElementById('doc-editor-pane');
+ if (docPane) {
+ docPane.style.setProperty('position', 'fixed', 'important');
+ docPane.style.setProperty('left', `${Math.ceil(rect.right + splitGap)}px`, 'important');
+ docPane.style.setProperty('right', '0px', 'important');
+ docPane.style.setProperty('top', '0px', 'important');
+ docPane.style.setProperty('bottom', '0px', 'important');
+ docPane.style.setProperty('width', 'auto', 'important');
+ docPane.style.setProperty('max-width', 'none', 'important');
+ docPane.style.setProperty('height', '100vh', 'important');
+ docPane.style.setProperty('z-index', '260', 'important');
+ }
+ } catch (_) {}
+ }
+
+ function _scheduleEmailDocumentSplitMeasure(modal) {
+ requestAnimationFrame(() => {
+ _measureEmailDocumentSplit(modal);
+ requestAnimationFrame(() => _measureEmailDocumentSplit(modal));
+ });
+ setTimeout(() => _measureEmailDocumentSplit(modal), 260);
+ setTimeout(() => _measureEmailDocumentSplit(modal), 700);
+ }
+
+ function _clearEmailDocumentSplit() {
+ document.body.classList.remove('email-doc-split-active');
+ document.documentElement.style.removeProperty('--email-doc-split-left-x');
+ document.documentElement.style.removeProperty('--email-doc-split-email-w');
+ document.documentElement.style.removeProperty('--email-doc-split-right-x');
+ const docPane = document.getElementById('doc-editor-pane');
+ if (!docPane) return;
+ [
+ 'position', 'left', 'right', 'top', 'bottom', 'width', 'max-width',
+ 'height', 'z-index', 'transform',
+ ].forEach(prop => docPane.style.removeProperty(prop));
+ }
+
+ // Compute the left-edge x assuming the wide sidebar has collapsed to the
+ // rail. Used by the "try collapsing the sidebar first" path so we can decide
+ // whether collapsing recovers enough room before minimizing email.
+ function _emailSplitLeftEdgeIfSidebarCollapsed() {
+ return _readCssPx('--icon-rail-w');
+ }
+
+ function _hasDesktopRoomForEmailAndDocument(modal, opts = {}) {
+ if (window.innerWidth <= 768) return false;
+ if (window.innerWidth >= 1100) return true;
+ const content = modal?.querySelector?.('.modal-content');
+ const rect = content?.getBoundingClientRect?.();
+ const isFullscreen = modal?.classList?.contains('email-lib-fullscreen')
+ || modal?.classList?.contains('email-window-fullscreen');
+ const emailWidth = isFullscreen
+ ? Math.min(440, Math.max(360, Math.round(window.innerWidth * 0.30)))
+ : Math.max(360, Math.round(rect?.width || 440));
+ // Relaxed thresholds — the old 560 + 72 forced an unnecessary tab-down
+ // on ~1200–1300px viewports where there was visually plenty of room.
+ const docMinWidth = 460;
+ const breathingRoom = 40;
+ const leftEdgeNow = isFullscreen ? _emailSplitLeftEdge() : Math.max(0, Math.round(rect?.left || _emailSplitLeftEdge()));
+ const leftEdge = opts.assumeSidebarCollapsed ? _emailSplitLeftEdgeIfSidebarCollapsed() : leftEdgeNow;
+ return (window.innerWidth - leftEdge - emailWidth) >= (docMinWidth + breathingRoom);
+ }
+
+ export function _prepareEmailWindowForDocument(modal) {
+ if (window.innerWidth <= 768) return true;
+ if (!modal) return false;
+ // Try to make breathing room by collapsing the wide sidebar to the rail
+ // when there isn't enough horizontal space for both panes. The
+ // route-collapse marker that collapseSidebarToRail() sets means the
+ // sidebar will auto-restore when the doc closes. Crucially, we no
+ // longer fall back to clearing the split when even that isn't enough —
+ // the user opted out of auto-tab-down, so we proceed with the dock
+ // even if it's cramped.
+ if (!_hasDesktopRoomForEmailAndDocument(modal)) {
+ const sidebar = document.getElementById('sidebar');
+ const sidebarWasOpen = sidebar && !sidebar.classList.contains('hidden');
+ if (sidebarWasOpen && _hasDesktopRoomForEmailAndDocument(modal, { assumeSidebarCollapsed: true })) {
+ try { collapseSidebarToRail(); } catch (_) {}
+ }
+ }
+ if (modal.classList.contains('modal-left-docked')) {
+ const content = modal.querySelector('.modal-content');
+ const rect = content?.getBoundingClientRect?.();
+ if (content?._leftDockNavObs) {
+ try { content._leftDockNavObs.navObs.disconnect(); } catch (_) {}
+ try { content._leftDockNavObs.bodyObs && content._leftDockNavObs.bodyObs.disconnect(); } catch (_) {}
+ try { content._leftDockNavObs.disconnectDocObs && content._leftDockNavObs.disconnectDocObs(); } catch (_) {}
+ try { window.removeEventListener('resize', content._leftDockNavObs.reanchor); } catch (_) {}
+ delete content._leftDockNavObs;
+ }
+ modal.classList.remove('modal-left-docked');
+ modal.classList.add('email-snap-left');
+ document.body.classList.remove('left-dock-active');
+ document.documentElement.style.removeProperty('--left-dock-w');
+ if (content) {
+ delete content._dockSide;
+ content.style.position = 'fixed';
+ content.style.left = Math.round(rect?.left || _emailSplitLeftEdge()) + 'px';
+ content.style.top = '0';
+ content.style.right = 'auto';
+ content.style.bottom = '0';
+ content.style.width = Math.round(rect?.width || 440) + 'px';
+ content.style.maxWidth = Math.round(rect?.width || 440) + 'px';
+ content.style.height = '100vh';
+ content.style.maxHeight = '100vh';
+ content.style.borderRadius = '0';
+ content.style.transform = 'none';
+ content.style.margin = '0';
+ }
+ }
+ if (modal.classList.contains('email-snap-left') || modal.classList.contains('modal-left-docked')) {
+ const rect = modal.querySelector('.modal-content')?.getBoundingClientRect?.();
+ _setEmailDocumentSplit(rect?.left || _emailSplitLeftEdge(), rect?.width || 420);
+ _scheduleEmailDocumentSplitMeasure(modal);
+ return false;
+ }
+ // If Email is fullscreen and there is room, park it left instead of
+ // minimizing so the document/compose pane can open beside it.
+ _snapEmailModalToLeftSidebar(modal);
+ return false;
+ }
+
+ function _wireUnreadTabClick() {
+ if (_emailUnreadChipClickWired) return;
+ _emailUnreadChipClickWired = true;
+ document.addEventListener('click', (e) => {
+ const chip = e.target?.closest?.('.minimized-dock-chip[data-modal-id="email-lib-modal"][data-email-unread-label]');
+ if (!chip || e.target?.classList?.contains('minimized-dock-x')) return;
+ setTimeout(_toggleUnreadEmails, 0);
+ });
+ }
+
+ async function _deleteEmailAndAdvance(em, card, opts = {}) {
+ if (!em || em.uid == null) return;
+ if (opts.confirm !== false) {
+ const subject = em.subject || '(no subject)';
+ const ok = await styledConfirm(`Delete "${subject}"?`, { confirmText: 'Delete', cancelText: 'Cancel', danger: true });
+ if (!ok) return;
+ }
+ const busy = _showEmailDeleteOverlay(card);
+ await busy?.ready;
+ const wasExpanded = !!card?.classList?.contains('doclib-card-expanded');
+ const sibling = wasExpanded
+ ? (_findSiblingEmailCard(card, +1) || _findSiblingEmailCard(card, -1))
+ : null;
+ const nextUid = sibling ? sibling.dataset.uid : null;
+ try {
+ const response = await fetch(`${API_BASE}/api/email/delete/${encodeURIComponent(em.uid)}?${_emailMutationQuery(em)}`, { method: 'DELETE' });
+ await _requireSuccessfulEmailMutation(response, 'Failed to delete email');
+ } catch (err) {
+ console.error('Failed to delete email:', err);
+ busy?.remove?.();
+ showToast('Failed to delete email');
+ return;
+ }
+ busy?.remove?.();
+ await _animateEmailCardRemoval([em.uid]);
+ state._libEmails = state._libEmails.filter(e => String(e.uid) !== String(em.uid));
+ state._selectedUids.delete(em.uid);
+ _updateBulkBar();
+ _renderGrid();
+ _libCacheWriteBack();
+ showToast('Moved to Trash');
+ if (!wasExpanded || !nextUid) return;
+ const grid = document.getElementById('email-lib-grid');
+ const nextCard = grid?.querySelector(`.doclib-card[data-uid="${CSS.escape(String(nextUid))}"]`);
+ const nextEm = state._libEmails.find(e => String(e.uid) === String(nextUid));
+ if (nextCard && nextEm) {
+ await _toggleCardPreview(nextCard, nextEm);
+ nextCard.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
+ } else {
+ document.getElementById('email-lib-modal')?.classList.remove('email-reading');
+ }
+ }
+
+ export function _showEmailDeleteOverlay(target) {
+ if (!target) return null;
+ const wp = spinnerModule.createWhirlpool(18);
+ const overlay = document.createElement('div');
+ overlay.className = 'email-delete-overlay';
+ overlay.appendChild(wp.element);
+ const prevPos = target.style.position;
+ const prevPointerEvents = target.style.pointerEvents;
+ if (getComputedStyle(target).position === 'static') target.style.position = 'relative';
+ target.style.pointerEvents = 'none';
+ target.classList.add('email-delete-busy');
+ target.appendChild(overlay);
+ const ready = new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ return {
+ ready,
+ remove() {
+ try { wp.destroy?.(); } catch (_) {}
+ overlay.remove();
+ target.classList.remove('email-delete-busy');
+ target.style.pointerEvents = prevPointerEvents;
+ target.style.position = prevPos;
+ }
+ };
+ }
+
+ export function _animateEmailCardRemoval(uids, opts = {}) {
+ const uidSet = new Set((uids || []).map(uid => String(uid)));
+ if (!uidSet.size) return Promise.resolve();
+ const grid = document.getElementById('email-lib-grid');
+ if (!grid) return Promise.resolve();
+ const cards = Array.from(grid.querySelectorAll('.doclib-card[data-uid]'))
+ .filter(card => uidSet.has(String(card.dataset.uid)));
+ if (!cards.length) return Promise.resolve();
+ const duration = Number(opts.duration || 230);
+
+ for (const card of cards) {
+ const rect = card.getBoundingClientRect();
+ card.style.setProperty('--email-remove-h', `${Math.max(rect.height, card.scrollHeight)}px`);
+ card.style.maxHeight = 'var(--email-remove-h)';
+ card.style.overflow = 'hidden';
+ card.classList.add('email-card-removing');
+ }
+
+ return new Promise(resolve => {
+ window.setTimeout(resolve, duration + 35);
+ });
+ }
+
+
+ function _selectedEmailExportPayload() {
+ const selected = new Set(Array.from(state._selectedUids || []).map(uid => String(uid)));
+ return (state._libEmails || [])
+ .filter(em => selected.has(String(em.uid)))
+ .map(em => ({
+ uid: String(em.uid || ''),
+ folder: String(em.folder || state._libFolder || 'INBOX'),
+ account_id: String(em.account_id || state._libAccountId || ''),
+ subject: String(em.subject || ''),
+ date: (() => {
+ const parsed = em.date_epoch ? new Date(Number(em.date_epoch) * 1000) : new Date(em.date || '');
+ return Number.isFinite(parsed.getTime()) ? parsed.toISOString().slice(0, 10) : '';
+ })(),
+ }))
+ .filter(em => em.uid);
+ }
+
+ function _downloadBlob(blob, filename) {
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = filename || 'selected-email-attachments.zip';
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 1500);
+ }
+
+ function _filenameFromContentDisposition(header) {
+ const value = String(header || '');
+ const utf = value.match(/filename\*=UTF-8''([^;]+)/i);
+ if (utf) {
+ try { return decodeURIComponent(utf[1]); } catch (_) {}
+ }
+ const quoted = value.match(/filename="([^"]+)"/i);
+ if (quoted) return quoted[1];
+ const bare = value.match(/filename=([^;]+)/i);
+ return bare ? bare[1].trim() : '';
+ }
+
+ export async function _exportSelectedAttachments() {
+ const messages = _selectedEmailExportPayload();
+ if (!messages.length) {
+ showToast('Select emails first');
+ return;
+ }
+ const actionsBtn = document.getElementById('email-lib-bulk-actions');
+ const deleteBtn = document.getElementById('email-lib-bulk-delete');
+ const cancelBtn = document.getElementById('email-lib-bulk-cancel');
+ const selectAll = document.getElementById('email-lib-select-all');
+ const countEl = document.getElementById('email-lib-selected-count');
+ const originalActionsHtml = actionsBtn?.innerHTML || '';
+ const originalCountText = countEl?.textContent || '';
+ let busySpinner = null;
+ try {
+ if (actionsBtn) {
+ actionsBtn.disabled = true;
+ actionsBtn.classList.add('email-bulk-loading');
+ actionsBtn.innerHTML = '<span class="email-bulk-loading-label">Exporting</span>';
+ busySpinner = spinnerModule.create('', 'clean', 'whirlpool');
+ const spEl = busySpinner.createElement();
+ spEl.classList.add('email-bulk-whirlpool');
+ actionsBtn.appendChild(spEl);
+ busySpinner.start();
+ }
+ if (deleteBtn) deleteBtn.disabled = true;
+ if (cancelBtn) cancelBtn.disabled = true;
+ if (selectAll) selectAll.disabled = true;
+ if (countEl) countEl.textContent = `Exporting attachments from ${messages.length}…`;
+ const res = await fetch(`${API_BASE}/api/email/attachments-download-bulk`, {
+ method: 'POST',
+ credentials: 'same-origin',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ messages,
+ category: String(state._libFilter || '').replace(/^tag:/, ''),
+ }),
+ });
+ if (!res.ok) {
+ let detail = '';
+ try {
+ const data = await res.json();
+ detail = data?.detail || data?.error || '';
+ } catch (_) {}
+ throw new Error(detail || `HTTP ${res.status}`);
+ }
+ const blob = await res.blob();
+ const filename = _filenameFromContentDisposition(res.headers.get('Content-Disposition')) || 'selected-email-attachments.zip';
+ _downloadBlob(blob, filename);
+ showToast(`Exported attachments from ${messages.length} selected email${messages.length === 1 ? '' : 's'}`);
+ } catch (err) {
+ console.error('Failed to export selected email attachments:', err);
+ showToast(err?.message || 'Failed to export attachments');
+ } finally {
+ if (busySpinner) busySpinner.destroy();
+ if (actionsBtn) {
+ actionsBtn.disabled = false;
+ actionsBtn.classList.remove('email-bulk-loading');
+ actionsBtn.innerHTML = originalActionsHtml || actionsBtn.innerHTML;
+ }
+ if (deleteBtn) deleteBtn.disabled = false;
+ if (cancelBtn) cancelBtn.disabled = false;
+ if (selectAll) selectAll.disabled = false;
+ if (countEl) countEl.textContent = originalCountText;
+ _updateBulkBar();
+ }
+ }
+
+ // URL-suffix helper — appends &account_id=... when an account is actively selected.
+ // Every email route call in this file goes through here so switching accounts
+ // is a single-variable flip.
+ // Open the Settings modal and activate a specific tab. Used by empty-state
+ // "Set up at: Settings › X" links across email/calendar/etc.
+ function _openSettingsTab(tab) {
+ if (tab === 'integrations' && window.adminModule && typeof window.adminModule.open === 'function') {
+ window.adminModule.open('integrations');
+ return;
+ }
+ if (settingsModule && typeof settingsModule.open === 'function') {
+ settingsModule.open(tab || 'services');
+ return;
+ }
+ const modal = document.getElementById('settings-modal');
+ if (!modal) return;
+ modal.classList.remove('hidden');
+ const tabBtn = modal.querySelector(`[data-settings-tab="${tab || 'services'}"]`);
+ if (tabBtn) tabBtn.click();
+ }
+
+ function _openGlobalEmailSettings(focus) {
+ const host = document.getElementById('settings-email-preferences');
+ if (host && focus) host.dataset.emailSettingsFocus = focus;
+ _openSettingsTab('email');
+ setTimeout(() => {
+ const section = focus === 'show-tags'
+ ? document.querySelector('#settings-email-preferences .email-settings-display-section')
+ : document.querySelector(`#settings-email-preferences .email-settings-${focus || 'style'}-section`);
+ if (section) {
+ section.scrollIntoView?.({ block: 'nearest' });
+ }
+ }, 0);
+ }
+
+ function _emailSetupHintHtml() {
+ return '<div style="margin-top:6px;opacity:0.72;font-size:11px;">' +
+ 'Setup: <a href="#" data-open-settings="integrations" style="color:var(--accent,var(--red));text-decoration:underline;">Settings &rsaquo; Integrations</a>' +
+ '</div>';
+ }
+
+ function _wireEmailSetupHint(root) {
+ root?.querySelectorAll?.('[data-open-settings]').forEach(link => {
+ if (link.dataset.emailSetupBound === '1') return;
+ link.dataset.emailSetupBound = '1';
+ link.addEventListener('click', (e) => {
+ e.preventDefault();
+ _openSettingsTab(link.dataset.openSettings || 'integrations');
+ });
+ });
+ }
+
+ export function _acct() {
+ return state._libAccountId ? `&account_id=${encodeURIComponent(state._libAccountId)}` : '';
+ }
+
+ export function _emailMutationQuery(em, fallbackFolder = state._libFolder) {
+ const folder = String(em?.folder || fallbackFolder || 'INBOX');
+ const accountId = em?.account_id || state._libAccountId || '';
+ const params = new URLSearchParams({ folder });
+ if (accountId) params.set('account_id', String(accountId));
+ if (em?.message_id) params.set('message_id', String(em.message_id));
+ return params.toString();
+ }
+
+ export async function _requireSuccessfulEmailMutation(response, fallback = 'Email operation failed') {
+ const data = await response.json().catch(() => null);
+ if (!response.ok || data?.success !== true) {
+ throw new Error(data?.error || `${fallback} (${response.status})`);
+ }
+ return data;
+ }
+
+
+ function _rememberedEmailAccountId() {
+ try {
+ return String(localStorage.getItem(_LIB_LAST_ACCOUNT_KEY) || '').trim();
+ } catch (_) {
+ return '';
+ }
+ }
+
+ // Per-(account, folder, filter, attachments) cache of the most recent
+ // first-page list response. Lets open-after-refresh paint the previous
+ // list instantly while the network refresh runs behind it. Search results
+ // and __scheduled__ are deliberately not cached.
+ const _libListCache = new Map();
+ const _LIB_CACHE_MAX = 24;
+ const _LIB_INITIAL_PAGE_SIZE = 100;
+ const _LIB_SESSION_CACHE_PREFIX = 'odysseus.email.list.';
+ const _LIB_SESSION_CACHE_TTL_MS = 10 * 60 * 1000;
+ const _LIB_PERSIST_CACHE_PREFIX = 'odysseus.email.list.v2.';
+ const _LIB_PERSIST_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
+ const _LIB_PERSIST_CACHE_MAX = 12;
+ const _LIB_LAST_ACCOUNT_KEY = 'odysseus.email.lastAccountId';
+ const _LIB_PREWARM_COOLDOWN_MS = 5 * 60 * 1000;
+ let _libPrewarmDelayTimer = null;
+ let _libPrewarmIdleHandle = null;
+ let _libPrewarmPromise = null;
+ let _libPrewarmResolve = null;
+ let _libPrewarmAbortController = null;
+ let _libPrewarmDetachPriorityListeners = null;
+ let _libPrewarmGeneration = 0;
+ let _libLastPrewarmAt = 0;
+ let _libUnreadPrewarmKey = '';
+ let _libUnreadPrewarmAt = 0;
+ let _libRenderedViewKey = '';
+ let _libSyncStatus = {
+ updatedAt: '',
+ source: '',
+ warming: false,
+ loading: false,
+ };
+ let _libSyncTicker = null;
+
+ function _libSyncDateFrom(value) {
+ if (!value) return null;
+ const d = new Date(value);
+ return Number.isFinite(d.getTime()) ? d : null;
+ }
+
+ function _libRelativeTime(value) {
+ const d = _libSyncDateFrom(value);
+ if (!d) return '';
+ const seconds = Math.max(0, Math.floor((Date.now() - d.getTime()) / 1000));
+ if (seconds < 45) return 'just now';
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes}m ago`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.floor(hours / 24);
+ return `${days}d ago`;
+ }
+
+ function _renderEmailSyncStatus() {
+ const el = document.getElementById('email-lib-sync-status');
+ if (!el) return;
+ const parts = [];
+ const rel = _libRelativeTime(_libSyncStatus.updatedAt);
+ if (rel) parts.push(`Last: ${rel}`);
+ if (_libSyncStatus.loading) {
+ if (state._libEmails.length) parts.push('Updating...');
+ el.textContent = parts.join(' · ');
+ el.style.visibility = parts.length ? 'visible' : 'hidden';
+ return;
+ }
+ el.textContent = parts.join(' · ');
+ el.style.visibility = parts.length ? 'visible' : 'hidden';
+ }
+
+ function _setEmailSyncStatus(next = {}) {
+ if (Object.prototype.hasOwnProperty.call(next, 'updatedAt')) {
+ const updatedAt = next.updatedAt || '';
+ if (!updatedAt) {
+ _libSyncStatus.updatedAt = _libSyncStatus.updatedAt || '';
+ } else if (_libSyncDateFrom(updatedAt)) {
+ _libSyncStatus.updatedAt = updatedAt;
+ }
+ }
+ if (Object.prototype.hasOwnProperty.call(next, 'source')) {
+ _libSyncStatus.source = next.source || '';
+ }
+ if (Object.prototype.hasOwnProperty.call(next, 'warming')) {
+ _libSyncStatus.warming = Boolean(next.warming);
+ }
+ if (Object.prototype.hasOwnProperty.call(next, 'loading')) {
+ _libSyncStatus.loading = Boolean(next.loading);
+ }
+ _renderEmailSyncStatus();
+ }
+
+ function _libCacheKeyFor(accountId, folder, filter, hasAttachments) {
+ return [
+ accountId || '',
+ folder || '',
+ filter || '',
+ hasAttachments ? 1 : 0,
+ state._libDateFrom || '',
+ state._libDateTo || '',
+ ].join('|');
+ }
+ function _libCacheKey() {
+ return _libCacheKeyFor(
+ state._libAccountId || '',
+ state._libFolder || '',
+ state._libFilter || '',
+ state._libHasAttachments
+ );
+ }
+ function _libSessionCacheKey(key) {
+ return _LIB_SESSION_CACHE_PREFIX + encodeURIComponent(String(key || ''));
+ }
+ function _libPersistCacheKey(key) {
+ return _LIB_PERSIST_CACHE_PREFIX + encodeURIComponent(String(key || ''));
+ }
+ function _libSessionCacheGet(key) {
+ try {
+ const raw = sessionStorage.getItem(_libSessionCacheKey(key));
+ if (!raw) return null;
+ const parsed = JSON.parse(raw);
+ if (!parsed || !parsed.savedAt || (Date.now() - parsed.savedAt) > _LIB_SESSION_CACHE_TTL_MS) {
+ sessionStorage.removeItem(_libSessionCacheKey(key));
+ return null;
+ }
+ return parsed.value || null;
+ } catch (_) {
+ return null;
+ }
+ }
+ function _libPersistCacheGet(key) {
+ try {
+ const storageKey = _libPersistCacheKey(key);
+ const raw = localStorage.getItem(storageKey);
+ if (!raw) return null;
+ const parsed = JSON.parse(raw);
+ if (!parsed || !parsed.savedAt || (Date.now() - parsed.savedAt) > _LIB_PERSIST_CACHE_TTL_MS) {
+ localStorage.removeItem(storageKey);
+ return null;
+ }
+ return parsed.value || null;
+ } catch (_) {
+ return null;
+ }
+ }
+ function _libSessionCachePut(key, value) {
+ try {
+ sessionStorage.setItem(_libSessionCacheKey(key), JSON.stringify({ savedAt: Date.now(), value }));
+ } catch (_) {}
+ }
+ function _libPrunePersistCache() {
+ try {
+ const entries = [];
+ for (let i = 0; i < localStorage.length; i++) {
+ const key = localStorage.key(i);
+ if (!key || !key.startsWith(_LIB_PERSIST_CACHE_PREFIX)) continue;
+ let savedAt = 0;
+ try {
+ savedAt = Number(JSON.parse(localStorage.getItem(key) || '{}')?.savedAt || 0);
+ } catch (_) {}
+ entries.push({ key, savedAt });
+ }
+ entries.sort((a, b) => b.savedAt - a.savedAt);
+ for (const stale of entries.slice(_LIB_PERSIST_CACHE_MAX)) {
+ localStorage.removeItem(stale.key);
+ }
+ } catch (_) {}
+ }
+ function _libPersistCachePut(key, value) {
+ try {
+ localStorage.setItem(_libPersistCacheKey(key), JSON.stringify({ savedAt: Date.now(), value }));
+ _libPrunePersistCache();
+ } catch (_) {
+ try { localStorage.removeItem(_libPersistCacheKey(key)); } catch {}
+ }
+ }
+ function _looksLikeFixtureEmailRow(row) {
+ if (!row || typeof row !== 'object') return false;
+ const account = String(row.account || row._account || row.account_id || row._account_id || '').toLowerCase();
+ const from = `${row.from || ''} ${row.from_name || ''} ${row.from_address || ''}`.toLowerCase();
+ const subject = String(row.subject || '').toLowerCase();
+ const messageId = String(row.message_id || '').toLowerCase();
+ return account.includes('fixture')
+ || from.includes('fixture@example')
+ || from.includes('older fixture')
+ || subject === 'older inbox message'
+ || messageId.includes('fixture-email-');
+ }
+ function _libCacheHasFixtureRows(value) {
+ return Boolean(value && Array.isArray(value.emails) && value.emails.some(_looksLikeFixtureEmailRow));
+ }
+ function _libDropCacheKey(key) {
+ _libListCache.delete(key);
+ try { sessionStorage.removeItem(_libSessionCacheKey(key)); } catch (_) {}
+ try { localStorage.removeItem(_libPersistCacheKey(key)); } catch (_) {}
+ }
+ function _libCacheGet(key) {
+ const memory = _libListCache.get(key);
+ if (memory) {
+ if (_libCacheHasFixtureRows(memory)) {
+ _libDropCacheKey(key);
+ return null;
+ }
+ return memory;
+ }
+ const stored = _libSessionCacheGet(key) || _libPersistCacheGet(key);
+ if (stored) {
+ if (_libCacheHasFixtureRows(stored)) {
+ _libDropCacheKey(key);
+ return null;
+ }
+ _libListCache.set(key, stored);
+ return stored;
+ }
+ return null;
+ }
+ function _libCachePut(key, value) {
+ if (_libCacheHasFixtureRows(value)) {
+ _libDropCacheKey(key);
+ return;
+ }
+ // Re-insert to bump LRU recency.
+ _libListCache.delete(key);
+ _libListCache.set(key, value);
+ _libSessionCachePut(key, value);
+ _libPersistCachePut(key, value);
+ if (_libListCache.size > _LIB_CACHE_MAX) {
+ const oldest = _libListCache.keys().next().value;
+ _libListCache.delete(oldest);
+ }
+ }
+
+ function _resetBulkSelectionForContextChange({ rerender = false } = {}) {
+ const hadSelection = !!(state._selectedUids && state._selectedUids.size);
+ const wasSelectMode = !!state._selectMode;
+ if (state._selectedUids) state._selectedUids.clear();
+ state._selectMode = false;
+ if (hadSelection || wasSelectMode) {
+ _updateBulkBar();
+ if (rerender) _renderGrid();
+ }
+ }
+
+ export function _resetEmailListForFreshLoad({ useCache = true, refreshAfterCache = false } = {}) {
+ _exitEmailReaderModeForList();
+ _resetBulkSelectionForContextChange();
+ state._libOffset = 0;
+ _emailMailboxGeneration += 1;
+ _libLoadSeq += 1;
+ const ck = _libCacheKey();
+ const cached = useCache ? _libCacheGet(ck) : null;
+ if (cached && Array.isArray(cached.emails) && cached.emails.length) {
+ state._libEmails = cached.emails.slice();
+ state._libTotal = cached.total || state._libEmails.length;
+ state._libJustOpened = false;
+ _renderGrid();
+ const stats = document.getElementById('email-lib-stats');
+ if (stats) stats.textContent = `${state._libTotal} emails`;
+ _setEmailSyncStatus({ updatedAt: cached.sync?.updated_at || '', source: cached.sync?.source || 'client_cache', loading: refreshAfterCache });
+ _libRenderedViewKey = ck;
+ return;
+ }
+ if (state._libEmails.length && _libRenderedViewKey === ck) {
+ _renderGrid();
+ _setEmailSyncStatus({ loading: false });
+ return;
+ }
+ state._libEmails = [];
+ state._libTotal = 0;
+ _libRenderedViewKey = ck;
+ const grid = document.getElementById('email-lib-grid');
+ if (grid) _renderEmailLoading(grid);
+ const stats = document.getElementById('email-lib-stats');
+ if (stats) stats.textContent = 'Loading...';
+ _setEmailSyncStatus({ loading: true });
+ }
+
+ function _exitEmailReaderModeForList() {
+ const modal = document.getElementById('email-lib-modal');
+ modal?.classList.remove('email-reading');
+ modal?.style.removeProperty('--email-reading-modal-min-h');
+ const grid = document.getElementById('email-lib-grid');
+ grid?.querySelectorAll('.email-card-expanded, .doclib-card-expanded').forEach(card => {
+ unbindExpandedCardDismiss(card);
+ card.classList.remove('email-card-expanded');
+ card.classList.remove('doclib-card-expanded');
+ card.style.minHeight = '';
+ card.querySelector('.email-card-reader')?.remove();
+ });
+ }
+
+ export function _loadEmailsFresh({ force = true, useCache = true, refreshAfterCache = true, showRefreshSpinner = false } = {}) {
+ const refreshBtn = showRefreshSpinner ? document.getElementById('email-lib-refresh-btn') : null;
+ refreshBtn?.classList.add('email-lib-refreshing');
+ const resolvedFolder = _resolveEmailFolderAlias(state._libFolder);
+ if (resolvedFolder && resolvedFolder !== state._libFolder) {
+ state._libFolder = resolvedFolder;
+ const folderSel = document.getElementById('email-lib-folder');
+ if (folderSel) folderSel.value = resolvedFolder;
+ _renderFolderPicker();
+ }
+ _resetEmailListForFreshLoad({ useCache, refreshAfterCache });
+ return _loadEmails({ force, useCache }).finally(() => {
+ refreshBtn?.classList.remove('email-lib-refreshing');
+ });
+ }
+
+ async function _refreshEmailLibraryFromUi(btn = null) {
+ btn?.classList.add('email-lib-refreshing');
+ state._libOffset = 0;
+ // Don't wipe state._libEmails — _loadEmails will paint the current
+ // list while the forced refetch runs, so the grid doesn't blank out
+ // mid-refresh. `force: true` adds the cache-buster so the server's
+ // 8s list cache is bypassed for an actually-fresh result.
+ try {
+ await _loadEmails({ force: true });
+ } finally {
+ btn?.classList.remove('email-lib-refreshing');
+ // Flash a checkmark for ~900ms so the user gets a clear "done" cue.
+ if (btn) {
+ const orig = btn.innerHTML;
+ btn.classList.add('email-lib-refresh-done');
+ btn.innerHTML = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;"><polyline points="20 6 9 17 4 12"/></svg>';
+ setTimeout(() => {
+ if (btn.classList.contains('email-lib-refresh-done')) {
+ btn.classList.remove('email-lib-refresh-done');
+ btn.innerHTML = orig;
+ }
+ }, 900);
+ }
+ }
+ }
+
+ // Refresh the currently visible mailbox after another surface sends a message.
+ // Keep the user's folder, filters, and scroll context intact.
+ export async function refreshEmailLibrary() {
+ if (!state._libOpen) return false;
+ await _loadEmailsFresh({
+ force: true,
+ useCache: false,
+ refreshAfterCache: false,
+ showRefreshSpinner: true,
+ });
+ return true;
+ }
+
+ function _initMobileEmailPullRefresh() {
+ const grid = document.getElementById('email-lib-grid');
+ const modal = document.getElementById('email-lib-modal');
+ const host = modal?.querySelector('.admin-card');
+ if (!grid || !host || grid.dataset.pullRefreshBound === '1') return;
+ if (!('ontouchstart' in window || navigator.maxTouchPoints > 0)) return;
+ grid.dataset.pullRefreshBound = '1';
+
+ const THRESHOLD = 72;
+ const MAX_PULL = 104;
+ let startY = 0;
+ let pullY = 0;
+ let tracking = false;
+ let refreshing = false;
+
+ const indicator = document.createElement('div');
+ indicator.className = 'chat-pull-refresh email-pull-refresh';
+ indicator.setAttribute('aria-hidden', 'true');
+ indicator.innerHTML = '<div class="chat-pull-refresh-spinner"></div>';
+ host.prepend(indicator);
+ const spinnerMount = indicator.querySelector('.chat-pull-refresh-spinner');
+ try {
+ const spinner = spinnerModule.createWhirlpool(18);
+ spinnerMount.replaceChildren(spinner.element);
+ } catch (_) {}
+
+ function setPull(px, active = false) {
+ pullY = Math.max(0, Math.min(MAX_PULL, px));
+ const pct = Math.min(1, pullY / THRESHOLD);
+ indicator.style.setProperty('--pull-refresh-y', `${pullY}px`);
+ indicator.style.setProperty('--pull-refresh-progress', `${pct}`);
+ indicator.classList.toggle('is-visible', active || refreshing || pullY > 2);
+ indicator.classList.toggle('is-ready', pct >= 1 && !refreshing);
+ indicator.classList.toggle('is-refreshing', refreshing);
+ }
+
+ async function runRefresh() {
+ if (refreshing) return;
+ refreshing = true;
+ setPull(THRESHOLD, true);
+ try {
+ await _refreshEmailLibraryFromUi(document.getElementById('email-lib-refresh-btn'));
+ } catch (err) {
+ console.warn('email pull refresh failed:', err);
+ } finally {
+ refreshing = false;
+ setPull(0, false);
+ }
+ }
+
+ grid.addEventListener('touchstart', (e) => {
+ if (refreshing || window.innerWidth > 768) return;
+ if (grid.scrollTop > 0) return;
+ if (e.target?.closest?.('button, input, textarea, select, a, .email-card-reader, .doclib-card-expanded')) return;
+ tracking = true;
+ startY = e.touches[0].clientY;
+ setPull(0, false);
+ }, { passive: true });
+
+ grid.addEventListener('touchmove', (e) => {
+ if (!tracking || refreshing) return;
+ const dy = e.touches[0].clientY - startY;
+ if (dy <= 0) {
+ setPull(0, false);
+ return;
+ }
+ if (grid.scrollTop <= 0) {
+ e.preventDefault();
+ setPull(dy * 0.62, true);
+ }
+ }, { passive: false });
+
+ grid.addEventListener('touchend', () => {
+ if (!tracking) return;
+ tracking = false;
+ if (pullY >= THRESHOLD) runRefresh();
+ else setPull(0, false);
+ }, { passive: true });
+
+ grid.addEventListener('touchcancel', () => {
+ tracking = false;
+ if (!refreshing) setPull(0, false);
+ }, { passive: true });
+ }
+
+ function _isChatInteractionBusy() {
+ try {
+ if (window.__odysseusChatBusy) return true;
+ const until = Number(window.__odysseusChatBusyUntil || 0);
+ return until > Date.now();
+ } catch (_) {
+ return false;
+ }
+ }
+
+ function _canRunEmailPrewarm() {
+ if (state._libOpen || state._libLoading || _libSearchInFlight) return false;
+ if (document.visibilityState && document.visibilityState !== 'visible') return false;
+ return !_isChatInteractionBusy();
+ }
+
+ function _isEmailPrewarmTemporarilyBlocked() {
+ if (state._libOpen || state._libLoading || _libSearchInFlight) return false;
+ if (document.visibilityState && document.visibilityState !== 'visible') return false;
+ return _isChatInteractionBusy();
+ }
+
+ function _isEmailPrewarmCurrent(generation, signal) {
+ return generation === _libPrewarmGeneration
+ && !signal?.aborted
+ && _canRunEmailPrewarm();
+ }
+
+ function _settleEmailPrewarm(generation, value = false) {
+ if (generation !== _libPrewarmGeneration) return;
+ const resolve = _libPrewarmResolve;
+ const detachPriorityListeners = _libPrewarmDetachPriorityListeners;
+ _libPrewarmDelayTimer = null;
+ _libPrewarmIdleHandle = null;
+ _libPrewarmPromise = null;
+ _libPrewarmResolve = null;
+ _libPrewarmAbortController = null;
+ _libPrewarmDetachPriorityListeners = null;
+ detachPriorityListeners?.();
+ resolve?.(value);
+ }
+
+ function _cancelEmailPrewarm() {
+ const resolve = _libPrewarmResolve;
+ const detachPriorityListeners = _libPrewarmDetachPriorityListeners;
+ _libPrewarmGeneration += 1;
+ if (_libPrewarmDelayTimer !== null) {
+ clearTimeout(_libPrewarmDelayTimer);
+ }
+ if (_libPrewarmIdleHandle !== null && typeof window.cancelIdleCallback === 'function') {
+ try { window.cancelIdleCallback(_libPrewarmIdleHandle); } catch (_) {}
+ }
+ try { _libPrewarmAbortController?.abort(); } catch (_) {}
+ _libPrewarmDelayTimer = null;
+ _libPrewarmIdleHandle = null;
+ _libPrewarmPromise = null;
+ _libPrewarmResolve = null;
+ _libPrewarmAbortController = null;
+ _libPrewarmDetachPriorityListeners = null;
+ detachPriorityListeners?.();
+ resolve?.(false);
+ }
+
+ function _scheduleEmailPrewarm(task, { delay = 0 } = {}) {
+ if (_libPrewarmPromise) return _libPrewarmPromise;
+ // Do not disguise a timer as idle work. Browsers without the genuine idle
+ // callback simply skip this optional optimization and load on demand.
+ if (typeof window.requestIdleCallback !== 'function') return Promise.resolve(false);
+
+ const generation = ++_libPrewarmGeneration;
+ _libPrewarmPromise = new Promise(resolve => { _libPrewarmResolve = resolve; });
+ const promise = _libPrewarmPromise;
+ let attemptPending = false;
+ let retryRequested = false;
+
+ function clearScheduledAttempt() {
+ if (_libPrewarmDelayTimer !== null) clearTimeout(_libPrewarmDelayTimer);
+ if (_libPrewarmIdleHandle !== null && typeof window.cancelIdleCallback === 'function') {
+ try { window.cancelIdleCallback(_libPrewarmIdleHandle); } catch (_) {}
+ }
+ _libPrewarmDelayTimer = null;
+ _libPrewarmIdleHandle = null;
+ }
+
+ function scheduleIdleRetry(delay = 500) {
+ if (generation !== _libPrewarmGeneration) return;
+ retryRequested = true;
+ if (attemptPending || _libPrewarmDelayTimer !== null || _libPrewarmIdleHandle !== null) return;
+ if (document.visibilityState && document.visibilityState !== 'visible') return;
+ _libPrewarmDelayTimer = setTimeout(requestIdle, Math.max(50, Number(delay) || 500));
+ }
+
+ function handlePriorityChange() {
+ if (generation !== _libPrewarmGeneration) return;
+ if (_canRunEmailPrewarm()) {
+ scheduleIdleRetry(50);
+ return;
+ }
+
+ const priorityBlocked = _isChatInteractionBusy()
+ || (document.visibilityState && document.visibilityState !== 'visible');
+ if (!priorityBlocked) return;
+
+ retryRequested = true;
+ clearScheduledAttempt();
+ const controller = _libPrewarmAbortController;
+ _libPrewarmAbortController = null;
+ try { controller?.abort(); } catch (_) {}
+ // A hidden page waits for visibilitychange. Chat priority also retains the
+ // timer fallback for busy-until windows whose final transition has no event.
+ if (!document.visibilityState || document.visibilityState === 'visible') {
+ scheduleIdleRetry();
+ }
+ }
+
+ window.addEventListener('odysseus:chat-busy-change', handlePriorityChange);
+ document.addEventListener('visibilitychange', handlePriorityChange);
+ _libPrewarmDetachPriorityListeners = () => {
+ window.removeEventListener('odysseus:chat-busy-change', handlePriorityChange);
+ document.removeEventListener('visibilitychange', handlePriorityChange);
+ };
+
+ function requestIdle() {
+ if (generation !== _libPrewarmGeneration) return;
+ _libPrewarmDelayTimer = null;
+ try {
+ _libPrewarmIdleHandle = window.requestIdleCallback((deadline) => {
+ if (generation !== _libPrewarmGeneration) return;
+ _libPrewarmIdleHandle = null;
+ const hasIdleBudget = Boolean(
+ deadline
+ && !deadline.didTimeout
+ && typeof deadline.timeRemaining === 'function'
+ && deadline.timeRemaining() > 0
+ );
+ if (!_canRunEmailPrewarm()) {
+ if (_isEmailPrewarmTemporarilyBlocked()) {
+ scheduleIdleRetry();
+ } else {
+ _settleEmailPrewarm(generation, false);
+ }
+ return;
+ }
+ if (!hasIdleBudget) {
+ scheduleIdleRetry();
+ return;
+ }
+ if (generation !== _libPrewarmGeneration) {
+ _settleEmailPrewarm(generation, false);
+ return;
+ }
+ const controller = new AbortController();
+ _libPrewarmAbortController = controller;
+ attemptPending = true;
+ retryRequested = false;
+ Promise.resolve()
+ .then(() => task({ signal: controller.signal, generation }))
+ .then(value => {
+ if (controller !== _libPrewarmAbortController || controller.signal.aborted) return;
+ _settleEmailPrewarm(generation, Boolean(value));
+ })
+ .catch(() => {
+ if (controller !== _libPrewarmAbortController || controller.signal.aborted) return;
+ _settleEmailPrewarm(generation, false);
+ })
+ .finally(() => {
+ attemptPending = false;
+ if (generation !== _libPrewarmGeneration) return;
+ if (retryRequested) scheduleIdleRetry();
+ });
+ });
+ } catch (_) {
+ _settleEmailPrewarm(generation, false);
+ }
+ }
+
+ const wait = Math.max(0, Number(delay) || 0);
+ if (wait > 0) _libPrewarmDelayTimer = setTimeout(requestIdle, wait);
+ else requestIdle();
+ return promise;
+ }
+
+ export function prewarmEmailLibrary({ delay = 2500 } = {}) {
+ if (_libPrewarmPromise) return _libPrewarmPromise;
+ const elapsed = Date.now() - _libLastPrewarmAt;
+ if (elapsed >= 0 && elapsed < _LIB_PREWARM_COOLDOWN_MS) return Promise.resolve(false);
+ return _scheduleEmailPrewarm(_prewarmEmailViews, { delay });
+ }
+
+ function _chooseEmailPrewarmAccountId(accounts) {
+ const enabled = Array.isArray(accounts) ? accounts.filter(a => a && a.enabled !== false) : [];
+ const remembered = _rememberedEmailAccountId();
+ const current = String(state._libAccountId || '').trim();
+ const chosen = enabled.find(a => String(a.id || '') === remembered)
+ || enabled.find(a => String(a.id || '') === current)
+ || enabled.find(a => a.is_default)
+ || enabled[0]
+ || null;
+ return String(chosen?.id || '').trim();
+ }
+
+ async function _ensureEmailAccountsForPrewarm({ signal, generation } = {}) {
+ if (!_isEmailPrewarmCurrent(generation, signal)) return null;
+ const accountsFresh = _libAccountsLoadedAt && (Date.now() - _libAccountsLoadedAt) < _LIB_ACCOUNTS_TTL_MS;
+ if (!(Array.isArray(state._libAccounts) && state._libAccounts.length && accountsFresh)) {
+ try {
+ const accountsRes = await fetch(`${API_BASE}/api/email/accounts`, {
+ credentials: 'same-origin',
+ signal,
+ });
+ if (!_isEmailPrewarmCurrent(generation, signal)) return null;
+ if (accountsRes.ok) {
+ const accountsData = await accountsRes.json().catch(() => ({}));
+ if (!_isEmailPrewarmCurrent(generation, signal)) return null;
+ if (Array.isArray(accountsData.accounts)) {
+ state._libAccounts = accountsData.accounts;
+ _libAccountsLoadedAt = Date.now();
+ }
+ }
+ } catch (err) {
+ if (err?.name === 'AbortError') return null;
+ }
+ }
+
+ const accountId = _chooseEmailPrewarmAccountId(state._libAccounts);
+ if (!_isEmailPrewarmCurrent(generation, signal)) return null;
+ if (!accountId) return null;
+ return accountId;
+ }
+
+ export function prewarmUnreadEmails({ limit = 8, maxUid = 0 } = {}) {
+ return _scheduleEmailPrewarm(
+ context => _prewarmUnreadEmailsNow({ limit, maxUid }, context),
+ { delay: 0 }
+ );
+ }
+
+ async function _prewarmUnreadEmailsNow({ limit = 8, maxUid = 0 } = {}, { signal, generation } = {}) {
+ if (!_isEmailPrewarmCurrent(generation, signal)) return false;
+ const accountId = await _ensureEmailAccountsForPrewarm({ signal, generation });
+ if (accountId === null || !_isEmailPrewarmCurrent(generation, signal)) return false;
+ const n = Math.max(1, Math.min(20, Number(limit) || 8));
+ const key = `${accountId}|${maxUid || 0}|${n}`;
+ if (_libUnreadPrewarmKey === key && (Date.now() - _libUnreadPrewarmAt) < 60 * 1000) return true;
+ try {
+ const folder = 'INBOX';
+ const res = await fetch(emailApiUrl('/api/email/list', {
+ folder,
+ limit: n,
+ offset: 0,
+ filter: 'unread',
+ account_id: accountId || undefined,
+ }), {
+ credentials: 'same-origin',
+ signal,
+ });
+ if (!_isEmailPrewarmCurrent(generation, signal) || !res.ok) return false;
+ const data = await res.json().catch(() => null);
+ if (!_isEmailPrewarmCurrent(generation, signal)) return false;
+ if (!data || data.error || !Array.isArray(data.emails) || !data.emails.length) return false;
+ const sync = data.sync || {};
+ _libCachePut(_libCacheKeyFor(accountId, folder, 'unread', false), {
+ emails: data.emails,
+ total: data.total || data.emails.length,
+ sync,
+ });
+ _libUnreadPrewarmKey = key;
+ _libUnreadPrewarmAt = Date.now();
+ return true;
+ } catch (_) {
+ return false;
+ }
+ }
+
+ async function _prewarmEmailViews({ signal, generation } = {}) {
+ if (!_isEmailPrewarmCurrent(generation, signal)) return false;
+ _setEmailSyncStatus({ warming: true });
+ const folder = 'INBOX';
+ const filter = 'all';
+ try {
+ const accountId = await _ensureEmailAccountsForPrewarm({ signal, generation });
+ if (accountId === null || !_isEmailPrewarmCurrent(generation, signal)) return false;
+ const ck = _libCacheKeyFor(accountId, folder, filter, false);
+ if (_libCacheGet(ck)) {
+ _libLastPrewarmAt = Date.now();
+ return true;
+ }
+
+ // One optional first-page request only. Folder metadata, unread state, and
+ // other accounts remain demand-driven so startup cannot fan out into IMAP.
+ const res = await fetch(emailApiUrl('/api/email/list', {
+ folder,
+ limit: _LIB_INITIAL_PAGE_SIZE,
+ offset: 0,
+ filter,
+ account_id: accountId || undefined,
+ }), {
+ credentials: 'same-origin',
+ signal,
+ });
+ if (!_isEmailPrewarmCurrent(generation, signal) || !res.ok) return false;
+ const data = await res.json().catch(() => null);
+ if (!_isEmailPrewarmCurrent(generation, signal)) return false;
+ if (!data || data.error || !Array.isArray(data.emails)) return false;
+ const sync = data.sync || {};
+ _libCachePut(ck, {
+ emails: data.emails,
+ total: data.total || 0,
+ sync,
+ });
+ _libLastPrewarmAt = Date.now();
+ _setEmailSyncStatus({
+ updatedAt: sync.updated_at || new Date().toISOString(),
+ source: sync.source || '',
+ warming: true,
+ });
+ return true;
+ } catch (_) {
+ return false;
+ } finally {
+ _setEmailSyncStatus({ warming: false });
+ }
+ }
+ export function _libCacheWriteBack() {
+ // After a local mutation that already updated state._libEmails
+ // (delete / archive / bulk), sync the change into the cache so the
+ // next reopen doesn't briefly show the pre-mutation state before the
+ // refetch wins. Skipped during search (results aren't the real list)
+ // and on the scheduled virtual folder.
+ if (state._libSearch) return;
+ if (state._libFolder === '__scheduled__') return;
+ const ck = _libCacheKey();
+ if (_libListCache.has(ck)) {
+ _libCachePut(ck, {
+ emails: state._libEmails.slice(),
+ total: state._libTotal,
+ sync: {
+ updated_at: _libSyncStatus.updatedAt || new Date().toISOString(),
+ source: _libSyncStatus.source || 'local',
+ },
+ });
+ }
+ }
+
+ // Expose the active account id to other modules (document.js uses this when sending).
+ // Simple global rather than cross-module import to keep coupling minimal.
+ export function _publishActiveAccount() {
+ try { window.__odysseusActiveEmailAccount = state._libAccountId || null; } catch (_) {}
+ try {
+ if (state._libAccountId) localStorage.setItem(_LIB_LAST_ACCOUNT_KEY, state._libAccountId);
+ } catch (_) {}
+ // Publish the active account's own address so reply-all can exclude us from
+ // the recipient list. This global was read in emailInbox.js but never set.
+ try {
+ const accts = state._libAccounts || [];
+ const active = accts.find(a => a && a.id === state._libAccountId)
+ || accts.find(a => a && a.is_default)
+ || accts[0];
+ window._myEmailAddress = (active && (active.from_address || active.imap_user)) || '';
+ // Also publish every configured address so reply-all can exclude all of
+ // the user's own mailboxes, not just the active one (multi-account users
+ // were getting their other addresses added to Cc).
+ const all = [];
+ for (const a of accts) {
+ if (a && a.from_address) all.push(a.from_address);
+ if (a && a.imap_user) all.push(a.imap_user);
+ }
+ window._myEmailAddresses = all;
+ } catch (_) {}
+ }
+
+ export function initEmailLibrary(config) {
+ state._docModule = config.documentModule;
+ const onEmailClick = config.onEmailClick;
+ state._onEmailClick = typeof onEmailClick === 'function' ? (options = {}) => {
+ const accountId = String(state._libAccountId || '');
+ const libraryFolder = String(state._libFolder || 'INBOX');
+ const messageFolder = String(options.email?.folder || libraryFolder);
+ const mailboxGeneration = _emailMailboxGeneration;
+ const mailboxContext = Object.freeze({
+ accountId,
+ libraryFolder,
+ messageFolder,
+ mailboxGeneration,
+ isCurrent: () => (
+ String(state._libAccountId || '') === accountId &&
+ String(state._libFolder || 'INBOX') === libraryFolder &&
+ _emailMailboxGeneration === mailboxGeneration
+ ),
+ });
+ return onEmailClick({ ...options, mailboxContext });
+ } : null;
+ }
+
+ export function isOpen() { return state._libOpen; }
+
++export async function openEmailFromTool(target, isCurrent = () => true) {
++ const response = await fetch(`${API_BASE}/api/email/accounts`, { credentials: 'same-origin' });
++ if (!response.ok) throw new Error('Could not load email accounts');
++ const data = await response.json();
++ const key = String(target.account || '').trim().toLowerCase();
++ const matches = (data.accounts || []).filter(account =>
++ [account.id, account.from_address, account.imap_user, account.name]
++ .some(value => value && String(value).trim().toLowerCase() === key));
++ if (matches.length !== 1) throw new Error('Could not uniquely identify the email account');
++ if (!/^\d+$/.test(String(target.uid || ''))) throw new Error('Invalid email message ID');
++ if (!isCurrent()) return;
++ openEmailLibrary({ uid: String(target.uid), folder: target.folder || 'INBOX', account_id: matches[0].id });
++}
++
+ export function openEmailLibrary(opts = {}) {
+ // Foreground email always wins: cancel a delayed/idle callback and abort the
+ // one optional request if it has already started. Generation checks make a
+ // non-abortable response harmless if it races this transition.
+ _cancelEmailPrewarm();
+ // Preserve a valid inbox snapshot while rebuilding the modal. Reader
+ // failures and mobile draft transitions can reopen this window before the
+ // next list request has completed; clearing the snapshot here made that
+ // normal recovery path look like an empty inbox.
+ const previousLibraryWasOpen = state._libOpen;
+ const previousAccountId = state._libAccountId || '';
+ const previousFolder = state._libFolder || 'INBOX';
+ const previousFilter = state._libFilter || 'all';
+ const previousSearch = state._libSearch || '';
+ const previousEmails = Array.isArray(state._libEmails) ? state._libEmails.slice() : [];
+
+ // Force-clean any stale DOM state from previous attempts
+ const existing = document.getElementById('email-lib-modal');
+ if (existing) existing.remove();
+ if (state._libEscHandler) {
+ document.removeEventListener('keydown', state._libEscHandler, true);
+ state._libEscHandler = null;
+ }
+ if (state._libInnerEscHandler) {
+ window.removeEventListener('keydown', state._libInnerEscHandler, true);
+ state._libInnerEscHandler = null;
+ }
+ _emailMailboxGeneration += 1;
+ state._libOpen = true;
+ // On mobile the sidebar overlays content — close it so the email view isn't
+ // opened behind it (same pattern as session-switch/delete).
+ if (window.innerWidth <= 768) {
+ const _sb = document.getElementById('sidebar');
+ if (_sb) _sb.classList.add('hidden');
+ const _bd = document.getElementById('sidebar-backdrop');
+ if (_bd) _bd.classList.remove('visible');
+ // Email was opened last → bring the email windows IN FRONT of any open doc
+ // (they alternate: whichever was opened last wins). The doc stays open
+ // behind it; reopening the doc flips it back on top.
+ document.body.classList.add('email-front');
+ }
+ state._libOffset = 0;
+ state._libSearch = '';
+ state._libSearchDraft = '';
+ // Reset select-mode on each open so the toolbar Select button
+ // never opens already-toggled-on after a previous session.
+ state._selectMode = false;
+ if (state._selectedUids) state._selectedUids.clear();
+ state._libSearchPills = [];
+ _libSuggestionCache = null;
+ state._libFilter = 'all';
+ state._libHasAttachments = false;
+ // Animate the very first card render with a domino cascade (same as the
+ // sidebar section-domino-in keyframe). Reset by _renderGrid after the
+ // animation is queued so subsequent filter/sort re-renders are instant.
+ state._libJustOpened = true;
+ if (Object.prototype.hasOwnProperty.call(opts, 'account_id')) {
+ state._libAccountId = opts.account_id || null;
+ _publishActiveAccount();
+ } else if (!state._libAccountId) {
+ const rememberedAccount = _rememberedEmailAccountId();
+ if (rememberedAccount) {
+ state._libAccountId = rememberedAccount;
+ _publishActiveAccount();
+ }
+ }
+ state._libViewInlineImages = _readEmailInlineImagesPreference();
+ if (opts.folder) state._libFolder = opts.folder;
+ state._libPendingExpandUid = opts.uid || null;
+
+ const sameMailbox = previousLibraryWasOpen
+ && previousAccountId === (state._libAccountId || '')
+ && previousFolder === (state._libFolder || 'INBOX')
+ && previousFilter === 'all'
+ && !previousSearch
+ && previousEmails.length > 0;
+ state._libEmails = sameMailbox ? previousEmails : [];
+ state._libTotal = sameMailbox ? Math.max(state._libTotal || 0, previousEmails.length) : 0;
+
+ const modal = document.createElement('div');
+ modal.className = 'modal';
+ modal.id = 'email-lib-modal';
+ modal.innerHTML = `
+ <div class="modal-content doclib-modal-content" style="width:min(720px, 92vw);background:var(--bg);">
+ <div class="modal-header">
+ <h4>
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;">
+ <rect x="2" y="4" width="20" height="16" rx="2"/>
+ <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/>
+ </svg>
+ <span id="email-lib-title-text">Email</span>
+ <span id="email-lib-auto-reply-status-dot" class="email-lib-auto-reply-status-dot" aria-label="Auto Reply active" title="Auto Reply active" style="display:none"></span>
+ <span id="email-lib-auto-reply-badge" class="email-lib-auto-reply-badge" role="button" tabindex="0" title="Auto Reply is active" style="display:none">Auto Reply</span>
+ <span id="email-lib-unread-badge" class="email-lib-unread-badge" role="button" tabindex="0" title="Show unread emails" style="display:none"></span>
+ <span id="email-lib-stats" class="memory-count" style="font-size:0.6em;opacity:0.6;font-weight:normal;margin-left:8px;position:relative;top:-2px"></span>
+ </h4>
+ <div class="email-lib-header-actions" style="display:flex;align-items:center;gap:8px;">
+ <button class="email-settings-header-back" id="email-settings-header-back" type="button" title="Back" aria-label="Back" style="display:none;">
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5"/><path d="M12 19l-7-7 7-7"/></svg>
+ <span>Back</span>
+ </button>
+ <button class="close-btn" id="email-lib-close">\u2716</button>
+ </div>
+ </div>
+ <div class="modal-body" style="display:flex;flex-direction:column;gap:10px;overflow:hidden;">
+ <div class="admin-card" style="flex:1;flex-direction:column;display:flex;overflow:hidden;">
+ <div class="email-accounts-row">
+ <div id="email-lib-accounts" style="display:flex;gap:4px;flex:1;min-width:0;"></div>
+ <button class="memory-toolbar-btn email-compose-jiggle" id="email-lib-compose-btn">
+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:-2px;margin-right:3px;"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>
+ New
+ </button>
+ </div>
+ <div class="memory-toolbar">
+ <div class="memory-category-filters">
+ <div class="email-folder-picker" id="email-folder-picker" style="flex:1;min-width:0;position:relative;">
+ <select class="memory-sort-select email-folder-select-control" id="email-lib-folder" style="display:none;">
+ <option value="INBOX">Inbox</option>
+ </select>
+ <button type="button" class="email-filter-btn email-folder-btn" id="email-folder-btn" aria-haspopup="listbox" aria-expanded="false">
+ <span class="email-filter-current"><span class="email-filter-icon email-folder-current-icon"></span><span class="email-filter-label email-folder-label">Inbox</span></span>
+ <svg class="email-filter-caret" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
+ </button>
+ <div class="email-filter-menu email-folder-menu" id="email-folder-menu" role="listbox" hidden></div>
+ </div>
+ <!-- Hidden native select kept as the source of truth — all
+ existing change handlers still fire via the custom picker
+ dispatching 'change' on it. -->
+ <select class="memory-sort-select" id="email-lib-filter" style="display:none;">
+ <option value="all">All</option>
+ <option value="unread">Unread</option>
+ <option value="favorites">Favorites</option>
+ <option value="undone">Undone</option>
+ <option value="reminders">Reminders</option>
+ <option value="unanswered">Unanswered</option>
+ <option value="pending_30d">Pending · 30d</option>
+ <option value="stale_30d">Stale · &gt;30d</option>
+ <optgroup label="Tags">
+ <option value="tag:urgent">Urgent</option>
+ <option value="tag:reply-soon">Reply soon</option>
+ <option value="tag:bills">Bills</option>
+ <option value="tag:receipt">Receipt</option>
+ <option value="tag:travel">Travel</option>
+ <option value="tag:spam">Spam</option>
+ </optgroup>
+ </select>
+ <div class="email-filter-picker" id="email-filter-picker" style="flex:1;min-width:0;position:relative;">
+ <button type="button" class="email-filter-btn" id="email-filter-btn" aria-haspopup="listbox" aria-expanded="false">
+ <span class="email-filter-current"><span class="email-filter-icon"></span><span class="email-filter-label">All</span></span>
+ <svg class="email-filter-caret" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
+ </button>
+ <div class="email-filter-menu" id="email-filter-menu" role="listbox" hidden></div>
+ </div>
+ <button class="memory-toolbar-btn email-filter-select-btn" id="email-lib-select-btn"><svg class="memory-select-btn-icon" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:3px;"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="3" fill="currentColor" stroke="none"/></svg>Select</button>
+ <button class="memory-toolbar-btn email-filter-refresh-btn" id="email-lib-refresh-btn" title="Refresh">
+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;"><path d="M1 4v6h6"/><path d="M23 20v-6h-6"/><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/></svg>
+ </button>
+ <button class="memory-toolbar-btn email-filter-settings-btn" id="email-lib-settings-btn" title="Email settings" aria-label="Email settings" aria-expanded="false">
+ ${_EMAIL_SETTINGS_ICON}
+ </button>
+ <button class="memory-toolbar-btn email-reminders-clear-btn hidden" id="email-reminders-clear-btn" title="Permanently delete Odysseus reminder emails">
+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;"><path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6l-1 14H6L5 6"/></svg>
+ Clear
+ </button>
+ </div>
+ <div class="email-search-row" style="display:flex;gap:6px;align-items:flex-start;">
+ <div class="email-search-wrap" style="position:relative;flex:1;min-width:140px;">
+ <div class="email-lib-chip-bar memory-search-input" id="email-lib-chip-bar" style="width:100%;padding-right:36px;padding-left:26px;display:flex;align-items:center;flex-wrap:nowrap;gap:4px;cursor:text;min-height:30px;position:relative;">
+ <svg class="email-lib-chip-bar-icon" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="position:absolute;left:8px;top:50%;transform:translateY(-50%);pointer-events:none;color:var(--accent, var(--red));"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35"/></svg>
+ <span id="email-lib-pills" style="display:flex;align-items:center;gap:4px;min-width:0;max-width:calc(100% - 70px);overflow-x:auto;overflow-y:hidden;scrollbar-width:none;flex:0 1 auto;"></span>
+ <input type="text" id="email-lib-search" placeholder="Search by name or text" autocomplete="off" style="flex:1;min-width:80px;border:0;outline:none;background:transparent;color:inherit;font:inherit;padding:0;position:relative;top:-1px;" />
+ <button type="button" class="memory-toolbar-btn email-search-options-btn" id="email-search-options-btn" title="Search options" aria-label="Search options" aria-expanded="false">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><circle cx="5" cy="12" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="19" cy="12" r="2"/></svg>
+ </button>
+ </div>
+ <div id="email-lib-suggest" style="display:none;position:absolute;top:calc(100% + 2px);left:0;right:0;z-index:60;background:var(--panel,var(--bg));border:1px solid var(--border);border-radius:6px;box-shadow:0 6px 18px rgba(0,0,0,0.25);max-height:240px;overflow-y:auto;"></div>
+ <div class="email-search-options-menu" id="email-search-options-menu" hidden>
+ <div class="email-search-options-title">Filter by...</div>
+ <button type="button" class="dropdown-item-compact" data-email-search-option="undone"><span class="dropdown-icon email-search-option-icon"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></span><span>Not done</span></button>
+ <button type="button" class="dropdown-item-compact hidden" data-email-search-option="reminders"><span class="dropdown-icon email-search-option-icon"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.268 21a2 2 0 0 0 3.464 0"/><path d="M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"/></svg></span><span>Reminders</span></button>
+ <button type="button" class="dropdown-item-compact" data-email-search-option="attachments"><span class="dropdown-icon email-search-option-icon"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 17.93 8.8l-8.59 8.57a2 2 0 0 1-2.83 2.83l8.49-8.48"/></svg></span><span>Attachments</span></button>
+ <button type="button" class="dropdown-item-compact" data-email-search-option="date"><span class="dropdown-icon email-search-option-icon"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="17" rx="2"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg></span><span>Date range</span></button>
+ <div class="email-search-date-panel" hidden>
+ <label><span>From</span><input type="date" id="email-search-date-from"></label>
+ <label><span>To</span><input type="date" id="email-search-date-to"></label>
+ <div class="email-search-date-actions"><button type="button" data-email-date-clear>Clear</button><button type="button" data-email-date-apply>Apply</button></div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div id="email-lib-bulk" class="memory-bulk-bar hidden" style="margin-bottom:5px;">
+ <label class="memory-bulk-check-all" style="position:relative;top:0px;" title="Select all emails currently loaded in this view"><input type="checkbox" id="email-lib-select-all"> All in view</label>
+ <span id="email-lib-selected-count" style="position:relative;top:1px;">0 Selected</span>
+ <button class="memory-toolbar-btn" id="email-lib-bulk-actions" style="position:relative;top:-2px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>Actions <span style="opacity:0.55;font-size:9px;">▼</span></button>
+ <button class="memory-toolbar-btn" id="email-lib-bulk-delete" style="position:relative;top:-2px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>Delete</button>
+ <button class="memory-toolbar-btn" id="email-lib-bulk-cancel" title="Cancel (Esc)" style="margin-left:4px;padding:3px 6px;position:relative;top:-2px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
+ </div>
+ <div id="email-lib-grid" class="doclib-grid"></div>
+ <div id="email-lib-sync-status" class="email-lib-sync-status" aria-live="polite"></div>
+ <div id="email-lib-settings-page" class="email-settings-page" hidden></div>
+ <button class="email-lib-fab" id="email-lib-fab" type="button" aria-label="New email">
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="4.5" width="19" height="15" rx="2.5"/><path d="M3 6.5l9 6 9-6"/></svg>
+ <span class="email-lib-fab-label">New</span>
+ </button>
+ </div>
+ </div>
+ </div>
+ `;
+
+ document.body.appendChild(modal);
+ modal.style.display = 'block';
+ _syncEmailAutoReplyTitle(!!state._libAutoReplyActive);
+ _refreshUnreadBadge({ syncAutoReplyTitle: true }).catch(() => {});
+ document.getElementById('email-lib-grid')?.scrollTo(0, 0);
+ modal.querySelector('.email-settings-body')?.scrollTo(0, 0);
+ _renderEmailSyncStatus();
+ if (_libSyncTicker) clearInterval(_libSyncTicker);
+ _libSyncTicker = setInterval(_renderEmailSyncStatus, 30000);
+ // Make modal background non-blocking so user can interact with rest of the app
+ modal.style.cssText += 'pointer-events:none;background:transparent;';
+
+ // Register so the chip carries the right label/icon. restoreFn left
+ // empty — just unminimizing the modal is enough; whatever email was
+ // expanded inside stays expanded.
+ try {
+ Modals.register('email-lib-modal', {
+ label: 'Email',
+ icon: 'M2 4h20v16H2zM22 7l-9.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7',
+ closeFn: () => {
+ const m = document.getElementById('email-lib-modal');
+ if (m) m.classList.add('hidden');
+ },
+ restoreFn: () => {
+ // Reopened last → bring the email windows in front of any open doc.
+ document.body.classList.add('email-front');
+ // Mobile: tapping the library chip chips down any open email
+ // reader so the library is the only visible window. Pairs with
+ // the per-reader restoreFn that chips the library down when a
+ // reader is brought up.
+ if (window.innerWidth <= 768) {
+ document.querySelectorAll('.modal[id^="email-reader-"]').forEach(other => {
+ try {
+ if (Modals.isRegistered(other.id) && !Modals.isMinimized(other.id)) {
+ Modals.minimize(other.id);
+ }
+ } catch {}
+ });
+ }
+ },
+ });
+ } catch (_) {}
+ _wireUnreadTabClick();
+ const unreadBadge = document.getElementById('email-lib-unread-badge');
+ unreadBadge?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ if (unreadBadge.dataset.mode === 'away') {
+ _openGlobalEmailSettings('auto-reply');
+ return;
+ }
+ _toggleUnreadEmails();
+ });
+ unreadBadge?.addEventListener('keydown', (e) => {
+ if (e.key !== 'Enter' && e.key !== ' ') return;
+ e.preventDefault();
+ if (unreadBadge.dataset.mode === 'away') {
+ _openGlobalEmailSettings('auto-reply');
+ return;
+ }
+ _toggleUnreadEmails();
+ });
+ const autoReplyBadge = document.getElementById('email-lib-auto-reply-badge');
+ const openAutoReplySettings = (e) => {
+ e.stopPropagation();
+ _openGlobalEmailSettings('auto-reply');
+ };
+ autoReplyBadge?.addEventListener('click', openAutoReplySettings);
+ autoReplyBadge?.addEventListener('keydown', (e) => {
+ if (e.key !== 'Enter' && e.key !== ' ') return;
+ e.preventDefault();
+ openAutoReplySettings(e);
+ });
+ const content = modal.querySelector('.modal-content');
+ if (content) {
+ const isMobile = window.innerWidth <= 768;
+ if (isMobile) {
+ // Bottom-anchored sheet on mobile
+ content.style.position = 'fixed';
+ content.style.pointerEvents = 'auto';
+ content.style.left = '0';
+ content.style.right = '0';
+ content.style.bottom = '0';
+ content.style.top = 'auto';
+ content.style.transform = 'none';
+ } else {
+ // Center on screen using fixed positioning + computed offsets
+ content.style.position = 'fixed';
+ content.style.pointerEvents = 'auto';
+ // Wait a frame for size to stabilize, then center. Center against the
+ // modal's max-height (85vh) — NOT the live offsetHeight, which is tiny
+ // while the email list is still loading and put the window ~1/3 down
+ // (then it grew off the bottom as the list filled in).
+ requestAnimationFrame(() => {
+ const w = content.offsetWidth;
+ const refH = window.innerHeight * 0.85;
+ content.style.left = Math.max(20, (window.innerWidth - w) / 2) + 'px';
+ content.style.top = Math.max(20, (window.innerHeight - refH) / 2) + 'px';
+ content.style.transform = 'none';
+ });
+ }
+ }
+
+ // Wire events
+ document.getElementById('email-lib-close').addEventListener('click', closeEmailLibrary);
+ document.getElementById('email-settings-header-back')?.addEventListener('click', _hideEmailSettingsPage);
+
+ // Clicking the modal header (anywhere except buttons/inputs) collapses
+ // any currently-expanded email card and returns to the inbox list view.
+ // Acts as a "back to email menu" gesture.
+ const libHeader = modal.querySelector('.modal-header');
+ if (libHeader) {
+ libHeader.style.cursor = 'pointer';
+ libHeader.addEventListener('click', (ev) => {
+ if (ev.target.closest('button, input, select, a')) return;
+ const g = document.getElementById('email-lib-grid');
+ if (!g) return;
+ g.querySelectorAll('.doclib-card.doclib-card-expanded').forEach(c => {
+ const uid = c.dataset.uid;
+ const liveEm = state._libEmails.find(e => String(e.uid) === String(uid));
+ if (liveEm) _toggleCardPreview(c, liveEm);
+ });
+ });
+ }
+
+ // Drag-to-top edge → snap to fullscreen (Aero Snap). Dragging away from
+ // the top edge while fullscreen unsnaps back to a centered window.
+ _makeDraggable(content, modal, 'email-lib-fullscreen');
+
+ document.getElementById('email-lib-folder').addEventListener('change', (e) => {
+ state._libFolder = _resolveEmailFolderAlias(e.target.value);
+ if (e.target.value !== state._libFolder) e.target.value = state._libFolder;
+ _renderFolderPicker();
+ _renderSearchPills();
+ _loadEmailsFresh();
+ });
+ document.getElementById('email-lib-filter').addEventListener('change', (e) => {
+ state._libFilter = e.target.value;
+ _syncUnreadWindowGlow();
+ _syncReminderClearButton();
+ _renderSearchPills();
+ _loadEmailsFresh();
+ _syncSearchOptionsMenu();
+ // Mirror the picker label/icon.
+ _renderFilterPickerCurrent();
+ });
+ _initFilterPicker();
+ _initFolderPicker();
+ const searchOptionsBtn = document.getElementById('email-search-options-btn');
+ const searchOptionsMenu = document.getElementById('email-search-options-menu');
+ searchOptionsBtn?.addEventListener('click', (ev) => {
+ ev.preventDefault();
+ ev.stopPropagation();
+ const shouldOpen = !!searchOptionsMenu?.hidden;
+ if (searchOptionsMenu) searchOptionsMenu.hidden = !shouldOpen;
+ searchOptionsBtn.setAttribute('aria-expanded', String(shouldOpen));
+ _syncSearchOptionsMenu();
+ });
+ searchOptionsMenu?.addEventListener('click', (ev) => {
+ const item = ev.target.closest('[data-email-search-option]');
+ if (!item) return;
+ ev.preventDefault();
+ ev.stopPropagation();
+ const opt = item.dataset.emailSearchOption;
+ if (opt === 'attachments') _toggleEmailAttachmentFilter();
+ else if (opt === 'undone' || opt === 'reminders') _setEmailListFilter(opt);
+ else if (opt === 'date') {
+ const panel = searchOptionsMenu.querySelector('.email-search-date-panel');
+ panel.hidden = !panel.hidden;
+ const from = panel.querySelector('#email-search-date-from');
+ const to = panel.querySelector('#email-search-date-to');
+ if (from) from.value = state._libDateFrom || '';
+ if (to) to.value = state._libDateTo || '';
+ }
+ searchOptionsMenu.hidden = false;
+ searchOptionsBtn?.setAttribute('aria-expanded', 'true');
+ });
+ searchOptionsMenu?.querySelector('[data-email-date-apply]')?.addEventListener('click', (ev) => {
+ ev.preventDefault(); ev.stopPropagation();
+ const nextFrom = searchOptionsMenu.querySelector('#email-search-date-from')?.value || '';
+ const nextTo = searchOptionsMenu.querySelector('#email-search-date-to')?.value || '';
+ if (nextFrom && nextTo && nextFrom > nextTo) {
+ showToast('From date must be before To date');
+ return;
+ }
+ state._libDateFrom = nextFrom;
+ state._libDateTo = nextTo;
+ _syncSearchOptionsMenu();
+ _renderSearchPills();
+ _loadEmailsFresh({ useCache: false });
+ searchOptionsMenu.querySelector('.email-search-date-panel').hidden = true;
+ });
+ searchOptionsMenu?.querySelector('[data-email-date-clear]')?.addEventListener('click', (ev) => {
+ ev.preventDefault(); ev.stopPropagation();
+ state._libDateFrom = '';
+ state._libDateTo = '';
+ _syncSearchOptionsMenu();
+ _renderSearchPills();
+ _loadEmailsFresh({ useCache: false });
+ searchOptionsMenu.querySelector('.email-search-date-panel').hidden = true;
+ });
+ if (state._emailSearchOptionsDismiss) {
+ document.removeEventListener('click', state._emailSearchOptionsDismiss);
+ }
+ state._emailSearchOptionsDismiss = (ev) => {
+ if (!searchOptionsMenu || searchOptionsMenu.hidden) return;
+ if (ev.target.closest('#email-search-options-menu, #email-search-options-btn')) return;
+ searchOptionsMenu.hidden = true;
+ searchOptionsBtn?.setAttribute('aria-expanded', 'false');
+ };
+ document.addEventListener('click', state._emailSearchOptionsDismiss);
+ _syncSearchOptionsMenu();
+ document.getElementById('email-reminders-clear-btn')?.addEventListener('click', async () => {
+ const ok = await styledConfirm('Permanently delete all Odysseus reminder emails?', {
+ confirmText: 'Delete',
+ cancelText: 'Cancel',
+ danger: true,
+ });
+ if (!ok) return;
+ try {
+ const res = await fetch(`${API_BASE}/api/email/odysseus/reminders?permanent=1${_acct()}`, {
+ method: 'DELETE',
+ credentials: 'same-origin',
+ });
+ const data = await res.json().catch(() => ({}));
+ showToast(`Deleted ${data.deleted || 0} reminder email${(data.deleted || 0) === 1 ? '' : 's'}`);
+ if ((data.deleted || 0) > 0) {
+ const visibleUids = Array.from(document.querySelectorAll('#email-lib-grid .doclib-card[data-uid]'))
+ .map(card => card.dataset.uid)
+ .filter(Boolean);
+ await _animateEmailCardRemoval(visibleUids);
+ }
+ state._libFilter = 'all';
+ const filterEl = document.getElementById('email-lib-filter');
+ if (filterEl) filterEl.value = 'all';
+ _renderFilterPickerCurrent();
+ _syncSearchOptionsMenu();
+ _syncReminderClearButton();
+ _renderSearchPills();
+ _loadEmailsFresh();
+ } catch (err) {
+ console.error(err);
+ showToast('Failed to clear reminder emails');
+ }
+ });
+ // The old "sort" dropdown (Latest / Unread first / Favorites first) was merged
+ // into the filter dropdown above — "Favorites" is now a filter (server-side
+ // \Flagged search). _libSort stays at its 'recent' default so the grid keeps
+ // the API's newest-first order.
+
+ // Chip-bar search: pills represent contact + free-text filters; the live
+ // input below drives the autocomplete dropdown. Old behavior — instant
+ // local filter on every keystroke + server-side IMAP search after 350ms
+ // — is replaced by deterministic local filtering against the snapshot.
+ _initEmailSearchChipBar();
+
+ document.getElementById('email-lib-refresh-btn').addEventListener('click', async () => {
+ await _refreshEmailLibraryFromUi(document.getElementById('email-lib-refresh-btn'));
+ });
+ _initMobileEmailPullRefresh();
+ document.getElementById('email-lib-settings-btn')?.addEventListener('click', (ev) => {
+ ev.preventDefault();
+ ev.stopPropagation();
+ _openGlobalEmailSettings('show-tags');
+ });
+
+
+ const _composeNew = () => {
+ // Desktop: keep Email open when there is enough room for it plus the
+ // compose/document pane. Mobile still tabs down so the doc owns the screen.
+ if (_prepareEmailWindowForDocument(document.getElementById('email-lib-modal'))) {
+ if (!Modals.minimize('email-lib-modal')) closeEmailLibrary();
+ }
+ if (state._onEmailClick) state._onEmailClick({ compose: true });
+ if (document.body.classList.contains('email-doc-split-active')) {
+ _scheduleEmailDocumentSplitMeasure(document.getElementById('email-lib-modal'));
+ }
+ };
+ document.getElementById('email-lib-compose-btn').addEventListener('click', _composeNew);
+
+ // Mobile FAB: same action as the (desktop) New button, plus collapse-to-icon
+ // while the list scrolls and spring back out to "New" when scrolling stops.
+ const _fab = document.getElementById('email-lib-fab');
+ if (_fab) {
+ _fab.addEventListener('click', _composeNew);
+ const _grid = document.getElementById('email-lib-grid');
+ if (_grid) {
+ let _fabIdle = null;
+ _grid.addEventListener('scroll', () => {
+ _fab.classList.add('collapsed');
+ clearTimeout(_fabIdle);
+ _fabIdle = setTimeout(() => _fab.classList.remove('collapsed'), 280);
+ _positionFab(); // Firefox's toolbar shows/hides on scroll
+ }, { passive: true });
+ }
+
+ // Keep the FAB above the browser's bottom toolbar. env(safe-area-inset)
+ // doesn't cover Firefox-for-Android's URL bar, and its 100dvh handling is
+ // unreliable, so measure how far the panel extends below the *visible*
+ // (visualViewport) area and lift the button by that much.
+ function _positionFab() {
+ if (!_fab.isConnected) { // modal was rebuilt/closed — stop listening
+ window.visualViewport?.removeEventListener('resize', _positionFab);
+ window.visualViewport?.removeEventListener('scroll', _positionFab);
+ window.removeEventListener('resize', _positionFab);
+ return;
+ }
+ const card = _fab.parentElement; // .admin-card (positioned)
+ const vh = window.visualViewport ? window.visualViewport.height : window.innerHeight;
+ const overflowBelow = card ? Math.max(0, Math.round(card.getBoundingClientRect().bottom - vh)) : 0;
+ _fab.style.bottom = `calc(18px + env(safe-area-inset-bottom, 0px) + ${overflowBelow}px)`;
+ }
+ if (window.visualViewport) {
+ window.visualViewport.addEventListener('resize', _positionFab);
+ window.visualViewport.addEventListener('scroll', _positionFab);
+ }
+ window.addEventListener('resize', _positionFab);
+ // Run after layout settles (modal opens with an animation).
+ requestAnimationFrame(() => requestAnimationFrame(_positionFab));
+ setTimeout(_positionFab, 300);
+
+ // Reveal the FAB with a scale-from-center pop only AFTER the email list has
+ // rendered (the window is "fully loaded") — position it first while it's
+ // still invisible so it never flashes at the top and slides down.
+ let _revealed = false;
+ const _revealFab = () => {
+ if (_revealed || !_fab.isConnected) return;
+ _revealed = true;
+ _positionFab();
+ // The FAB is an absolute child of .modal-content, which slides up on open
+ // (sheet-enter). Wait until that entrance finishes before popping the FAB
+ // in, otherwise it rides the slide ("swipes down with the window").
+ const content = _fab.closest('.modal-content');
+ const pop = () => { _positionFab(); requestAnimationFrame(() => _fab.classList.add('fab-revealed')); };
+ if (!content || content.classList.contains('sheet-ready')) {
+ pop();
+ } else {
+ let done = false;
+ const onEnd = () => {
+ if (done) return; done = true;
+ content.removeEventListener('animationend', onEnd);
+ pop();
+ };
+ content.addEventListener('animationend', onEnd);
+ setTimeout(onEnd, 450); // fallback if animationend doesn't fire
+ }
+ };
+ if (_grid) {
+ if (_grid.children.length) {
+ _revealFab();
+ } else {
+ const _gobs = new MutationObserver(() => {
+ if (_grid.children.length) { _gobs.disconnect(); _revealFab(); }
+ });
+ _gobs.observe(_grid, { childList: true });
+ // Safety net — never leave the FAB hidden if the list stays empty.
+ setTimeout(() => { _gobs.disconnect(); _revealFab(); }, 1600);
+ }
+ } else {
+ setTimeout(_revealFab, 400);
+ }
+ }
+
+ // Select mode toggle — icon + label swap matches the brain memories
+ // select button (dot+Select ↔ X+Cancel).
+ const _SELECT_BTN_DOT_SVG = '<svg class="memory-select-btn-icon" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:3px;"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="3" fill="currentColor" stroke="none"/></svg>';
+ const _SELECT_BTN_X_SVG = '<svg class="memory-select-btn-icon" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" style="vertical-align:-2px;margin-right:3px;"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
+ const _setSelectBtnState = (on) => {
+ const btn = document.getElementById('email-lib-select-btn');
+ if (!btn) return;
+ if (on) { btn.classList.add('active'); btn.innerHTML = _SELECT_BTN_X_SVG + 'Cancel'; }
+ else { btn.classList.remove('active'); btn.innerHTML = _SELECT_BTN_DOT_SVG + 'Select'; }
+ };
+ document.getElementById('email-lib-select-btn').addEventListener('click', () => {
+ state._selectMode = !state._selectMode;
+ state._selectedUids.clear();
+ _setSelectBtnState(state._selectMode);
+ _updateBulkBar();
+ _renderGrid();
+ });
+ document.getElementById('email-lib-select-all').addEventListener('change', (e) => {
+ if (e.target.checked) {
+ state._libEmails.forEach(em => state._selectedUids.add(em.uid));
+ } else {
+ state._selectedUids.clear();
+ }
+ _updateBulkBar();
+ _renderGrid();
+ });
+
+ // Bulk cancel — wired with the same teardown a fresh Cancel-via-toggle does.
+ // Lets the global Esc handler (keyboard-shortcuts.js) close select mode by
+ // clicking the visible [id$="-bulk-cancel"] button.
+ document.getElementById('email-lib-bulk-cancel')?.addEventListener('click', () => {
+ state._selectMode = false;
+ state._selectedUids.clear();
+ _setSelectBtnState(false);
+ _updateBulkBar();
+ _renderGrid();
+ });
+
+ // Bulk actions
+ document.getElementById('email-lib-bulk-actions').addEventListener('click', (e) => {
+ e.stopPropagation();
+ if (state._selectedUids.size === 0) {
+ showToast('Select emails first');
+ return;
+ }
+ _showBulkActionsMenu(e.currentTarget);
+ });
+ document.getElementById('email-lib-bulk-delete')?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ if (state._selectedUids.size === 0) {
+ showToast('Select emails first');
+ return;
+ }
+ _bulkAction('delete');
+ });
+
+ const selectExpandedEmailText = () => {
+ const expanded = document.querySelector('#email-lib-modal .doclib-card.doclib-card-expanded');
+ const reader = expanded?.querySelector('.email-card-reader') || expanded;
+ return _selectEmailReaderContents(reader);
+ };
+
+ // ESC to close + Arrow nav + Delete on the selected / currently-expanded email.
+ state._libEscHandler = (e) => {
+ const modal = document.getElementById('email-lib-modal');
+ if (!modal || modal.classList.contains('hidden')) return;
+ if ((e.ctrlKey || e.metaKey) && String(e.key || '').toLowerCase() === 'a') {
+ const t = e.target;
+ if (_isEmailTypingTarget(t)) return;
+ if (selectExpandedEmailText()) {
+ e.preventDefault();
+ e.stopPropagation();
+ e.stopImmediatePropagation?.();
+ }
+ return;
+ }
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ e.stopImmediatePropagation?.();
+ if (modal.classList.contains('email-settings-mode')) {
+ _hideEmailSettingsPage();
+ return;
+ }
+ if (state._selectMode) {
+ state._selectMode = false;
+ state._selectedUids.clear();
+ _setSelectBtnState(false);
+ _updateBulkBar();
+ _renderGrid();
+ return;
+ }
+ const expanded = modal.querySelector('.doclib-card.doclib-card-expanded');
+ if (expanded) {
+ _exitEmailReaderModeForList();
+ expanded.focus?.({ preventScroll: true });
+ return;
+ }
+ if (modal.classList.contains('email-reading')) {
+ _exitEmailReaderModeForList();
+ return;
+ }
+ closeEmailLibrary();
+ return;
+ }
+ // Don't hijack arrows / delete while the user is typing somewhere.
+ const t = e.target;
+ if (_isEmailTypingTarget(t)) return;
+ const isDeleteKey = e.key === 'Delete' || e.key === 'Backspace';
+ if (isDeleteKey && state._selectMode && state._selectedUids.size > 0) {
+ e.preventDefault();
+ _bulkAction('delete');
+ return;
+ }
+ const expanded = document.querySelector('#email-lib-modal .doclib-card.doclib-card-expanded');
+ if (!expanded) return;
+ if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
+ const dir = e.key === 'ArrowLeft' ? '-1' : '1';
+ const btn = expanded.querySelector(`.email-card-nav-btn[data-nav-dir="${dir}"]`);
+ if (btn) { e.preventDefault(); btn.click(); }
+ } else if (isDeleteKey) {
+ const em = state._libEmails.find(x => String(x.uid) === String(expanded.dataset.uid));
+ if (em) {
+ e.preventDefault();
+ _deleteEmailAndAdvance(em, expanded);
+ }
+ }
+ };
+ document.addEventListener('keydown', state._libEscHandler, true);
+
+ // The global UI Escape arbiter is a document-level capture listener and can
+ // close the hovered modal before this library handler sees the event. Give
+ // email's inner layers a window-level first pass so Escape closes exactly
+ // one inner state before the library itself is dismissed.
+ state._libInnerEscHandler = (e) => {
+ if (e.key !== 'Escape') return;
+ const modal = document.getElementById('email-lib-modal');
+ if (!modal || modal.classList.contains('hidden')) return;
+ if (dismissTopMenu()) {
+ e.preventDefault();
+ e.stopPropagation();
+ e.stopImmediatePropagation?.();
+ return;
+ }
+ if (modal.classList.contains('email-settings-mode')) {
+ e.preventDefault();
+ e.stopPropagation();
+ e.stopImmediatePropagation?.();
+ _hideEmailSettingsPage();
+ return;
+ }
+ if (state._selectMode) {
+ e.preventDefault();
+ e.stopPropagation();
+ e.stopImmediatePropagation?.();
+ state._selectMode = false;
+ state._selectedUids.clear();
+ _setSelectBtnState(false);
+ _updateBulkBar();
+ _renderGrid();
+ return;
+ }
+ const expanded = modal.querySelector('.doclib-card.doclib-card-expanded');
+ if (expanded || modal.classList.contains('email-reading')) {
+ e.preventDefault();
+ e.stopPropagation();
+ e.stopImmediatePropagation?.();
+ _exitEmailReaderModeForList();
+ }
+ };
+ window.addEventListener('keydown', state._libInnerEscHandler, true);
+
+ const grid = document.getElementById('email-lib-grid');
+ if (grid && !grid.children.length) _renderEmailLoading(grid);
+ if (Array.isArray(state._libAccounts) && state._libAccounts.length) {
+ _renderAccountsStrip();
+ } else {
+ _renderAccountsLoading();
+ }
+ const fastAccountAtOpen = state._libAccountId || '';
+ if (fastAccountAtOpen) {
+ _loadEmails({ useCache: true });
+ }
+ // If we already know the previous/default account, paint that inbox first
+ // from the durable index and validate accounts in parallel. Cold refreshes
+ // otherwise waited on `/accounts` before even trying the cheap indexed list.
+ (async () => {
+ await _loadAccounts();
+ _refreshUnreadBadge().catch(() => {});
+ _loadFolders();
+ _loadEmailReminderBellVisibility();
+ if (!fastAccountAtOpen || fastAccountAtOpen !== (state._libAccountId || '')) {
+ _loadEmails({ useCache: true });
+ }
+ })();
+ }
+
+ export async function _loadAccounts({ force = false } = {}) {
+ const hasCachedAccounts = Array.isArray(state._libAccounts) && state._libAccounts.length;
+ const accountsFresh = _libAccountsLoadedAt && (Date.now() - _libAccountsLoadedAt) < _LIB_ACCOUNTS_TTL_MS;
+ if (!force && hasCachedAccounts && accountsFresh) {
+ if (!state._libAccountId) {
+ const def = state._libAccounts.find(a => a.is_default) || state._libAccounts[0];
+ state._libAccountId = def?.id || null;
+ _publishActiveAccount();
+ }
+ state._libViewInlineImages = _readEmailInlineImagesPreference();
+ _renderAccountsStrip();
+ return;
+ }
+ try {
+ const r = await fetch(`${API_BASE}/api/email/accounts`, { credentials: 'same-origin' });
+ if (!r.ok) return;
+ const d = await r.json();
+ state._libAccounts = d.accounts || [];
+ _libAccountsLoadedAt = Date.now();
+ } catch (_) {
+ if (!hasCachedAccounts) state._libAccounts = [];
+ }
+ // The 'Default' chip is gone — pick an explicit account so the email
+ // list and any per-email actions (open in new tab, mark read, etc.)
+ // always carry an account_id and can't desync from the server's
+ // is_default state.
+ if (state._libAccountId && state._libAccounts.length && !state._libAccounts.some(a => a && a.id === state._libAccountId)) {
+ state._libAccountId = null;
+ }
+ if (!state._libAccountId && state._libAccounts.length) {
+ const def = state._libAccounts.find(a => a.is_default) || state._libAccounts[0];
+ state._libAccountId = def.id;
+ _publishActiveAccount();
+ }
+ state._libViewInlineImages = _readEmailInlineImagesPreference();
+ _renderAccountsStrip();
+ _refreshAccountUnreadHighlights().catch(() => {});
+ }
+
+ export function _renderAccountsStrip() {
+ const strip = document.getElementById('email-lib-accounts');
+ if (!strip) return;
+ strip.style.display = 'flex';
+ const esc = s => String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
+ // The 'Default' chip caused desync bugs (changing the server-side
+ // default via the dot while still on the cached 'default' view would
+ // open the wrong account's emails). Each account renders as its own
+ // chip; the active one is selected explicitly via _loadAccounts.
+ let html = '';
+ // Keep the server default first; unread status remains the only dot on a
+ // mailbox chip, while the explicit default control lives in Settings.
+ const accounts = (state._libAccounts || []).slice().sort((a, b) => Number(!!b.is_default) - Number(!!a.is_default));
+ const nameCounts = new Map();
+ accounts.forEach(a => {
+ const name = String(a.name || '').trim();
+ if (name) nameCounts.set(name, (nameCounts.get(name) || 0) + 1);
+ });
+ for (const a of accounts) {
+ const active = state._libAccountId === a.id ? ' active' : '';
+ const accountAddress = a.from_address || a.imap_user || '';
+ const accountName = String(a.name || '').trim();
+ const accountLabel = accountName && nameCounts.get(accountName) > 1 && accountAddress
+ ? `${accountName} · ${accountAddress}`
+ : (accountName || accountAddress || 'account');
+ const unread = _accountUnreadState.get(String(a.id || '')) || {};
+ const unreadCount = Number(unread.unreadCount || 0);
+ const unreadClass = unreadCount > 0 ? ' email-account-has-unread' : '';
+ const unreadTitle = unreadCount > 0 ? ` · ${unreadCount > 999 ? '999+' : unreadCount} unread` : '';
+ const away = state._libAutoReplyActive && state._libAccountId === a.id;
+ const label = away ? (accountAddress || accountLabel) : accountLabel;
+ const awayLabel = away ? '<span class="email-account-away-label">(AWAY)</span>' : '';
+ const unreadDot = unreadCount > 0
+ ? `<span class="email-account-unread-dot" aria-hidden="true"></span>`
+ : '';
+ html += `<span class="gallery-chip-wrap" style="position:relative;display:inline-flex;align-items:center;">`
+ + `<button class="memory-toolbar-btn gallery-chip email-account-chip${active}${unreadClass}" data-acc-id="${esc(a.id)}" title="${esc(a.from_address || a.imap_user || '')}${away ? ' · auto reply active' : ''}${unreadTitle}" style="padding-right:24px;">${unreadDot}${awayLabel}<span class="email-account-chip-label">${esc(label)}</span>${unreadCount > 0 ? `<span class="email-account-unread-count">${unreadCount > 999 ? '999+' : unreadCount}</span>` : ''}</button>`
+ + `</span>`;
+ }
+ strip.innerHTML = html;
+ strip.querySelectorAll('button[data-acc-id]').forEach(btn => {
+ btn.addEventListener('click', async () => {
+ const nextAccountId = btn.dataset.accId || null;
+ if ((state._libAccountId || null) === nextAccountId) return;
+ // Tag filters belong to the current mailbox account. Keeping one while
+ // switching accounts can show an empty or misleading result set.
+ if (String(state._libFilter || '').startsWith('tag:')) {
+ state._libFilter = 'all';
+ const filterEl = document.getElementById('email-lib-filter');
+ if (filterEl) filterEl.value = 'all';
+ }
+ state._libSearchPills = (state._libSearchPills || []).filter((pill) => {
+ const value = String(pill?.value || pill?.text || '');
+ return pill?.type !== 'filter' || !value.includes('tag:');
+ });
+ state._libAccountId = nextAccountId;
+ state._libViewInlineImages = _readEmailInlineImagesPreference(nextAccountId);
+ _publishActiveAccount();
+ _renderAccountsStrip();
+ _renderFilterPickerCurrent();
+ _syncSearchOptionsMenu();
+ _renderSearchPills();
+ _loadEmailsFresh({ force: true, useCache: true, refreshAfterCache: true, showRefreshSpinner: true });
+ _loadFolders({ resetMissing: true }).catch(() => {});
+ _refreshUnreadBadge({ syncAutoReplyTitle: true }).catch(() => {});
+ _refreshAccountUnreadHighlights().catch(() => {});
+ });
+ });
+ // Idempotent — wire wheel + grab-drag scroll once per strip element.
+ if (!strip._scrollWired) {
+ strip._scrollWired = true;
+ // Vertical wheel → horizontal scroll. Only intercept when there's
+ // actually horizontal overflow to scroll through, otherwise let the
+ // page do its normal vertical scroll.
+ strip.addEventListener('wheel', (e) => {
+ if (strip.scrollWidth <= strip.clientWidth) return;
+ if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return;
+ e.preventDefault();
+ strip.scrollLeft += e.deltaY;
+ }, { passive: false });
+ // Click-and-drag scroll. Track mousedown, then mousemove deltas
+ // bump scrollLeft. Cancel a chip click if the user actually dragged
+ // more than a few pixels.
+ let dragging = false;
+ let startX = 0;
+ let startScroll = 0;
+ let moved = 0;
+ strip.style.cursor = 'grab';
+ strip.addEventListener('mousedown', (e) => {
+ if (e.button !== 0) return;
+ dragging = true;
+ moved = 0;
+ startX = e.pageX;
+ startScroll = strip.scrollLeft;
+ strip.style.cursor = 'grabbing';
+ strip.style.userSelect = 'none';
+ });
+ window.addEventListener('mousemove', (e) => {
+ if (!dragging) return;
+ const dx = e.pageX - startX;
+ moved = Math.max(moved, Math.abs(dx));
+ strip.scrollLeft = startScroll - dx;
+ });
+ window.addEventListener('mouseup', () => {
+ if (!dragging) return;
+ dragging = false;
+ strip.style.cursor = 'grab';
+ strip.style.userSelect = '';
+ });
+ // Swallow chip clicks fired after a real drag — the user meant to scroll,
+ // not select.
+ strip.addEventListener('click', (e) => {
+ if (moved > 5) { e.stopPropagation(); e.preventDefault(); moved = 0; }
+ }, true);
+ }
+ _publishActiveAccount();
+ }
+
+ async function _refreshAccountUnreadHighlights() {
+ const accounts = Array.isArray(state._libAccounts) ? state._libAccounts.slice() : [];
+ if (!accounts.length) return;
+ const seq = ++_accountUnreadSeq;
+ const next = new Map();
+ await Promise.all(accounts.map(async (a) => {
+ const id = String(a && a.id || '');
+ if (!id) return;
+ try {
+ const res = await fetch(emailApiUrl('/api/email/unread-state', {
+ folder: 'INBOX',
+ account_id: id,
+ }), { credentials: 'same-origin' });
+ if (!res.ok) return;
+ const data = await res.json().catch(() => ({}));
+ next.set(id, {
+ unreadCount: Number(data.unread_count || 0),
+ maxUid: Number(data.max_uid || 0),
+ });
+ } catch (_) {}
+ }));
+ if (seq !== _accountUnreadSeq) return;
+ _accountUnreadState = next;
+ _renderAccountsStrip();
+ }
+
+ export async function mountEmailSettings(host) {
+ if (!host) return;
+ host.classList.add('email-settings-page');
+ const head = host.querySelector('.email-settings-page-head');
+ const body = host.querySelector('.email-settings-body');
+ const defaultCard = document.getElementById('settings-email-default-card');
+ const defaultHost = document.getElementById('settings-email-default-host');
+ if (!head || !body) return;
+
+ const render = async () => {
+ body.innerHTML = _emailSettingsLoadingHtml();
+ try {
+ await _loadAccounts().catch(() => {});
+ const multipleAccounts = (state._libAccounts || []).filter(a => a && a.enabled !== false).length > 1;
+ if (defaultCard) defaultCard.hidden = !multipleAccounts;
+ if (defaultHost) defaultHost.innerHTML = multipleAccounts ? _emailSettingsAccountSelectHtml() : '';
+ head.innerHTML = '';
+ const [cfg, writingStyle] = await Promise.all([
+ _fetchEmailSettingsConfig(),
+ _fetchEmailWritingStyle().catch(() => ''),
+ ]);
+ body.innerHTML = _emailWritingStyleHtml(writingStyle)
+ + _emailDisplaySettingsHtml(cfg)
+ + _emailCleanupSettingsHtml()
+ + _emailSettingsFormHtml(cfg);
+ state._libAutoReplyActive = _isAutoReplyActiveForCurrentAccount(cfg);
+ state._libAutoReplyDraftActive = null;
+ _syncEmailAutoReplyTitle(state._libAutoReplyActive);
+ _syncAutoReplyCalendarEvent(cfg).catch((err) => console.warn('Failed to reconcile auto-reply calendar event:', err));
+ const focus = host.dataset.emailSettingsFocus;
+ if (focus) {
+ const section = focus === 'show-tags'
+ ? body.querySelector('.email-settings-display-section')
+ : body.querySelector(`.email-settings-${focus}-section`);
+ if (section) {
+ section.scrollIntoView?.({ block: 'nearest' });
+ }
+ delete host.dataset.emailSettingsFocus;
+ }
+ _bindEmailSettingsPageControls(host, defaultHost);
+ defaultHost?.querySelector('.email-settings-default')?.addEventListener('click', async (ev) => {
+ ev.stopPropagation();
+ const acctId = ev.currentTarget.dataset.emailDefaultId;
+ const account = (state._libAccounts || []).find(a => a && a.id === acctId);
+ if (!acctId || account?.is_default) return;
+ try {
+ const response = await fetch(`${API_BASE}/api/email/accounts/${encodeURIComponent(acctId)}/set-default`, {
+ method: 'POST', credentials: 'same-origin',
+ });
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ for (const a of state._libAccounts) a.is_default = a.id === acctId;
+ _syncEmailSettingsAccountPicker(defaultHost);
+ _renderAccountsStrip();
+ } catch (err) {
+ console.error('Set default account failed:', err);
+ }
+ });
+ defaultHost?.querySelector('.email-settings-default')?.addEventListener('keydown', (ev) => {
+ if (ev.key !== 'Enter' && ev.key !== ' ') return;
+ ev.preventDefault();
+ ev.currentTarget.click();
+ });
+ defaultHost?.querySelector('#email-settings-account-select')?.addEventListener('change', async (ev) => {
+ state._libAccountId = ev.currentTarget.value || null;
+ _publishActiveAccount();
+ _renderAccountsStrip();
+ await render();
+ });
+ } catch (_) {
+ body.innerHTML = '<div class="email-settings-error">Could not load settings.</div>';
+ }
+ };
+ await render();
+ }
+
+ export async function openEmailLibrarySettings() {
+ openEmailLibrary();
+ await _showEmailSettingsPage();
+ }
+
+ export function closeEmailLibrary() {
+ _cancelEmailPrewarm();
+ const modal = document.getElementById('email-lib-modal');
+ if (modal) modal.remove();
+ if (_libSyncTicker) {
+ clearInterval(_libSyncTicker);
+ _libSyncTicker = null;
+ }
+ _clearEmailDocumentSplit();
+ if (state._libEscHandler) {
+ document.removeEventListener('keydown', state._libEscHandler, true);
+ state._libEscHandler = null;
+ }
+ if (state._libInnerEscHandler) {
+ window.removeEventListener('keydown', state._libInnerEscHandler, true);
+ state._libInnerEscHandler = null;
+ }
+ if (state._emailSearchOptionsDismiss) {
+ document.removeEventListener('click', state._emailSearchOptionsDismiss);
+ state._emailSearchOptionsDismiss = null;
+ }
+ state._libOpen = false;
+ // If the /email route collapsed the wide sidebar to make room for
+ // the fullscreen modal, re-expand it now that the modal is gone.
+ try { window._restoreSidebarIfRouteCollapsed?.(); } catch (_) {}
+ }
+
+ // Make a modal draggable by its header. If `modal` and `fsClass` are
+ // provided, dragging to the top edge of the viewport snaps to fullscreen
+ // (Aero Snap). Dragging away from the top while fullscreen unsnaps.
+ export function _makeDraggable(content, modal, fsClass) {
+ if (!content) return;
+ const header = content.querySelector('.modal-header');
+ if (!header) return;
+ // Per-modal fullscreen behavior — caller supplies fsClass, we apply
+ // the same inline-style fullscreen pattern email-lib + email-window
+ // both use. exitFullscreen restores the default windowed size
+ // (min(720px, 92vw) × 85vh) and centers around the cursor.
+ const enterFullscreen = () => {
+ if (!fsClass || modal.classList.contains(fsClass)) return;
+ modal.classList.add(fsClass);
+ content.style.position = 'fixed';
+ content.style.left = '0';
+ content.style.top = '0';
+ content.style.right = '0';
+ content.style.bottom = '0';
+ content.style.width = '100vw';
+ content.style.maxWidth = '100vw';
+ content.style.height = '100vh';
+ content.style.maxHeight = '100vh';
+ content.style.borderRadius = '0';
+ content.style.transform = 'none';
+ };
+ const exitFullscreen = (cx, cy) => {
+ if (!fsClass || !modal.classList.contains(fsClass)) return;
+ modal.classList.remove(fsClass);
+ content.style.width = 'min(720px, 92vw)';
+ content.style.maxWidth = '';
+ content.style.height = '';
+ content.style.maxHeight = '85vh';
+ content.style.borderRadius = '';
+ content.style.right = '';
+ content.style.bottom = '';
+ const w = Math.min(720, window.innerWidth * 0.92);
+ content.style.left = Math.max(8, cx - w / 2) + 'px';
+ content.style.top = Math.max(8, cy - 20) + 'px';
+ };
+ makeWindowDraggable(modal, {
+ content,
+ header,
+ fsClass,
+ skipSelector: '.close-btn, .modal-close',
+ enableLeftDock: true, // park the email on the left while replying on the right
+ onDragStart: ({ rect }) => {
+ if (!modal.classList.contains('email-snap-left')) return;
+ modal.classList.remove('email-snap-left');
+ _clearEmailDocumentSplit();
+ content.style.position = 'fixed';
+ content.style.left = `${Math.round(rect.left)}px`;
+ content.style.top = `${Math.round(rect.top)}px`;
+ content.style.right = '';
+ content.style.bottom = '';
+ content.style.width = `${Math.max(420, Math.round(rect.width || 560))}px`;
+ content.style.maxWidth = '';
+ content.style.height = `${Math.max(320, Math.round(rect.height || 620))}px`;
+ content.style.maxHeight = '85vh';
+ content.style.borderRadius = '';
+ content.style.transform = 'none';
+ content.style.margin = '0';
+ },
+ onEnterFullscreen: fsClass ? enterFullscreen : null,
+ onExitFullscreen: fsClass ? exitFullscreen : null,
+ });
+ }
+
+ // When the user clicks Reply on a fullscreened email view, dock the email
+ // modal to the left as a narrow sidebar so the doc panel (which opens on
+ // the right side of the chat area) is visible side-by-side. Only triggers
+ // when the viewport is wide enough to make a true split worthwhile. Returns
+ // true if the snap was applied, false otherwise.
+ export function _snapEmailModalToLeftSidebar(modal) {
+ if (!modal) return false;
+ if (window.innerWidth < 900) return false;
+ // "Open in new tab" reader modals (id="email-view-…") are explicitly
+ // floating windows the user already positioned. Replying from one
+ // shouldn't yank it to the left edge — leave it on top in its current
+ // spot. Reply still opens the compose document; the user can drag the
+ // reader away or close it themselves.
+ if ((modal.id || '').startsWith('email-view-')) return false;
+ const content = modal.querySelector('.modal-content');
+ if (!content) return false;
+ // Only dock if currently fullscreen — for a manually-sized window the
+ // user already chose its layout; don't surprise them by snapping it.
+ const wasLibFs = modal.classList.contains('email-lib-fullscreen');
+ const wasWinFs = modal.classList.contains('email-window-fullscreen');
+ if (!wasLibFs && !wasWinFs) return false;
+ modal.classList.remove('email-lib-fullscreen');
+ modal.classList.remove('email-window-fullscreen');
+ modal.classList.add('email-snap-left');
+ const W = Math.min(440, Math.max(360, Math.round(window.innerWidth * 0.30)));
+ const left = _emailSplitLeftEdge();
+ content.style.position = 'fixed';
+ content.style.left = '0';
+ content.style.top = '0';
+ content.style.right = '';
+ content.style.bottom = '0';
+ content.style.width = W + 'px';
+ content.style.maxWidth = W + 'px';
+ content.style.height = '100vh';
+ content.style.maxHeight = '100vh';
+ content.style.borderRadius = '0';
+ content.style.transform = 'none';
+ content.style.margin = '0';
+ _setEmailDocumentSplit(left, W);
+ _scheduleEmailDocumentSplitMeasure(modal);
+ return true;
+ }
+
+ export async function _loadFolders({ resetMissing = false, live = false } = {}) {
+ const seq = ++_libFolderSeq;
+ const accountAtStart = state._libAccountId || '';
+ try {
+ const res = await fetch(emailApiUrl('/api/email/folders', {
+ account_id: accountAtStart || undefined,
+ cached_only: live ? undefined : 1,
+ }));
+ let data = await res.json();
+ if (seq !== _libFolderSeq || accountAtStart !== (state._libAccountId || '')) return;
+ const sel = document.getElementById('email-lib-folder');
+ if (!sel || !data.folders) return;
+ state._libFolders = data.folders;
+ const resolvedFolder = _resolveEmailFolderAlias(state._libFolder);
+ if (resolvedFolder !== state._libFolder && data.folders.includes(resolvedFolder)) {
+ state._libFolder = resolvedFolder;
+ }
+ if (resetMissing && state._libFolder !== '__scheduled__' && !data.folders.includes(state._libFolder)) {
+ state._libFolder = data.folders.includes('INBOX') ? 'INBOX' : (data.folders[0] || 'INBOX');
+ state._libFilter = 'all';
+ state._libSearch = '';
+ state._libHasAttachments = false;
+ _libListCache.clear();
+ const searchEl = document.getElementById('email-lib-search');
+ const filterEl = document.getElementById('email-lib-filter');
+ const attachEl = document.getElementById('email-attachments-btn');
+ if (searchEl) searchEl.value = '';
+ if (filterEl) filterEl.value = 'all';
+ if (attachEl) attachEl.classList.remove('active');
+ _syncUnreadWindowGlow();
+ _syncReminderClearButton();
+ }
+ sel.innerHTML = '';
+ const folderHeader = document.createElement('option');
+ folderHeader.disabled = true;
+ folderHeader.textContent = '─────────';
+ sel.appendChild(folderHeader);
+ const { priority, others } = sortedFolders(data.folders);
+ for (const f of priority) {
+ const opt = document.createElement('option');
+ opt.value = f;
+ opt.textContent = folderDisplayName(f);
+ if (f === state._libFolder) opt.selected = true;
+ sel.appendChild(opt);
+ }
+ for (const f of others) {
+ const opt = document.createElement('option');
+ opt.value = f;
+ opt.textContent = folderDisplayName(f);
+ if (f === state._libFolder) opt.selected = true;
+ sel.appendChild(opt);
+ }
+ if (!data.folders.some(f => /trash|bin|deleted/i.test(String(f)))) {
+ const trashOpt = document.createElement('option');
+ trashOpt.value = 'Trash';
+ trashOpt.textContent = 'Trash';
+ if (String(state._libFolder).toLowerCase() === 'trash') trashOpt.selected = true;
+ sel.appendChild(trashOpt);
+ }
+ // Some providers omit Drafts from the folder discovery response even
+ // though IMAP APPEND can still write to the standard Drafts mailbox.
+ // Keep it available beside the provider-discovered folders.
+ const hasDraftsFolder = data.folders.some(f => String(f).toLowerCase().includes('draft'));
+ if (!hasDraftsFolder) {
+ const draftOpt = document.createElement('option');
+ draftOpt.value = 'Drafts';
+ draftOpt.textContent = 'Drafts';
+ if (String(state._libFolder).toLowerCase() === 'drafts') draftOpt.selected = true;
+ sel.appendChild(draftOpt);
+ }
+ // Scheduled (special virtual folder)
+ const schedOpt = document.createElement('option');
+ schedOpt.value = '__scheduled__';
+ schedOpt.textContent = 'Scheduled';
+ if (state._libFolder === '__scheduled__') schedOpt.selected = true;
+ sel.appendChild(schedOpt);
+ sel.value = state._libFolder;
+ _renderFolderPicker();
+ } catch (e) {}
+ }
+
+ function _crossFolderCandidates() {
+ const available = Array.isArray(state._libFolders) ? state._libFolders.filter(Boolean) : [];
+ const lower = new Map(available.map(f => [String(f).toLowerCase(), f]));
+ const pick = (patterns, fallback) => {
+ for (const p of patterns) {
+ const direct = lower.get(String(p).toLowerCase());
+ if (direct) return direct;
+ }
+ const match = available.find(f => patterns.some(p => String(f).toLowerCase().includes(String(p).toLowerCase())));
+ return match || fallback;
+ };
+ const candidates = [
+ pick(['INBOX'], 'INBOX'),
+ pick(['[Gmail]/Sent Mail', 'Sent Mail', 'Sent Items', 'INBOX.Sent', 'Sent'], '[Gmail]/Sent Mail'),
+ pick(['Archive', '[Gmail]/All Mail', 'All Mail'], '[Gmail]/All Mail'),
+ ];
+ return Array.from(new Set(candidates.filter(Boolean)));
+ }
+
+ function _findEmailFolder(patterns, fallback) {
+ const available = Array.isArray(state._libFolders) ? state._libFolders.filter(Boolean) : [];
+ const lower = new Map(available.map(f => [String(f).toLowerCase(), f]));
+ for (const p of patterns) {
+ const direct = lower.get(String(p).toLowerCase());
+ if (direct) return direct;
+ }
+ return available.find(f => patterns.some(p => String(f).toLowerCase().includes(String(p).toLowerCase()))) || fallback;
+ }
+
+ function _resolveEmailFolderAlias(folder) {
+ const raw = String(folder || '').trim();
+ const key = raw.toLowerCase();
+ if (!raw || key === 'inbox' || raw === '__scheduled__') return raw || 'INBOX';
+ if (key === 'sent' || key === 'sent mail' || key === 'sent items') {
+ return _findEmailFolder(['[Gmail]/Sent Mail', '[Google Mail]/Sent Mail', 'Sent Mail', 'Sent Items', 'INBOX.Sent', 'Sent'], raw);
+ }
+ if (key === 'archive' || key === 'archives' || key === 'all mail' || key === 'archive / all mail') {
+ return _findEmailFolder(['[Gmail]/All Mail', '[Google Mail]/All Mail', 'All Mail', 'Archive', 'Archives'], raw);
+ }
+ if (key === 'starred' || key === 'favorites' || key === 'flagged') {
+ return _findEmailFolder(['[Gmail]/Starred', '[Google Mail]/Starred', 'Starred', 'Flagged'], raw);
+ }
+ if (key === 'junk' || key === 'spam') {
+ return _findEmailFolder(['[Gmail]/Spam', '[Google Mail]/Spam', 'Spam', 'Junk'], raw);
+ }
+ if (key === 'trash' || key === 'bin' || key === 'deleted') {
+ return _findEmailFolder(['[Gmail]/Trash', '[Google Mail]/Trash', '[Gmail]/Bin', 'Trash', 'Bin', 'Deleted Messages', 'Deleted Items'], raw);
+ }
+ if (key === 'draft' || key === 'drafts') {
+ return _findEmailFolder(['[Gmail]/Drafts', '[Google Mail]/Drafts', 'Drafts', 'Draft', 'INBOX.Drafts'], raw);
+ }
+ return raw;
+ }
+
+ function _sentFolderName() {
+ return _findEmailFolder(['[Gmail]/Sent Mail', 'Sent Mail', 'Sent Items', 'INBOX.Sent', 'Sent'], 'Sent');
+ }
+
+ function _deriveSearchScope(rawQuery) {
+ const original = String(rawQuery || '').trim();
+ const tokens = original.split(/\s+/).filter(Boolean);
+ let scope = 'all';
+ const kept = [];
+ let forced = '';
+ for (const token of tokens) {
+ const t = token.toLowerCase().replace(/^#+/, '').replace(/:$/, '');
+ if (['sent', 'sentmail', 'sent-mail', 'outbox'].includes(t)) {
+ forced = 'sent';
+ continue;
+ }
+ if (['inbox'].includes(t)) {
+ forced = 'inbox';
+ continue;
+ }
+ kept.push(token);
+ }
+ if (forced) scope = forced;
+ let folder = 'INBOX';
+ let serverScope = 'all';
+ if (scope === 'sent') {
+ folder = _sentFolderName();
+ serverScope = 'folder';
+ } else if (scope === 'inbox') {
+ folder = 'INBOX';
+ serverScope = 'folder';
+ } else if (scope === 'current') {
+ folder = state._libFolder || 'INBOX';
+ serverScope = 'folder';
+ }
+ return {
+ scope,
+ folder,
+ serverScope,
+ q: forced ? kept.join(' ').trim() : original,
+ forced,
+ };
+ }
+
+ // Snapshot of state._libEmails taken right before search starts so we
+ // can both filter locally and restore on clear without re-fetching.
+ let _libPreSearchEmails = null;
+ let _libPreSearchTotal = 0;
+ let _libServerSearchEmails = null;
+ let _libServerSearchTotal = 0;
+
+ // Cached contact suggestions for the chip-input autocomplete. Built on
+ // first focus / first keystroke from contacts + currently-loaded senders.
+ let _libSuggestionCache = null;
+ let _libSuggestionFocusIdx = 0;
+
+ async function _buildSuggestionSource() {
+ // Combine the contacts list with senders/recipients visible in the
+ // loaded email list. Dedup by lowercased email address; prefer
+ // contact-supplied display names where present.
+ const map = new Map();
+ const _add = (name, email) => {
+ const key = String(email || '').trim().toLowerCase();
+ if (!key) return;
+ const prev = map.get(key);
+ if (!prev || (name && !prev.name)) {
+ map.set(key, { name: (name || '').trim(), email: key });
+ }
+ };
+ // 1) Senders / recipients already in the loaded grid.
+ for (const em of (state._libEmails || [])) {
+ _add(em.from_name, em.from_address);
+ const _parse = (s) => String(s || '').split(',').forEach(seg => {
+ const m = seg.match(/^\s*"?([^"<]*)"?\s*<?([^>]+)>?\s*$/);
+ if (m) _add(m[1], m[2]);
+ });
+ _parse(em.to);
+ _parse(em.cc);
+ }
+ // 2) Address book — best-effort.
+ try {
+ const r = await fetch(`${API_BASE}/api/contacts/list`, { credentials: 'same-origin' });
+ if (r.ok) {
+ const d = await r.json();
+ for (const c of (d.contacts || [])) {
+ const email = c.email || (c.emails && c.emails[0]) || '';
+ _add(c.name || c.full_name, email);
+ }
+ }
+ } catch (_) {}
+ return Array.from(map.values()).filter(x => x.email);
+ }
+
+ function _scoreSuggestion(s, needle) {
+ // Crude relevance: startsWith on name or email wins big; substring is fine.
+ const n = (s.name || '').toLowerCase();
+ const e = (s.email || '').toLowerCase();
+ if (n.startsWith(needle) || e.startsWith(needle)) return 3;
+ if (n.includes(needle) || e.includes(needle)) return 2;
+ return 0;
+ }
+
+ function _formatEmailSuggestionDate(em) {
+ let d = null;
+ if (em && em.date) {
+ const parsed = new Date(em.date);
+ if (Number.isFinite(parsed.getTime())) d = parsed;
+ }
+ if (!d && em && em.date_epoch) {
+ const parsed = new Date(Number(em.date_epoch) * 1000);
+ if (Number.isFinite(parsed.getTime())) d = parsed;
+ }
+ if (!d) return '';
+ const now = new Date();
+ const opts = d.getFullYear() === now.getFullYear()
+ ? { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }
+ : { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' };
+ return d.toLocaleDateString(undefined, opts);
+ }
+
+ // Filter / attachment suggestions surfaced inside the same chip-bar
+ // dropdown. Typing 'attachment', 'unread', 'urgent' etc. surfaces the
+ // corresponding filter row with its icon; picking it pins a filter
+ // pill that drives state._libFilter or the has-attachments toggle.
+ const _LIB_FILTER_OPTIONS = [
+ { value: 'filter:has-attachments', label: 'Has attachments', keywords: ['attachment', 'attachments', 'has attachment', 'attach'] },
+ { value: 'filter:unread', label: 'Unread', keywords: ['unread', 'new', 'unseen'] },
+ { value: 'filter:favorites', label: 'Favorites', keywords: ['favorite', 'favorites', 'starred', 'star', 'flagged'] },
+ { value: 'filter:undone', label: 'Undone', keywords: ['undone', 'pending', 'todo'] },
+ { value: 'filter:reminders', label: 'Reminders', keywords: ['reminder', 'reminders'] },
+ { value: 'filter:unanswered', label: 'Unanswered', keywords: ['unanswered', 'unreplied', 'no reply'] },
+ { value: 'filter:pending_30d', label: 'Pending · 30d', keywords: ['pending 30d', 'pending', 'recent pending'] },
+ { value: 'filter:stale_30d', label: 'Stale · >30d', keywords: ['stale', 'old', 'stale 30d'] },
+ { value: 'filter:tag:urgent', label: 'Urgent', keywords: ['urgent', 'critical'] },
+ { value: 'filter:tag:reply-soon', label: 'Reply soon', keywords: ['reply soon', 'reply', 'follow up'] },
+ { value: 'filter:tag:bills', label: 'Bills', keywords: ['bill', 'bills', 'billing'] },
+ { value: 'filter:tag:receipt', label: 'Receipt', keywords: ['receipt', 'receipts', 'purchase'] },
+ { value: 'filter:tag:travel', label: 'Travel', keywords: ['travel', 'trip', 'booking'] },
+ { value: 'filter:tag:spam', label: 'Spam', keywords: ['spam', 'junk'] },
+ ];
+
+ function _libFilterIconFor(value) {
+ // value is 'filter:<X>' — strip prefix and reuse the existing icon map.
+ const v = String(value || '').replace(/^filter:/, '');
+ if (v === 'has-attachments') return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 17.93 8.8l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>';
+ if (v === 'date-range') return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="17" rx="2"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>';
+ return _EMAIL_FILTER_ICONS[v] || _EMAIL_FILTER_ICONS['all'];
+ }
+
+ function _scoreFilterOption(opt, needle) {
+ for (const kw of opt.keywords) {
+ if (kw === needle) return 4;
+ if (kw.startsWith(needle)) return 3;
+ if (kw.includes(needle)) return 2;
+ }
+ if (opt.label.toLowerCase().includes(needle)) return 2;
+ return 0;
+ }
+
+ function _filterSuggestions(needle, limit = 10) {
+ const n = String(needle || '').trim().toLowerCase();
+ if (!n) return [];
+ // Filter / attachment matches first — typing 'unread' should surface
+ // the filter row before contact suggestions, since 'unread' isn't a
+ // person.
+ const filterMatches = _LIB_FILTER_OPTIONS
+ .map(opt => ({ s: { kind: 'filter', value: opt.value, label: opt.label, icon: _libFilterIconFor(opt.value) }, score: _scoreFilterOption(opt, n) }))
+ .filter(x => x.score > 0);
+ const src = _libSuggestionCache || [];
+ const contactMatches = src
+ .map(s => ({ s: { kind: 'contact', ...s }, score: _scoreSuggestion(s, n) }))
+ .filter(x => x.score > 0);
+ // Email subject / sender-name matches — use the snapshot (unfiltered
+ // list) when available so suggestions don't shrink as pills narrow the
+ // visible grid. Cap to 4 so contacts + filters stay visible.
+ const emails = _libPreSearchEmails || state._libEmails || [];
+ const emailMatches = [];
+ for (const em of emails) {
+ const subj = String(em.subject || '').toLowerCase();
+ const fromN = String(em.from_name || '').toLowerCase();
+ let score = 0;
+ if (subj.startsWith(n) || fromN.startsWith(n)) score = 3;
+ else if (subj.includes(n) || fromN.includes(n)) score = 1;
+ if (score > 0) {
+ emailMatches.push({
+ s: {
+ kind: 'email',
+ uid: em.uid,
+ subject: em.subject || '(no subject)',
+ from_name: em.from_name || em.from_address || '',
+ date_label: _formatEmailSuggestionDate(em),
+ },
+ score,
+ });
+ }
+ if (emailMatches.length >= 4) break;
+ }
+ return filterMatches.concat(contactMatches).concat(emailMatches)
+ .sort((a, b) => b.score - a.score)
+ .slice(0, limit)
+ .map(x => x.s);
+ }
+
+ function _exactTypedFilterSuggestion(value) {
+ const needle = String(value || '').trim().toLowerCase();
+ if (!needle) return null;
+ // Keep automatic conversion deliberately exact. A query such as
+ // "attachment invoice" should remain a text search, while the common
+ // one-word shortcut should become the existing filter pill.
+ const option = _LIB_FILTER_OPTIONS.find(opt => (
+ opt.value === 'filter:has-attachments' && opt.keywords.includes(needle)
+ ));
+ return option
+ ? { kind: 'filter', value: option.value, label: option.label, icon: _libFilterIconFor(option.value) }
+ : null;
+ }
+
+ function _emailMatchesPill(em, pill) {
+ if (!pill) return false;
+ if (pill.type === 'contact') {
+ const target = (pill.email || '').toLowerCase();
+ if (!target) return false;
+ if (String(em.from_address || '').toLowerCase() === target) return true;
+ if (String(em.to || '').toLowerCase().includes(target)) return true;
+ if (String(em.cc || '').toLowerCase().includes(target)) return true;
+ return false;
+ }
+ if (pill.type === 'filter') {
+ // Filter pills delegate to the server-side filter (state._libFilter)
+ // or the has-attachments toggle. The list is already pre-filtered by
+ // those when this runs, so the pill is effectively always-true here
+ // — it lives in the pill bar purely as a visible affordance.
+ return true;
+ }
+ // text pill — broad local-match
+ const q = (pill.text || '').toLowerCase();
+ if (!q) return true;
+ return _matchesQuery(em, q);
+ }
+
+ function _matchesQuery(em, q) {
+ const needle = q.toLowerCase();
+ const dateNeedle = _formatEmailSuggestionDate(em).toLowerCase();
+ const dateOnlyNeedle = dateNeedle.replace(/\s+\d{1,2}:\d{2}\s*(am|pm)?$/i, '');
+ const rawDate = String(em.date || em.date_display || '').toLowerCase();
+ return (
+ String(em.subject || '').toLowerCase().includes(needle) ||
+ String(em.from_name || '').toLowerCase().includes(needle) ||
+ String(em.from_address || '').toLowerCase().includes(needle) ||
+ String(em.to || '').toLowerCase().includes(needle) ||
+ String(em.cc || '').toLowerCase().includes(needle) ||
+ String(em.snippet || em.preview || '').toLowerCase().includes(needle) ||
+ dateNeedle.includes(needle) ||
+ dateOnlyNeedle.includes(needle) ||
+ rawDate.includes(needle)
+ );
+ }
+
+ // Apply the active pill filter to the snapshot. Each pill is OR-ed; an
+ // email shows up if ANY pill matches (a contact pill matches by from/to/cc
+ // equality, a text pill matches by the broad _matchesQuery substring).
+ function _applyPillFilter() {
+ _exitEmailReaderModeForList();
+ const pills = state._libSearchPills || [];
+ const draft = (state._libSearchDraft || '').trim();
+ const noPills = pills.length === 0;
+ const noDraft = draft.length === 0;
+ // First time we apply with anything active: snapshot the loaded list.
+ if (!noPills || draft.length >= 1) {
+ if (!_libPreSearchEmails) {
+ _libPreSearchEmails = (state._libEmails || []).slice();
+ _libPreSearchTotal = state._libTotal;
+ }
+ }
+ if (noPills && noDraft) {
+ if (_libPreSearchEmails) {
+ state._libEmails = _libPreSearchEmails;
+ state._libTotal = _libPreSearchTotal;
+ _libPreSearchEmails = null;
+ _libPreSearchTotal = 0;
+ }
+ _renderGrid();
+ return;
+ }
+ const source = _libServerSearchEmails || _libPreSearchEmails || state._libEmails || [];
+ // If the active server search covers a piece of text (either the live
+ // draft OR an Enter-committed text pill), skip the local re-filter for
+ // it — _emailMatchesPill only checks subject/from_name/from_address/
+ // snippet (no BODY), so it was dropping legitimate server hits where
+ // the match was in body text. Real pills (contact, filter chips) still
+ // apply, and other text pills with different strings still apply.
+ const libSearchLower = (_libSearchHadResults ? (state._libSearch || '').trim().toLowerCase() : '');
+ const hasRefinementBase = !!(_libServerSearchEmails && pills.length > 1);
+ const serverHandledDraft = !hasRefinementBase && !!(libSearchLower && draft && libSearchLower === draft.toLowerCase());
+ const draftPill = (!serverHandledDraft && draft.length >= 1) ? { type: 'text', text: draft } : null;
+ // Filter out text pills whose text matches the active server search —
+ // those were the trigger for the IMAP query and don't need re-checking.
+ const effectiveBasePills = (libSearchLower && !hasRefinementBase)
+ ? pills.filter(p => !(p.type === 'text' && (p.text || '').toLowerCase() === libSearchLower))
+ : pills;
+ const effective = draftPill ? effectiveBasePills.concat([draftPill]) : effectiveBasePills;
+ // AND across pills — "alice + bob" should mean both alice AND bob are
+ // somewhere on the email (from/to/cc), not "from alice OR from bob".
+ const filtered = source.filter(em => effective.every(p => _emailMatchesPill(em, p)));
+ state._libEmails = filtered;
+ _renderGrid();
+ }
+ // Back-compat shim: older call sites still expect _localSearchFilter.
+ function _localSearchFilter(query) {
+ state._libSearchDraft = String(query || '');
+ _applyPillFilter();
+ }
+
+ // Render the active pills inside the chip bar. Each pill carries a × to
+ // remove individually. Backspace on empty input also pops the last one.
+ function _emailFilterLabelFor(value) {
+ const v = String(value || '');
+ if (v === 'has-attachments') return 'Attachments';
+ const sel = document.getElementById('email-lib-filter');
+ const opt = sel?.querySelector?.(`option[value="${CSS.escape(v)}"]`);
+ if (opt) return opt.textContent || v;
+ const match = _LIB_FILTER_OPTIONS.find(o => o.value === `filter:${v}`);
+ return match?.label || v;
+ }
+
+ function _activeEmailFilterPills() {
+ const active = [];
+ if (state._libHasAttachments) {
+ active.push({ value: 'has-attachments', label: _emailFilterLabelFor('has-attachments') });
+ }
+ const filter = String(state._libFilter || 'all');
+ if (filter && filter !== 'all') {
+ active.push({ value: filter, label: _emailFilterLabelFor(filter) });
+ }
+ if (state._libDateFrom || state._libDateTo) {
+ const range = state._libDateFrom && state._libDateTo
+ ? `${state._libDateFrom} – ${state._libDateTo}`
+ : state._libDateFrom ? `From ${state._libDateFrom}` : `Through ${state._libDateTo}`;
+ active.push({ value: 'date-range', label: range });
+ }
+ return active;
+ }
+
+ function _clearActiveEmailFilterPill(value) {
+ _resetBulkSelectionForContextChange({ rerender: true });
+ const v = String(value || '');
+ if (v === 'has-attachments') {
+ state._libHasAttachments = false;
+ } else if (v === 'date-range') {
+ state._libDateFrom = '';
+ state._libDateTo = '';
+ } else if (state._libFilter === v) {
+ state._libFilter = 'all';
+ const sel = document.getElementById('email-lib-filter');
+ if (sel) sel.value = 'all';
+ }
+ _syncUnreadWindowGlow();
+ _syncReminderClearButton();
+ _renderFilterPickerCurrent();
+ _syncSearchOptionsMenu();
+ _renderSearchPills();
+ _loadEmailsFresh();
+ }
+
+ function _renderSearchPills() {
+ const wrap = document.getElementById('email-lib-pills');
+ if (!wrap) return;
+ const pills = (state._libSearchPills || []).filter(p => p.type !== 'filter');
+ state._libSearchPills = pills;
+ const folderSelect = document.getElementById('email-lib-folder');
+ const folder = String(folderSelect?.value || state._libFolder || 'INBOX');
+ const showingFolderPill = folder && folder !== 'INBOX' && folder !== '__scheduled__';
+ const filterPills = _activeEmailFilterPills();
+ const chipBar = document.getElementById('email-lib-chip-bar');
+ const input = document.getElementById('email-lib-search');
+ const visiblePillCount = pills.length + filterPills.length + (showingFolderPill ? 1 : 0);
+ if (chipBar) chipBar.classList.toggle('has-email-lib-pills', visiblePillCount > 0);
+ if (input) input.placeholder = visiblePillCount > 0 ? '' : 'Search by name or text';
+ const esc = s => String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
+ const folderLabel = folderDisplayName(folder);
+ const folderPill = showingFolderPill
+ ? `<span class="email-lib-pill email-lib-folder-pill" data-folder-pill="${esc(folder)}" title="${esc(folderLabel)}" style="display:inline-flex;align-items:center;gap:3px;padding:0 5px 0 7px;border-radius:999px;background:color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);color:var(--accent, var(--red));font-size:11px;line-height:20px;height:20px;font-weight:600;max-width:170px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:0;">
+ <span style="overflow:hidden;text-overflow:ellipsis;">${esc(folderLabel)}</span>
+ <button type="button" class="email-lib-folder-pill-x" title="Back to Inbox" style="background:transparent;border:0;color:inherit;cursor:pointer;font-size:12px;line-height:1;padding:0 2px;opacity:0.7;position:relative;top:-4px;">×</button>
+ </span>`
+ : '';
+ const filterPillHtml = filterPills.map(p => {
+ const titleAttr = esc(p.label);
+ return `<span class="email-lib-pill email-lib-filter-pill" data-email-filter-pill="${esc(p.value)}" title="${titleAttr}" style="display:inline-flex;align-items:center;gap:3px;padding:0 5px 0 7px;border-radius:999px;background:color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);color:var(--accent, var(--red));font-size:11px;line-height:20px;height:20px;font-weight:600;max-width:170px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:0;">
+ <span class="email-lib-pill-icon" style="display:inline-flex;align-items:center;width:13px;height:13px;flex-shrink:0;">${_libFilterIconFor(`filter:${p.value}`)}</span>
+ <span class="email-lib-filter-pill-label" style="overflow:hidden;text-overflow:ellipsis;">${esc(p.label)}</span>
+ <button type="button" class="email-lib-filter-pill-x" data-email-filter-pill="${esc(p.value)}" title="Remove" style="background:transparent;border:0;color:inherit;cursor:pointer;font-size:12px;line-height:1;padding:0 2px;opacity:0.7;position:relative;top:-4px;">×</button>
+ </span>`;
+ }).join('');
+ wrap.innerHTML = folderPill + filterPillHtml + pills.map((p, i) => {
+ const label = p.type === 'contact' ? (p.name || p.email || '?') : (p.text || '');
+ return `<span class="email-lib-pill" data-pill-idx="${i}" style="display:inline-flex;align-items:center;gap:3px;padding:0 5px 0 7px;border-radius:999px;background:color-mix(in srgb, var(--accent, var(--red)) 14%, transparent);color:var(--accent, var(--red));font-size:11px;line-height:20px;height:20px;font-weight:600;max-width:170px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:0;">
+ <span style="overflow:hidden;text-overflow:ellipsis;">${esc(label)}</span>
+ <button type="button" class="email-lib-pill-x" data-pill-idx="${i}" title="Remove" style="background:transparent;border:0;color:inherit;cursor:pointer;font-size:12px;line-height:1;padding:0 2px;opacity:0.7;position:relative;top:-4px;">×</button>
+ </span>`;
+ }).join('');
+ requestAnimationFrame(() => {
+ if (wrap.scrollWidth <= wrap.clientWidth) return;
+ for (const value of ['has-attachments', 'reminders']) {
+ const pill = wrap.querySelector(`.email-lib-filter-pill[data-email-filter-pill="${value}"]`);
+ if (!pill) continue;
+ pill.classList.add('email-lib-filter-pill-icon-only');
+ if (wrap.scrollWidth <= wrap.clientWidth) break;
+ }
+ });
+ wrap.querySelectorAll('.email-lib-filter-pill[data-email-filter-pill="date-range"]').forEach(pill => {
+ pill.style.cursor = 'pointer';
+ pill.addEventListener('click', (ev) => {
+ if (ev.target.closest('.email-lib-filter-pill-x')) return;
+ const menu = document.getElementById('email-search-options-menu');
+ const trigger = document.getElementById('email-search-options-btn');
+ const panel = menu?.querySelector('.email-search-date-panel');
+ if (!menu || !panel) return;
+ menu.hidden = false;
+ panel.hidden = false;
+ trigger?.setAttribute('aria-expanded', 'true');
+ const from = panel.querySelector('#email-search-date-from');
+ const to = panel.querySelector('#email-search-date-to');
+ if (from) from.value = state._libDateFrom || '';
+ if (to) to.value = state._libDateTo || '';
+ from?.focus();
+ });
+ });
+ wrap.querySelectorAll('.email-lib-pill-x').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const idx = Number(btn.dataset.pillIdx);
+ if (Number.isFinite(idx)) _removeSearchPillAt(idx);
+ });
+ });
+ wrap.querySelectorAll('.email-lib-filter-pill-x').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ _clearActiveEmailFilterPill(btn.dataset.emailFilterPill || '');
+ });
+ });
+ wrap.querySelectorAll('.email-lib-folder-pill-x').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ _resetBulkSelectionForContextChange({ rerender: true });
+ const folders = Array.isArray(state._libFolders) ? state._libFolders : [];
+ state._libFolder = folders.includes('INBOX') ? 'INBOX' : (folders.find(f => !/sent/i.test(String(f || ''))) || 'INBOX');
+ const folderSel = document.getElementById('email-lib-folder');
+ if (folderSel) folderSel.value = state._libFolder;
+ _renderFolderPicker();
+ _renderSearchPills();
+ _loadEmailsFresh();
+ });
+ });
+ }
+
+ function _applyFilterPillSideEffect(pill) {
+ // Filter pills drive the existing has-attachments toggle / filter
+ // dropdown so the server returns the right list. Only one filter
+ // pill is active at a time (see _addSearchPill).
+ const sel = document.getElementById('email-lib-filter');
+ if (pill.value === 'filter:has-attachments') {
+ if (!state._libHasAttachments) {
+ state._libHasAttachments = true;
+ _syncSearchOptionsMenu();
+ }
+ if (sel && sel.value !== 'all') { sel.value = 'all'; sel.dispatchEvent(new Event('change')); }
+ return;
+ }
+ // Any other filter pill — set the dropdown value, clear attachments
+ if (state._libHasAttachments) {
+ state._libHasAttachments = false;
+ _syncSearchOptionsMenu();
+ }
+ if (sel) {
+ const v = pill.value.replace(/^filter:/, '');
+ if (sel.value !== v) { sel.value = v; sel.dispatchEvent(new Event('change')); }
+ }
+ }
+
+ function _clearFilterPillSideEffect() {
+ const sel = document.getElementById('email-lib-filter');
+ if (state._libHasAttachments) {
+ state._libHasAttachments = false;
+ _syncSearchOptionsMenu();
+ }
+ if (sel && sel.value !== 'all') {
+ sel.value = 'all'; sel.dispatchEvent(new Event('change'));
+ }
+ }
+
+ function _addSearchPill(pill) {
+ if (!pill) return;
+ _resetBulkSelectionForContextChange({ rerender: true });
+ if (!Array.isArray(state._libSearchPills)) state._libSearchPills = [];
+ // Dedup by email (contact), text (text pill), or filter value.
+ if (pill.type === 'contact') {
+ const key = (pill.email || '').toLowerCase();
+ if (!key) return;
+ if (state._libSearchPills.some(p => p.type === 'contact' && (p.email || '').toLowerCase() === key)) return;
+ } else if (pill.type === 'text') {
+ const t = (pill.text || '').toLowerCase();
+ if (!t) return;
+ if (state._libSearchPills.some(p => p.type === 'text' && (p.text || '').toLowerCase() === t)) return;
+ } else if (pill.type === 'filter') {
+ // Filter state renders as a synthetic pill from state._libFilter /
+ // state._libHasAttachments. Do not store a duplicate search pill.
+ state._libSearchPills = state._libSearchPills.filter(p => p.type !== 'filter');
+ _applyFilterPillSideEffect(pill);
+ _renderSearchPills();
+ return;
+ }
+ state._libSearchPills.push(pill);
+ _renderSearchPills();
+ _applyPillFilter();
+ }
+
+ function _searchQueryFromPills() {
+ const parts = [];
+ for (const p of state._libSearchPills || []) {
+ if (p.type === 'text' && p.text) parts.push(String(p.text).trim());
+ else if (p.type === 'contact' && (p.email || p.name)) parts.push(String(p.email || p.name).trim());
+ }
+ return parts.filter(Boolean).join(' ').trim();
+ }
+
+ function _removeSearchPillAt(idx) {
+ if (!Array.isArray(state._libSearchPills)) return;
+ _resetBulkSelectionForContextChange({ rerender: true });
+ const removed = state._libSearchPills[idx];
+ state._libSearchPills.splice(idx, 1);
+ if (removed && removed.type === 'filter') _clearFilterPillSideEffect();
+ _renderSearchPills();
+ // Pill cleared all the way: if we got into search-result mode via the
+ // IMAP search, the pre-search snapshot is now those results too (set
+ // in _doSearch). Restoring from it would leave the user staring at
+ // the same results with the pill bar empty. Re-fetch the real inbox
+ // so removing the last pill genuinely "goes back".
+ const noPillsLeft = (state._libSearchPills || []).length === 0
+ && !(state._libSearchDraft || '').trim();
+ if (noPillsLeft && _libSearchHadResults) {
+ _libSearchHadResults = false;
+ _libPreSearchEmails = null;
+ _libPreSearchTotal = 0;
+ _libServerSearchEmails = null;
+ _libServerSearchTotal = 0;
+ state._libSearch = '';
+ state._libOffset = 0;
+ const _searchInput = document.getElementById('email-lib-search');
+ if (_searchInput) _searchInput.value = '';
+ _loadEmails({ useCache: true });
+ return;
+ }
+ const remainingQuery = _searchQueryFromPills();
+ if (remainingQuery.length >= 2) {
+ state._libSearch = remainingQuery;
+ const _searchInput = document.getElementById('email-lib-search');
+ if (_searchInput) _searchInput.value = '';
+ state._libSearchDraft = '';
+ _doSearch();
+ return;
+ }
+ if ((state._libSearchPills || []).length && _libSearchHadResults) {
+ _libSearchHadResults = false;
+ _libPreSearchEmails = null;
+ _libPreSearchTotal = 0;
+ _libServerSearchEmails = null;
+ _libServerSearchTotal = 0;
+ state._libSearch = '';
+ state._libOffset = 0;
+ _loadEmails({ useCache: true });
+ return;
+ }
+ _applyPillFilter();
+ }
+
+ // Render the autocomplete dropdown below the input. focusIdx highlights
+ // the active row; Tab autocompletes / Enter accepts that row.
+ function _renderSearchSuggestions(items) {
+ const menu = document.getElementById('email-lib-suggest');
+ if (!menu) return;
+ if (!items.length) { menu.style.display = 'none'; menu.innerHTML = ''; return; }
+ const esc = s => String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
+ menu.innerHTML = items.map((s, i) => {
+ const highlight = i === _libSuggestionFocusIdx ? 'background:color-mix(in srgb, var(--fg) 8%, transparent);' : '';
+ if (s.kind === 'filter') {
+ return `<div class="email-lib-suggest-item" data-idx="${i}" style="display:flex;align-items:center;gap:8px;padding:6px 10px;cursor:pointer;font-size:12px;${highlight}">
+ <span style="display:inline-flex;align-items:center;width:13px;height:13px;color:var(--accent, var(--red));flex-shrink:0;">${s.icon}</span>
+ <span style="font-weight:600;">${esc(s.label)}</span>
+ </div>`;
+ }
+ if (s.kind === 'email') {
+ return `<div class="email-lib-suggest-item" data-idx="${i}" style="display:flex;align-items:center;gap:6px;padding:6px 10px;cursor:pointer;font-size:12px;${highlight}">
+ <span style="display:inline-flex;align-items:center;width:13px;height:13px;color:var(--fg-muted, var(--fg));opacity:0.55;flex-shrink:0;"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><polyline points="2 6 12 13 22 6"/></svg></span>
+ <span style="font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${esc(s.subject)}</span>
+ ${s.from_name ? `<span style="opacity:0.55;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">— ${esc(s.from_name)}</span>` : ''}
+ ${s.date_label ? `<span style="margin-left:auto;opacity:0.48;font-size:11px;white-space:nowrap;flex-shrink:0;">${esc(s.date_label)}</span>` : ''}
+ </div>`;
+ }
+ return `<div class="email-lib-suggest-item" data-idx="${i}" style="display:flex;align-items:center;gap:6px;padding:6px 10px;cursor:pointer;font-size:12px;${highlight}">
+ <span style="font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${esc(s.name || s.email)}</span>
+ ${s.name ? `<span style="opacity:0.55;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${esc(s.email)}</span>` : ''}
+ </div>`;
+ }).join('');
+ menu.style.display = '';
+ menu.querySelectorAll('.email-lib-suggest-item').forEach(row => {
+ row.addEventListener('mousedown', (e) => {
+ // mousedown (not click) so we beat the input blur handler that hides the menu.
+ e.preventDefault();
+ const idx = Number(row.dataset.idx);
+ const item = items[idx];
+ if (item) _acceptSuggestion(item);
+ });
+ });
+ }
+
+ function _hideSearchSuggestions() {
+ const menu = document.getElementById('email-lib-suggest');
+ if (menu) { menu.style.display = 'none'; menu.innerHTML = ''; }
+ _libSuggestionFocusIdx = 0;
+ }
+
+ function _acceptSuggestion(s) {
+ const input = document.getElementById('email-lib-search');
+ if (s.kind === 'filter') {
+ _addSearchPill({ type: 'filter', value: s.value, label: s.label });
+ } else if (s.kind === 'email') {
+ // Clear the draft + dropdown and open the matching card directly.
+ if (input) input.value = '';
+ state._libSearchDraft = '';
+ _hideSearchSuggestions();
+ _applyPillFilter();
+ const grid = document.getElementById('email-lib-grid');
+ const card = grid?.querySelector(`.doclib-card[data-uid="${CSS.escape(String(s.uid))}"]`);
+ const em = (state._libEmails || []).find(x => String(x.uid) === String(s.uid))
+ || (_libPreSearchEmails || []).find(x => String(x.uid) === String(s.uid));
+ if (card && em) {
+ card.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
+ _toggleCardPreview(card, em);
+ }
+ return;
+ } else {
+ _addSearchPill({ type: 'contact', name: s.name, email: s.email });
+ // Same as the text-pill path in the Enter handler: trigger the IMAP
+ // search so unloaded emails (older than the current page) show up
+ // when picking a contact. The local pill filter then narrows the
+ // search results to that contact's address.
+ const _q = (s.email || s.name || '').trim();
+ if (_q && _q.length >= 2) {
+ state._libSearch = _q;
+ _doSearch();
+ }
+ }
+ if (input) input.value = '';
+ state._libSearchDraft = '';
+ _hideSearchSuggestions();
+ _applyPillFilter();
+ if (input) input.focus();
+ }
+
+ async function _initEmailSearchChipBar() {
+ const bar = document.getElementById('email-lib-chip-bar');
+ const input = document.getElementById('email-lib-search');
+ if (!bar || !input) return;
+ state._libSearchPills = state._libSearchPills || [];
+ state._libSearchDraft = '';
+ _renderSearchPills();
+
+ // Lazy-load suggestion source on first focus / keystroke.
+ const _ensureSuggestionCache = async () => {
+ if (_libSuggestionCache) return;
+ _libSuggestionCache = await _buildSuggestionSource();
+ };
+
+ // Click anywhere in the bar lands the cursor in the input field.
+ bar.addEventListener('click', (e) => {
+ if (e.target.closest('.email-lib-pill-x')) return;
+ input.focus();
+ });
+
+ let _itemsRef = [];
+ const _refreshSuggestions = async () => {
+ await _ensureSuggestionCache();
+ _itemsRef = _filterSuggestions(input.value);
+ // Default to no focused suggestion — text typing should feel like
+ // regular search; the user has to ArrowDown / Tab explicitly to
+ // pick a contact. Enter without a focused row commits as text.
+ _libSuggestionFocusIdx = -1;
+ _renderSearchSuggestions(_itemsRef);
+ };
+
+ input.addEventListener('focus', _refreshSuggestions);
+ // Debounced IMAP search — fires ~500ms after the user stops typing so
+ // searches for names/text not in the current inbox page actually surface
+ // hits, instead of just locally filtering the visible window.
+ //
+ // Live local filtering on EVERY keystroke was clobbering server hits:
+ // _emailMatchesPill / _matchesQuery check subject/from_name/from_address/
+ // snippet but never body, so intermediate text like "sam" reduced the
+ // 61 server results to whatever matched just those four fields (often
+ // 0). User saw "no emails" while typing. So local filter is gone from
+ // the typing path — debounced server search drives the grid. Pill
+ // add/remove still re-runs the local filter through _applyPillFilter
+ // directly.
+ let _libSearchTypingTimer = null;
+ input.addEventListener('input', async () => {
+ _resetBulkSelectionForContextChange({ rerender: true });
+ state._libSearchDraft = input.value;
+ await _refreshSuggestions();
+ if (_libSearchTypingTimer) clearTimeout(_libSearchTypingTimer);
+ const v = input.value.trim();
+ if (v.length >= 2) {
+ _libSearchTypingTimer = setTimeout(() => {
+ const cur = (input.value || '').trim();
+ if (cur === v && cur.length >= 2) {
+ state._libSearch = cur;
+ _doSearch();
+ }
+ }, 500);
+ } else if (!v && _libSearchHadResults) {
+ // Cleared the input → restore the inbox the same way the pill-clear
+ // path does. Otherwise the stale search results stayed up after the
+ // user backspaced everything out.
+ _libSearchHadResults = false;
+ _libPreSearchEmails = null;
+ _libPreSearchTotal = 0;
+ state._libSearch = '';
+ state._libOffset = 0;
+ _loadEmails({ useCache: true });
+ }
+ });
+ input.addEventListener('keydown', (e) => {
+ const menu = document.getElementById('email-lib-suggest');
+ const menuOpen = menu && menu.style.display !== 'none';
+ if (e.key === 'Backspace' && !input.value && (state._libSearchPills || []).length) {
+ e.preventDefault();
+ _removeSearchPillAt(state._libSearchPills.length - 1);
+ return;
+ }
+ if (e.key === 'ArrowDown' && menuOpen) {
+ e.preventDefault();
+ // -1 → 0 → 1 → … → length-1, then wraps back to -1 (no selection)
+ const next = _libSuggestionFocusIdx + 1;
+ _libSuggestionFocusIdx = next >= _itemsRef.length ? -1 : next;
+ _renderSearchSuggestions(_itemsRef);
+ return;
+ }
+ if (e.key === 'ArrowUp' && menuOpen) {
+ e.preventDefault();
+ // -1 → length-1 → length-2 → … → 0 → -1
+ const next = _libSuggestionFocusIdx - 1;
+ _libSuggestionFocusIdx = next < -1 ? _itemsRef.length - 1 : next;
+ _renderSearchSuggestions(_itemsRef);
+ return;
+ }
+ if (e.key === 'Tab' && menuOpen) {
+ // Tab autocompletes the FIRST suggestion (most-relevant), regardless
+ // of whether the user arrowed down yet — matches the user's mental
+ // model of "type a name and tab to pick".
+ const pick = _libSuggestionFocusIdx >= 0 ? _itemsRef[_libSuggestionFocusIdx] : _itemsRef[0];
+ if (pick) { e.preventDefault(); _acceptSuggestion(pick); return; }
+ }
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ // Only commit a contact if the user explicitly focused one. Plain
+ // Enter should default to a text pill so regular text search works
+ // without forcing a contact pick.
+ if (menuOpen && _libSuggestionFocusIdx >= 0 && _itemsRef[_libSuggestionFocusIdx]) {
+ _acceptSuggestion(_itemsRef[_libSuggestionFocusIdx]);
+ return;
+ }
+ const v = input.value.trim();
+ if (v) {
+ const typedFilter = _exactTypedFilterSuggestion(v);
+ if (typedFilter) {
+ _acceptSuggestion(typedFilter);
+ return;
+ }
+ _addSearchPill({ type: 'text', text: v });
+ input.value = '';
+ state._libSearchDraft = '';
+ _hideSearchSuggestions();
+ // Pill-only filtering used to only check emails already loaded into
+ // state._libEmails (the visible page of the inbox). Searches for
+ // names/text that aren't in the current page returned "no emails"
+ // even when matches existed on the server. Trigger the IMAP
+ // search so state._libEmails is replaced with the actual hits,
+ // then the pill filter narrows to matches.
+ state._libSearch = v;
+ _doSearch();
+ }
+ return;
+ }
+ if (e.key === 'Escape') {
+ if (menuOpen) {
+ // Just close the dropdown — let the modal Esc handler run on the
+ // next Esc to actually dismiss the library.
+ e.preventDefault();
+ e.stopPropagation();
+ _hideSearchSuggestions();
+ } else {
+ // Blur first so the modal Esc handler doesn't get suppressed by
+ // any IME / typing-target check, and let the event propagate.
+ try { input.blur(); } catch (_) {}
+ }
+ }
+ });
+ }
+
+ // Click-to-add: clicking a recipient-chip in the email reader OR a
+ // .email-meta-sender in the library list drops the person into the
+ // library search as a contact pill so the user can pivot to "everything
+ // from / to this person" in one tap.
+ window.addEventListener('click', (e) => {
+ const lib = document.getElementById('email-lib-modal');
+ // 1) Recipient chips inside the email reader area
+ const chip = e.target.closest && e.target.closest('.recipient-chip');
+ if (chip && chip.closest('.email-reader-header, .email-card-reader, .email-reader-tab-modal')) {
+ // Don't pivot to library search for chips in the From / To / Cc
+ // meta — clicking those should just toggle the expanded address
+ // view via the per-reader handler.
+ if (chip.closest('.email-reader-meta')) return;
+ const email = (chip.dataset && chip.dataset.email) || '';
+ const name = (chip.dataset && chip.dataset.name) || (chip.textContent || '').trim();
+ if (!email) return;
+ e.preventDefault();
+ e.stopPropagation();
+ try { window.openEmailLibrary && window.openEmailLibrary(); } catch (_) {}
+ _addSearchPill({ type: 'contact', name, email });
+ return;
+ }
+ // 2) Sender name in a library list card row (only when the library is open)
+ if (lib && !lib.classList.contains('hidden')) {
+ const senderEl = e.target.closest && e.target.closest('.email-meta-sender');
+ if (senderEl && senderEl.closest('#email-lib-grid')) {
+ if (state._selectMode) return;
+ const email = (senderEl.dataset && senderEl.dataset.email) || '';
+ const name = (senderEl.dataset && senderEl.dataset.name) || (senderEl.textContent || '').trim();
+ if (!email) return;
+ e.preventDefault();
+ e.stopPropagation();
+ _addSearchPill({ type: 'contact', name, email });
+ }
+ }
+ }, true);
+
+ async function _doSearch() {
+ _exitEmailReaderModeForList();
+ _resetBulkSelectionForContextChange({ rerender: true });
+ const seq = ++_libSearchSeq;
+ const derived = _deriveSearchScope(state._libSearch);
+ const q = derived.q;
+ if (q.length < 2 && !derived.forced) {
+ // Empty or too short — restore the normal folder if a previous search
+ // had replaced the grid contents.
+ if (_libSearchHadResults) {
+ _libSearchHadResults = false;
+ state._libOffset = 0;
+ await _loadEmails({ useCache: true });
+ return;
+ }
+ _renderGrid();
+ return;
+ }
+ const accountAtStart = state._libAccountId || '';
+ const folderAtStart = derived.folder || state._libFolder || 'INBOX';
+ const serverScopeAtStart = derived.serverScope || 'all';
+ // No grid-blanking spinner — the local filter already painted something
+ // useful. Surface progress in the stats badge instead so the user knows
+ // the server search is still grinding.
+ const stats = document.getElementById('email-lib-stats');
+ const originalStatsText = stats?.textContent || '';
+ if (stats) stats.textContent = 'Searching…';
+ _libSearchInFlight = true;
+ _setEmailSyncStatus({ loading: true });
+ // Force a re-render so the "Searching…" empty-state shows (and any
+ // existing "No emails" gets replaced) while the fetch is in flight.
+ _renderGrid();
+
+ const stillCurrent = () => (
+ seq === _libSearchSeq &&
+ q === _deriveSearchScope(state._libSearch).q &&
+ accountAtStart === (state._libAccountId || '') &&
+ folderAtStart === (_deriveSearchScope(state._libSearch).folder || state._libFolder || 'INBOX') &&
+ // A local/index result can be opened while the slower provider search is
+ // still running. Do not let that second response re-render the grid and
+ // destroy the reader the user just opened.
+ !document.querySelector('#email-lib-grid .email-card-expanded')
+ );
+ const searchUrl = (localOnly = false) => {
+ const params = new URLSearchParams({
+ folder: folderAtStart,
+ q,
+ limit: '100',
+ scope: serverScopeAtStart,
+ });
+ if (accountAtStart) params.set('account_id', accountAtStart);
+ if (localOnly) params.set('local_only', '1');
+ return `${API_BASE}/api/email/search?${params.toString()}`;
+ };
+ const folderListUrl = () => {
+ const params = new URLSearchParams({
+ folder: folderAtStart,
+ limit: '100',
+ offset: '0',
+ filter: state._libFilter || 'all',
+ });
+ if (accountAtStart) params.set('account_id', accountAtStart);
+ return `${API_BASE}/api/email/list?${params.toString()}`;
+ };
+ const mergeSearchResults = (painted, incoming) => {
+ const byKey = new Map();
+ const out = [];
+ const add = (em) => {
+ if (!em) return;
+ const key = `${em.account_id || accountAtStart || ''}:${em.folder || folderAtStart || ''}:${em.uid || em.message_id || JSON.stringify(em)}`;
+ if (byKey.has(key)) return;
+ byKey.set(key, em);
+ out.push(em);
+ };
+ (painted || []).forEach(add);
+ const additions = [];
+ const addIncoming = (em) => {
+ if (!em) return;
+ const key = `${em.account_id || accountAtStart || ''}:${em.folder || folderAtStart || ''}:${em.uid || em.message_id || JSON.stringify(em)}`;
+ if (byKey.has(key)) return;
+ byKey.set(key, em);
+ additions.push(em);
+ };
+ (incoming || []).forEach(addIncoming);
+ additions.sort((a, b) => {
+ const ad = Number(a?.date_epoch || 0);
+ const bd = Number(b?.date_epoch || 0);
+ if (bd !== ad) return bd - ad;
+ return String(b?.date || '').localeCompare(String(a?.date || ''));
+ });
+ return out.concat(additions);
+ };
+ let paintedInterimResults = false;
+ const paintSearchData = (data, interim = false) => {
+ if (!stillCurrent()) return false;
+ if (data.error) throw new Error(data.error);
+ let results = data.emails || [];
+ if (!interim && paintedInterimResults) {
+ results = mergeSearchResults(state._libEmails || [], results);
+ }
+ if (!interim && paintedInterimResults && results.length === 0) {
+ if (stats) {
+ const count = state._libTotal || (state._libEmails || []).length;
+ stats.textContent = `${count} cached match${count === 1 ? '' : 'es'}`;
+ }
+ _setEmailSyncStatus({
+ updatedAt: data.sync?.updated_at || '',
+ source: data.sync?.source || data.source || '',
+ loading: false,
+ });
+ return true;
+ }
+ _libSearchHadResults = true;
+ const pills = state._libSearchPills || [];
+ const preservingBase = !!(_libServerSearchEmails && pills.length > 1);
+ if (!preservingBase) {
+ _libServerSearchEmails = results.slice();
+ _libServerSearchTotal = Math.max(Number(data.total || 0), results.length);
+ _libPreSearchEmails = results.slice();
+ _libPreSearchTotal = _libServerSearchTotal;
+ state._libEmails = results;
+ state._libTotal = _libServerSearchTotal;
+ } else {
+ state._libEmails = _libServerSearchEmails.slice();
+ state._libTotal = _libServerSearchTotal;
+ }
+ if (pills.length) {
+ _applyPillFilter();
+ if (!(state._libEmails || []).length && !preservingBase) state._libEmails = results;
+ }
+ _renderGrid();
+ const count = Math.max(Number(data.total || 0), results.length);
+ if (stats) {
+ if (interim) {
+ stats.textContent = `${count} cached match${count === 1 ? '' : 'es'} · searching…`;
+ } else {
+ const source = data.source === 'index' ? ' cached' : '';
+ stats.textContent = `${count}${source} match${count === 1 ? '' : 'es'}`;
+ }
+ }
+ _setEmailSyncStatus({
+ updatedAt: interim ? '' : (data.sync?.updated_at || ''),
+ source: data.sync?.source || data.source || '',
+ loading: interim,
+ });
+ if (interim && results.length) paintedInterimResults = true;
+ return true;
+ };
+
+ try {
+ if (q.length < 2 && derived.forced) {
+ const res = await fetch(folderListUrl());
+ const data = await res.json();
+ if (!stillCurrent()) return;
+ paintSearchData({
+ emails: (data.emails || []).map(em => ({ ...em, folder: folderAtStart })),
+ total: data.total || (data.emails || []).length,
+ source: 'folder',
+ sync: { source: 'folder' },
+ }, false);
+ return;
+ }
+ const fullSearchPromise = fetch(searchUrl(false)).then(res => res.json());
+ const localSearchPromise = fetch(searchUrl(true)).then(res => res.json());
+ try {
+ const localData = await localSearchPromise;
+ if (!stillCurrent()) return;
+ if (!localData.error && (localData.emails || []).length) {
+ paintSearchData(localData, true);
+ }
+ } catch (_) {
+ if (!stillCurrent()) return;
+ }
+
+ const data = await fullSearchPromise;
+ if (!stillCurrent()) return;
+ paintSearchData(data, false);
+ } catch (e) {
+ if (stats) stats.textContent = originalStatsText || 'Search failed';
+ try { console.error('[email-search] fetch failed:', e); } catch {}
+ } finally {
+ _libSearchInFlight = false;
+ _setEmailSyncStatus({ loading: false });
+ // If the full search was intentionally ignored because its result landed
+ // after the user opened a reader, finish the progress label without
+ // touching the grid or collapsing that reader.
+ const openReader = document.querySelector('#email-lib-grid .email-card-expanded');
+ if (openReader && stats && /searching/i.test(stats.textContent || '')) {
+ const count = state._libTotal || (state._libEmails || []).length;
+ stats.textContent = `${count} cached match${count === 1 ? '' : 'es'}`;
+ }
+ }
+ }
+
+ // Custom dropdown for the email filter (All/Unread/Favorites/...). Replaces
+ // the native <select> so each row can carry an SVG icon. The hidden
+ // <select id="email-lib-filter"> stays as the value source — clicking a
+ // menu item updates its value and dispatches 'change', so every existing
+ // listener keeps working.
+ const _EMAIL_FILTER_ICONS = {
+ 'all': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>',
+ 'unread': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><line x1="8" y1="16" x2="16" y2="8"/><line x1="8" y1="8" x2="16" y2="16"/></svg>',
+ 'favorites': '<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>',
+ 'undone': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="3"/></svg>',
+ 'reminders': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.268 21a2 2 0 0 0 3.464 0"/><path d="M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"/></svg>',
+ 'unanswered': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg>',
+ 'pending_30d': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>',
+ 'stale_30d': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="10" y1="14" x2="14" y2="18"/><line x1="14" y1="14" x2="10" y2="18"/></svg>',
+ 'tag:urgent': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
+ 'tag:reply-soon':'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/><circle cx="18" cy="6" r="2" fill="currentColor" stroke="none"/></svg>',
+ 'tag:spam': '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>',
+ };
+
+ function _filterIcon(value) {
+ return _EMAIL_FILTER_ICONS[value] || _EMAIL_FILTER_ICONS['all'];
+ }
+
+ function _folderIcon(value) {
+ const v = String(value || '').toLowerCase();
+ if (value === '__scheduled__') {
+ return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>';
+ }
+ if (v.includes('sent')) {
+ return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>';
+ }
+ if (v.includes('star') || v.includes('favorite')) {
+ return '<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>';
+ }
+ if (v.includes('archive') || v.includes('all mail')) {
+ return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="5" rx="1"/><path d="M5 9v10h14V9"/><path d="M10 13h4"/></svg>';
+ }
+ if (v.includes('junk') || v.includes('spam')) {
+ return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>';
+ }
+ if (v.includes('trash') || v.includes('bin')) {
+ return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>';
+ }
+ if (v.includes('draft')) {
+ return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>';
+ }
+ if (v === 'inbox' || v.includes('inbox')) {
+ return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11Z"/></svg>';
+ }
+ return '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>';
+ }
+
+ function _renderFolderPicker() {
+ const sel = document.getElementById('email-lib-folder');
+ const btn = document.getElementById('email-folder-btn');
+ const menu = document.getElementById('email-folder-menu');
+ if (!sel || !btn || !menu) return;
+ const value = sel.value || state._libFolder || 'INBOX';
+ const selectedOpt = [...sel.options].find(o => o.value === value && !o.disabled);
+ const label = selectedOpt?.textContent || folderDisplayName(value);
+ const iconWrap = btn.querySelector('.email-folder-current-icon');
+ const labelEl = btn.querySelector('.email-folder-label');
+ if (iconWrap) iconWrap.innerHTML = _folderIcon(value);
+ if (labelEl) labelEl.textContent = label;
+ const esc = s => String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
+ const rows = [];
+ for (const opt of sel.children) {
+ if (opt.disabled) {
+ rows.push('<div class="email-filter-group email-folder-group">Folders</div>');
+ continue;
+ }
+ rows.push(`<button type="button" role="option" class="email-filter-item email-folder-item" data-value="${esc(opt.value)}">
+ <span class="email-filter-item-icon">${_folderIcon(opt.value)}</span>
+ <span class="email-filter-item-label">${esc(opt.textContent || folderDisplayName(opt.value))}</span>
+ </button>`);
+ }
+ menu.innerHTML = rows.join('');
+ }
+
+ function _initFolderPicker() {
+ const sel = document.getElementById('email-lib-folder');
+ const picker = document.getElementById('email-folder-picker');
+ const btn = document.getElementById('email-folder-btn');
+ const menu = document.getElementById('email-folder-menu');
+ if (!sel || !picker || !btn || !menu || picker._wired) return;
+ picker._wired = true;
+ let dismiss = () => {};
+ const finishClose = () => {
+ menu.hidden = true;
+ btn.setAttribute('aria-expanded', 'false');
+ dismiss = () => {};
+ };
+ const open = () => {
+ const filterMenu = document.getElementById('email-filter-menu');
+ const filterBtn = document.getElementById('email-filter-btn');
+ filterMenu?._dismiss?.();
+ if (filterMenu && !filterMenu.hidden) filterMenu.hidden = true;
+ if (filterBtn) filterBtn.setAttribute('aria-expanded', 'false');
+ _renderFolderPicker();
+ menu.hidden = false;
+ btn.setAttribute('aria-expanded', 'true');
+ dismiss = bindMenuDismiss(menu, finishClose, e => !picker.contains(e.target));
+ };
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ if (menu.hidden) open(); else dismiss();
+ });
+ menu.addEventListener('click', (e) => {
+ const item = e.target.closest('.email-folder-item');
+ if (!item) return;
+ sel.value = item.dataset.value;
+ sel.dispatchEvent(new Event('change', { bubbles: true }));
+ dismiss();
+ });
+ document.addEventListener('click', (e) => {
+ if (!menu.hidden && !picker.contains(e.target)) dismiss();
+ });
+ _renderFolderPicker();
+ }
+
+ function _renderFilterPickerCurrent() {
+ const sel = document.getElementById('email-lib-filter');
+ const btn = document.getElementById('email-filter-btn');
+ if (!sel || !btn) return;
+ const value = sel.value || 'all';
+ const opt = sel.querySelector(`option[value="${CSS.escape(value)}"]`);
+ const label = opt ? opt.textContent : value;
+ const iconWrap = btn.querySelector('.email-filter-icon');
+ const labelEl = btn.querySelector('.email-filter-label');
+ if (iconWrap) iconWrap.innerHTML = _filterIcon(value);
+ if (labelEl) labelEl.textContent = label;
+ }
+
+ function _initFilterPicker() {
+ const sel = document.getElementById('email-lib-filter');
+ const picker = document.getElementById('email-filter-picker');
+ const btn = document.getElementById('email-filter-btn');
+ const menu = document.getElementById('email-filter-menu');
+ if (!sel || !picker || !btn || !menu || picker._wired) return;
+ picker._wired = true;
+
+ // Build menu from the hidden <select> contents (preserves optgroup labels).
+ const items = [];
+ for (const child of sel.children) {
+ if (child.tagName === 'OPTGROUP') {
+ items.push({ group: child.label });
+ for (const o of child.children) {
+ items.push({ value: o.value, label: o.textContent, group: child.label });
+ }
+ } else if (child.tagName === 'OPTION') {
+ items.push({ value: child.value, label: child.textContent });
+ }
+ }
+ menu.innerHTML = '<div class="email-filter-menu-title">Filter by...</div>' + items.map(it => {
+ if (!it.value) {
+ return `<div class="email-filter-group">${it.group}</div>`;
+ }
+ return `<button type="button" role="option" class="email-filter-item" data-value="${it.value}">
+ <span class="email-filter-item-icon">${_filterIcon(it.value)}</span>
+ <span class="email-filter-item-label">${it.label}</span>
+ </button>`;
+ }).join('');
+
+ let dismiss = () => {};
+ const finishClose = () => {
+ menu.hidden = true;
+ btn.setAttribute('aria-expanded', 'false');
+ dismiss = () => {};
+ };
+ const open = () => {
+ const folderMenu = document.getElementById('email-folder-menu');
+ const folderBtn = document.getElementById('email-folder-btn');
+ folderMenu?._dismiss?.();
+ if (folderMenu && !folderMenu.hidden) folderMenu.hidden = true;
+ if (folderBtn) folderBtn.setAttribute('aria-expanded', 'false');
+ menu.hidden = false;
+ btn.setAttribute('aria-expanded', 'true');
+ dismiss = bindMenuDismiss(menu, finishClose, e => !picker.contains(e.target));
+ };
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ if (menu.hidden) open(); else dismiss();
+ });
+ menu.addEventListener('click', (e) => {
+ const item = e.target.closest('.email-filter-item');
+ if (!item) return;
+ sel.value = item.dataset.value;
+ sel.dispatchEvent(new Event('change', { bubbles: true }));
+ dismiss();
+ });
+ document.addEventListener('click', (e) => {
+ if (!menu.hidden && !picker.contains(e.target)) dismiss();
+ });
+ _renderFilterPickerCurrent();
+ }
+
+ function _renderEmailLoading(grid) {
+ if (!grid) return null;
+ grid.innerHTML = '';
+ const wrap = document.createElement('div');
+ wrap.className = 'email-list-skeleton';
+ wrap.setAttribute('aria-label', 'Loading emails');
+ wrap.innerHTML = Array.from({ length: 8 }, (_, idx) => `
+ <div class="email-skeleton-row${idx % 3 === 2 ? ' compact' : ''}">
+ <span class="email-skeleton-dot"></span>
+ <div class="email-skeleton-lines">
+ <span class="email-skeleton-line title"></span>
+ <span class="email-skeleton-line meta"></span>
+ </div>
+ <span class="email-skeleton-line date"></span>
+ </div>
+ `).join('');
+ grid.appendChild(wrap);
+ return null;
+ }
+
+ export function _emailReaderSkeletonHtml() {
+ return `
+ <div class="email-reader-skeleton" aria-label="Loading email">
+ <div class="email-reader-skeleton-header">
+ <span class="email-skeleton-line chip"></span>
+ <span class="email-skeleton-line chip short"></span>
+ <span class="email-skeleton-line action"></span>
+ <span class="email-skeleton-line action"></span>
+ <span class="email-skeleton-line action"></span>
+ </div>
+ <div class="email-reader-skeleton-atts">
+ <span class="email-skeleton-line attachment"></span>
+ <span class="email-skeleton-line attachment short"></span>
+ </div>
+ <div class="email-reader-skeleton-body">
+ <span class="email-skeleton-line body wide"></span>
+ <span class="email-skeleton-line body"></span>
+ <span class="email-skeleton-line body medium"></span>
+ <span class="email-skeleton-line body gap"></span>
+ <span class="email-skeleton-line body wide"></span>
+ <span class="email-skeleton-line body medium"></span>
+ <span class="email-skeleton-line body"></span>
+ <span class="email-skeleton-line body wide"></span>
+ <span class="email-skeleton-line body medium"></span>
+ <span class="email-skeleton-line body gap"></span>
+ <span class="email-skeleton-line body"></span>
+ <span class="email-skeleton-line body wide"></span>
+ <span class="email-skeleton-line body short"></span>
+ </div>
+ </div>
+ `;
+ }
+
+ function _appendEmailSearchProgressRow(grid) {
+ if (!grid || !_libSearchInFlight || grid.querySelector('.email-search-progress-row')) return;
+ const row = document.createElement('div');
+ row.className = 'email-search-progress-row';
+ row.innerHTML = `
+ <span class="email-search-progress-dot"></span>
+ <span>Searching more mail...</span>
+ `;
+ grid.appendChild(row);
+ }
+
+ // Refreshes the small accent-pill in the modal title with the unread count
+ // for the current folder. When the inbox is currently filtered to unread, the
+ // pill flips to show the total-emails count + "all" label, because clicking
+ // it would toggle the filter off — so the label needs to advertise the
+ // action, not the now-current view. Uses the cheap unread-state endpoint for
+ // the normal badge; silent on failure.
+ export async function _refreshUnreadBadge({ unreadCountOverride = null, preserveAutoReplyTitle = false, syncAutoReplyTitle = false } = {}) {
+ const badge = document.getElementById('email-lib-unread-badge');
+ if (!badge) return;
+ const refreshSeq = ++state._autoReplyRefreshSeq;
+ const accountAtStart = String(state._libAccountId || '');
+ try {
+ const folder = state._libFolder || 'INBOX';
+ const autoReplyBadge = document.getElementById('email-lib-auto-reply-badge');
+ if (folder === '__scheduled__') {
+ badge.style.display = 'none';
+ if (syncAutoReplyTitle && !preserveAutoReplyTitle) _syncEmailAutoReplyTitle(false);
+ return;
+ }
+ const cfg = await _fetchEmailSettingsConfig().catch(() => null);
+ // Several mailbox/account refreshes can overlap while the settings page
+ // is saving. Do not let an older response restore the previous account's
+ // Auto Reply state after the current account has already changed.
+ if (refreshSeq !== state._autoReplyRefreshSeq || accountAtStart !== String(state._libAccountId || '')) return;
+ if (!cfg) return;
+ const awayActive = _isAutoReplyActiveForCurrentAccount(cfg);
+ if (!preserveAutoReplyTitle) {
+ const awayChanged = state._libAutoReplyActive !== awayActive;
+ state._libAutoReplyActive = awayActive;
+ if (awayChanged) _renderAccountsStrip();
+ if (syncAutoReplyTitle && typeof state._libAutoReplyDraftActive !== 'boolean') {
+ _syncEmailAutoReplyTitle(awayActive);
+ }
+ }
+ if (autoReplyBadge) {
+ autoReplyBadge.title = awayActive ? 'Auto Reply is active - open settings' : 'Auto Reply is off';
+ }
+ let n;
+ if (unreadCountOverride !== null && unreadCountOverride !== undefined) {
+ n = Math.max(0, Number(unreadCountOverride) || 0);
+ } else {
+ const res = await fetch(emailApiUrl('/api/email/unread-state', {
+ folder,
+ account_id: state._libAccountId || undefined,
+ }));
+ const data = await res.json();
+ n = data.unread_count || 0;
+ }
+ _syncUnreadTabBadge(n);
+ if (folder === 'INBOX') _syncCurrentAccountUnreadCount(n);
+ badge.classList.remove('email-lib-away-badge');
+ if (state._libFilter === 'unread') {
+ // Currently viewing unread — show what the click will take you to.
+ try {
+ const allRes = await fetch(`${API_BASE}/api/email/list?folder=${encodeURIComponent(folder)}${_acct()}&limit=1&filter=all`);
+ const allData = await allRes.json();
+ const t = allData.total || 0;
+ badge.textContent = `${t} all`;
+ badge.title = 'Show all emails';
+ badge.dataset.mode = 'unread';
+ badge.style.display = '';
+ } catch (_) {
+ badge.textContent = 'Show all';
+ badge.title = 'Show all emails';
+ badge.dataset.mode = 'unread';
+ badge.style.display = '';
+ }
+ } else if (n > 0) {
+ badge.textContent = n > 999 ? '999+ unread' : `${n} unread`;
+ badge.title = 'Show unread emails';
+ badge.dataset.mode = 'unread';
+ badge.style.display = '';
+ } else {
+ delete badge.dataset.mode;
+ badge.style.display = 'none';
+ }
+ } catch (_) { _syncUnreadTabBadge(0); }
+ }
+
+ export async function _loadEmails({ force = false, useCache = true } = {}) {
+ const seq = ++_libLoadSeq;
+ state._libLoading = true;
+ const accountAtStart = state._libAccountId || '';
+ const folderAtStart = state._libFolder;
+ const filterAtStart = state._libFilter;
+ const offsetAtStart = state._libOffset;
+ const searchAtStart = state._libSearch;
+ const hasAttachmentsAtStart = state._libHasAttachments;
+ const dateFromAtStart = state._libDateFrom || '';
+ const dateToAtStart = state._libDateTo || '';
+
+ const grid = document.getElementById('email-lib-grid');
+ if (!grid) { if (seq === _libLoadSeq) state._libLoading = false; return; }
+
+ // SWR: when loading the first page of a real folder with no search,
+ // paint the cached list immediately (no spinner, no blank grid) and
+ // then quietly refetch behind it. Pagination, search, and the
+ // scheduled virtual folder skip the cache and use the old spinner
+ // path. `force` (Refresh button) can still consult the cache for
+ // perceptual continuity, but adds a cache-buster so the server's 8s
+ // list cache is bypassed too. Account/folder/filter changes pass
+ // `useCache: false` so stale rows from the previous view never flash.
+ const cacheable =
+ offsetAtStart === 0 &&
+ !searchAtStart &&
+ folderAtStart !== '__scheduled__';
+ const ck = cacheable ? _libCacheKey() : null;
+ const cachedCandidate = (useCache && cacheable) ? _libCacheGet(ck) : null;
+ // Do not paint a cached empty result while a forced refresh is already
+ // underway. A transient provider failure can cache an empty tag filter;
+ // rendering it first flashes "No emails" before the fresh rows arrive.
+ const cached = cachedCandidate
+ && Array.isArray(cachedCandidate.emails)
+ && cachedCandidate.emails.length
+ ? cachedCandidate
+ : null;
+ let paintedExisting = Boolean(cached || state._libEmails.length);
+ const paintData = (data, { cacheSource = false } = {}) => {
+ state._libEmails = data.emails || [];
+ state._libTotal = data.total || 0;
+ _libRenderedViewKey = ck || '';
+ const sync = data.sync || {};
+ const _activePills = (state._libSearchPills || []).length > 0
+ || (state._libSearchDraft || '').length > 0;
+ if (_activePills) {
+ _libPreSearchEmails = state._libEmails.slice();
+ _libPreSearchTotal = state._libTotal;
+ _applyPillFilter();
+ } else {
+ _renderGrid();
+ }
+ const stats = document.getElementById('email-lib-stats');
+ if (stats) stats.textContent = `${state._libTotal} emails`;
+ _setEmailSyncStatus({
+ updatedAt: sync.updated_at || '',
+ source: sync.source || (cacheSource ? 'client_cache' : ''),
+ loading: false,
+ });
+ if (cacheable && !cacheSource) {
+ _libCachePut(ck, { emails: state._libEmails.slice(), total: state._libTotal, sync });
+ }
+ };
+
+ let sp = null;
+ if (cached) {
+ // Suppress the open-cascade animation when we're painting from
+ // cache — the data was already on screen a moment ago, so sliding
+ // each card in fresh feels janky. Also prevents the cascade from
+ // re-firing when the bg refetch lands within the 900ms cleanup
+ // window and appends new card nodes into the still-classed grid.
+ state._libJustOpened = false;
+ const grid2 = document.getElementById('email-lib-grid');
+ if (grid2) grid2.classList.remove('email-lib-just-opened');
+ paintData(cached, { cacheSource: true });
+ paintedExisting = true;
+ if (force) _setEmailSyncStatus({ loading: true });
+ if (!force) return;
+ } else if (state._libEmails.length && cacheable) {
+ _renderGrid();
+ _setEmailSyncStatus({ loading: true });
+ paintedExisting = true;
+ } else {
+ sp = _renderEmailLoading(grid);
+ }
+
+ try {
+ _syncUnreadWindowGlow();
+ if (folderAtStart === '__scheduled__') {
+ await _loadScheduled(grid, sp);
+ } else {
+ const accountQS = accountAtStart ? `&account_id=${encodeURIComponent(accountAtStart)}` : '';
+ const attQS = hasAttachmentsAtStart ? '&has_attachments=1' : '';
+ const dateQS = `${dateFromAtStart ? `&date_from=${encodeURIComponent(dateFromAtStart)}` : ''}${dateToAtStart ? `&date_to=${encodeURIComponent(dateToAtStart)}` : ''}`;
+ if (!cached && cacheable && !force) {
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), 450);
+ try {
+ const fastRes = await fetch(`${API_BASE}/api/email/list?folder=${encodeURIComponent(folderAtStart)}${accountQS}&limit=${_LIB_INITIAL_PAGE_SIZE}&offset=${offsetAtStart}&filter=${filterAtStart}${attQS}&cached_only=1`, {
+ signal: ctrl.signal,
+ });
+ const fastData = await fastRes.json().catch(() => null);
+ if (seq === _libLoadSeq
+ && accountAtStart === (state._libAccountId || '')
+ && fastData
+ && !fastData.error
+ && Array.isArray(fastData.emails)
+ && fastData.emails.length) {
+ if (sp) { sp.destroy(); sp = null; }
+ state._libJustOpened = false;
+ grid.classList.remove('email-lib-just-opened');
+ paintData(fastData);
+ paintedExisting = true;
+ if (!force) return;
+ }
+ } catch (_) {
+ // Cold index miss/timeout: leave the spinner and continue to IMAP.
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+ // `refresh=1` is the explicit manual-refresh contract: the server
+ // evicts its list cache, drops the pooled IMAP handle, and refetches
+ // visible rows instead of trusting the durable index. `&_=...` remains
+ // as a browser/proxy cache-buster.
+ const buster = force ? `&refresh=1&_=${Date.now()}` : '';
+ const res = await fetch(`${API_BASE}/api/email/list?folder=${encodeURIComponent(folderAtStart)}${accountQS}&limit=${_LIB_INITIAL_PAGE_SIZE}&offset=${offsetAtStart}&filter=${filterAtStart}${attQS}${dateQS}${buster}`);
+ const data = await res.json();
+ if (seq !== _libLoadSeq || accountAtStart !== (state._libAccountId || '')) return;
+ if (data.error) throw new Error(data.error);
+ const sync = data.sync || {};
+ if (sp) sp.destroy();
+ paintData({ emails: data.emails || [], total: data.total || 0, sync });
+ if (filterAtStart === 'unread') {
+ _refreshUnreadBadge({ unreadCountOverride: data.total || 0 });
+ } else {
+ _refreshUnreadBadge();
+ _refreshAccountUnreadHighlights().catch(() => {});
+ }
+ }
+ } catch (e) {
+ if (seq !== _libLoadSeq || accountAtStart !== (state._libAccountId || '')) return;
+ if (sp) sp.destroy();
+ // If we already painted the cached list, leave it on screen — beats
+ // wiping it for "Failed to load" when there's still readable content.
+ if (!paintedExisting) {
+ const msg = e && e.message ? `Failed to load: ${e.message}` : 'Failed to load';
+ grid.innerHTML = `<div class="email-loading">${_esc(msg)}${_emailSetupHintHtml()}</div>`;
+ _wireEmailSetupHint(grid);
+ }
+ } finally {
+ if (seq === _libLoadSeq) state._libLoading = false;
+ }
+ }
+
+ async function _loadScheduled(grid, sp) {
+ const res = await fetch(`${API_BASE}/api/email/scheduled`);
+ const data = await res.json();
+ if (sp) sp.destroy();
+ const items = data.scheduled || [];
+ grid.innerHTML = '';
+ const stats = document.getElementById('email-lib-stats');
+ if (stats) stats.textContent = `${items.length} scheduled`;
+ _setEmailSyncStatus({
+ updatedAt: new Date().toISOString(),
+ source: 'local',
+ loading: false,
+ });
+
+ if (items.length === 0) {
+ grid.innerHTML = '<div class="email-loading">No scheduled emails</div>';
+ return;
+ }
+
+ for (const it of items) {
+ const card = document.createElement('div');
+ card.className = 'doclib-card memory-item';
+
+ const sendDate = new Date(it.send_at);
+ const dateStr = sendDate.toLocaleString([], {
+ month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'
+ });
+
+ const content = document.createElement('div');
+ content.style.cssText = 'flex:1;min-width:0;';
+ const subject = it.subject || '(no subject)';
+ const toDisplay = it.to || '(no recipient)';
+
+ content.innerHTML = `
+ <div style="display:flex;align-items:center;gap:6px;">
+ <span class="memory-item-title">${_esc(subject)}</span>
+ ${it.status === 'failed' ? '<span style="font-size:9px;color:var(--red);border:1px solid var(--red);padding:1px 4px;border-radius:4px;">FAILED</span>' : '<span style="font-size:9px;opacity:0.6;border:1px solid var(--border);padding:1px 4px;border-radius:4px;">PENDING</span>'}
+ </div>
+ <div style="font-size:10px;opacity:0.7;margin-top:2px;">
+ To: ${_esc(toDisplay)} · Sends ${_esc(dateStr)}
+ </div>
+ ${it.error ? `<div style="font-size:10px;color:var(--red);margin-top:2px;">${_esc(it.error)}</div>` : ''}
+ `;
+ card.appendChild(content);
+
+ // Cancel button
+ const cancelBtn = document.createElement('button');
+ cancelBtn.className = 'memory-item-btn';
+ cancelBtn.title = 'Cancel scheduled send';
+ cancelBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
+ cancelBtn.addEventListener('click', async (e) => {
+ e.stopPropagation();
+ const { styledConfirm } = await import('../ui.js?v=20260916largetoolscroll1');
+ const ok = await styledConfirm(`Cancel scheduled email "${subject}"?`, { confirmText: 'Cancel Send', cancelText: 'Keep', danger: true });
+ if (!ok) return;
+ try {
+ await fetch(`${API_BASE}/api/email/scheduled/${it.id}`, { method: 'DELETE' });
+ _loadEmails();
+ } catch (err) { console.error(err); }
+ });
+ const actionsWrap = document.createElement('div');
+ actionsWrap.className = 'memory-item-actions';
+ actionsWrap.appendChild(cancelBtn);
+ card.appendChild(actionsWrap);
+
+ grid.appendChild(card);
+ }
+ }
+
+ function _emailDateBucketLabel(value) {
+ if (!value) return 'Older';
+ const d = new Date(value);
+ if (Number.isNaN(d.getTime())) return 'Older';
+ const dayStart = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
+ const now = new Date();
+ const today = dayStart(now);
+ const day = dayStart(d);
+ const diff = Math.round((today - day) / 86400000);
+ if (diff === 0) return 'Today';
+ if (diff === 1) return 'Yesterday';
+ if (diff > 1 && diff < 7) return d.toLocaleDateString([], { weekday: 'long' });
+ if (diff >= 365) {
+ const years = Math.floor(diff / 365);
+ return `${years} ${years === 1 ? 'year' : 'years'} ago`;
+ }
+ if (diff >= 180) return '6 months ago';
+ if (diff >= 30) return `${Math.floor(diff / 30) * 30} days ago`;
+ const sameYear = d.getFullYear() === now.getFullYear();
+ return d.toLocaleDateString([], sameYear ? { month: 'long', day: 'numeric' } : { month: 'long', day: 'numeric', year: 'numeric' });
+ }
+
+ function _createEmailDateHeader(label, timelineBreak = false) {
+ const el = document.createElement('div');
+ el.className = 'date-section-header email-date-section-header' + (timelineBreak ? ' email-date-gap-break' : '');
+ el.textContent = label;
+ return el;
+ }
+
+ // Add breathing room only for an unexpected hole in an otherwise dense
+ // timeline. A uniformly sparse archive should remain compact, even when its
+ // dates are months apart.
+ function _emailTimelineGapThreshold(items) {
+ const dates = items.map(em => new Date(em?.date).getTime()).filter(Number.isFinite);
+ const gaps = [];
+ for (let i = 1; i < dates.length; i++) {
+ const gap = Math.abs(dates[i - 1] - dates[i]) / 86400000;
+ if (gap > 0) gaps.push(gap);
+ }
+ if (!gaps.length) return 90;
+ gaps.sort((a, b) => a - b);
+ const middle = Math.floor(gaps.length / 2);
+ const median = gaps.length % 2 ? gaps[middle] : (gaps[middle - 1] + gaps[middle]) / 2;
+ return Math.max(90, median * 2.5);
+ }
+
+ function _dateGroupEmailsWithPinned(items, mode = 'recent') {
+ const ordered = [];
+ let groupLabel = null;
+ let groupItems = [];
+ const priority = (em) => {
+ if (mode === 'unread') return Number(!em?.is_read);
+ return Number(!!em?.is_flagged);
+ };
+ const flushGroup = () => {
+ if (!groupItems.length) return;
+ ordered.push(...groupItems.map((em, idx) => ({ em, idx }))
+ .sort((a, b) => priority(b.em) - priority(a.em) || a.idx - b.idx)
+ .map(item => item.em));
+ groupItems = [];
+ };
+ for (const em of items) {
+ const label = _emailDateBucketLabel(em?.date);
+ if (label !== groupLabel) {
+ flushGroup();
+ groupLabel = label;
+ }
+ groupItems.push(em);
+ }
+ flushGroup();
+ return ordered;
+ }
+
+ export function _renderGrid() {
+ const grid = document.getElementById('email-lib-grid');
+ if (!grid) return;
+ const modal = document.getElementById('email-lib-modal');
+ // A background mailbox refresh must not destroy the reader currently being
+ // viewed. Clearing the grid here removes the expanded card while leaving
+ // `.email-reading` on the modal, which produces a headerless full email
+ // list. Explicit folder/account/search changes call the reset helper first.
+ if (grid.querySelector('.doclib-card-expanded, .email-card-expanded')) return;
+ if (modal?.classList.contains('email-reading')) {
+ modal.classList.remove('email-reading');
+ modal.style.removeProperty('--email-reading-modal-min-h');
+ }
+ grid.innerHTML = '';
+
+ let filtered = state._libEmails;
+ try { console.log('[email-search] _renderGrid: state._libEmails.length=', (state._libEmails || []).length, 'pills=', (state._libSearchPills || []).length, 'draft=', JSON.stringify(state._libSearchDraft || ''), 'libSearch=', JSON.stringify(state._libSearch || '')); } catch {}
+ _syncSearchOptionsMenu();
+
+ // 'recent' is the default order from the API. Date stays the primary
+ // grouping; unread/favorite priorities float inside each date section.
+ filtered = _dateGroupEmailsWithPinned([...filtered], state._libSort);
+
+ if (filtered.length === 0) {
+ // Active search — don't flash "No emails": the IMAP fetch is still
+ // running. Show a "Searching…" placeholder until _doSearch resolves
+ // and renders again. Without this the user saw an empty state
+ // smiley for ~500ms between the optimistic pill-filter clear and
+ // the server response landing.
+ if (_libSearchInFlight) {
+ _renderEmailLoading(grid);
+ return;
+ }
+ // Inbox-zero is a win — pair the message with a small smiley so the
+ // empty state reads as "all caught up", not "something's broken".
+ const _smileyIco = '<span style="vertical-align:-3px;margin-left:6px;">' + emptyStateIcon('smiley') + '</span>';
+ // Only show the "Set up at Settings › Integrations" hint when the inbox
+ // is TRULY empty — no filter, no search, no source emails. A sub-filter
+ // (reminders, unread, etc.) that happens to be empty isn't a setup
+ // problem; the link there reads as nonsense.
+ const _isTrulyEmpty = (
+ state._libEmails.length === 0
+ && (!state._libFilter || state._libFilter === 'all')
+ && !(state._libSearch || '').trim()
+ );
+ if (_isTrulyEmpty) {
+ grid.innerHTML =
+ '<div class="email-loading" style="display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;text-align:center;">' +
+ '<span>No emails' + _smileyIco + '</span>' +
+ '<span style="opacity:0.7;font-size:11px;">' +
+ 'Set up at: <a href="#" data-open-settings="integrations" style="color:var(--accent,var(--red));text-decoration:underline;">Settings &rsaquo; Integrations</a>' +
+ '</span>' +
+ '</div>';
+ const _link = grid.querySelector('[data-open-settings]');
+ if (_link) _link.addEventListener('click', (e) => {
+ e.preventDefault();
+ _openSettingsTab(_link.dataset.openSettings || 'integrations');
+ });
+ } else {
+ grid.innerHTML =
+ '<div class="email-loading" style="display:flex;align-items:center;justify-content:center;gap:8px;flex-wrap:wrap;">' +
+ '<span>No emails' + _smileyIco + '</span>' +
+ '</div>';
+ }
+ return;
+ }
+
+ // Cascade-on-open: fire the same domino-in animation the sidebar
+ // section uses. Only on the FIRST grid render after the library is
+ // opened — subsequent re-renders (filter/sort/search) need to be
+ // instant.
+ if (state._libJustOpened) {
+ grid.classList.add('email-lib-just-opened');
+ state._libJustOpened = false;
+ // Strip the class after the cascade so it doesn't restrict later
+ // animations (e.g. the FLIP reflow when archiving). Worst-case
+ // duration matches the longest delay in the keyframe set below.
+ setTimeout(() => grid.classList.remove('email-lib-just-opened'), 900);
+ }
+ let lastDateLabel = null;
+ const timelineGapThreshold = _emailTimelineGapThreshold(filtered);
+ let previousEmailTime = null;
+ for (const em of filtered) {
+ const dateLabel = _emailDateBucketLabel(em?.date);
+ if (dateLabel !== lastDateLabel) {
+ const emailTime = new Date(em?.date).getTime();
+ const gapDays = Number.isFinite(previousEmailTime) && Number.isFinite(emailTime)
+ ? Math.abs(previousEmailTime - emailTime) / 86400000
+ : 0;
+ const timelineBreak = gapDays > 90 && gapDays > timelineGapThreshold;
+ grid.appendChild(_createEmailDateHeader(dateLabel, timelineBreak));
+ lastDateLabel = dateLabel;
+ }
+ grid.appendChild(_createCard(em));
+ const emailTime = new Date(em?.date).getTime();
+ if (Number.isFinite(emailTime)) previousEmailTime = emailTime;
+ }
+ _appendEmailSearchProgressRow(grid);
+
+ // If a deep-link asked us to expand a specific email, do it when the card
+ // exists. Keep the UID through cached paints so a later fresh load can
+ // still expand a newly-sent message that was absent from the cache.
+ if (state._libPendingExpandUid) {
+ const target = filtered.find(e => String(e.uid) === String(state._libPendingExpandUid));
+ const wantUid = state._libPendingExpandUid;
+ if (target) {
+ const cards = grid.querySelectorAll('.doclib-card');
+ const targetCard = Array.from(cards).find(c => c.dataset.uid === String(wantUid));
+ if (targetCard) {
+ state._libPendingExpandUid = null;
+ requestAnimationFrame(() => _toggleCardPreview(targetCard, target));
+ }
+ }
+ }
+ }
+
+ function _createCard(em) {
+ _normalizeEmailStateFlags(em);
+ const card = document.createElement('div');
+ let cls = 'doclib-card memory-item';
+ if (em.is_answered) cls += ' email-card-answered';
+ else if (!em.is_read) cls += ' email-card-unread';
+ card.className = cls;
+ card.dataset.uid = String(em.uid);
+ card.dataset.emailAccount = String(em.account_id || state._libAccountId || '');
+ const cardFolder = _hasActiveEmailSearchResults()
+ ? (em.folder || state._libFolder || 'INBOX')
+ : (state._libFolder || em.folder || 'INBOX');
+ card.dataset.emailFolder = String(cardFolder);
+ if (state._selectMode && state._selectedUids.has(em.uid)) card.classList.add('selected');
+
+ // Checkbox in select mode
+ if (state._selectMode) {
+ const cb = document.createElement('input');
+ cb.type = 'checkbox';
+ cb.className = 'memory-select-cb';
+ cb.checked = state._selectedUids.has(em.uid);
+ cb.addEventListener('click', e => e.stopPropagation());
+ cb.addEventListener('change', () => {
+ if (cb.checked) state._selectedUids.add(em.uid);
+ else state._selectedUids.delete(em.uid);
+ card.classList.toggle('selected', cb.checked);
+ _updateBulkBar();
+ });
+ card.appendChild(cb);
+ }
+
+ // In Sent results, show the recipient(s) — the sender is always you and
+ // hides the actually useful info. Search results can be stamped with their
+ // real folder while the visible folder selector still says INBOX, so the
+ // selected mailbox remains authoritative for normal folder views.
+ const isSentFolderEarly = /sent/i.test(cardFolder);
+ let senderName;
+ let senderAddress;
+ if (isSentFolderEarly) {
+ senderName = _formatRecipients(em.to) || em.to || '(no recipient)';
+ // First address out of em.to for click-to-pill targeting.
+ const _firstTo = String(em.to || '').split(',')[0] || '';
+ const _m = _firstTo.match(/<([^>]+)>/);
+ senderAddress = (_m ? _m[1] : _firstTo).trim();
+ } else {
+ senderName = em.from_name || em.from_address;
+ senderAddress = em.from_address || '';
+ }
+ const color = _senderColor(senderName);
+
+ let dateStr = '';
+ if (em.date) {
+ try {
+ const d = new Date(em.date);
+ const now = new Date();
+ const sameYear = d.getFullYear() === now.getFullYear();
+ const dateOpts = sameYear
+ ? { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }
+ : { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' };
+ dateStr = d.toLocaleString([], dateOpts);
+ } catch (_) {}
+ }
+
+ const content = document.createElement('div');
+ content.style.cssText = 'flex:1;min-width:0;';
+
+ const titleRow = document.createElement('div');
+ titleRow.className = 'email-card-titlerow';
+ titleRow.style.cssText = 'display:flex;align-items:center;gap:6px;';
+
+ const titleEl = document.createElement('span');
+ titleEl.className = 'memory-item-title';
+ titleEl.textContent = em.subject || '(no subject)';
+ // Hover preview: surface the cached AI summary directly on the title via
+ // a native browser tooltip — no need to open the email to skim it.
+ if (em.cached_summary) {
+ titleEl.title = em.cached_summary;
+ titleEl.classList.add('email-card-has-summary');
+ }
+ titleRow.appendChild(titleEl);
+ const cardChevron = document.createElement('span');
+ cardChevron.className = 'doclib-card-chevron';
+ cardChevron.setAttribute('aria-hidden', 'true');
+ cardChevron.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>';
+
+ const isSentFolder = /sent/i.test(cardFolder);
+ const statusCluster = document.createElement('span');
+ statusCluster.className = 'email-card-status';
+ statusCluster.setAttribute('aria-label', 'Email status');
+
+ if (em.has_attachments) {
+ const att = document.createElement('span');
+ att.className = 'email-card-attachment';
+ att.title = 'Has attachments';
+ att.style.cssText = 'opacity:0.6;flex-shrink:0;display:inline-flex;';
+ att.innerHTML = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 17.93 8.8l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>';
+ statusCluster.appendChild(att);
+ }
+
+ const tags = state._libShowTags ? _visibleEmailTagsForRender(em) : [];
+ if (state._libShowTags && (tags.length || em.is_spam_verdict)) {
+ const tagWrap = document.createElement('span');
+ tagWrap.className = 'email-tags email-card-tags' + (tags.length > 2 ? ' email-tags-collapsed' : '');
+ tagWrap.innerHTML = _emailTagGroupHtml(tags, em);
+ if (em.is_spam_verdict) {
+ tagWrap.insertAdjacentHTML('beforeend', '<span class="email-tag email-tag-spam">spam</span>');
+ }
+ let moreBtn = tagWrap.querySelector('[data-email-tags-more]');
+ if (moreBtn) {
+ const tintSource = tagWrap.querySelector('.email-tag');
+ requestAnimationFrame(() => {
+ if (tintSource?.isConnected) moreBtn.style.setProperty('--email-tags-more-color', getComputedStyle(tintSource).color);
+ });
+ }
+ tagWrap.addEventListener('click', (ev) => {
+ if (state._selectMode) return;
+ const calBtn = ev.target.closest('[data-calendar-event-uid]');
+ const tagBtn = ev.target.closest('[data-email-filter-tag]');
+ const moreBtn = ev.target.closest('[data-email-tags-more]');
+ if (!calBtn && !tagBtn && !moreBtn) return;
+ ev.preventDefault();
+ ev.stopPropagation();
+ if (moreBtn) {
+ const expanded = tagWrap.classList.toggle('email-tags-expanded');
+ moreBtn.setAttribute('aria-expanded', expanded ? 'true' : 'false');
+ const pills = tagWrap.querySelectorAll(':scope > .email-tag, :scope > .email-tag-extra');
+ if (expanded) {
+ tagWrap.style.flexWrap = 'wrap';
+ pills.forEach(pill => { pill.style.display = 'inline-flex'; });
+ moreBtn.style.display = 'inline-flex';
+ } else {
+ tagWrap.style.flexWrap = '';
+ pills.forEach(pill => { pill.style.display = ''; });
+ moreBtn.style.display = '';
+ requestAnimationFrame(() => _fitEmailCardTags(titleRow));
+ }
+ } else if (calBtn) _openCalendarEventFromEmail(calBtn.dataset.calendarEventUid);
+ else _applyTagFilterFromPill(tagBtn.dataset.emailFilterTag);
+ });
+ titleRow.appendChild(tagWrap);
+ }
+
+ // Keep the status controls in one right-aligned cluster. Favorite is always
+ // present as an outline so it is discoverable before activation.
+ if (!isSentFolder) {
+ const doneCheck = document.createElement('span');
+ doneCheck.className = 'email-card-done' + (em.is_answered ? ' active' : '');
+ doneCheck.title = em.is_answered ? 'Mark not done' : 'Mark done';
+ doneCheck.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
+ const _toggleDone = async (e) => {
+ if (e) e.stopPropagation();
+ // Use the visible class as source of truth — em.is_answered could
+ // be stale from a background sync, which would leave the user
+ // clicking and seeing no UI change.
+ const wasActive = doneCheck.classList.contains('active');
+ const newState = !wasActive;
+ em.is_answered = newState;
+ doneCheck.classList.toggle('active', newState);
+ doneCheck.title = newState ? 'Mark not done' : 'Mark done';
+ // Animate in both directions so the user gets explicit feedback when
+ // un-checking too — without this the hover state and the active state
+ // look identical, so the click felt like a no-op.
+ doneCheck.classList.remove('just-checked', 'just-unchecked');
+ void doneCheck.offsetWidth; // restart animation
+ doneCheck.classList.add(newState ? 'just-checked' : 'just-unchecked');
+ setTimeout(() => doneCheck.classList.remove('just-checked', 'just-unchecked'), 500);
+ if (newState) {
+ _clearDoneResponseTagsLocal(em);
+ titleRow.querySelectorAll('.email-tag-urgent, .email-tag-reply-soon, .email-tag-action-needed').forEach(n => n.remove());
+ _syncEmailReadState(em.uid, true);
+ }
+ try {
+ if (newState) {
+ await fetch(`${API_BASE}/api/email/mark-answered/${em.uid}?folder=${encodeURIComponent(cardFolder)}${_acct()}`, { method: 'POST' });
+ await fetch(`${API_BASE}/api/email/mark-read/${em.uid}?folder=${encodeURIComponent(cardFolder)}${_acct()}`, { method: 'POST' });
+ } else {
+ await fetch(`${API_BASE}/api/email/clear-answered/${em.uid}?folder=${encodeURIComponent(cardFolder)}${_acct()}`, { method: 'POST' });
+ }
+ } catch (err) { console.error(err); }
+ };
+ doneCheck.addEventListener('click', _toggleDone);
+ statusCluster.appendChild(doneCheck);
+ }
+
+ const favoriteToggle = document.createElement('button');
+ favoriteToggle.type = 'button';
+ favoriteToggle.className = 'email-card-favorite' + (em.is_flagged ? ' active' : '');
+ favoriteToggle.title = em.is_flagged ? 'Unfavorite' : 'Favorite';
+ favoriteToggle.setAttribute('aria-label', favoriteToggle.title);
+ favoriteToggle.setAttribute('aria-pressed', em.is_flagged ? 'true' : 'false');
+ favoriteToggle.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="' + (em.is_flagged ? 'currentColor' : 'none') + '" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>';
+ favoriteToggle.addEventListener('click', async (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const next = !em.is_flagged;
+ const favoritesView = state._libFilter === 'favorites';
+ const previousIndex = state._libEmails.findIndex(item => item === em);
+ em.is_flagged = next;
+ // The Favorites mailbox is already a server-filtered snapshot. Remove an
+ // unfavorited row locally so the click has immediate, visible feedback.
+ if (favoritesView && !next) {
+ state._libEmails = state._libEmails.filter(item => item !== em);
+ }
+ _renderGrid();
+ try {
+ const res = await fetch(`${API_BASE}/api/email/flag/${em.uid}?folder=${encodeURIComponent(cardFolder)}${_acct()}&on=${next ? 'true' : 'false'}`, { method: 'POST' });
+ const data = await res.json().catch(() => null);
+ if (!res.ok || data?.success === false) throw new Error(data?.error || `HTTP ${res.status}`);
+ _libCacheWriteBack();
+ } catch (err) {
+ em.is_flagged = !next;
+ if (favoritesView && !next && previousIndex >= 0) {
+ state._libEmails.splice(previousIndex, 0, em);
+ }
+ _renderGrid();
+ console.error('Failed to toggle favorite:', err);
+ }
+ });
+ const doneControl = statusCluster.querySelector('.email-card-done');
+ if (doneControl) statusCluster.insertBefore(favoriteToggle, doneControl);
+ else statusCluster.appendChild(favoriteToggle);
+
+ if (!isSentFolder && !em.is_read) {
+ const dot = document.createElement('span');
+ dot.className = 'email-card-unread-dot';
+ dot.style.cssText = `width:6px;height:6px;border-radius:50%;background:${color};flex-shrink:0;margin-left:2px;`;
+ statusCluster.appendChild(dot);
+ }
+ titleRow.appendChild(statusCluster);
+ requestAnimationFrame(() => _fitEmailCardTags(titleRow));
+ _emailTagFitObserver?.observe(titleRow);
+
+ // Prev/next arrows — visible only when this card is the expanded one
+ // (CSS-gated so collapsed cards stay clean). Click navigates by collapsing
+ // this card and expanding the neighbour.
+ const navArrows = document.createElement('span');
+ navArrows.className = 'email-card-nav-arrows';
+ navArrows.innerHTML = `
+ <button type="button" class="email-card-nav-btn" data-nav-dir="-1" title="Previous email"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg></button>
+ <button type="button" class="email-card-nav-btn" data-nav-dir="1" title="Next email"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg></button>
+ `;
+ navArrows.addEventListener('click', async (ev) => {
+ const btn = ev.target.closest('.email-card-nav-btn');
+ if (!btn || btn.disabled) return;
+ ev.stopPropagation();
+ const card = navArrows.closest('.doclib-card');
+ if (!card) return;
+ const dir = parseInt(btn.dataset.navDir, 10);
+ const sibling = _findSiblingEmailCard(card, dir);
+ if (!sibling) return;
+ const nextEm = state._libEmails.find(e => String(e.uid) === String(sibling.dataset.uid));
+ if (!nextEm) return;
+ await _toggleCardPreview(card, em);
+ await _toggleCardPreview(sibling, nextEm);
+ sibling.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
+ });
+ // Keep navigation in the same status row as Favorite and Done. The
+ // per-card `.memory-item-actions` menu
+ // at the bottom of the card stays visible while expanded (see the CSS
+ // override below), so duplicating it in the header was redundant.
+ statusCluster.appendChild(navArrows);
+
+ content.appendChild(titleRow);
+
+ const meta = document.createElement('div');
+ meta.className = 'memory-item-meta';
+ meta.style.cssText = 'font-size:10px;opacity:0.7;margin-top:2px;';
+ const showFolderChip = !!(_libSearchHadResults && cardFolder);
+ const prettyFolder = folderDisplayName(cardFolder);
+ const sentChip = isSentFolderEarly ? '<span class="email-sent-chip" title="Sent email">Sent</span>' : '';
+ const folderChip = showFolderChip && !isSentFolderEarly
+ ? `<span class="email-folder-chip" title="${_esc(cardFolder)}">${_esc(prettyFolder)}</span>`
+ : '';
+ const senderPrefix = isSentFolderEarly ? 'to ' : '';
+ meta.innerHTML = `${sentChip}<span class="email-meta-sender" data-email="${_esc(senderAddress || '')}" data-name="${_esc(senderName || '')}"><span style="opacity:0.55">${senderPrefix}</span><span style="color:${color};font-weight:600">${_esc(senderName)}</span></span><span class="email-meta-sep"> · </span><span class="email-meta-date-group"><span class="email-meta-date">${_esc(dateStr)}</span>${folderChip}</span>`;
+ content.appendChild(meta);
+
+ card.appendChild(content);
+
+ // Per-card menu button (... menu)
+ if (!state._selectMode) {
+ const actionsWrap = document.createElement('div');
+ actionsWrap.className = 'memory-item-actions';
+ const menuBtn = document.createElement('button');
+ menuBtn.className = 'memory-item-btn';
+ menuBtn.title = 'Actions';
+ menuBtn.style.position = 'relative';
+ menuBtn.style.top = '-1px';
+ menuBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg>';
+ menuBtn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ _showCardMenu(em, menuBtn);
+ });
+ actionsWrap.appendChild(menuBtn);
+ card.appendChild(actionsWrap);
+ card.appendChild(cardChevron);
+
+ // Long-press anywhere on the row opens the same actions menu — matches
+ // the chats / archive / research / documents tabs' long-press UX.
+ let _hold = null, _holdStart = null;
+ const _cancelHold = () => { if (_hold) { clearTimeout(_hold); _hold = null; } _holdStart = null; };
+ card.addEventListener('pointerdown', (e) => {
+ if (card.classList.contains('email-card-expanded') || card.classList.contains('doclib-card-expanded')) return;
+ if (e.target.closest('button, .email-card-done, .recipient-chip, .memory-select-cb, .email-card-nav-btn')) return;
+ _holdStart = { x: e.clientX, y: e.clientY };
+ _hold = setTimeout(() => {
+ _hold = null;
+ if (card.classList.contains('email-card-expanded') || card.classList.contains('doclib-card-expanded')) return;
+ card._suppressNextClick = true;
+ setTimeout(() => { card._suppressNextClick = false; }, 400);
+ if (navigator.vibrate) try { navigator.vibrate(15); } catch {}
+ if (window.innerWidth <= 768 && ('ontouchstart' in window || navigator.maxTouchPoints > 0)) {
+ const selectBtn = document.getElementById('email-lib-select-btn');
+ if (selectBtn) {
+ if (!selectBtn.classList.contains('active')) selectBtn.click();
+ setTimeout(() => document.querySelector(`#email-lib-grid .doclib-card[data-uid="${CSS.escape(String(em.uid))}"] .memory-select-cb`)?.click(), 40);
+ return;
+ }
+ }
+ _showCardMenu(em, menuBtn);
+ }, 500);
+ });
+ card.addEventListener('pointermove', (e) => {
+ if (!_holdStart) return;
+ if (Math.hypot(e.clientX - _holdStart.x, e.clientY - _holdStart.y) > 10) _cancelHold();
+ });
+ card.addEventListener('pointerup', _cancelHold);
+ card.addEventListener('pointercancel', _cancelHold);
+ }
+
+ // Click handler — toggle preview expansion
+ card.addEventListener('click', async (e) => {
+ if (card._suppressNextClick) { card._suppressNextClick = false; return; }
+ if (state._selectMode) {
+ if (state._selectedUids.has(em.uid)) state._selectedUids.delete(em.uid);
+ else state._selectedUids.add(em.uid);
+ card.classList.toggle('selected', state._selectedUids.has(em.uid));
+ const cb = card.querySelector('.memory-select-cb');
+ if (cb) cb.checked = state._selectedUids.has(em.uid);
+ _updateBulkBar();
+ return;
+ }
+ if (e.shiftKey) {
+ e.preventDefault();
+ await _openEmailAsTab(em, cardFolder);
+ return;
+ }
+ if (/draft/i.test(String(state._libFolder || '')) && state._docModule?.openEmailDraft) {
+ try {
+ await _openDraftInComposer(em);
+ } catch (err) {
+ console.error('Failed to open email draft:', err);
+ showToast(`Could not open draft: ${err.message || err}`);
+ }
+ return;
+ }
+ await _toggleCardPreview(card, em);
+ });
+
+ return card;
+ }
+
+ export function _findSiblingEmailCard(card, dir) {
+ const grid = card.closest('.doclib-grid');
+ if (!grid) return null;
+ const cards = [...grid.querySelectorAll('.doclib-card[data-uid]')];
+ const idx = cards.indexOf(card);
+ if (idx === -1) return null;
+ return cards[idx + dir] || null;
+ }
+
+ function _syncCardNavArrows(card) {
+ const prev = card.querySelector('.email-card-nav-btn[data-nav-dir="-1"]');
+ const next = card.querySelector('.email-card-nav-btn[data-nav-dir="1"]');
+ if (prev) prev.disabled = !_findSiblingEmailCard(card, -1);
+ if (next) next.disabled = !_findSiblingEmailCard(card, 1);
+ }
+
+ async function _openDraftInComposer(em) {
+ if (!state._docModule?.openEmailDraft) return false;
+ const folder = em?.folder || state._libFolder || 'Drafts';
+ const account = state._libAccountId ? `&account_id=${encodeURIComponent(state._libAccountId)}` : '';
+ const res = await fetch(`${API_BASE}/api/email/read/${encodeURIComponent(em.uid)}?folder=${encodeURIComponent(folder)}${account}&mark_seen=false`);
+ if (!res.ok) throw new Error(`Draft load failed: HTTP ${res.status}`);
+ const data = await res.json();
+ if (data.error) throw new Error(data.error);
+ await state._docModule.openEmailDraft({ ...em, ...data });
+ return true;
+ }
+
+ const _emailReadPrefetching = new Set();
+ let _emailReadPrefetchTimer = null;
+
+ function _prefetchAdjacentEmails(card, count = 1) {
+ if (!card || state._libFolder === '__scheduled__') return;
+ const grid = card.closest('.doclib-grid');
+ if (!grid) return;
+ const cards = [...grid.querySelectorAll('.doclib-card[data-uid]')];
+ const idx = cards.indexOf(card);
+ if (idx === -1) return;
+ const targets = [];
+ for (let i = 1; i <= count; i++) {
+ if (cards[idx + i]) targets.push(cards[idx + i]);
+ }
+ if (targets.length < count) {
+ for (let i = 1; targets.length < count && cards[idx - i]; i++) targets.push(cards[idx - i]);
+ }
+ const target = targets.find(t => t?.dataset?.uid);
+ const uid = target?.dataset?.uid;
+ if (!uid) return;
+ // Use the email's actual folder when it was stamped by the search
+ // endpoint; otherwise default to the currently-selected folder.
+ const _emFold = (() => {
+ const emObj = (state._libEmails || []).find(e => String(e.uid) === String(uid));
+ return (emObj && emObj.folder) || state._libFolder || 'INBOX';
+ })();
+ const key = `${state._libAccountId || ''}|${_emFold}|${uid}`;
+ if (_emailReadPrefetching.has(key) || _emailReadPrefetching.size > 0) return;
+ if (_emailReadPrefetchTimer) clearTimeout(_emailReadPrefetchTimer);
+ _emailReadPrefetchTimer = setTimeout(() => {
+ _emailReadPrefetchTimer = null;
+ if (document.hidden) return;
+ _emailReadPrefetching.add(key);
+ fetch(`${API_BASE}/api/email/read/${encodeURIComponent(uid)}?folder=${encodeURIComponent(_emFold)}${_acct()}&mark_seen=false`)
+ .catch(() => {})
+ .finally(() => _emailReadPrefetching.delete(key));
+ }, 2500);
+ }
+
+ export async function _toggleCardPreview(card, em) {
+ _normalizeEmailStateFlags(em);
+ const accountAtStart = state._libAccountId || '';
+ const libraryFolderAtStart = state._libFolder || 'INBOX';
+ // Prefer the per-email folder stamped by the search endpoint (results
+ // from "All Mail" carry folder="[Gmail]/All Mail"). Falls back to the
+ // currently-selected folder for normal inbox cards.
+ const folderAtStart = _hasActiveEmailSearchResults()
+ ? ((em && em.folder) || libraryFolderAtStart)
+ : libraryFolderAtStart;
+ const uidAtStart = String(em?.uid || card?.dataset?.uid || '');
+ const wasReadAtStart = !!em?.is_read;
+ const openGeneration = ++_emailCardOpenSeq;
+ const readContext = Object.freeze({
+ accountId: String(accountAtStart),
+ libraryFolder: String(libraryFolderAtStart),
+ folder: String(folderAtStart),
+ uid: uidAtStart,
+ mailboxGeneration: _emailMailboxGeneration,
+ });
+ const readContextKey = _emailReadContextKey(readContext);
+ const isCurrentOpen = () => (
+ openGeneration === _emailCardOpenSeq &&
+ _emailReadContextIsCurrent(readContext) &&
+ accountAtStart === (state._libAccountId || '') &&
+ libraryFolderAtStart === (state._libFolder || 'INBOX') &&
+ uidAtStart === String(card?.dataset?.uid || '') &&
+ card.isConnected &&
+ card.classList.contains('email-card-expanded')
+ );
+ const grid = card.closest('.doclib-grid');
+ const gridRect = grid?.getBoundingClientRect?.();
+ const modal = document.getElementById('email-lib-modal');
+ const modalContent = card.closest('.modal-content');
+ const modalRect = modalContent?.getBoundingClientRect?.();
+ const currentRect = card.getBoundingClientRect();
+ const stableOpenHeight = Math.max(
+ currentRect.height || 0,
+ (modalRect?.height || 0) - 84,
+ Math.min(Math.max(260, window.innerHeight * 0.56), gridRect?.height || window.innerHeight)
+ );
+
+ // Already expanded — collapse
+ if (card.classList.contains('email-card-expanded')) {
+ unbindExpandedCardDismiss(card);
+ card.classList.remove('email-card-expanded');
+ card.classList.remove('doclib-card-expanded');
+ card.style.minHeight = '';
+ modal?.classList.remove('email-reading');
+ modal?.style.removeProperty('--email-reading-modal-min-h');
+ const reader = card.querySelector('.email-card-reader');
+ if (reader) reader.remove();
+ return;
+ }
+
+ // Every authoritative open supersedes any older optimistic mutation for the
+ // same immutable mailbox identity. Carry the original unread state forward
+ // so a close/reopen followed by failure still rolls back exactly once, while
+ // a late failure from the superseded request cannot undo a newer success.
+ const previousMutation = _emailReadMutations.get(readContextKey);
+ const readMutation = {
+ generation: ++_emailReadMutationSeq,
+ rollbackUnread: !wasReadAtStart || !!previousMutation?.rollbackUnread,
+ };
+ _emailReadMutations.set(readContextKey, readMutation);
+ const restoreUnreadState = () => {
+ if (_emailReadMutations.get(readContextKey)?.generation !== readMutation.generation) return;
+ _emailReadMutations.delete(readContextKey);
+ if (readMutation.rollbackUnread) _syncEmailReadState(uidAtStart, false, readContext);
+ };
+ const commitReadState = () => {
+ // A successful STORE/mark_seen is authoritative for this immutable
+ // mailbox identity even when a newer open is still pending. Retire that
+ // newer rollback token too, otherwise its later failure could restore an
+ // unread state that no longer exists at the provider.
+ _emailReadMutations.delete(readContextKey);
+ _syncEmailReadState(uidAtStart, true, readContext);
+ };
+
+ // Collapse any other expanded card
+ if (grid) {
+ grid.querySelectorAll('.email-card-expanded').forEach(c => {
+ unbindExpandedCardDismiss(c);
+ c.classList.remove('email-card-expanded');
+ c.classList.remove('doclib-card-expanded');
+ c.style.minHeight = '';
+ const r = c.querySelector('.email-card-reader');
+ if (r) r.remove();
+ });
+ }
+
+ card.classList.add('email-card-expanded');
+ card.classList.add('doclib-card-expanded');
+ bindExpandedCardDismiss(card, () => _toggleCardPreview(card, em));
+ card.style.minHeight = `${Math.round(stableOpenHeight)}px`;
+ // Pull the card into view in case the user clicked an email further up
+ // the list whose top is partially scrolled off the viewport. Wait for
+ // the layout to settle (minHeight just changed) before scrolling so
+ // the browser scrolls toward the post-expansion position.
+ requestAnimationFrame(() => {
+ try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (_) {}
+ });
+ if (!wasReadAtStart) {
+ // Keep the current optimistic visual update, but let the read request below
+ // own the provider-side \Seen transition. A failure restores unread state.
+ _syncEmailReadState(uidAtStart, true, readContext);
+ }
+ // Class hook on the modal so the header-hide / padding rules work on
+ // browsers without :has() support (Firefox mobile) — the :has() versions
+ // below stay as the desktop path.
+ if (modal && modalRect?.height) {
+ modal.style.setProperty('--email-reading-modal-min-h', `${Math.round(modalRect.height)}px`);
+ }
+ modal?.classList.add('email-reading');
+
+ // Show loading reader with whirlpool spinner
+ const reader = document.createElement('div');
+ reader.className = 'email-card-reader email-card-reader-loading';
+ reader.style.minHeight = `${Math.max(180, Math.round(stableOpenHeight - 70))}px`;
+ reader.innerHTML = _emailReaderSkeletonHtml();
+ card.appendChild(reader);
+ _markEmailReaderActive(reader);
+ const showFailedReader = (message) => {
+ try {
+ _showEmailReaderLoadError(reader, message, () => {
+ try { reader.remove(); } catch (_) {}
+ card.classList.remove('email-card-expanded', 'doclib-card-expanded');
+ card.style.minHeight = '';
+ setTimeout(() => { _toggleCardPreview(card, em); }, 0);
+ });
+ showToast(message || 'Failed to load email');
+ } catch (_) {}
+ };
+
+ let authoritativeReadSucceeded = false;
+ try {
+ const accountQueryAtStart = accountAtStart ? `&account_id=${encodeURIComponent(accountAtStart)}` : '';
+ const res = await fetch(`${API_BASE}/api/email/read/${encodeURIComponent(uidAtStart)}?folder=${encodeURIComponent(folderAtStart)}${accountQueryAtStart}&mark_seen=true`);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ let data = await res.json();
+ if (data.error) {
+ restoreUnreadState();
+ if (isCurrentOpen()) showFailedReader(`Failed to load email: ${data.error}`);
+ return;
+ }
+ data = _normalizeEmailStateFlags({ ...em, ...data });
+ Object.assign(em, data);
+ _syncEmailDoneState(uidAtStart, data.is_answered, readContext);
+ if (data.mark_seen_failed) {
+ // The body is authoritative even when the provider refused the \Seen
+ // transition. Render the message and roll the unread marker back so the
+ // list keeps telling the truth, rather than refusing to open a message
+ // we successfully read.
+ restoreUnreadState();
+ } else {
+ authoritativeReadSucceeded = true;
+ commitReadState();
+ }
+ if (!isCurrentOpen()) return;
+ _stampReaderContext(reader, { ...em, ...data }, state._libFolder, state._libAccountId);
+
+ // Build the attachments wrap using the shared helper so the signature-
+ // image filter (small inline PNGs/JPGs, Outlook image001 placeholders,
+ // logo/banner files) is applied here too. Falls back to '' when every
+ // attachment is filtered out.
+ const attsHtml = _buildAttsHtmlFor(em.uid, data);
+
+ // Format date nicely (compact): "Mar 21, 2026 14:32"
+ let dateDisplay = data.date || '';
+ try {
+ if (data.date) {
+ const d = new Date(data.date);
+ if (!isNaN(d.getTime())) {
+ dateDisplay = d.toLocaleString([], {
+ month: 'short', day: 'numeric', year: 'numeric',
+ hour: '2-digit', minute: '2-digit',
+ });
+ }
+ }
+ } catch (_) {}
+
+ // Build recipient chip group from a comma-separated address list
+ const buildRecipients = (str) => {
+ if (!str) return '';
+ const addrs = _splitRecipientList(str);
+ if (addrs.length === 0) return '';
+ return addrs.map(a => {
+ const name = _extractName(a);
+ return _recipientChipHtml(a, name);
+ }).join('');
+ };
+
+ // Build the From chip too — single chip with name, click reveals address
+ const fromChip = _recipientChipHtml(`${data.from_name || ''} <${data.from_address || ''}>`, data.from_name || data.from_address, 'from-chip');
+
+ reader.innerHTML = `
+ <div class="email-reader-header">
+ <div class="email-reader-meta">
+ <div class="email-reader-meta-row email-reader-meta-from">
+ <strong>From:</strong>
+ <span class="recipient-chips">${fromChip}${_recipientMetaToggleHtml(data)}</span>
+ </div>
+ ${(data.to || data.cc) ? `<div class="email-reader-meta-details" hidden>
+ ${data.to ? `<div class="email-reader-meta-row"><strong>To:</strong><span class="recipient-chips">${buildRecipients(data.to)}</span></div>` : ''}
+ ${data.cc ? `<div class="email-reader-meta-row"><strong>Cc:</strong><span class="recipient-chips">${buildRecipients(data.cc)}</span></div>` : ''}
+ </div>` : ''}
+ <div class="email-reader-actions-inline">
+ <button class="memory-toolbar-btn reader-icon-btn" data-act="ai-reply" title="${data.cached_ai_reply ? 'AI Reply (cached draft ready)' : 'AI Reply (suggest a draft)'}">${_aiReplyIcon(data)}<span class="reader-btn-label">AI reply</span></button>
+ <button class="memory-toolbar-btn reader-icon-btn" data-act="reply" title="Reply"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg><span class="reader-btn-label">Reply</span></button>
+ ${_hasMultipleRecipients(data) ? `<button class="memory-toolbar-btn reader-icon-btn" data-act="reply-all" title="Reply All"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="7 17 2 12 7 7"/><polyline points="12 17 7 12 12 7"/><path d="M22 18v-2a4 4 0 0 0-4-4H7"/></svg><span class="reader-btn-label">Reply all</span></button>` : ''}
+ <button class="memory-toolbar-btn reader-icon-btn" data-act="forward" title="Forward"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 17 20 12 15 7"/><path d="M4 18v-2a4 4 0 0 1 4-4h12"/></svg><span class="reader-btn-label">Forward</span></button>
+ <div class="email-reader-more-wrap" style="position:relative">
+ <button class="memory-toolbar-btn reader-icon-btn" data-act="more" title="More actions"><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg><span class="reader-btn-label">More</span></button>
+ </div>
+ </div>
+ </div>
+ </div>
+ ${attsHtml}
+ <div class="email-reader-body${data.body_html ? ' html-body' : ''}">${_safeRenderEmailBody(data)}</div>
+ `;
+ _markEmailReaderActive(reader);
+ reader.classList.remove('email-card-reader-loading');
+ reader.style.minHeight = '';
+
+ _wireEmailAttachmentWrap(reader, folderAtStart);
+ _wireEmailInlineImages(reader);
+ _loadDeferredAttachmentsIntoReader(reader, em.uid, folderAtStart, data, !!em.has_attachments);
+ _maybeAutoTranslateEmail(reader);
+
+ reader.querySelector('[data-act="reply"]')?.addEventListener('click', async (ev) => {
+ ev.stopPropagation();
+ _snapEmailModalToLeftSidebar(ev.currentTarget.closest('.modal'));
+ if (state._onEmailClick) await state._onEmailClick({ email: em, emailData: data, mode: 'reply' });
+ });
+ reader.querySelector('[data-act="reply-all"]')?.addEventListener('click', async (ev) => {
+ ev.stopPropagation();
+ _snapEmailModalToLeftSidebar(ev.currentTarget.closest('.modal'));
+ if (state._onEmailClick) await state._onEmailClick({ email: em, emailData: data, mode: 'reply-all' });
+ });
+ reader.querySelector('[data-act="ai-reply"]')?.addEventListener('click', (ev) => _handleAiReplyButton(ev, em, data));
+ reader.querySelector('[data-act="forward"]')?.addEventListener('click', async (ev) => {
+ ev.stopPropagation();
+ if (state._onEmailClick) await state._onEmailClick({ email: em, emailData: data, mode: 'forward' });
+ });
+ reader.querySelector('[data-act="more"]')?.addEventListener('click', (ev) => {
+ ev.stopPropagation();
+ _showReaderMoreMenu(em, card, reader, ev.currentTarget, data);
+ });
+ reader.querySelector('[data-act="summarize"]')?.addEventListener('click', async (ev) => {
+ ev.stopPropagation();
+ await _summarizeEmail(reader, data, ev.currentTarget);
+ });
+ _wireMetaToggle(reader);
+ _wireReaderActionOverflow(reader);
+ // Refresh the title-row prev/next arrows for this newly-expanded card.
+ _syncCardNavArrows(card);
+
+ // Horizontal swipe on the reader switches to prev/next email — but
+ // only when the underlying content can't scroll further in the swipe
+ // direction. If the email body is wider than the viewport (HTML emails
+ // with tables, embedded images), normal horizontal scroll wins; nav
+ // only fires once the user has reached an edge.
+ {
+ let _sx = 0, _sy = 0, _swiping = false, _intent = null;
+ let _scrollEl = null;
+ let _startScrollLeft = 0;
+ const SWIPE_THRESHOLD = 60;
+ const VERT_ABORT = 14;
+ const findHScroller = (el) => {
+ while (el && el !== reader) {
+ if (el.scrollWidth - el.clientWidth > 2) return el;
+ el = el.parentElement;
+ }
+ return null;
+ };
+ reader.addEventListener('touchstart', (ev) => {
+ if (ev.touches.length !== 1) { _swiping = false; return; }
+ if (ev.target.closest('button, a, .recipient-chip, .email-attachment-chip, .email-reader-more-wrap')) { _swiping = false; return; }
+ _sx = ev.touches[0].clientX;
+ _sy = ev.touches[0].clientY;
+ _scrollEl = findHScroller(ev.target);
+ _startScrollLeft = _scrollEl ? _scrollEl.scrollLeft : 0;
+ _swiping = true;
+ _intent = null;
+ }, { passive: true });
+ reader.addEventListener('touchmove', (ev) => {
+ if (!_swiping) return;
+ const dx = ev.touches[0].clientX - _sx;
+ const dy = ev.touches[0].clientY - _sy;
+ if (!_intent) {
+ if (Math.abs(dy) > VERT_ABORT && Math.abs(dy) > Math.abs(dx)) {
+ _intent = 'scroll';
+ _swiping = false;
+ return;
+ }
+ if (Math.abs(dx) > 12) _intent = 'swipe';
+ }
+ }, { passive: true });
+ reader.addEventListener('touchend', (ev) => {
+ if (!_swiping) return;
+ _swiping = false;
+ const t = (ev.changedTouches && ev.changedTouches[0]) || null;
+ if (!t || _intent !== 'swipe') return;
+ const dx = t.clientX - _sx;
+ const dy = t.clientY - _sy;
+ if (Math.abs(dx) < SWIPE_THRESHOLD || Math.abs(dy) > Math.abs(dx)) return;
+ // If a horizontally-scrollable element captured the swipe, let it
+ // scroll instead of changing email — UNLESS the user was already
+ // at the edge (scrollLeft can't move further in that direction).
+ if (_scrollEl) {
+ const max = _scrollEl.scrollWidth - _scrollEl.clientWidth;
+ const atLeftEdge = _scrollEl.scrollLeft <= 2;
+ const atRightEdge = _scrollEl.scrollLeft >= max - 2;
+ // Swiping LEFT (dx<0) reveals content to the right → if not at
+ // right edge, that's a scroll, not a nav.
+ if (dx < 0 && !atRightEdge) return;
+ // Swiping RIGHT (dx>0) reveals content to the left → if not at
+ // left edge, that's a scroll, not a nav.
+ if (dx > 0 && !atLeftEdge) return;
+ // If the browser already scrolled during this gesture, treat as
+ // scroll regardless (the user clearly wanted to pan).
+ if (_scrollEl.scrollLeft !== _startScrollLeft) return;
+ }
+ const dir = dx < 0 ? 1 : -1;
+ const navBtn = card.querySelector(`.email-card-nav-btn[data-nav-dir="${dir}"]`);
+ if (navBtn && !navBtn.disabled) navBtn.click();
+ }, { passive: true });
+ }
+
+ // If the email has a pre-cached summary, show it immediately. Fold
+ // state is persisted via _summaryCollapsedPref inside the renderer.
+ if (data.cached_summary) {
+ const sumBtn = reader.querySelector('[data-act="summarize"]');
+ _showCachedSummary(reader, data.cached_summary, sumBtn);
+ }
+
+ _wireRecipientChips(reader);
+ // Always stop bubbling so the card's click doesn't fire while reading.
+ reader.addEventListener('click', (ev) => { ev.stopPropagation(); });
+ } catch (e) {
+ if (!authoritativeReadSucceeded) restoreUnreadState();
+ if (isCurrentOpen()) {
+ showFailedReader(e?.message ? `Failed to load email: ${e.message}` : 'Failed to load email');
+ }
+ }
+ }
+
+
+ // Global preference: AI summary panels stay collapsed across every email
+ // once the user folds one, and stay expanded once they unfold. Stored in
+ // localStorage so the choice survives reloads.
+ const _SUMMARY_COLLAPSED_KEY = 'odysseus.email.summaryCollapsed';
+ export function _summaryCollapsedPref() {
+ try { return localStorage.getItem(_SUMMARY_COLLAPSED_KEY) === '1'; } catch { return false; }
+ }
+ export function _setSummaryCollapsedPref(v) {
+ try { localStorage.setItem(_SUMMARY_COLLAPSED_KEY, v ? '1' : '0'); } catch {}
+ }
+
+ function _showCachedSummary(reader, summary, btn) {
+ const body = reader.querySelector('.email-reader-body');
+ if (!body) return;
+ if (body.querySelector('.email-summary-panel')) return;
+ const panel = document.createElement('div');
+ panel.className = 'email-summary-panel';
+ if (_summaryCollapsedPref()) panel.classList.add('collapsed');
+ panel.innerHTML =
+ '<div class="email-summary-header email-summary-toggle" role="button" tabindex="0">'
+ + '<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg>'
+ + '<span>Summary</span>'
+ + '<svg class="email-summary-chevron" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="margin-left:auto;transition:transform .15s ease;"><polyline points="6 9 12 15 18 9"/></svg>'
+ + '</div>'
+ + '<div class="email-summary-content"></div>';
+ panel.querySelector('.email-summary-content').textContent = summary;
+ body.insertBefore(panel, body.firstChild);
+ const toggle = panel.querySelector('.email-summary-toggle');
+ // Header click folds/unfolds. Persists so the next email opens in the
+ // same state.
+ const _flip = () => {
+ panel.classList.toggle('collapsed');
+ _setSummaryCollapsedPref(panel.classList.contains('collapsed'));
+ };
+ if (toggle) {
+ toggle.addEventListener('click', (ev) => { ev.stopPropagation(); _flip(); });
+ toggle.addEventListener('keydown', (ev) => {
+ if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); _flip(); }
+ });
+ }
+ if (btn) {
+ btn.classList.add('active');
+ const label = btn.querySelector('.btn-label');
+ if (label) label.textContent = 'Summary';
+ }
+ }
+
+
+ export async function _translateEmail(reader, language, opts = {}) {
+ const body = reader?.querySelector?.('.email-reader-body');
+ if (!body) return;
+ const existing = body.querySelector('.email-translation-panel');
+ if (existing) {
+ if (opts.auto && !opts.force) return;
+ existing.remove();
+ }
+ const targetLanguage = language || 'English';
+ const sourceText = _emailBodyTextForTranslate(reader);
+ if (!sourceText) {
+ try { uiModule?.showError?.('No email body to translate'); } catch {}
+ return;
+ }
+
+ body.querySelectorAll('.email-translation-panel').forEach(p => p.remove());
+ const panel = document.createElement('div');
+ panel.className = 'email-summary-panel email-translation-panel';
+ panel.innerHTML =
+ '<div class="email-summary-header email-summary-toggle" role="button" tabindex="0">'
+ + '<svg class="email-translation-icon" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m5 8 6 6"/><path d="m4 14 6-6 2-3"/><path d="M2 5h12"/><path d="M7 2h1"/><path d="m22 22-5-10-5 10"/><path d="M14 18h6"/></svg>'
+ + `<span>Translation · ${_esc(targetLanguage)}</span>`
+ + '<svg class="email-summary-chevron" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="margin-left:auto;transition:transform .15s ease;"><polyline points="6 9 12 15 18 9"/></svg>'
+ + '</div>'
+ + '<div class="email-summary-content email-translation-loading"><span class="email-translation-busy"><span class="email-translation-spinner"></span><span class="email-translation-loading-text">Translating...</span></span></div>';
+ body.insertBefore(panel, body.firstChild);
+ const translationToggle = panel.querySelector('.email-summary-toggle');
+ if (translationToggle) {
+ const flip = () => panel.classList.toggle('collapsed');
+ translationToggle.addEventListener('click', (ev) => { ev.stopPropagation(); flip(); });
+ translationToggle.addEventListener('keydown', (ev) => {
+ if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); flip(); }
+ });
+ }
+
+ const content = panel.querySelector('.email-summary-content');
+ const sp = spinnerModule.createWhirlpool(18);
+ content.querySelector('.email-translation-spinner')?.appendChild(sp.element);
+ try {
+ const res = await fetch(`${API_BASE}/api/email/translate`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ body: sourceText,
+ subject: reader.dataset.emailSubject || '',
+ from: reader.dataset.emailFrom || '',
+ target_language: targetLanguage,
+ auto: !!opts.auto,
+ }),
+ });
+ const result = await res.json().catch(() => ({}));
+ sp.destroy();
+ content.innerHTML = '';
+ if (res.ok && result.success && result.same_language) {
+ panel.remove();
+ } else if (res.ok && result.success && result.translation) {
+ content.textContent = String(result.translation || '')
+ .replace(/^\s*<<<TRANSLATION>>>\s*/i, '')
+ .replace(/\s*<<<END>>>\s*$/i, '')
+ .trim();
+ } else {
+ panel.remove();
+ try { uiModule?.showError?.(result.error || 'Failed to translate'); } catch {}
+ }
+ } catch (_) {
+ sp.destroy();
+ panel.remove();
+ try { uiModule?.showError?.('Failed to translate'); } catch {}
+ }
+ }
+
+ export async function _maybeAutoTranslateEmail(reader) {
+ if (reader) reader.dataset.autoTranslateChecked = '1';
+ }
+
+ // Keep an email ⋮ dropdown inside the viewport: when it would spill past the
+ // bottom (e.g. an email low on a phone screen), flip it above the anchor if
+ // there's more room up there, and cap height + scroll if it still overflows.
+ export function _fitEmailDropdown(dropdown, rect) {
+ requestAnimationFrame(() => {
+ const margin = 8;
+ // Horizontal clamp — keep the dropdown inside the viewport regardless of
+ // whether it was anchored via left or right. Needed now that some
+ // triggers (e.g. the right-aligned bulk "Actions" button) sit close to
+ // the right edge, where a left-anchored menu would spill off-screen.
+ const dw = dropdown.offsetWidth;
+ const curLeft = dropdown.getBoundingClientRect().left;
+ if (curLeft + dw > window.innerWidth - margin) {
+ dropdown.style.left = Math.max(margin, window.innerWidth - margin - dw) + 'px';
+ dropdown.style.right = 'auto';
+ } else if (curLeft < margin) {
+ dropdown.style.left = margin + 'px';
+ dropdown.style.right = 'auto';
+ }
+ // Vertical fit — flip up or cap+scroll if it doesn't fit below.
+ const dh = dropdown.offsetHeight;
+ const below = window.innerHeight - rect.bottom - margin;
+ const above = rect.top - margin;
+ if (dh <= below) return; // fits below as-is
+ if (above > below) { // flip upward
+ dropdown.style.top = 'auto';
+ dropdown.style.bottom = (window.innerHeight - rect.top + 4) + 'px';
+ if (dh > above) { dropdown.style.maxHeight = above + 'px'; dropdown.style.overflowY = 'auto'; }
+ } else { // keep below, cap + scroll
+ dropdown.style.maxHeight = below + 'px';
+ dropdown.style.overflowY = 'auto';
+ }
+ });
+ }
+
+ function _fitReaderActions(meta) {
+ const row = meta?.querySelector(':scope > .email-reader-actions-inline');
+ if (!row) return;
+ const candidates = row.querySelectorAll(':scope > .reader-icon-btn:not([data-act="more"]), :scope > :not(.email-reader-more-wrap) > .reader-icon-btn');
+ candidates.forEach(button => button.classList.remove('reader-action-overflowed'));
+ row.classList.remove('email-reader-actions-compact');
+ const buttonsWidth = Array.from(row.children).reduce((sum, child) => sum + child.getBoundingClientRect().width, 0)
+ + Math.max(0, row.children.length - 1) * 4;
+ const compact = buttonsWidth > Math.max(190, meta.clientWidth - 150);
+ row.classList.toggle('email-reader-actions-compact', compact);
+ if (compact) {
+ // Keep the two common drafting actions visible on narrow screens. Put
+ // the less frequent recipient variants in More first.
+ row.querySelectorAll('[data-act="reply-all"], [data-act="forward"]')
+ .forEach(button => button.classList.add('reader-action-overflowed'));
+ }
+ }
+
+ const _readerActionFitObserver = typeof ResizeObserver === 'function'
+ ? new ResizeObserver(entries => {
+ for (const entry of entries) _fitReaderActions(entry.target);
+ })
+ : null;
+
+ export function _wireReaderActionOverflow(reader) {
+ const meta = reader?.querySelector('.email-reader-meta');
+ if (!meta) return;
+ requestAnimationFrame(() => _fitReaderActions(meta));
+ _readerActionFitObserver?.observe(meta);
+ }
+
+
+ // _extractName lives in ./emailLibrary/utils.js
+
+
+ // Sanitize untrusted HTML email bodies before injecting via innerHTML.
+ //
+ // Denylist sanitizer — has to block every well-known XSS sink:
+ // - <script>, <iframe>, <object>, <embed>, <form>, <style>, <link>
+ // - SVG entirely (event handlers, <use href="javascript:">, <foreignObject>,
+ // <animate>, <set>, etc.). Email clients don't need SVG.
+ // - <math> (MathML can carry handlers).
+ // - <base href="...">, <meta http-equiv="refresh">, <noscript>, <frame>,
+ // <frameset>, <applet>, <portal>.
+ // - on* attributes; javascript:/vbscript:/data: URLs in href/src/srcset/
+ // formaction/action/background/poster/data attributes.
+ // - srcdoc (defensive — iframe is already nuked).
+ // - inline `style` declarations containing javascript: or expression().
+ // _sanitizeHtml / _escLinkify live in ./emailLibrary/utils.js
diff --cc static/js/settings/agent.js
index 000000000,4c8e6dc19..7c48e9831
mode 000000,100644..100644
--- a/static/js/settings/agent.js
+++ b/static/js/settings/agent.js
@@@ -1,0 -1,58 +1,58 @@@
+ // Agent settings panel.
+ // Extracted verbatim from static/js/settings.js. Behaviour is unchanged: the
+ // functions moved, their bodies did not. settings.js imports them and calls
+ // them from the same places, so load order and init sequence are untouched.
+
+ import { byId as el } from './dom.js';
+ import { postSettings as _postSettings } from './api.js';
+
+ export async function initAgentSettings() {
+ var toolsInput = el('set-agentMaxTools');
+ var roundsInput = el('set-agentMaxRounds');
+ var supInput = el('set-agentSupervisorLadder');
+ var msg = el('set-agentMsg');
+ if (!toolsInput) return;
+
+ try {
+ var res = await fetch('/api/auth/settings', { credentials: 'same-origin' });
+ var settings = await res.json();
+ if (settings.agent_max_tool_calls) toolsInput.value = settings.agent_max_tool_calls;
+ if (roundsInput && settings.agent_max_rounds) roundsInput.value = settings.agent_max_rounds;
+ if (supInput) supInput.checked = !!settings.agent_supervisor_ladder;
+ } catch (e) {}
+
+ // Clamp + coerce a raw input to an int in [lo, hi]; falls back to `dflt`
+ // when blank/non-numeric. Mirrors the server-side validation.
+ function clampInt(raw, lo, hi, dflt) {
+ var n = parseInt(raw, 10);
+ if (isNaN(n)) return dflt;
+ return Math.max(lo, Math.min(n, hi));
+ }
+
+ async function save() {
+ var tools = clampInt(toolsInput.value, 0, 1000, 0);
+ var rounds = roundsInput ? clampInt(roundsInput.value, 1, 200, 20) : null;
+ toolsInput.value = tools; // reflect the clamped value
+ if (roundsInput) roundsInput.value = rounds;
+ var payload = { agent_max_tool_calls: tools };
+ if (rounds != null) payload.agent_max_rounds = rounds;
+ if (supInput) payload.agent_supervisor_ladder = !!supInput.checked;
+ try {
+ await _postSettings(payload);
+ msg.textContent = (tools > 0 ? 'Limit: ' + tools + ' tool calls' : 'Unlimited tool calls') +
+ (rounds != null ? ' · ' + rounds + ' steps/message' : '') +
+ (supInput && supInput.checked ? ' · supervisor on' : '');
+ msg.style.color = 'var(--fg)';
- } catch (e) { msg.textContent = 'Failed to save'; msg.style.color = 'var(--red)'; }
++ } catch (e) { msg.textContent = e.status === 403 ? 'Admin access is required to change these settings.' : 'Failed to save'; msg.style.color = 'var(--red)'; }
+ }
+
+ toolsInput.addEventListener('change', save);
+ if (roundsInput) roundsInput.addEventListener('change', save);
+ if (supInput) supInput.addEventListener('change', save);
+ var cur = parseInt(toolsInput.value, 10) || 0;
+ var curR = roundsInput ? (parseInt(roundsInput.value, 10) || 20) : null;
+ msg.textContent = (cur > 0 ? 'Limit: ' + cur + ' tool calls' : 'Unlimited tool calls') +
+ (curR != null ? ' · ' + curR + ' steps/message' : '') +
+ (supInput && supInput.checked ? ' · supervisor on' : '');
+
+ }
diff --cc static/js/settings/api.js
index 000000000,80be549a3..3109b9348
mode 000000,100644..100644
--- a/static/js/settings/api.js
+++ b/static/js/settings/api.js
@@@ -1,0 -1,16 +1,26 @@@
+ // Lifted verbatim from static/js/settings.js so extracted panels can post
+ // settings without importing the module they were extracted from.
++import uiModule from '../ui.js?v=20260916largetoolscroll1';
+ import { invalidateSettings } from '../appConfig.js';
+
+ export async function postSettings(body) {
+ try {
- return await fetch('/api/auth/settings', {
++ const response = await fetch('/api/auth/settings', {
+ method: 'POST',
+ credentials: 'same-origin',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
++ if (!response.ok) {
++ const error = new Error(response.status === 403
++ ? 'Admin access is required to change these settings.'
++ : 'Failed to save');
++ error.status = response.status;
++ if (response.status === 403) uiModule.showError(error.message);
++ throw error;
++ }
++ return response;
+ } finally {
+ invalidateSettings();
+ }
+ }
diff --cc static/js/settings/imageModels.js
index 000000000,c01cc67c2..34bd8d614
mode 000000,100644..100644
--- a/static/js/settings/imageModels.js
+++ b/static/js/settings/imageModels.js
@@@ -1,0 -1,59 +1,60 @@@
+ // Image-model settings panel.
+ // Extracted verbatim from static/js/settings.js. Behaviour is unchanged: the
+ // functions moved, their bodies did not. settings.js imports them and calls
+ // them from the same places, so load order and init sequence are untouched.
+
+ import { byId as el } from './dom.js';
+ import { postSettings as _postSettings } from './api.js';
++import { modelCaps } from '../editor/ai-models.js';
+ import { sortModelIds } from '../modelSort.js';
+
+ export async function initImageSettings() {
+ const modelSel = el('set-imgModelSelect');
+ const qualSel = el('set-imgQualitySelect');
+ const msg = el('set-imgSettingsMsg');
+ const enabledToggle = el('set-imgEnabledToggle');
+ const configWrap = modelSel ? modelSel.closest('div[style*="flex-direction"]') : null;
+ try {
+ const endpointsRes = await fetch('/api/model-endpoints', { credentials: 'same-origin' });
+ const endpoints = await endpointsRes.json();
+ const imageModels = new Set();
+ (Array.isArray(endpoints) ? endpoints : []).forEach(endpoint => {
- if (!endpoint.is_enabled || !endpoint.online || String(endpoint.model_type || '').toLowerCase() !== 'image') return;
++ if (!endpoint.is_enabled || !endpoint.online) return;
+ (Array.isArray(endpoint.models) ? endpoint.models : []).forEach(modelId => {
- if (modelId) imageModels.add(String(modelId));
++ if (modelId && modelCaps(modelId, '', endpoint.model_type).gen) imageModels.add(String(modelId));
+ });
+ });
+ sortModelIds(Array.from(imageModels)).forEach(mid => {
+ const opt = document.createElement('option');
+ opt.value = mid;
+ opt.textContent = mid;
+ modelSel.appendChild(opt);
+ });
+ } catch (e) { console.warn('Failed to load models for image settings', e); }
+ try {
+ const settingsRes = await fetch('/api/auth/settings', { credentials: 'same-origin' });
+ const settings = await settingsRes.json();
+ if (settings.image_model) modelSel.value = settings.image_model;
+ if (settings.image_quality) qualSel.value = settings.image_quality;
+ if (enabledToggle) enabledToggle.checked = settings.image_gen_enabled === true;
+ } catch (e) { console.warn('Failed to load settings', e); }
+
+ function syncImgDisabled() {
+ var off = enabledToggle && !enabledToggle.checked;
+ var card = enabledToggle ? enabledToggle.closest('.admin-card') : null;
+ if (card) card.style.opacity = off ? '0.45' : '';
+ if (configWrap) configWrap.style.pointerEvents = off ? 'none' : '';
+ }
+ syncImgDisabled();
+
+ async function saveSettings() {
+ try {
+ const res = await _postSettings({ image_gen_enabled: enabledToggle ? enabledToggle.checked : false, image_model: modelSel.value, image_quality: qualSel.value });
+ if (!res.ok) throw new Error(await res.text().catch(() => `HTTP ${res.status}`));
+ msg.textContent = 'Saved'; msg.style.color = 'var(--fg)'; setTimeout(() => { msg.textContent = ''; }, 2000);
- } catch (e) { msg.textContent = 'Failed to save'; msg.style.color = 'var(--red)'; }
++ } catch (e) { msg.textContent = e.status === 403 ? 'Admin access is required to change these settings.' : 'Failed to save'; msg.style.color = 'var(--red)'; }
+ }
+ modelSel.addEventListener('change', saveSettings);
+ qualSel.addEventListener('change', saveSettings);
+ if (enabledToggle) enabledToggle.addEventListener('change', function() { syncImgDisabled(); saveSettings(); });
+ }
diff --cc static/js/settings/speech.js
index 000000000,00b583e4e..94dd05df0
mode 000000,100644..100644
--- a/static/js/settings/speech.js
+++ b/static/js/settings/speech.js
@@@ -1,0 -1,247 +1,247 @@@
+ // Text-to-speech and speech-to-text settings panels.
+ // Extracted verbatim from static/js/settings.js. Behaviour is unchanged: the
+ // functions moved, their bodies did not. settings.js imports them and calls
+ // them from the same places, so load order and init sequence are untouched.
+
+ import { byId as el } from './dom.js';
+ import { postSettings as _postSettings } from './api.js';
+
+ export async function initTtsSettings() {
+ var provSel = el('set-ttsProviderSelect');
+ var modelSelect = el('set-ttsModelSelect');
+ var modelInput = el('set-ttsModelInput');
+ var voiceSelect = el('set-ttsVoiceSelect');
+ var voiceInput = el('set-ttsVoiceInput');
+ var modelRow = el('set-ttsModelRow');
+ var voiceRow = el('set-ttsVoiceRow');
+ var speedSelect = el('set-ttsSpeedSelect');
+ var speedRow = el('set-ttsSpeedRow');
+ var ttsMsg = el('set-ttsSettingsMsg');
+ var ttsEnabledToggle = el('set-ttsEnabledToggle');
+ var ttsConfigWrap = provSel ? provSel.closest('div[style*="flex-direction"]') : null;
+
+ function isEndpoint() { return provSel.value.startsWith('endpoint:'); }
+ function getModel() { return isEndpoint() ? modelSelect.value : modelInput.value; }
+ function getVoice() { return isEndpoint() ? voiceSelect.value : voiceInput.value; }
+
+ function updateVisibility() {
+ var prov = provSel.value;
+ modelRow.style.display = prov.startsWith('endpoint:') ? 'flex' : 'none';
+ voiceRow.style.display = prov === 'disabled' ? 'none' : 'flex';
+ speedRow.style.display = prov === 'disabled' ? 'none' : 'flex';
+ if (isEndpoint()) {
+ modelSelect.style.display = ''; modelInput.style.display = 'none';
+ voiceSelect.style.display = ''; voiceInput.style.display = 'none';
+ } else {
+ modelSelect.style.display = 'none'; modelInput.style.display = '';
+ voiceSelect.style.display = 'none'; voiceInput.style.display = prov === 'disabled' ? 'none' : '';
+ }
+ }
+
+ var ttsKeywords = ['tts', 'audio'];
+ try {
+ var epRes = await fetch('/api/model-endpoints', { credentials: 'same-origin' });
+ var endpoints = await epRes.json();
+ endpoints.forEach(function(ep) {
+ if (!ep.is_enabled) return;
+ var hasTTS = (ep.models || []).some(m => ttsKeywords.some(kw => m.toLowerCase().includes(kw)));
+ if (!hasTTS) return;
+ var opt = document.createElement('option'); opt.value = 'endpoint:' + ep.id; opt.textContent = ep.name + ' (API)'; provSel.appendChild(opt);
+ });
+ } catch (e) { console.warn('Failed to load endpoints for TTS', e); }
+
+ try {
+ var settingsRes = await fetch('/api/auth/settings', { credentials: 'same-origin' });
+ var settings = await settingsRes.json();
+ if (settings.tts_provider) provSel.value = settings.tts_provider;
+ if (settings.tts_model) { modelSelect.value = settings.tts_model; modelInput.value = settings.tts_model; }
+ if (settings.tts_voice) { voiceSelect.value = settings.tts_voice; voiceInput.value = settings.tts_voice; }
+ if (settings.tts_speed) { speedSelect.value = settings.tts_speed; }
+ if (ttsEnabledToggle) ttsEnabledToggle.checked = settings.tts_enabled !== false;
+ } catch (e) { console.warn('Failed to load TTS settings', e); }
+
+ function syncTtsDisabled() {
+ var off = ttsEnabledToggle && !ttsEnabledToggle.checked;
+ var card = ttsEnabledToggle ? ttsEnabledToggle.closest('.admin-card') : null;
+ if (card) card.style.opacity = off ? '0.45' : '';
+ if (ttsConfigWrap) ttsConfigWrap.style.pointerEvents = off ? 'none' : '';
+ }
+ syncTtsDisabled();
+ updateVisibility();
+
+ async function saveTTS() {
+ try {
+ await _postSettings({ tts_enabled: ttsEnabledToggle ? ttsEnabledToggle.checked : true, tts_provider: provSel.value, tts_model: getModel() || 'tts-1', tts_voice: getVoice() || 'alloy', tts_speed: speedSelect.value || '1' });
+ ttsMsg.textContent = 'Saved'; ttsMsg.style.color = 'var(--fg)'; setTimeout(() => { ttsMsg.textContent = ''; }, 2000);
+ if (window.aiTTSManager) window.aiTTSManager.checkAvailability();
- } catch (e) { ttsMsg.textContent = 'Failed to save'; ttsMsg.style.color = 'var(--red)'; }
++ } catch (e) { ttsMsg.textContent = e.status === 403 ? 'Admin access is required to change these settings.' : 'Failed to save'; ttsMsg.style.color = 'var(--red)'; }
+ }
+
+ async function saveAndClearCache() {
+ await saveTTS();
+ fetch('/api/tts/clear-cache', { method: 'POST', credentials: 'same-origin' }).catch(function(){});
+ }
+
+ provSel.addEventListener('change', function() {
+ var prov = provSel.value;
+ if (prov === 'local') voiceInput.value = 'af_heart';
+ else if (isEndpoint()) { voiceSelect.value = 'alloy'; modelSelect.value = 'tts-1'; }
+ else if (prov === 'browser') { voiceInput.value = ''; voiceInput.placeholder = 'OS default voice'; }
+ updateVisibility();
+ saveTTS();
+ });
+ modelSelect.addEventListener('change', saveAndClearCache);
+ modelInput.addEventListener('change', saveTTS);
+ voiceSelect.addEventListener('change', saveAndClearCache);
+ voiceInput.addEventListener('change', saveTTS);
+ speedSelect.addEventListener('change', saveAndClearCache);
+ if (ttsEnabledToggle) ttsEnabledToggle.addEventListener('change', function() { syncTtsDisabled(); saveTTS(); });
+
+ // Preview / test button
+ var previewBtn = el('set-ttsPreviewBtn');
+ if (previewBtn) {
+ var previewAudio = null;
+ var previewPlaying = false;
+ function resetPreview() { previewPlaying = false; previewBtn.textContent = 'Preview'; previewBtn.style.borderColor = ''; }
+
+ previewBtn.addEventListener('click', async function() {
+ if (previewPlaying) {
+ if (previewAudio) { previewAudio.pause(); previewAudio = null; }
+ window.speechSynthesis.cancel();
+ resetPreview(); return;
+ }
+ var prov = provSel.value;
+ if (prov === 'disabled') {
+ ttsMsg.textContent = 'Select a provider first'; ttsMsg.style.color = 'var(--red, #e55)';
+ setTimeout(function() { ttsMsg.textContent = ''; }, 2000); return;
+ }
+ var testText = 'Hello, this is a test of text to speech.';
+ previewPlaying = true; previewBtn.textContent = 'Loading...';
+ try {
+ if (prov === 'browser') {
+ if (!('speechSynthesis' in window)) throw new Error('Browser TTS not supported');
+ var utt = new SpeechSynthesisUtterance(testText);
+ var voiceVal = getVoice();
+ if (voiceVal) {
+ var voices = window.speechSynthesis.getVoices();
+ var target = voiceVal.toLowerCase();
+ var match = voices.find(function(v) { return v.name.toLowerCase() === target; }) ||
+ voices.find(function(v) { return v.name.toLowerCase().includes(target); });
+ if (match) utt.voice = match;
+ }
+ utt.rate = parseFloat(speedSelect.value) || 1;
+ previewBtn.textContent = 'Stop'; previewBtn.style.borderColor = 'var(--red, #e55)';
+ await new Promise(function(resolve, reject) {
+ utt.onend = resolve;
+ utt.onerror = function(e) { reject(new Error('Browser TTS: ' + e.error)); };
+ window.speechSynthesis.speak(utt);
+ });
+ } else {
+ var res = await fetch('/api/tts/synthesize', {
+ method: 'POST', credentials: 'same-origin',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ text: testText, format: 'audio' })
+ });
+ if (!res.ok) { var err = await res.json().catch(function() { return {}; }); throw new Error(err.detail?.message || 'Synthesis failed'); }
+ var blob = await res.blob();
+ var url = URL.createObjectURL(blob);
+ previewAudio = new Audio(url);
+ previewBtn.textContent = 'Stop'; previewBtn.style.borderColor = 'var(--red, #e55)';
+ await new Promise(function(resolve, reject) {
+ previewAudio.onended = function() { URL.revokeObjectURL(url); previewAudio = null; resolve(); };
+ previewAudio.onerror = function() { URL.revokeObjectURL(url); previewAudio = null; reject(new Error('Playback failed')); };
+ previewAudio.play().catch(reject);
+ });
+ }
+ } catch (e) {
+ ttsMsg.textContent = 'Preview failed: ' + e.message; ttsMsg.style.color = 'var(--red, #e55)';
+ setTimeout(function() { ttsMsg.textContent = ''; }, 3000);
+ } finally {
+ resetPreview();
+ }
+ });
+ }
+ }
+
+ export async function initSttSettings() {
+ var provSel = el('set-sttProviderSelect');
+ var modelSelect = el('set-sttModelSelect');
+ var modelInput = el('set-sttModelInput');
+ var modelRow = el('set-sttModelRow');
+ var langRow = el('set-sttLangRow');
+ var langInput = el('set-sttLangInput');
+ var sttMsg = el('set-sttSettingsMsg');
+ var sttEnabledToggle = el('set-sttEnabledToggle');
+ var sttConfigWrap = el('set-sttConfigWrap');
+ // STT was removed from AI Defaults — bail if the UI isn't present.
+ if (!provSel) return;
+
+ function isEndpoint() { return provSel.value.startsWith('endpoint:'); }
+ function getModel() { return isEndpoint() ? modelInput.value : modelSelect.value; }
+
+ function updateVisibility() {
+ var prov = provSel.value;
+ var showModel = prov === 'local' || prov.startsWith('endpoint:');
+ var showLang = prov !== 'disabled';
+ modelRow.style.display = showModel ? 'flex' : 'none';
+ langRow.style.display = showLang ? 'flex' : 'none';
+ if (isEndpoint()) {
+ modelSelect.style.display = 'none'; modelInput.style.display = '';
+ } else {
+ modelSelect.style.display = ''; modelInput.style.display = 'none';
+ }
+ }
+
+ function syncSttDisabled() {
+ var off = sttEnabledToggle && !sttEnabledToggle.checked;
+ var card = sttEnabledToggle ? sttEnabledToggle.closest('.admin-card') : null;
+ if (card) card.style.opacity = off ? '0.45' : '';
+ if (sttConfigWrap) sttConfigWrap.style.pointerEvents = off ? 'none' : '';
+ }
+
+ // Effective provider: if toggle is off, treat as disabled regardless of provider select
+ function effectiveProvider() {
+ if (sttEnabledToggle && !sttEnabledToggle.checked) return 'disabled';
+ return provSel.value;
+ }
+
+ // Add API endpoints that might support STT
+ try {
+ var epRes = await fetch('/api/model-endpoints', { credentials: 'same-origin' });
+ var endpoints = await epRes.json();
+ endpoints.forEach(function(ep) {
+ if (!ep.is_enabled) return;
+ var opt = document.createElement('option'); opt.value = 'endpoint:' + ep.id; opt.textContent = ep.name + ' (API)'; provSel.appendChild(opt);
+ });
+ } catch (e) { console.warn('Failed to load endpoints for STT', e); }
+
+ // Load saved settings
+ try {
+ var settingsRes = await fetch('/api/auth/settings', { credentials: 'same-origin' });
+ var settings = await settingsRes.json();
+ if (settings.stt_provider) provSel.value = settings.stt_provider;
+ if (settings.stt_model) { modelSelect.value = settings.stt_model; modelInput.value = settings.stt_model; }
+ if (settings.stt_language) langInput.value = settings.stt_language;
+ if (sttEnabledToggle) sttEnabledToggle.checked = settings.stt_enabled !== false;
+ } catch (e) { console.warn('Failed to load STT settings', e); }
+
+ syncSttDisabled();
+ updateVisibility();
+
+ async function saveSTT() {
+ try {
+ var enabled = sttEnabledToggle ? sttEnabledToggle.checked : false;
+ await _postSettings({ stt_enabled: enabled, stt_provider: provSel.value, stt_model: getModel() || 'base', stt_language: langInput.value.trim() });
+ sttMsg.textContent = 'Saved'; sttMsg.style.color = 'var(--fg)'; setTimeout(() => { sttMsg.textContent = ''; }, 2000);
+ // Notify voiceRecorder of effective provider and update send button icon
+ if (window.voiceRecorderModule) window.voiceRecorderModule._sttProvider = effectiveProvider();
+ if (window._updateSendBtnIcon) window._updateSendBtnIcon();
- } catch (e) { sttMsg.textContent = 'Failed to save'; sttMsg.style.color = 'var(--red)'; }
++ } catch (e) { sttMsg.textContent = e.status === 403 ? 'Admin access is required to change these settings.' : 'Failed to save'; sttMsg.style.color = 'var(--red)'; }
+ }
+
+ provSel.addEventListener('change', function() { updateVisibility(); saveSTT(); });
+ modelSelect.addEventListener('change', saveSTT);
+ modelInput.addEventListener('change', saveSTT);
+ langInput.addEventListener('change', saveSTT);
+ if (sttEnabledToggle) sttEnabledToggle.addEventListener('change', function() { syncSttDisabled(); saveSTT(); });
+ }
diff --cc static/js/settings/writingStyle.js
index 000000000,0a0a7e648..cffe6953a
mode 000000,100644..100644
--- a/static/js/settings/writingStyle.js
+++ b/static/js/settings/writingStyle.js
@@@ -1,0 -1,71 +1,71 @@@
+ // Document writing-style settings panel.
+ // Extracted verbatim from static/js/settings.js. Behaviour is unchanged: the
+ // functions moved, their bodies did not. settings.js imports them and calls
+ // them from the same places, so load order and init sequence are untouched.
+
+ import { byId as el } from './dom.js';
+ import { postSettings as _postSettings } from './api.js';
+
+ export async function initDocumentWritingStyle() {
+ const styleEl = el('set-document-style');
+ const saveBtn = el('set-document-style-save');
+ const extractBtn = el('set-document-style-extract');
+ const fileEl = el('set-document-style-file');
+ const msg = el('set-document-style-msg');
+ if (!styleEl || !saveBtn) return;
+ try {
+ const res = await fetch('/api/auth/settings', { credentials: 'same-origin' });
+ const data = await res.json();
+ styleEl.value = String(data.document_writing_style || '');
+ } catch (_) {
+ if (msg) msg.textContent = 'Failed to load';
+ }
+ saveBtn.addEventListener('click', async () => {
+ if (msg) msg.textContent = 'Saving...';
+ try {
+ const res = await _postSettings({ document_writing_style: styleEl.value });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ if (msg) msg.textContent = '✓ Saved';
- } catch (_) {
- if (msg) msg.textContent = 'Failed to save';
++ } catch (e) {
++ if (msg) msg.textContent = e.status === 403 ? 'Admin access is required to change these settings.' : 'Failed to save';
+ }
+ setTimeout(() => { if (msg) msg.textContent = ''; }, 3000);
+ });
+ extractBtn?.addEventListener('click', () => fileEl?.click());
+ fileEl?.addEventListener('change', async () => {
+ const file = fileEl.files?.[0];
+ if (!file) return;
+ extractBtn.disabled = true;
+ let whirlpool = null;
+ if (msg) {
+ msg.replaceChildren();
+ try {
+ const spinner = window.spinnerModule || (await import('../spinner.js')).default;
+ whirlpool = spinner.createWhirlpool(14);
+ whirlpool.element.style.cssText = 'display:inline-flex;width:14px;height:14px;margin-right:7px;';
+ const label = document.createElement('span');
+ label.textContent = 'Analyzing...';
+ msg.append(whirlpool.element, label);
+ } catch (_) {
+ msg.textContent = 'Analyzing...';
+ }
+ }
+ try {
+ const body = new FormData();
+ body.append('file', file);
+ const res = await fetch('/api/auth/settings/document-style/extract', {
+ method: 'POST', credentials: 'same-origin', body,
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok || !data.style) throw new Error(data.detail || data.error || 'Extraction failed');
+ styleEl.value = String(data.style);
+ if (msg) msg.textContent = '✓ Extracted — review and save';
+ } catch (error) {
+ if (msg) msg.textContent = error.message || 'Extraction failed';
+ } finally {
+ whirlpool?.destroy?.();
+ extractBtn.disabled = false;
+ fileEl.value = '';
+ }
+ });
+ }
diff --cc static/sw.js
index 97c35236c,f5635528a..0bdb47f38
--- a/static/sw.js
+++ b/static/sw.js
@@@ -7,7 -7,7 +7,7 @@@
// - Other static assets (images/fonts/libs): cache-first with bg refresh.
// - API / non-GET: never cached.
// Bump CACHE_NAME whenever the precache list or SW logic changes.
- const CACHE_NAME = 'odysseus-v651-chatgpt-usage-collapse';
-const CACHE_NAME = 'odysseus-v655-email-library-split';
++const CACHE_NAME = 'odysseus-v656-pr40-editor-precache';
// KaTeX resolves these from its own stylesheet, so caching the CSS without them
// gives offline math fallback glyphs instead of proper typesetting.
@@@ -113,6 -143,6 +143,7 @@@ const PANEL_PRECACHE =
'/static/js/galleryEditor.js?v=20260909movepicklayer1',
'/static/js/editor/ai-inpaint.js?v=20260708match1',
'/static/js/editor/ai-models.js',
++ '/static/js/editor/ai-operation.js',
'/static/js/editor/ai-rembg.js',
'/static/js/editor/ai-tool-runner.js',
'/static/js/editor/ai-tools-misc.js',
@@@ -163,6 -195,6 +196,8 @@@
'/static/js/editor/layer-geometry.js',
'/static/js/editor/precision-guides.js',
'/static/js/editor/layer-panel.js',
++ '/static/js/editor/layer-style-menu.js',
++ '/static/js/editor/layer-styles.js',
'/static/js/editor/mask-utils.js',
'/static/js/editor/shortcuts-popover.js',
'/static/js/editor/slider-ux.js',
@@@ -183,6 -215,6 +218,7 @@@
'/static/js/editor/tools/lasso.js',
'/static/js/editor/tools/marquee.js',
'/static/js/editor/tools/move.js',
++ '/static/js/editor/tools/pen-selection.js',
'/static/js/editor/tools/stroke.js',
'/static/js/editor/tools/transform-drag.js',
'/static/js/editor/tools/transform-handles.js',
diff --cc tests/documentSelectionCaret.mjs
index 1e6b837eb,000000000..ca5e9b991
mode 100644,000000..100644
--- a/tests/documentSelectionCaret.mjs
+++ b/tests/documentSelectionCaret.mjs
@@@ -1,48 -1,0 +1,48 @@@
- import { readFileSync } from 'node:fs';
+import assert from 'node:assert/strict';
++import { documentSource } from './helpers/document_source.mjs';
+import { chromium } from 'playwright';
+
- const source = readFileSync('static/js/document.js', 'utf8');
++const source = documentSource();
+const start = source.indexOf(' function clearSelection(');
+const cleanup = source.slice(start, source.indexOf(' function clearSelectionAt(', start));
+assert.equal((source.match(/if \(_selections.length\) clearSelection\(\{ preserveCaret: true \}\);/g) || []).length, 2);
+const browser = await chromium.launch({ headless: true });
+try {
+ const page = await browser.newPage();
+ await page.setContent('<div id="rich" contenteditable="true">before SELECT after</div><span id="doc-selection-badge"></span>');
+ await page.evaluate(cleanup => {
+ let _selections = [{ kind: 'rich' }];
+ const _richSelectionHighlightName = 'test-selection';
+ const rich = document.getElementById('rich');
+ const _emailRichbodyActive = () => rich;
+ const _scheduleDocumentStats = () => {};
+ eval(cleanup + '\nwindow.clearPinned = clearSelection;');
+ rich.addEventListener('input', () => {
+ if (_selections.length) window.clearPinned({ preserveCaret: true });
+ });
+ rich.focus();
+ const range = document.createRange();
+ range.setStart(rich.firstChild, 7);
+ range.setEnd(rich.firstChild, 13);
+ window.getSelection().removeAllRanges();
+ window.getSelection().addRange(range);
+ }, cleanup);
+ await page.keyboard.type('new');
+ const result = await page.evaluate(() => ({
+ text: document.getElementById('rich').textContent,
+ offset: window.getSelection().anchorOffset,
+ collapsed: window.getSelection().isCollapsed,
+ ranges: window.getSelection().rangeCount,
+ badge: document.getElementById('doc-selection-badge').style.display,
+ }));
+ assert.equal(result.text, 'before new after');
+ assert.equal(result.offset, 10);
+ assert.equal(result.collapsed, true);
+ assert.equal(result.ranges, 1);
+ assert.equal(result.badge, 'none');
+ await page.evaluate(() => window.clearPinned());
+ assert.equal(await page.evaluate(() => window.getSelection().rangeCount), 0);
+ console.log('PASS: replacement typing preserves caret; explicit clear still removes selection.');
+} finally {
+ await browser.close();
+}
diff --cc tests/editor-layer-styles.mjs
index 60285ff5f,000000000..1013c69fa
mode 100644,000000..100644
--- a/tests/editor-layer-styles.mjs
+++ b/tests/editor-layer-styles.mjs
@@@ -1,72 -1,0 +1,73 @@@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { chromium } from 'playwright';
++import { appCss } from './helpers/stylesheets.mjs';
+
+const browser = await chromium.launch({ headless: true });
+try {
+ const page = await browser.newPage();
+ await page.route('http://editor.test/**', async route => {
+ const path = new URL(route.request().url()).pathname;
+ if (path === '/') return route.fulfill({ contentType: 'text/html', body: '<button id="fx" style="position:fixed;bottom:4px;right:4px">fx</button>' });
+ if (!path.endsWith('.js')) return route.fulfill({ status: 404, body: '' });
+ return route.fulfill({ contentType: 'text/javascript', body: await readFile(new URL('../static/js/editor' + path, import.meta.url), 'utf8') });
+ });
+ await page.goto('http://editor.test/');
+ const results = await page.evaluate(async () => {
+ const { LAYER_STYLES } = await import('/layer-styles.js');
+ const { normalizeEffect, renderEffects, renderEffectsAsync, effectsWithPreview } = await import('/effects.js');
+ const source = document.createElement('canvas'); source.width = source.height = 64;
+ const ctx = source.getContext('2d'); ctx.fillStyle = '#668899'; ctx.fillRect(16, 16, 32, 32);
+ const original = ctx.getImageData(0, 0, 64, 64).data;
+ const shadow = normalizeEffect({ id: 'shadow', type: 'drop-shadow', params: { color: '#ff0000', opacity: 1, blur: 0, x: 8, y: 8 } });
+ const shadowed = renderEffects(source, [shadow]);
+ const pixel = (canvas, x, y) => [...canvas.getContext('2d').getImageData(x, y, 1, 1).data];
+ if (String(pixel(shadowed, 30, 30)) !== String(pixel(source, 30, 30))) throw Error('shadow covers source');
+ if (String(pixel(shadowed, 50, 50)) !== '255,0,0,255') throw Error('shadow offset or color');
+ const workerShadow = await renderEffectsAsync(source, [shadow]);
+ if (String(pixel(workerShadow, 50, 50)) !== String(pixel(shadowed, 50, 50))) throw Error('shadow worker mismatch');
+ const edited = { ...shadow, params: { ...shadow.params, x: 12 } };
+ const preview = effectsWithPreview({ effects: [shadow], _effectPreview: edited });
+ if (preview.length !== 1 || preview[0] !== edited) throw Error('duplicate preview');
+ const result = [];
+ for (const type of Object.keys(LAYER_STYLES)) {
+ const effect = normalizeEffect({ type });
+ if (normalizeEffect(JSON.parse(JSON.stringify(effect))).type !== type) throw Error('restore ' + type);
+ const sync = renderEffects(source, [effect]).getContext('2d').getImageData(0, 0, 64, 64).data;
+ if (!sync.some((v, i) => v !== original[i])) throw Error('no effect ' + type);
+ const asyncCanvas = await renderEffectsAsync(source, [effect]);
+ const asyncPixels = asyncCanvas.getContext('2d').getImageData(0, 0, 64, 64).data;
+ const difference = sync.reduce((max, v, i) => Math.max(max, Math.abs(v - asyncPixels[i])), 0);
+ if (difference > 2) throw Error('worker mismatch ' + type + ': ' + difference);
+ const hidden = renderEffects(source, [{ ...effect, visible: false }]).getContext('2d').getImageData(0, 0, 64, 64).data;
+ if (hidden.some((v, i) => v !== original[i])) throw Error('hidden ' + type);
+ if (ctx.getImageData(0, 0, 64, 64).data.some((v, i) => v !== original[i])) throw Error('mutated ' + type);
+ result.push(type);
+ }
+ return result;
+ });
+ assert.equal(results.length, 7);
- await page.addStyleTag({ content: await readFile(new URL('../static/style.css', import.meta.url), 'utf8') });
++ await page.addStyleTag({ content: await appCss() });
+ await page.evaluate(async () => {
+ const { openLayerStyleMenu } = await import('/layer-style-menu.js');
+ document.querySelector('#fx').onclick = event => { event.stopPropagation(); openLayerStyleMenu(event.currentTarget, () => {}); };
+ });
+ for (const viewport of [{ width: 1280, height: 720 }, { width: 375, height: 420 }]) {
+ await page.setViewportSize(viewport);
+ await page.locator('#fx').click();
+ const menu = page.locator('.ge-layer-style-menu');
+ assert.equal(await menu.locator('button').count(), 10);
+ const bounds = await menu.boundingBox();
+ assert.equal(await menu.evaluate(el => getComputedStyle(el).opacity), '1');
+ assert.ok(bounds.x >= 0 && bounds.y >= 0 && bounds.x + bounds.width <= viewport.width && bounds.y + bounds.height <= viewport.height);
+ await page.screenshot({ path: `/tmp/editor-layer-styles-${viewport.width}.png` });
+ await page.keyboard.press('Escape');
+ await page.waitForTimeout(30);
+ assert.equal(await menu.count(), 0);
+ }
+ await page.locator('#fx').click();
+ await page.locator('#fx').click();
+ await page.waitForTimeout(30);
+ assert.equal(await page.locator('.ge-layer-style-menu').count(), 0, 'repeat click closes menu');
+ console.log('7 styles: render, worker parity, restoration, visibility and source preservation passed; 10-item menu fits desktop/mobile and closes on Escape.');
+} finally { await browser.close(); }
diff --cc tests/editorRichUpdate.mjs
index fac8aeae0,000000000..d39243928
mode 100644,000000..100644
--- a/tests/editorRichUpdate.mjs
+++ b/tests/editorRichUpdate.mjs
@@@ -1,49 -1,0 +1,49 @@@
- import { readFileSync } from 'node:fs';
+import assert from 'node:assert/strict';
++import { documentSource } from './helpers/document_source.mjs';
+import { chromium } from 'playwright';
- const source = readFileSync('static/js/document.js', 'utf8');
++const source = documentSource();
+function extract(name) {
+ const start = source.indexOf(` function ${name}(`);
+ const rest = source.slice(start + 2);
+ const next = rest.slice(10).search(/\n (?:export )?(?:async )?function /);
+ return rest.slice(0, next + 10);
+}
+const functions = ['_showRichTextEditor', '_syncEmailRichbody'].map(extract).join('\n');
+const browser = await chromium.launch({headless:true});
+try {
+ const page = await browser.newPage();
+ await page.setContent('<div class="doc-editor-pane"><div id="doc-editor-wrap"></div><textarea id="doc-editor-textarea"></textarea><div id="doc-email-richbody" contenteditable="true"></div></div>');
+ const result = await page.evaluate(async (functions) => {
+ const docs = new Map(); const activeDocId = 'fixture';
+ let _richInlineCodeTypingArmed = false;
+ const _clearRichImageSelection = () => {};
+ const _normalizeRichTextImages = () => {};
+ const _normalizeRichChecklists = () => {};
+ const _normalizeRichInlineCode = () => {};
+ const _wireEmailRichbody = () => {};
+ const _syncRichEmptyImport = () => {};
+ const _isRichTextLang = lang => lang === 'richtext';
+ const _sanitizedRichTextHtml = rich => rich.innerHTML;
+ const _richTextContentToHtml = content => content;
+ const _emailRichbodyActive = () => document.getElementById('doc-email-richbody');
+ const newContent = '<p>This sentence needs work.</p><p><strong>Keep this.</strong></p>';
+ const doc = {id:activeDocId, language:'richtext',content:newContent}; docs.set(activeDocId,doc);
+ eval(functions + '\n_showRichTextEditor(doc);');
+ return {overlayGone:!document.querySelector('.doc-rich-diff-overlay'),rich:_emailRichbodyActive().innerHTML,mirror:document.getElementById('doc-editor-textarea').value,content:doc.content,newContent};
+ }, functions);
+ assert.equal(result.overlayGone, true);
+ assert.equal(result.rich,result.newContent); assert.equal(result.mirror,result.newContent); assert.equal(result.content,result.newContent);
+ const discardSource = source.slice(source.indexOf(' function exitDiffMode('), source.indexOf(' function isDiffModeActive('));
+ const staleSaveCount = await page.evaluate(discardSource => {
+ let _diffModeActive = true, _diffChunks = [], _diffOldContent = 'stale text', _diffNewContent = 'saved text', _diffUnresolvedCount = 1;
+ let saves = 0;
+ const saveDocument = () => { saves++; };
+ const syncHighlighting = () => {};
+ const updateLineNumbers = () => {};
+ eval(discardSource + '\nexitDiffMode(true, { persist: false });');
+ return saves;
+ }, discardSource);
+ assert.equal(staleSaveCount, 0);
+ console.log('PASS: saved rich-text changes appear immediately with no transient diff overlay.');
+ console.log('PASS: clearing a stale review diff cannot overwrite a newer saved edit.');
+} finally {await browser.close();}
diff --cc tests/editorSuggestionApply.mjs
index a6015e4a3,000000000..9ad712d91
mode 100644,000000..100644
--- a/tests/editorSuggestionApply.mjs
+++ b/tests/editorSuggestionApply.mjs
@@@ -1,71 -1,0 +1,71 @@@
- import { readFileSync } from 'node:fs';
+import assert from 'node:assert/strict';
++import { documentSource } from './helpers/document_source.mjs';
+import { chromium } from 'playwright';
+
- const source = readFileSync('static/js/document.js', 'utf8');
++const source = documentSource();
+const start = source.indexOf(' function _applySuggestions(');
+const end = source.indexOf(' /** Animate transition to next suggestion */', start);
+assert.ok(start >= 0 && end > start);
+const applySource = source.slice(start, end);
+
+const browser = await chromium.launch({ headless: true });
+try {
+ const page = await browser.newPage();
+ await page.setContent('<textarea id="doc-editor-textarea"></textarea><div id="doc-email-richbody"></div><iframe id="doc-html-preview"></iframe>');
+ const results = await page.evaluate((fn) => {
+ const textarea = document.getElementById('doc-editor-textarea');
+ const rich = document.getElementById('doc-email-richbody');
+ const docs = new Map();
+ const activeDocId = 'test-doc';
+ let saves = 0;
+ const errors = [];
+ const uiModule = { showError: message => errors.push(message) };
+ const saveCurrentToMap = () => {
+ const doc = docs.get(activeDocId);
+ doc.content = doc.language === 'richtext' ? rich.innerHTML :
+ doc.language === 'email' ? `To: [email protected]\n\n${rich.innerHTML}` : textarea.value;
+ };
+ const _isRichTextLang = lang => lang === 'richtext';
+ const _showRichTextEditor = doc => { rich.innerHTML = doc.content; textarea.value = doc.content; };
+ const _showEmailFields = doc => { rich.innerHTML = doc.content.split('\n\n').slice(1).join('\n\n'); };
+ const _refreshMarkdownPreviewIfVisible = () => {};
+ const _htmlPreviewActive = true;
+ const _isRenderLang = lang => lang === 'svg';
+ const _themedRenderSrcdoc = content => content;
+ const syncHighlighting = () => {};
+ const saveDocument = () => { saveCurrentToMap(); saves++; };
+ return eval(fn + `
+ const outcome = {};
+ for (const language of ['richtext', 'email', 'markdown', 'javascript', 'svg']) {
+ const original = language === 'email' ? 'To: [email protected]\\n\\n<p>old phrase</p>' :
+ language === 'richtext' ? '<p>old phrase</p>' : 'old phrase';
+ docs.set(activeDocId, { id: activeDocId, language, content: original });
+ if (language === 'email' || language === 'richtext') rich.innerHTML = '<p>old phrase</p>';
+ else textarea.value = original;
+ const applied = _applySuggestions([{ id: 'one', find: 'old phrase', replace: 'new phrase' }]);
+ outcome[language] = {
+ applied, content: docs.get(activeDocId).content,
+ preview: document.getElementById('doc-html-preview').srcdoc,
+ visible: language === 'email' || language === 'richtext' ? rich.innerHTML : textarea.value,
+ };
+ }
+ const before = saves;
+ const unmatched = _applySuggestions([{ id: 'missing', find: 'absent phrase', replace: 'x' }]);
+ ({ outcome, saves, before, unmatched, errors });
+ `);
+ }, applySource);
+ for (const language of ['richtext', 'email', 'markdown', 'javascript', 'svg']) {
+ assert.deepEqual(results.outcome[language].applied, ['one']);
+ assert.match(results.outcome[language].content, /new phrase/);
+ assert.match(results.outcome[language].visible, /new phrase/);
+ }
+ assert.match(results.outcome.svg.preview, /new phrase/);
+ assert.equal(results.saves, 5);
+ assert.equal(results.before, 5);
+ assert.deepEqual(results.unmatched, []);
+ assert.equal(results.errors.length, 1);
+ console.log('PASS: accepting suggestions updates and saves rich text, email, markdown, and code documents.');
+ console.log('PASS: stale suggestions remain pending and do not save an unchanged document.');
+} finally {
+ await browser.close();
+}
diff --cc tests/editorSuggestionButtons.mjs
index 0aad688e0,000000000..549bcf54b
mode 100644,000000..100644
--- a/tests/editorSuggestionButtons.mjs
+++ b/tests/editorSuggestionButtons.mjs
@@@ -1,53 -1,0 +1,54 @@@
- import { readFileSync } from 'node:fs';
+import assert from 'node:assert/strict';
++import { documentSource } from './helpers/document_source.mjs';
+import { chromium } from 'playwright';
++import { appCss } from './helpers/stylesheets.mjs';
+
- const source = readFileSync('static/js/document.js', 'utf8');
++const source = documentSource();
+const start = source.indexOf(' function _showCurrentSuggestion()');
+const end = source.indexOf(' /** Show inline diff by modifying', start);
+assert.ok(start >= 0 && end > start);
+const renderSource = source.slice(start, end);
+
+const browser = await chromium.launch({ headless: true });
+try {
+ const page = await browser.newPage({ viewport: { width: 700, height: 500 } });
+ await page.setContent('<div class="doc-editor-pane"><div id="doc-editor-wrap"></div></div>');
- await page.addStyleTag({ path: 'static/style.css' });
++ await page.addStyleTag({ content: await appCss() });
+ const result = await page.evaluate(code => {
+ let _activeSuggestions = [];
+ let _suggestionTotal = 0, _suggestionIndex = 0;
+ let accepted = [];
+ const _clearSuggestionHighlight = () => {};
+ const topPortalZ = () => 10031;
+ const _clearInlineDiff = () => {};
+ const _clearSuggestionTextSelection = () => {};
+ const _esc = value => String(value || '');
+ const clearAllSuggestions = () => {};
+ const _applySuggestions = suggestions => { accepted = suggestions.map(s => s.id); return accepted; };
+ const _animateNext = () => {};
+ return eval(code + `
+ const inspect = count => {
+ _activeSuggestions = Array.from({length:count}, (_, i) => ({id:String(i),find:'old'+i,replace:'new'+i,reason:'Reason'}));
+ _suggestionTotal = count;
+ _showCurrentSuggestion();
+ const card = document.getElementById('doc-suggestion-active');
+ const buttons = [...card.querySelectorAll('.doc-suggestion-actions button')];
+ const cardRight = card.getBoundingClientRect().right;
+ return {labels:buttons.map(button => button.textContent.trim()),
+ fits:buttons.every(button => button.getBoundingClientRect().right <= cardRight + 1)};
+ };
+ const one = inspect(1);
+ const many = inspect(3);
+ document.querySelector('.doc-suggestion-accept-all').click();
+ ({one, many, accepted});
+ `);
+ }, renderSource);
+ assert.deepEqual(result.one.labels, ['Accept', 'Accept All', 'Skip']);
+ assert.deepEqual(result.many.labels, ['Accept', 'Accept All', 'Skip']);
+ assert.equal(result.one.fits, true);
+ assert.equal(result.many.fits, true);
+ assert.deepEqual(result.accepted, ['0', '1', '2']);
+ console.log('PASS: Accept, Accept All, and Skip stay visible and fit in one row.');
+} finally {
+ await browser.close();
+}
diff --cc tests/helpers/document_source.mjs
index 000000000,000000000..c92187f57
new file mode 100644
--- /dev/null
+++ b/tests/helpers/document_source.mjs
@@@ -1,0 -1,0 +1,32 @@@
++// JS twin of tests/helpers/document_source.py: the document editor's whole
++// implementation set, so tests keep finding code as it moves out of the
++// static/js/document.js entry into static/js/document/.
++import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
++import { dirname, join } from 'node:path';
++import { fileURLToPath } from 'node:url';
++
++const HERE = dirname(fileURLToPath(import.meta.url));
++const JS = join(HERE, '..', '..', 'static', 'js');
++const ENTRY = join(JS, 'document.js');
++const IMPL_DIR = join(JS, 'document');
++
++function walk(dir) {
++ return readdirSync(dir).sort().flatMap(name => {
++ const path = join(dir, name);
++ if (statSync(path).isDirectory()) return walk(path);
++ return name.endsWith('.js') ? [path] : [];
++ });
++}
++
++/** Every file holding document-editor implementation, entry first. */
++export function documentSourcePaths() {
++ if (!existsSync(ENTRY)) {
++ throw new Error(`document editor entry point is missing: ${ENTRY}`);
++ }
++ return [ENTRY, ...(existsSync(IMPL_DIR) ? walk(IMPL_DIR).sort() : [])];
++}
++
++/** The whole implementation set as one string, entry first. */
++export function documentSource() {
++ return documentSourcePaths().map(path => readFileSync(path, 'utf8')).join('\n');
++}
diff --cc tests/helpers/test_settings_shell_coordinator.mjs
index 79bf1fd84,199f6283b..8336d5922
--- a/tests/helpers/test_settings_shell_coordinator.mjs
+++ b/tests/helpers/test_settings_shell_coordinator.mjs
@@@ -796,6 -820,6 +820,14 @@@ const STUBS = new Map(
},
},
],
++ [
++ path.join(JS, 'editor/ai-models.js'),
++ {
++ modelCaps() {
++ return {};
++ },
++ },
++ ],
[
path.join(JS, 'providers.js'),
{
diff --cc tests/historyResumeRendering.test.mjs
index 5e08016a9,ee1faf5fb..5b97ae95a
--- a/tests/historyResumeRendering.test.mjs
+++ b/tests/historyResumeRendering.test.mjs
@@@ -54,9 -54,8 +54,10 @@@ async function setup()
window.markdownModule = (await import('/static/js/markdown.js')).default;
markdownModule.renderMermaid = undefined;
window.createTurnRendering = (await import('/static/js/turnRendering.js')).createTurnRendering;
+ window.startsContinuationRound = (await import('/static/js/turnRendering.js')).startsContinuationRound;
window.applyModelRouteEventState = (await import('/static/js/chatModelProvenance.js')).applyModelRouteEventState;
window.createTerminalStreamError = (await import('/static/js/chatStreamErrors.js')).createTerminalStreamError;
++ window.generatedImageResult = (await import('/static/js/generatedImageResult.js')).generatedImageResult;
window.addMessage = (0, eval)('(' + addMessage + ')');
window.resumeStream = (0, eval)('(' + resume + ')');
window.chatRenderer = { addMessage: window.addMessage, recordSessionMetricsCost: noop, buildSourcesBox, buildFindingsBox, buildRagSourcesBox };
diff --cc tests/test_background_chat_completion_ui_static.py
index 3a7f50b51,a64f7fb47..436da2f3d
--- a/tests/test_background_chat_completion_ui_static.py
+++ b/tests/test_background_chat_completion_ui_static.py
@@@ -24,15 -25,15 +25,16 @@@ def test_background_completion_survives
def test_sidebar_has_clear_working_and_done_states():
-- assert "session-run-state" in SESSIONS
-- assert "Agent finished while you were away" in SESSIONS
-- assert ".session-run-state.is-working" in CSS
-- assert ".session-run-state.is-done" in CSS
++ # The provider star carries the run state: it spins while working and
++ # becomes a check mark when done. The separate text pill is retired, and
++ # any pill left from an older render is removed.
++ assert "star.classList.toggle('processing', isRunning)" in SESSIONS
++ assert "star.classList.toggle('notify', isCompleted)" in SESSIONS
++ assert "listItem.querySelector('.session-run-state')" in SESSIONS
++ assert "state.remove();" in SESSIONS
assert ".session-star.notify::after" in CSS
-- assert "content: '\\2713'" in CSS
++ assert "polyline points='20 6 9 17 4 12'" in CSS
assert ".session-star.notify {\n animation: none;" in CSS
-- assert "spinnerModule.createWhirlpool(12)" in SESSIONS
-- assert "session-run-whirlpool" in CSS
assert "state.textContent = 'Working'" not in SESSIONS
diff --cc tests/test_browser_observation.py
index 835ca00ca,000000000..d84bbfdcc
mode 100644,000000..100644
--- a/tests/test_browser_observation.py
+++ b/tests/test_browser_observation.py
@@@ -1,31 -1,0 +1,40 @@@
+import json
+
+from src.clean_agent_preview import preview_tool_result_text
+
+
++def test_legacy_page_text_retains_access_block_evidence():
++ result = {'url': 'https://example.org', 'title': 'Security verification',
++ 'text': 'Unusual traffic. Complete the CAPTCHA.'}
++ output = preview_tool_result_text({'output': json.dumps(result), 'exit_code': 0},
++ 'private_browser', {})
++ assert 'Security verification' in output
++ assert 'Complete the CAPTCHA' in output
++
++
+def test_snapshot_survives_large_duplicate_refs():
+ result = {'refs': {f'e{i}': {'name': 'noise' * 50} for i in range(1000)},
+ 'origin': 'https://example.org',
+ 'snapshot': '- button "Categories" [ref=e12]\n- link "Co-Operative" [ref=e999]'}
+ output = preview_tool_result_text({'output': json.dumps([{'result': result}]), 'exit_code': 0},
+ 'private_browser', {})
+ assert 'Co-Operative' in output and '[ref=e999]' in output
+ assert 'Categories' in output and 'https://example.org' in output
+ assert 'noise' not in output and len(output) < 300
+
+
+def test_failed_click_retains_error_and_updated_refs():
+ output = preview_tool_result_text({'exit_code': 1, 'output':
+ 'Element covered\n\n[page state after failed click]\n' + json.dumps([
+ {'result': {'snapshot': '- dialog "Choices"\n- button "Close" [ref=e2]'}}])},
+ 'private_browser', {'action': 'click'})
+ assert 'Exit code: 1' in output and 'Element covered' in output
+ assert 'Close' in output and '[ref=e2]' in output
+
+
+def test_long_snapshot_is_bounded_with_explicit_omission():
+ snapshot = '\n'.join(f'- link "Item {i}" [ref=e{i}]' for i in range(2000))
+ output = preview_tool_result_text({'output': json.dumps({'snapshot': snapshot})}, 'private_browser', {})
+ assert len(output) <= 8000
+ assert 'shortened at line boundaries' in output
+ assert '[ref=e0]' in output and '[ref=e1999]' in output
diff --cc tests/test_browser_transport_recovery.py
index d0d0307d6,000000000..6cb0cdca3
mode 100644,000000..100644
--- a/tests/test_browser_transport_recovery.py
+++ b/tests/test_browser_transport_recovery.py
@@@ -1,125 -1,0 +1,125 @@@
+import pytest
+
+from src.clean_agent_preview import browser_transport_recovery
+
+
+URL = 'https://example.com/catalog/'
+
+
[email protected]('error', ['HTTP2_PROTOCOL_ERROR', 'NAME_NOT_RESOLVED', 'CONNECTION_RESET'])
+def test_failed_navigation_preserves_task_and_uses_permitted_fetch(error):
+ message = browser_transport_recovery(
+ {'action': 'open', 'url': URL}, 'net::ERR_' + error, {'web_fetch'}, set())
+ assert URL in message
+ assert 'original objective' in message
+ assert 'Use web_fetch once' in message
+
+
+def test_exhausted_fetch_uses_search_instead_of_bouncing():
+ message = browser_transport_recovery(
+ {'action': 'open', 'url': URL}, 'net::ERR_HTTP2_PROTOCOL_ERROR',
+ {'web_fetch', 'web_search'}, {URL.rstrip('/')})
+ assert 'Use web_search' in message
+ assert 'Use web_fetch' not in message
+
+
[email protected]('action', ['click', 'fill', 'press', 'evaluate'])
+def test_mutating_batch_never_replayed(action):
+ assert not browser_transport_recovery(
+ {'action': 'batch', 'commands': [['open', URL], [action, 'target']]},
+ 'net::ERR_HTTP2_PROTOCOL_ERROR', {'web_fetch'}, set())
+
+
+def test_read_only_batch_and_no_available_tools():
+ message = browser_transport_recovery(
+ {'action': 'batch', 'commands': [['open', URL], ['snapshot']]},
+ 'net::ERR_HTTP2_PROTOCOL_ERROR', set(), set())
+ assert 'No permitted retrieval fallback' in message
+
+
[email protected]('output', ['net::ERR_CERT_AUTHORITY_INVALID', 'CAPTCHA', 'Access denied', 'OK'])
+def test_no_transport_recovery_for_security_or_success(output):
+ assert not browser_transport_recovery({'action': 'open', 'url': URL}, output, {'web_fetch'}, set())
+
+
[email protected]('fetch_succeeds', [False, True])
+async def test_stream_recovers_navigation_then_fetch_without_email_classifier(monkeypatch, fetch_succeeds):
+ import json
+ from types import SimpleNamespace
+ from dataclasses import replace
+ import src.clean_agent_preview as module
+ import src.email_task_intent as email_intent
+ from src.tool_policy import ToolPolicy
+ from src.tool_schemas import FUNCTION_TOOL_SCHEMAS
+ from src.turn_contract import resolve_full_inventory_contract
+
+ requests, calls = [], []
+ def call(name, args):
+ return {'tool_calls': [{'index': 0, 'id': name, 'type': 'function',
+ 'function': {'name': name, 'arguments': json.dumps(args)}}]}
+ responses = iter([
+ call('private_browser', {'action': 'batch', 'commands': [['open', URL], ['find', 'wardrobe'], ['snapshot']]}),
+ call('web_fetch', {'url': URL}),
+ call('web_search', {'query': 'wardrobe'}),
+ {'content': 'The site could not be read and no usable product evidence was found.'},
+ ])
+ class Response:
+ def __init__(self, delta): self.delta = delta
+ async def __aenter__(self): return self
+ async def __aexit__(self, *args): pass
+ def raise_for_status(self): pass
+ async def aiter_lines(self):
+ yield 'data: ' + json.dumps({'choices': [{'delta': self.delta}]})
+ yield 'data: [DONE]'
+ class Client:
+ def __init__(self, **kwargs): pass
+ async def __aenter__(self): return self
+ async def __aexit__(self, *args): pass
+ def stream(self, *args, **kwargs):
+ requests.append(kwargs['json'])
+ return Response(next(responses))
+ async def execute(block, **kwargs):
+ calls.append(block.tool_type)
+ if block.tool_type == 'private_browser':
+ return block.tool_type, {'output': 'net::ERR_HTTP2_PROTOCOL_ERROR', 'exit_code': 1}
+ if block.tool_type == 'web_fetch':
+ return block.tool_type, {'output': 'Homepage navigation' if fetch_succeeds else 'Connection reset',
+ 'exit_code': 0 if fetch_succeeds else 1}
+ assert 'site:example.com' in block.content
+ return block.tool_type, {'output': 'No usable product results.', 'exit_code': 0}
+ async def no_email_classifier(*args, **kwargs):
+ raise AssertionError('Web-only request must not use email interpretation')
+ monkeypatch.setattr(module.httpx, 'AsyncClient', Client)
+ monkeypatch.setattr(module, 'execute_tool_block', execute)
+ monkeypatch.setattr(email_intent, 'classify_email_task', no_email_classifier)
+ policy = ToolPolicy()
+ schemas = [s for s in FUNCTION_TOOL_SCHEMAS if s['function']['name'] in {'private_browser', 'web_fetch', 'web_search'}]
+ contract = replace(resolve_full_inventory_contract(schemas=schemas, policy=policy),
+ required=frozenset({'private_browser'}))
+ chunks = [chunk async for chunk in module.stream_preview(
+ endpoint_url='http://fixture', model='Ajax', headers={}, turn_contract=contract,
+ history_session=SimpleNamespace(history=[
+ {'role': 'user', 'content': 'Browse https://wrong.example/catalog/ and find a wardrobe'},
+ {'role': 'assistant', 'content': 'Navigation failed.'}]),
+ messages=[{'role': 'user', 'content': 'Browse https://wrong.example/catalog/ and find a wardrobe'},
+ {'role': 'assistant', 'content': 'Navigation failed.'},
+ {'role': 'user', 'content': URL}],
+ session_id='fixture-browser', owner='test', disabled_tools=set(), tool_policy=policy)]
+ assert calls == ['private_browser', 'web_fetch', 'web_search'], '\n'.join(chunks)
- assert requests[1]['tool_choice'] == 'required'
++ assert requests[1]['tool_choice'] == 'auto'
+ assert [s['function']['name'] for s in requests[1]['tools']] == ['web_fetch']
- assert requests[2]['tool_choice'] == 'required'
++ assert requests[2]['tool_choice'] == 'auto'
+ assert [s['function']['name'] for s in requests[2]['tools']] == ['web_search']
+ assert any('browser_transport_fallback' in chunk for chunk in chunks)
+ assert any('[DONE]' in chunk for chunk in chunks)
+ assert all(m['role'] != 'system' for m in requests[0]['messages'][1:])
+ assert 'Corrected target: ' + URL in requests[0]['messages'][0]['content']
+
+
[email protected]('arguments', ['"url"', '[]', 'null', '42'])
+def test_provider_history_requires_object_tool_arguments(arguments):
+ from src.clean_agent_preview import protocol_safe_tool_calls
+ calls = [{'function': {'name': 'web_fetch', 'arguments': arguments}}]
+ assert protocol_safe_tool_calls(calls)[0]['function']['arguments'] == '{}'
+ assert calls[0]['function']['arguments'] == arguments
diff --cc tests/test_chat_ttft_timer_static.py
index d5d28b430,303f66699..cf1e00566
--- a/tests/test_chat_ttft_timer_static.py
+++ b/tests/test_chat_ttft_timer_static.py
@@@ -25,10 -25,11 +25,11 @@@ def test_measured_ttft_is_shown_in_mess
def test_compact_footer_and_details_show_real_performance_counters():
assert "`${Number(tps).toFixed(2)} tok/s`" in RENDERER
- assert "`${Number(ttft).toFixed(3)}s TTFT`" in RENDERER
- assert "`${Number(injectedTokens).toLocaleString()} in`" in RENDERER
+ assert "const visibleTtft = metrics.client_ttft ?? metrics.time_to_first_token" in RENDERER
+ assert "${Number(visibleTtft).toFixed(3)}s" in RENDERER
- assert "${Number(injectedTokens).toLocaleString()}" in RENDERER
assert '<span class="ctx-label">Input</span>' in RENDERER
-- assert '<span class="ctx-label">Injected</span>' in RENDERER
++ # Injected-context size is no longer a separate details row.
++ assert '<span class="ctx-label">Injected</span>' not in RENDERER
assert 'all rounds' not in RENDERER
assert 'first request' not in RENDERER
assert 'Tool schemas' in RENDERER
diff --cc tests/test_chatgpt_reasoning_and_grouping.py
index 9c36ad474,b94f8d1e7..adc3fe171
--- a/tests/test_chatgpt_reasoning_and_grouping.py
+++ b/tests/test_chatgpt_reasoning_and_grouping.py
@@@ -108,14 -109,14 +109,15 @@@ def test_composer_reasoning_effort_ui_m
assert 'id="reasoning-effort-current"' in html
assert 'id="reasoning-effort-menu"' in html
assert 'title="Reasoning effort"' in html
-- assert 'class="reasoning-effort-prefix">Effort: </span>' in html
++ assert 'class="reasoning-effort-prefix">Reasoning effort</span>' in html
# CSS classes
assert ".reasoning-effort-wrap" in css
assert ".reasoning-effort-btn" in css
assert ".reasoning-effort-menu" in css
assert ".reasoning-effort-option" in css
-- # Responsive hide of prefix
-- assert ".reasoning-effort-prefix { display: none; }" in css
++ # The control lives in the Chat Context popup, where the prefix is the
++ # row label rather than chat-bar text hidden at narrow widths.
++ assert ".chat-context-popup .reasoning-effort-prefix {" in css
def test_chat_submit_includes_reasoning_effort():
diff --cc tests/test_clean_agent_preview.py
index b0f5f503c,e85abc8ac..6be1af5f6
--- a/tests/test_clean_agent_preview.py
+++ b/tests/test_clean_agent_preview.py
@@@ -4377,11 -4360,11 +4377,13 @@@ def test_v3_schema_uses_configured_vers
monkeypatch.setenv('ODYSSEUS_TOOL_CONTRACT_ROOT', str(contract_root))
module.contract_builder.cache_clear()
try:
-- notes = next(
++ # Probe a tool whose compact description the harness does not
++ # replace; manage_notes now carries a full harness-owned override.
++ search = next(
s for s in FUNCTION_TOOL_SCHEMAS
-- if s['function']['name'] == 'manage_notes'
++ if s['function']['name'] == 'web_search'
)
-- compact = module.compact_schemas([notes])[0]
++ compact = module.compact_schemas([search])[0]
assert compact['function']['description'].startswith('versioned-contract-loaded')
finally:
module.contract_builder.cache_clear()
@@@ -4392,7 -4375,7 +4394,8 @@@ def test_v3_document_edit_schema_has_on
if s['function']['name'] == 'edit_document')
parameters = edit['function']['parameters']
assert parameters['required'] == ['edits']
-- assert set(parameters['properties']) == {'edits'}
++ assert set(parameters['properties']) == {'edits', 'more'}
++ assert parameters['properties']['more']['type'] == 'boolean'
def test_v3_ui_schema_advertises_only_policy_executable_client_local_actions():
@@@ -5650,7 -5551,7 +5653,7 @@@ async def test_blocked_search_engine_br
)
raw = [chunk async for chunk in stream_preview(
endpoint_url='http://test', model='test',
-- messages=[{'role': 'user', 'content': 'Open browser and find the latest AI news.'}],
++ messages=[{'role': 'user', 'content': 'Open browser and find an AI model release.'}],
headers={}, turn_contract=contract, session_id='test', owner='test',
disabled_tools=set(), tool_policy=ToolPolicy(), max_rounds=4,
)]
@@@ -5720,7 -5621,7 +5723,9 @@@ async def test_native_stream_reserves_r
async def execute(block, **kwargs):
executed.append(block.tool_type)
-- return block.tool_type, {"output": "ok", "exit_code": 0}
++ return block.tool_type, {"output": "ok", "exit_code": 0,
++ "materialized_artifacts": ["/tmp_workspace/results"]
++ if block.tool_type == "python" and "out.md" in block.content else []}
monkeypatch.setattr(module.httpx, "AsyncClient", Client)
monkeypatch.setattr(module, "execute_tool_block", execute)
@@@ -5832,7 -5733,7 +5837,9 @@@ async def test_native_stream_reserves_w
executed.append(block.tool_type)
if block.tool_type == "web_search":
now[0] = 450.0
-- return block.tool_type, {"output": "ok", "exit_code": 0}
++ return block.tool_type, {"output": "ok", "exit_code": 0,
++ "materialized_artifacts": ["/tmp_workspace/results"]
++ if block.tool_type == "python" and "out.md" in block.content else []}
monkeypatch.setattr(module.time, "monotonic", lambda: now[0])
monkeypatch.setattr(module.httpx, "AsyncClient", Client)
diff --cc tests/test_document_edit_reference_js.py
index 243d23406,9ee7842ff..e214a6b06
--- a/tests/test_document_edit_reference_js.py
+++ b/tests/test_document_edit_reference_js.py
@@@ -1,6 -1,8 +1,8 @@@
"""Regression guards for document-selection references in chat bubbles."""
from pathlib import Path
+ from tests.helpers.stylesheets import app_css
-from tests.helpers.document_source import document_source
++from tests.helpers.document_source import document_source, function_body
ROOT = Path(__file__).resolve().parents[1]
@@@ -46,7 -48,7 +48,7 @@@ def test_document_module_has_one_browse
def test_clearing_a_rich_selection_also_resets_native_selection_stats():
-- clear_body = DOCUMENT.split("function clearSelection() {", 1)[1].split("\n }", 1)[0]
++ clear_body = function_body("clearSelection")
assert "browserSelection.removeAllRanges()" in clear_body
assert "_scheduleDocumentStats()" in clear_body
diff --cc tests/test_document_source_test_hygiene.py
index 000000000,ab68844ac..82b326f53
mode 000000,100644..100644
--- a/tests/test_document_source_test_hygiene.py
+++ b/tests/test_document_source_test_hygiene.py
@@@ -1,0 -1,200 +1,197 @@@
+ """Tests must reason about the document editor's module set, not one file.
+
+ ``static/js/document.js`` is being decomposed. It stays the URL the browser
+ requests, so a browser test that imports ``/static/js/document.js`` keeps
+ working. What does not survive is reading the file off disk: a test that greps
+ the entry file alone silently covers less as soon as the behaviour it names
+ moves into a module, and it keeps passing while doing so.
+
+ ``tests/helpers/document_source`` is the way to read it. This fails on the two
+ habits that break, both of which existed here before the helper did.
+ """
+
+ import re
+ from pathlib import Path
+
+ ROOT = Path(__file__).resolve().parents[1]
+ SELF = Path(__file__).name
+
+ # The helper itself names the file, because being the one place that does is
+ # the point.
-ALLOWED = {SELF, "document_source.py"}
++ALLOWED = {SELF, "document_source.py", "document_source.mjs"}
+
+ # Every test language the assertions can hide in. A Python-only glob is what
+ # let the JS references to ``static/style.css`` outlive the file they named.
+ _SUFFIXES = ("*.py", "*.mjs", "*.js", "*.html")
+
+ # Reading the entry file off disk. Not matched: `/static/js/document.js` as a
+ # request URL or a dynamic `import()`, which stay correct through the wrapper,
+ # and which `test_frontend_module_version_parity.py` already pins.
+ _DIRECT_READ = re.compile(
+ r'["\']static/js/document\.js["\']' # string literal
+ r'|"static"\s*/\s*"js"\s*/\s*"document\.js"' # pathlib join
+ )
+
+ # Slices of the form `src.split(A, 1)[1].split(B, 1)[0]` -- "the region between
+ # A and B". That region is only what the test means while A and B are
+ # neighbours in one file. Several also hard-code the entry file's two-space
+ # indentation, which no extracted module reproduces.
+ _ADJACENCY_SLICE = re.compile(
+ r'(?P<var>\b[A-Za-z_]\w*)\.split\(\s*\n?\s*(?P<q1>["\'])(?P<a>(?:[^"\'\\]|\\.)+?)(?P=q1)'
+ r'\s*,\s*1\s*\)\[1\]\s*\n?\s*\.split\(\s*\n?\s*(?P<q2>["\'])(?P<b>(?:[^"\'\\]|\\.)+?)(?P=q2)'
+ r'\s*,\s*1\s*\)\[0\]',
+ re.S,
+ )
+
+ # The adjacency slices still in the tree, each spanning a whole family of
+ # functions rather than one construct -- "everything from _docxHexColor to
+ # exportAsDocx". Collapsing one to its first member drops what the assertions
+ # look for, so they cannot be rewritten mechanically: each is converted when
+ # the family it spans becomes a module, and its entry deleted here then.
+ #
+ # This list may only shrink. A new entry means a new adjacency-dependent slice
+ # was written, which is the habit the helper exists to end.
+ KNOWN_ADJACENCY_SLICES = {
+ ('test_document_active_restore.py',
+ 'for (const doc of activeDocs)',
+ '_syncDocIndicator'),
- ('test_document_edit_reference_js.py',
- 'function clearSelection() {',
- '\\n }'),
+ ('test_document_rich_checklist_enter.py',
+ 'function _handleRichChecklistEnter',
+ 'let _richInlineCodeTypingArmed'),
+ ('test_document_rich_docx_export.py',
+ 'async function exportAsDocx',
+ '/** Delete the active document'),
+ ('test_document_rich_docx_export.py',
+ 'function _docxHexColor',
+ 'async function exportAsDocx'),
+ ('test_document_rich_structure_tools.py',
+ 'function _showMdDropdown',
+ 'function initMdToolbar'),
+ ('test_document_rich_table_header_preservation.py',
+ 'function _applyRichTableAction',
+ 'function applyMdFormat'),
+ ('test_document_rich_table_header_preservation.py',
+ 'function _richTableHeaderModes',
+ 'function _replaceRichTable'),
+ ('test_document_rich_table_headers.py',
+ 'function _applyRichTableAction',
+ 'function applyMdFormat'),
+ ('test_document_rich_table_merge_split.py',
+ 'function _showMdDropdown',
+ 'function initMdToolbar'),
+ ('test_document_rich_text_tools.py',
+ '// ---- Selection-based AI editing ----',
+ '// ── Inline Suggestion Comments'),
+ ('test_document_rich_text_tools.py',
+ '// Undo button in header',
+ '// Diff toggle button'),
+ ('test_document_rich_text_tools.py',
+ '// ── In-document find (Ctrl+F) ──',
+ '// Delete (or Backspace)'),
+ ('test_document_rich_text_tools.py',
+ 'const _richSpacingBlockSelector',
+ 'function _focusRichTextOffset'),
+ ('test_document_rich_text_tools.py',
+ 'function _insertRichTextImages',
+ 'async function _uploadMarkdownImages'),
+ ('test_document_rich_text_tools.py',
+ 'function _normalizeRichLinkUrl',
+ 'function _promptImageAlt'),
+ ('test_document_rich_text_tools.py',
+ 'function _normalizeRichLinkUrl',
+ 'function _promptLink'),
+ ('test_document_rich_text_tools.py',
+ 'function _replaceAllLiteral',
+ 'function _doFind'),
+ ('test_document_rich_text_tools.py',
+ 'function _replaceRichTable',
+ 'function applyMdFormat'),
+ ('test_document_rich_text_tools.py',
+ 'function _richLinkAtRange',
+ 'function _richSelectionCell'),
+ ('test_document_rich_text_tools.py',
+ 'function _richSelectionChecklistItem',
+ 'function _cleanRichTextPasteHtml'),
+ ('test_document_rich_text_tools.py',
+ 'function _richSelectionInlineCode',
+ 'function _cleanRichTextPasteHtml'),
+ ('test_document_rich_text_tools.py',
+ 'function _showMdDropdown',
+ 'function initMdToolbar'),
+ ('test_document_rich_text_tools.py',
+ 'function _wireEmailRichbody',
+ 'function _richSelectionElement'),
+ ('test_document_rich_toolbar_menus.py',
+ 'function _showMdDropdown',
+ 'function initMdToolbar'),
+ ('test_document_rich_toolbar_menus.py',
+ 'function initMdToolbar',
+ 'function _applyDocFont'),
+ ('test_document_toolbar_order.py',
+ 'const _DOCUMENT_TOOLBAR_GROUPS',
+ 'function _orderDocumentToolbar'),
+ ('test_review_docx_async_identity.py',
+ ' let _docxPreviewRequest = 0;',
+ ' /** Parse CSV'),
+ }
+
+
+ def _test_sources() -> list[Path]:
+ found: list[Path] = []
+ for suffix in _SUFFIXES:
+ found.extend((ROOT / "tests").rglob(suffix))
+ return [p for p in sorted(set(found)) if p.name not in ALLOWED]
+
+
+ def test_sources_are_discoverable() -> None:
+ """Guard the guard: a layout change must not make this vacuous."""
+ sources = _test_sources()
+ assert len(sources) > 100
+ suffixes = {p.suffix for p in sources}
+ assert {".py", ".mjs", ".js"} <= suffixes, suffixes
+ assert any(p.parent != ROOT / "tests" for p in sources), "walk is not recursive"
+
+
+ def test_no_test_reads_the_document_entry_file_off_disk() -> None:
+ offenders = [
+ str(p.relative_to(ROOT))
+ for p in _test_sources()
+ if _DIRECT_READ.search(p.read_text(encoding="utf-8"))
+ ]
+
+ assert not offenders, (
+ "read the document editor through tests.helpers.document_source instead "
+ "of static/js/document.js, which is becoming a re-export wrapper: "
+ f"{offenders}"
+ )
+
+
+ def test_adjacency_slices_only_shrink() -> None:
+ """No new "region between two declarations" slice enters the tree."""
+ found = set()
+ for path in _test_sources():
+ if path.suffix != ".py":
+ continue
+ source = path.read_text(encoding="utf-8")
+ if "tests.helpers.document_source" not in source:
+ continue
+ bound = {
+ m.group(1)
+ for m in re.finditer(r"(\w+)\s*=\s*document_source\(\)", source)
+ }
+ for m in _ADJACENCY_SLICE.finditer(source):
+ if m.group("var") in bound:
+ found.add((path.name, m.group("a"), m.group("b")))
+
+ added = found - KNOWN_ADJACENCY_SLICES
+ assert not added, (
+ "these slices depend on two declarations being neighbours in one file, "
+ "which decomposition breaks; use function_body()/declaration() or "
+ "assert against the owning module: " + repr(sorted(added))
+ )
+
+ removed = KNOWN_ADJACENCY_SLICES - found
+ assert not removed, (
+ "these adjacency slices are gone -- delete them from "
+ f"KNOWN_ADJACENCY_SLICES so the list keeps shrinking: {sorted(removed)}"
+ )
diff --cc tests/test_editor_ai_tool_runner_static.py
index 5f6a1718b,5f6a1718b..8bb62b488
--- a/tests/test_editor_ai_tool_runner_static.py
+++ b/tests/test_editor_ai_tool_runner_static.py
@@@ -3,13 -3,13 +3,17 @@@ from pathlib import Pat
ROOT = Path(__file__).resolve().parents[1]
RUNNER = (ROOT / "static/js/editor/ai-tool-runner.js").read_text(encoding="utf-8")
++OPERATION = (ROOT / "static/js/editor/ai-operation.js").read_text(encoding="utf-8")
def test_ai_runner_keeps_busy_state_until_result_image_is_decoded():
-- assert "await new Promise((resolve, reject) =>" in RUNNER
-- assert "img.onload = resolve;" in RUNNER
-- assert "reject(new Error('Failed to decode result image'))" in RUNNER
++ # Decoding lives in the shared, cancellable ai-operation helper.
++ assert "const img = await decodeAIImage(data.image, operation.signal);" in RUNNER
++ assert "image.onload = () => { cleanup(); resolve(image); };" in OPERATION
++ assert "reject(new Error('Failed to decode result image'))" in OPERATION
assert "layer.ctx.drawImage(img, 0, 0);" in RUNNER
++ assert RUNNER.index("await decodeAIImage(") < RUNNER.index("layer.ctx.drawImage(img, 0, 0);")
++ assert "} finally {\n operation.finish();" in RUNNER
def test_ai_runner_does_not_commit_a_result_from_a_closed_editor():
diff --cc tests/test_editor_writing_action_routing.py
index 0ca3346fd,000000000..26ee55aec
mode 100644,000000..100644
--- a/tests/test_editor_writing_action_routing.py
+++ b/tests/test_editor_writing_action_routing.py
@@@ -1,304 -1,0 +1,304 @@@
+"""Writing-menu source text must not redirect the requested editor operation."""
+import re
- from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from src.clean_agent_preview import (
+ targets_active_editor, active_editor_suggestion_request, scope_active_editor_contract,
+ required_active_editor_tool_choice,
+)
+from src.turn_contract import (
+ editor_request_instructions, requested_capabilities, selected_tools_for_request,
+ preserve_bound_editor_selected_tools, resolve_turn_contract,
+)
+from src.tool_schemas import FUNCTION_TOOL_SCHEMAS
+from src.tool_policy import ToolPolicy
++from tests.helpers.document_source import declaration
+
- MENU = Path('static/js/document.js').read_text().split('const _AI_WRITING_ACTIONS = Object.freeze({', 1)[1].split('});', 1)[0]
++MENU = declaration('_AI_WRITING_ACTIONS')
+ACTIONS = dict(re.findall(r"\s+(\w+): '([^']+)'", MENU))
+
+
[email protected]('action', ['proofread', 'improve', 'concise', 'style', 'sources'])
[email protected]('newline', ['\n', '\r\n'])
+def test_writing_actions_keep_inline_tools_despite_source_topics(action, newline):
+ prompt = ACTIONS[action] + '\n\nUse this configured writing style as the source of truth:\n---\nUse clear sentences about files and tasks.\n---'
+ prompt += '\n\nImportant scope: work only on this selected passage. Selected passage:\n---\nThe calendar lists events. I read notes about Python scripts, images and a new document. This sentnce needs help.\n---'
+ prompt = prompt.replace('\n', newline)
+ doc = SimpleNamespace(title='Essay', language='markdown', current_content='This sentnce needs help.')
+ families = requested_capabilities(prompt, active_document=True)
+ assert families == ({'documents', 'search_browser'} if action == 'sources' else {'documents'})
+ assert targets_active_editor(doc, prompt)
+ assert active_editor_suggestion_request(doc, prompt) == (action != 'proofread')
+ selected = preserve_bound_editor_selected_tools(prompt, selected_tools_for_request(prompt), active_document=True)
+ contract = resolve_turn_contract(capabilities=families, schemas=FUNCTION_TOOL_SCHEMAS,
+ policy=ToolPolicy(), selected_tools=selected)
+ scoped = scope_active_editor_contract(contract, suggestion_only=action != 'proofread', source_verification=action == 'sources')
+ names = {s['function']['name'] for s in scoped.schemas()}
+ if action == 'proofread':
+ assert names == {'edit_document', 'update_document'}
+ return
+ assert 'suggest_document' in names
+ assert not names & {'edit_document', 'update_document', 'create_document', 'bash'}
+ if action == 'sources':
+ assert 'web_search' in names
+ else:
+ assert names == {'suggest_document'}
+ assert required_active_editor_tool_choice(active_editor_target=True, suggestion_target=True,
+ whole_draft_target=False, offered=scoped.schemas())['function']['name'] == 'suggest_document'
+
+
+def test_source_boundary_preserves_trailing_instructions_and_plain_requests():
+ prompt = 'Proofread the open document. Selected passage:\n---\nCreate a new email.\n---\nAlso check sources online.'
+ assert 'Create a new email' not in editor_request_instructions(prompt)
+ assert 'Also check sources online.' in editor_request_instructions(prompt)
+ assert editor_request_instructions('Create a new email.') == 'Create a new email.'
+
+
+def test_editor_requests_do_not_capture_explicit_other_targets():
+ doc = SimpleNamespace(title='Essay', language='markdown', current_content='Text')
+ for prompt in ['Write a note', 'Create a new document', 'Edit my calendar event']:
+ assert not targets_active_editor(doc, prompt)
+
+
[email protected]('prompt', ['Fix the spelling in the open document.',
+ 'Correct this sentence.', 'Polish this paragraph.',
+ 'Shorten the open document.', 'Rewrite this document.'])
+def test_direct_edits_share_the_capability_router(prompt):
+ doc = SimpleNamespace(title='Essay', language='markdown', current_content='Text')
+ assert requested_capabilities(prompt, active_document=True) == {'documents'}
+ assert targets_active_editor(doc, prompt)
+ assert not active_editor_suggestion_request(doc, prompt)
+
+
+def test_source_review_still_requires_tool_completion_after_research():
+ schemas = [s for s in FUNCTION_TOOL_SCHEMAS if s['function']['name'] in {'web_search', 'suggest_document'}]
+ assert required_active_editor_tool_choice(active_editor_target=True, suggestion_target=True,
+ whole_draft_target=False, offered=schemas) == 'required'
+
+
[email protected]('value', [3, None, [], 'not an object'])
+def test_malformed_editor_tool_arguments_get_a_recoverable_error(value):
+ from src.clean_agent_preview import normalize_preview_call_args
+ with pytest.raises(ValueError, match='JSON object'):
+ normalize_preview_call_args('suggest_document', value)
+
+
[email protected]('tool,prompt,args', [
+ ('suggest_document', 'Proofread the open document. Create inline suggestions only; do not apply changes.',
+ {'suggestions': [{'find': 'A sentnce.', 'replace': 'A sentence.', 'reason': 'Spelling.'}],
+ 'more': True}),
+ ('edit_document', 'Fix the spelling in the open document.',
+ {'edits': [{'find': 'A sentnce.', 'replace': 'A sentence.'}]}),
+ ('update_document', 'Rewrite the whole open document.', {'content': 'A sentence.'}),
+])
+async def test_editor_loop_recovers_scalar_arguments_and_emits_editor_event(monkeypatch, tool, prompt, args):
+ import json
+ import src.clean_agent_preview as runner
+ from src.turn_contract import resolve_full_inventory_contract
+ requests, executed = [], []
+ deltas = iter([
+ {'content': 'PREMATURE_SUCCESS', 'tool_calls': [{'index': 0, 'id': 'bad', 'function': {'name': tool, 'arguments': '123'}}]},
+ {'tool_calls': [{'index': 0, 'id': 'good', 'function': {'name': tool, 'arguments': json.dumps(args)}}]},
+ {'content': 'Done.'},
+ ])
+ class Response:
+ def __init__(self, delta): self.delta = delta
+ async def __aenter__(self): return self
+ async def __aexit__(self, *args): pass
+ def raise_for_status(self): pass
+ async def aiter_lines(self):
+ yield 'data: ' + json.dumps({'choices': [{'delta': self.delta}]})
+ yield 'data: [DONE]'
+ class Client:
+ def __init__(self, **kwargs): pass
+ async def __aenter__(self): return self
+ async def __aexit__(self, *args): pass
+ def stream(self, *args, **kwargs):
+ requests.append(kwargs['json'])
+ return Response(next(deltas))
+ async def execute(block, **kwargs):
+ executed.append(block)
+ return tool, {'exit_code': 0, 'action': 'suggest' if tool == 'suggest_document' else 'update',
+ 'doc_id': 'fixture', 'content': 'A sentence.', 'title': 'Fixture',
+ 'language': 'markdown', 'version': 2,
+ 'suggestions': args.get('suggestions', [])}
+ import src.email_task_intent as intent_module
+ async def classify(*args, **kwargs):
+ return intent_module.EmailTaskIntent('other', (), 'Edit the open document')
+ monkeypatch.setattr(intent_module, 'classify_email_task', classify)
+ monkeypatch.setattr(runner.httpx, 'AsyncClient', Client)
+ monkeypatch.setattr(runner, 'execute_tool_block', execute)
+ policy = ToolPolicy()
+ # Preserve both direct writers; model chooses between targeted and full edit.
+ schemas = [s for s in FUNCTION_TOOL_SCHEMAS if s['function']['name'] in
+ {'suggest_document', 'edit_document', 'update_document'}]
+ contract = resolve_full_inventory_contract(schemas=schemas, policy=policy)
+ doc = SimpleNamespace(id='fixture', title='Fixture', language='markdown', current_content='A sentnce.')
+ events = [json.loads(c[6:]) async for c in runner.stream_preview(
+ endpoint_url='http://test', model='Ajax', messages=[{'role': 'user', 'content': prompt}],
+ headers={}, turn_contract=contract, session_id='fixture', owner='fixture',
+ disabled_tools=set(), tool_policy=policy, active_document=doc, max_tokens=4096,
+ ) if '[DONE]' not in c]
+ assert len(executed) == 1
+ assert requests[-1]["max_tokens"] == 256
+ assert not requests[-1].get("tools")
+ assert requests[0]['max_tokens'] == 4096
+ assert requests[0]['tool_choice'] == 'auto'
+ assert not any('PREMATURE_SUCCESS' in e.get('delta', '') for e in events)
+ assert requests[0]['parallel_tool_calls'] is False
+ assert 'parallel_tool_calls' not in requests[-1]
+ outputs = [e for e in events if e.get('type') == 'tool_output']
+ assert any(e.get('type') == 'editor_progress' for e in events)
+ assert outputs[0]['execution_attempted'] is False
+ assert 'JSON object' in outputs[0]['output']
+ assert outputs[1]['error'] is False
+ if tool == 'suggest_document':
+ assert any(e.get('type') == 'doc_suggestions' for e in events)
+ else:
+ assert any(e.get('type') == 'doc_update' for e in events)
+
+
+async def test_finish_after_saved_editor_batch_skips_another_model_request(monkeypatch):
+ import json
+ import src.clean_agent_preview as runner
+ from src.turn_contract import resolve_full_inventory_contract
+
+ requests, executed = [], []
+ args = {'edits': [{'find': 'A sentnce.', 'replace': 'A sentence.'}], 'more': True}
+
+ class Response:
+ async def __aenter__(self): return self
+ async def __aexit__(self, *ignored): pass
+ def raise_for_status(self): pass
+ async def aiter_lines(self):
+ yield 'data: ' + json.dumps({'choices': [{'delta': {'tool_calls': [
+ {'index': 0, 'id': 'edit', 'function': {
+ 'name': 'edit_document', 'arguments': json.dumps(args)}}
+ ]}}]})
+ yield 'data: [DONE]'
+
+ class Client:
+ def __init__(self, **ignored): pass
+ async def __aenter__(self): return self
+ async def __aexit__(self, *ignored): pass
+ def stream(self, *ignored, **kwargs):
+ requests.append(kwargs['json'])
+ return Response()
+
+ async def execute(block, **ignored):
+ executed.append(block)
+ return 'edit_document', {'exit_code': 0, 'action': 'edit', 'doc_id': 'fixture',
+ 'content': 'A sentence.', 'title': 'Fixture',
+ 'language': 'markdown', 'version': 2, 'applied': 1}
+
+ import src.email_task_intent as intent_module
+ async def classify(*ignored, **kwargs):
+ return intent_module.EmailTaskIntent('other', (), 'Edit the open document')
+ monkeypatch.setattr(intent_module, 'classify_email_task', classify)
+ monkeypatch.setattr(runner.httpx, 'AsyncClient', Client)
+ monkeypatch.setattr(runner, 'execute_tool_block', execute)
+ monkeypatch.setattr(runner.agent_runs, 'should_finish', lambda _session: bool(executed))
+ policy = ToolPolicy()
+ schemas = [s for s in FUNCTION_TOOL_SCHEMAS if s['function']['name'] == 'edit_document']
+ contract = resolve_full_inventory_contract(schemas=schemas, policy=policy)
+ doc = SimpleNamespace(id='fixture', title='Fixture', language='markdown', current_content='A sentnce.')
+ events = [json.loads(chunk[6:]) async for chunk in runner.stream_preview(
+ endpoint_url='http://test', model='Ajax', messages=[{'role': 'user', 'content': 'Fix the spelling in the open document.'}],
+ headers={}, turn_contract=contract, session_id='fixture', owner='fixture',
+ disabled_tools=set(), tool_policy=policy, active_document=doc, max_tokens=4096,
+ ) if chunk.startswith('data: ') and '[DONE]' not in chunk]
+ assert len(requests) == 1
+ assert len(executed) == 1
+ assert any(e.get('type') == 'doc_update' for e in events)
+ assert any(e.get('type') == 'final_response' and 'saved so far' in e.get('content', '')
+ for e in events)
+
+
+async def test_finish_interrupts_wait_for_next_model_token():
+ import asyncio
+ from src.clean_agent_preview import preview_lines_until_finish
+
+ finish = asyncio.Event()
+ waiting = asyncio.Event()
+ released = asyncio.Event()
+
+ class SlowResponse:
+ async def aiter_lines(self):
+ waiting.set()
+ try:
+ await asyncio.Event().wait()
+ yield 'unreachable'
+ finally:
+ released.set()
+
+ task = asyncio.create_task(_collect_preview_lines(SlowResponse(), finish))
+ await asyncio.wait_for(waiting.wait(), 1)
+ finish.set()
+ assert await asyncio.wait_for(task, 1) == []
+ assert released.is_set()
+
+
+async def _collect_preview_lines(response, finish):
+ from src.clean_agent_preview import preview_lines_until_finish
+ return [line async for line in preview_lines_until_finish(response, finish)]
+
+
+def test_selection_only_edit_cannot_replace_all_occurrences():
+ from src.clean_agent_preview import normalize_preview_call_args
+ with pytest.raises(ValueError, match='Selection-only'):
+ normalize_preview_call_args('edit_document', {'edits': [
+ {'find': 'typo', 'replace': 'word', 'replace_all': True}]},
+ user_text='Important scope: work only on this selected passage.')
+
+
+def test_concise_suggestions_must_actually_shorten_prose():
+ from src.clean_agent_preview import document_suggestion_quality_error
+ prompt = ACTIONS['concise']
+ original = '<p>This sentnce has an unecessary delay.</p>'
+ spelling_only = '<p>This sentence has an unnecessary delay.</p>'
+ proposed = {'suggestions': [{'find': original, 'replace': spelling_only}]}
+ assert 'does not make its passage more concise' in document_suggestion_quality_error(
+ 'suggest_document', proposed, user_text=prompt)
+ proposed['suggestions'][0]['replace'] = '<p>This sentence drags.</p>'
+ assert document_suggestion_quality_error('suggest_document', proposed, user_text=prompt) is None
+ proposed['suggestions'][0]['replace'] = spelling_only
+ assert document_suggestion_quality_error('suggest_document', proposed,
+ user_text='Proofread the open document.') is None
+
+
+def test_ajax_editor_schema_limits_batches_and_exposes_continuation():
+ from src.clean_agent_preview import compact_schemas
+ schemas = compact_schemas([s for s in FUNCTION_TOOL_SCHEMAS
+ if s['function']['name'] in {'edit_document', 'suggest_document'}], model='Ajax')
+ by_name = {s['function']['name']: s['function']['parameters']['properties'] for s in schemas}
+ assert by_name['edit_document']['edits']['maxItems'] == 12
+ assert by_name['suggest_document']['suggestions']['maxItems'] == 12
+ assert by_name['edit_document']['more']['type'] == 'boolean'
+ assert by_name['suggest_document']['more']['type'] == 'boolean'
+
+
+def test_exact_edits_continue_but_suggestions_finish_after_one_bounded_set():
+ from src.clean_agent_preview import editor_batch_continues
+ assert editor_batch_continues('edit_document', {'edits': [{}] * 12})
+ assert not editor_batch_continues('suggest_document', {'suggestions': [{}] * 12})
+ assert not editor_batch_continues('suggest_document', {'suggestions': [{}], 'more': True})
+ assert not editor_batch_continues('edit_document', {'edits': [{}] * 11})
+ assert not editor_batch_continues('edit_document', {'edits': [{}] * 12, 'more': False})
+ assert editor_batch_continues('edit_document', {'edits': [{}], 'more': True})
+
+
+def test_noop_sibling_does_not_create_a_failed_tool_card_after_a_real_edit():
+ import json
+ from src.clean_agent_preview import drop_redundant_editor_noops
+ good = {'function': {'name': 'edit_document', 'arguments': json.dumps({
+ 'edits': [{'find': 'old', 'replace': 'new'}]})}}
+ noop = {'function': {'name': 'edit_document', 'arguments': json.dumps({
+ 'edits': [{'find': 'already correct', 'replace': 'already correct'}]})}}
+ assert drop_redundant_editor_noops([good, noop]) == [good]
+ assert drop_redundant_editor_noops([noop]) == [noop]
+ assert drop_redundant_editor_noops([good, good]) == [good]
diff --cc tests/test_email_attachment_text.py
index 56cbd0f0f,000000000..9e6ac95a9
mode 100644,000000..100644
--- a/tests/test_email_attachment_text.py
+++ b/tests/test_email_attachment_text.py
@@@ -1,113 -1,0 +1,113 @@@
+import os
+
+import pytest
+
+from src.email_attachment_text import attachment_text
+from src.clean_agent_preview import compact_schemas
+
+
+def test_text_and_truncation(tmp_path):
+ path = tmp_path / 'invoice.csv'
+ path.write_text('Item,Amount\nServices,12345\n', encoding='utf-8')
+ assert '12345' in attachment_text(path)['content']
+ result = attachment_text(path, max_chars=10)
+ assert len(result['content']) == 10
+ assert 'truncated' in result['content_note']
+
+
+def test_real_pdf_text(tmp_path):
- import fitz
++ fitz = pytest.importorskip('fitz') # PyMuPDF is in requirements-optional.txt
+ path = tmp_path / 'payslip.pdf'
+ with fitz.open() as doc:
+ page = doc.new_page()
+ page.insert_text((72, 72), 'Gross pay: 150000\nNet pay: 120000')
+ doc.save(path)
+ result = attachment_text(path)
+ assert result['content_status'] == 'read'
+ assert '120000' in result['content']
+ assert 'Page 1' in result['content']
+
+
+def test_blank_pdf_reports_ocr(tmp_path):
+ from pypdf import PdfWriter
+ path = tmp_path / 'scan.pdf'
+ writer = PdfWriter()
+ writer.add_blank_page(width=100, height=100)
+ writer.write(path)
+ assert attachment_text(path)['content_status'] == 'needs_ocr'
+
+
+def test_xlsx(tmp_path):
- from openpyxl import Workbook
++ Workbook = pytest.importorskip('openpyxl').Workbook # requirements-optional.txt
+ path = tmp_path / 'expenses.xlsx'
+ book = Workbook()
+ book.active.append(['Expenses', 12500])
+ book.save(path)
+ result = attachment_text(path)
+ assert 'Expenses\t12500' in result['content']
+
+
+def test_bad_pdf_reports_failure(tmp_path):
+ path = tmp_path / 'bad.pdf'
+ path.write_bytes(b'not a pdf')
+ assert attachment_text(path)['content_status'] == 'failed'
+
+
+def test_compact_live_alias_explains_reading():
+ schema = {'type': 'function', 'function': {'name': 'mcp__email__download_attachment',
+ 'description': 'Download', 'parameters': {'type': 'object', 'properties': {}}}}
+ description = compact_schemas([schema], model='Ajax')[0]['function']['description']
+ assert 'before answering' in description
+ assert 'contents inline' in description
+
+
+def test_discovered_attachment_read_does_not_need_explicit_download_request():
+ from src.clean_agent_preview import evaluate_preview_call
+ decision = evaluate_preview_call('mcp__email__download_attachment',
+ {'uid': '42', 'index': 0, 'account': '[email protected]'},
+ 'What email had my latest payslip and how much')
+ assert decision.allowed
+ assert not evaluate_preview_call('write_file', {'path': '/tmp/test', 'content': 'x'},
+ 'What email had my latest payslip and how much').allowed
+
+
+async def _live_attachment_check(monkeypatch):
+ import json
+ import os
+ import src.clean_agent_preview as module
+ from src.tool_policy import ToolPolicy
+ from src.tool_schemas import FUNCTION_TOOL_SCHEMAS
+ from src.turn_contract import resolve_full_inventory_contract
+ executions = []
+ async def execute(block, **kwargs):
+ name = block.tool_type.removeprefix('mcp__email__')
+ executions.append(name)
+ outputs = {
+ 'list_email_accounts': 'Account: [email protected]',
+ 'search_emails': 'UID: 42\nFolder: INBOX\nAccount: [email protected]\nSubject: September 2026 Payslip\nDate: 2026-09-25',
+ 'read_email': 'UID: 42\nFolder: INBOX\nAccount: [email protected]\nSubject: September 2026 Payslip\nBody: Your payslip is attached.\nAttachments: [0] payslip.pdf (application/pdf)',
+ 'download_attachment': 'Attachment content:\nPage 1:\nSeptember 2026 payslip\nGross pay: JPY 150000\nNet pay: JPY 120000',
+ }
+ return block.tool_type, {'exit_code': 0, 'stdout': outputs[name]}
+ monkeypatch.setattr(module, 'execute_tool_block', execute)
+ schemas = [s for s in FUNCTION_TOOL_SCHEMAS if s['function']['name'] in {
+ 'list_email_accounts', 'search_emails', 'read_email', 'download_attachment'}]
+ policy = ToolPolicy()
+ contract = resolve_full_inventory_contract(schemas=schemas, policy=policy)
+ chunks = [c async for c in module.stream_preview(
+ endpoint_url=os.environ['ODYSSEUS_AJAX_TEST_URL'], model='Ajax', headers={},
+ messages=[{'role': 'user', 'content': 'What email had my latest payslip and how much'}],
+ turn_contract=contract, owner='fixture', session_id='fixture-attachment',
+ disabled_tools=set(), tool_policy=policy, thinking_mode='off', max_rounds=6,
+ )]
+ events = [json.loads(c[6:]) for c in chunks if c.startswith('data: ') and '[DONE]' not in c]
+ answer = next((e['content'] for e in reversed(events) if e.get('type') == 'final_response'),
+ ''.join(e.get('delta', '') for e in events))
+ assert 'download_attachment' in executions, (executions, answer)
+ assert '120000' in answer.replace(',', ''), answer
+
+
[email protected](not os.environ.get('ODYSSEUS_AJAX_TEST_URL'), reason='Opt-in Ajax fixture test')
+async def test_live_ajax_reads_attachment(monkeypatch):
+ await _live_attachment_check(monkeypatch)
diff --cc tests/test_email_library_module_graph_js.py
index 000000000,3cd2566e4..dadf7a84b
mode 000000,100644..100644
--- a/tests/test_email_library_module_graph_js.py
+++ b/tests/test_email_library_module_graph_js.py
@@@ -1,0 -1,315 +1,316 @@@
+ """Module-graph coverage for the split email library.
+
+ ``specs/frontend.md`` records that this frontend has "no build-time type
+ checking, module graph validation, or script-order validation". That is
+ tolerable for a single 11k-line file and not tolerable for a package: splitting
+ ``emailLibrary.js`` into modules that import each other adds three failure modes
+ nothing else here would catch.
+
+ 1. The compatibility wrapper at ``static/js/emailLibrary.js`` drops an export.
+ Five call sites import that path; a missing name is ``undefined`` at call
+ time, not an error at load time, so the panel just stops responding.
+ 2. A module in the package fails to evaluate — a stale relative specifier after
+ a move, or a temporal-dead-zone read across an import cycle. The package has
+ cycles by construction: extracted modules call back into ``index.js`` from
+ event handlers. That is safe for hoisted function declarations and *not* safe
+ for a ``const`` read while the graph is still evaluating, and which one you
+ wrote is invisible in a diff.
+ 3. A new module is missing from the ``sw.js`` precache, so the panel that works
+ online cannot open offline.
+
+ The first and third are read off the source. The second needs a real module
+ loader, so it runs in a browser: each module is imported *on its own*, in a
+ fresh page, because entering the cycle at a submodule rather than at the entry
+ module is the order that exposes a dead-zone read.
+ """
+
+ import json
+ import re
+ import subprocess
+ from pathlib import Path
+
+ from tests.helpers.js_modules import (
+ EMAIL_LIBRARY_ENTRY,
+ EMAIL_LIBRARY_PACKAGE,
+ EMAIL_LIBRARY_WRAPPER,
+ email_library_paths,
+ )
+
+ ROOT = Path(__file__).resolve().parents[1]
+ _SW = ROOT / "static" / "sw.js"
+
+ # `export function foo`, `export async function foo`, `export const foo`.
+ _EXPORT_DECL = re.compile(
+ r"^export\s+(?:async\s+)?(?:function|const|let|class)\s+([A-Za-z_$][\w$]*)",
+ re.M,
+ )
+ # `export { a, b } from '...'` and `export { a, b }`.
+ _EXPORT_LIST = re.compile(r"export\s*\{([^}]*)\}", re.S)
+
+
+ def _declared_exports(path: Path) -> set[str]:
+ return set(_EXPORT_DECL.findall(path.read_text(encoding="utf-8")))
+
+
+ def _listed_exports(path: Path) -> set[str]:
+ names: set[str] = set()
+ for block in _EXPORT_LIST.findall(path.read_text(encoding="utf-8")):
+ for raw in block.split(","):
+ name = raw.strip().split(" as ")[-1].strip()
+ if name:
+ names.add(name)
+ return names
+
+
+ # The email library's public surface. The entry module exports more than this —
+ # siblings in the package import helpers back out of it — so the wrapper is what
+ # declares which names are API and which are package-internal.
+ #
-# Written out rather than derived because three of the five callers reach these
-# through a dynamic import and a property read (`mod.openEmailLibrary` in
-# chatStream.js and chatRenderer.js, `mod.refreshEmailLibrary` and
-# `mod.openEmailLibrary` in document.js, `mod.mountEmailSettings` in
++# Written out rather than derived because most callers reach these through a
++# dynamic import and a property read (`mod.openEmailLibrary` in chatStream.js
++# and chatRenderer.js, `mod.refreshEmailLibrary` and `mod.openEmailLibrary` in
++# document.js, `mod.openEmailFromTool` in chat.js, `mod.mountEmailSettings` in
+ # settings.js), which no import scan can see. Only emailInbox.js imports names
+ # statically, and `test_wrapper_exposes_every_statically_imported_name` covers
+ # that half exactly.
+ _PUBLIC_SURFACE = {
+ "closeEmailLibrary",
+ "initEmailLibrary",
+ "isOpen",
+ "mountEmailSettings",
++ "openEmailFromTool",
+ "openEmailLibrary",
+ "openEmailLibrarySettings",
+ "prewarmEmailLibrary",
+ "prewarmUnreadEmails",
+ "refreshEmailLibrary",
+ }
+
+ _STATIC_JS = ROOT / "static" / "js"
+ _WRAPPER_IMPORT = re.compile(
+ r"import\s*\{([^}]*)\}\s*from\s*'\./emailLibrary\.js(?:\?[^']*)?'", re.S
+ )
+
+
+ def test_wrapper_declares_the_public_surface():
+ assert _listed_exports(EMAIL_LIBRARY_WRAPPER) == _PUBLIC_SURFACE
+
+
+ def test_wrapper_re_exports_only_names_the_entry_module_has():
+ """A name in the wrapper that the entry module does not export is a
+ SyntaxError at load time, and it takes the whole email panel with it."""
+ entry = _declared_exports(EMAIL_LIBRARY_ENTRY) | _listed_exports(EMAIL_LIBRARY_ENTRY)
+ wrapper = _listed_exports(EMAIL_LIBRARY_WRAPPER)
+ assert wrapper, f"{EMAIL_LIBRARY_WRAPPER} re-exports nothing"
+ assert wrapper <= entry, (
+ "static/js/emailLibrary.js re-exports names static/js/emailLibrary/"
+ f"index.js does not export: {sorted(wrapper - entry)}"
+ )
+
+
+ def test_wrapper_exposes_every_statically_imported_name():
+ """Whatever a module outside the package imports by name must be there."""
+ wrapper = _listed_exports(EMAIL_LIBRARY_WRAPPER)
+ checked = 0
+ for path in sorted(_STATIC_JS.rglob("*.js")):
+ if path == EMAIL_LIBRARY_WRAPPER or EMAIL_LIBRARY_PACKAGE in path.parents:
+ continue
+ for block in _WRAPPER_IMPORT.findall(path.read_text(encoding="utf-8")):
+ for raw in block.split(","):
+ name = raw.strip().split(" as ")[0].strip()
+ if not name:
+ continue
+ checked += 1
+ assert name in wrapper, (
+ f"{path.relative_to(ROOT)} imports {name} from "
+ "static/js/emailLibrary.js, which does not export it"
+ )
+ assert checked, "no module imports names from static/js/emailLibrary.js"
+
+
+ _IMPORT_STATEMENT = re.compile(
+ r"^import\s+(\{[^}]*\}|\*\s+as\s+[\w$]+|[\w$]+)\s+from\s+'[^']+';", re.M | re.S
+ )
+ _TOP_LEVEL_DECL = re.compile(
+ r"^(?:export\s+)?(?:async\s+)?(?:function|const|let|var)\s+([A-Za-z_$][\w$]*)", re.M
+ )
+
+
+ def _bound_names(source: str) -> set[str]:
+ """Local names a module binds: imports plus top-level declarations."""
+ names = set(_TOP_LEVEL_DECL.findall(source))
+ for clause in _IMPORT_STATEMENT.findall(source):
+ clause = clause.strip()
+ if clause.startswith("{"):
+ names |= {
+ part.strip().split(" as ")[-1].strip()
+ for part in clause.strip("{}").split(",")
+ if part.strip()
+ }
+ else:
+ names.add(clause.split(" as ")[-1].strip())
+ return names
+
+
+ _REEXPORT = re.compile(r"^export\s*\{[^}]*\}\s*from\s*'[^']+';", re.M | re.S)
+ _WHOLE_LINE_COMMENT = re.compile(r"^\s*(?://|/\*|\*/|\*(?!/)).*$", re.M)
+
+
+ def _executable_body(source: str) -> str:
+ """The part of a module that actually runs a name.
+
+ Imports are dropped because a name in an import clause is the binding, not a
+ use. Re-export lists go for the same reason. Whole-line comments go because
+ prose says things like "no shared state" and `state` is a real binding here;
+ only full lines are stripped, so a `//` inside a URL literal is left alone.
+ """
+ ends = [m.end() for m in _IMPORT_STATEMENT.finditer(source)]
+ body = source[max(ends):] if ends else source
+ body = _REEXPORT.sub("", body)
+ return _WHOLE_LINE_COMMENT.sub("", body)
+
+
+ def test_no_module_uses_a_package_name_it_never_bound():
+ """A name used but never imported is a runtime ReferenceError, nothing less.
+
+ It is invisible to `node --check`, which parses without resolving scope, and
+ invisible to loading the module, because the throw happens inside a function
+ body the loader never calls. It is also the single most likely mistake when
+ code moves between modules — the declaration stays behind and the use comes
+ along.
+
+ The vocabulary checked is the package's own: every name any module here
+ binds. That is narrow on purpose. It is not a general no-undef pass, so it
+ never has to model the browser's globals and never produces a false
+ positive; it catches exactly the shape a split produces.
+ """
+ sources = {p.name: p.read_text(encoding="utf-8") for p in email_library_paths(True)}
+ vocabulary: set[str] = set()
+ for source in sources.values():
+ vocabulary |= _bound_names(source)
+
+ unbound: dict[str, list[str]] = {}
+ for name, source in sources.items():
+ bound = _bound_names(source)
+ body = _executable_body(source)
+ missing = sorted(
+ word
+ for word in vocabulary - bound
+ if re.search(r"(?<![\w$.])" + re.escape(word) + r"(?![\w$])", body)
+ )
+ if missing:
+ unbound[name] = missing
+ assert not unbound, (
+ "modules use names they neither declare nor import, which throws at call "
+ f"time and nowhere earlier: {unbound}"
+ )
+
+
+ def test_every_package_module_is_precached():
+ sw = _SW.read_text(encoding="utf-8")
+ for path in email_library_paths():
+ url = "/static/js/emailLibrary/" + path.name
+ assert f"'{url}'" in sw, (
+ f"{url} is not in the static/sw.js precache, so a panel that works "
+ "online will not open offline"
+ )
+
+
+ def test_every_package_module_evaluates_on_its_own_in_a_browser():
+ """Import each module first, alone, and require it to evaluate.
+
+ Entering the package at a submodule is what turns an import cycle from
+ harmless into a `ReferenceError: cannot access '…' before initialization`.
+ Importing the entry module first would hide exactly that.
+ """
+ urls = ["/static/js/emailLibrary.js"] + [
+ "/static/js/emailLibrary/" + p.name for p in email_library_paths()
+ ]
+ script = r'''
+ import { chromium } from 'playwright';
+ const origin = process.env.ODYSSEUS_TEST_STATIC_ORIGIN;
+ const urls = JSON.parse(process.env.ODYSSEUS_EMAIL_MODULE_URLS);
+ const browser = await chromium.launch({ headless: true });
+ const results = {};
+ for (const url of urls) {
+ const page = await browser.newPage();
+ // Same synthetic shell the other email browser tests use: these
+ // modules touch #toast and #sidebar while evaluating.
+ await page.goto(`${origin}/static/js/documentStats.js`);
+ await page.setContent('<div id="toast"></div><div id="chat-container"></div><div id="sidebar"></div>');
+ results[url] = await page.evaluate(async (target) => {
+ try {
+ const mod = await import(target);
+ return { ok: true, exports: Object.keys(mod).sort() };
+ } catch (err) {
+ return { ok: false, error: String(err && err.message || err) };
+ }
+ }, url);
+ await page.close();
+ }
+ console.log(JSON.stringify(results));
+ await browser.close();
+ '''
+ result = subprocess.run(
+ ["node", "--input-type=module", "-e", script],
+ cwd=ROOT,
+ check=False,
+ capture_output=True,
+ text=True,
+ env={
+ **__import__("os").environ,
+ "ODYSSEUS_EMAIL_MODULE_URLS": json.dumps(urls),
+ },
+ )
+ assert result.returncode == 0, result.stderr
+ data = json.loads(result.stdout)
+ broken = {url: info["error"] for url, info in data.items() if not info["ok"]}
+ assert not broken, f"modules that failed to evaluate on their own: {broken}"
+ assert set(data) == set(urls)
+
+
+ def test_wrapper_and_entry_module_hand_out_the_same_functions():
+ """Importing either path must give one live module instance.
+
+ Two instances would mean two copies of the panel's module state, and the
+ panel is a singleton keyed on DOM ids — the second copy would fight the
+ first over `#email-lib-modal`.
+ """
+ script = r'''
+ import { chromium } from 'playwright';
+ const origin = process.env.ODYSSEUS_TEST_STATIC_ORIGIN;
+ const browser = await chromium.launch({ headless: true });
+ const page = await browser.newPage();
+ await page.goto(`${origin}/static/js/documentStats.js`);
+ await page.setContent('<div id="toast"></div><div id="chat-container"></div><div id="sidebar"></div>');
+ const out = await page.evaluate(async () => {
+ const wrapper = await import('/static/js/emailLibrary.js');
+ const entry = await import('/static/js/emailLibrary/index.js');
+ const names = Object.keys(wrapper).sort();
+ return {
+ names,
+ identical: names.filter((n) => wrapper[n] === entry[n]),
+ callable: names.filter((n) => typeof wrapper[n] === 'function'),
+ };
+ });
+ console.log(JSON.stringify(out));
+ await browser.close();
+ '''
+ result = subprocess.run(
+ ["node", "--input-type=module", "-e", script],
+ cwd=ROOT,
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+ assert result.returncode == 0, result.stderr
+ data = json.loads(result.stdout)
+ assert data["names"], "the wrapper exported nothing at runtime"
+ assert data["identical"] == data["names"], (
+ "the wrapper and the entry module handed out different objects for "
+ f"{sorted(set(data['names']) - set(data['identical']))}"
+ )
+ assert data["callable"] == data["names"], (
+ "not every export is callable: "
+ f"{sorted(set(data['names']) - set(data['callable']))}"
+ )
diff --cc tests/test_image_research_settings_static.py
index 1e07626e1,7c76f7293..7f5a26d96
--- a/tests/test_image_research_settings_static.py
+++ b/tests/test_image_research_settings_static.py
@@@ -9,7 -15,7 +15,9 @@@ def test_image_settings_only_list_onlin
assert "fetch('/api/model-endpoints'" in settings
assert "!endpoint.is_enabled || !endpoint.online" in settings
-- assert "endpoint.model_type || '').toLowerCase() !== 'image'" in settings
++ # Image capability is decided per model, so image models served from a
++ # general endpoint (for example gpt-image-1) are listed too.
++ assert "modelCaps(modelId, '', endpoint.model_type).gen" in settings
assert "stable-diffusion-3.5-medium', 'stable-diffusion-inpainting" not in settings
assert "(not detected)" not in settings[settings.index("async function initImageSettings"):settings.index("function syncImgDisabled")]
diff --cc tests/test_pr6020_browser_review_regressions.py
index ca8dd7cca,ca8dd7cca..c2ab29336
--- a/tests/test_pr6020_browser_review_regressions.py
+++ b/tests/test_pr6020_browser_review_regressions.py
@@@ -502,10 -502,10 +502,13 @@@ def test_superseded_stream_cleanup_leav
function _setForegroundChatBusy() {{}}
const window = {{}};
const sessionModule = {{ getCurrentSessionId() {{ return 'session-1'; }} }};
++ let docFinalized = 0;
++ const documentModule = {{ streamDocFinalize() {{ docFinalized += 1; }} }};
{state_and_stop}
function runCleanup(abortCtrl, streamGeneration) {{
const streamSessionId = 'session-1';
const _sendState = {{ generation: streamGeneration, abortCtrl }};
++ const _streamSawDone = false;
{finally_cleanup}
return _ownsStreamState;
}}
@@@ -520,6 -520,6 +523,7 @@@
_pendingRunStops.set('session-1:2', newCtrl);
const preRegOwns = runCleanup(oldCtrl, 1);
const afterPreReg = {{
++ docFinalized,
ownEntryRemoved: !_activeStreams.has('session-1'),
replacementPendingKept: _pendingRunStops.has('session-1:2'),
sessionKept: _streamSessionId === 'session-1',
@@@ -528,6 -528,6 +532,7 @@@
_activeStreams.set('session-1', {{ abortCtrl: newCtrl, holder: null, lastActivity: 2 }});
const postRegOwns = runCleanup(oldCtrl, 1);
const afterPostReg = {{
++ docFinalized,
replacementRegistrationKept: _activeStreams.has('session-1'),
replacementPendingKept: _pendingRunStops.has('session-1:2'),
sessionKept: _streamSessionId === 'session-1',
@@@ -535,6 -535,6 +540,7 @@@
// Owner: the current-generation send cleans up normally.
const ownerOwns = runCleanup(newCtrl, 2);
const afterOwner = {{
++ docFinalized,
registered: _activeStreams.has('session-1'),
pendingKept: _pendingRunStops.has('session-1:2'),
sessionCleared: _streamSessionId === null,
@@@ -547,18 -547,18 +553,22 @@@
assert _run_node(script) == {
"preRegOwns": False,
"afterPreReg": {
++ # A superseded send must not finalize the replacement's document stream.
++ "docFinalized": 0,
"ownEntryRemoved": True,
"replacementPendingKept": True,
"sessionKept": True,
},
"postRegOwns": False,
"afterPostReg": {
++ "docFinalized": 0,
"replacementRegistrationKept": True,
"replacementPendingKept": True,
"sessionKept": True,
},
"ownerOwns": True,
"afterOwner": {
++ "docFinalized": 1,
"registered": False,
"pendingKept": False,
"sessionCleared": True,
diff --cc tests/test_preview_drafting_recovery.py
index 043a63933,000000000..b8b8df0e4
mode 100644,000000..100644
--- a/tests/test_preview_drafting_recovery.py
+++ b/tests/test_preview_drafting_recovery.py
@@@ -1,186 -1,0 +1,190 @@@
+import json
+from types import SimpleNamespace
+
+import jsonschema
+import pytest
+
+from src.clean_agent_preview import compact_schemas, conversation, stream_preview
+from src.tool_schemas import FUNCTION_TOOL_SCHEMAS
+from src.tool_policy import ToolPolicy
+from src.turn_contract import resolve_full_inventory_contract
+
+
+def test_explicit_thinking_off_wins_without_tools(monkeypatch):
+ import src.clean_agent_preview as module
+ monkeypatch.setattr(module, 'uses_odysseus_progressive_thinking', lambda model: True)
+ assert module.progressive_thinking_for_turn('Ajax', []) is True
+ assert module.progressive_thinking_for_turn('Ajax', [], 'off') is False
+
+
+def test_fetch_requires_a_page_in_full_and_compact_contracts():
+ schema = next(s for s in FUNCTION_TOOL_SCHEMAS if s['function']['name'] == 'web_fetch')
- for item in [schema, compact_schemas([schema])[0]]:
- params = item['function']['parameters']
- with pytest.raises(jsonschema.ValidationError):
- jsonschema.validate({'query': 'compose a letter'}, params)
++ # The preview validates calls against the compact contract, which requires
++ # url or urls. The full schema is sent to providers whose top-level
++ # parameter contract rejects anyOf (test_model_tool_modes), so it accepts
++ # both forms without the combinator.
++ compact = compact_schemas([schema])[0]['function']['parameters']
++ with pytest.raises(jsonschema.ValidationError):
++ jsonschema.validate({'query': 'compose a letter'}, compact)
++ for params in [schema['function']['parameters'], compact]:
+ jsonschema.validate({'url': 'https://example.com', 'query': 'details'}, params)
+ jsonschema.validate({'urls': ['https://example.com']}, params)
+
+
[email protected]('reply', ['you suck', 'thanks', 'a complaint', 'friendly'])
+def test_clarification_history_keeps_task_recipient_and_question(reply):
+ history = SimpleNamespace(history=[
+ {'role': 'user', 'content': 'write email'},
+ {'role': 'assistant', 'content': 'Who is it for?'},
+ {'role': 'user', 'content': 'Jordan'},
+ {'role': 'assistant', 'content': 'What do you want to say to Jordan?'},
+ ])
+ result = conversation(history, [{'role': 'user', 'content': reply}])
+ assert [m['content'] for m in result] == [
+ 'write email', 'Who is it for?', 'Jordan',
+ 'What do you want to say to Jordan?', reply,
+ ]
+
+
+async def test_bad_fetch_gets_correction_not_permission_refusal(monkeypatch):
+ import src.clean_agent_preview as module
+ requests = []
+ responses = iter([
+ {'tool_calls': [{'index': 0, 'id': 'bad-fetch', 'type': 'function',
+ 'function': {'name': 'web_fetch', 'arguments': '{"query":"compose a letter"}'}}]},
+ {'content': 'Dear Jordan,\nGreetings from under the sea!'},
+ ])
+
+ class Response:
+ def __init__(self, delta): self.delta = delta
+ async def __aenter__(self): return self
+ async def __aexit__(self, *args): pass
+ def raise_for_status(self): pass
+ async def aiter_lines(self):
+ yield 'data: ' + json.dumps({'choices': [{'delta': self.delta}]})
+ yield 'data: [DONE]'
+
+ class Client:
+ def __init__(self, **kwargs): pass
+ async def __aenter__(self): return self
+ async def __aexit__(self, *args): pass
+ def stream(self, *args, **kwargs):
+ requests.append(json.loads(json.dumps(kwargs['json'])))
+ return Response(next(responses))
+
+ async def execute(*args, **kwargs):
+ pytest.fail('Malformed fetch must never execute')
+
+ monkeypatch.setattr(module.httpx, 'AsyncClient', Client)
+ monkeypatch.setattr(module, 'execute_tool_block', execute)
+ schemas = [s for s in FUNCTION_TOOL_SCHEMAS if s['function']['name'] == 'web_fetch']
+ policy = ToolPolicy()
+ contract = resolve_full_inventory_contract(schemas=schemas, policy=policy)
+ events = [json.loads(chunk[6:]) async for chunk in stream_preview(
+ endpoint_url='http://test', model='test',
+ messages=[{'role': 'user', 'content': 'write an email as a fish to Jordan'}],
+ headers={}, turn_contract=contract, session_id='test', owner='test',
+ disabled_tools=set(), tool_policy=policy,
+ ) if '[DONE]' not in chunk]
+ assert len(requests) == 2
+ correction = requests[1]['messages']
+ assert any('requires url or urls' in str(m.get('content')) for m in correction)
+ assert any('not a permission denial' in str(m.get('content')) for m in correction)
+ metrics = next(e['data'] for e in events if e.get('type') == 'metrics')
+ assert metrics['clean_v3_turn'][-1]['content'].startswith('Dear Jordan')
+ assert metrics['tool_schema_names'] == ['web_fetch']
+ assert metrics['tool_schema_count'] == len(metrics['tool_schema_names'])
+
+
+async def test_ajax_complete_draft_has_no_lookup_or_delivery_tools(monkeypatch):
+ import src.clean_agent_preview as module
+ import src.email_task_intent as intent_module
+ requests = []
+ classifications = []
+ async def classify(*args, **kwargs):
+ classifications.append(kwargs)
+ kwargs['accounting'].update(input_tokens=100, output_tokens=20, usage_source='real')
+ return intent_module.EmailTaskIntent('draft', (), 'Thank Jon for lunch')
+ class Response:
+ async def __aenter__(self): return self
+ async def __aexit__(self, *args): pass
+ def raise_for_status(self): pass
+ async def aiter_lines(self):
+ yield 'data: ' + json.dumps({'choices': [{'delta': {'content': 'Hi Jon, thanks for lunch!'}}]})
+ yield 'data: ' + json.dumps({'choices': [], 'usage': {'prompt_tokens': 200, 'completion_tokens': 30}})
+ yield 'data: [DONE]'
+ class Client:
+ def __init__(self, **kwargs): pass
+ async def __aenter__(self): return self
+ async def __aexit__(self, *args): pass
+ def stream(self, *args, **kwargs):
+ requests.append(kwargs['json'])
+ return Response()
+ async def execute(*args, **kwargs):
+ pytest.fail('A fully supplied chat draft needs no tool execution')
+ monkeypatch.setattr(intent_module, 'classify_email_task', classify)
+ monkeypatch.setattr(module.httpx, 'AsyncClient', Client)
+ monkeypatch.setattr(module, 'execute_tool_block', execute)
+ policy = ToolPolicy()
+ schemas = [s for s in FUNCTION_TOOL_SCHEMAS if s['function']['name'] in {'web_fetch', 'ask_user', 'read_email'}]
+ contract = resolve_full_inventory_contract(schemas=schemas, policy=policy)
+ events = [json.loads(chunk[6:]) async for chunk in stream_preview(
+ endpoint_url='http://test', model='Ajax', headers={}, turn_contract=contract,
+ messages=[{'role': 'user', 'content': 'Draft an email thanking Jon for lunch'}],
+ session_id='test', owner='test', disabled_tools=set(), tool_policy=policy,
+ thinking_mode='off',
+ ) if '[DONE]' not in chunk]
+ assert len(requests) == 1
+ assert len(classifications) == 1
+ assert not requests[0].get('tools')
+ assert any(e.get('stage') == 'email_task_scope' for e in events)
+ metrics = next(e['data'] for e in events if e.get('type') == 'metrics')
+ assert metrics['input_tokens'] == 300
+ assert metrics['output_tokens'] == 50
+ assert metrics['injected_tokens'] == metrics['last_request_tokens'] == 200
+
+
[email protected]('failure', ['timeout', 'invalid_json'])
+async def test_ajax_scope_failure_finishes_protocol_without_execution(monkeypatch, failure):
+ import httpx
+ import src.clean_agent_preview as module
+ import src.email_task_intent as intent_module
+
+ async def classify(*args, **kwargs):
+ if failure == 'timeout':
+ raise httpx.ReadTimeout('fixture')
+ kwargs['accounting'].update(input_tokens=101, output_tokens=12, usage_source='real')
+ raise ValueError('Malformed classifier output')
+
+ class Client:
+ def __init__(self, **kwargs): pass
+ async def __aenter__(self): return self
+ async def __aexit__(self, *args): pass
+ def stream(self, *args, **kwargs):
+ pytest.fail('Unknown scope must not generate with broad tools')
+
+ async def execute(*args, **kwargs):
+ pytest.fail('Unknown scope must not execute')
+
+ monkeypatch.setattr(intent_module, 'classify_email_task', classify)
+ monkeypatch.setattr(module.httpx, 'AsyncClient', Client)
+ monkeypatch.setattr(module, 'execute_tool_block', execute)
+ policy = ToolPolicy()
+ schemas = [s for s in FUNCTION_TOOL_SCHEMAS if s['function']['name'] in {'web_fetch', 'read_email'}]
+ contract = resolve_full_inventory_contract(schemas=schemas, policy=policy)
+ chunks = [c async for c in stream_preview(
+ endpoint_url='http://test', model='Ajax', headers={}, turn_contract=contract,
+ messages=[{'role': 'user', 'content': 'Draft an email thanking Jon for lunch'}],
+ session_id='test', owner='test', disabled_tools=set(), tool_policy=policy)]
+ events = [json.loads(c[6:]) for c in chunks if c.startswith('data: ') and '[DONE]' not in c]
+ metrics = next(e['data'] for e in events if e.get('type') == 'metrics')
+ assert metrics['email_task_scope']['failed'] is True
+ assert metrics['agent_rounds'] == metrics['tool_calls'] == 0
+ assert metrics['total_tokens'] == (113 if failure == 'invalid_json' else 0)
+ assert 'No action was taken' in metrics['clean_v3_turn'][-1]['content']
+ assert any(e.get('type') == 'final_response' for e in events)
+ assert not any(e.get('delta') for e in events)
+ assert chunks[-1] == 'data: [DONE]\n\n'
diff --cc tests/test_product_turn_contract_route.py
index be77739ae,8055c6516..07dc5bdb9
--- a/tests/test_product_turn_contract_route.py
+++ b/tests/test_product_turn_contract_route.py
@@@ -332,12 -336,11 +336,12 @@@ async def test_native_sft_owner_can_use
@pytest.mark.asyncio
[email protected]('deny_core', [False, True])
- async def test_exact_odysseus_clean_route_keeps_requested_family_and_core(
+ async def test_exact_odysseus_clean_route_offers_only_requested_compact_family(
- monkeypatch, registered_mcp_manager,
+ monkeypatch, registered_mcp_manager, deny_core,
):
from routes import chat_routes
- from src import tool_security
+ from src import settings, tool_security
endpoint = _chat_stream_endpoint(
monkeypatch, "agent", {},
@@@ -373,11 -372,9 +377,10 @@@
contract = observed[0]
assert contract.selection_mode == "clean_compact_v3_preview"
assert contract.capabilities == {"tasks"}
- from src.clean_agent_preview import INTERACTIVE_CORE_TOOLS
- assert contract.offered == ({"manage_tasks"} | INTERACTIVE_CORE_TOOLS) & contract.executable
- assert contract.offered == {"manage_tasks", "ask_user"}
++ assert contract.offered == ({"manage_tasks"} if deny_core else {"manage_tasks", "ask_user"})
++ assert not {"bash", "python", "read_file", "web_search", "web_fetch"} & contract.offered
assert contract.required == {"manage_tasks"}
- if deny_core:
- assert not contract.offered & INTERACTIVE_CORE_TOOLS
+ assert contract.permits("manage_tasks")
@pytest.mark.asyncio
diff --cc tests/test_tool_routing_experiment.py
index d09caf00e,25fcd03d2..116b0edc6
--- a/tests/test_tool_routing_experiment.py
+++ b/tests/test_tool_routing_experiment.py
@@@ -52,7 -52,7 +52,7 @@@ def test_web_subject_followup_does_not_
assert capabilities == {'search_browser'}
assert result.offered
assert {schema.rsplit('__', 1)[-1] for schema in result.offered} <= {
-- 'web_search', 'web_fetch', 'private_browser', 'youtube_tool',
++ 'web_search', 'web_fetch', 'get_weather', 'private_browser', 'youtube_tool',
'search_hf_models', 'pdf_extract',
}
assert not result.offered.intersection({
diff --cc tests/test_tui_round_cap.py
index cdad7173a,cdad7173a..7d08f70ff
--- a/tests/test_tui_round_cap.py
+++ b/tests/test_tui_round_cap.py
@@@ -2,6 -2,6 +2,7 @@@
import json
++from src.tool_policy import WEB_TOOL_NAMES
from routes.chat_routes import (
_effective_agent_rounds,
_effective_native_output_tokens,
@@@ -811,14 -811,14 +812,14 @@@ def test_local_network_turn_is_not_shor
context = _host_bridge_context()
assert not _web_search_unavailable_for_turn(
{"web", "files"},
-- {"web_search", "web_fetch"},
++ set(WEB_TOOL_NAMES),
"Find the local IP for ajax; do not use web search.",
context,
None,
)
assert _web_search_unavailable_for_turn(
{"web"},
-- {"web_search", "web_fetch"},
++ set(WEB_TOOL_NAMES),
"Search the web for the latest Qwen release.",
context,
None,
diff --cc tests/test_yoyo_builtin_theme.py
index 3845c099e,3845c099e..f5f5eee9c
--- a/tests/test_yoyo_builtin_theme.py
+++ b/tests/test_yoyo_builtin_theme.py
@@@ -17,5 -17,5 +17,9 @@@ def test_agent_theme_inventory_includes
interaction = (ROOT / "src/ai_interaction.py").read_text(encoding="utf-8")
schemas = (ROOT / "src/tool_schemas.py").read_text(encoding="utf-8")
-- assert '"monolith", "yoyo"' in interaction
++ from src.theme_palette import THEME_PRESETS
++
++ # The agent's preset inventory is the shared palette module's tuple.
++ assert THEME_PRESETS[-2:] == ("monolith", "yoyo")
++ assert "from src.theme_palette import THEME_PRESETS" in interaction
assert "blueprint, monolith, yoyo" in schemas
diff --cc tests/tools/editor_writing_smoke.py
index 19ec96ebc,000000000..f2b2100f1
mode 100644,000000..100644
--- a/tests/tools/editor_writing_smoke.py
+++ b/tests/tools/editor_writing_smoke.py
@@@ -1,144 -1,0 +1,145 @@@
+"""Opt-in Ajax smoke test: temporary SQLite docs, stubbed web, no real mutations.
+
+Run from repository root with PYTHONPATH=. and ODYSSEUS_EDITOR_TEST_ENDPOINT set.
+Optional ODYSSEUS_EDITOR_ACTIONS selects comma-separated actions.
+"""
+import asyncio, json, os, re, tempfile
+from pathlib import Path
+from types import SimpleNamespace
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+from core import database
+from src import database as compat
+from src.agent_tools import TOOL_HANDLERS
+import src.clean_agent_preview as runner
+from src.tool_policy import ToolPolicy
+from src.tool_schemas import FUNCTION_TOOL_SCHEMAS
++from tests.helpers.document_source import declaration
+from src.turn_contract import requested_capabilities, selected_tools_for_request, preserve_bound_editor_selected_tools, resolve_turn_contract
- menu=Path('static/js/document.js').read_text().split('const _AI_WRITING_ACTIONS = Object.freeze({',1)[1].split('});',1)[0]
++menu=declaration('_AI_WRITING_ACTIONS')
+actions=dict(re.findall(r"\s+(\w+): '([^']+)'",menu))
+image_body = '<p>Old caption</p><p><img src="/api/generated-image/fixture.png" alt="Fixture image" width="320" height="180"></p><p>Keep this paragraph unchanged.</p>'
+email_body = ('To: [email protected]\nSubject: Re: Design review\nIn-Reply-To: <[email protected]>\n---\n'
+ '<div class="email-reply-edit-slot"><p>Hi Sam,</p><p>I can attend on Tuesday.</p><p>Thanks,<br>Alex</p></div>'
+ '<div class="email-quoted-history" contenteditable="false"><p>Sam wrote: Can you attend on Tuesday?</p></div>')
+edit_cases = {
+ 'rich-image-caption': ('richtext', image_body,
+ 'Change Old caption to New caption in the open document. Preserve the embedded image, its attributes, and all other text.',
+ lambda value: value == image_body.replace('Old caption', 'New caption')),
+ 'email-reply-only': ('email', email_body,
+ 'Change Tuesday to Wednesday only in my reply, not in the quoted email. Keep the recipient, subject, signature and quoted history unchanged.',
+ lambda value: value == email_body.replace('I can attend on Tuesday.', 'I can attend on Wednesday.')),
+ 'email-subject-only': ('email', email_body,
+ 'Change only the subject of this open email draft to Schedule confirmation. Leave all other headers, reply text and quoted history unchanged.',
+ lambda value: value == email_body.replace('Subject: Re: Design review', 'Subject: Schedule confirmation')),
+ 'email-recipient-only': ('email', email_body,
+ 'Change only the recipient of this open email draft to [email protected]. Do not send it. Keep the greeting, subject, body and quoted history unchanged.',
+ lambda value: value == email_body.replace('To: [email protected]', 'To: [email protected]')),
+ 'email-signature-only': ('email', email_body,
+ 'Change Alex to Alexandra only in my reply signature. Keep all headers, other reply text, formatting and quoted history unchanged.',
+ lambda value: value == email_body.replace('Thanks,<br>Alex', 'Thanks,<br>Alexandra')),
+ 'delete-line': ('text', 'Alpha\nRemove this line\nGamma\n',
+ 'Delete only the line Remove this line, including its newline. Keep everything else unchanged.',
+ lambda value: value == 'Alpha\nGamma\n'),
+ 'replace-all': ('text', 'alpha is first.\nalpha is repeated.\nKeep: violet-72\n',
+ 'Replace every occurrence of alpha with beta. Keep everything else unchanged.',
+ lambda value: value == 'beta is first.\nbeta is repeated.\nKeep: violet-72\n'),
+ 'append-line': ('text', 'Alpha\nBeta\n',
+ 'Append Gamma on a new final line, ending with a newline. Keep the existing two lines unchanged and do not add a blank line.',
+ lambda value: value == 'Alpha\nBeta\nGamma\n'),
+ 'markdown-table': ('markdown', '| Item | Status |\n| --- | --- |\n| Alpha | pending |\n| Beta | pending |\n\nKeep this paragraph unchanged.',
+ 'Change only the Beta row status from pending to done. Keep the Alpha row and all other text unchanged.',
+ lambda value: value == '| Item | Status |\n| --- | --- |\n| Alpha | pending |\n| Beta | done |\n\nKeep this paragraph unchanged.'),
+ 'rich-link-text': ('richtext', '<p>Read <a href="https://example.com/manual" target="_blank">old guide</a> before starting.</p><p><strong>Keep this paragraph unchanged.</strong></p>',
+ 'Change the link text from old guide to setup guide. Keep its URL, attributes, formatting and all other text unchanged.',
+ lambda value: value == '<p>Read <a href="https://example.com/manual" target="_blank">setup guide</a> before starting.</p><p><strong>Keep this paragraph unchanged.</strong></p>'),
+ 'json-value': ('json', '{"name":"outer","settings":{"name":"inner","enabled":true},"count":7}',
+ 'Change settings.name to updated. Leave the outer name and all other values unchanged.',
+ lambda value: json.loads(value) == {'name':'outer','settings':{'name':'updated','enabled':True},'count':7}),
+ 'repeated': ('text', 'First: alpha\nSecond: alpha\nKeep: violet-72',
+ 'Change only the second alpha to beta. Keep everything else unchanged.',
+ lambda value: value == 'First: alpha\nSecond: beta\nKeep: violet-72'),
+ 'quoted-code': ('javascript', 'const label = "old";\nconst count = 7;\n',
+ 'Change the label string to new. Keep the count and all other code unchanged.',
+ lambda value: value == 'const label = "new";\nconst count = 7;\n'),
+ 'svg-color': ('svg', '<svg xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" fill="orange"/></svg>',
+ 'Make the circle white without changing its size or position.',
+ lambda value: value == '<svg xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" fill="white"/></svg>'),
+}
+async def main():
+ failures=[]
+ selected_actions = os.environ.get('ODYSSEUS_EDITOR_ACTIONS', ','.join([*actions,'edit','update'])).split(',')
+ unknown = set(selected_actions) - (set(actions) | set(edit_cases) | {'edit', 'update'})
+ if unknown: raise ValueError('Unknown editor test actions: ' + ', '.join(sorted(unknown)))
+ with tempfile.TemporaryDirectory(prefix='editor-fixture-') as tmp:
+ engine=create_engine('sqlite:///'+tmp+'/test.db');database.Base.metadata.create_all(engine)
+ factory=sessionmaker(bind=engine);database.SessionLocal=compat.SessionLocal=factory
+ for action in selected_actions:
+ body='The calendar has events and notes about Python scripts. This sentnce is unecessarily long and it is very very unclear.\n\nKeep this paragraph unchanged.'
+ if action=='sources': body='Water freezes at 10 degrees Celsius at standard pressure.\n\nKeep this paragraph unchanged.'
+ rich_fixture = os.environ.get('ODYSSEUS_EDITOR_RICH_FIXTURE') == '1'
+ if rich_fixture and action != 'sources':
+ body = ''.join(f'<p>Section {i}: This sentnce has an unecessary delay. That banana is ripe; being patient helps.</p>' for i in range(1, 9)) + '<p><strong>Keep this paragraph unchanged.</strong></p>'
+ language = 'richtext' if rich_fixture else 'markdown'
+ if action in edit_cases:
+ language, body, _, _ = edit_cases[action]
+ with factory() as db:
+ db.add(database.Document(id=action,owner='fixture-owner',title='Fixture',language=language,current_content=body));db.commit()
+ doc=SimpleNamespace(id=action,title='Fixture',language=language,current_content=body)
+ prompt=actions.get(action, 'Fix sentnce to sentence in the open document.' if action=='edit' else 'Rewrite the whole open document as two short bullet points.')
+ if action in edit_cases: prompt = edit_cases[action][2]
+ if action in actions:
+ if action=='style': prompt+='\n\nUse this configured writing style as the source of truth:\n---\nUse plain, concise English.\n---'
+ prompt+='\n\nImportant scope: work only on this selected passage and do not suggest changes elsewhere in the document. Selected passage:\n---\n'+body.split('\n\n')[0]+'\n---'
+ if rich_fixture:
+ prompt = prompt.split('\n\nImportant scope:')[0] + '\n\nThere is no selection. Work on the whole open document.'
+ calls=[]
+ async def execute(block, **kwargs):
+ name=block.tool_type
+ calls.append(name)
+ if name in {'web_search','web_fetch','private_browser'}:
+ return 'fixture evidence',{'output':json.dumps({'results':[{'title':'Freezing point of water','url':'https://example.com/water','content':'At standard pressure, water freezes at 0 degrees Celsius.'}]}),'exit_code':0}
+ assert name in {'suggest_document','edit_document','update_document'},name
+ result=await TOOL_HANDLERS[name](block.content,{'owner':'fixture-owner','doc_id':action})
+ return name,result
+ runner.execute_tool_block=execute
+ policy=ToolPolicy();families=requested_capabilities(prompt,active_document=True)
+ selected=preserve_bound_editor_selected_tools(prompt,selected_tools_for_request(prompt),active_document=True)
+ contract=resolve_turn_contract(capabilities=families,schemas=FUNCTION_TOOL_SCHEMAS,policy=policy,selected_tools=selected)
+ events=[]
+ async for chunk in runner.stream_preview(endpoint_url=os.environ['ODYSSEUS_EDITOR_TEST_ENDPOINT'],model='Ajax',headers={},turn_contract=contract,messages=[{'role':'user','content':prompt}],session_id='fixture-editor',owner='fixture-owner',disabled_tools=set(),tool_policy=policy,thinking_mode='off',active_document=doc,max_tokens=int(os.environ.get("ODYSSEUS_EDITOR_MAX_TOKENS", "4096"))):
+ if chunk.startswith('data: ') and '[DONE]' not in chunk:
+ event=json.loads(chunk[6:]); events.append(event)
+ if event.get('type') == 'tool_output': print('CHECK', action, event.get('tool'), 'round=' + str(event.get('round')), 'error=' + str(event.get('error')), flush=True)
+ with factory() as db: after=db.get(database.Document,action).current_content
+ suggestions=[e for e in events if e.get('type')=='doc_suggestions']
+ outputs=[{'tool':e['tool'],'error':e.get('error'),'output':e.get('output','')[:200], 'arguments':e.get('command','')[:2000]} for e in events if e.get('type')=='tool_output']
+ ok=bool(suggestions) and after==body if action in actions and action!='proofread' else after!=body
+ if action=='sources':ok=ok and any(n in calls for n in ['web_search','web_fetch','private_browser'])
+ if action in actions and action!='proofread':
+ ok=ok and all(item['find'] in body.split('\n\n')[0] for event in suggestions for item in event['suggestions'])
+ if action=='concise':
+ from src.clean_agent_preview import document_suggestion_quality_error
+ ok=ok and all(document_suggestion_quality_error('suggest_document',
+ {'suggestions': event['suggestions']}, user_text=prompt) is None for event in suggestions)
+ if action in {'edit','proofread'}: ok=ok and 'Keep this paragraph unchanged.' in after
+ if action == 'proofread': ok = ok and 'sentnce' not in after and 'unecessarily' not in after
+ if action in edit_cases: ok = edit_cases[action][3](after)
+ if rich_fixture and action=='proofread':
+ ok = ok and 'sentnce' not in after and 'unecessary' not in after
+ ok = ok and after.count('That banana is ripe; being patient helps.') == 8
+ ok = ok and after.count('<p>') == 9 and '<strong>Keep this paragraph unchanged.</strong>' in after
+ if not ok: failures.append(action)
+ answer = ''
+ for event in events:
+ if event.get('type') == 'final_response': answer = event.get('content') or ''
+ elif isinstance(event.get('delta'), str):
+ if event.get('replacement_scope') == 'turn': answer = ''
+ answer += event['delta']
+ print(json.dumps({'action':action,'pass':ok,'failed_attempts':sum(bool(o.get('error')) for o in outputs),'calls':calls,'suggestions':suggestions,'outputs':outputs,'changed':after!=body,'answer':answer}),flush=True)
+ if os.environ.get('ODYSSEUS_EDITOR_TRACE'):
+ print('EVENTS', json.dumps(events), flush=True)
+ engine.dispose()
+ if failures: raise SystemExit('Failed writing actions: '+', '.join(failures))
+if __name__ == '__main__':
+ asyncio.run(main())
diff --cc website/configuration-reference.md
index 000000000,7af02dcec..133036acc
mode 000000,100644..100644
--- a/website/configuration-reference.md
+++ b/website/configuration-reference.md
@@@ -1,0 -1,267 +1,277 @@@
+ ---
+ layout: default
+ ---
+
+ # Configuration reference: ODYSSEUS_* environment variables
+
+ <!-- This page is generated from the source tree by `scripts/generate_env_reference.py`. Do not edit it by hand: run the script instead. `tests/test_env_reference.py` fails when the committed page and the source disagree, or when a variable is read without an entry in the script's notes table. -->
+
+ Odysseus reads its runtime configuration from the Settings UI. The
+ environment variables below are the deployment-level escape hatches underneath
+ that: they are read directly from the process environment, mostly at import or
+ startup, and most installs never need any of them.
+
+ `.env.example` stays a short, deployment-level example on purpose - `APP_BIND`,
+ `APP_PORT`, `AUTH_ENABLED`, `DATABASE_URL` and a pre-seeded admin password. This
+ page is the complete list, which is a different job.
+
+ Truthiness is not uniform across the codebase. Where a variable is described as
+ "truthy" the read accepts `1`, `true`, `yes` and usually `on`; where it is
+ described as a switch that turns something off, the read rejects `0`, `false`,
+ `no` and `off` and treats everything else as on. The `Default` column is the
+ value the code falls back to when the variable is unset, quoted from the source.
+
-The source tree reads **98** `ODYSSEUS_*` variables: 78 an operator may want to set, and 20 that are internal - sentinels, fixture switches, capture hooks and development tooling. The internal ones are listed too, in their own section, so this page can be checked against the source mechanically.
++The source tree reads **108** `ODYSSEUS_*` variables: 78 an operator may want to set, and 30 that are internal - sentinels, fixture switches, capture hooks and development tooling. The internal ones are listed too, in their own section, so this page can be checked against the source mechanically.
+
+ > This page is generated. Edit `scripts/generate_env_reference.py` and
+ > re-run it; `tests/test_env_reference.py` enforces that the committed page
+ > matches the source.
+
+ ## Variables you can set
+
+ ### Deployment and first run
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_ADMIN_PASSWORD` | `''` | `setup.py:102` (+4 more) | Password for the admin account created on first run. Setup refuses a value shorter than its minimum length rather than silently falling back. |
+ | `ODYSSEUS_ADMIN_USER` | `''` | `setup.py:101` (+2 more) | Username for the admin account created on first run. Setup uses env vars first, then an interactive prompt, then a random password. |
+ | `ODYSSEUS_ALLOW_OLLAMA_CLI_SCAN` | *unset* | `routes/cookbook_helpers.py:544` (+1 more) | On Windows only, set truthy to let the Cookbook dependency probe shell out to `ollama list`. Ignored on other platforms, where the scan always runs. |
+ | `ODYSSEUS_CONTAINER_NETWORK_MODE` | `''` | `app.py:1022` (+1 more) | Declares the container's Docker network mode. Set to `host` to skip host-gateway probing when discovering local model endpoints. |
+ | `ODYSSEUS_ENABLE_HOST_DOCKER` | `''` | `src/host_docker_access.py:41` | Security-relevant. Must be exactly `true` before tools may use a mounted host Docker socket, and the socket itself must exist. |
+ | `ODYSSEUS_INPROCESS_POLLERS` | `'1'` | `routes/email/email_pollers.py:1722` | The same off switch for the in-process email pollers, when `odysseus-mail poll-scheduled` is the sole external driver. |
+ | `ODYSSEUS_INPROCESS_TASKS` | `'1'` | `app.py:1311` | Set to 0, false, no or off to stop the in-process scheduled-task runner, for deployments where an external worker drives task firing. |
+ | `ODYSSEUS_MODEL_KEEPALIVE` | `''` | `app.py:1218` | Opt-in periodic model keep-alive pings. Off by default: the ping path runs model discovery, so stale LAN endpoints add background pressure. |
+ | `ODYSSEUS_REQUIRE_TOOL_INDEX_READY` | `''` | `src/readiness.py:61` | Set truthy to make semantic tool-index readiness gate startup. Off by default so an install stays available on deterministic tool selection. |
+ | `ODYSSEUS_SKIP_ADMIN_PROMPT` | *unset* | `setup.py:112` | Any non-empty value suppresses the interactive admin-credential prompt even on a TTY, for unattended installs. |
+ | `ODYSSEUS_SLOW_REQUEST_LOG_SECONDS` | `'0.75'` | `app.py:239` | Request duration in seconds above which the middleware logs a slow-request warning. |
+ | `ODYSSEUS_STARTUP_WARMUPS` | `''` | `app.py:1192` | Opt-in startup pings of the configured model endpoints. Off by default because they compete with the first seconds of UI use. |
-| `ODYSSEUS_TOOL_INDEX_PREWARM` | `'1'` | `src/tool_index.py:771` | Set to 0, false, no or off to skip background initialization of semantic tool retrieval at startup. |
++| `ODYSSEUS_TOOL_INDEX_PREWARM` | `'1'` | `src/tool_index.py:772` | Set to 0, false, no or off to skip background initialization of semantic tool retrieval at startup. |
+
+ ### Data directories and paths
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_DATA_DIR` | `get_default_data_dir()` | `src/constants.py:56` (+1 more) | Root directory for every persisted file. Prefer this over the per-path overrides; the rest of `src/constants.py` derives from it. |
+ | `ODYSSEUS_MAIL_ATTACHMENTS_DIR` | `os.path.join(DATA_DIR, 'mail-attachments')` | `src/constants.py:102` | Dedicated override for the mail attachment store, which otherwise lives under the data directory. |
+
+ ### Model routing and providers
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_COPILOT_API_VERSION` | `'2026-06-01'` | `src/copilot.py:39` | Dated API-version header the Copilot models and chat endpoints require. |
+ | `ODYSSEUS_COPILOT_CLIENT_ID` | `'01ab8ac9400c4e429b23'` | `src/copilot.py:34` | GitHub OAuth client id for the Copilot device flow. The default is the public VS Code client id; override it only with your own allow-listed app. |
+ | `ODYSSEUS_DEEPSEEK_REASONING_EFFORT` | `'high'` | `src/llm_core.py:1727` | Reasoning effort for DeepSeek. Only `high` and `max` are accepted; any other value falls back to the default. |
+ | `ODYSSEUS_FIRST_TOKEN_TIMEOUT` | `''` | `src/llm_core.py:223` | Seconds to wait for the first streamed token from a local endpoint before failing. Unset keeps the generous read timeout, which makes a stalled backend look like a hung agent. |
+ | `ODYSSEUS_LOCAL_MODEL_GATE` | `'true'` | `src/llm_core.py:95` | On by default. Set 0, false, no or off to drop the gate that checks a local endpoint before routing a request to it. |
+ | `ODYSSEUS_MISTRAL_REASONING_EFFORT` | `'high'` | `src/llm_core.py:1723` | Reasoning effort sent to Mistral thinking-capable models. The API accepts high, medium, low and none. |
+ | `ODYSSEUS_MLX_IMAGE_VLM_MODEL` | *unset* | `scripts/mlx_image_server.py:299` | Vision-language model id for the MLX image server script. Required unless `--vlm-model` is passed on the command line. |
+ | `ODYSSEUS_QWEN_ROUTE_THINKING` | `'auto'` | `src/agent_loop.py:166` | Thinking policy for the Qwen routing step. An unrecognized value falls back to `auto`. |
+
+ ### Agent loop and tool execution
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_DISABLE_MCP` | `''` | `src/builtin_mcp.py:89` | Truthy disables MCP entirely, as an escape hatch for compatibility problems with a server. |
-| `ODYSSEUS_MAX_VISUAL_EVIDENCE_FRAMES` | `'3'` | `src/agent_loop.py:15360` | How many video frames one tool result may contribute. Clamped to 1-8. |
-| `ODYSSEUS_MAX_VISUAL_EVIDENCE_IMAGES` | `'1'` | `src/agent_loop.py:15328` | How many images one tool result may contribute to the model turn. Clamped to 1-8. |
++| `ODYSSEUS_MAX_VISUAL_EVIDENCE_FRAMES` | `'3'` | `src/agent_loop.py:15366` | How many video frames one tool result may contribute. Clamped to 1-8. |
++| `ODYSSEUS_MAX_VISUAL_EVIDENCE_IMAGES` | `'1'` | `src/agent_loop.py:15334` | How many images one tool result may contribute to the model turn. Clamped to 1-8. |
+ | `ODYSSEUS_MCP_ALLOWED_COMMANDS` | `''` | `src/agent_tools/admin_tools.py:140` | Security-relevant. Comma-separated allowlist of MCP launcher basenames the agent may start. Empty by default, and the deny list still wins. |
+ | `ODYSSEUS_PYTHON_TOOL_SITE_PACKAGES` | `''` | `src/agent_tools/subprocess_tools.py:925` | Security-relevant. Absolute package roots, separated by the platform path separator, exposed to the sandboxed Python tool. Empty exposes none. |
+ | `ODYSSEUS_SCRIPT_HOST` | `'localhost'` | `src/builtin_actions.py:919` | Default host for the run-script action. `localhost`, `127.0.0.1`, `local` and empty run locally; any other value runs over SSH. |
+ | `ODYSSEUS_TOOL_APPROVAL_GATE` | `'0'` | `src/tool_capabilities.py:645` | Security-relevant. Truthy makes tool calls pass through the approval gate. Off by default. |
+
+ ### Browser automation
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_BROWSER_EXECUTABLE` | `''` | `src/builtin_mcp.py:114` | Absolute path to the Chrome or Chromium binary. Empty searches the usual names, then lets Playwright MCP pick its own browser. |
+ | `ODYSSEUS_BROWSER_ISOLATED` | `'1'` | `src/builtin_mcp.py:139` | Security-relevant. On by default, adding `--isolated` so each browser session starts clean. Set 0, false or no to keep a persistent profile. |
+ | `ODYSSEUS_BROWSER_MCP_CACHE` | `os.path.join(base_dir, 'data', 'local', 'playwright-mcp-cache')` | `src/builtin_mcp.py:229` | Cache directory handed to the browser MCP server, so its npm download survives a container rebuild. |
+ | `ODYSSEUS_BROWSER_MCP_REQUIRE_CACHE` | `''` | `src/builtin_mcp.py:90` | Truthy refuses to start the browser MCP server unless its npm package is already in the npx cache, instead of installing it at startup. |
-| `ODYSSEUS_BROWSER_NAMESPACE` | `'odysseus-ui'` | `src/agent_tools/web_tools.py:2355` (+5 more) | Namespace for the detached agent-browser daemon's pid files, so two runtimes on one machine do not terminate each other's browsers. |
++| `ODYSSEUS_BROWSER_NAMESPACE` | `'odysseus-ui'` | `src/agent_tools/web_tools.py:2441` (+5 more) | Namespace for the detached agent-browser daemon's pid files, so two runtimes on one machine do not terminate each other's browsers. |
+ | `ODYSSEUS_BROWSER_NO_SANDBOX` | `'1'` | `src/builtin_mcp.py:142` | Security-relevant. On by default, adding `--no-sandbox` because the Docker image cannot use the Chromium sandbox. Set 0, false or no to keep it. |
-| `ODYSSEUS_BROWSER_SCREENSHOT_DIR` | *unset* | `src/agent_tools/web_tools.py:3010` | Where private-browser screenshots are written. Falls back to the container path, then the system temp directory. |
++| `ODYSSEUS_BROWSER_SCREENSHOT_DIR` | *unset* | `src/agent_tools/web_tools.py:3135` | Where private-browser screenshots are written. Falls back to the container path, then the system temp directory. |
+
+ ### Container and workspace mounts
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_WORKSPACE_CONTAINER_ROOT` | *unset* | `src/workspace_paths.py:31` | Container-side root that the host root maps onto. An `or` fallback, not a read default, supplies `/workspace` when it is unset. |
+ | `ODYSSEUS_WORKSPACE_DEFAULT` | `''` | `routes/workspace_routes.py:97` | Default workspace path the admin-only workspace route reports. Empty means no default is configured. |
+ | `ODYSSEUS_WORKSPACE_HOST_ROOT` | *unset* | `src/workspace_paths.py:29` | Single host-side root, paired with the container root below. Simpler than the explicit mount list when there is only one mount. |
+ | `ODYSSEUS_WORKSPACE_MOUNTS` | `''` | `src/workspace_paths.py:19` | `host=container` path pairs separated by commas or semicolons, so the agent can translate a container path back to the host path a user typed. |
+
+ ### Email
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_DOCUMENT_OWNER` | `''` | `mcp_servers/email_server.py:208` | Owner stamped on documents the email MCP server creates. Stdio MCP tools get no authenticated user, so without this a draft is invisible. |
+ | `ODYSSEUS_IMAP_TIMEOUT_SECONDS` | *unset* | `routes/email/email_helpers.py:1163` | IMAP socket timeout in seconds, clamped to 5-300. A non-numeric value falls back to 30 rather than failing. |
+
+ ### Calendar, notes and single-user mode
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_ALLOW_PRIVATE_CALDAV` | `'0'` | `src/caldav_sync.py:52` | Security-relevant. Truthy lets CalDAV sync reach private and link-local addresses. Off by default; this is an SSRF guard. |
+ | `ODYSSEUS_FALLBACK_OWNER` | `'owner@localhost'` | `routes/calendar_routes.py:65` | Owner address that single-user mode attributes an unauthenticated request to. Only reachable while single-user mode is on. |
+ | `ODYSSEUS_SINGLE_USER` | `'1'` | `routes/calendar_routes.py:66` | Security-relevant. On by default. Set to 0 on a real multi-user install so unauthenticated calendar writes are rejected rather than absorbed. |
+
+ ### Upload and media limits
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_CHAT_UPLOAD_MAX_BYTES` | `10 * 1024 * 1024` | `src/upload_limits.py:33` | Maximum bytes accepted for a chat attachment. |
+ | `ODYSSEUS_EDITOR_DRAFT_MAX_BYTES` | `256 * 1024 * 1024` | `src/upload_limits.py:47` | Maximum bytes accepted for a saved editor draft. |
+ | `ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES` | `25 * 1024 * 1024` | `src/upload_limits.py:56` | Maximum bytes accepted for an attachment added while composing mail. |
+ | `ODYSSEUS_GALLERY_TRANSFORM_UPLOAD_MAX_BYTES` | `25 * 1024 * 1024` | `src/upload_limits.py:44` (+1 more) | Maximum bytes accepted for an image handed to a gallery transform. |
+ | `ODYSSEUS_GALLERY_UPLOAD_MAX_BYTES` | `100 * 1024 * 1024` | `src/upload_limits.py:41` (+1 more) | Maximum bytes accepted for a gallery upload. |
+ | `ODYSSEUS_ICS_MAX_BYTES` | `10 * 1024 * 1024` | `src/upload_limits.py:62` | Maximum bytes accepted for an imported ICS file. |
+ | `ODYSSEUS_MEDIA_FRAME_TIMEOUT` | `30` | `src/media_ingress.py:146` | Seconds allowed for extracting frames from a video before giving up. |
+ | `ODYSSEUS_MEDIA_MAX_AUDIO_BYTES` | `32 * 1024 * 1024` | `src/media_ingress.py:129` | Largest source audio file the media pipeline will read. |
+ | `ODYSSEUS_MEDIA_MAX_DIMENSION` | `1600` | `src/media_ingress.py:138` | Longest edge in pixels an image is resized down to before encoding. |
+ | `ODYSSEUS_MEDIA_MAX_DOCUMENT_BYTES` | `32 * 1024 * 1024` | `src/media_ingress.py:126` | Largest source document the media pipeline will read. |
+ | `ODYSSEUS_MEDIA_MAX_DOCUMENT_CHARS` | `24000` | `src/media_ingress.py:135` | How many characters of an ingested document are inlined into the turn. |
+ | `ODYSSEUS_MEDIA_MAX_ENCODED_BYTES` | `24 * 1024 * 1024` | `src/media_ingress.py:132` | Budget for the encoded payload handed to the model, counted cumulatively across one turn's attachments rather than per file. |
+ | `ODYSSEUS_MEDIA_MAX_FILES` | `4` | `src/media_ingress.py:119` | How many local media files one agent turn may ingest. |
+ | `ODYSSEUS_MEDIA_MAX_IMAGE_BYTES` | `12 * 1024 * 1024` | `src/media_ingress.py:120` | Largest source image the media pipeline will read. |
+ | `ODYSSEUS_MEDIA_MAX_PIXELS` | `40000000` | `src/media_ingress.py:139` | Total pixel budget for a source image, as a decompression-bomb guard. |
+ | `ODYSSEUS_MEDIA_MAX_VIDEO_BYTES` | `128 * 1024 * 1024` | `src/media_ingress.py:123` | Largest source video the media pipeline will read. |
+ | `ODYSSEUS_MEDIA_MAX_VIDEO_FRAMES` | `8` | `src/media_ingress.py:140` | How many frames are sampled from a video. |
+ | `ODYSSEUS_MEDIA_PROBE_TIMEOUT` | `15` | `src/media_ingress.py:143` | Seconds allowed for probing a video's metadata before giving up. |
+ | `ODYSSEUS_MEMORY_IMPORT_MAX_BYTES` | `10 * 1024 * 1024` | `src/upload_limits.py:50` (+1 more) | Maximum bytes accepted for a memory import file. |
+ | `ODYSSEUS_PERSONAL_UPLOAD_MAX_BYTES` | `25 * 1024 * 1024` | `src/upload_limits.py:53` (+1 more) | Maximum bytes accepted for a personal-documents upload. |
+ | `ODYSSEUS_STT_MAX_AUDIO_BYTES` | `25 * 1024 * 1024` | `src/upload_limits.py:59` | Maximum bytes accepted for an audio file submitted for transcription. |
+
+ ### Search
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_SEARCH_PROVIDER` | `''` | `services/search/providers.py:43` | Forces the search provider, overriding the Settings value. Empty keeps the UI authoritative, which is what a normal install wants. |
+
+ ### Memory and skills
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_SKILL_SEMANTIC_RETRIEVAL` | `'1'` | `services/memory/skills.py:789` | On by default. Set 0, false, no or off to fall back to keyword-only skill retrieval when no vector store is reachable. |
+ | `ODYSSEUS_SKILL_SEMANTIC_THRESHOLD` | `'0.4'` | `services/memory/skills.py:800` | Minimum semantic score a skill needs to be retrieved. A non-numeric value falls back to the default. |
+
+ ### Speech and vision models
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_GROUNDING_MODEL` | `'google/owlvit-base-patch32'` | `routes/gallery/gallery_routes.py:95` | Object-grounding model id the gallery loads for text-driven selection. |
+ | `ODYSSEUS_SAM_MODEL` | `'facebook/sam-vit-base'` | `routes/gallery/gallery_routes.py:59` | Segmentation model id the gallery loads for subject selection. |
+ | `ODYSSEUS_STT_MODEL` | *unset* | `src/agent_tools/media_tools.py:2184` | Default speech-to-text model for media transcription when the tool call does not name one. |
+ | `ODYSSEUS_TTS_CACHE_MAX_BYTES` | `500 * 1024 * 1024` | `services/tts/tts_service.py:47` | Cap on the synthesized-speech cache. A non-numeric value falls back to the default. |
+
+ ### Auth and internal API
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_INTERNAL_BASE` | *unset* | `src/constants.py:178` | Base URL the in-app tool layer uses for loopback HTTP calls. Set it when the app is not reachable at the port it thinks it is bound to. |
+ | `ODYSSEUS_INTERNAL_TOKEN` | *unset* | `core/middleware.py:20` | Security-relevant. Token that lets the in-app tool layer reach admin-gated routes over loopback. Unset generates a fresh per-process token, which is what you want unless something outside the process needs the same value. |
+
+ ### Integrations (Claude, Codex)
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_API_TOKEN` | `''` | `integrations/claude/skills/odysseus/scripts/odysseus_api.py:40` (+1 more) | API token those scripts authenticate with. Both this and the URL are required; the scripts name whichever is missing. |
+ | `ODYSSEUS_URL` | `''` | `integrations/claude/skills/odysseus/scripts/odysseus_api.py:39` (+1 more) | Base URL of the Odysseus instance the bundled integration scripts call. |
+
+ ## Internal and development-only variables
+
+ Listed for completeness. Setting one of these on a real install is either a no-op or a way to break something quietly.
+
+ ### Model routing and providers
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_COPILOT_EDITOR_VERSION` | `'Odysseus/1.0'` | `src/copilot.py:54` | Editor-version header presented to the Copilot API. Kept stable on purpose. |
+ | `ODYSSEUS_COPILOT_INTEGRATION_ID` | `'vscode-chat'` | `src/copilot.py:51` | Integration id presented to the Copilot API. Kept stable on purpose. |
+ | `ODYSSEUS_COPILOT_USER_AGENT` | `'Odysseus/1.0'` | `src/copilot.py:48` | Editor-like User-Agent presented to the Copilot API. Kept stable on purpose. |
+ | `ODYSSEUS_DEBUG_LLM_SHAPE` | `''` | `src/llm_core.py:3552` (+1 more) | Truthy logs the shape of streamed provider chunks. Debugging aid for provider response parsing. |
+
+ ### Agent loop and tool execution
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_CAPTURE_MODEL_REQUESTS` | `''` | `src/agent_loop.py:3921` | Truthy writes model-request snapshots for local debugging. The marker file `/tmp/odysseus_capture_model_requests` enables the same thing. |
+ | `ODYSSEUS_EXPOSE_RAW_BROWSER_MCP` | `''` | `src/agent_loop.py:4126` | Truthy stops hiding the raw Playwright MCP tools from agent prompts when the private-browser tool is available. |
-| `ODYSSEUS_TOOL_CONTRACT_ROOT` | `'<repo>/scripts'` | `src/clean_agent_preview.py:1952` (+1 more) | Directory holding the tool-contract scripts the clean-agent preview loads. The default is the repository's bundled scripts directory; set the variable to override it. |
++| `ODYSSEUS_TOOL_CONTRACT_ROOT` | `'<repo>/scripts'` | `src/clean_agent_preview.py:2183` (+1 more) | Directory holding the tool-contract scripts the clean-agent preview loads. The default is the repository's bundled scripts directory; set the variable to override it. |
+
+ ### Email
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_EMAIL_FIXTURE` | *unset* | `mcp_servers/email_server.py:1122` (+7 more) | Exactly `1`, plus a fixture file on disk, makes the email MCP server serve fixtures instead of a real mailbox. |
+
+ ### Testing, capture and development tooling
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
++| `ODYSSEUS_AJAX_TEST_URL` | *unset* | `tests/test_ajax_email_live.py:17` (+4 more) | Chat-completions URL of a live Ajax endpoint. Unset skips the opt-in live Ajax email tests. |
++| `ODYSSEUS_EDITOR_ACTIONS` | `','.join([*actions, 'edit', 'update'])` | `tests/tools/editor_writing_smoke.py:71` | Comma-separated writing actions the editor-writing smoke tool runs. Unset runs every action plus edit and update. |
++| `ODYSSEUS_EDITOR_MAX_TOKENS` | `'4096'` | `tests/tools/editor_writing_smoke.py:110` | Completion token limit for each editor-writing smoke request. |
++| `ODYSSEUS_EDITOR_RICH_FIXTURE` | *unset* | `tests/tools/editor_writing_smoke.py:80` | Set to 1 to run the editor-writing smoke tool against a rich-text document fixture instead of Markdown. |
++| `ODYSSEUS_EDITOR_TEST_ENDPOINT` | *unset* | `tests/tools/editor_writing_smoke.py:110` (+1 more) | Chat-completions URL the opt-in editor-writing and organizer smoke tools drive. Both tools require it. |
++| `ODYSSEUS_EDITOR_TRACE` | *unset* | `tests/tools/editor_writing_smoke.py:140` | Any non-empty value prints every stream event after each editor-writing smoke action. |
++| `ODYSSEUS_ORGANIZER_AUTO_CHOICE` | *unset* | `tests/tools/organizer_smoke.py:199` | With organizer tracing on, any non-empty value replaces forced tool choice with auto on traced requests. |
++| `ODYSSEUS_ORGANIZER_CASES` | *unset* | `tests/tools/organizer_smoke.py:223` (+1 more) | Comma-separated organizer smoke case names to run. Unset runs every case. |
++| `ODYSSEUS_ORGANIZER_TRACE` | *unset* | `tests/tools/organizer_smoke.py:193` | Any non-empty value prints each provider request the organizer smoke tool sends. |
++| `ODYSSEUS_ORGANIZER_TRACE_MESSAGES` | *unset* | `tests/tools/organizer_smoke.py:203` | With organizer tracing on, any non-empty value also prints the request messages. |
+ | `ODYSSEUS_QA_TEACHER_ATTEMPTS` | `'3'` | `scripts/odysseus_conversation_qa.py:370` | Retry budget for the conversation-QA teacher model call. Clamped to 1-3. |
+ | `ODYSSEUS_QA_TEACHER_TIMEOUT` | `'120'` | `scripts/odysseus_conversation_qa.py:372` | Timeout in seconds for that call. Clamped to 15-120. |
+ | `ODYSSEUS_RUNTIME_REVISION` | `''` | `routes/chat_helpers.py:198` (+1 more) | Revision string stamped into each captured SFT trace record, so a trace can be tied back to the build that produced it. |
+ | `ODYSSEUS_SFT_DISABLE_WORKSPACE_TOOLS` | `'1'` | `src/agent_loop.py:7404` | On by default. Keeps synthetic personal-assistant fixtures out of workspace mode; set 0, false, no or off to let them through. |
+ | `ODYSSEUS_SFT_FORCE_UTC_TIMEZONE` | `'0'` | `routes/chat_routes.py:2070` | Truthy forces `sft_` accounts to UTC for deterministic batch generation. Interactive accounts still follow the browser timezone. |
+ | `ODYSSEUS_SFT_TRACE_CAPTURE` | `'1'` | `routes/chat_helpers.py:161` (+1 more) | On by default, but only for owners whose name starts with `sft_`. Set 0, false, no or off to stop writing training traces. |
+ | `ODYSSEUS_SFT_TRACE_DIR` | *unset* | `routes/chat_helpers.py:195` (+2 more) | Directory the SFT trace JSONL files are written to. Defaults to `sft_traces` under the data directory. |
+ | `ODYSSEUS_SKIP_RUN_HINT` | *unset* | `setup.py:284` | Any non-empty value suppresses the `start the server with` hint at the end of setup. `start-macos.sh` sets it because it starts the server itself. |
+ | `ODYSSEUS_TEST_STATIC_ORIGIN` | *unset* | `scripts/css_snapshot.py:249` (+6 more) | Origin an already-running static server is serving the repository from, so snapshot tooling reuses it instead of starting its own. |
+ | `ODYSSEUS_TEST_STATIC_PORT` | *unset* | `tests/conftest.py:137` | Fixed port for the test suite's static server. Unset takes an ephemeral port, which is what keeps parallel runs from colliding. |
+
+ ### Build and release metadata
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_BUILD_VERSION` | `''` | `src/constants.py:15` | Overrides the build-version string the API and UI report, without touching the public application version. |
+ | `ODYSSEUS_SOURCE_COMMIT` | `''` | `src/constants.py:33` | Overrides the source commit reported for runtime provenance, for builds that ship without a git directory. |
+
+ ## How this page is generated
+
+ The generator walks the Python sources under `app.py`, `launcher.py`, `setup.py`, `companion`, `config`, `core`, `integrations`, `mcp_servers`, `routes`, `scripts`, `services`, `src`, `tests` and finds
+ reads three ways, because no single pattern covers the codebase:
+
+ - Direct reads: `os.getenv(...)`, and any `.get` / `.setdefault` / `.pop` call or
+ subscript keyed by an `ODYSSEUS_*` literal, including names held in a
+ module-level constant. The receiver is not required to be `os.environ`, because
+ several call sites read through a mapping passed in as an argument
+ (`src/tool_index.py`, `src/host_docker_access.py`).
+ - Calls to env-reader helpers - any function that forwards one of its own
+ parameters to an environment read. This is detected rather than hardcoded, so a
+ new helper needs no change here. It is what finds the upload caps in
+ `src/upload_limits.py` and the media-ingress overrides in
+ `src/media_ingress.py`.
+ - A regex sweep of the raw file text, for reads the AST cannot see.
+ `routes/cookbook_helpers.py` builds an Ollama probe script as a list of source
+ lines, so one read lives inside a string literal.
+
+ The three passes are not redundancy. A line-based grep for a direct
-`os.environ.get("ODYSSEUS_...` call finds 70 of the 98 variables on this
++`os.environ.get("ODYSSEUS_...` call finds 80 of the 108 variables on this
+ page. What it misses is reads through an env-reader helper, reads whose call
+ spans more than one line, reads whose variable name is held in a module
+ constant, and reads through a mapping passed in as an argument - which is the
+ whole reason this page is generated rather than maintained.
+
+ The `Default` column shows the expression as written, with one level of
+ indirection resolved: a module-level constant and a dataclass field default are
+ replaced by the literal they hold, so `defaults.max_media_files` shows as `4`.
+ Anything computed at import time - `get_default_data_dir()` - is shown as
+ written, because that is the honest answer. A few call sites supply their
+ fallback with `or` rather than a default argument; those show as *unset* and say
+ so in the last column.
+
+ Regenerate it with:
+
+ ```bash
+ python3 scripts/generate_env_reference.py
+ ```