Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

1.3 KB
Raw Blame
import { hasTag } from "~/lib/taggedUnion";
import { useAtomValue } from "@effect/atom-react";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback } from "react";

import { appAtomRegistry } from "../../rpc/atomRegistry";
import { fetchSessionState } from "./auth";

const primarySessionStateAtom = Atom.make(Effect.promise(fetchSessionState)).pipe(
  Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),
  Atom.setIdleTTL(5 * 60_000),
  Atom.withLabel("primary-environment:session"),
);

export function refreshPrimarySessionState(): void {
  appAtomRegistry.refresh(primarySessionStateAtom);
}

export function usePrimarySessionState() {
  const result = useAtomValue(primarySessionStateAtom);

  const refresh = useCallback(() => {
    refreshPrimarySessionState();
  }, []);

  let error: string | null = null;

  if (hasTag(result, "Failure")) {
    const cause = Cause.squash(result.cause);
    error = cause instanceof Error ? cause.message : "Could not read environment session.";
  }

  return {
    data: Option.getOrNull(AsyncResult.value(result)),
    error,
    isPending: result.waiting,
    refresh,
  };
}