Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

14.1 KB
Raw Blame
"""Is the frontend build on disk whole enough to hand to a browser?

``index.html`` and the hashed bundles it points at are written by separate
steps of one ``npm run build``, and Vite runs with ``emptyOutDir: true`` — so
``dist/`` passes through a state where ``index.html`` is still the OLD one
while ``dist/assets/`` has already been deleted. Measured on 2026-08-22 with a
200 ms poll against the live server during a real rebuild:

* 1.8 s serving the previous ``index.html`` whose ``<script type="module">``
  answered 404,
* then 5.2 s with no ``index.html`` at all (the holding page),
* then the new build.

The middle 5.2 s are harmless: the holding page refreshes itself. The first
1.8 s are not. A window that loads that document gets the boot splash, its
entry bundle 404s, and NOTHING further runs — no React, no bundle watch, no
preload recovery. The only thing left is the blank-window watchdog in
``index.html``, which allows a splash 20 seconds before it acts. Twenty seconds
of a near-black window with a small spinner is what gets reported as "it goes
black when it reloads by itself".

The fix is to never serve that document. An ``index.html`` whose own entry
assets are not on disk is not a page, it is a trap: the caller falls back to
the holding page, which says what is happening and comes back on its own.

Deliberately un-cached. The whole point is that ``index.html`` can stay
byte-identical while the files underneath it disappear, so a result keyed on
its mtime would be exactly wrong. Costs one small read plus a handful of
``stat`` calls, on a route a window hits when it loads and once per bundle-watch
poll.
"""

from __future__ import annotations

import logging
import re
import threading
import time
from pathlib import Path

__all__ = [
    "referenced_assets",
    "build_is_complete",
    "recover_conflicted_index",
    "holding_page_html",
    "MissingBuildWatch",
    "MISSING_BUILD_GRACE_S",
    "missing_build_watch",
    "HOLDING_ATTRIBUTE",
    "HOLDING_MARKER",
]

# Present in the holding page and in nothing else, so a page that is waiting
# for a build can tell — from the document alone — whether the server is ready
# to hand it a real one yet. Both the page below and the frontend's automatic
# reloads test for it.
HOLDING_MARKER = "jarvis-build-holding"

# The ONLY form a document is ever tested against. The bare word is not safe:
# the real index.html ships an inline watchdog that names the marker in its own
# source, so a test for the word alone took every genuine build for the
# holding page — this page then never reloaded into the app, and the
# frontend's own reloads (src/lib/safeReload.ts) never fired (2026-08-22/23).
# The attribute form lives on the holding page's element and nowhere else;
# index.html composes it at runtime so it can never contain it literally.
HOLDING_ATTRIBUTE = f'data-state="{HOLDING_MARKER}"'

# Every hashed build output index.html points at. Mirrors the frontend's own
# `bundleFingerprint` (src/lib/bundleWatch.ts) — keep the two patterns in
# lockstep, they are answering the same question from opposite ends.
_ASSET_REF = re.compile(r"/assets/[A-Za-z0-9._-]+")


def referenced_assets(html: str) -> list[str]:
    """The ``/assets/...`` URLs *html* asks the browser to load.

    Order-preserving and de-duplicated, so a caller can report the first
    missing one without a second pass.
    """
    seen: dict[str, None] = {}
    for ref in _ASSET_REF.findall(html):
        seen.setdefault(ref, None)
    return list(seen)


def build_is_complete(index_file: Path, dist_dir: Path) -> bool:
    """True when *index_file* and every asset it references exist on disk.

    False for a missing/unreadable index, and false while a rebuild has taken
    the assets out from under an index that is still there. A build that
    references no assets at all is treated as complete — that is a hand-written
    or placeholder page, not a half-written Vite output.
    """
    try:
        html = index_file.read_text(encoding="utf-8", errors="replace")
    except OSError:
        return False
    if any(line.startswith("<<<<<<< ") for line in html.splitlines()):
        return False
    return _assets_exist(html, dist_dir)


def _assets_exist(html: str, dist_dir: Path) -> bool:
    for ref in referenced_assets(html):
        candidate = dist_dir / ref.lstrip("/")
        try:
            if not candidate.is_file():
                return False
        except OSError:
            return False
    return True


def recover_conflicted_index(index_file: Path, dist_dir: Path) -> str | None:
    """Serve an intact side of a Git-conflicted build without editing the merge.

    ``dist/`` is tracked, so a merge can put conflict markers into index.html
    while leaving one side's hashed assets on disk. The normal completeness
    check then sees assets from both sides and holds the desktop on Updating
    forever. Prefer the local side, then the incoming side, only when its entry
    assets exist. The unresolved file remains available for the merge owner.
    """
    try:
        lines = index_file.read_text(encoding="utf-8", errors="replace").splitlines(keepends=True)
    except FileNotFoundError:
        # A rebuild removes index.html for a moment; there is no conflict to
        # recover and nothing to warn about — the caller serves the holding page.
        return None
    except OSError:
        logging.getLogger(__name__).warning(
            "Cannot inspect the conflicted frontend index at %s", index_file, exc_info=True
        )
        return None
    if not any(line.startswith("<<<<<<< ") for line in lines):
        return None

    variants = [[], []]
    cursor = 0
    conflicts = 0
    while cursor < len(lines):
        line = lines[cursor]
        if not line.startswith("<<<<<<< "):
            for variant in variants:
                variant.append(line)
            cursor += 1
            continue

        conflicts += 1
        cursor += 1
        sides = [[], []]
        side = 0
        while cursor < len(lines) and not lines[cursor].startswith(">>>>>>> "):
            line = lines[cursor]
            if line.startswith("||||||| "):
                side = -1  # Ignore the diff3 base version.
            elif line.rstrip("\r\n") == "=======":
                side = 1
            elif side >= 0:
                sides[side].append(line)
            cursor += 1
        if cursor == len(lines) or side != 1:
            return None
        for variant, content in zip(variants, sides, strict=True):
            variant.extend(content)
        cursor += 1

    if not conflicts:
        return None
    for variant in variants:
        html = "".join(variant)
        if (
            html.lstrip("\ufeff\r\n ").lower().startswith("<!doctype html>")
            and "</html>" in html
            and referenced_assets(html)
            and _assets_exist(html, dist_dir)
        ):
            return html
    return None


# How long dist/ may stay without a complete build before the holding page
# stops saying "Updating…" and says the build is missing. A real rebuild leaves
# it incomplete for about seven seconds (measured 2026-08-22, see above); a
# slow machine running a cold `npm run build` gets generous headroom on top.
MISSING_BUILD_GRACE_S = 90.0

_log = logging.getLogger(__name__)


class MissingBuildWatch:
    """Tell a rebuild in flight apart from a UI build that is simply absent.

    The holding page used to say "Updating…" and poll forever when an install
    shipped without ``dist/`` (issue #1057), and nothing in the log said why.
    The server reports every holding-page answer here: once the build has been
    unavailable for longer than :data:`MISSING_BUILD_GRACE_S`, or was already
    missing when the server started, the page says so and one WARNING names
    the path. A complete build resets the watch.
    """

    def __init__(self, grace_s: float = MISSING_BUILD_GRACE_S) -> None:
        self._grace_s = grace_s
        self._lock = threading.Lock()
        self._since: float | None = None
        self._missing_at_startup = False
        self._warned = False

    def note_startup(self, index_file: Path, *, now: float | None = None) -> bool:
        """Record whether the server started without ``index.html``."""
        if index_file.is_file():
            return False
        with self._lock:
            self._missing_at_startup = True
            if self._since is None:
                self._since = time.monotonic() if now is None else now
        self._warn_once(index_file, "at startup")
        return True

    def observe(self, index_file: Path, *, now: float | None = None) -> bool:
        """A holding page is about to be served. Is the build missing for real?"""
        current = time.monotonic() if now is None else now
        with self._lock:
            if self._since is None:
                self._since = current
            missing = self._missing_at_startup or current - self._since >= self._grace_s
        if missing:
            self._warn_once(index_file, f"for more than {int(self._grace_s)} seconds")
        return missing

    def clear(self) -> None:
        """A complete build is on disk again."""
        with self._lock:
            self._since = None
            self._missing_at_startup = False
            self._warned = False

    def _warn_once(self, index_file: Path, when: str) -> None:
        with self._lock:
            if self._warned:
                return
            self._warned = True
        _log.warning(
            "UI build missing %s: no complete frontend build at %s. The window "
            "shows a 'UI build missing' notice until one appears. Reinstall the "
            "app, or run `npm run build` in dodaios/ui/web/frontend in a source "
            "checkout.",
            when,
            index_file,
        )


missing_build_watch = MissingBuildWatch()


def holding_page_html(*, build_missing: bool = False) -> str:
    """The page a window gets while a rebuild is between two states on disk.

    It is the boot splash, deliberately: the same ground, the same ring, the
    same theme resolution from the same ``localStorage`` key as
    ``frontend/index.html`` — so a rebuild looks like the app starting rather
    than like a different program taking over the window. Keep the colours and
    the storage key in lockstep with that file.

    It does NOT use ``<meta http-equiv="refresh">``. A blind timer reloads into
    the same half-written build over and over, which is the flicker this whole
    area keeps producing. Instead it asks the server for the entry document and
    reloads only once the answer is no longer this page — meaning a complete
    build is on disk and a reload will land on something that runs.

    ``build_missing`` swaps "Updating…" for a notice that the UI build is not
    installed, with the two ways to get one. The page keeps polling, so a build
    that does land still takes over on its own.
    """
    if build_missing:
        status = (
            '<div class="sub">UI build missing</div>'
            '<div class="hint">The web interface files (dodaios/ui/web/dist) are '
            "not installed. Reinstall the app, or run <code>npm run build</code> "
            "in dodaios/ui/web/frontend in a source checkout. This page reloads "
            "on its own once the build is there.</div>"
        )
    else:
        status = '<div class="sub">Updating…</div>'
    return (
        "<!doctype html>"
        '<html lang="en" class="dark"><head>'
        '<meta charset="utf-8">'
        '<meta name="viewport" content="width=device-width, initial-scale=1.0">'
        "<title>Assistant</title>"
        "<script>(function(){var m='dark';try{var s=(localStorage.getItem("
        "'jarvis.theme')||'').trim();if(s==='light'||s==='dark'){m=s;}"
        "else if(s==='system'){m=window.matchMedia('(prefers-color-scheme: light)')"
        ".matches?'light':'dark';}}catch(e){}"
        "var r=document.documentElement;r.classList.toggle('dark',m==='dark');"
        "r.style.colorScheme=m;})();</script>"
        "<style>"
        ":root{--jbs-bg:#fcfbf8;--jbs-accent:#a86b00;"
        "--jbs-ring:rgba(168,107,0,0.22);--jbs-name:#2b2b33;--jbs-sub:#6b6b76}"
        ":root.dark{--jbs-bg:#0a0e14;--jbs-accent:#e7c46e;"
        "--jbs-ring:rgba(231,196,110,0.2);--jbs-name:#e6e6e6;--jbs-sub:#9aa3ad}"
        "html,body{margin:0;height:100%;background:var(--jbs-bg)}"
        "#s{position:fixed;inset:0;display:flex;flex-direction:column;"
        "align-items:center;justify-content:center;gap:18px;"
        "background:var(--jbs-bg);color:var(--jbs-accent);"
        "font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif}"
        "#s .ring{width:38px;height:38px;border-radius:50%;"
        "border:3px solid var(--jbs-ring);border-top-color:var(--jbs-accent);"
        "animation:sp 0.8s linear infinite}"
        "#s .name{font-size:15px;font-weight:600;letter-spacing:0.04em;"
        "color:var(--jbs-name)}"
        "#s .sub{font-size:12px;color:var(--jbs-sub);letter-spacing:0.06em;"
        "text-transform:uppercase}"
        "#s .hint{max-width:440px;padding:0 16px;font-size:13px;line-height:1.5;"
        "text-align:center;color:var(--jbs-name)}"
        "#s .hint code{font-family:ui-monospace,Consolas,monospace;"
        "color:var(--jbs-accent)}"
        "@keyframes sp{to{transform:rotate(360deg)}}"
        "</style></head><body>"
        f'<div id="s" data-state="{HOLDING_MARKER}">'
        '<div class="ring"></div>'
        '<div class="name"></div>'
        f"{status}"
        "</div>"
        "<script>(function(){try{var n=(localStorage.getItem("
        "'jarvis.assistantName')||'').trim();if(n){"
        "document.querySelector('#s .name').textContent=n;document.title=n;}}"
        "catch(e){}})();</script>"
        "<script>(function(){"
        "var tries=0;"
        "function look(){"
        "tries++;"
        "fetch('/',{cache:'no-store',headers:{Accept:'text/html'}})"
        f".then(function(r){{return r.ok?r.text():'{HOLDING_MARKER}';}})"
        f".then(function(t){{if(t.indexOf('{HOLDING_ATTRIBUTE}')===-1){{"
        "location.reload();return;}"
        "setTimeout(look, tries<20?700:3000);})"
        "['catch'](function(){setTimeout(look, tries<20?700:3000);});"
        "}"
        "setTimeout(look,700);"
        "})();</script>"
        "</body></html>"
    )