OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
feat: add react doctor to the ci (#1984)
Mike Fortmand305dddafc58
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.ymlindex cf6a7b12d..a1275650e 100644--- a/.github/workflows/codeql.yml+++ b/.github/workflows/codeql.yml@@ -30,7 +30,7 @@ jobs:steps:- name: Checkout repository- uses: actions/checkout@v6+ uses: actions/checkout@v4# Initializes the CodeQL tools for scanning.- name: Initialize CodeQLdiff --git a/.github/workflows/lint-frontend.yml b/.github/workflows/lint-frontend.ymlindex 0e7a9d70c..b032d750c 100644--- a/.github/workflows/lint-frontend.yml+++ b/.github/workflows/lint-frontend.yml@@ -48,3 +48,33 @@ jobs:- name: TypeScript type checkworking-directory: frontendrun: npm run typecheck++ react-doctor:+ name: React Doctor+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ with:+ persist-credentials: false++ - name: Set up Node.js+ uses: actions/setup-node@v4+ with:+ node-version: '20'+ cache: 'npm'+ cache-dependency-path: frontend/package-lock.json++ - name: Install dependencies+ working-directory: frontend+ run: npm ci++ - name: React Doctor score check+ working-directory: frontend+ run: |+ SCORE=$(npx -y [email protected] --score --yes)+ echo "React Doctor score: $SCORE"+ if [ "$SCORE" -lt 40 ]; then+ echo "::error::React Doctor score $SCORE is below the minimum threshold of 40"+ npx -y [email protected] --verbose --yes+ exit 1+ fidiff --git a/.github/workflows/react-doctor.yml b/.github/workflows/react-doctor.ymlnew file mode 100644index 000000000..1a15cb44e--- /dev/null+++ b/.github/workflows/react-doctor.yml@@ -0,0 +1,52 @@+# React Doctor — finds security, performance, correctness, accessibility,+# bundle-size, and architecture issues in React codebases.+#+# Docs: https://www.react.doctor/ci+# Source: https://github.com/millionco/react-doctor++name: React Doctor++on:+ # Scans the PR's changed files and posts a sticky summary comment listing only the new issues introduced relative to the merge base of the target branch.+ pull_request:+ types: [opened, synchronize, reopened, ready_for_review]+ # Scans `main` on every push to track the health-score trend and catch regressions that slipped past PR review.+ push:+ branches: ["main"]++permissions:+ contents: read+ pull-requests: write+ issues: write+ statuses: write++# Cancels any in-flight scan for the same PR (or branch, on push) the moment a new commit arrives, so reviewers only ever see the latest run.+concurrency:+ group: react-doctor-${{ github.event.pull_request.number || github.ref }}+ cancel-in-progress: true++jobs:+ react-doctor:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0++ - uses: millionco/react-doctor@v2+ with:+ directory: frontend+ version: "0.5.8"+ # Advisory by default: React Doctor reports findings on every PR — a+ # sticky summary comment, inline review comments, and a commit status+ # with the health score — but never fails the check, so it won't red-X+ # a teammate's PR on day one. When your team trusts the signal, graduate+ # the gate: uncomment the block below and set blocking to "error" (fail+ # on new error-severity findings) or "warning" (fail on any finding).+ # Full reference: https://www.react.doctor/ci+ # blocking: error # Gate level: "none" (advisory, the default) | "warning" | "error"+ # scope: full # On PRs, scan the whole project instead of just changed files+ # comment: false # Disable the sticky PR summary comment+ # review-comments: false # Disable inline review comments on changed lines+ # commit-status: false # Disable the commit status (score + counts, links to the run)+ # project: "web,admin" # In a monorepo, scan specific workspace project(s)diff --git a/frontend/app/api/mutations/useCancelTaskMutation.ts b/frontend/app/api/mutations/useCancelTaskMutation.tsindex de12fc372..5727422b6 100644--- a/frontend/app/api/mutations/useCancelTaskMutation.ts+++ b/frontend/app/api/mutations/useCancelTaskMutation.ts@@ -15,6 +15,21 @@ export interface CancelTaskResponse {task_id: string;}+async function cancelTask(+ variables: CancelTaskRequest,+): Promise<CancelTaskResponse> {+ const response = await fetch(`/api/tasks/${variables.taskId}/cancel`, {+ method: "POST",+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.error || "Failed to cancel task");+ }++ return response.json();+}+export const useCancelTaskMutation = (options?: Omit<UseMutationOptions<CancelTaskResponse, Error, CancelTaskRequest>,@@ -23,21 +38,6 @@ export const useCancelTaskMutation = () => {const queryClient = useQueryClient();- async function cancelTask(- variables: CancelTaskRequest,- ): Promise<CancelTaskResponse> {- const response = await fetch(`/api/tasks/${variables.taskId}/cancel`, {- method: "POST",- });-- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));- throw new Error(errorData.error || "Failed to cancel task");- }-- return response.json();- }-const { onSuccess, onError, onSettled, ...restOptions } = options ?? {};return useMutation({diff --git a/frontend/app/api/mutations/useCreateApiKeyMutation.ts b/frontend/app/api/mutations/useCreateApiKeyMutation.tsindex ad79693d8..9caed9477 100644--- a/frontend/app/api/mutations/useCreateApiKeyMutation.ts+++ b/frontend/app/api/mutations/useCreateApiKeyMutation.ts@@ -16,6 +16,25 @@ export interface CreateApiKeyResponse {created_at: string;}+async function createApiKey(+ variables: CreateApiKeyRequest,+): Promise<CreateApiKeyResponse> {+ const response = await fetch("/api/keys", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(variables),+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.error || "Failed to create API key");+ }++ return response.json();+}+export const useCreateApiKeyMutation = (options?: Omit<UseMutationOptions<CreateApiKeyResponse, Error, CreateApiKeyRequest>,@@ -24,25 +43,6 @@ export const useCreateApiKeyMutation = () => {const queryClient = useQueryClient();- async function createApiKey(- variables: CreateApiKeyRequest,- ): Promise<CreateApiKeyResponse> {- const response = await fetch("/api/keys", {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(variables),- });-- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));- throw new Error(errorData.error || "Failed to create API key");- }-- return response.json();- }-return useMutation({mutationFn: createApiKey,onSuccess: (...args) => {diff --git a/frontend/app/api/mutations/useOnboardingMutation.ts b/frontend/app/api/mutations/useOnboardingMutation.tsindex 9f3ebc06b..4cb96dfd8 100644--- a/frontend/app/api/mutations/useOnboardingMutation.ts+++ b/frontend/app/api/mutations/useOnboardingMutation.ts@@ -30,6 +30,25 @@ interface OnboardingResponse {task_id?: string;}+async function submitOnboarding(+ variables: OnboardingVariables,+): Promise<OnboardingResponse> {+ const response = await fetch("/api/onboarding", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(variables),+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || "Failed to complete onboarding");+ }++ return response.json();+}+export const useOnboardingMutation = (options?: Omit<UseMutationOptions<OnboardingResponse, Error, OnboardingVariables>,@@ -40,25 +59,6 @@ export const useOnboardingMutation = (const updateOnboardingMutation = useUpdateOnboardingStateMutation();- async function submitOnboarding(- variables: OnboardingVariables,- ): Promise<OnboardingResponse> {- const response = await fetch("/api/onboarding", {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(variables),- });-- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || "Failed to complete onboarding");- }-- return response.json();- }-return useMutation({mutationFn: submitOnboarding,onSuccess: (data) => {diff --git a/frontend/app/api/mutations/useOnboardingRollbackMutation.ts b/frontend/app/api/mutations/useOnboardingRollbackMutation.tsindex 272193279..127a9c982 100644--- a/frontend/app/api/mutations/useOnboardingRollbackMutation.ts+++ b/frontend/app/api/mutations/useOnboardingRollbackMutation.ts@@ -14,6 +14,32 @@ interface RollbackParams {embedding_only?: boolean;}+async function rollbackOnboarding(+ params: RollbackParams | void,+): Promise<OnboardingRollbackResponse> {+ const requestBody = params || { embedding_only: false };++ const response = await fetch("/api/onboarding/rollback", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(requestBody),+ });++ if (!response.ok) {+ const text = await response.text();+ let message = "Failed to rollback onboarding";+ try {+ const error = JSON.parse(text);+ if (error.error) message = error.error;+ } catch {}+ throw new Error(message);+ }++ return response.json();+}+export const useOnboardingRollbackMutation = (options?: Omit<UseMutationOptions<@@ -26,27 +52,6 @@ export const useOnboardingRollbackMutation = () => {const queryClient = useQueryClient();- async function rollbackOnboarding(- params: RollbackParams | void,- ): Promise<OnboardingRollbackResponse> {- const requestBody = params || { embedding_only: false };-- const response = await fetch("/api/onboarding/rollback", {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(requestBody),- });-- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || "Failed to rollback onboarding");- }-- return response.json();- }-return useMutation({mutationFn: rollbackOnboarding,onSettled: () => {diff --git a/frontend/app/api/mutations/useRetryTaskMutation.ts b/frontend/app/api/mutations/useRetryTaskMutation.tsindex 7e17ebc20..cb0e7c060 100644--- a/frontend/app/api/mutations/useRetryTaskMutation.ts+++ b/frontend/app/api/mutations/useRetryTaskMutation.ts@@ -32,6 +32,32 @@ export interface RetryTaskResponse {error?: string;}+async function retryTask(+ variables: RetryTaskRequest,+): Promise<RetryTaskResponse> {+ const body = JSON.stringify(+ variables.filePaths != null ? { file_paths: variables.filePaths } : {},+ );++ const response = await fetch(`/api/tasks/${variables.taskId}/retry`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body,+ });++ const payload = (await response+ .json()+ .catch(() => ({}))) as RetryTaskResponse;++ if (!response.ok) {+ throw new Error(+ payload.message || payload.error || "Failed to retry task files",+ );+ }++ return payload;+}+export const useRetryTaskMutation = (options?: Omit<UseMutationOptions<RetryTaskResponse, Error, RetryTaskRequest>,@@ -40,32 +66,6 @@ export const useRetryTaskMutation = () => {const queryClient = useQueryClient();- async function retryTask(- variables: RetryTaskRequest,- ): Promise<RetryTaskResponse> {- const body = JSON.stringify(- variables.filePaths != null ? { file_paths: variables.filePaths } : {},- );-- const response = await fetch(`/api/tasks/${variables.taskId}/retry`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body,- });-- const payload = (await response- .json()- .catch(() => ({}))) as RetryTaskResponse;-- if (!response.ok) {- throw new Error(- payload.message || payload.error || "Failed to retry task files",- );- }-- return payload;- }-const { onSuccess, onError, onSettled, ...restOptions } = options ?? {};return useMutation({diff --git a/frontend/app/api/mutations/useRevokeApiKeyMutation.ts b/frontend/app/api/mutations/useRevokeApiKeyMutation.tsindex b1ef8b0d2..95b1185bc 100644--- a/frontend/app/api/mutations/useRevokeApiKeyMutation.ts+++ b/frontend/app/api/mutations/useRevokeApiKeyMutation.ts@@ -12,6 +12,21 @@ export interface RevokeApiKeyResponse {success: boolean;}+async function revokeApiKey(+ variables: RevokeApiKeyRequest,+): Promise<RevokeApiKeyResponse> {+ const response = await fetch(`/api/keys/${variables.key_id}`, {+ method: "DELETE",+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.error || "Failed to revoke API key");+ }++ return response.json();+}+export const useRevokeApiKeyMutation = (options?: Omit<UseMutationOptions<RevokeApiKeyResponse, Error, RevokeApiKeyRequest>,@@ -20,21 +35,6 @@ export const useRevokeApiKeyMutation = () => {const queryClient = useQueryClient();- async function revokeApiKey(- variables: RevokeApiKeyRequest,- ): Promise<RevokeApiKeyResponse> {- const response = await fetch(`/api/keys/${variables.key_id}`, {- method: "DELETE",- });-- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));- throw new Error(errorData.error || "Failed to revoke API key");- }-- return response.json();- }-return useMutation({mutationFn: revokeApiKey,onSuccess: (...args) => {diff --git a/frontend/app/api/mutations/useSyncConnector.ts b/frontend/app/api/mutations/useSyncConnector.tsindex 25426e32b..287aa3e5d 100644--- a/frontend/app/api/mutations/useSyncConnector.ts+++ b/frontend/app/api/mutations/useSyncConnector.ts@@ -154,8 +154,24 @@ const syncAllConnectorsPreview = async (): Promise<SyncAllPreviewResponse> => {return response.json();};-export const useSyncConnectorPreview = () =>- useMutation({ mutationFn: syncConnectorPreview });+export const useSyncConnectorPreview = () => {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: syncConnectorPreview,+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ["tasks"], exact: false });+ },+ });+};-export const useSyncAllConnectorsPreview = () =>- useMutation({ mutationFn: syncAllConnectorsPreview });+export const useSyncAllConnectorsPreview = () => {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: syncAllConnectorsPreview,+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ["tasks"], exact: false });+ },+ });+};diff --git a/frontend/app/api/mutations/useUpdateSettingsMutation.ts b/frontend/app/api/mutations/useUpdateSettingsMutation.tsindex 569a105b6..d2c9130e4 100644--- a/frontend/app/api/mutations/useUpdateSettingsMutation.ts+++ b/frontend/app/api/mutations/useUpdateSettingsMutation.ts@@ -87,6 +87,25 @@ export interface UpdateSettingsResponse {settings: Settings;}+async function updateSettings(+ variables: UpdateSettingsRequest,+): Promise<UpdateSettingsResponse> {+ const response = await fetch("/api/settings", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(variables),+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new UpdateSettingsError(response.status, errorData);+ }++ return response.json();+}+export const useUpdateSettingsMutation = (options?: Omit<UseMutationOptions<UpdateSettingsResponse, Error, UpdateSettingsRequest>,@@ -96,25 +115,6 @@ export const useUpdateSettingsMutation = (const queryClient = useQueryClient();const { refetch: refetchModels } = useGetCurrentProviderModelsQuery();- async function updateSettings(- variables: UpdateSettingsRequest,- ): Promise<UpdateSettingsResponse> {- const response = await fetch("/api/settings", {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(variables),- });-- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));- throw new UpdateSettingsError(response.status, errorData);- }-- return response.json();- }-return useMutation({mutationFn: updateSettings,onSuccess: (...args) => {diff --git a/frontend/app/api/queries/useDoclingHealthQuery.ts b/frontend/app/api/queries/useDoclingHealthQuery.tsindex e0ba5dcfd..5e77eecc1 100644--- a/frontend/app/api/queries/useDoclingHealthQuery.ts+++ b/frontend/app/api/queries/useDoclingHealthQuery.ts@@ -9,6 +9,36 @@ export interface DoclingHealthResponse {message?: string;}+async function checkDoclingHealth(): Promise<DoclingHealthResponse> {+ try {+ const response = await fetch("/api/docling/health", {+ method: "GET",+ headers: {+ "Content-Type": "application/json",+ },+ });++ if (response.ok) {+ return { status: "healthy" };+ } else if (response.status === 503) {+ return {+ status: "unhealthy",+ message: `Health check failed with status: ${response.status}`,+ };+ } else {+ return {+ status: "unhealthy",+ message: `Health check failed with status: ${response.status}`,+ };+ }+ } catch (error) {+ return {+ status: "backend-unavailable",+ message: error instanceof Error ? error.message : "Connection failed",+ };+ }+}+export const useDoclingHealthQuery = (options?: Omit<UseQueryOptions<DoclingHealthResponse>,@@ -17,40 +47,6 @@ export const useDoclingHealthQuery = () => {const queryClient = useQueryClient();- async function checkDoclingHealth(): Promise<DoclingHealthResponse> {- try {- // Call backend proxy endpoint instead of direct localhost- const response = await fetch("/api/docling/health", {- method: "GET",- headers: {- "Content-Type": "application/json",- },- });-- if (response.ok) {- return { status: "healthy" };- } else if (response.status === 503) {- // Backend is up but docling is down (backend returns 503 for docling issues)- return {- status: "unhealthy",- message: `Health check failed with status: ${response.status}`,- };- } else {- // Other backend errors - treat as docling unhealthy- return {- status: "unhealthy",- message: `Health check failed with status: ${response.status}`,- };- }- } catch (error) {- // Network error - backend is likely down, don't show docling banner- return {- status: "backend-unavailable",- message: error instanceof Error ? error.message : "Connection failed",- };- }- }-return useQuery({queryKey: ["docling-health"],diff --git a/frontend/app/api/queries/useGetAllFiltersQuery.ts b/frontend/app/api/queries/useGetAllFiltersQuery.tsindex 2e9d64ace..2bcf54933 100644--- a/frontend/app/api/queries/useGetAllFiltersQuery.ts+++ b/frontend/app/api/queries/useGetAllFiltersQuery.ts@@ -5,26 +5,25 @@ import {} from "@tanstack/react-query";import type { KnowledgeFilter } from "./useGetFiltersSearchQuery";+async function getAllFilters(): Promise<KnowledgeFilter[]> {+ const response = await fetch("/api/knowledge-filter/search", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ query: "", limit: 1000 }),+ });++ const json = await response.json();+ if (!response.ok || !json.success) {+ return [];+ }+ return (json.filters || []) as KnowledgeFilter[];+}+export const useGetAllFiltersQuery = (options?: Omit<UseQueryOptions<KnowledgeFilter[]>, "queryKey" | "queryFn">,) => {const queryClient = useQueryClient();- async function getAllFilters(): Promise<KnowledgeFilter[]> {- const response = await fetch("/api/knowledge-filter/search", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ query: "", limit: 1000 }), // Fetch all filters- });-- const json = await response.json();- if (!response.ok || !json.success) {- // ensure we always return a KnowledgeFilter[] to satisfy the return type- return [];- }- return (json.filters || []) as KnowledgeFilter[];- }-return useQuery<KnowledgeFilter[]>({queryKey: ["knowledge-filters", "all"],diff --git a/frontend/app/api/queries/useGetApiKeysQuery.ts b/frontend/app/api/queries/useGetApiKeysQuery.tsindex 60803ec5b..f0f585c02 100644--- a/frontend/app/api/queries/useGetApiKeysQuery.ts+++ b/frontend/app/api/queries/useGetApiKeysQuery.ts@@ -12,17 +12,17 @@ export interface GetApiKeysResponse {keys: ApiKey[];}+async function getApiKeys(): Promise<GetApiKeysResponse> {+ const response = await fetch("/api/keys");+ if (response.ok) {+ return await response.json();+ }+ throw new Error("Failed to fetch API keys");+}+export const useGetApiKeysQuery = (options?: Omit<UseQueryOptions<GetApiKeysResponse>, "queryKey" | "queryFn">,) => {- async function getApiKeys(): Promise<GetApiKeysResponse> {- const response = await fetch("/api/keys");- if (response.ok) {- return await response.json();- }- throw new Error("Failed to fetch API keys");- }-return useQuery({queryKey: ["api-keys"],queryFn: getApiKeys,diff --git a/frontend/app/api/queries/useGetSearchQuery.ts b/frontend/app/api/queries/useGetSearchQuery.tsindex 6fdc4505a..9d94f9e00 100644--- a/frontend/app/api/queries/useGetSearchQuery.ts+++ b/frontend/app/api/queries/useGetSearchQuery.ts@@ -83,6 +83,20 @@ const EMPTY_SEARCH_RESULT: SearchResult = { files: [], warnings: [] };export { EMPTY_SEARCH_RESULT };+const getFileIdentity = (chunk: ChunkResult): string => {+ const normalizedFilename = chunk.filename?.trim();+ if (normalizedFilename) {+ return normalizedFilename;+ }++ const normalizedSourceUrl = chunk.source_url?.trim();+ if (normalizedSourceUrl) {+ return normalizedSourceUrl;+ }++ return "Untitled source";+};+export const useGetSearchQuery = (query: string,queryData?: ParsedQueryData | null,@@ -92,19 +106,6 @@ export const useGetSearchQuery = (>,) => {const queryClient = useQueryClient();- const getFileIdentity = (chunk: ChunkResult): string => {- const normalizedFilename = chunk.filename?.trim();- if (normalizedFilename) {- return normalizedFilename;- }-- const normalizedSourceUrl = chunk.source_url?.trim();- if (normalizedSourceUrl) {- return normalizedSourceUrl;- }-- return "Untitled source";- };// Normalize the query to match what will actually be searchedconst effectiveQuery = query || queryData?.query || "*";diff --git a/frontend/app/api/queries/useGetSettingsQuery.ts b/frontend/app/api/queries/useGetSettingsQuery.tsindex 063af2b0c..16158ec6e 100644--- a/frontend/app/api/queries/useGetSettingsQuery.ts+++ b/frontend/app/api/queries/useGetSettingsQuery.ts@@ -81,21 +81,20 @@ export interface Settings {environment?: string;}+async function getSettings(): Promise<Settings> {+ const response = await fetch("/api/settings");+ if (response.ok) {+ return await response.json();+ } else {+ throw new Error("Failed to fetch settings");+ }+}+export const useGetSettingsQuery = (options?: Omit<UseQueryOptions<Settings>, "queryKey" | "queryFn">,) => {const queryClient = useQueryClient();- async function getSettings(): Promise<Settings> {- const response = await fetch("/api/settings");- if (response.ok) {- // Merge with defaults to ensure all properties exist- return await response.json();- } else {- throw new Error("Failed to fetch settings");- }- }-return useQuery({queryKey: ["settings"],diff --git a/frontend/app/api/queries/useGetTasksQuery.ts b/frontend/app/api/queries/useGetTasksQuery.tsindex 9beeee494..5aa71a7ca 100644--- a/frontend/app/api/queries/useGetTasksQuery.ts+++ b/frontend/app/api/queries/useGetTasksQuery.ts@@ -82,22 +82,22 @@ export interface TasksResponse {export const TASKS_QUERY_KEY = ["tasks", "enhanced"] as const;+async function getTasks(): Promise<Task[]> {+ const response = await fetch("/api/tasks/enhanced");++ if (!response.ok) {+ throw new Error("Failed to fetch tasks");+ }++ const data: TasksResponse = await response.json();+ return data.tasks || [];+}+export const useGetTasksQuery = (options?: Omit<UseQueryOptions<Task[]>, "queryKey" | "queryFn">,) => {const queryClient = useQueryClient();- async function getTasks(): Promise<Task[]> {- const response = await fetch("/api/tasks/enhanced");-- if (!response.ok) {- throw new Error("Failed to fetch tasks");- }-- const data: TasksResponse = await response.json();- return data.tasks || [];- }-return useQuery({queryKey: [...TASKS_QUERY_KEY],diff --git a/frontend/app/chat/_components/assistant-message.tsx b/frontend/app/chat/_components/assistant-message.tsxindex d32188b25..285f1f1bc 100644--- a/frontend/app/chat/_components/assistant-message.tsx+++ b/frontend/app/chat/_components/assistant-message.tsx@@ -17,11 +17,13 @@ import type {FunctionCall,TokenUsage as TokenUsageType,} from "../_types/types";-import { FunctionCallsContainer } from "./function-calls";+import { FunctionCallsContainer } from "./function-calls/container";import { Message } from "./message";import MessageActions from "./message-actions";import { TokenUsage } from "./token-usage";+const EMPTY_FUNCTION_CALLS: FunctionCall[] = [];+interface AssistantMessageProps {content: string;functionCalls?: FunctionCall[];@@ -43,7 +45,7 @@ interface AssistantMessageProps {export function AssistantMessage({content,- functionCalls = [],+ functionCalls = EMPTY_FUNCTION_CALLS,messageIndex,expandedFunctionCalls,onToggle,diff --git a/frontend/app/knowledge/page.tsx b/frontend/app/knowledge/page.tsxindex 46d2d5f80..f572bee4f 100644--- a/frontend/app/knowledge/page.tsx+++ b/frontend/app/knowledge/page.tsx@@ -230,19 +230,23 @@ function SearchPage() {]),);- const mostRecent = [...candidates].sort((a, b) => {- const aMs =- taskTimestampMsById.get(a.task_id) ??- parseTimestampMs(a.updated_at) ??- parseTimestampMs(a.created_at) ??- 0;- const bMs =- taskTimestampMsById.get(b.task_id) ??- parseTimestampMs(b.updated_at) ??- parseTimestampMs(b.created_at) ??- 0;- return bMs - aMs;- })[0];+ const mostRecent = candidates.reduce(+ (best, cur) => {+ const curMs =+ taskTimestampMsById.get(cur.task_id) ??+ parseTimestampMs(cur.updated_at) ??+ parseTimestampMs(cur.created_at) ??+ 0;+ if (!best) return cur;+ const bestMs =+ taskTimestampMsById.get(best.task_id) ??+ parseTimestampMs(best.updated_at) ??+ parseTimestampMs(best.created_at) ??+ 0;+ return curMs > bestMs ? cur : best;+ },+ undefined as (typeof candidates)[0] | undefined,+ );return mostRecent?.task_id || null;},diff --git a/frontend/app/settings/_components/s3-settings-form.tsx b/frontend/app/settings/_components/s3-settings-form.tsxindex 523e8cf64..a9fe98ec6 100644--- a/frontend/app/settings/_components/s3-settings-form.tsx+++ b/frontend/app/settings/_components/s3-settings-form.tsx@@ -67,9 +67,7 @@ export function S3SettingsForm({id="s3-access-key"type="password"placeholder={- accessKeySet- ? "•••••••• (loaded from env)"- : "AKIAIOSFODNN7EXAMPLE"+ accessKeySet ? "•••••••• (loaded from env)" : "Your access key ID"}autoComplete="off"/>@@ -91,7 +89,7 @@ export function S3SettingsForm({placeholder={secretKeySet? "•••••••• (loaded from env)"- : "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"+ : "Your secret access key"}autoComplete="off"/>diff --git a/frontend/components/cloud-picker/unified-cloud-picker.tsx b/frontend/components/cloud-picker/unified-cloud-picker.tsxindex ed6f6de95..c2e3498e8 100644--- a/frontend/components/cloud-picker/unified-cloud-picker.tsx+++ b/frontend/components/cloud-picker/unified-cloud-picker.tsx@@ -13,10 +13,12 @@ import {UnifiedCloudPickerProps,} from "./types";+const EMPTY_FILES: CloudFile[] = [];+export const UnifiedCloudPicker = ({provider,onFileSelected,- selectedFiles = [],+ selectedFiles = EMPTY_FILES,isAuthenticated,isIngesting,accessToken,diff --git a/frontend/components/dev-role-toggle.tsx b/frontend/components/dev-role-toggle.tsxindex 504e6ea40..6e57374fb 100644--- a/frontend/components/dev-role-toggle.tsx+++ b/frontend/components/dev-role-toggle.tsx@@ -20,10 +20,9 @@ function parseApiError(if (typeof detail === "string") return detail;if (Array.isArray(detail)) {const msg = detail- .map((d) =>- typeof d === "object" && d && "msg" in d ? String(d.msg) : "",+ .flatMap((d) =>+ typeof d === "object" && d && "msg" in d ? [String(d.msg)] : [],)- .filter(Boolean).join("; ");if (msg) return msg;}diff --git a/frontend/components/knowledge-dropdown.tsx b/frontend/components/knowledge-dropdown.tsxindex 6caf462e4..f6d1c9a9b 100644--- a/frontend/components/knowledge-dropdown.tsx+++ b/frontend/components/knowledge-dropdown.tsx@@ -852,8 +852,6 @@ export function KnowledgeDropdown() {type="file"// @ts-ignore - webkitdirectory is not in TypeScript types but is widely supportedwebkitdirectory=""- // @ts-ignore- directory=""multipleonChange={handleFolderSelect}className="hidden"diff --git a/frontend/components/knowledge-filter-list.tsx b/frontend/components/knowledge-filter-list.tsxindex 455cf399d..957c112e5 100644--- a/frontend/components/knowledge-filter-list.tsx+++ b/frontend/components/knowledge-filter-list.tsx@@ -31,6 +31,22 @@ interface KnowledgeFilterListProps {onFilterSelect: (filter: KnowledgeFilter | null) => void;}+const parseQueryData = (queryData: string): ParsedQueryData => {+ const parsed = JSON.parse(queryData);+ return {+ query: parsed.query ?? "",+ filters: {+ data_sources: parsed.filters?.data_sources ?? ["*"],+ document_types: parsed.filters?.document_types ?? ["*"],+ owners: parsed.filters?.owners ?? ["*"],+ },+ limit: parsed.limit ?? 10,+ scoreThreshold: parsed.scoreThreshold ?? 0,+ color: parsed.color ?? "zinc",+ icon: parsed.icon ?? "filter",+ };+};+export function KnowledgeFilterList({selectedFilter,onFilterSelect,@@ -56,23 +72,6 @@ export function KnowledgeFilterList({startCreateMode();};- const parseQueryData = (queryData: string): ParsedQueryData => {- const parsed = JSON.parse(queryData);- // Provide defaults for missing fields to handle API-created filters- return {- query: parsed.query ?? "",- filters: {- data_sources: parsed.filters?.data_sources ?? ["*"],- document_types: parsed.filters?.document_types ?? ["*"],- owners: parsed.filters?.owners ?? ["*"],- },- limit: parsed.limit ?? 10,- scoreThreshold: parsed.scoreThreshold ?? 0,- color: parsed.color ?? "zinc",- icon: parsed.icon ?? "filter",- };- };-return (<div className="flex-1 min-h-0 flex flex-col"><div className="px-3 flex-1 min-h-0 flex flex-col">diff --git a/frontend/components/knowledge-filter-panel.tsx b/frontend/components/knowledge-filter-panel.tsxindex 250c6e259..955fa2486 100644--- a/frontend/components/knowledge-filter-panel.tsx+++ b/frontend/components/knowledge-filter-panel.tsx@@ -59,6 +59,16 @@ export const filterAccentClasses: Record<FilterColor, string> = {red: "bg-accent-red text-accent-red-foreground",};+const formatDate = (dateString: string) => {+ return new Date(dateString).toLocaleDateString("en-US", {+ year: "numeric",+ month: "short",+ day: "numeric",+ hour: "2-digit",+ minute: "2-digit",+ });+};+export function KnowledgeFilterPanel() {const {queryOverride,@@ -237,16 +247,6 @@ export function KnowledgeFilterPanel() {}};- const formatDate = (dateString: string) => {- return new Date(dateString).toLocaleDateString("en-US", {- year: "numeric",- month: "short",- day: "numeric",- hour: "2-digit",- minute: "2-digit",- });- };-const handleFilterChange = (facetType: keyof typeof selectedFilters,newValues: string[],diff --git a/frontend/components/navigation.tsx b/frontend/components/navigation.tsxindex fc2a50a51..ea15bfd89 100644--- a/frontend/components/navigation.tsx+++ b/frontend/components/navigation.tsx@@ -522,17 +522,9 @@ export function Navigation({<divclassName="opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 data-[state=open]:text-foreground transition-opacity p-1 hover:bg-accent rounded text-muted-foreground hover:text-foreground ml-2 flex-shrink-0 cursor-pointer"title="More options"- role="button"- tabIndex={0}onClick={(e) => {e.stopPropagation();}}- onKeyDown={(e) => {- if (e.key === "Enter" || e.key === " ") {- e.preventDefault();- e.stopPropagation();- }- }}><EllipsisVertical className="h-4 w-4" /></div>diff --git a/frontend/components/sync-confirm-dialog.tsx b/frontend/components/sync-confirm-dialog.tsxindex 54331ac45..5e887706f 100644--- a/frontend/components/sync-confirm-dialog.tsx+++ b/frontend/components/sync-confirm-dialog.tsx@@ -127,6 +127,20 @@ const normalize = (};};+const OrphanList = ({ list }: { list: OrphanFile[] }) => (+ <ul className="space-y-1 text-sm">+ {list.map((o) => (+ <li+ key={o.document_id}+ className="truncate"+ title={o.filename || o.document_id}+ >+ {o.filename || o.document_id}+ </li>+ ))}+ </ul>+);+const DeletesAlert = ({orphansByType,totalOrphans,@@ -136,20 +150,6 @@ const DeletesAlert = ({totalOrphans: number;isSyncAll: boolean;}) => {- const renderList = (list: OrphanFile[]) => (- <ul className="space-y-1 text-sm">- {list.map((o) => (- <li- key={o.document_id}- className="truncate"- title={o.filename || o.document_id}- >- {o.filename || o.document_id}- </li>- ))}- </ul>- );-const entries = Object.entries(orphansByType);return (@@ -172,7 +172,7 @@ const DeletesAlert = ({<div className="text-xs font-semibold uppercase tracking-wide mb-1">{formatConnectorLabel(type)} ({list.length})</div>- {renderList(list)}+ <OrphanList list={list} />{index < entries.length - 1 ? (<Separator className="mt-3" />) : null}@@ -180,7 +180,9 @@ const DeletesAlert = ({))}</div>) : (- <div className="pr-2">{renderList(entries[0]?.[1] ?? [])}</div>+ <div className="pr-2">+ <OrphanList list={entries[0]?.[1] ?? []} />+ </div>)}</ScrollArea>{totalOrphans > SCROLL_HINT_THRESHOLD ? (diff --git a/frontend/components/task-notification-menu.tsx b/frontend/components/task-notification-menu.tsxindex af491064b..e3dd6ce10 100644--- a/frontend/components/task-notification-menu.tsx+++ b/frontend/components/task-notification-menu.tsx@@ -36,6 +36,106 @@ import {import { parseTimestampMs } from "@/lib/time-utils";import { cn } from "@/lib/utils";+const getTaskIcon = (+ status: Task["status"],+ hasFailedFiles = false,+ isTotalFailure = false,+) => {+ switch (status) {+ case "completed":+ if (hasFailedFiles) {+ if (isTotalFailure) {+ return <XCircle className="size-4 text-destructive" />;+ }+ return <AlertCircle className="h-4 w-4 text-brand-amber" />;+ }+ return <CheckCircle className="h-4 w-4 text-green-500" />;+ case "failed":+ case "error":+ return <XCircle className="size-4 text-destructive" />;+ case "pending":+ return <Clock className="h-4 w-4 text-yellow-500" />;+ case "running":+ case "processing":+ return <Loader2 className="h-4 w-4 text-blue-500 animate-spin" />;+ default:+ return <Clock className="h-4 w-4 text-gray-500" />;+ }+};++const formatTaskProgress = (+ task: Task,+): { basic: string; detailed: TaskProgressDetailed } | null => {+ const total = task.total_files || 0;+ const processed = task.processed_files || 0;+ const successful = task.successful_files || 0;+ const failed = task.failed_files || 0;+ const running = task.running_files || 0;+ const pending = task.pending_files || 0;++ if (total > 0) {+ return {+ basic: `${processed}/${total} files`,+ detailed: {+ total,+ processed,+ successful,+ failed,+ running,+ pending,+ remaining: total - processed,+ },+ };+ }+ return null;+};++const formatDuration = (seconds?: number) => {+ if (!seconds || seconds < 0) return null;++ if (seconds < 60) {+ return `${Math.round(seconds)}s`;+ } else if (seconds < 3600) {+ const mins = Math.floor(seconds / 60);+ const secs = Math.round(seconds % 60);+ return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;+ } else {+ const hours = Math.floor(seconds / 3600);+ const mins = Math.floor((seconds % 3600) / 60);+ return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;+ }+};++const formatRelativeTime = (dateString: string) => {+ let date: Date;++ if (/^\d+$/.test(dateString)) {+ const timestamp = parseInt(dateString);+ date = new Date(timestamp < 10000000000 ? timestamp * 1000 : timestamp);+ } else if (/^\d+\.\d+$/.test(dateString)) {+ const timestamp = parseFloat(dateString);+ date = new Date(timestamp * 1000);+ } else {+ date = new Date(dateString);+ }++ if (isNaN(date.getTime())) {+ console.warn("Invalid date format:", dateString);+ return "Unknown time";+ }++ const now = new Date();+ const diffMs = now.getTime() - date.getTime();+ const diffMinutes = Math.floor(diffMs / 60000);+ const diffHours = Math.floor(diffMs / 3600000);+ const diffDays = Math.floor(diffMs / 86400000);++ if (diffMinutes < 1) return "Just now";+ if (diffMinutes < 60) return `${diffMinutes}m ago`;+ if (diffHours < 24) return `${diffHours}h ago`;+ return `${diffDays}d ago`;+};+export function TaskNotificationMenu() {const isCloudBrand = useIsCloudBrand();const {@@ -110,33 +210,6 @@ export function TaskNotificationMenu() {// Don't render if menu is closedif (!isMenuOpen) return null;- const getTaskIcon = (- status: Task["status"],- hasFailedFiles = false,- isTotalFailure = false,- ) => {- switch (status) {- case "completed":- if (hasFailedFiles) {- if (isTotalFailure) {- return <XCircle className="size-4 text-destructive" />;- }- return <AlertCircle className="h-4 w-4 text-brand-amber" />;- }- return <CheckCircle className="h-4 w-4 text-green-500" />;- case "failed":- case "error":- return <XCircle className="size-4 text-destructive" />;- case "pending":- return <Clock className="h-4 w-4 text-yellow-500" />;- case "running":- case "processing":- return <Loader2 className="h-4 w-4 text-blue-500 animate-spin" />;- default:- return <Clock className="h-4 w-4 text-gray-500" />;- }- };-const pastTaskRowClass = cn("w-full py-mmd px-4 transition-colors hover:bg-muted/60",isCloudBrand ? "border-t border-muted" : "rounded-mmd border border-muted",@@ -249,88 +322,6 @@ export function TaskNotificationMenu() {}};- const formatTaskProgress = (- task: Task,- ): { basic: string; detailed: TaskProgressDetailed } | null => {- const total = task.total_files || 0;- const processed = task.processed_files || 0;- const successful = task.successful_files || 0;- const failed = task.failed_files || 0;- const running = task.running_files || 0;- const pending = task.pending_files || 0;-- if (total > 0) {- return {- basic: `${processed}/${total} files`,- detailed: {- total,- processed,- successful,- failed,- running,- pending,- remaining: total - processed,- },- };- }- return null;- };-- const formatDuration = (seconds?: number) => {- if (!seconds || seconds < 0) return null;-- if (seconds < 60) {- return `${Math.round(seconds)}s`;- } else if (seconds < 3600) {- const mins = Math.floor(seconds / 60);- const secs = Math.round(seconds % 60);- return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;- } else {- const hours = Math.floor(seconds / 3600);- const mins = Math.floor((seconds % 3600) / 60);- return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;- }- };-- const formatRelativeTime = (dateString: string) => {- // Handle different timestamp formats- let date: Date;-- // If it's a number (Unix timestamp), convert it- if (/^\d+$/.test(dateString)) {- const timestamp = parseInt(dateString);- // If it looks like seconds (less than 10^13), convert to milliseconds- date = new Date(timestamp < 10000000000 ? timestamp * 1000 : timestamp);- }- // If it's a decimal number (Unix timestamp with decimals)- else if (/^\d+\.\d+$/.test(dateString)) {- const timestamp = parseFloat(dateString);- // Convert seconds to milliseconds- date = new Date(timestamp * 1000);- }- // Otherwise, try to parse as ISO string or other date format- else {- date = new Date(dateString);- }-- // Check if date is valid- if (isNaN(date.getTime())) {- console.warn("Invalid date format:", dateString);- return "Unknown time";- }-- const now = new Date();- const diffMs = now.getTime() - date.getTime();- const diffMinutes = Math.floor(diffMs / 60000);- const diffHours = Math.floor(diffMs / 3600000);- const diffDays = Math.floor(diffMs / 86400000);-- if (diffMinutes < 1) return "Just now";- if (diffMinutes < 60) return `${diffMinutes}m ago`;- if (diffHours < 24) return `${diffHours}h ago`;- return `${diffDays}d ago`;- };-const cancelTaskButtonClass = cn("h-10 w-full shrink-0 shadow-none",isCloudBranddiff --git a/frontend/components/ui/command.tsx b/frontend/components/ui/command.tsxindex 50a8165f9..040061dc9 100644--- a/frontend/components/ui/command.tsx+++ b/frontend/components/ui/command.tsx@@ -28,7 +28,7 @@ const CommandDialog = ({ children, ...props }: CommandDialogProps) => {return (<Dialog {...props}><DialogContent className="overflow-hidden p-0 shadow-lg">- <Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">+ <Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[data-cmdk-input-wrapper]_svg]:h-5 [&_[data-cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">{children}</Command></DialogContent>@@ -40,7 +40,7 @@ const CommandInput = React.forwardRef<React.ElementRef<typeof CommandPrimitive.Input>,React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>>(({ className, ...props }, ref) => (- <div className="flex items-center border-b px-3" cmdk-input-wrapper="">+ <div className="flex items-center border-b px-3" data-cmdk-input-wrapper=""><Search className="mr-2 h-4 w-4 shrink-0 opacity-50" /><CommandPrimitive.Inputref={ref}diff --git a/frontend/lib/task-utils.ts b/frontend/lib/task-utils.tsindex c2ba96f8d..da0e2f723 100644--- a/frontend/lib/task-utils.ts+++ b/frontend/lib/task-utils.ts@@ -178,7 +178,7 @@ export function sortTaskFileEntries(entries: Array<[string, TaskFileEntry]>,direction: TaskFileNameSort = "asc",): Array<[string, TaskFileEntry]> {- const sorted = [...entries].sort(([pathA, infoA], [pathB, infoB]) =>+ const sorted = entries.toSorted(([pathA, infoA], [pathB, infoB]) =>getTaskFileName(pathA, infoA).localeCompare(getTaskFileName(pathB, infoB),undefined,