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

8.5 KB
Raw Blame
import toast from '../components/ui/Toast';
import { trackRequest } from './actionFeedback.js';

export const API_BASE = '/api'; // exported for sub-modules that use fetch() directly

// Stable ID for the PortOS baseline app (mirrors server PORTOS_APP_ID). Defined
// in the dependency-free lib/appIdentity.js and re-exported here so callers that
// only need the id don't drag this module's React import along with it.
export { PORTOS_APP_ID } from '../lib/appIdentity.js';

// Bounce to /login when the auth gate (server: services/authGate.js) rejects a
// request with 401 + AUTH_REQUIRED. Shared by request() AND the streaming-fetch
// helpers (apiLocalLlm.streamLocalLlmTest, etc.) that bypass request() to read a
// stream body but must still honor session expiry — otherwise a session that
// lapses mid-feature just errors in place instead of re-authenticating.
export function maybeRedirectToLogin(response, error) {
  if (response.status === 401 && error?.code === 'AUTH_REQUIRED' && typeof window !== 'undefined') {
    if (!window.location.pathname.startsWith('/login')) {
      const next = encodeURIComponent(window.location.pathname + window.location.search);
      window.location.replace(`/login?next=${next}`);
    }
  }
}

// Shared `!response.ok` envelope: parse the server's JSON error body, bounce to
// /login on session expiry, and throw an Error carrying `.code`/`.status`/
// `.context` from the response. Toasting is NOT done here — request() does its
// own (with `silent` support); the streaming/blob callers that bypass request()
// to read a raw Response deliberately surface their own errors instead.
export async function throwApiError(response) {
  // A valid JSON body that isn't an object (e.g. a bare `null`) parses
  // successfully but has no `.error`/`.code`/`.context` to read — fall back
  // to the same HTTP-status shape used when the body isn't JSON at all.
  const parsedError = await response.json().catch(() => null);
  const error =
    parsedError && typeof parsedError === 'object' ? parsedError : { error: `HTTP ${response.status}` };
  // Auth gate (server: services/authGate.js) returns 401 with code AUTH_REQUIRED
  // for any /api request without a valid session. Bounce to /login so the
  // user can re-authenticate; skip if we're already there.
  maybeRedirectToLogin(response, error);
  const err = new Error(error.error || `HTTP ${response.status}`);
  err.code = error?.code;
  err.status = response.status;
  // Forward structured context the server attached to the error (e.g.
  // ERR_PARTIAL_COMMIT_ISSUES carries `{ universeId, seriesId,
  // arcAlreadyPersisted, skipArcOnRetry }` so the Importer client can
  // shape its retry without re-overwriting persisted state).
  if (error?.context) err.context = error.context;
  throw err;
}

// A request started from a tap marks the tapped button busy until it settles
// (services/actionFeedback.js), so every action responds at once.
export function request(endpoint, options = {}) {
  return trackRequest(performRequest(endpoint, options));
}

// Shell bootstrap reads (settings, voice config, capabilities) are fetched by
// several concurrently mounted components. Share one in-flight request per key;
// the entry clears on settle so later calls (e.g. after a socket push) refetch.
// Each caller gets its own clone so one consumer's mutation can't leak into another.
const inflightReads = new Map();
// Options that change error handling are part of the key, so a silent caller never
// joins (or starts) a flight whose failure toasts, and vice versa.
export function singleFlightRead(endpoint, start, options = {}) {
  // A caller owns its signal's lifetime; aborting it must not cancel another
  // consumer's read or make a remount join the request its cleanup just aborted.
  if (options.signal) return start();
  const key = `${endpoint}|silent:${!!options.silent}|hco:${!!options.hostControlOptional}`;
  let pending = inflightReads.get(key);
  if (!pending) {
    pending = start().finally(() => inflightReads.delete(key));
    inflightReads.set(key, pending);
  }
  return pending.then((value) => (value && typeof value === 'object' ? structuredClone(value) : value));
}

async function performRequest(endpoint, options = {}) {
  // `hostControlOptional` marks a background read whose caller renders its own
  // "needs operator authority" state, so a host-control refusal does not toast.
  const { silent, responseType, hostControlOptional, ...fetchOptions } = options;
  const url = `${API_BASE}${endpoint}`;
  // Skip the JSON content-type header for FormData bodies — the browser must
  // set `multipart/form-data; boundary=…` itself, and any pre-supplied value
  // (including ours) suppresses the auto-boundary and breaks the upload.
  const isFormData = typeof FormData !== 'undefined' && fetchOptions.body instanceof FormData;
  const baseHeaders = isFormData ? {} : { 'Content-Type': 'application/json' };
  const config = {
    ...fetchOptions,
    headers: {
      ...baseHeaders,
      ...fetchOptions.headers
    }
  };

  const response = await fetch(url, config).catch(() => null);
  if (!response) {
    const msg = 'Server unreachable — check your connection and try again';
    if (!silent) toast.error(msg);
    const err = new Error(msg);
    err.code = 'SERVER_UNREACHABLE';
    throw err;
  }

  if (!response.ok) {
    try {
      await throwApiError(response);
    } catch (err) {
      // A host-control refusal (server: lib/hostControlRoutes.js) surfaces even
      // from a silent caller: the operator pressed a button that ran nothing,
      // and only this message says why. A `hostControlOptional` read was not a
      // button press and shows the refusal itself.
      if (err.code === 'HOST_CONTROL_FORBIDDEN') {
        if (!hostControlOptional) toast.error(err.message);
      } else if (!silent) {
        // Platform unavailability is a warning, not an error
        if (err.code === 'PLATFORM_UNAVAILABLE') {
          toast(err.message, { icon: '⚠️' });
        } else if (err.code !== 'AUTH_REQUIRED') {
          toast.error(err.message);
        }
      }
      throw err;
    }
  }

  // Handle 204 No Content
  if (response.status === 204) {
    return null;
  }

  if (responseType === 'arraybuffer') {
    return response.arrayBuffer();
  }
  // `responseType: 'text'` returns the raw body so callers (e.g. catalog
  // export, which may be JSON, markdown, or YAML) get a string they can
  // wrap in a Blob and trigger a download from. JSON.parse on the caller
  // side when needed.
  if (responseType === 'text') {
    return response.text();
  }
  if (responseType === 'blob') {
    return response.blob();
  }

  return response.json();
}

// Search
// Query string from a filter object, dropping absent/empty values so a cleared
// filter never reaches the server as `?q=`. Returns '' when nothing is set.
export const queryString = (params = {}) => {
  const qs = new URLSearchParams();
  for (const [key, value] of Object.entries(params)) {
    if (value === undefined || value === null || value === '') continue;
    qs.set(key, String(value));
  }
  const encoded = qs.toString();
  return encoded ? `?${encoded}` : '';
};

export const search = (q) => request(`/search?q=${encodeURIComponent(q)}`);

// Default export for simplified imports
export default {
  get: (endpoint, options) => request(endpoint, { method: 'GET', ...options }),
  post: (endpoint, body, options) => request(endpoint, {
    method: 'POST',
    body: JSON.stringify(body),
    ...options
  }),
  put: (endpoint, body, options) => request(endpoint, {
    method: 'PUT',
    body: JSON.stringify(body),
    ...options
  }),
  delete: (endpoint, options) => request(endpoint, { method: 'DELETE', ...options })
};

// File/Blob uploads stream as multipart; retain base64 JSON for older callers.
export function uploadBody(data, filename) {
  if (typeof Blob !== 'undefined' && data instanceof Blob) {
    const body = new FormData();
    body.append('file', data, filename || data.name || 'upload');
    return body;
  }
  return JSON.stringify({ data, ...(filename ? { filename } : {}) });
}

export function isServerUnreachable(err) {
  if (typeof navigator !== 'undefined' && navigator.onLine === false) return true;
  if (!err) return false;
  if (err.code === 'SERVER_UNREACHABLE' || err.code === 'ECONNREFUSED' || err.code === 'ENOTFOUND') return true;
  if (err.status === 502 || err.status === 503 || err.status === 504) return true;
  const msg = typeof err === 'string' ? err : err.message || '';
  return /server unreachable|failed to fetch|networkerror|load failed|econnrefused|net::err/i.test(msg);
}