Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
7.6 KB
Raw Blame
"use client";

import { useEffect, useMemo } from "react";
import { ApiClient } from "../api/client";
import { installFreezeWatchdog } from "../diagnostics/freeze-watchdog";
import { setApiInstance, setSchemaLogger } from "../api";
import { createAuthStore, registerAuthStore } from "../auth";
import { createChatStore, registerChatStore } from "../chat";
import {
  I18nProvider,
  LocaleAdapterProvider,
  UserLocaleSync,
} from "../i18n/react";
import { WSProvider } from "../realtime";
import { QueryProvider } from "../provider";
import { createLogger } from "../logger";
import { defaultStorage } from "./storage";
import { AuthInitializer } from "./auth-initializer";
import {
  createSessionRenewal,
  watchSessionActivity,
  type SessionRenewal,
} from "./session-renewal";
import type { CoreProviderProps, ClientIdentity } from "./types";
import type { StorageAdapter } from "../types/storage";
import { ClientUsageReporter } from "../client-usage";
import {
  configureShortcutPlatform,
  configureShortcutRuntime,
} from "../shortcuts/platform";

// Module-level singletons — created once at first render, never recreated.
// Vite HMR preserves module-level state, so these survive hot reloads.
let initialized = false;
let authStore: ReturnType<typeof createAuthStore>;
let chatStore: ReturnType<typeof createChatStore>;
// Token mode only. Cookie-mode browsers have their session re-issued by the
// server on any authenticated request, so there is nothing for a client-side
// renewer to do there (MUL-7436).
let sessionRenewal: SessionRenewal | null = null;
// Named rather than positional: onLogin / onLogout / onSessionExpired are
// three adjacent `() => void`, and nothing but the argument order would tell
// them apart at the call site.
interface InitCoreOptions {
  apiBaseUrl: string;
  storage: StorageAdapter;
  onLogin?: () => void;
  onLogout?: () => void;
  onSessionExpired?: () => void;
  cookieAuth?: boolean;
  identity?: ClientIdentity;
}

function initCore({
  apiBaseUrl,
  storage,
  onLogin,
  onLogout,
  onSessionExpired,
  cookieAuth,
  identity,
}: InitCoreOptions) {
  if (initialized) return;

  configureShortcutPlatform(
    identity?.os === "macos" ||
      identity?.os === "windows" ||
      identity?.os === "linux" ||
      identity?.os === "unknown"
      ? identity.os
      : null,
  );
  // Authoritative override; before this runs (module-eval store hydration)
  // detectShortcutRuntime() reads the preload globals and already agrees.
  configureShortcutRuntime(
    identity?.platform === "desktop" ? "desktop" : null,
  );

  const api = new ApiClient(apiBaseUrl, {
    logger: createLogger("api"),
    // A 401 mid-session has to end the session, not just drop the token.
    // Dropping it alone left the shell mounted with `user` still set, so no
    // shell ever showed the login page and every following request went out
    // unauthenticated — the user got a wall of "missing authorization"
    // toasts with no way forward (MUL-7028). The store action is idempotent,
    // so a screenful of parallel 401s is still one expiry.
    //
    // `authStore` is assigned a few lines below, synchronously, and this
    // callback can only run from a request — never before boot finishes.
    onUnauthorized: (reason) => {
      authStore.getState().sessionExpired(reason);
    },
    // Token mode only. Desktop runs one ApiClient per window over one shared
    // localStorage, so the credential has to be read through to storage rather
    // than cached per instance — otherwise a session renewed in one window
    // leaves the others sending a token that is on its way out (MUL-7436).
    getToken: cookieAuth
      ? undefined
      : () => storage.getItem("multica_token"),
    identity,
  });
  setApiInstance(api);
  setSchemaLogger(createLogger("api-schema"));

  // In token mode, hydrate token from storage.
  if (!cookieAuth) {
    const token = storage.getItem("multica_token");
    if (token) api.setToken(token);
  }
  // Workspace identity is URL-driven: the [workspaceSlug] layout resolves
  // the slug and calls setCurrentWorkspace(slug, wsId) on mount. The api
  // client reads the slug from that singleton for the X-Workspace-Slug
  // header. No boot-time hydration from storage is required.

  authStore = createAuthStore({
    api,
    storage,
    onLogin,
    onLogout,
    onSessionExpired,
    cookieAuth,
  });
  registerAuthStore(authStore);

  chatStore = createChatStore({ storage });
  registerChatStore(chatStore);

  if (!cookieAuth) {
    sessionRenewal = createSessionRenewal({
      api,
      storage,
      isAuthenticated: () => authStore.getState().status === "authenticated",
      logger: createLogger("auth"),
    });
  }

  initialized = true;
}

export function CoreProvider({
  children,
  apiBaseUrl = "",
  wsUrl = "ws://localhost:8080/ws",
  storage = defaultStorage,
  cookieAuth,
  onLogin,
  onLogout,
  onSessionExpired,
  identity,
  locale,
  resources,
  localeAdapter,
  syncUserLocale = true,
}: CoreProviderProps) {
  // Initialize singletons on first render only. Dependencies are read-once:
  // apiBaseUrl, storage, and callbacks are set at app boot and never change at runtime.
  // eslint-disable-next-line react-hooks/exhaustive-deps
  useMemo(
    () =>
      initCore({
        apiBaseUrl,
        storage,
        onLogin,
        onLogout,
        onSessionExpired,
        cookieAuth,
        identity,
      }),
    [],
  );

  // Client-only freeze watchdog — shared by web and desktop. No-op on the
  // server and idempotent, so mounting it here covers both apps in one place.
  useEffect(() => {
    installFreezeWatchdog();
  }, []);

  // Sliding session renewal, driven by use rather than by a clock. The store
  // subscription covers the launch check: at mount the boot identity probe is
  // still running, so the first attempt that finds a live session is the one
  // that fires — and `maybeRenew` declines cheaply for every store update
  // after that until the server-supplied interval has elapsed.
  useEffect(() => {
    const renewal = sessionRenewal;
    if (!renewal) return;
    const unsubscribe = authStore.subscribe(() => renewal.maybeRenew());
    const stopWatching = watchSessionActivity(renewal);
    renewal.maybeRenew();
    return () => {
      unsubscribe();
      stopWatching();
    };
  }, []);

  // I18nProvider wraps everything else: server and client must use the same
  // (locale, resources) to avoid hydration mismatch. Language switching goes
  // through window.location.reload(), never client-side changeLanguage.
  const tree = (
    <QueryProvider>
      <AuthInitializer
        onLogin={onLogin}
        storage={storage}
        cookieAuth={cookieAuth}
        identity={identity}
      >
        {/* Desktop's reporter owns both activity and runtime state so it must
            be the only writer for that installation. */}
        {identity?.platform !== "desktop" && (
          <ClientUsageReporter storage={storage} identity={identity} />
        )}
        <WSProvider
          wsUrl={wsUrl}
          authStore={authStore}
          storage={storage}
          cookieAuth={cookieAuth}
          identity={identity}
        >
          {children}
        </WSProvider>
      </AuthInitializer>
    </QueryProvider>
  );

  // UserLocaleSync requires a LocaleAdapter to persist; only mount it when
  // the host app provides one (web layout + desktop App both do).
  const withAdapter = localeAdapter ? (
    <LocaleAdapterProvider adapter={localeAdapter}>
      {syncUserLocale && <UserLocaleSync />}
      {tree}
    </LocaleAdapterProvider>
  ) : (
    tree
  );

  return (
    <I18nProvider locale={locale} resources={resources}>
      {withAdapter}
    </I18nProvider>
  );
}