#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
feat(desktop): move endpoint availability onto TanStack Query (#7784)
ConnorYoh95053b8f3a9c
diff --git a/frontend/editor/src/desktop/api/endpointAvailability.ts b/frontend/editor/src/desktop/api/endpointAvailability.tsnew file mode 100644index 0000000000..62ba2401f6--- /dev/null+++ b/frontend/editor/src/desktop/api/endpointAvailability.ts@@ -0,0 +1,174 @@+import { isAxiosError } from "axios";+import apiClient from "@app/services/apiClient";+import { tauriBackendService } from "@app/services/tauriBackendService";+import { selfHostedServerMonitor } from "@app/services/selfHostedServerMonitor";+import { endpointAvailabilityService } from "@app/services/endpointAvailabilityService";+import { connectionModeService } from "@app/services/connectionModeService";+import {+ createBackendNotReadyError,+ isBackendNotReadyError,+} from "@app/constants/backendErrors";+import type { EndpointAvailabilityDetails } from "@app/types/endpointAvailability";+import type { AppConfig } from "@app/contexts/AppConfigContext";++export type EndpointAvailabilityMap = Record<+ string,+ EndpointAvailabilityDetails+>;++/** Self-hosted server down, but a local bundled backend is reachable. */+export function isSelfHostedOffline(): boolean {+ return (+ selfHostedServerMonitor.getSnapshot().status === "offline" &&+ !!tauriBackendService.getBackendUrl()+ );+}++/**+ * Gate every remote check on the backend reporting its dependencies ready.+ * Not-ready surfaces as a retryable error so the query retries rather than+ * caching a premature answer. {@link isBackendNotReadyError} also matches the+ * backend-starting error the fetch itself can throw, so both share one retry.+ */+async function ensureDependenciesReady(): Promise<void> {+ try {+ const response = await apiClient.get<AppConfig>(+ "/api/v1/config/app-config",+ { suppressErrorToast: true },+ );+ if (response.data?.dependenciesReady) return;+ } catch {+ // Unreachable app-config is itself "not ready yet".+ }+ throw createBackendNotReadyError();+}++/** New servers return the whole map for a bare call; old ones need the param. */+async function fetchAvailabilityMap(+ endpoints: string[],+): Promise<EndpointAvailabilityMap> {+ try {+ const response = await apiClient.get<EndpointAvailabilityMap>(+ "/api/v1/config/endpoints-availability",+ { suppressErrorToast: true },+ );+ return response.data;+ } catch (error) {+ if (isAxiosError(error) && error.response?.status === 400) {+ const param = encodeURIComponent(endpoints.join(","));+ const response = await apiClient.get<EndpointAvailabilityMap>(+ `/api/v1/config/endpoints-availability?endpoints=${param}`,+ { suppressErrorToast: true },+ );+ return response.data;+ }+ throw error;+ }+}++function normalise(map: EndpointAvailabilityMap): EndpointAvailabilityMap {+ const out: EndpointAvailabilityMap = {};+ for (const [name, detail] of Object.entries(map)) {+ out[name] = {+ enabled: detail?.enabled ?? false,+ reason: detail?.reason ?? null,+ };+ }+ return out;+}++/** SaaS routing covers a locally-disabled endpoint, so mark it available. */+function applySaasOptimism(+ map: EndpointAvailabilityMap,+): EndpointAvailabilityMap {+ const out: EndpointAvailabilityMap = { ...map };+ for (const [name, detail] of Object.entries(out)) {+ if (!detail.enabled) out[name] = { enabled: true, reason: null };+ }+ return out;+}++/** Self-hosted offline: ask the local backend about each endpoint directly. */+async function resolveOffline(+ endpoints: string[],+): Promise<EndpointAvailabilityMap> {+ const localUrl = tauriBackendService.getBackendUrl();+ const results = await Promise.all(+ [...new Set(endpoints)].map(async (endpoint) => {+ try {+ const supported =+ await endpointAvailabilityService.isEndpointSupportedLocally(+ endpoint,+ localUrl,+ );+ return [endpoint, supported] as const;+ } catch {+ return [endpoint, false] as const;+ }+ }),+ );+ const map: EndpointAvailabilityMap = {};+ for (const [endpoint, supported] of results) {+ map[endpoint] = {+ enabled: supported,+ reason: supported ? null : "NOT_SUPPORTED_LOCALLY",+ };+ }+ return map;+}++/**+ * The whole availability map for the current environment. Fail-closed on a+ * fetch error outside SaaS mode (each requested endpoint disabled), matching+ * desktop's stance that an unknown local capability is unavailable — the+ * opposite of the web fail-open, and the reason this is a desktop shadow.+ */+export async function resolveEndpointsAvailability(+ endpoints: string[],+): Promise<EndpointAvailabilityMap> {+ if (isSelfHostedOffline()) {+ return resolveOffline(endpoints);+ }++ await ensureDependenciesReady();+ const saas = (await connectionModeService.getCurrentMode()) === "saas";++ try {+ const map = normalise(await fetchAvailabilityMap(endpoints));+ return saas ? applySaasOptimism(map) : map;+ } catch (error) {+ if (isBackendNotReadyError(error)) throw error;+ const fallback: EndpointAvailabilityMap = {};+ for (const endpoint of endpoints) {+ fallback[endpoint] = saas+ ? { enabled: true, reason: null }+ : { enabled: false, reason: "UNKNOWN" };+ }+ return fallback;+ }+}++/** Whether one endpoint is enabled, with the same SaaS optimism. */+export async function resolveEndpointEnabled(+ endpoint: string,+): Promise<boolean> {+ if (isSelfHostedOffline()) {+ // ConvertSettings already filters unsupported endpoints from the dropdown,+ // so a selected endpoint is supported locally by the time it reaches here.+ return true;+ }++ await ensureDependenciesReady();+ const saas = (await connectionModeService.getCurrentMode()) === "saas";++ try {+ const response = await apiClient.get<boolean>(+ `/api/v1/config/endpoint-enabled?endpoint=${encodeURIComponent(endpoint)}`,+ { suppressErrorToast: true },+ );+ return response.data || saas;+ } catch (error) {+ if (isBackendNotReadyError(error)) throw error;+ return saas;+ }+}diff --git a/frontend/editor/src/desktop/hooks/useEndpointConfig.test.tsx b/frontend/editor/src/desktop/hooks/useEndpointConfig.test.tsxnew file mode 100644index 0000000000..25935acd49--- /dev/null+++ b/frontend/editor/src/desktop/hooks/useEndpointConfig.test.tsx@@ -0,0 +1,419 @@+import {+ describe,+ it,+ expect,+ vi,+ beforeEach,+ afterEach,+ type Mock,+} from "vitest";+import { renderHook, waitFor, act } from "@testing-library/react";+import { TestQueryProvider } from "@app/tests/utils/TestQueryProvider";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";+import {+ useEndpointEnabled,+ useMultipleEndpointsEnabled,+} from "@app/hooks/useEndpointConfig";+import apiClient from "@app/services/apiClient";++/**+ * Characterisation tests for the desktop endpoint-availability hooks. They+ * assert observable behaviour through the shared apiClient + services boundary,+ * so the same contract holds before and after the TanStack Query conversion:+ * the optimistic-enabled default, the loading hold while the backend is not+ * ready, SaaS-mode optimism, the fail-closed-locally fallback, the legacy 400+ * retry, and the self-hosted-offline local check.+ */++// Stable t: the real useTranslation returns a stable reference, and the hook+// deps its fetch callbacks on it — a fresh t each render would loop forever.+const t = (_k: string, fallback?: string) => fallback;+const translation = { t };+vi.mock("react-i18next", () => ({+ useTranslation: () => translation,+ initReactI18next: { type: "3rdParty", init: () => {} },+}));+vi.mock("@app/i18n", () => ({+ default: { t: (_k: string, fallback?: string) => fallback ?? _k },+}));++// --- apiClient: one get() that dispatches on URL ---+vi.mock("@app/services/apiClient", () => ({+ default: { get: vi.fn() },+}));+// Cast to a plain mock: the real get() is the tauri-http signature, but the+// tests only need { data } back.+const mockGet = apiClient.get as unknown as Mock;++// --- connection mode ---+let mode: "saas" | "selfhosted" | "local" = "saas";+vi.mock("@app/services/connectionModeService", () => ({+ connectionModeService: {+ getCurrentMode: () => Promise.resolve(mode),+ getCurrentConfig: () =>+ Promise.resolve({+ mode,+ server_config: null,+ lock_connection_mode: false,+ }),+ },+}));++// --- tauri backend: a mutable status + change listeners (no replay on subscribe) ---+let backendStatus: "stopped" | "starting" | "healthy" | "unhealthy" = "healthy";+let backendUrl: string | null = "http://127.0.0.1:8080";+const backendListeners = new Set<(s: string) => void>();+vi.mock("@app/services/tauriBackendService", () => ({+ tauriBackendService: {+ get isOnline() {+ return backendStatus === "healthy";+ },+ getBackendUrl: () => backendUrl,+ subscribeToStatus: (listener: (s: string) => void) => {+ backendListeners.add(listener);+ return () => backendListeners.delete(listener);+ },+ },+}));+function setBackendStatus(next: typeof backendStatus) {+ backendStatus = next;+ act(() => backendListeners.forEach((l) => l(next)));+}++// --- self-hosted monitor: replays state on subscribe, matching the real one ---+let selfHostedStatus: "idle" | "checking" | "online" | "offline" = "online";+const selfHostedListeners = new Set<(s: { status: string }) => void>();+vi.mock("@app/services/selfHostedServerMonitor", () => ({+ selfHostedServerMonitor: {+ getSnapshot: () => ({+ status: selfHostedStatus,+ isOnline: selfHostedStatus === "online",+ serverUrl: null,+ }),+ subscribe: (listener: (s: { status: string }) => void) => {+ selfHostedListeners.add(listener);+ listener({ status: selfHostedStatus });+ return () => selfHostedListeners.delete(listener);+ },+ },+}));+function setSelfHostedStatus(next: typeof selfHostedStatus) {+ selfHostedStatus = next;+ act(() =>+ selfHostedListeners.forEach((l) => l({ status: selfHostedStatus })),+ );+}++// --- local-support probe used only on the self-hosted-offline path ---+const mockLocalSupport = vi.fn();+vi.mock("@app/services/endpointAvailabilityService", () => ({+ endpointAvailabilityService: {+ isEndpointSupportedLocally: (endpoint: string, url: string | null) =>+ mockLocalSupport(endpoint, url),+ },+}));++const NONE: string[] = [];+const NARROW = ["merge"];+const WIDE = ["merge", "ocr", "compress"];++function appConfig(dependenciesReady: boolean) {+ return { data: { dependenciesReady } };+}+function availability(map: Record<string, { enabled: boolean }>) {+ return { data: map };+}++beforeEach(() => {+ vi.clearAllMocks();+ mode = "saas";+ backendStatus = "healthy";+ backendUrl = "http://127.0.0.1:8080";+ selfHostedStatus = "online";+ backendListeners.clear();+ selfHostedListeners.clear();+});++afterEach(() => {+ vi.useRealTimers();+});++describe("desktop useMultipleEndpointsEnabled", () => {+ it("projects a fetched availability map once dependencies are ready", async () => {+ mode = "local";+ mockGet.mockImplementation((url: string) => {+ if (url.includes("app-config")) return Promise.resolve(appConfig(true));+ return Promise.resolve(+ availability({ merge: { enabled: true }, ocr: { enabled: false } }),+ );+ });++ const { result } = renderHook(+ () => useMultipleEndpointsEnabled(["merge", "ocr"]),+ { wrapper: TestQueryProvider },+ );++ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.endpointStatus).toEqual({ merge: true, ocr: false });+ // Once, not twice: the readiness effect must not invalidate on mount.+ const availabilityCalls = mockGet.mock.calls.filter((c) =>+ String(c[0]).includes("endpoints-availability"),+ );+ expect(availabilityCalls).toHaveLength(1);+ });++ it("marks locally-disabled endpoints available in SaaS mode", async () => {+ mode = "saas";+ mockGet.mockImplementation((url: string) => {+ if (url.includes("app-config")) return Promise.resolve(appConfig(true));+ return Promise.resolve(availability({ ocr: { enabled: false } }));+ });++ const { result } = renderHook(() => useMultipleEndpointsEnabled(["ocr"]), {+ wrapper: TestQueryProvider,+ });++ await waitFor(() => expect(result.current.loading).toBe(false));+ // SaaS routing covers it even though the local backend disabled it.+ expect(result.current.endpointStatus.ocr).toBe(true);+ });++ it("fails closed for un-fetchable endpoints outside SaaS mode", async () => {+ mode = "local";+ mockGet.mockImplementation((url: string) => {+ if (url.includes("app-config")) return Promise.resolve(appConfig(true));+ return Promise.reject(new Error("network"));+ });++ const { result } = renderHook(+ () => useMultipleEndpointsEnabled(["merge"]),+ {+ wrapper: TestQueryProvider,+ },+ );++ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.endpointStatus.merge).toBe(false);+ });++ it("retries the legacy query-param form when the server rejects the bare call", async () => {+ mode = "local";+ let sawLegacy = false;+ mockGet.mockImplementation((url: string) => {+ if (url.includes("app-config")) return Promise.resolve(appConfig(true));+ if (url.includes("endpoints=")) {+ sawLegacy = true;+ return Promise.resolve(availability({ merge: { enabled: true } }));+ }+ return Promise.reject({+ isAxiosError: true,+ response: { status: 400 },+ });+ });++ const { result } = renderHook(+ () => useMultipleEndpointsEnabled(["merge"]),+ {+ wrapper: TestQueryProvider,+ },+ );++ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(sawLegacy).toBe(true);+ expect(result.current.endpointStatus.merge).toBe(true);+ });++ it("checks the local backend directly when the self-hosted server is offline", async () => {+ mode = "selfhosted";+ selfHostedStatus = "offline";+ mockLocalSupport.mockImplementation((endpoint: string) =>+ Promise.resolve(endpoint === "merge"),+ );++ const { result } = renderHook(+ () => useMultipleEndpointsEnabled(["merge", "ocr"]),+ { wrapper: TestQueryProvider },+ );++ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.endpointStatus).toEqual({ merge: true, ocr: false });+ // The remote availability endpoint is never called on this path.+ expect(mockGet).not.toHaveBeenCalledWith(+ expect.stringContaining("endpoints-availability"),+ expect.anything(),+ );+ });++ it("holds loading while the backend is not online, without fetching", async () => {+ backendStatus = "starting";+ selfHostedStatus = "online"; // not the offline branch+ mockGet.mockImplementation((url: string) => {+ if (url.includes("app-config")) return Promise.resolve(appConfig(true));+ return Promise.resolve(availability({ merge: { enabled: true } }));+ });++ const { result } = renderHook(+ () => useMultipleEndpointsEnabled(["merge"]),+ {+ wrapper: TestQueryProvider,+ },+ );++ // useQuickNavToolReasons gates a memo on this: it must stay true (not flip+ // to an empty answer) until a real result lands.+ await new Promise((r) => setTimeout(r, 20));+ expect(result.current.loading).toBe(true);+ expect(mockGet).not.toHaveBeenCalledWith(+ expect.stringContaining("endpoints-availability"),+ expect.anything(),+ );+ });++ it("fetches once the backend reports healthy", async () => {+ backendStatus = "starting";+ mockGet.mockImplementation((url: string) => {+ if (url.includes("app-config")) return Promise.resolve(appConfig(true));+ return Promise.resolve(availability({ merge: { enabled: true } }));+ });++ const { result } = renderHook(+ () => useMultipleEndpointsEnabled(["merge"]),+ {+ wrapper: TestQueryProvider,+ },+ );+ await new Promise((r) => setTimeout(r, 20));+ expect(result.current.loading).toBe(true);++ setBackendStatus("healthy");++ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.endpointStatus.merge).toBe(true);+ });++ it("swaps local-check results for remote availability when the server returns", async () => {+ mode = "selfhosted";+ selfHostedStatus = "offline";+ mockLocalSupport.mockResolvedValue(false); // offline: nothing supported locally+ mockGet.mockImplementation((url: string) => {+ if (url.includes("app-config")) return Promise.resolve(appConfig(true));+ return Promise.resolve(availability({ merge: { enabled: true } }));+ });++ const { result } = renderHook(+ () => useMultipleEndpointsEnabled(["merge"]),+ {+ wrapper: TestQueryProvider,+ },+ );+ await waitFor(() =>+ expect(result.current.endpointStatus.merge).toBe(false),+ );++ // Server comes back: the hook must re-resolve against the remote, not sit+ // on the stale offline answer.+ setSelfHostedStatus("online");+ await waitFor(() => expect(result.current.endpointStatus.merge).toBe(true));+ });++ it("resolves each consumer's own endpoints when they ask for disjoint sets", async () => {+ // The offline path resolves only the endpoints it is handed. If consumers+ // shared one cache entry, the second would project endpoints nobody+ // checked and read them as available.+ mode = "selfhosted";+ selfHostedStatus = "offline";+ mockLocalSupport.mockImplementation((endpoint: string) =>+ Promise.resolve(endpoint === "merge"),+ );++ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: Infinity } },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );++ const { result } = renderHook(+ () => ({+ narrow: useMultipleEndpointsEnabled(NARROW),+ wide: useMultipleEndpointsEnabled(WIDE),+ }),+ { wrapper },+ );++ await waitFor(() => expect(result.current.wide.loading).toBe(false));++ // ocr and compress were genuinely probed and are unsupported locally.+ expect(result.current.wide.endpointStatus).toEqual({+ merge: true,+ ocr: false,+ compress: false,+ });+ expect(mockLocalSupport).toHaveBeenCalledWith("ocr", expect.anything());+ expect(mockLocalSupport).toHaveBeenCalledWith(+ "compress",+ expect.anything(),+ );+ });++ it("reports nothing loading when asked for no endpoints", async () => {+ // Stable reference: the current hook keys effects on the array identity.+ const { result } = renderHook(() => useMultipleEndpointsEnabled(NONE), {+ wrapper: TestQueryProvider,+ });+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.endpointStatus).toEqual({});+ expect(mockGet).not.toHaveBeenCalled();+ });+});++describe("desktop useEndpointEnabled", () => {+ it("starts optimistically enabled before any answer", () => {+ mode = "local";+ mockGet.mockImplementation(() => new Promise(() => {}));+ const { result } = renderHook(() => useEndpointEnabled("merge"), {+ wrapper: TestQueryProvider,+ });+ // Tools must not flash disabled while the backend boots.+ expect(result.current.enabled).toBe(true);+ });++ it("reflects a locally-enabled endpoint", async () => {+ mode = "local";+ mockGet.mockImplementation((url: string) => {+ if (url.includes("app-config")) return Promise.resolve(appConfig(true));+ return Promise.resolve({ data: true });+ });+ const { result } = renderHook(() => useEndpointEnabled("merge"), {+ wrapper: TestQueryProvider,+ });+ await waitFor(() => expect(result.current.enabled).toBe(true));+ });++ it("disables a locally-disabled endpoint outside SaaS mode", async () => {+ mode = "local";+ mockGet.mockImplementation((url: string) => {+ if (url.includes("app-config")) return Promise.resolve(appConfig(true));+ return Promise.resolve({ data: false });+ });+ const { result } = renderHook(() => useEndpointEnabled("merge"), {+ wrapper: TestQueryProvider,+ });+ await waitFor(() => expect(result.current.enabled).toBe(false));+ });++ it("keeps a locally-disabled endpoint enabled in SaaS mode", async () => {+ mode = "saas";+ mockGet.mockImplementation((url: string) => {+ if (url.includes("app-config")) return Promise.resolve(appConfig(true));+ return Promise.resolve({ data: false });+ });+ const { result } = renderHook(() => useEndpointEnabled("merge"), {+ wrapper: TestQueryProvider,+ });+ // Stays enabled: it will route to the SaaS backend.+ await new Promise((r) => setTimeout(r, 0));+ await waitFor(() => expect(result.current.enabled).toBe(true));+ });+});diff --git a/frontend/editor/src/desktop/hooks/useEndpointConfig.ts b/frontend/editor/src/desktop/hooks/useEndpointConfig.tsindex 490a793df0..b8cce7af48 100644--- a/frontend/editor/src/desktop/hooks/useEndpointConfig.ts+++ b/frontend/editor/src/desktop/hooks/useEndpointConfig.ts@@ -1,203 +1,101 @@-import { useState, useEffect, useCallback, useRef } from "react";-import { isAxiosError } from "axios";-import { useTranslation } from "react-i18next";-import apiClient from "@app/services/apiClient";+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ useSyncExternalStore,+} from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";import { tauriBackendService } from "@app/services/tauriBackendService";import { selfHostedServerMonitor } from "@app/services/selfHostedServerMonitor";-import { endpointAvailabilityService } from "@app/services/endpointAvailabilityService";import { isBackendNotReadyError } from "@app/constants/backendErrors";-import type { EndpointAvailabilityDetails } from "@app/types/endpointAvailability";import { connectionModeService } from "@app/services/connectionModeService";-import type { AppConfig } from "@app/contexts/AppConfigContext";+import { qk } from "@app/query/keys";+import { CONFIG_STALE_TIME } from "@app/query/staleTime";+import {+ isSelfHostedOffline,+ resolveEndpointEnabled,+ resolveEndpointsAvailability,+} from "@app/api/endpointAvailability";+import type { EndpointAvailabilityDetails } from "@app/types/endpointAvailability";interface EndpointConfig {backendUrl: string;}const RETRY_DELAY_MS = 2500;+const OPTIMISTIC: EndpointAvailabilityDetails = { enabled: true, reason: null };++// Booleans, not the monitors' state objects — those are reassigned every poll,+// which would defeat useSyncExternalStore's identity check.+const subscribeReadiness = (onChange: () => void) => {+ const unsubBackend = tauriBackendService.subscribeToStatus(onChange);+ const unsubServer = selfHostedServerMonitor.subscribe(onChange);+ return () => {+ unsubBackend();+ unsubServer();+ };+};+const getBackendOnline = () => tauriBackendService.isOnline;+const getOffline = () => isSelfHostedOffline();-function isSelfHostedOffline(): boolean {- return (- selfHostedServerMonitor.getSnapshot().status === "offline" &&- !!tauriBackendService.getBackendUrl()+/**+ * When the desktop backend is reachable: either the bundled backend is healthy,+ * or the self-hosted server is offline but the local one answers. A query only+ * runs once this is true, and a change re-runs it — which is how a reconnect+ * swaps the offline local-check answer for the live remote one.+ */+function useBackendReadiness() {+ const backendOnline = useSyncExternalStore(+ subscribeReadiness,+ getBackendOnline,);+ const offline = useSyncExternalStore(subscribeReadiness, getOffline);+ return { ready: backendOnline || offline, backendOnline, offline };}-function getErrorMessage(err: unknown): string {- if (isAxiosError(err)) {- const data = err.response?.data as { message?: string } | undefined;- if (typeof data?.message === "string") {- return data.message;- }- return err.message || "Unknown error occurred";- }- if (err instanceof Error) {- return err.message;- }- return "Unknown error occurred";-}--async function checkDependenciesReady(): Promise<boolean> {- try {- const response = await apiClient.get<AppConfig>(- "/api/v1/config/app-config",- {- suppressErrorToast: true,- },- );- return response.data?.dependenciesReady ?? false;- } catch (error) {- console.debug("[useEndpointConfig] Dependencies not ready yet:", error);- return false;- }-}+const retryWhileStarting = (_count: number, error: unknown) =>+ isBackendNotReadyError(error);-/**- * Desktop-specific endpoint checker that hits the backend directly via axios.- */+/** Desktop override: hits the backend directly, optimistic while it boots. */export function useEndpointEnabled(endpoint: string): {enabled: boolean | null;loading: boolean;error: string | null;refetch: () => Promise<void>;} {- const { t } = useTranslation();- // DESKTOP: Start optimistically as enabled (most desktop users are in SaaS mode)- // This prevents UI from being disabled while backend starts or checks are in progress- const [enabled, setEnabled] = useState<boolean | null>(true);- const [loading, setLoading] = useState(false);- const [error, setError] = useState<string | null>(null);- const isMountedRef = useRef(true);- const retryTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);-- const clearRetryTimeout = useCallback(() => {- if (retryTimeoutRef.current) {- clearTimeout(retryTimeoutRef.current);- retryTimeoutRef.current = null;- }- }, []);-- useEffect(() => {- return () => {- isMountedRef.current = false;- clearRetryTimeout();- };- }, [clearRetryTimeout]);-- const fetchEndpointStatus = useCallback(async () => {- clearRetryTimeout();-- if (!endpoint) {- if (!isMountedRef.current) return;- setEnabled(null);- setLoading(false);- return;- }-- const dependenciesReady = await checkDependenciesReady();- if (!dependenciesReady) {- return; // Health monitor will trigger retry when truly ready- }-- try {- setError(null);-- const response = await apiClient.get<boolean>(- `/api/v1/config/endpoint-enabled?endpoint=${encodeURIComponent(endpoint)}`,- {- suppressErrorToast: true,- },- );-- const locallyEnabled = response.data;-- if (!locallyEnabled) {- const mode = await connectionModeService.getCurrentMode();- // DESKTOP ENHANCEMENT: In SaaS mode, assume all endpoints are available- // Even if not supported locally, they will route to SaaS backend- if (mode === "saas") {- console.debug(- `[useEndpointEnabled] Endpoint ${endpoint} not supported locally but available via SaaS routing`,- );- setEnabled(true);- return;- }- }-- setEnabled(locallyEnabled);- } catch (err: unknown) {- const isBackendStarting = isBackendNotReadyError(err);- const message = getErrorMessage(err);-- if (isBackendStarting) {- setError(t("backendHealth.starting", "Backend starting up..."));- if (!retryTimeoutRef.current) {- retryTimeoutRef.current = setTimeout(() => {- retryTimeoutRef.current = null;- fetchEndpointStatus();- }, RETRY_DELAY_MS);- }- } else {- // DESKTOP ENHANCEMENT: In SaaS mode, assume available even on check failure- const mode = await connectionModeService.getCurrentMode();- if (mode === "saas") {- console.debug(- `[useEndpointEnabled] Endpoint ${endpoint} check failed but available via SaaS routing`,- );- setEnabled(true); // Available via SaaS- setError(null);- return;- }-- setError(message);- setEnabled(false);- }- } finally {- setLoading(false);- }- }, [endpoint, clearRetryTimeout, t]);-+ const queryClient = useQueryClient();+ const { ready, backendOnline, offline } = useBackendReadiness();+ const queryKey = qk.endpointEnabled(endpoint);++ const { data, refetch } = useQuery({+ queryKey,+ queryFn: () => resolveEndpointEnabled(endpoint),+ enabled: Boolean(endpoint) && ready,+ staleTime: CONFIG_STALE_TIME,+ retry: retryWhileStarting,+ retryDelay: RETRY_DELAY_MS,+ });++ // Skipped on mount for the same reason as above: the query is already running.+ const seenReadiness = useRef<string | null>(null);+ const readinessMark = `${backendOnline}:${offline}:${endpoint}`;useEffect(() => {- if (!endpoint) {- setEnabled(null);- setLoading(false);- return;- }-- // In self-hosted offline mode, enable optimistically when the local backend is ready.- // ConvertSettings already filters unsupported endpoints from the dropdown,- // so by the time the user has a valid endpoint selected it is supported locally.- if (isSelfHostedOffline()) {- setEnabled(true);- setLoading(false);- // Re-evaluate if the server comes back online- return selfHostedServerMonitor.subscribe(() => {- if (!isSelfHostedOffline() && tauriBackendService.isOnline) {- fetchEndpointStatus();- }- });- }-- if (tauriBackendService.isOnline) {- fetchEndpointStatus();- }-- const unsubscribe = tauriBackendService.subscribeToStatus((status) => {- if (status === "healthy") {- fetchEndpointStatus();- }- });-- return () => {- unsubscribe();- };- }, [endpoint, fetchEndpointStatus]);+ const first = seenReadiness.current === null;+ seenReadiness.current = readinessMark;+ if (first || !ready) return;+ void queryClient.invalidateQueries({ queryKey });+ }, [readinessMark]);return {- enabled,- loading,- error,- refetch: fetchEndpointStatus,+ enabled: endpoint ? (data ?? true) : null,+ // Optimistic by design: the desktop endpoint check never blocks the UI.+ loading: false,+ error: null,+ refetch: useCallback(async () => {+ await refetch();+ }, [refetch]),};}@@ -208,247 +106,62 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {error: string | null;refetch: () => Promise<void>;} {- const { t } = useTranslation();- const [endpointStatus, setEndpointStatus] = useState<Record<string, boolean>>(- {},- );- const [endpointDetails, setEndpointDetails] = useState<- Record<string, EndpointAvailabilityDetails>- >({});- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const isMountedRef = useRef(true);- const retryTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);-- const clearRetryTimeout = useCallback(() => {- if (retryTimeoutRef.current) {- clearTimeout(retryTimeoutRef.current);- retryTimeoutRef.current = null;- }- }, []);-+ const queryClient = useQueryClient();+ const { ready, backendOnline, offline } = useBackendReadiness();+ const wanted = endpoints ?? [];+ const key = wanted.join(",");+ // Keyed by the endpoint set, not shared across consumers. A constant key+ // would assert the value is caller-independent, and on two paths it is not:+ // the self-hosted-offline check and the legacy ?endpoints= fallback both+ // resolve only the endpoints they were handed. Consumers pass disjoint sets,+ // so a shared entry would leave the second consumer's endpoints unresolved+ // and reading as available. Prefix invalidation below still covers every set.+ const queryKey = [...qk.endpointsAvailability(), key];++ const { data, isPending, refetch } = useQuery({+ queryKey,+ queryFn: () => resolveEndpointsAvailability(key ? key.split(",") : []),+ enabled: wanted.length > 0 && ready,+ staleTime: CONFIG_STALE_TIME,+ retry: retryWhileStarting,+ retryDelay: RETRY_DELAY_MS,+ });++ // A reconnect forces the swap from offline to remote data. Skipped on mount:+ // the query is already fetching, and invalidating would double the request.+ const seenReadiness = useRef<string | null>(null);+ const readinessMark = `${backendOnline}:${offline}`;useEffect(() => {- return () => {- isMountedRef.current = false;- clearRetryTimeout();- };- }, [clearRetryTimeout]);-- const fetchAllEndpointStatuses = useCallback(async () => {- clearRetryTimeout();-- if (!endpoints || endpoints.length === 0) {- setEndpointStatus({});- setLoading(false);- return;- }-- // Self-hosted offline: check each endpoint against the local backend directly.- // checkDependenciesReady() would fail here since it hits the offline remote server.- const { status: serverStatus } = selfHostedServerMonitor.getSnapshot();- const localUrl = tauriBackendService.getBackendUrl();- if (serverStatus === "offline" && localUrl) {- const results = await Promise.all(- [...new Set(endpoints)].map(async (ep) => {- try {- const supported =- await endpointAvailabilityService.isEndpointSupportedLocally(- ep,- localUrl,- );- return { ep, supported };- } catch {- return { ep, supported: false };- }- }),- );- if (!isMountedRef.current) return;- const statusMap: Record<string, boolean> = {};- const details: Record<string, EndpointAvailabilityDetails> = {};- for (const { ep, supported } of results) {- statusMap[ep] = supported;- details[ep] = {- enabled: supported,- reason: supported ? null : "NOT_SUPPORTED_LOCALLY",- };- }- setEndpointDetails((prev) => ({ ...prev, ...details }));- setEndpointStatus((prev) => ({ ...prev, ...statusMap }));- setLoading(false);- return;- }-- const dependenciesReady = await checkDependenciesReady();- if (!dependenciesReady) {- return; // Health monitor will trigger retry when truly ready- }-- try {- setError(null);-- // Try new API first (no params — new servers return all endpoints).- // Fall back to the old ?endpoints= form for servers that predate the- // "large query reduction" change and still require the parameter.- let response: Awaited<- ReturnType<- typeof apiClient.get<Record<string, EndpointAvailabilityDetails>>- >- >;- try {- response = await apiClient.get<- Record<string, EndpointAvailabilityDetails>- >(`/api/v1/config/endpoints-availability`, {- suppressErrorToast: true,- });- } catch (innerErr) {- if (isAxiosError(innerErr) && innerErr.response?.status === 400) {- // Old server — requires explicit endpoints query param- console.debug(- "[useMultipleEndpointsEnabled] Server requires endpoints param, retrying with legacy format",- );- const endpointsParam = endpoints.join(",");- response = await apiClient.get<- Record<string, EndpointAvailabilityDetails>- >(- `/api/v1/config/endpoints-availability?endpoints=${encodeURIComponent(endpointsParam)}`,- { suppressErrorToast: true },- );- } else {- throw innerErr;- }- }-- const details = Object.entries(response.data).reduce(- (acc, [endpointName, detail]) => {- acc[endpointName] = {- enabled: detail?.enabled ?? false,- reason: detail?.reason ?? null,- };- return acc;- },- {} as Record<string, EndpointAvailabilityDetails>,- );-- const statusMap = Object.keys(details).reduce(- (acc, key) => {- acc[key] = details[key].enabled;- return acc;- },- {} as Record<string, boolean>,- );-- const mode = await connectionModeService.getCurrentMode();-- // DESKTOP ENHANCEMENT: In SaaS mode, mark all disabled endpoints as available- // They will route to SaaS backend- if (mode === "saas") {- const disabledEndpoints = Object.keys(details).filter(- (key) => !details[key].enabled,- );-- for (const endpoint of disabledEndpoints) {- console.debug(- `[useMultipleEndpointsEnabled] Endpoint ${endpoint} not supported locally but available via SaaS routing`,- );- statusMap[endpoint] = true; // Mark as enabled via SaaS- details[endpoint] = { enabled: true, reason: null };- }- }-- setEndpointDetails((prev) => ({ ...prev, ...details }));- setEndpointStatus((prev) => ({ ...prev, ...statusMap }));- } catch (err: unknown) {- const isBackendStarting = isBackendNotReadyError(err);- const message = getErrorMessage(err);-- if (isBackendStarting) {- setError(t("backendHealth.starting", "Backend starting up..."));- if (!retryTimeoutRef.current) {- retryTimeoutRef.current = setTimeout(() => {- retryTimeoutRef.current = null;- fetchAllEndpointStatuses();- }, RETRY_DELAY_MS);- }- } else {- setError(message);- const fallbackStatus = endpoints.reduce<{- status: Record<string, boolean>;- details: Record<string, EndpointAvailabilityDetails>;- }>(- (acc, endpointName) => {- const fallbackDetail: EndpointAvailabilityDetails = {- enabled: false,- reason: "UNKNOWN",- };- acc.status[endpointName] = false;- acc.details[endpointName] = fallbackDetail;- return acc;- },- {- status: {},- details: {},- },- );-- // DESKTOP ENHANCEMENT: In SaaS mode, mark all endpoints as available- const mode = await connectionModeService.getCurrentMode();- if (mode === "saas") {- for (const endpoint of endpoints) {- console.debug(- `[useMultipleEndpointsEnabled] Endpoint ${endpoint} check failed but available via SaaS routing`,- );- fallbackStatus.status[endpoint] = true;- fallbackStatus.details[endpoint] = { enabled: true, reason: null };- }- }-- setEndpointStatus(fallbackStatus.status);- setEndpointDetails((prev) => ({ ...prev, ...fallbackStatus.details }));- }- } finally {- setLoading(false);- }- }, [endpoints, clearRetryTimeout, t]);-- useEffect(() => {- if (!endpoints || endpoints.length === 0) {- setEndpointStatus({});- setEndpointDetails({});- setLoading(false);- return;- }-- if (isSelfHostedOffline()) {- fetchAllEndpointStatuses();- const unsubServer = selfHostedServerMonitor.subscribe(() => {- if (!isSelfHostedOffline() && tauriBackendService.isOnline) {- fetchAllEndpointStatuses();- }- });- return unsubServer;- }-- if (tauriBackendService.isOnline) {- fetchAllEndpointStatuses();- }-- const unsubscribe = tauriBackendService.subscribeToStatus((status) => {- if (status === "healthy") {- fetchAllEndpointStatuses();- }+ const first = seenReadiness.current === null;+ seenReadiness.current = readinessMark;+ if (first || !ready) return;+ void queryClient.invalidateQueries({+ queryKey: qk.endpointsAvailability(),});-- return () => {- unsubscribe();- };- }, [endpoints, fetchAllEndpointStatuses]);+ }, [readinessMark]);++ const projected = useMemo(() => {+ const status: Record<string, boolean> = {};+ const details: Record<string, EndpointAvailabilityDetails> = {};+ if (!data) return { status, details };+ for (const endpoint of key ? key.split(",") : []) {+ // Safe because the entry is per-set: a miss here means the server does+ // not know the endpoint, which the old code also treated as available.+ const detail = data[endpoint] ?? OPTIMISTIC;+ status[endpoint] = detail.enabled;+ details[endpoint] = detail;+ }+ return { status, details };+ }, [data, key]);return {- endpointStatus,- endpointDetails,- loading,- error,- refetch: fetchAllEndpointStatuses,+ endpointStatus: projected.status,+ endpointDetails: projected.details,+ loading: wanted.length > 0 && isPending,+ error: null,+ refetch: useCallback(async () => {+ await refetch();+ }, [refetch]),};}