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.5 KB
Raw Blame
import React from "react";
import ReactDOM from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./App";
import { ThemeProvider } from "./hooks/useTheme";
import { ViewErrorBoundary } from "./components/ViewErrorBoundary";
import { AuthGate } from "./components/AuthGate";
import { installPreloadRecovery } from "./lib/preloadRecovery";
import { POLL_MS, bundleFingerprint, installBundleWatch } from "./lib/bundleWatch";
import { reloadHeld, setReloadHold } from "./lib/reloadHold";
import { useEventStore } from "./store/events";
import { browserSafeReloadDeps, reloadWhenServable } from "./lib/safeReload";
import { loadUiLocale, useI18nStore } from "./i18n";
import "./index.css";

// When the frontend is rebuilt while the window is open, the old main bundle
// still references lazy chunks by their previous content hash; those URLs now
// 404 and the dynamic import() rejects, hard-crashing whichever view tried to
// load (e.g. the Wiki page's ObsidianButton). Vite fires `vite:preloadError`
// for exactly this case — reload once to pick up the fresh bundle, and only
// once per incident, because a rebuild in progress hands the reload the same
// missing chunk and the window ends up cycling. See lib/preloadRecovery.
installPreloadRecovery({
  storage: sessionStorage,
  // Never a bare location.reload(). The chunk went missing because a rebuild
  // is running, which is precisely when the entry document is also briefly
  // unservable — reloading into that leaves the window with no JavaScript and
  // nothing left to recover with. See lib/safeReload. It also waits out a live
  // call or a streaming reply, like every automatic reload (lib/reloadHold).
  reload: () => reloadWhenServable(browserSafeReloadDeps({ held: reloadHeld })),
  defer: (fn, ms) => {
    window.setTimeout(fn, ms);
  },
});

// The other half of the same problem: a window sitting on an open view never
// asks for a deleted chunk, so it never notices a rebuild at all and shows an
// old UI until someone restarts the whole application. Ask the server what a
// fresh window would load, and reload when the answer has changed — a rebuild
// is then something the user watches happen instead of something they operate.
// See lib/bundleWatch for the two guards that keep this quiet.
//
// A typed reply streams into this document the way a call does, so it holds
// reloads too. `chatThinking` always ends: the reply, an error, or the turn's
// timeout clears it (lib/chat).
useEventStore.subscribe((state) =>
  setReloadHold("typed-chat-reply", state.chatThinking),
);
{
  let lastInput: number | null = null;
  const noteInput = () => {
    lastInput = Date.now();
  };
  for (const kind of ["keydown", "pointerdown"] as const) {
    window.addEventListener(kind, noteInput, { capture: true, passive: true });
  }
  installBundleWatch({
    // The server may already have changed before our first poll completes.
    baseline: bundleFingerprint(document.head.innerHTML),
    fetchIndex: () =>
      fetch("/", {
        cache: "no-store",
        headers: { Accept: "text/html" },
        // A request the engine never settles must not outlive the next tick;
        // the watch treats a late answer as lost, this makes sure it IS lost.
        signal:
          typeof AbortSignal.timeout === "function"
            ? AbortSignal.timeout(POLL_MS - 500)
            : undefined,
      }).then((response) => (response.ok ? response.text() : "")),
    reload: () => reloadWhenServable(browserSafeReloadDeps({ held: reloadHeld })),
    idleFor: () => (lastInput === null ? null : Date.now() - lastInput),
    held: reloadHeld,
    visible: () => document.visibilityState !== "hidden",
    every: (fn, ms) => window.setInterval(fn, ms),
    stop: (handle) => window.clearInterval(handle),
  });
}

// Say it out loud when the main thread stops answering the user. In a WebView
// there is no console to notice it in, so a multi-second block shows up only as
// "Not responding" in the window title and as keystrokes arriving late in a
// terminal pane — with nothing anywhere to say what ran. The backend reports
// its own stalls the same way (dodaios/core/loop_watchdog.py); this covers the
// half that draws the window. Silent unless something actually blocks.
void import("./lib/uiStallWatch").then(({ watchUiStalls }) => {
  watchUiStalls((payload) => {
    void fetch("/api/diagnostics/ui-stall", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
      // The thread that just unblocked may be on its way to blocking again, and
      // this report must survive that rather than be cancelled with the page.
      keepalive: true,
    }).catch(() => undefined);
  });
});

// Tell the backend which timezone this person lives in. A voice request such
// as "a briefing every day at 8" has no client of its own, so the routine it
// creates is scheduled on this zone instead of the server clock.
try {
  const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  if (timezone) {
    void fetch("/api/tasks/client-timezone", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ timezone }),
    }).catch(() => undefined);
  }
} catch {
  // A runtime without Intl zone data simply leaves voice routines to ask.
}

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5_000,
      // Sections are unmounted on every switch, so their queries go inactive
      // the moment you leave one. At the five-minute default the cache was
      // gone before most people came back, and the section repainted from
      // nothing — a blank shell for a whole round trip. Half an hour keeps
      // the last answer on screen while the refetch runs behind it.
      gcTime: 30 * 60_000,
      // Returning to the window used to refire every mounted query at once.
      // The sections already poll or refetch on their own filters, so the
      // burst bought nothing and arrived exactly when the app felt slowest.
      refetchOnWindowFocus: false,
      retry: 1,
    },
  },
});

// The appshot editor's own desktop window (a click on the corner card) loads
// just the editor, not the app around it. Lazy, so the app never carries it.
const AppshotEditorWindow = React.lazy(() =>
  import("./views/AppshotEditorWindow").then((m) => ({ default: m.AppshotEditorWindow })),
);
const isEditorWindow = new URLSearchParams(window.location.search).get("view") === "appshot-editor";

function renderApp(): void {
  ReactDOM.createRoot(document.getElementById("root")!).render(
    <React.StrictMode>
      <QueryClientProvider client={queryClient}>
        <ThemeProvider>
          <ViewErrorBoundary
            viewName="App"
            resetKey="root"
            onRecover={() => window.location.reload()}
          >
            <AuthGate quiet={isEditorWindow}>
              {isEditorWindow ? (
                <React.Suspense
                  fallback={
                    <div className="fixed inset-0 bg-popover" data-testid="appshot-editor-window" />
                  }
                >
                  <AppshotEditorWindow />
                </React.Suspense>
              ) : (
                <App />
              )}
            </AuthGate>
          </ViewErrorBoundary>
        </ThemeProvider>
      </QueryClientProvider>
    </React.StrictMode>,
  );
}

void loadUiLocale(useI18nStore.getState().ui)
  .catch((error: unknown) => console.warn("Stored interface language could not be loaded", error))
  .finally(renderApp);