Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

6.3 KB
Raw Blame
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router';
import {
  EIDOVERSE_FRAME_VERSION,
  EIDOVERSE_LABEL_PREFERENCES,
  eidoverseIdentityRenameName,
  eidoverseNavigationTarget,
  isEidoverseFrameMessage,
} from '../lib/eidoverseFrame';
export default function useEidoverseFrame(hostUrl, objects = [], onTravel = null, onIdentityRename = null) {
  const frameRef = useRef(null);
  const travelRef = useRef(onTravel);
  travelRef.current = onTravel;
  const identityRenameRef = useRef(onIdentityRename);
  identityRenameRef.current = onIdentityRename;
  const objectsRef = useRef(objects);
  objectsRef.current = objects;
  const sessionRef = useRef(null);
  const departureRef = useRef(null);
  const [loaded, setLoaded] = useState({ id: 0, url: null });
  const [connection, setConnection] = useState({ status: 'checking', capabilities: {} });
  const [labelVisibility, setLabelVisibility] = useState('off');
  const preferenceRef = useRef(labelVisibility);
  const navigate = useNavigate();

  const onFrameLoad = useCallback(() => {
    sessionRef.current = null;
    if (frameRef.current?.getAttribute('src') === 'about:blank') return;
    setConnection({ status: 'checking', capabilities: {} });
    setLoaded((current) => ({ id: current.id + 1, url: hostUrl }));
  }, [hostUrl]);

  useEffect(() => {
    if (!hostUrl || loaded.url !== hostUrl || !frameRef.current?.contentWindow) return undefined;
    const source = frameRef.current.contentWindow;
    const origin = new URL(hostUrl).origin;
    const nonce = Array.from(crypto.getRandomValues(new Uint8Array(16)),
      (byte) => byte.toString(16).padStart(2, '0')).join('');
    const session = { source, origin, nonce, capabilities: {} };
    sessionRef.current = session;
    const timer = setTimeout(() => {
      setConnection({ status: 'unsupported', capabilities: {} });
    }, 5000);
    const receive = (event) => {
      if (sessionRef.current !== session || frameRef.current?.contentWindow !== source
        || !isEidoverseFrameMessage(event, session)) return;
      const data = event.data;
      if (data.type === 'eidoverse:ready') {
        clearTimeout(timer);
        session.capabilities = Object.fromEntries(['objectLabels', 'portosNavigation', 'labelPreferences', 'worldDeparture', 'objectInteraction', 'identityRenameRequest']
          .map((key) => [key, data.capabilities?.[key] === 1]));
        setConnection({ status: 'ready', capabilities: session.capabilities });
        if (session.capabilities.labelPreferences) source.postMessage({
          type: 'portos:label-preference', version: EIDOVERSE_FRAME_VERSION, nonce,
          labelVisibility: preferenceRef.current,
        }, origin);
      } else if (data.type === 'eidoverse:departed' && session.capabilities.worldDeparture) {
        departureRef.current?.(data.ok === true);
      } else if (data.type === 'eidoverse:navigate' && session.capabilities.portosNavigation) {
        const target = eidoverseNavigationTarget(data, objectsRef.current);
        if (!target) return;
        const object = objectsRef.current.find((entry) => entry.id === data.entityId);
        if (object?.travelPeerId && travelRef.current) travelRef.current(object.travelPeerId);
        else navigate(target);
      } else if (data.type === 'eidoverse:identity-rename' && session.capabilities.identityRenameRequest) {
        const name = eidoverseIdentityRenameName(data);
        if (name !== null) identityRenameRef.current?.(name);
      }
    };
    window.addEventListener('message', receive);
    source.postMessage({
      type: 'portos:connect', version: EIDOVERSE_FRAME_VERSION, nonce,
      capabilities: {
        portosNavigation: 1,
        labelPreferences: 1,
        ...(identityRenameRef.current ? { identityRenameRequest: 1 } : {}),
      },
      labelVisibility: preferenceRef.current,
    }, origin);
    return () => {
      clearTimeout(timer);
      window.removeEventListener('message', receive);
      departureRef.current?.(false);
      if (sessionRef.current === session) sessionRef.current = null;
    };
  }, [hostUrl, loaded, navigate]);

  const leaveWorld = useCallback(async () => {
    const session = sessionRef.current;
    const element = frameRef.current;
    if (!element) return;
    if (session?.capabilities.worldDeparture) {
      await new Promise((resolve, reject) => {
        const timer = setTimeout(() => finish(false), 5000);
        const finish = (ok) => {
          clearTimeout(timer);
          departureRef.current = null;
          if (ok) resolve();
          else reject(new Error('Could not leave the current world. Reload it before trying again.'));
        };
        departureRef.current = finish;
        session.source.postMessage({ type: 'portos:depart', version: EIDOVERSE_FRAME_VERSION,
          nonce: session.nonce }, session.origin);
      });
    }
    // Retire even legacy renderers before navigating. A page retained in the
    // browser's back/forward cache must not keep its old world alive.
    await new Promise((resolve, reject) => {
      const onLoad = () => { clearTimeout(timer); resolve(); };
      const timer = setTimeout(() => {
        element.removeEventListener('load', onLoad);
        reject(new Error('The previous world is still closing. Reload before trying again.'));
      }, 3000);
      element.addEventListener('load', onLoad, { once: true });
      element.src = 'about:blank';
    });
  }, []);

  useEffect(() => {
    const restore = (event) => {
      if (event.persisted && hostUrl && frameRef.current?.getAttribute('src') === 'about:blank') {
        frameRef.current.src = hostUrl;
      }
    };
    window.addEventListener('pageshow', restore);
    return () => window.removeEventListener('pageshow', restore);
  }, [hostUrl]);

  const changeLabelVisibility = useCallback((value) => {
    if (!EIDOVERSE_LABEL_PREFERENCES.includes(value)) return;
    preferenceRef.current = value;
    setLabelVisibility(value);
    const session = sessionRef.current;
    if (session?.capabilities.labelPreferences) {
      session.source.postMessage({
        type: 'portos:label-preference', version: EIDOVERSE_FRAME_VERSION,
        nonce: session.nonce, labelVisibility: value,
      }, session.origin);
    }
  }, []);

  return { frameRef, onFrameLoad, connection, labelVisibility, changeLabelVisibility, leaveWorld };
}