Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

2.0 KB
Raw Blame
import { useState, useEffect } from "react";
import { connectionModeService } from "@editor/services/connectionModeService";
import { endpointAvailabilityService } from "@editor/services/endpointAvailabilityService";
import { tauriBackendService } from "@editor/services/tauriBackendService";
import { useLocalProcessingOnly } from "@editor/hooks/useLocalProcessingOnly";

/**
 * Desktop hook to check if a tool endpoint will use cloud backend
 * @param endpointName - The endpoint name to check (e.g., 'ocr-pdf', 'compress-pdf')
 * @returns true if the tool will use cloud credits, false otherwise
 */
export function useToolCloudStatus(endpointName?: string): boolean {
  const localOnly = useLocalProcessingOnly();
  const [usesCloud, setUsesCloud] = useState(false);

  useEffect(() => {
    const checkCloudRouting = async () => {
      if (localOnly || !endpointName) {
        setUsesCloud(false);
        return;
      }

      try {
        // Don't show cloud badges until backend is healthy
        // This prevents showing incorrect cloud status during startup
        if (!tauriBackendService.isOnline) {
          setUsesCloud(false);
          return;
        }

        // Check if in SaaS mode
        const mode = await connectionModeService.getCurrentMode();
        if (mode !== "saas") {
          setUsesCloud(false);
          return;
        }

        const supportedLocally =
          await endpointAvailabilityService.isEndpointSupportedLocally(
            endpointName,
            tauriBackendService.getBackendUrl(),
          );
        setUsesCloud(!supportedLocally);
      } catch {
        setUsesCloud(false);
      }
    };

    // Initial check
    checkCloudRouting();

    // Subscribe to backend status changes to re-check when backend becomes healthy
    const unsubscribe = tauriBackendService.subscribeToStatus((status) => {
      if (status === "healthy") {
        checkCloudRouting();
      }
    });

    return unsubscribe;
  }, [endpointName, localOnly]);

  return !localOnly && usesCloud;
}