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.

7.6 KB
Raw Blame
/**
 * Notice that the frontend on disk is newer than the one this window is
 * running, and pick it up without anyone restarting anything.
 *
 * The desktop window has no reload key and no dev tools, so for a long time the
 * only way to see a rebuilt frontend was the in-app Restart button — which
 * stops and starts the whole application, voice stack and agent panes included,
 * to replace files the browser would have fetched on its own. `index.html` is
 * served `no-store` and every asset carries a content hash, so a plain reload
 * has always been enough. This module is the missing trigger.
 *
 * It complements ./preloadRecovery rather than replacing it: that one heals a
 * window that has ALREADY crashed on a chunk deleted by a rebuild, which only
 * happens when the user navigates into a view that was not loaded yet. A window
 * sitting on an open view never asks for a missing chunk and stays stale
 * forever. This one asks the server what a fresh window would load.
 *
 * Two rules keep it from being worse than the problem:
 *
 * * a change must survive two consecutive polls, because a build in progress
 *   publishes an `index.html` whose chunks are not all written yet, and
 *   reloading into that is the flicker loop preloadRecovery was written for;
 * * the user must be idle for a moment, because a reload in the middle of a
 *   sentence loses the sentence — and nothing may hold reloads off: a live
 *   voice call is owned by this document, and "no keystroke for two seconds"
 *   is exactly what a user who is talking looks like (see ./reloadHold).
 *
 * And two rules keep it from quietly dying, which is the failure that was
 * actually reported (2026-08-23: the desktop window ran a morning-old build
 * through two rebuilds and showed every section it had not visited yet as a
 * crash):
 *
 * * a window that says it is hidden is still checked, only slower. The
 *   desktop shell's engine (WebView2 under pywebview) was measured reporting
 *   an on-screen, on-top window as `visibilityState === "hidden"` for minutes
 *   at a time; a watch that trusts that verdict never polls again. One request
 *   every half minute is nothing, and a reload of a window nobody is looking at
 *   costs nothing either;
 * * a check that never answers does not hold the watch. The single in-flight
 *   guard protected against stacking, but a request the engine never settles —
 *   a server mid-restart, a socket the machine slept through — turned it into
 *   a permanent lock. An answer that is late past a few ticks is treated as
 *   lost and a fresh check goes out.
 */

/** How often the served bundle is checked, while the window is visible. */
export const POLL_MS = 5_000;

/** Quiet time required before a reload is allowed to interrupt. */
export const IDLE_MS = 2_000;

/** A window that reports itself hidden still checks, every this many ticks. */
export const HIDDEN_EVERY_N_TICKS = 6;

/** A check still unanswered after this many ticks no longer blocks the next. */
export const STALE_INFLIGHT_TICKS = 3;

/**
 * What the running document would have to load to be current.
 *
 * The hashed asset URLs in `index.html` ARE the identity of a build, so a
 * rebuild that changes nothing produces the same fingerprint and nothing
 * happens. Sorted because the order of preload links is not a promise.
 */
export function bundleFingerprint(html: string): string {
  const assets = html.match(/\/assets\/[A-Za-z0-9._-]+/g);
  if (!assets) return "";
  return [...new Set(assets)].sort().join(" ");
}

export interface BundleWatchDeps {
  /** Identity of the loaded document, never of a later server response. */
  baseline?: string;
  /** Fetch the SPA entry document the server would hand a fresh window. */
  fetchIndex: () => Promise<string>;
  /** Reload this window. */
  reload: () => void;
  /** Milliseconds since the last keystroke or pointer press, or null if none. */
  idleFor: () => number | null;
  /** Is something in this window (a live voice call) holding reloads off? */
  held?: () => boolean;
  /** Is this window on screen? A hidden window polls {@link HIDDEN_EVERY_N_TICKS}× slower. */
  visible: () => boolean;
  /** Schedule the repeating check. Returns a handle for {@link stop}. */
  every: (fn: () => void, ms: number) => number;
  /** Cancel a handle from {@link BundleWatchDeps.every}. */
  stop: (handle: number) => void;
}

/**
 * The decision, isolated from every timer and every fetch.
 *
 * `baseline` is what this window is running, `seen` the fingerprint just
 * fetched, `confirmed` the one already seen changed on the previous poll.
 */
export function shouldReload({
  baseline,
  seen,
  confirmed,
  idleMs,
  held = false,
}: {
  baseline: string;
  seen: string;
  confirmed: string | null;
  idleMs: number | null;
  held?: boolean;
}): boolean {
  if (!baseline || !seen || seen === baseline) return false;
  // A build in flight can serve a half-written index; the same fingerprint
  // twice means the build finished and this is what it produced.
  if (confirmed !== seen) return false;
  // A reload would hang up a call this document owns; the next poll after the
  // hold is released picks the build up.
  if (held) return false;
  // No input at all means nothing to interrupt.
  return idleMs === null || idleMs >= IDLE_MS;
}

/**
 * Start watching. Returns a function that stops the watch.
 *
 * Production supplies the loaded document's fingerprint. The first response
 * is only a fallback for callers without a document, never a newer build's
 * claim about what an already open window is running.
 */
export function installBundleWatch(deps: BundleWatchDeps): () => void {
  let baseline = deps.baseline ?? "";
  let stopped = false;
  let reloading = false;
  let confirmed: string | null = null;
  // Ticks the current check has been waiting for its answer; 0 = none open.
  let inflightTicks = 0;
  // Which check is current. An answer from a check that was given up on must
  // not be mistaken for fresh information.
  let generation = 0;
  let hiddenTicks = 0;

  const check = () => {
    if (stopped || reloading) return;
    if (inflightTicks > 0 && inflightTicks < STALE_INFLIGHT_TICKS) {
      // One check at a time — a slow answer is not a reason to stack another.
      inflightTicks += 1;
      return;
    }
    if (!deps.visible()) {
      // Hidden is a hint to go easy, never a reason to stop: the verdict is
      // wrong in at least one engine this app ships in (see the module note).
      hiddenTicks += 1;
      if (hiddenTicks % HIDDEN_EVERY_N_TICKS !== 0) return;
    } else {
      hiddenTicks = 0;
    }
    inflightTicks = 1;
    generation += 1;
    const mine = generation;
    void deps
      .fetchIndex()
      .then((html) => {
        if (stopped || mine !== generation) return;
        const seen = bundleFingerprint(html);
        if (!seen) return;
        if (!baseline) {
          baseline = seen;
          return;
        }
        if (
          shouldReload({
            baseline,
            seen,
            confirmed,
            idleMs: deps.idleFor(),
            held: deps.held?.() ?? false,
          })
        ) {
          reloading = true;
          deps.reload();
          return;
        }
        confirmed = seen === baseline ? null : seen;
      })
      .catch(() => {
        // The server restarting, a dropped socket, a machine asleep: the next
        // poll asks again. A window must never reload because a request failed.
      })
      .finally(() => {
        if (mine === generation) inflightTicks = 0;
      });
  };

  check();
  const handle = deps.every(check, POLL_MS);
  return () => {
    stopped = true;
    generation += 1;
    deps.stop(handle);
  };
}