diff --git a/DashAI/back/api/front_api.py b/DashAI/back/api/front_api.py index 110356755..6184ee2d8 100644 --- a/DashAI/back/api/front_api.py +++ b/DashAI/back/api/front_api.py @@ -1,16 +1,41 @@ +import gzip import mimetypes import os +from functools import lru_cache from pathlib import Path from typing import Any, Dict -from fastapi import APIRouter, Depends -from fastapi.responses import FileResponse, RedirectResponse +from fastapi import APIRouter, Depends, Request +from fastapi.responses import FileResponse, RedirectResponse, Response from kink import di, inject +from starlette.concurrency import run_in_threadpool mimetypes.add_type("text/javascript", ".js") router = APIRouter() +ASSET_CACHE_CONTROL = "public, max-age=31536000, immutable" +COMPRESSIBLE_ASSET_SUFFIXES = (".js", ".css") + + +@lru_cache(maxsize=512) +def _gzip_asset(path: str, mtime_ns: int) -> bytes: + """Compress a build asset once per file version. + + Parameters + ---------- + path : str + Absolute path of the asset. + mtime_ns : int + Modification time of the asset, so a rebuilt file is compressed again. + + Returns + ------- + bytes + The gzip compressed content. + """ + return gzip.compress(Path(path).read_bytes(), compresslevel=6) + # React router should handle paths under /app, which are defined in index.html @router.get("/app/{full_path:path}") @@ -32,6 +57,7 @@ async def read_index( @inject async def serve_files( file: str, + request: Request, config: Dict[str, Any] = Depends(lambda: di["config"]), ): front_build_path = config["FRONT_BUILD_PATH"] @@ -39,7 +65,19 @@ async def serve_files( if file == "": return RedirectResponse(url="/app/") path = Path(f"{front_build_path}/{file}").absolute() - os.stat(path) - return FileResponse(path) + stat = os.stat(path) + if not file.startswith("assets/"): + return FileResponse(path) + headers = {"Cache-Control": ASSET_CACHE_CONTROL, "Vary": "Accept-Encoding"} + accepts_gzip = "gzip" in request.headers.get("accept-encoding", "") + if accepts_gzip and path.suffix in COMPRESSIBLE_ASSET_SUFFIXES: + body = await run_in_threadpool(_gzip_asset, str(path), stat.st_mtime_ns) + headers["Content-Encoding"] = "gzip" + return Response( + body, + media_type=mimetypes.guess_type(path.name)[0], + headers=headers, + ) + return FileResponse(path, headers=headers) except FileNotFoundError: return RedirectResponse(url="/app/") diff --git a/DashAI/front/src/App.jsx b/DashAI/front/src/App.jsx index 045b16369..ee03053fa 100644 --- a/DashAI/front/src/App.jsx +++ b/DashAI/front/src/App.jsx @@ -1,4 +1,4 @@ -import React from "react"; +import React, { Suspense, lazy } from "react"; import { BrowserRouter, @@ -10,26 +10,35 @@ import { import { TourRegistryProvider } from "./contexts/TourRegistryContext"; import "./App.css"; -import DatasetsPage from "./pages/datasets/Datasets"; -import ModelsPage from "./pages/models/Models"; import Home from "./pages/home/Home"; import ResponsiveAppBar from "./components/ResponsiveAppBar"; -import PluginsPage from "./pages/plugins/Plugins"; -import PluginsDetails from "./pages/plugins/components/PluginsDetails"; -import Generative from "./pages/generative/Generative"; import { GenerativeProvider } from "./components/generative/GenerativeContext"; -import HubContent from "./pages/hub/HubContent"; -import HubImportPage from "./pages/hub/HubImportPage"; import JobQueueWidget from "./components/jobs/JobQueueWidget"; -import RAGCreatePage from "./pages/generative/RAG/RAGCreatePage"; -import RAGPromptsPage from "./pages/generative/RAG/RAGPromptsPage"; -import RAGSessionPage from "./pages/generative/RAGSession/RAGSessionPage"; -import SessionRouter from "./pages/generative/SessionRouter"; import { DatasetsAndNotebooksProvider } from "./components/custom/contexts/DatasetsAndNotebooksContext"; import { DatasetsProvider } from "./contexts/DatasetsContext"; import { ModelsProvider } from "./components/models/ModelsContext"; import { RAG_WORKFLOW_NAME } from "./constants/generativeWorkflows"; +const DatasetsPage = lazy(() => import("./pages/datasets/Datasets")); +const ModelsPage = lazy(() => import("./pages/models/Models")); +const PluginsPage = lazy(() => import("./pages/plugins/Plugins")); +const PluginsDetails = lazy( + () => import("./pages/plugins/components/PluginsDetails"), +); +const Generative = lazy(() => import("./pages/generative/Generative")); +const HubContent = lazy(() => import("./pages/hub/HubContent")); +const HubImportPage = lazy(() => import("./pages/hub/HubImportPage")); +const RAGCreatePage = lazy( + () => import("./pages/generative/RAG/RAGCreatePage"), +); +const RAGPromptsPage = lazy( + () => import("./pages/generative/RAG/RAGPromptsPage"), +); +const RAGSessionPage = lazy( + () => import("./pages/generative/RAGSession/RAGSessionPage"), +); +const SessionRouter = lazy(() => import("./pages/generative/SessionRouter")); + /** * Scopes a RAG route to its own session list. * @@ -68,54 +77,55 @@ function App() { - - } /> - } /> - }> - } /> - } /> + + + } /> + } /> + }> + } /> + } /> + } + /> + } + /> + } /> + } + /> + } /> + } /> + } /> + } /> + } + /> + } /> + + } /> } + path="/app/models/datasets/:id" + element={} /> } + path="/app/models/sessions/:id" + element={} /> - } /> } + path="/app/models/sessions/new/:taskName" + element={} /> - } /> - } /> - } /> - } /> } + path="/app/models/sessions/:id/model/:runId" + element={} /> - } /> - - } /> - } - /> - } - /> - } - /> - } - /> - } /> - {/* RAG is an entry point of the Generative module, not a step + } /> + {/* RAG is an entry point of the Generative module, not a step inside session creation, and the entry point *is* creating a session: picking RAG used to land on a menu whose only card was "new session", so starting one took two clicks. Existing @@ -123,61 +133,62 @@ function App() { provider scopes to RAG so the shared list stays separate. Route matching is case-insensitive, so the previous /app/generative/RAG/... links keep working. */} - - - - } - /> - } - /> - - - - } - /> - {/* Documents belong to a session now, so that page is gone. + + + + } + /> + } + /> + + + + } + /> + {/* Documents belong to a session now, so that page is gone. Prompts are shared templates again, with their own library where create/delete and dependent sessions are explicit. */} - } - /> - - - - } - /> - } - /> - } - /> - } - /> - - } /> - + } + /> + + + + } + /> + } + /> + } + /> + } + /> + } /> - } /> + + } /> + } /> + - - + + diff --git a/DashAI/front/src/api/generativeTask.ts b/DashAI/front/src/api/generativeTask.ts index 157172389..b2e95cae2 100644 --- a/DashAI/front/src/api/generativeTask.ts +++ b/DashAI/front/src/api/generativeTask.ts @@ -1,4 +1,5 @@ import api from "./api"; +import i18n from "../utils/i18n"; import type { IGenerativeTask } from "../types/generativeTask"; import type { ISession, ISessionParameterHistory } from "../types/session"; @@ -9,7 +10,9 @@ export const getGenerativeTask = async (): Promise => { return response.data; }; -export const getRelatedComponents = async ( +const pendingRelatedComponents = new Map>(); + +const fetchRelatedComponents = async ( relatedComponent: string, ): Promise => { try { @@ -24,6 +27,20 @@ export const getRelatedComponents = async ( } }; +export const getRelatedComponents = async ( + relatedComponent: string, +): Promise => { + const key = `${relatedComponent}|${i18n.language}`; + let request = pendingRelatedComponents.get(key); + if (request === undefined) { + request = fetchRelatedComponents(relatedComponent).finally(() => { + pendingRelatedComponents.delete(key); + }); + pendingRelatedComponents.set(key, request); + } + return structuredClone(await request); +}; + export const createGenerativeSession = async ( sessionData: Omit, ): Promise => { diff --git a/DashAI/front/src/components/models/FoldMetricsChart.jsx b/DashAI/front/src/components/models/FoldMetricsChart.jsx index 8671a6950..e745efc04 100644 --- a/DashAI/front/src/components/models/FoldMetricsChart.jsx +++ b/DashAI/front/src/components/models/FoldMetricsChart.jsx @@ -6,7 +6,7 @@ import React, { useCallback, } from "react"; import PropTypes from "prop-types"; -import Plot from "react-plotly.js"; +import Plot from "../shared/LazyPlot"; import { Box, CircularProgress, diff --git a/DashAI/front/src/components/models/LiveMetricsChart.jsx b/DashAI/front/src/components/models/LiveMetricsChart.jsx index 6782731fa..312596463 100644 --- a/DashAI/front/src/components/models/LiveMetricsChart.jsx +++ b/DashAI/front/src/components/models/LiveMetricsChart.jsx @@ -7,7 +7,7 @@ import { ButtonGroup, } from "@mui/material"; import { useTheme, alpha } from "@mui/material/styles"; -import Plot from "react-plotly.js"; +import Plot from "../shared/LazyPlot"; import { useEffect, useMemo, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import ResultsGraphsParameters from "../../pages/results/components/ResultsGraphsParameters"; diff --git a/DashAI/front/src/components/notebooks/dataset/ExportableCard.jsx b/DashAI/front/src/components/notebooks/dataset/ExportableCard.jsx index 6d04346ae..4e1e093e3 100644 --- a/DashAI/front/src/components/notebooks/dataset/ExportableCard.jsx +++ b/DashAI/front/src/components/notebooks/dataset/ExportableCard.jsx @@ -13,7 +13,6 @@ import ImageOutlinedIcon from "@mui/icons-material/ImageOutlined"; import BarChartOutlinedIcon from "@mui/icons-material/BarChartOutlined"; import TableChartOutlinedIcon from "@mui/icons-material/TableChartOutlined"; import DataObjectOutlinedIcon from "@mui/icons-material/DataObjectOutlined"; -import html2canvas from "html2canvas"; import { useTranslation } from "react-i18next"; /** @@ -48,6 +47,7 @@ export default function ExportableCard({ try { // Wait a tick so the hidden button is removed from the DOM before capture await new Promise((r) => requestAnimationFrame(r)); + const { default: html2canvas } = await import("html2canvas"); const canvas = await html2canvas(element, { backgroundColor: null, scale: 2, @@ -78,6 +78,7 @@ export default function ExportableCard({ setCapturing(true); try { await new Promise((r) => requestAnimationFrame(r)); + const { default: html2canvas } = await import("html2canvas"); const canvas = await html2canvas(chart, { backgroundColor: null, scale: 2, diff --git a/DashAI/front/src/components/notebooks/dataset/tabs/CorrelationsTab.jsx b/DashAI/front/src/components/notebooks/dataset/tabs/CorrelationsTab.jsx index 8dfb9461d..ddf92ed1e 100644 --- a/DashAI/front/src/components/notebooks/dataset/tabs/CorrelationsTab.jsx +++ b/DashAI/front/src/components/notebooks/dataset/tabs/CorrelationsTab.jsx @@ -1,7 +1,7 @@ import { useMemo } from "react"; import { Box, Typography, CardContent } from "@mui/material"; import { useTheme } from "@mui/material/styles"; -import Plot from "react-plotly.js"; +import Plot from "../../../shared/LazyPlot"; import ExportableCard from "../ExportableCard"; import { useTranslation } from "react-i18next"; diff --git a/DashAI/front/src/components/notebooks/dataset/tabs/NumericTab.jsx b/DashAI/front/src/components/notebooks/dataset/tabs/NumericTab.jsx index 01353159a..86593a22e 100644 --- a/DashAI/front/src/components/notebooks/dataset/tabs/NumericTab.jsx +++ b/DashAI/front/src/components/notebooks/dataset/tabs/NumericTab.jsx @@ -3,7 +3,7 @@ import { Box, Typography, CardContent, Alert, Button } from "@mui/material"; import { useTheme } from "@mui/material/styles"; import TrendingUpIcon from "@mui/icons-material/TrendingUp"; import InfoIcon from "@mui/icons-material/Info"; -import Plot from "react-plotly.js"; +import Plot from "../../../shared/LazyPlot"; import { StatBox } from "../StatBox"; import { MetricRow } from "../MetricRow"; import ExportableCard from "../ExportableCard"; diff --git a/DashAI/front/src/components/notebooks/datasetCreation/Upload.jsx b/DashAI/front/src/components/notebooks/datasetCreation/Upload.jsx index 0e1af73a2..dae5f9717 100644 --- a/DashAI/front/src/components/notebooks/datasetCreation/Upload.jsx +++ b/DashAI/front/src/components/notebooks/datasetCreation/Upload.jsx @@ -18,7 +18,6 @@ import { import PreviewDataset from "./PreviewDataset"; import { useSnackbar } from "notistack"; -import JSZip from "jszip"; import { useTranslation } from "react-i18next"; import { useTourContext } from "../../tour/TourProvider"; @@ -138,6 +137,7 @@ function Upload({ } const arrayBuffer = await file.arrayBuffer(); + const { default: JSZip } = await import("jszip"); const zip = await JSZip.loadAsync(arrayBuffer); let found = false; diff --git a/DashAI/front/src/components/notebooks/explorer/visualizations/PlotlyJsonVisualizer.jsx b/DashAI/front/src/components/notebooks/explorer/visualizations/PlotlyJsonVisualizer.jsx index 5c719a270..587a54546 100644 --- a/DashAI/front/src/components/notebooks/explorer/visualizations/PlotlyJsonVisualizer.jsx +++ b/DashAI/front/src/components/notebooks/explorer/visualizations/PlotlyJsonVisualizer.jsx @@ -1,7 +1,7 @@ import React, { useState, useRef } from "react"; import PropTypes from "prop-types"; import { useTheme } from "@mui/material/styles"; -import Plot from "react-plotly.js"; +import Plot from "../../../shared/LazyPlot"; import { Box, IconButton, Tooltip, Menu, MenuItem } from "@mui/material"; import Dialog from "@mui/material/Dialog"; import ZoomInIcon from "@mui/icons-material/ZoomIn"; diff --git a/DashAI/front/src/components/notebooks/tool/ToolGridItem.jsx b/DashAI/front/src/components/notebooks/tool/ToolGridItem.jsx index 21e1cdf4a..b26c5747c 100644 --- a/DashAI/front/src/components/notebooks/tool/ToolGridItem.jsx +++ b/DashAI/front/src/components/notebooks/tool/ToolGridItem.jsx @@ -162,6 +162,7 @@ export default function ToolGridItem({ { + const objectUrl = URL.createObjectURL(file); + setUrl(objectUrl); + return () => URL.revokeObjectURL(objectUrl); + }, [file]); + + if (!url) return null; + return ( + + ); +} + function computeWidth(val, placeholder) { const len = Math.max( String(val ?? "").length, @@ -108,18 +132,7 @@ function InputField({ if (effectiveType === "Image" || dtype === "image") { return ( - {value instanceof File && ( - - )} + {value instanceof File && } ({ ), }); -export function DescriptionBlock({ text, isError }) { +export const DescriptionBlock = memo(function DescriptionBlock({ + text, + isError, +}) { const [expanded, setExpanded] = useState(false); const { t } = useTranslation(["common"]); @@ -122,7 +125,7 @@ export function DescriptionBlock({ text, isError }) { )} ); -} +}); DescriptionBlock.propTypes = { text: PropTypes.string, diff --git a/DashAI/front/src/components/shared/LazyPlot.jsx b/DashAI/front/src/components/shared/LazyPlot.jsx new file mode 100644 index 000000000..f7c76dce3 --- /dev/null +++ b/DashAI/front/src/components/shared/LazyPlot.jsx @@ -0,0 +1,15 @@ +import { Suspense, forwardRef, lazy } from "react"; + +const Plot = lazy(() => import("react-plotly.js")); + +const LazyPlot = forwardRef(function LazyPlot(props, ref) { + return ( + } + > + + + ); +}); + +export default LazyPlot; diff --git a/DashAI/front/src/components/shared/PlotActions.jsx b/DashAI/front/src/components/shared/PlotActions.jsx index e404a4eea..84575961b 100644 --- a/DashAI/front/src/components/shared/PlotActions.jsx +++ b/DashAI/front/src/components/shared/PlotActions.jsx @@ -8,7 +8,7 @@ import { MenuItem, Dialog, } from "@mui/material"; -import Plot from "react-plotly.js"; +import Plot from "./LazyPlot"; import DownloadIcon from "@mui/icons-material/Download"; import FullscreenIcon from "@mui/icons-material/Fullscreen"; import CloseIcon from "@mui/icons-material/Close"; diff --git a/DashAI/front/src/components/tour/TourProvider.jsx b/DashAI/front/src/components/tour/TourProvider.jsx index 7f4bb4ce0..99b32ca5a 100644 --- a/DashAI/front/src/components/tour/TourProvider.jsx +++ b/DashAI/front/src/components/tour/TourProvider.jsx @@ -1,12 +1,13 @@ import React, { + Suspense, createContext, + lazy, useContext, useState, useEffect, useCallback, useRef, } from "react"; -import Joyride from "react-joyride"; import GlobalStyles from "@mui/material/GlobalStyles"; import { useTranslation } from "react-i18next"; import { useTour } from "../../hooks/useTour"; @@ -16,6 +17,8 @@ import { useTheme } from "@mui/material/styles"; import { CustomTooltip } from "./CustomTooltip"; import { useTourRegistry } from "../../contexts/TourRegistryContext"; +const Joyride = lazy(() => import("react-joyride")); + // The overlay (not the spotlight) has mix-blend-mode: hard-light. // Everything inside the overlay (including spotlight box-shadow) blends // with the PAGE CONTENT behind, so we must pre-invert colors differently @@ -182,29 +185,31 @@ export const TourProvider = ({ return ( - + + + {children} ); diff --git a/DashAI/front/src/components/updates/UpdatesButton.jsx b/DashAI/front/src/components/updates/UpdatesButton.jsx index a1046e7f4..30f77cd0b 100644 --- a/DashAI/front/src/components/updates/UpdatesButton.jsx +++ b/DashAI/front/src/components/updates/UpdatesButton.jsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from "react"; +import React, { Suspense, lazy, useEffect, useState } from "react"; import Badge from "@mui/material/Badge"; import IconButton from "@mui/material/IconButton"; import Tooltip from "@mui/material/Tooltip"; @@ -6,7 +6,8 @@ import SystemUpdateAltOutlinedIcon from "@mui/icons-material/SystemUpdateAltOutl import { useTheme } from "@mui/material/styles"; import { useTranslation } from "react-i18next"; import { getUpdateCheck } from "../../api/system"; -import UpdatesDialog from "./UpdatesDialog"; + +const UpdatesDialog = lazy(() => import("./UpdatesDialog")); export default function UpdatesButton() { const theme = useTheme(); @@ -60,7 +61,9 @@ export default function UpdatesButton() { - setOpen(false)} info={info} /> + + setOpen(false)} info={info} /> + > ); } diff --git a/DashAI/front/src/hooks/useJobPolling.js b/DashAI/front/src/hooks/useJobPolling.js index 5f009a748..15609f53d 100644 --- a/DashAI/front/src/hooks/useJobPolling.js +++ b/DashAI/front/src/hooks/useJobPolling.js @@ -116,7 +116,9 @@ export function useJobManager() { const unsubscribe = subscribeJobs((updatedJobs) => { if (Array.isArray(updatedJobs)) { // `updatedJobs` is incremental (changes since cursor), so merge it. - setJobs((previousJobs) => mergeJobsById(previousJobs, updatedJobs)); + if (updatedJobs.length > 0) { + setJobs((previousJobs) => mergeJobsById(previousJobs, updatedJobs)); + } setLoading(false); } }); diff --git a/DashAI/front/src/hooks/useStrategyKind.js b/DashAI/front/src/hooks/useStrategyKind.js index f3236c401..7913f57da 100644 --- a/DashAI/front/src/hooks/useStrategyKind.js +++ b/DashAI/front/src/hooks/useStrategyKind.js @@ -9,6 +9,23 @@ import { getComponents } from "../api/component"; * session and none of them should trigger its own request. */ const metadataCache = new Map(); +const pendingRequests = new Map(); + +function fetchStrategyMetadata(strategyName) { + if (!pendingRequests.has(strategyName)) { + const request = getComponents({ model: strategyName }) + .then((component) => { + const value = component?.metadata ?? {}; + metadataCache.set(strategyName, value); + return value; + }) + .finally(() => { + pendingRequests.delete(strategyName); + }); + pendingRequests.set(strategyName, request); + } + return pendingRequests.get(strategyName); +} /** * Read the metadata an evaluation strategy declares. @@ -40,9 +57,7 @@ export function useStrategyMetadata(strategyName) { let cancelled = false; const fetchMetadata = async () => { try { - const component = await getComponents({ model: strategyName }); - const value = component?.metadata ?? {}; - metadataCache.set(strategyName, value); + const value = await fetchStrategyMetadata(strategyName); if (!cancelled) setMetadata(value); } catch (error) { console.error(`Error fetching the ${strategyName} metadata`, error); diff --git a/DashAI/front/src/index.jsx b/DashAI/front/src/index.jsx index 1462d5b58..0f049892a 100644 --- a/DashAI/front/src/index.jsx +++ b/DashAI/front/src/index.jsx @@ -6,23 +6,25 @@ import CssBaseline from "@mui/material/CssBaseline"; import App from "./App"; import { SnackbarProvider } from "notistack"; import { CustomThemeProvider } from "./contexts/ThemeContext"; -import "./utils/i18n"; +import { i18nReady } from "./utils/i18n"; const root = ReactDOM.createRoot(document.getElementById("root")); -root.render( - - - - - - - - , -); +i18nReady.finally(() => { + root.render( + + + + + + + + , + ); +}); diff --git a/DashAI/front/src/pages/results/components/ResultsGraphsPlot.jsx b/DashAI/front/src/pages/results/components/ResultsGraphsPlot.jsx index 362ed6809..625906c1f 100644 --- a/DashAI/front/src/pages/results/components/ResultsGraphsPlot.jsx +++ b/DashAI/front/src/pages/results/components/ResultsGraphsPlot.jsx @@ -2,7 +2,7 @@ import React, { useEffect, useRef, useState } from "react"; import PropTypes from "prop-types"; import { Box, Typography } from "@mui/material"; import { useTheme } from "@mui/material/styles"; -import Plot from "react-plotly.js"; +import Plot from "../../../components/shared/LazyPlot"; import { useTranslation } from "react-i18next"; import { DragIndicator } from "@mui/icons-material"; import PlotActions from "../../../components/shared/PlotActions"; diff --git a/DashAI/front/src/utils/i18n/index.js b/DashAI/front/src/utils/i18n/index.js index 12815699e..1da340c27 100644 --- a/DashAI/front/src/utils/i18n/index.js +++ b/DashAI/front/src/utils/i18n/index.js @@ -2,25 +2,47 @@ import i18n from "i18next"; import { initReactI18next } from "react-i18next"; import LanguageDetector from "i18next-browser-languagedetector"; -const localeFiles = import.meta.glob("./locales/*/*.json", { +const fallbackFiles = import.meta.glob("./locales/en/*.json", { eager: true, import: "default", }); -const resources = {}; -for (const [path, content] of Object.entries(localeFiles)) { - const [, language, namespace] = path.match( - /\.\/locales\/([^/]+)\/([^/]+)\.json$/, - ); - resources[language] ??= {}; - resources[language][namespace] = content; +const lazyFiles = import.meta.glob( + ["./locales/*/*.json", "!./locales/en/*.json"], + { + import: "default", + }, +); + +const resources = { en: {} }; +for (const [path, content] of Object.entries(fallbackFiles)) { + const [, namespace] = path.match(/\.\/locales\/en\/([^/]+)\.json$/); + resources.en[namespace] = content; } -i18n +const lazyLocaleBackend = { + type: "backend", + init() {}, + read(language, namespace, callback) { + const load = lazyFiles[`./locales/${language}/${namespace}.json`]; + if (!load) { + callback(null, {}); + return; + } + load().then( + (content) => callback(null, content), + (error) => callback(error, null), + ); + }, +}; + +export const i18nReady = i18n + .use(lazyLocaleBackend) .use(LanguageDetector) .use(initReactI18next) .init({ resources, + partialBundledLanguages: true, supportedLngs: ["en", "es", "pt", "de", "zh"], nonExplicitSupportedLngs: true, fallbackLng: "en", diff --git a/DashAI/front/src/utils/jobPoller.js b/DashAI/front/src/utils/jobPoller.js index 275e693f8..465bec9e8 100644 --- a/DashAI/front/src/utils/jobPoller.js +++ b/DashAI/front/src/utils/jobPoller.js @@ -1,6 +1,8 @@ import { getJobs, isQueueEmpty, getJobChanges } from "../api/job"; const POLL_INTERVAL = 1000; // Default polling interval (2 seconds) +const HIDDEN_POLL_INTERVAL = 10000; +const STALLED_POLL_TIMEOUT = 10000; // Central state const state = { @@ -11,6 +13,8 @@ const state = { lastFetchTime: null, // Last successful fetch time lastCursor: null, // Last cursor for job changes lastCompletionTime: null, // Last time a job was completed + inFlight: 0, + lastPollStart: 0, }; export const FAILED_JOB_STATUSES = ["error", "cancelled", "killed"]; @@ -34,9 +38,22 @@ export function startJobPoller() { // Poll immediately and then at regular intervals pollJobs(); - state.intervalId = setInterval(pollJobs, POLL_INTERVAL); + state.intervalId = setInterval(pollOnTick, POLL_INTERVAL); } +function pollOnTick() { + const sinceLastPoll = Date.now() - state.lastPollStart; + if (state.inFlight > 0 && sinceLastPoll < STALLED_POLL_TIMEOUT) return; + if (document.hidden && sinceLastPoll < HIDDEN_POLL_INTERVAL) return; + pollJobs(); +} + +document.addEventListener("visibilitychange", () => { + if (!document.hidden && state.active && state.inFlight === 0) { + pollJobs(); + } +}); + /** * Stop the global job polling system */ @@ -63,6 +80,8 @@ function hasActiveJobs(jobs) { * Main polling function that checks all jobs */ async function pollJobs() { + state.inFlight += 1; + state.lastPollStart = Date.now(); try { if (state.subscribers.size === 0 && state.jobWatchers.size === 0) { const isEmpty = await isQueueEmpty(); @@ -156,6 +175,8 @@ async function pollJobs() { } } catch (error) { console.error("[JobPoller] Error polling jobs:", error); + } finally { + state.inFlight -= 1; } } diff --git a/DashAI/front/vite.config.mjs b/DashAI/front/vite.config.mjs index aec0e90c9..c84905d93 100644 --- a/DashAI/front/vite.config.mjs +++ b/DashAI/front/vite.config.mjs @@ -23,6 +23,17 @@ export default defineConfig({ build: { outDir: "build", sourcemap: false, + rollupOptions: { + output: { + manualChunks(id) { + const locale = id.match(/\/locales\/([a-z]+)\/[^/]+\.json$/); + if (locale && locale[1] !== "en") { + return `locale-${locale[1]}`; + } + return undefined; + }, + }, + }, }, optimizeDeps: { esbuildOptions: { diff --git a/tests/back/test_main.py b/tests/back/test_main.py index c0e67b2f3..71bce1544 100644 --- a/tests/back/test_main.py +++ b/tests/back/test_main.py @@ -12,3 +12,77 @@ def test_app_front(tmp_path): response = client.get("/app/") assert response.status_code == 200 + + +def test_hashed_assets_are_cached_as_immutable(tmp_path, monkeypatch): + """Vite names every file under ``assets/`` after its content hash. + + A new build writes new names, so the browser can keep those files for good + and skip revalidating them on every launch. Other files keep their + default headers, since their names do not change between builds. + """ + build = tmp_path / "build" + (build / "assets").mkdir(parents=True) + (build / "index.html").write_text("") + (build / "assets" / "index-abc123.js").write_text("console.log(1);") + (build / "manifest.json").write_text("{}") + monkeypatch.setenv("FRONT_BUILD_PATH", str(build)) + client = TestClient( + create_app( + local_path=tmp_path / "data", + logging_level="ERROR", + enable_seeding=False, + ) + ) + + asset = client.get("/assets/index-abc123.js") + assert asset.status_code == 200 + assert asset.headers["cache-control"] == "public, max-age=31536000, immutable" + + manifest = client.get("/manifest.json") + assert manifest.status_code == 200 + assert "cache-control" not in manifest.headers + + index = client.get("/app/") + assert index.headers["cache-control"] == "no-cache" + + +def test_asset_scripts_and_styles_are_gzipped_when_accepted(tmp_path, monkeypatch): + """FastAPI serves the build without compression of its own. + + Scripts and styles under ``assets/`` are sent gzip compressed to clients + that accept it and as they are to clients that do not; other asset types + such as fonts are already compressed and are never gzipped again. + """ + script = b"export const value = 1;\n" * 200 + build = tmp_path / "build" + (build / "assets").mkdir(parents=True) + (build / "index.html").write_text("") + (build / "assets" / "index-abc123.js").write_bytes(script) + (build / "assets" / "font-abc123.woff2").write_bytes(b"woff2") + monkeypatch.setenv("FRONT_BUILD_PATH", str(build)) + client = TestClient( + create_app( + local_path=tmp_path / "data", + logging_level="ERROR", + enable_seeding=False, + ) + ) + + gzipped = client.get("/assets/index-abc123.js", headers={"Accept-Encoding": "gzip"}) + assert gzipped.status_code == 200 + assert gzipped.headers["content-encoding"] == "gzip" + assert gzipped.headers["content-type"].startswith("text/javascript") + assert gzipped.headers["vary"] == "Accept-Encoding" + assert int(gzipped.headers["content-length"]) < len(script) + assert gzipped.content == script + + plain = client.get( + "/assets/index-abc123.js", headers={"Accept-Encoding": "identity"} + ) + assert "content-encoding" not in plain.headers + assert plain.content == script + + font = client.get("/assets/font-abc123.woff2", headers={"Accept-Encoding": "gzip"}) + assert "content-encoding" not in font.headers + assert font.content == b"woff2"