Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

linting

Mike Fortman443a46be8ddb
diff --git a/.github/workflows/lint-frontend.yml b/.github/workflows/lint-frontend.yml
new file mode 100644
index 000000000..01711d630
--- /dev/null
+++ b/.github/workflows/lint-frontend.yml
@@ -0,0 +1,29 @@
+name: Frontend Lint
+
+on:
+ pull_request:
+ paths:
+ - 'frontend/**'
+ - '.github/workflows/lint-frontend.yml'
+
+jobs:
+ biome:
+ name: Biome
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - 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: Biome check
+ working-directory: frontend
+ run: npm run lint
diff --git a/frontend/.husky/pre-commit b/frontend/.husky/pre-commit
new file mode 100755
index 000000000..f450749af
--- /dev/null
+++ b/frontend/.husky/pre-commit
@@ -0,0 +1 @@
+cd frontend && npx lint-staged
diff --git a/frontend/app/api/get-query-client.ts b/frontend/app/api/get-query-client.ts
index 4602496c0..a2b26bbaf 100644
--- a/frontend/app/api/get-query-client.ts
+++ b/frontend/app/api/get-query-client.ts
@@ -1,7 +1,7 @@
import {
- QueryClient,
defaultShouldDehydrateQuery,
isServer,
+ QueryClient,
} from "@tanstack/react-query";
function makeQueryClient() {
diff --git a/frontend/app/api/mutations/useConnectConnectorMutation.ts b/frontend/app/api/mutations/useConnectConnectorMutation.ts
index 9054976c1..893a90086 100644
--- a/frontend/app/api/mutations/useConnectConnectorMutation.ts
+++ b/frontend/app/api/mutations/useConnectConnectorMutation.ts
@@ -3,75 +3,85 @@ import { toast } from "sonner";
import type { Connector } from "../queries/useGetConnectorsQuery";
interface ConnectResponse {
- connection_id: string;
- oauth_config?: {
- authorization_endpoint: string;
- client_id: string;
- scopes: string[];
- redirect_uri: string;
- };
+ connection_id: string;
+ oauth_config?: {
+ authorization_endpoint: string;
+ client_id: string;
+ scopes: string[];
+ redirect_uri: string;
+ };
}
export const useConnectConnectorMutation = () => {
- const queryClient = useQueryClient();
+ const queryClient = useQueryClient();
- return useMutation({
- mutationFn: async ({ connector, redirectUri }: { connector: Connector; redirectUri: string }): Promise<ConnectResponse> => {
- const response = await fetch("/api/auth/init", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- connector_type: connector.type,
- purpose: "data_source",
- name: `${connector.name} Connection`,
- redirect_uri: redirectUri,
- }),
- });
-
- if (!response.ok) {
- const result = await response.json();
- throw new Error(result.error || `Failed to initiate connection for ${connector.name}`);
- }
- return response.json();
+ return useMutation({
+ mutationFn: async ({
+ connector,
+ redirectUri,
+ }: {
+ connector: Connector;
+ redirectUri: string;
+ }): Promise<ConnectResponse> => {
+ const response = await fetch("/api/auth/init", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
},
- onMutate: async ({ connector }) => {
- // Cancel any outgoing refetches
- await queryClient.cancelQueries({ queryKey: ["connectors"] });
+ body: JSON.stringify({
+ connector_type: connector.type,
+ purpose: "data_source",
+ name: `${connector.name} Connection`,
+ redirect_uri: redirectUri,
+ }),
+ });
- // Snapshot the previous value
- const previousConnectors = queryClient.getQueryData<Connector[]>(["connectors"]);
+ if (!response.ok) {
+ const result = await response.json();
+ throw new Error(
+ result.error || `Failed to initiate connection for ${connector.name}`,
+ );
+ }
+ return response.json();
+ },
+ onMutate: async ({ connector }) => {
+ // Cancel any outgoing refetches
+ await queryClient.cancelQueries({ queryKey: ["connectors"] });
- return { previousConnectors };
- },
- onError: (err, { connector }, context) => {
- // Roll back if mutation fails
- if (context?.previousConnectors) {
- queryClient.setQueryData(["connectors"], context.previousConnectors);
- }
- toast.error(err.message);
- },
- onSuccess: (result, { connector }) => {
- if (result.oauth_config) {
- localStorage.setItem("connecting_connector_id", result.connection_id);
- localStorage.setItem("connecting_connector_type", connector.type);
- localStorage.setItem("auth_purpose", "data_source");
+ // Snapshot the previous value
+ const previousConnectors = queryClient.getQueryData<Connector[]>([
+ "connectors",
+ ]);
- const authUrl =
- `${result.oauth_config.authorization_endpoint}?` +
- `client_id=${result.oauth_config.client_id}&` +
- `response_type=code&` +
- `scope=${result.oauth_config.scopes.join(" ")}&` +
- `redirect_uri=${encodeURIComponent(
- result.oauth_config.redirect_uri,
- )}&` +
- `access_type=offline&` +
- `prompt=select_account&` +
- `state=${result.connection_id}`;
+ return { previousConnectors };
+ },
+ onError: (err, { connector }, context) => {
+ // Roll back if mutation fails
+ if (context?.previousConnectors) {
+ queryClient.setQueryData(["connectors"], context.previousConnectors);
+ }
+ toast.error(err.message);
+ },
+ onSuccess: (result, { connector }) => {
+ if (result.oauth_config) {
+ localStorage.setItem("connecting_connector_id", result.connection_id);
+ localStorage.setItem("connecting_connector_type", connector.type);
+ localStorage.setItem("auth_purpose", "data_source");
- window.location.href = authUrl;
- }
- },
- });
+ const authUrl =
+ `${result.oauth_config.authorization_endpoint}?` +
+ `client_id=${result.oauth_config.client_id}&` +
+ `response_type=code&` +
+ `scope=${result.oauth_config.scopes.join(" ")}&` +
+ `redirect_uri=${encodeURIComponent(
+ result.oauth_config.redirect_uri,
+ )}&` +
+ `access_type=offline&` +
+ `prompt=select_account&` +
+ `state=${result.connection_id}`;
+
+ window.location.href = authUrl;
+ }
+ },
+ });
};
diff --git a/frontend/app/api/mutations/useDisconnectConnectorMutation.ts b/frontend/app/api/mutations/useDisconnectConnectorMutation.ts
index c3baf0d0d..71b31d7ff 100644
--- a/frontend/app/api/mutations/useDisconnectConnectorMutation.ts
+++ b/frontend/app/api/mutations/useDisconnectConnectorMutation.ts
@@ -3,53 +3,61 @@ import { toast } from "sonner";
import type { Connector } from "../queries/useGetConnectorsQuery";
export const useDisconnectConnectorMutation = () => {
- const queryClient = useQueryClient();
+ const queryClient = useQueryClient();
- return useMutation({
- mutationFn: async (connector: Connector) => {
- const response = await fetch(`/api/connectors/${connector.type}/disconnect`, {
- method: "DELETE",
- });
-
- if (!response.ok) {
- const result = await response.json();
- throw new Error(result.error || `Failed to disconnect ${connector.name}`);
- }
- return response.json();
+ return useMutation({
+ mutationFn: async (connector: Connector) => {
+ const response = await fetch(
+ `/api/connectors/${connector.type}/disconnect`,
+ {
+ method: "DELETE",
},
- onMutate: async (connector) => {
- // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
- await queryClient.cancelQueries({ queryKey: ["connectors"] });
+ );
- // Snapshot the previous value
- const previousConnectors = queryClient.getQueryData<Connector[]>(["connectors"]);
+ if (!response.ok) {
+ const result = await response.json();
+ throw new Error(
+ result.error || `Failed to disconnect ${connector.name}`,
+ );
+ }
+ return response.json();
+ },
+ onMutate: async (connector) => {
+ // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
+ await queryClient.cancelQueries({ queryKey: ["connectors"] });
- // Optimistically update to the new value
- if (previousConnectors) {
- queryClient.setQueryData<Connector[]>(["connectors"],
- previousConnectors.map((c) =>
- c.type === connector.type
- ? { ...c, status: "not_connected", connectionId: undefined }
- : c
- )
- );
- }
+ // Snapshot the previous value
+ const previousConnectors = queryClient.getQueryData<Connector[]>([
+ "connectors",
+ ]);
- return { previousConnectors };
- },
- onError: (err, connector, context) => {
- // If the mutation fails, use the context returned from onMutate to roll back
- if (context?.previousConnectors) {
- queryClient.setQueryData(["connectors"], context.previousConnectors);
- }
- toast.error(`Failed to disconnect ${connector.name}: ${err.message}`);
- },
- onSuccess: (_, connector) => {
- toast.success(`${connector.name} disconnected`);
- },
- onSettled: () => {
- // Always refetch after error or success to ensure we have the correct data
- queryClient.invalidateQueries({ queryKey: ["connectors"] });
- },
- });
+ // Optimistically update to the new value
+ if (previousConnectors) {
+ queryClient.setQueryData<Connector[]>(
+ ["connectors"],
+ previousConnectors.map((c) =>
+ c.type === connector.type
+ ? { ...c, status: "not_connected", connectionId: undefined }
+ : c,
+ ),
+ );
+ }
+
+ return { previousConnectors };
+ },
+ onError: (err, connector, context) => {
+ // If the mutation fails, use the context returned from onMutate to roll back
+ if (context?.previousConnectors) {
+ queryClient.setQueryData(["connectors"], context.previousConnectors);
+ }
+ toast.error(`Failed to disconnect ${connector.name}: ${err.message}`);
+ },
+ onSuccess: (_, connector) => {
+ toast.success(`${connector.name} disconnected`);
+ },
+ onSettled: () => {
+ // Always refetch after error or success to ensure we have the correct data
+ queryClient.invalidateQueries({ queryKey: ["connectors"] });
+ },
+ });
};
diff --git a/frontend/app/api/mutations/useOnboardingMutation.ts b/frontend/app/api/mutations/useOnboardingMutation.ts
index 4672f4b48..fb8272a8d 100644
--- a/frontend/app/api/mutations/useOnboardingMutation.ts
+++ b/frontend/app/api/mutations/useOnboardingMutation.ts
@@ -33,14 +33,14 @@ export const useOnboardingMutation = (
options?: Omit<
UseMutationOptions<OnboardingResponse, Error, OnboardingVariables>,
"mutationFn"
- >
+ >,
) => {
const queryClient = useQueryClient();
const updateOnboardingMutation = useUpdateOnboardingStateMutation();
async function submitOnboarding(
- variables: OnboardingVariables
+ variables: OnboardingVariables,
): Promise<OnboardingResponse> {
const response = await fetch("/api/onboarding", {
method: "POST",
@@ -70,7 +70,7 @@ export const useOnboardingMutation = (
console.log(
"Saved OpenRAG docs filter ID:",
- data.openrag_docs_filter_id
+ data.openrag_docs_filter_id,
);
}
},
diff --git a/frontend/app/api/mutations/useOnboardingRollbackMutation.ts b/frontend/app/api/mutations/useOnboardingRollbackMutation.ts
index f46f09b8c..b53ded1f7 100644
--- a/frontend/app/api/mutations/useOnboardingRollbackMutation.ts
+++ b/frontend/app/api/mutations/useOnboardingRollbackMutation.ts
@@ -43,4 +43,3 @@ export const useOnboardingRollbackMutation = (
...options,
});
};
-
diff --git a/frontend/app/api/mutations/useUpdateSettingsMutation.ts b/frontend/app/api/mutations/useUpdateSettingsMutation.ts
index f0e6ce586..e1a7e9ddf 100644
--- a/frontend/app/api/mutations/useUpdateSettingsMutation.ts
+++ b/frontend/app/api/mutations/useUpdateSettingsMutation.ts
@@ -3,8 +3,8 @@ import {
useMutation,
useQueryClient,
} from "@tanstack/react-query";
-import type { Settings } from "../queries/useGetSettingsQuery";
import { useGetCurrentProviderModelsQuery } from "../queries/useGetModelsQuery";
+import type { Settings } from "../queries/useGetSettingsQuery";
export interface UpdateSettingsRequest {
// Agent settings
diff --git a/frontend/app/api/queries/useGetAllFiltersQuery.ts b/frontend/app/api/queries/useGetAllFiltersQuery.ts
index 5264d981d..2e9d64ace 100644
--- a/frontend/app/api/queries/useGetAllFiltersQuery.ts
+++ b/frontend/app/api/queries/useGetAllFiltersQuery.ts
@@ -1,36 +1,36 @@
import {
- type UseQueryOptions,
- useQuery,
- useQueryClient,
+ type UseQueryOptions,
+ useQuery,
+ useQueryClient,
} from "@tanstack/react-query";
import type { KnowledgeFilter } from "./useGetFiltersSearchQuery";
export const useGetAllFiltersQuery = (
- options?: Omit<UseQueryOptions<KnowledgeFilter[]>, "queryKey" | "queryFn">,
+ options?: Omit<UseQueryOptions<KnowledgeFilter[]>, "queryKey" | "queryFn">,
) => {
- const queryClient = useQueryClient();
+ 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
- });
+ 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[];
- }
+ 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"],
- queryFn: getAllFilters,
- ...options,
- },
- queryClient,
- );
+ return useQuery<KnowledgeFilter[]>(
+ {
+ queryKey: ["knowledge-filters", "all"],
+ queryFn: getAllFilters,
+ ...options,
+ },
+ queryClient,
+ );
};
diff --git a/frontend/app/api/queries/useGetConnectorTokenQuery.ts b/frontend/app/api/queries/useGetConnectorTokenQuery.ts
index effd76e87..5a8fd4839 100644
--- a/frontend/app/api/queries/useGetConnectorTokenQuery.ts
+++ b/frontend/app/api/queries/useGetConnectorTokenQuery.ts
@@ -1,46 +1,46 @@
-import { useQuery, type UseQueryOptions } from "@tanstack/react-query";
+import { type UseQueryOptions, useQuery } from "@tanstack/react-query";
interface TokenResponse {
- access_token: string;
- expires_in?: number;
- token_type?: string;
- error?: string;
+ access_token: string;
+ expires_in?: number;
+ token_type?: string;
+ error?: string;
}
export const useGetConnectorTokenQuery = (
- {
- connectorType,
- connectionId,
- resource,
- }: {
- connectorType: string;
- connectionId: string | undefined;
- resource?: string;
- },
- options?: Omit<UseQueryOptions<TokenResponse>, "queryKey" | "queryFn">,
+ {
+ connectorType,
+ connectionId,
+ resource,
+ }: {
+ connectorType: string;
+ connectionId: string | undefined;
+ resource?: string;
+ },
+ options?: Omit<UseQueryOptions<TokenResponse>, "queryKey" | "queryFn">,
) => {
- return useQuery({
- queryKey: ["connector-token", connectorType, connectionId, resource],
- queryFn: async (): Promise<TokenResponse> => {
- if (!connectionId) {
- throw new Error("Connection ID is required for fetching token");
- }
+ return useQuery({
+ queryKey: ["connector-token", connectorType, connectionId, resource],
+ queryFn: async (): Promise<TokenResponse> => {
+ if (!connectionId) {
+ throw new Error("Connection ID is required for fetching token");
+ }
- let url = `/api/connectors/${connectorType}/token?connection_id=${connectionId}`;
- if (resource) {
- url += `&resource=${encodeURIComponent(resource)}`;
- }
+ let url = `/api/connectors/${connectorType}/token?connection_id=${connectionId}`;
+ if (resource) {
+ url += `&resource=${encodeURIComponent(resource)}`;
+ }
- const response = await fetch(url);
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.error || "Failed to fetch access token");
- }
+ const response = await fetch(url);
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.error || "Failed to fetch access token");
+ }
- return response.json();
- },
- enabled: !!connectorType && !!connectionId && (options?.enabled ?? true),
- staleTime: 1000 * 60 * 5, // 5 minutes
- ...options,
- });
+ return response.json();
+ },
+ enabled: !!connectorType && !!connectionId && (options?.enabled ?? true),
+ staleTime: 1000 * 60 * 5, // 5 minutes
+ ...options,
+ });
};
diff --git a/frontend/app/api/queries/useGetConnectorsQuery.ts b/frontend/app/api/queries/useGetConnectorsQuery.ts
index 8638fa448..84a197249 100644
--- a/frontend/app/api/queries/useGetConnectorsQuery.ts
+++ b/frontend/app/api/queries/useGetConnectorsQuery.ts
@@ -1,118 +1,118 @@
import { type UseQueryOptions, useQuery } from "@tanstack/react-query";
interface GoogleDriveFile {
- id: string;
- name: string;
- mimeType: string;
- webViewLink?: string;
- iconLink?: string;
+ id: string;
+ name: string;
+ mimeType: string;
+ webViewLink?: string;
+ iconLink?: string;
}
interface OneDriveFile {
- id: string;
- name: string;
- mimeType?: string;
- webUrl?: string;
- driveItem?: {
- file?: { mimeType: string };
- folder?: unknown;
- };
+ id: string;
+ name: string;
+ mimeType?: string;
+ webUrl?: string;
+ driveItem?: {
+ file?: { mimeType: string };
+ folder?: unknown;
+ };
}
export interface Connector {
- id: string;
- name: string;
- description: string;
- icon: string; // The icon name from the API
- status: "not_connected" | "connected" | "error";
- type: string;
- connectionId?: string;
- clientId?: string;
- baseUrl?: string;
- access_token?: string;
- selectedFiles?: GoogleDriveFile[] | OneDriveFile[];
- available?: boolean;
+ id: string;
+ name: string;
+ description: string;
+ icon: string; // The icon name from the API
+ status: "not_connected" | "connected" | "error";
+ type: string;
+ connectionId?: string;
+ clientId?: string;
+ baseUrl?: string;
+ access_token?: string;
+ selectedFiles?: GoogleDriveFile[] | OneDriveFile[];
+ available?: boolean;
}
interface Connection {
- connection_id: string;
- is_active: boolean;
- is_authenticated?: boolean;
- created_at: string;
- last_sync?: string;
- client_id?: string;
- base_url?: string;
+ connection_id: string;
+ is_active: boolean;
+ is_authenticated?: boolean;
+ created_at: string;
+ last_sync?: string;
+ client_id?: string;
+ base_url?: string;
}
export interface GetConnectorsResponse {
- connectors: Connector[];
+ connectors: Connector[];
}
export const useGetConnectorsQuery = (
- options?: Omit<UseQueryOptions<Connector[]>, "queryKey" | "queryFn">,
+ options?: Omit<UseQueryOptions<Connector[]>, "queryKey" | "queryFn">,
) => {
- async function getConnectors(): Promise<Connector[]> {
- const connectorsResponse = await fetch("/api/connectors");
- if (!connectorsResponse.ok) {
- throw new Error("Failed to fetch available connectors");
- }
+ async function getConnectors(): Promise<Connector[]> {
+ const connectorsResponse = await fetch("/api/connectors");
+ if (!connectorsResponse.ok) {
+ throw new Error("Failed to fetch available connectors");
+ }
- const { connectors: connectorsMap } = await connectorsResponse.json();
- const connectorTypes = Object.keys(connectorsMap);
+ const { connectors: connectorsMap } = await connectorsResponse.json();
+ const connectorTypes = Object.keys(connectorsMap);
- const connectorsWithStatus = await Promise.all(
- connectorTypes.map(async (type) => {
- const connectorData = connectorsMap[type];
- const statusResponse = await fetch(`/api/connectors/${type}/status`);
+ const connectorsWithStatus = await Promise.all(
+ connectorTypes.map(async (type) => {
+ const connectorData = connectorsMap[type];
+ const statusResponse = await fetch(`/api/connectors/${type}/status`);
- let status: Connector["status"] = "not_connected";
- let connectionId: string | undefined;
+ let status: Connector["status"] = "not_connected";
+ let connectionId: string | undefined;
- if (statusResponse.ok) {
- const statusData = await statusResponse.json();
- const connections = statusData.connections || [];
- const activeConnection = connections.find(
- (conn: Connection) => conn.is_active && conn.is_authenticated,
- );
+ if (statusResponse.ok) {
+ const statusData = await statusResponse.json();
+ const connections = statusData.connections || [];
+ const activeConnection = connections.find(
+ (conn: Connection) => conn.is_active && conn.is_authenticated,
+ );
- if (activeConnection) {
- status = "connected";
- connectionId = activeConnection.connection_id;
- return {
- id: type,
- name: connectorData.name,
- description: connectorData.description,
- icon: connectorData.icon,
- status,
- type,
- connectionId,
- clientId: activeConnection.client_id,
- baseUrl: activeConnection.base_url,
- available: connectorData.available,
- } as Connector;
- }
- }
+ if (activeConnection) {
+ status = "connected";
+ connectionId = activeConnection.connection_id;
+ return {
+ id: type,
+ name: connectorData.name,
+ description: connectorData.description,
+ icon: connectorData.icon,
+ status,
+ type,
+ connectionId,
+ clientId: activeConnection.client_id,
+ baseUrl: activeConnection.base_url,
+ available: connectorData.available,
+ } as Connector;
+ }
+ }
- return {
- id: type,
- name: connectorData.name,
- description: connectorData.description,
- icon: connectorData.icon,
- status,
- type,
- connectionId,
- available: connectorData.available,
- } as Connector;
- }),
- );
+ return {
+ id: type,
+ name: connectorData.name,
+ description: connectorData.description,
+ icon: connectorData.icon,
+ status,
+ type,
+ connectionId,
+ available: connectorData.available,
+ } as Connector;
+ }),
+ );
- return connectorsWithStatus;
- }
+ return connectorsWithStatus;
+ }
- return useQuery({
- queryKey: ["connectors"],
- queryFn: getConnectors,
- refetchOnMount: "always",
- ...options,
- });
+ return useQuery({
+ queryKey: ["connectors"],
+ queryFn: getConnectors,
+ refetchOnMount: "always",
+ ...options,
+ });
};
diff --git a/frontend/app/api/queries/useGetConversationsQuery.ts b/frontend/app/api/queries/useGetConversationsQuery.ts
index 668626059..20d375052 100644
--- a/frontend/app/api/queries/useGetConversationsQuery.ts
+++ b/frontend/app/api/queries/useGetConversationsQuery.ts
@@ -53,7 +53,9 @@ export const useGetConversationsQuery = (
const queryClient = useQueryClient();
const { isOnboardingComplete } = useChat();
- async function getConversations(context: { signal?: AbortSignal }): Promise<ChatConversation[]> {
+ async function getConversations(context: {
+ signal?: AbortSignal;
+ }): Promise<ChatConversation[]> {
try {
// Fetch from the selected endpoint only
const apiEndpoint =
@@ -89,7 +91,7 @@ export const useGetConversationsQuery = (
return conversations;
} catch (error) {
// Ignore abort errors - these are expected when requests are cancelled
- if (error instanceof Error && error.name === 'AbortError') {
+ if (error instanceof Error && error.name === "AbortError") {
return [];
}
console.error(`Failed to fetch ${endpoint} conversations:`, error);
@@ -109,7 +111,7 @@ export const useGetConversationsQuery = (
queryFn: getConversations,
staleTime: 5000, // Consider data fresh for 5 seconds to prevent excessive refetching
gcTime: 5 * 60 * 1000, // Keep in cache for 5 minutes
- networkMode: 'always', // Ensure requests can be cancelled
+ networkMode: "always", // Ensure requests can be cancelled
refetchOnMount: false, // Don't refetch on every mount
refetchOnWindowFocus: false, // Don't refetch when window regains focus
...options,
diff --git a/frontend/app/api/queries/useGetFilterByIdQuery.ts b/frontend/app/api/queries/useGetFilterByIdQuery.ts
index 353b3153c..090b6f87a 100644
--- a/frontend/app/api/queries/useGetFilterByIdQuery.ts
+++ b/frontend/app/api/queries/useGetFilterByIdQuery.ts
@@ -1,7 +1,7 @@
import type { KnowledgeFilter } from "./useGetFiltersSearchQuery";
export async function getFilterById(
- filterId: string
+ filterId: string,
): Promise<KnowledgeFilter | null> {
try {
const response = await fetch(`/api/knowledge-filter/${filterId}`, {
diff --git a/frontend/app/api/queries/useGetFiltersSearchQuery.ts b/frontend/app/api/queries/useGetFiltersSearchQuery.ts
index d57d25726..26c110f53 100644
--- a/frontend/app/api/queries/useGetFiltersSearchQuery.ts
+++ b/frontend/app/api/queries/useGetFiltersSearchQuery.ts
@@ -1,7 +1,7 @@
import {
+ type UseQueryOptions,
useQuery,
useQueryClient,
- type UseQueryOptions,
} from "@tanstack/react-query";
export interface KnowledgeFilter {
diff --git a/frontend/app/api/queries/useGetNudgesQuery.ts b/frontend/app/api/queries/useGetNudgesQuery.ts
index ac4c1fde5..4fc2163b5 100644
--- a/frontend/app/api/queries/useGetNudgesQuery.ts
+++ b/frontend/app/api/queries/useGetNudgesQuery.ts
@@ -30,12 +30,14 @@ export const useGetNudgesQuery = (
const { chatId, filters, limit, scoreThreshold } = params ?? {};
const queryClient = useQueryClient();
const { isOnboardingComplete } = useChat();
-
+
// Check if LLM provider is healthy
// If health data is not available yet, assume healthy (optimistic)
// Only disable if health data exists and shows LLM error
const { data: health } = useProviderHealthQuery();
- const isLLMHealthy = health === undefined || (health?.status === "healthy" && !health?.llm_error);
+ const isLLMHealthy =
+ health === undefined ||
+ (health?.status === "healthy" && !health?.llm_error);
function cancel() {
queryClient.removeQueries({
@@ -43,7 +45,9 @@ export const useGetNudgesQuery = (
});
}
- async function getNudges(context: { signal?: AbortSignal }): Promise<Nudge[]> {
+ async function getNudges(context: {
+ signal?: AbortSignal;
+ }): Promise<Nudge[]> {
try {
const requestBody: {
filters?: NudgeFilters;
@@ -78,7 +82,7 @@ export const useGetNudgesQuery = (
return DEFAULT_NUDGES;
} catch (error) {
// Ignore abort errors - these are expected when requests are cancelled
- if (error instanceof Error && error.name === 'AbortError') {
+ if (error instanceof Error && error.name === "AbortError") {
return DEFAULT_NUDGES;
}
console.error("Error getting nudges", error);
@@ -96,7 +100,7 @@ export const useGetNudgesQuery = (
queryKey: ["nudges", chatId, filters, limit, scoreThreshold],
queryFn: getNudges,
staleTime: 10000, // Consider data fresh for 10 seconds to prevent rapid refetching
- networkMode: 'always', // Ensure requests can be cancelled
+ networkMode: "always", // Ensure requests can be cancelled
refetchOnMount: false, // Don't refetch on every mount
refetchOnWindowFocus: false, // Don't refetch when window regains focus
refetchInterval: (query) => {
diff --git a/frontend/app/api/queries/useGetSearchAggregations.ts b/frontend/app/api/queries/useGetSearchAggregations.ts
index e44d37288..58ee1e1d8 100644
--- a/frontend/app/api/queries/useGetSearchAggregations.ts
+++ b/frontend/app/api/queries/useGetSearchAggregations.ts
@@ -1,7 +1,7 @@
import {
+ type UseQueryOptions,
useQuery,
useQueryClient,
- type UseQueryOptions,
} from "@tanstack/react-query";
export interface FacetBucket {
diff --git a/frontend/app/api/queries/useGetSearchQuery.ts b/frontend/app/api/queries/useGetSearchQuery.ts
index c77be72a3..4d7db437d 100644
--- a/frontend/app/api/queries/useGetSearchQuery.ts
+++ b/frontend/app/api/queries/useGetSearchQuery.ts
@@ -77,10 +77,11 @@ export const useGetSearchQuery = (
try {
// For wildcard queries, use a high limit to get all files
// Otherwise use the limit from queryData or default to 100
- const isWildcardQuery = effectiveQuery.trim() === "*" || effectiveQuery.trim() === "";
+ const isWildcardQuery =
+ effectiveQuery.trim() === "*" || effectiveQuery.trim() === "";
const searchLimit = isWildcardQuery
? SEARCH_CONSTANTS.WILDCARD_QUERY_LIMIT
- : (queryData?.limit || 100);
+ : queryData?.limit || 100;
const searchPayload: SearchPayload = {
query: effectiveQuery,
@@ -133,8 +134,12 @@ export const useGetSearchQuery = (
});
if (!response.ok) {
- const errorData = await response.json().catch(() => ({ error: "Unknown error" }));
- throw new Error(errorData.error || `Search failed with status ${response.status}`);
+ const errorData = await response
+ .json()
+ .catch(() => ({ error: "Unknown error" }));
+ throw new Error(
+ errorData.error || `Search failed with status ${response.status}`,
+ );
}
const data = await response.json();
diff --git a/frontend/app/chat/_components/assistant-message.tsx b/frontend/app/chat/_components/assistant-message.tsx
index ae6cffbbd..f2d717dfa 100644
--- a/frontend/app/chat/_components/assistant-message.tsx
+++ b/frontend/app/chat/_components/assistant-message.tsx
@@ -3,7 +3,10 @@ import { motion } from "motion/react";
import DogIcon from "@/components/icons/dog-icon";
import { MarkdownRenderer } from "@/components/markdown-renderer";
import { cn } from "@/lib/utils";
-import type { FunctionCall, TokenUsage as TokenUsageType } from "../_types/types";
+import type {
+ FunctionCall,
+ TokenUsage as TokenUsageType,
+} from "../_types/types";
import { FunctionCalls } from "./function-calls";
import { Message } from "./message";
import { TokenUsage } from "./token-usage";
diff --git a/frontend/app/chat/_components/chat-input.tsx b/frontend/app/chat/_components/chat-input.tsx
index 5e1444662..a52678186 100644
--- a/frontend/app/chat/_components/chat-input.tsx
+++ b/frontend/app/chat/_components/chat-input.tsx
@@ -2,21 +2,25 @@ import Fuse from "fuse.js";
import { ArrowRight, Check, Funnel, Loader2, Plus } from "lucide-react";
import { AnimatePresence, motion } from "motion/react";
import {
- forwardRef,
- useImperativeHandle,
- useMemo,
- useRef,
- useState,
+ forwardRef,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
} from "react";
import { useDropzone } from "react-dropzone";
import TextareaAutosize from "react-textarea-autosize";
import { toast } from "sonner";
import type { FilterColor } from "@/components/filter-icon-popover";
+import {
+ SUPPORTED_EXTENSIONS,
+ SUPPORTED_FILE_TYPES,
+} from "@/components/knowledge-dropdown";
import { Button } from "@/components/ui/button";
import {
- Popover,
- PopoverAnchor,
- PopoverContent,
+ Popover,
+ PopoverAnchor,
+ PopoverContent,
} from "@/components/ui/popover";
import { useFileDrag } from "@/hooks/use-file-drag";
import { cn } from "@/lib/utils";
@@ -24,592 +28,593 @@ import { useGetAllFiltersQuery } from "../../api/queries/useGetAllFiltersQuery";
import type { KnowledgeFilterData } from "../_types/types";
import { FilePreview } from "./file-preview";
import { SelectedKnowledgeFilter } from "./selected-knowledge-filter";
-import { SUPPORTED_EXTENSIONS, SUPPORTED_FILE_TYPES } from "@/components/knowledge-dropdown";
export interface ChatInputHandle {
- focusInput: () => void;
- clickFileInput: () => void;
+ focusInput: () => void;
+ clickFileInput: () => void;
}
interface ChatInputProps {
- input: string;
- loading: boolean;
- isUploading: boolean;
- selectedFilter: KnowledgeFilterData | null;
- parsedFilterData: { color?: FilterColor } | null;
- uploadedFile: File | null;
- onSubmit: (e: React.FormEvent) => void;
- onChange: (value: string) => void;
- onKeyDown: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
- onFilterSelect: (filter: KnowledgeFilterData | null) => void;
- onFilePickerClick: () => void;
- setSelectedFilter: (filter: KnowledgeFilterData | null) => void;
- setIsFilterHighlighted: (highlighted: boolean) => void;
- onFileSelected: (file: File | null) => void;
+ input: string;
+ loading: boolean;
+ isUploading: boolean;
+ selectedFilter: KnowledgeFilterData | null;
+ parsedFilterData: { color?: FilterColor } | null;
+ uploadedFile: File | null;
+ onSubmit: (e: React.FormEvent) => void;
+ onChange: (value: string) => void;
+ onKeyDown: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
+ onFilterSelect: (filter: KnowledgeFilterData | null) => void;
+ onFilePickerClick: () => void;
+ setSelectedFilter: (filter: KnowledgeFilterData | null) => void;
+ setIsFilterHighlighted: (highlighted: boolean) => void;
+ onFileSelected: (file: File | null) => void;
}
const SAFE_SINGLE_LINE_CHARS = 80; // Number of chars that can safely fit in one line without wrapping, used to determine when to switch to multi-line mode
export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
- (
- {
- input,
- loading,
- isUploading,
- selectedFilter,
- parsedFilterData,
- uploadedFile,
- onSubmit,
- onChange,
- onKeyDown,
- onFilterSelect,
- onFilePickerClick,
- setSelectedFilter,
- setIsFilterHighlighted,
- onFileSelected,
- },
- ref,
- ) => {
- const inputRef = useRef<HTMLTextAreaElement>(null);
- const fileInputRef = useRef<HTMLInputElement>(null);
- const [isWrapped, setIsWrapped] = useState(false);
- const isMultiline = input.includes("\n") || isWrapped;
- const isDragging = useFileDrag();
-
- // Internal state for filter dropdown
- const [isFilterDropdownOpen, setIsFilterDropdownOpen] = useState(false);
- const [filterSearchTerm, setFilterSearchTerm] = useState("");
- const [selectedFilterIndex, setSelectedFilterIndex] = useState(0);
- const [anchorPosition, setAnchorPosition] = useState<{
- x: number;
- y: number;
- } | null>(null);
-
- // Fetch all filters once when dropdown opens
- const { data: allFilters = [] } = useGetAllFiltersQuery({
- enabled: isFilterDropdownOpen,
- });
-
- // Use fuse.js for fuzzy search on client side
- const filteredFilters = useMemo(() => {
- if (!filterSearchTerm) {
- return allFilters.slice(0, 20); // Return first 20 when no search term
- }
-
- const fuse = new Fuse(allFilters, {
- keys: ["name", "description"],
- threshold: 0.3, // 0.0 = perfect match, 1.0 = match anything
- includeScore: true,
- minMatchCharLength: 1,
- });
-
- const results = fuse.search(filterSearchTerm);
- return results.map((result) => result.item).slice(0, 20);
- }, [allFilters, filterSearchTerm]);
-
- const { getRootProps, getInputProps } = useDropzone({
- accept: SUPPORTED_FILE_TYPES,
- maxFiles: 1,
- disabled: !isDragging,
- onDrop: (acceptedFiles, fileRejections) => {
- if (fileRejections.length > 0) {
- const message = fileRejections.at(0)?.errors.at(0)?.message;
- toast.error(message || "Failed to upload file");
- return;
- }
- onFileSelected(acceptedFiles[0]);
- },
- });
-
- useImperativeHandle(ref, () => ({
- focusInput: () => {
- inputRef.current?.focus();
- },
- clickFileInput: () => {
- fileInputRef.current?.click();
- },
- }));
-
- const handleFilePickerChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- const files = e.target.files;
- if (files && files.length > 0) {
- onFileSelected(files[0]);
- } else {
- onFileSelected(null);
- }
- };
-
- const onAtClick = () => {
- if (!isFilterDropdownOpen) {
- setIsFilterDropdownOpen(true);
- setFilterSearchTerm("");
- setSelectedFilterIndex(0);
-
- // Get button position for popover anchoring
- const button = document.querySelector(
- "[data-filter-button]",
- ) as HTMLElement;
- if (button) {
- const rect = button.getBoundingClientRect();
- setAnchorPosition({
- x: rect.left + rect.width / 2,
- y: rect.top + rect.height / 2 - 12,
- });
- }
- } else {
- setIsFilterDropdownOpen(false);
- setAnchorPosition(null);
- }
- };
-
- const handleFilterSelect = (filter: KnowledgeFilterData | null) => {
- onFilterSelect(filter);
-
- // Remove the @searchTerm from the input
- const words = input.split(" ");
- const lastWord = words[words.length - 1];
-
- if (lastWord.startsWith("@")) {
- // Remove the @search term
- words.pop();
- onChange(words.join(" ") + (words.length > 0 ? " " : ""));
- }
-
- setIsFilterDropdownOpen(false);
- setFilterSearchTerm("");
- setSelectedFilterIndex(0);
- };
-
- const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
- const newValue = e.target.value;
- onChange(newValue); // Call parent's onChange with the string value
-
- // Detect visual wrapping - only collapse when text is clearly short enough
- // to prevent flickering at the boundary (flex-row has less width than flex-col)
- if (!newValue.includes("\n") && newValue.length < SAFE_SINGLE_LINE_CHARS) {
- setIsWrapped(false);
- } else {
- const textarea = e.target;
- const lineHeight = parseFloat(getComputedStyle(textarea).lineHeight) || 20;
- const wrapping = textarea.scrollHeight > lineHeight * 1.5;
- if (wrapping) {
- setIsWrapped(true);
- }
- }
-
- // Find if there's an @ at the start of the last word
- const words = newValue.split(" ");
- const lastWord = words[words.length - 1];
-
- if (lastWord.startsWith("@")) {
- const searchTerm = lastWord.slice(1); // Remove the @
- setFilterSearchTerm(searchTerm);
- setSelectedFilterIndex(0);
-
- // Only set anchor position when @ is first detected (search term is empty)
- if (searchTerm === "") {
- const getCursorPosition = (textarea: HTMLTextAreaElement) => {
- // Create a hidden div with the same styles as the textarea
- const div = document.createElement("div");
- const computedStyle = getComputedStyle(textarea);
-
- // Copy all computed styles to the hidden div
- for (const style of computedStyle) {
- (div.style as unknown as Record<string, string>)[style] =
- computedStyle.getPropertyValue(style);
- }
-
- // Set the div to be hidden but not un-rendered
- div.style.position = "absolute";
- div.style.visibility = "hidden";
- div.style.whiteSpace = "pre-wrap";
- div.style.wordWrap = "break-word";
- div.style.overflow = "hidden";
- div.style.height = "auto";
- div.style.width = `${textarea.getBoundingClientRect().width}px`;
-
- // Get the text up to the cursor position
- const cursorPos = textarea.selectionStart || 0;
- const textBeforeCursor = textarea.value.substring(0, cursorPos);
-
- // Add the text before cursor
- div.textContent = textBeforeCursor;
-
- // Create a span to mark the end position
- const span = document.createElement("span");
- span.textContent = "|"; // Cursor marker
- div.appendChild(span);
-
- // Add the text after cursor to handle word wrapping
- const textAfterCursor = textarea.value.substring(cursorPos);
- div.appendChild(document.createTextNode(textAfterCursor));
-
- // Add the div to the document temporarily
- document.body.appendChild(div);
-
- // Get positions
- const inputRect = textarea.getBoundingClientRect();
- const divRect = div.getBoundingClientRect();
- const spanRect = span.getBoundingClientRect();
-
- // Calculate the cursor position relative to the input
- const x = inputRect.left + (spanRect.left - divRect.left);
- const y = inputRect.top + (spanRect.top - divRect.top);
-
- // Clean up
- document.body.removeChild(div);
-
- return { x, y };
- };
-
- const pos = getCursorPosition(e.target);
- setAnchorPosition(pos);
- }
-
- if (!isFilterDropdownOpen) {
- setIsFilterDropdownOpen(true);
- }
- } else if (isFilterDropdownOpen) {
- // Close dropdown if @ is no longer present
- setIsFilterDropdownOpen(false);
- setFilterSearchTerm("");
- }
- };
-
- const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
- if (isFilterDropdownOpen) {
- if (e.key === "Escape") {
- e.preventDefault();
- setIsFilterDropdownOpen(false);
- setFilterSearchTerm("");
- setSelectedFilterIndex(0);
- inputRef.current?.focus();
- return;
- }
-
- if (e.key === "ArrowDown") {
- e.preventDefault();
- setSelectedFilterIndex((prev) =>
- prev < filteredFilters.length - 1 ? prev + 1 : 0,
- );
- return;
- }
-
- if (e.key === "ArrowUp") {
- e.preventDefault();
- setSelectedFilterIndex((prev) =>
- prev > 0 ? prev - 1 : filteredFilters.length - 1,
- );
- return;
- }
-
- if (e.key === "Enter") {
- // Check if we're at the end of an @ mention
- const cursorPos = e.currentTarget.selectionStart || 0;
- const textBeforeCursor = input.slice(0, cursorPos);
- const words = textBeforeCursor.split(" ");
- const lastWord = words[words.length - 1];
-
- if (
- lastWord.startsWith("@") &&
- filteredFilters[selectedFilterIndex]
- ) {
- e.preventDefault();
- handleFilterSelect(filteredFilters[selectedFilterIndex]);
- return;
- }
- }
-
- if (e.key === " ") {
- // Select filter on space if we're typing an @ mention
- const cursorPos = e.currentTarget.selectionStart || 0;
- const textBeforeCursor = input.slice(0, cursorPos);
- const words = textBeforeCursor.split(" ");
- const lastWord = words[words.length - 1];
-
- if (
- lastWord.startsWith("@") &&
- filteredFilters[selectedFilterIndex]
- ) {
- e.preventDefault();
- handleFilterSelect(filteredFilters[selectedFilterIndex]);
- return;
- }
- }
- }
-
- // Pass through to parent onKeyDown for other key handling
- onKeyDown(e);
- };
-
- return (
- <div className="w-full">
- <form onSubmit={onSubmit} className="relative">
- {/* Outer container - flex-col to stack file preview above input */}
- <div
- {...getRootProps()}
- className={cn(
- "flex flex-col w-full p-2 rounded-xl border border-input transition-all",
- !isDragging &&
- "hover:[&:not(:focus-within)]:border-muted-foreground focus-within:border-foreground",
- isDragging && "border-dashed",
- )}
- >
- <input {...getInputProps()} />
- {/* File Preview Section - Always above */}
- <AnimatePresence>
- {uploadedFile && (
- <motion.div
- initial={{ opacity: 0, height: 0, marginBottom: 0 }}
- animate={{ opacity: 1, height: "auto", marginBottom: 8 }}
- exit={{ opacity: 0, height: 0, marginBottom: 0 }}
- className="overflow-hidden"
- >
- <FilePreview
- uploadedFile={uploadedFile}
- onClear={() => {
- onFileSelected(null);
- }}
- isUploading={isUploading}
- />
- </motion.div>
- )}
- </AnimatePresence>
- <AnimatePresence>
- {isDragging && (
- <motion.div
- initial={{ opacity: 0, height: 0 }}
- animate={{ opacity: 1, height: 100 }}
- exit={{ opacity: 0, height: 0 }}
- className="overflow-hidden w-full flex flex-col items-center justify-center gap-2"
- >
- <p className="text-md font-medium text-primary">
- Add files to conversation
- </p>
- <p className="text-sm text-muted-foreground">
- Text formats and image files.{" "}
- <span className="font-semibold">10</span> files per chat,{" "}
- <span className="font-semibold">150 MB</span> each.
- </p>
- </motion.div>
- )}
- </AnimatePresence>
- {/* Main Input Container - flex-row or flex-col based on textarea height */}
- <div
- className={`relative flex w-full gap-2 ${
- isMultiline ? "flex-col" : "flex-row items-center"
- }`}
- >
- {/* Filter + Textarea Section */}
- <div
- className={`flex items-center gap-2 ${isMultiline ? "w-full" : "flex-1"}`}
- >
- {!isMultiline &&
- (selectedFilter ? (
- <SelectedKnowledgeFilter
- selectedFilter={selectedFilter}
- parsedFilterData={parsedFilterData}
- onClear={() => {
- setSelectedFilter(null);
- setIsFilterHighlighted(false);
- }}
- />
- ) : (
- <Button
- type="button"
- variant="ghost"
- size="iconSm"
- className="h-8 w-8 p-0 rounded-md hover:bg-muted/50"
- onMouseDown={(e) => {
- e.preventDefault();
- }}
- onClick={onAtClick}
- data-filter-button
- >
- <Funnel className="h-4 w-4" />
- </Button>
- ))}
- <div
- className="relative flex-1 flex items-center"
- >
- <TextareaAutosize
- ref={inputRef}
- value={input}
- onChange={handleChange}
- onKeyDown={handleKeyDown}
- maxRows={7}
- autoComplete="off"
- minRows={1}
- placeholder="Ask a question..."
- disabled={loading}
- className={`w-full text-sm bg-transparent focus-visible:outline-none resize-none`}
- rows={1}
- />
- </div>
- </div>
-
- {/* Action Buttons Section */}
- <div
- className={`flex items-center gap-2 ${isMultiline ? "justify-between w-full" : ""}`}
- >
- {isMultiline &&
- (selectedFilter ? (
- <SelectedKnowledgeFilter
- selectedFilter={selectedFilter}
- parsedFilterData={parsedFilterData}
- onClear={() => {
- setSelectedFilter(null);
- setIsFilterHighlighted(false);
- }}
- />
- ) : (
- <Button
- type="button"
- variant="ghost"
- size="iconSm"
- className="h-8 w-8 p-0 rounded-md hover:bg-muted/50"
- onMouseDown={(e) => {
- e.preventDefault();
- }}
- onClick={onAtClick}
- data-filter-button
- >
- <Funnel className="h-4 w-4" />
- </Button>
- ))}
- <div className="flex items-center gap-2">
- <Button
- type="button"
- variant="ghost"
- size="iconSm"
- onClick={onFilePickerClick}
- disabled={isUploading}
- className="h-8 w-8 p-0 !rounded-md hover:bg-muted/50"
- >
- <Plus className="h-4 w-4" />
- </Button>
- <Button
- variant="default"
- type="submit"
- size="iconSm"
- disabled={(!input.trim() && !uploadedFile) || loading}
- className="!rounded-md h-8 w-8 p-0"
- >
- {loading ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <ArrowRight className="h-4 w-4" />
- )}
- </Button>
- </div>
- </div>
- </div>
- </div>
- <input
- ref={fileInputRef}
- type="file"
- onChange={handleFilePickerChange}
- className="hidden"
- accept={SUPPORTED_EXTENSIONS.join(",")}
- />
-
- <Popover
- open={isFilterDropdownOpen}
- onOpenChange={(open) => {
- setIsFilterDropdownOpen(open);
- }}
- >
- {anchorPosition && (
- <PopoverAnchor
- asChild
- style={{
- position: "fixed",
- left: anchorPosition.x,
- top: anchorPosition.y,
- width: 1,
- height: 1,
- pointerEvents: "none",
- }}
- >
- <div />
- </PopoverAnchor>
- )}
- <PopoverContent
- className="w-64 p-2"
- side="top"
- align="start"
- sideOffset={6}
- alignOffset={-18}
- onOpenAutoFocus={(e) => {
- // Prevent auto focus on the popover content
- e.preventDefault();
- // Keep focus on the input
- }}
- >
- <div className="space-y-1">
- {filterSearchTerm && (
- <div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
- Searching: @{filterSearchTerm}
- </div>
- )}
- {allFilters.length === 0 ? (
- <div className="px-2 py-3 text-sm text-muted-foreground">
- No knowledge filters available
- </div>
- ) : (
- <>
- {!filterSearchTerm && (
- <button
- type="button"
- onClick={() => handleFilterSelect(null)}
- className={`w-full text-left px-2 py-2 text-sm rounded hover:bg-muted/50 flex items-center justify-between ${
- selectedFilterIndex === -1 ? "bg-muted/50" : ""
- }`}
- >
- <span>No knowledge filter</span>
- {!selectedFilter && (
- <Check className="h-4 w-4 shrink-0" />
- )}
- </button>
- )}
- {filteredFilters.map((filter, index) => (
- <button
- key={filter.id}
- type="button"
- onClick={() => handleFilterSelect(filter)}
- className={`w-full overflow-hidden text-left px-2 py-2 gap-2 text-sm rounded hover:bg-muted/50 flex items-center justify-between ${
- index === selectedFilterIndex ? "bg-muted/50" : ""
- }`}
- >
- <div className="overflow-hidden">
- <div className="font-medium truncate">
- {filter.name}
- </div>
- {filter.description && (
- <div className="text-xs text-muted-foreground truncate">
- {filter.description}
- </div>
- )}
- </div>
- {selectedFilter?.id === filter.id && (
- <Check className="h-4 w-4 shrink-0" />
- )}
- </button>
- ))}
- {filteredFilters.length === 0 && filterSearchTerm && (
- <div className="px-2 py-3 text-sm text-muted-foreground">
- No filters match &quot;{filterSearchTerm}&quot;
- </div>
- )}
- </>
- )}
- </div>
- </PopoverContent>
- </Popover>
- </form>
- </div>
- );
- },
+ (
+ {
+ input,
+ loading,
+ isUploading,
+ selectedFilter,
+ parsedFilterData,
+ uploadedFile,
+ onSubmit,
+ onChange,
+ onKeyDown,
+ onFilterSelect,
+ onFilePickerClick,
+ setSelectedFilter,
+ setIsFilterHighlighted,
+ onFileSelected,
+ },
+ ref,
+ ) => {
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [isWrapped, setIsWrapped] = useState(false);
+ const isMultiline = input.includes("\n") || isWrapped;
+ const isDragging = useFileDrag();
+
+ // Internal state for filter dropdown
+ const [isFilterDropdownOpen, setIsFilterDropdownOpen] = useState(false);
+ const [filterSearchTerm, setFilterSearchTerm] = useState("");
+ const [selectedFilterIndex, setSelectedFilterIndex] = useState(0);
+ const [anchorPosition, setAnchorPosition] = useState<{
+ x: number;
+ y: number;
+ } | null>(null);
+
+ // Fetch all filters once when dropdown opens
+ const { data: allFilters = [] } = useGetAllFiltersQuery({
+ enabled: isFilterDropdownOpen,
+ });
+
+ // Use fuse.js for fuzzy search on client side
+ const filteredFilters = useMemo(() => {
+ if (!filterSearchTerm) {
+ return allFilters.slice(0, 20); // Return first 20 when no search term
+ }
+
+ const fuse = new Fuse(allFilters, {
+ keys: ["name", "description"],
+ threshold: 0.3, // 0.0 = perfect match, 1.0 = match anything
+ includeScore: true,
+ minMatchCharLength: 1,
+ });
+
+ const results = fuse.search(filterSearchTerm);
+ return results.map((result) => result.item).slice(0, 20);
+ }, [allFilters, filterSearchTerm]);
+
+ const { getRootProps, getInputProps } = useDropzone({
+ accept: SUPPORTED_FILE_TYPES,
+ maxFiles: 1,
+ disabled: !isDragging,
+ onDrop: (acceptedFiles, fileRejections) => {
+ if (fileRejections.length > 0) {
+ const message = fileRejections.at(0)?.errors.at(0)?.message;
+ toast.error(message || "Failed to upload file");
+ return;
+ }
+ onFileSelected(acceptedFiles[0]);
+ },
+ });
+
+ useImperativeHandle(ref, () => ({
+ focusInput: () => {
+ inputRef.current?.focus();
+ },
+ clickFileInput: () => {
+ fileInputRef.current?.click();
+ },
+ }));
+
+ const handleFilePickerChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const files = e.target.files;
+ if (files && files.length > 0) {
+ onFileSelected(files[0]);
+ } else {
+ onFileSelected(null);
+ }
+ };
+
+ const onAtClick = () => {
+ if (!isFilterDropdownOpen) {
+ setIsFilterDropdownOpen(true);
+ setFilterSearchTerm("");
+ setSelectedFilterIndex(0);
+
+ // Get button position for popover anchoring
+ const button = document.querySelector(
+ "[data-filter-button]",
+ ) as HTMLElement;
+ if (button) {
+ const rect = button.getBoundingClientRect();
+ setAnchorPosition({
+ x: rect.left + rect.width / 2,
+ y: rect.top + rect.height / 2 - 12,
+ });
+ }
+ } else {
+ setIsFilterDropdownOpen(false);
+ setAnchorPosition(null);
+ }
+ };
+
+ const handleFilterSelect = (filter: KnowledgeFilterData | null) => {
+ onFilterSelect(filter);
+
+ // Remove the @searchTerm from the input
+ const words = input.split(" ");
+ const lastWord = words[words.length - 1];
+
+ if (lastWord.startsWith("@")) {
+ // Remove the @search term
+ words.pop();
+ onChange(words.join(" ") + (words.length > 0 ? " " : ""));
+ }
+
+ setIsFilterDropdownOpen(false);
+ setFilterSearchTerm("");
+ setSelectedFilterIndex(0);
+ };
+
+ const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
+ const newValue = e.target.value;
+ onChange(newValue); // Call parent's onChange with the string value
+
+ // Detect visual wrapping - only collapse when text is clearly short enough
+ // to prevent flickering at the boundary (flex-row has less width than flex-col)
+ if (
+ !newValue.includes("\n") &&
+ newValue.length < SAFE_SINGLE_LINE_CHARS
+ ) {
+ setIsWrapped(false);
+ } else {
+ const textarea = e.target;
+ const lineHeight =
+ parseFloat(getComputedStyle(textarea).lineHeight) || 20;
+ const wrapping = textarea.scrollHeight > lineHeight * 1.5;
+ if (wrapping) {
+ setIsWrapped(true);
+ }
+ }
+
+ // Find if there's an @ at the start of the last word
+ const words = newValue.split(" ");
+ const lastWord = words[words.length - 1];
+
+ if (lastWord.startsWith("@")) {
+ const searchTerm = lastWord.slice(1); // Remove the @
+ setFilterSearchTerm(searchTerm);
+ setSelectedFilterIndex(0);
+
+ // Only set anchor position when @ is first detected (search term is empty)
+ if (searchTerm === "") {
+ const getCursorPosition = (textarea: HTMLTextAreaElement) => {
+ // Create a hidden div with the same styles as the textarea
+ const div = document.createElement("div");
+ const computedStyle = getComputedStyle(textarea);
+
+ // Copy all computed styles to the hidden div
+ for (const style of computedStyle) {
+ (div.style as unknown as Record<string, string>)[style] =
+ computedStyle.getPropertyValue(style);
+ }
+
+ // Set the div to be hidden but not un-rendered
+ div.style.position = "absolute";
+ div.style.visibility = "hidden";
+ div.style.whiteSpace = "pre-wrap";
+ div.style.wordWrap = "break-word";
+ div.style.overflow = "hidden";
+ div.style.height = "auto";
+ div.style.width = `${textarea.getBoundingClientRect().width}px`;
+
+ // Get the text up to the cursor position
+ const cursorPos = textarea.selectionStart || 0;
+ const textBeforeCursor = textarea.value.substring(0, cursorPos);
+
+ // Add the text before cursor
+ div.textContent = textBeforeCursor;
+
+ // Create a span to mark the end position
+ const span = document.createElement("span");
+ span.textContent = "|"; // Cursor marker
+ div.appendChild(span);
+
+ // Add the text after cursor to handle word wrapping
+ const textAfterCursor = textarea.value.substring(cursorPos);
+ div.appendChild(document.createTextNode(textAfterCursor));
+
+ // Add the div to the document temporarily
+ document.body.appendChild(div);
+
+ // Get positions
+ const inputRect = textarea.getBoundingClientRect();
+ const divRect = div.getBoundingClientRect();
+ const spanRect = span.getBoundingClientRect();
+
+ // Calculate the cursor position relative to the input
+ const x = inputRect.left + (spanRect.left - divRect.left);
+ const y = inputRect.top + (spanRect.top - divRect.top);
+
+ // Clean up
+ document.body.removeChild(div);
+
+ return { x, y };
+ };
+
+ const pos = getCursorPosition(e.target);
+ setAnchorPosition(pos);
+ }
+
+ if (!isFilterDropdownOpen) {
+ setIsFilterDropdownOpen(true);
+ }
+ } else if (isFilterDropdownOpen) {
+ // Close dropdown if @ is no longer present
+ setIsFilterDropdownOpen(false);
+ setFilterSearchTerm("");
+ }
+ };
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (isFilterDropdownOpen) {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ setIsFilterDropdownOpen(false);
+ setFilterSearchTerm("");
+ setSelectedFilterIndex(0);
+ inputRef.current?.focus();
+ return;
+ }
+
+ if (e.key === "ArrowDown") {
+ e.preventDefault();
+ setSelectedFilterIndex((prev) =>
+ prev < filteredFilters.length - 1 ? prev + 1 : 0,
+ );
+ return;
+ }
+
+ if (e.key === "ArrowUp") {
+ e.preventDefault();
+ setSelectedFilterIndex((prev) =>
+ prev > 0 ? prev - 1 : filteredFilters.length - 1,
+ );
+ return;
+ }
+
+ if (e.key === "Enter") {
+ // Check if we're at the end of an @ mention
+ const cursorPos = e.currentTarget.selectionStart || 0;
+ const textBeforeCursor = input.slice(0, cursorPos);
+ const words = textBeforeCursor.split(" ");
+ const lastWord = words[words.length - 1];
+
+ if (
+ lastWord.startsWith("@") &&
+ filteredFilters[selectedFilterIndex]
+ ) {
+ e.preventDefault();
+ handleFilterSelect(filteredFilters[selectedFilterIndex]);
+ return;
+ }
+ }
+
+ if (e.key === " ") {
+ // Select filter on space if we're typing an @ mention
+ const cursorPos = e.currentTarget.selectionStart || 0;
+ const textBeforeCursor = input.slice(0, cursorPos);
+ const words = textBeforeCursor.split(" ");
+ const lastWord = words[words.length - 1];
+
+ if (
+ lastWord.startsWith("@") &&
+ filteredFilters[selectedFilterIndex]
+ ) {
+ e.preventDefault();
+ handleFilterSelect(filteredFilters[selectedFilterIndex]);
+ return;
+ }
+ }
+ }
+
+ // Pass through to parent onKeyDown for other key handling
+ onKeyDown(e);
+ };
+
+ return (
+ <div className="w-full">
+ <form onSubmit={onSubmit} className="relative">
+ {/* Outer container - flex-col to stack file preview above input */}
+ <div
+ {...getRootProps()}
+ className={cn(
+ "flex flex-col w-full p-2 rounded-xl border border-input transition-all",
+ !isDragging &&
+ "hover:[&:not(:focus-within)]:border-muted-foreground focus-within:border-foreground",
+ isDragging && "border-dashed",
+ )}
+ >
+ <input {...getInputProps()} />
+ {/* File Preview Section - Always above */}
+ <AnimatePresence>
+ {uploadedFile && (
+ <motion.div
+ initial={{ opacity: 0, height: 0, marginBottom: 0 }}
+ animate={{ opacity: 1, height: "auto", marginBottom: 8 }}
+ exit={{ opacity: 0, height: 0, marginBottom: 0 }}
+ className="overflow-hidden"
+ >
+ <FilePreview
+ uploadedFile={uploadedFile}
+ onClear={() => {
+ onFileSelected(null);
+ }}
+ isUploading={isUploading}
+ />
+ </motion.div>
+ )}
+ </AnimatePresence>
+ <AnimatePresence>
+ {isDragging && (
+ <motion.div
+ initial={{ opacity: 0, height: 0 }}
+ animate={{ opacity: 1, height: 100 }}
+ exit={{ opacity: 0, height: 0 }}
+ className="overflow-hidden w-full flex flex-col items-center justify-center gap-2"
+ >
+ <p className="text-md font-medium text-primary">
+ Add files to conversation
+ </p>
+ <p className="text-sm text-muted-foreground">
+ Text formats and image files.{" "}
+ <span className="font-semibold">10</span> files per chat,{" "}
+ <span className="font-semibold">150 MB</span> each.
+ </p>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ {/* Main Input Container - flex-row or flex-col based on textarea height */}
+ <div
+ className={`relative flex w-full gap-2 ${
+ isMultiline ? "flex-col" : "flex-row items-center"
+ }`}
+ >
+ {/* Filter + Textarea Section */}
+ <div
+ className={`flex items-center gap-2 ${isMultiline ? "w-full" : "flex-1"}`}
+ >
+ {!isMultiline &&
+ (selectedFilter ? (
+ <SelectedKnowledgeFilter
+ selectedFilter={selectedFilter}
+ parsedFilterData={parsedFilterData}
+ onClear={() => {
+ setSelectedFilter(null);
+ setIsFilterHighlighted(false);
+ }}
+ />
+ ) : (
+ <Button
+ type="button"
+ variant="ghost"
+ size="iconSm"
+ className="h-8 w-8 p-0 rounded-md hover:bg-muted/50"
+ onMouseDown={(e) => {
+ e.preventDefault();
+ }}
+ onClick={onAtClick}
+ data-filter-button
+ >
+ <Funnel className="h-4 w-4" />
+ </Button>
+ ))}
+ <div className="relative flex-1 flex items-center">
+ <TextareaAutosize
+ ref={inputRef}
+ value={input}
+ onChange={handleChange}
+ onKeyDown={handleKeyDown}
+ maxRows={7}
+ autoComplete="off"
+ minRows={1}
+ placeholder="Ask a question..."
+ disabled={loading}
+ className={`w-full text-sm bg-transparent focus-visible:outline-none resize-none`}
+ rows={1}
+ />
+ </div>
+ </div>
+
+ {/* Action Buttons Section */}
+ <div
+ className={`flex items-center gap-2 ${isMultiline ? "justify-between w-full" : ""}`}
+ >
+ {isMultiline &&
+ (selectedFilter ? (
+ <SelectedKnowledgeFilter
+ selectedFilter={selectedFilter}
+ parsedFilterData={parsedFilterData}
+ onClear={() => {
+ setSelectedFilter(null);
+ setIsFilterHighlighted(false);
+ }}
+ />
+ ) : (
+ <Button
+ type="button"
+ variant="ghost"
+ size="iconSm"
+ className="h-8 w-8 p-0 rounded-md hover:bg-muted/50"
+ onMouseDown={(e) => {
+ e.preventDefault();
+ }}
+ onClick={onAtClick}
+ data-filter-button
+ >
+ <Funnel className="h-4 w-4" />
+ </Button>
+ ))}
+ <div className="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="iconSm"
+ onClick={onFilePickerClick}
+ disabled={isUploading}
+ className="h-8 w-8 p-0 !rounded-md hover:bg-muted/50"
+ >
+ <Plus className="h-4 w-4" />
+ </Button>
+ <Button
+ variant="default"
+ type="submit"
+ size="iconSm"
+ disabled={(!input.trim() && !uploadedFile) || loading}
+ className="!rounded-md h-8 w-8 p-0"
+ >
+ {loading ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <ArrowRight className="h-4 w-4" />
+ )}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ <input
+ ref={fileInputRef}
+ type="file"
+ onChange={handleFilePickerChange}
+ className="hidden"
+ accept={SUPPORTED_EXTENSIONS.join(",")}
+ />
+
+ <Popover
+ open={isFilterDropdownOpen}
+ onOpenChange={(open) => {
+ setIsFilterDropdownOpen(open);
+ }}
+ >
+ {anchorPosition && (
+ <PopoverAnchor
+ asChild
+ style={{
+ position: "fixed",
+ left: anchorPosition.x,
+ top: anchorPosition.y,
+ width: 1,
+ height: 1,
+ pointerEvents: "none",
+ }}
+ >
+ <div />
+ </PopoverAnchor>
+ )}
+ <PopoverContent
+ className="w-64 p-2"
+ side="top"
+ align="start"
+ sideOffset={6}
+ alignOffset={-18}
+ onOpenAutoFocus={(e) => {
+ // Prevent auto focus on the popover content
+ e.preventDefault();
+ // Keep focus on the input
+ }}
+ >
+ <div className="space-y-1">
+ {filterSearchTerm && (
+ <div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
+ Searching: @{filterSearchTerm}
+ </div>
+ )}
+ {allFilters.length === 0 ? (
+ <div className="px-2 py-3 text-sm text-muted-foreground">
+ No knowledge filters available
+ </div>
+ ) : (
+ <>
+ {!filterSearchTerm && (
+ <button
+ type="button"
+ onClick={() => handleFilterSelect(null)}
+ className={`w-full text-left px-2 py-2 text-sm rounded hover:bg-muted/50 flex items-center justify-between ${
+ selectedFilterIndex === -1 ? "bg-muted/50" : ""
+ }`}
+ >
+ <span>No knowledge filter</span>
+ {!selectedFilter && (
+ <Check className="h-4 w-4 shrink-0" />
+ )}
+ </button>
+ )}
+ {filteredFilters.map((filter, index) => (
+ <button
+ key={filter.id}
+ type="button"
+ onClick={() => handleFilterSelect(filter)}
+ className={`w-full overflow-hidden text-left px-2 py-2 gap-2 text-sm rounded hover:bg-muted/50 flex items-center justify-between ${
+ index === selectedFilterIndex ? "bg-muted/50" : ""
+ }`}
+ >
+ <div className="overflow-hidden">
+ <div className="font-medium truncate">
+ {filter.name}
+ </div>
+ {filter.description && (
+ <div className="text-xs text-muted-foreground truncate">
+ {filter.description}
+ </div>
+ )}
+ </div>
+ {selectedFilter?.id === filter.id && (
+ <Check className="h-4 w-4 shrink-0" />
+ )}
+ </button>
+ ))}
+ {filteredFilters.length === 0 && filterSearchTerm && (
+ <div className="px-2 py-3 text-sm text-muted-foreground">
+ No filters match &quot;{filterSearchTerm}&quot;
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ </PopoverContent>
+ </Popover>
+ </form>
+ </div>
+ );
+ },
);
ChatInput.displayName = "ChatInput";
diff --git a/frontend/app/chat/_components/file-preview.tsx b/frontend/app/chat/_components/file-preview.tsx
index 95349b240..b3a4fc35a 100644
--- a/frontend/app/chat/_components/file-preview.tsx
+++ b/frontend/app/chat/_components/file-preview.tsx
@@ -23,7 +23,11 @@ const getFilePreviewUrl = (file: File): string => {
return "";
};
-export const FilePreview = ({ uploadedFile, onClear, isUploading = false }: FilePreviewProps) => {
+export const FilePreview = ({
+ uploadedFile,
+ onClear,
+ isUploading = false,
+}: FilePreviewProps) => {
return (
<div className="max-w-[250px] flex items-center gap-2 p-2 bg-muted rounded-lg">
{/* File Image Preview */}
diff --git a/frontend/app/chat/_components/token-usage.tsx b/frontend/app/chat/_components/token-usage.tsx
index 2fc5f03ae..c330b9738 100644
--- a/frontend/app/chat/_components/token-usage.tsx
+++ b/frontend/app/chat/_components/token-usage.tsx
@@ -7,7 +7,10 @@ interface TokenUsageProps {
export function TokenUsage({ usage }: TokenUsageProps) {
// Guard against partial/malformed usage data
- if (typeof usage.input_tokens !== "number" || typeof usage.output_tokens !== "number") {
+ if (
+ typeof usage.input_tokens !== "number" ||
+ typeof usage.output_tokens !== "number"
+ ) {
return null;
}
@@ -15,7 +18,8 @@ export function TokenUsage({ usage }: TokenUsageProps) {
<div className="flex items-center gap-2 mt-2 text-xs text-muted-foreground">
<Zap className="h-3 w-3" />
<span>
- {usage.input_tokens.toLocaleString()} in / {usage.output_tokens.toLocaleString()} out
+ {usage.input_tokens.toLocaleString()} in /{" "}
+ {usage.output_tokens.toLocaleString()} out
{usage.input_tokens_details?.cached_tokens ? (
<span className="text-green-500 ml-1">
({usage.input_tokens_details.cached_tokens.toLocaleString()} cached)
diff --git a/frontend/app/chat/page.tsx b/frontend/app/chat/page.tsx
index 44d8c70ac..6c3ffaa43 100644
--- a/frontend/app/chat/page.tsx
+++ b/frontend/app/chat/page.tsx
@@ -18,1264 +18,1264 @@ import { ChatInput, type ChatInputHandle } from "./_components/chat-input";
import Nudges from "./_components/nudges";
import { UserMessage } from "./_components/user-message";
import type {
- FunctionCall,
- KnowledgeFilterData,
- Message,
- RequestBody,
- SelectedFilters,
- ToolCallResult,
+ FunctionCall,
+ KnowledgeFilterData,
+ Message,
+ RequestBody,
+ SelectedFilters,
+ ToolCallResult,
} from "./_types/types";
function ChatPage() {
- const isDebugMode = process.env.NEXT_PUBLIC_OPENRAG_DEBUG === "true";
- const {
- endpoint,
- setEndpoint,
- currentConversationId,
- conversationData,
- setCurrentConversationId,
- addConversationDoc,
- forkFromResponse,
- refreshConversations,
- refreshConversationsSilent,
- refreshTrigger,
- previousResponseIds,
- setPreviousResponseIds,
- placeholderConversation,
- conversationFilter,
- setConversationFilter,
- } = useChat();
- const [messages, setMessages] = useState<Message[]>([
- {
- role: "assistant",
- content: "How can I assist?",
- timestamp: new Date(),
- },
- ]);
- const [input, setInput] = useState("");
- const { loading, setLoading } = useLoadingStore();
- const { setChatError } = useChat();
- const [asyncMode, setAsyncMode] = useState(true);
- const [expandedFunctionCalls, setExpandedFunctionCalls] = useState<
- Set<string>
- >(new Set());
- // previousResponseIds now comes from useChat context
- const [isUploading, setIsUploading] = useState(false);
- const [isFilterHighlighted, setIsFilterHighlighted] = useState(false);
- const [isUserInteracting, setIsUserInteracting] = useState(false);
- const [isForkingInProgress, setIsForkingInProgress] = useState(false);
- const [uploadedFile, setUploadedFile] = useState<File | null>(null);
- const [waitingTooLong, setWaitingTooLong] = useState(false);
-
- const chatInputRef = useRef<ChatInputHandle>(null);
-
- const { scrollToBottom } = useStickToBottomContext();
-
- const lastLoadedConversationRef = useRef<string | null>(null);
- const { addTask } = useTask();
-
- // Check if chat history is loading
- const { isLoading: isConversationsLoading } = useGetConversationsQuery(
- endpoint,
- refreshTrigger,
- );
-
- // Use conversation-specific filter instead of global filter
- const selectedFilter = conversationFilter;
-
- // Parse the conversation filter data
- const parsedFilterData = useMemo(() => {
- if (!selectedFilter?.query_data) return null;
- try {
- return JSON.parse(selectedFilter.query_data);
- } catch (error) {
- console.error("Error parsing filter data:", error);
- return null;
- }
- }, [selectedFilter]);
-
- // Use the chat streaming hook
- const apiEndpoint = endpoint === "chat" ? "/api/chat" : "/api/langflow";
- const {
- streamingMessage,
- sendMessage: sendStreamingMessage,
- abortStream,
- isLoading: isStreamLoading,
- } = useChatStreaming({
- endpoint: apiEndpoint,
- onComplete: (message, responseId) => {
- setMessages((prev) => [...prev, message]);
- setLoading(false);
- setWaitingTooLong(false);
- if (responseId) {
- cancelNudges();
- setPreviousResponseIds((prev) => ({
- ...prev,
- [endpoint]: responseId,
- }));
-
- if (!currentConversationId) {
- setCurrentConversationId(responseId);
- refreshConversations(true);
- } else {
- refreshConversationsSilent();
- }
-
- // Save filter association for this response
- if (conversationFilter && typeof window !== "undefined") {
- const newKey = `conversation_filter_${responseId}`;
- localStorage.setItem(newKey, conversationFilter.id);
- console.log(
- "[CHAT] Saved filter association:",
- newKey,
- "=",
- conversationFilter.id,
- );
- }
- }
- },
- onError: (error) => {
- console.error("Streaming error:", error);
- setLoading(false);
- setWaitingTooLong(false);
- // Set chat error flag to trigger test_completion=true on health checks
- setChatError(true);
- const errorMessage: Message = {
- role: "assistant",
- content:
- "Sorry, I couldn't connect to the chat service. Please try again.",
- timestamp: new Date(),
- };
- setMessages((prev) => [...prev, errorMessage]);
- },
- });
-
- // Show warning if waiting too long (20 seconds)
- useEffect(() => {
- let timeoutId: NodeJS.Timeout | null = null;
-
- if (isStreamLoading && !streamingMessage) {
- timeoutId = setTimeout(() => {
- setWaitingTooLong(true);
- }, 20000); // 20 seconds
- } else {
- setWaitingTooLong(false);
- }
-
- return () => {
- if (timeoutId) clearTimeout(timeoutId);
- };
- }, [isStreamLoading, streamingMessage]);
-
- const handleEndpointChange = (newEndpoint: EndpointType) => {
- setEndpoint(newEndpoint);
- // Clear the conversation when switching endpoints to avoid response ID conflicts
- setMessages([]);
- setPreviousResponseIds({ chat: null, langflow: null });
- };
-
- const handleFileUpload = async (file: File) => {
- console.log("handleFileUpload called with file:", file.name);
-
- if (isUploading) return;
-
- setIsUploading(true);
- setLoading(true);
-
- try {
- const formData = new FormData();
- formData.append("file", file);
- formData.append("endpoint", endpoint);
-
- // Add previous_response_id if we have one for this endpoint
- const currentResponseId = previousResponseIds[endpoint];
- if (currentResponseId) {
- formData.append("previous_response_id", currentResponseId);
- }
-
- const response = await fetch("/api/upload_context", {
- method: "POST",
- body: formData,
- });
-
- console.log("Upload response status:", response.status);
-
- if (!response.ok) {
- const errorText = await response.text();
- console.error(
- "Upload failed with status:",
- response.status,
- "Response:",
- errorText,
- );
- throw new Error("Failed to process document");
- }
-
- const result = await response.json();
- console.log("Upload result:", result);
-
- if (!response.ok) {
- // Set chat error flag if upload fails
- setChatError(true);
- }
-
- if (response.status === 201) {
- // New flow: Got task ID, start tracking with centralized system
- const taskId = result.task_id || result.id;
-
- if (!taskId) {
- console.error("No task ID in 201 response:", result);
- throw new Error("No task ID received from server");
- }
-
- // Add task to centralized tracking
- addTask(taskId);
-
- return null;
- } else if (response.ok) {
- // Original flow: Direct response
-
- const uploadMessage: Message = {
- role: "user",
- content: `I'm uploading a document called "${result.filename}". Here is its content:`,
- timestamp: new Date(),
- };
-
- const confirmationMessage: Message = {
- role: "assistant",
- content: `Confirmed`,
- timestamp: new Date(),
- };
-
- setMessages((prev) => [...prev, uploadMessage, confirmationMessage]);
-
- // Add file to conversation docs
- if (result.filename) {
- addConversationDoc(result.filename);
- }
-
- // Update the response ID for this endpoint
- if (result.response_id) {
- setPreviousResponseIds((prev) => ({
- ...prev,
- [endpoint]: result.response_id,
- }));
-
- // If this is a new conversation (no currentConversationId), set it now
- if (!currentConversationId) {
- setCurrentConversationId(result.response_id);
- refreshConversations(true);
- } else {
- // For existing conversations, do a silent refresh to keep backend in sync
- refreshConversationsSilent();
- }
-
- return result.response_id;
- }
- } else {
- throw new Error(`Upload failed: ${response.status}`);
- }
- } catch (error) {
- console.error("Upload failed:", error);
- // Set chat error flag to trigger test_completion=true on health checks
- setChatError(true);
- const errorMessage: Message = {
- role: "assistant",
- content: `❌ Failed to process document. Please try again.`,
- timestamp: new Date(),
- };
- setMessages((prev) => [...prev.slice(0, -1), errorMessage]);
- } finally {
- setIsUploading(false);
- setLoading(false);
- }
- };
-
- const handleFilePickerClick = () => {
- chatInputRef.current?.clickFileInput();
- };
-
- const handleFilterSelect = (filter: KnowledgeFilterData | null) => {
- // Update conversation-specific filter
- setConversationFilter(filter);
- setIsFilterHighlighted(false);
- };
-
- // Auto-focus the input on component mount
- useEffect(() => {
- chatInputRef.current?.focusInput();
- }, []);
-
- // Explicitly handle external new conversation trigger
- useEffect(() => {
- const handleNewConversation = () => {
- // Abort any in-flight streaming so it doesn't bleed into new chat
- abortStream();
- // Reset chat UI even if context state was already 'new'
- setMessages([
- {
- role: "assistant",
- content: "How can I assist?",
- timestamp: new Date(),
- },
- ]);
- setInput("");
- setExpandedFunctionCalls(new Set());
- setIsFilterHighlighted(false);
- setLoading(false);
- lastLoadedConversationRef.current = null;
-
- // Focus input after a short delay to ensure rendering is complete
- setTimeout(() => {
- chatInputRef.current?.focusInput();
- }, 100);
- };
-
- const handleFocusInput = () => {
- chatInputRef.current?.focusInput();
- };
-
- window.addEventListener("newConversation", handleNewConversation);
- window.addEventListener("focusInput", handleFocusInput);
- return () => {
- window.removeEventListener("newConversation", handleNewConversation);
- window.removeEventListener("focusInput", handleFocusInput);
- };
- }, [abortStream, setLoading]);
-
- // Load conversation only when user explicitly selects a conversation
- useEffect(() => {
- // Only load conversation data when:
- // 1. conversationData exists AND
- // 2. It's different from the last loaded conversation AND
- // 3. User is not in the middle of an interaction
- if (
- conversationData?.messages &&
- lastLoadedConversationRef.current !== conversationData.response_id &&
- !isUserInteracting &&
- !isForkingInProgress
- ) {
- console.log(
- "Loading conversation with",
- conversationData.messages.length,
- "messages",
- );
- // Convert backend message format to frontend Message interface
- const convertedMessages: Message[] = conversationData.messages.map(
- (msg: {
- role: string;
- content: string;
- timestamp?: string;
- response_id?: string;
- chunks?: Array<{
- item?: {
- type?: string;
- tool_name?: string;
- id?: string;
- inputs?: unknown;
- results?: unknown;
- status?: string;
- };
- delta?: {
- tool_calls?: Array<{
- id?: string;
- function?: { name?: string; arguments?: string };
- type?: string;
- }>;
- };
- type?: string;
- result?: unknown;
- output?: unknown;
- response?: unknown;
- }>;
- response_data?: unknown;
- }) => {
- const message: Message = {
- role: msg.role as "user" | "assistant",
- content: msg.content,
- timestamp: new Date(msg.timestamp || new Date()),
- };
-
- // Extract function calls from chunks or response_data
- if (msg.role === "assistant" && (msg.chunks || msg.response_data)) {
- const functionCalls: FunctionCall[] = [];
- console.log("Processing assistant message for function calls:", {
- hasChunks: !!msg.chunks,
- chunksLength: msg.chunks?.length,
- hasResponseData: !!msg.response_data,
- });
-
- // Process chunks (streaming data)
- if (msg.chunks && Array.isArray(msg.chunks)) {
- for (const chunk of msg.chunks) {
- // Handle Langflow format: chunks[].item.tool_call
- if (chunk.item && chunk.item.type === "tool_call") {
- const toolCall = chunk.item;
- console.log("Found Langflow tool call:", toolCall);
- functionCalls.push({
- id: toolCall.id || "",
- name: toolCall.tool_name || "unknown",
- arguments:
- (toolCall.inputs as Record<string, unknown>) || {},
- argumentsString: JSON.stringify(toolCall.inputs || {}),
- result: toolCall.results as
- | Record<string, unknown>
- | ToolCallResult[],
- status:
- (toolCall.status as "pending" | "completed" | "error") ||
- "completed",
- type: "tool_call",
- });
- }
- // Handle OpenAI format: chunks[].delta.tool_calls
- else if (chunk.delta?.tool_calls) {
- for (const toolCall of chunk.delta.tool_calls) {
- if (toolCall.function) {
- functionCalls.push({
- id: toolCall.id || "",
- name: toolCall.function.name || "unknown",
- arguments: toolCall.function.arguments
- ? JSON.parse(toolCall.function.arguments)
- : {},
- argumentsString: toolCall.function.arguments || "",
- status: "completed",
- type: toolCall.type || "function",
- });
- }
- }
- }
- // Process tool call results from chunks
- if (
- chunk.type === "response.tool_call.result" ||
- chunk.type === "tool_call_result"
- ) {
- const lastCall = functionCalls[functionCalls.length - 1];
- if (lastCall) {
- lastCall.result =
- (chunk.result as
- | Record<string, unknown>
- | ToolCallResult[]) ||
- (chunk as Record<string, unknown>);
- lastCall.status = "completed";
- }
- }
- }
- }
-
- // Process response_data (non-streaming data)
- if (msg.response_data && typeof msg.response_data === "object") {
- // Look for tool_calls in various places in the response data
- const responseData =
- typeof msg.response_data === "string"
- ? JSON.parse(msg.response_data)
- : msg.response_data;
-
- if (
- responseData.tool_calls &&
- Array.isArray(responseData.tool_calls)
- ) {
- for (const toolCall of responseData.tool_calls) {
- functionCalls.push({
- id: toolCall.id,
- name: toolCall.function?.name || toolCall.name,
- arguments:
- toolCall.function?.arguments || toolCall.arguments,
- argumentsString:
- typeof (
- toolCall.function?.arguments || toolCall.arguments
- ) === "string"
- ? toolCall.function?.arguments || toolCall.arguments
- : JSON.stringify(
- toolCall.function?.arguments || toolCall.arguments,
- ),
- result: toolCall.result,
- status: "completed",
- type: toolCall.type || "function",
- });
- }
- }
- }
-
- if (functionCalls.length > 0) {
- console.log("Setting functionCalls on message:", functionCalls);
- message.functionCalls = functionCalls;
- } else {
- console.log("No function calls found in message");
- }
-
- // Extract usage data from response_data
- if (msg.response_data && typeof msg.response_data === "object") {
- const responseData =
- typeof msg.response_data === "string"
- ? JSON.parse(msg.response_data)
- : msg.response_data;
- if (responseData.usage) {
- message.usage = responseData.usage;
- }
- }
- }
-
- return message;
- },
- );
-
- setMessages(convertedMessages);
- lastLoadedConversationRef.current = conversationData.response_id;
-
- // Set the previous response ID for this conversation
- setPreviousResponseIds((prev) => ({
- ...prev,
- [conversationData.endpoint]: conversationData.response_id,
- }));
-
- // Focus input when loading a conversation
- setTimeout(() => {
- chatInputRef.current?.focusInput();
- }, 100);
- } else if (!conversationData) {
- // No conversation selected (new conversation)
- lastLoadedConversationRef.current = null;
- }
- }, [
- conversationData,
- isUserInteracting,
- isForkingInProgress,
- setPreviousResponseIds,
- ]);
-
- // Handle new conversation creation - only reset messages when placeholderConversation is set
- useEffect(() => {
- if (placeholderConversation && currentConversationId === null) {
- console.log("Starting new conversation");
- setMessages([
- {
- role: "assistant",
- content: "How can I assist?",
- timestamp: new Date(),
- },
- ]);
- lastLoadedConversationRef.current = null;
-
- // Focus input when starting a new conversation
- setTimeout(() => {
- chatInputRef.current?.focusInput();
- }, 100);
- }
- }, [placeholderConversation, currentConversationId]);
-
- // Listen for file upload events from navigation
- useEffect(() => {
- const handleFileUploadStart = (event: CustomEvent) => {
- const { filename } = event.detail;
- console.log("Chat page received file upload start event:", filename);
-
- setLoading(true);
- setIsUploading(true);
- setUploadedFile(null); // Clear previous file
- };
-
- const handleFileUploaded = (event: CustomEvent) => {
- const { result } = event.detail;
- console.log("Chat page received file upload event:", result);
-
- setUploadedFile(null); // Clear file after upload
-
- // Update the response ID for this endpoint
- if (result.response_id) {
- setPreviousResponseIds((prev) => ({
- ...prev,
- [endpoint]: result.response_id,
- }));
- }
- };
-
- const handleFileUploadComplete = () => {
- console.log("Chat page received file upload complete event");
- setLoading(false);
- setIsUploading(false);
- };
-
- const handleFileUploadError = (event: CustomEvent) => {
- const { filename, error } = event.detail;
- console.log(
- "Chat page received file upload error event:",
- filename,
- error,
- );
-
- // Replace the last message with error message
- const errorMessage: Message = {
- role: "assistant",
- content: `❌ Upload failed for **${filename}**: ${error}`,
- timestamp: new Date(),
- };
- setMessages((prev) => [...prev.slice(0, -1), errorMessage]);
- setUploadedFile(null); // Clear file on error
- };
-
- window.addEventListener(
- "fileUploadStart",
- handleFileUploadStart as EventListener,
- );
- window.addEventListener(
- "fileUploaded",
- handleFileUploaded as EventListener,
- );
- window.addEventListener(
- "fileUploadComplete",
- handleFileUploadComplete as EventListener,
- );
- window.addEventListener(
- "fileUploadError",
- handleFileUploadError as EventListener,
- );
-
- return () => {
- window.removeEventListener(
- "fileUploadStart",
- handleFileUploadStart as EventListener,
- );
- window.removeEventListener(
- "fileUploaded",
- handleFileUploaded as EventListener,
- );
- window.removeEventListener(
- "fileUploadComplete",
- handleFileUploadComplete as EventListener,
- );
- window.removeEventListener(
- "fileUploadError",
- handleFileUploadError as EventListener,
- );
- };
- }, [endpoint, setPreviousResponseIds, setLoading]);
-
- // Get settings to check onboarding completion
- const { data: settings } = useGetSettingsQuery();
-
- // Check if onboarding is complete (current_step >= 4 means complete)
- const TOTAL_ONBOARDING_STEPS = 4;
- const isOnboardingComplete =
- settings?.onboarding?.current_step !== undefined &&
- settings.onboarding.current_step >= TOTAL_ONBOARDING_STEPS;
-
- // Prepare filters for nudges (same as chat)
- const processedFiltersForNudges = parsedFilterData?.filters
- ? (() => {
- const filters = parsedFilterData.filters;
- const processed: SelectedFilters = {
- data_sources: [],
- document_types: [],
- owners: [],
- };
- processed.data_sources = filters.data_sources.includes("*")
- ? []
- : filters.data_sources;
- processed.document_types = filters.document_types.includes("*")
- ? []
- : filters.document_types;
- processed.owners = filters.owners.includes("*") ? [] : filters.owners;
-
- const hasFilters =
- processed.data_sources.length > 0 ||
- processed.document_types.length > 0 ||
- processed.owners.length > 0;
- return hasFilters ? processed : undefined;
- })()
- : undefined;
-
- const { data: nudges = [], cancel: cancelNudges } = useGetNudgesQuery(
- {
- chatId: previousResponseIds[endpoint],
- filters: processedFiltersForNudges,
- limit: parsedFilterData?.limit ?? 3,
- scoreThreshold: parsedFilterData?.scoreThreshold ?? 0,
- },
- {
- enabled: isOnboardingComplete && !isConversationsLoading, // Only fetch nudges after onboarding is complete AND chat history is not loading
- },
- );
-
- const handleSSEStream = async (
- userMessage: Message,
- previousResponseId?: string,
- ) => {
- // Prepare filters
- const processedFilters = parsedFilterData?.filters
- ? (() => {
- const filters = parsedFilterData.filters;
- const processed: SelectedFilters = {
- data_sources: [],
- document_types: [],
- owners: [],
- };
- processed.data_sources = filters.data_sources.includes("*")
- ? []
- : filters.data_sources;
- processed.document_types = filters.document_types.includes("*")
- ? []
- : filters.document_types;
- processed.owners = filters.owners.includes("*") ? [] : filters.owners;
-
- const hasFilters =
- processed.data_sources.length > 0 ||
- processed.document_types.length > 0 ||
- processed.owners.length > 0;
- return hasFilters ? processed : undefined;
- })()
- : undefined;
-
- // Use passed previousResponseId if available, otherwise fall back to state
- const responseIdToUse = previousResponseId || previousResponseIds[endpoint];
-
- console.log("[CHAT] Sending streaming message:", {
- conversationFilter: conversationFilter?.id,
- currentConversationId,
- responseIdToUse,
- });
-
- // Use the hook to send the message
- await sendStreamingMessage({
- prompt: userMessage.content,
- previousResponseId: responseIdToUse || undefined,
- filters: processedFilters,
- filter_id: conversationFilter?.id, // ✅ Add filter_id for this conversation
- limit: parsedFilterData?.limit ?? 10,
- scoreThreshold: parsedFilterData?.scoreThreshold ?? 0,
- });
- scrollToBottom({
- animation: "smooth",
- duration: 1000,
- });
- };
-
- const handleSendMessage = async (
- inputMessage: string,
- previousResponseId?: string,
- ) => {
- if (!inputMessage.trim() || loading) return;
-
- const userMessage: Message = {
- role: "user",
- content: inputMessage.trim(),
- timestamp: new Date(),
- };
-
- if (messages.length === 1) {
- setMessages([userMessage]);
- } else {
- setMessages((prev) => [...prev, userMessage]);
- }
- setInput("");
- setLoading(true);
- setIsFilterHighlighted(false);
-
- scrollToBottom({
- animation: "smooth",
- duration: 1000,
- });
-
- if (asyncMode) {
- await handleSSEStream(userMessage, previousResponseId);
- } else {
- // Original non-streaming logic
- try {
- const apiEndpoint = endpoint === "chat" ? "/api/chat" : "/api/langflow";
-
- const requestBody: RequestBody = {
- prompt: userMessage.content,
- ...(parsedFilterData?.filters &&
- (() => {
- const filters = parsedFilterData.filters;
- const processed: SelectedFilters = {
- data_sources: [],
- document_types: [],
- owners: [],
- };
- // Only copy non-wildcard arrays
- processed.data_sources = filters.data_sources.includes("*")
- ? []
- : filters.data_sources;
- processed.document_types = filters.document_types.includes("*")
- ? []
- : filters.document_types;
- processed.owners = filters.owners.includes("*")
- ? []
- : filters.owners;
-
- // Only include filters if any array has values
- const hasFilters =
- processed.data_sources.length > 0 ||
- processed.document_types.length > 0 ||
- processed.owners.length > 0;
- return hasFilters ? { filters: processed } : {};
- })()),
- limit: parsedFilterData?.limit ?? 10,
- scoreThreshold: parsedFilterData?.scoreThreshold ?? 0,
- };
-
- // Add previous_response_id if we have one for this endpoint
- const currentResponseId = previousResponseIds[endpoint];
- if (currentResponseId) {
- requestBody.previous_response_id = currentResponseId;
- }
-
- // Add filter_id if a filter is selected for this conversation
- if (conversationFilter) {
- requestBody.filter_id = conversationFilter.id;
- }
-
- // Debug logging
- console.log("[DEBUG] Sending message with:", {
- previous_response_id: requestBody.previous_response_id,
- filter_id: requestBody.filter_id,
- currentConversationId,
- previousResponseIds,
- });
-
- const response = await fetch(apiEndpoint, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(requestBody),
- });
-
- const result = await response.json();
-
- if (response.ok) {
- const assistantMessage: Message = {
- role: "assistant",
- content: result.response,
- timestamp: new Date(),
- usage: result.usage,
- };
- setMessages((prev) => [...prev, assistantMessage]);
- if (result.response_id) {
- cancelNudges();
- }
-
- // Store the response ID if present for this endpoint
- if (result.response_id) {
- console.log(
- "[DEBUG] Received response_id:",
- result.response_id,
- "currentConversationId:",
- currentConversationId,
- );
-
- setPreviousResponseIds((prev) => ({
- ...prev,
- [endpoint]: result.response_id,
- }));
-
- // If this is a new conversation (no currentConversationId), set it now
- if (!currentConversationId) {
- console.log(
- "[DEBUG] Setting currentConversationId to:",
- result.response_id,
- );
- setCurrentConversationId(result.response_id);
- refreshConversations(true);
- } else {
- console.log(
- "[DEBUG] Existing conversation, doing silent refresh",
- );
- // For existing conversations, do a silent refresh to keep backend in sync
- refreshConversationsSilent();
- }
-
- // Carry forward the filter association to the new response_id
- if (conversationFilter && typeof window !== "undefined") {
- const newKey = `conversation_filter_${result.response_id}`;
- localStorage.setItem(newKey, conversationFilter.id);
- console.log(
- "[DEBUG] Saved filter association:",
- newKey,
- "=",
- conversationFilter.id,
- );
- }
- }
- } else {
- console.error("Chat failed:", result.error);
- // Set chat error flag to trigger test_completion=true on health checks
- setChatError(true);
- const errorMessage: Message = {
- role: "assistant",
- content: "Sorry, I encountered an error. Please try again.",
- timestamp: new Date(),
- };
- setMessages((prev) => [...prev, errorMessage]);
- }
- } catch (error) {
- console.error("Chat error:", error);
- // Set chat error flag to trigger test_completion=true on health checks
- setChatError(true);
- const errorMessage: Message = {
- role: "assistant",
- content:
- "Sorry, I couldn't connect to the chat service. Please try again.",
- timestamp: new Date(),
- };
- setMessages((prev) => [...prev, errorMessage]);
- }
- }
-
- setLoading(false);
- };
-
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault();
-
- // Check if there's an uploaded file and upload it first
- let uploadedResponseId: string | null = null;
- if (uploadedFile) {
- // Upload the file first
- const responseId = await handleFileUpload(uploadedFile);
- // Clear the file after upload
- setUploadedFile(null);
-
- // If the upload resulted in a new conversation, store the response ID
- if (responseId) {
- uploadedResponseId = responseId;
- setPreviousResponseIds((prev) => ({
- ...prev,
- [endpoint]: responseId,
- }));
- }
- }
-
- // Only send message if there's input text
- if (input.trim() || uploadedFile) {
- // Pass the responseId from upload (if any) to handleSendMessage
- handleSendMessage(
- !input.trim() ? FILE_CONFIRMATION : input,
- uploadedResponseId || undefined,
- );
- }
- };
-
- const toggleFunctionCall = (functionCallId: string) => {
- setExpandedFunctionCalls((prev) => {
- const newSet = new Set(prev);
- if (newSet.has(functionCallId)) {
- newSet.delete(functionCallId);
- } else {
- newSet.add(functionCallId);
- }
- return newSet;
- });
- };
-
- const handleForkConversation = (
- messageIndex: number,
- event?: React.MouseEvent,
- ) => {
- // Prevent any default behavior and stop event propagation
- if (event) {
- event.preventDefault();
- event.stopPropagation();
- }
-
- // Set interaction state to prevent auto-scroll interference
- setIsUserInteracting(true);
- setIsForkingInProgress(true);
-
- console.log("Fork conversation called for message index:", messageIndex);
-
- // Get messages up to and including the selected assistant message
- const messagesToKeep = messages.slice(0, messageIndex + 1);
-
- // The selected message should be an assistant message (since fork button is only on assistant messages)
- const forkedMessage = messages[messageIndex];
- if (forkedMessage.role !== "assistant") {
- console.error("Fork button should only be on assistant messages");
- setIsUserInteracting(false);
- setIsForkingInProgress(false);
- return;
- }
-
- // For forking, we want to continue from the response_id of the assistant message we're forking from
- // Since we don't store individual response_ids per message yet, we'll use the current conversation's response_id
- // This means we're continuing the conversation thread from that point
- const responseIdToForkFrom =
- currentConversationId || previousResponseIds[endpoint];
-
- // Create a new conversation by properly forking
- setMessages(messagesToKeep);
-
- // Use the chat context's fork method which handles creating a new conversation properly
- if (forkFromResponse) {
- forkFromResponse(responseIdToForkFrom || "");
- } else {
- // Fallback to manual approach
- setCurrentConversationId(null); // This creates a new conversation thread
-
- // Set the response_id we want to continue from as the previous response ID
- // This tells the backend to continue the conversation from this point
- setPreviousResponseIds((prev) => ({
- ...prev,
- [endpoint]: responseIdToForkFrom,
- }));
- }
-
- console.log("Forked conversation with", messagesToKeep.length, "messages");
-
- // Reset interaction state after a longer delay to ensure all effects complete
- setTimeout(() => {
- setIsUserInteracting(false);
- setIsForkingInProgress(false);
- console.log("Fork interaction complete, re-enabling auto effects");
- }, 500);
-
- // The original conversation remains unchanged in the sidebar
- // This new forked conversation will get its own response_id when the user sends the next message
- };
-
- const handleSuggestionClick = (suggestion: string) => {
- handleSendMessage(suggestion);
- };
-
- return (
- <>
- {/* Debug header - only show in debug mode */}
- {isDebugMode && (
- <div className="flex items-center justify-between p-6">
- <div className="flex items-center gap-2"></div>
- <div className="flex items-center gap-4">
- {/* Async Mode Toggle */}
- <div className="flex items-center gap-2 bg-muted/50 rounded-lg p-1">
- <Button
- variant={!asyncMode ? "default" : "ghost"}
- size="sm"
- onClick={() => setAsyncMode(false)}
- className="h-7 text-xs"
- >
- Streaming Off
- </Button>
- <Button
- variant={asyncMode ? "default" : "ghost"}
- size="sm"
- onClick={() => setAsyncMode(true)}
- className="h-7 text-xs"
- >
- <Zap className="h-3 w-3 mr-1" />
- Streaming On
- </Button>
- </div>
- {/* Endpoint Toggle */}
- <div className="flex items-center gap-2 bg-muted/50 rounded-lg p-1">
- <Button
- variant={endpoint === "chat" ? "default" : "ghost"}
- size="sm"
- onClick={() => handleEndpointChange("chat")}
- className="h-7 text-xs"
- >
- Chat
- </Button>
- <Button
- variant={endpoint === "langflow" ? "default" : "ghost"}
- size="sm"
- onClick={() => handleEndpointChange("langflow")}
- className="h-7 text-xs"
- >
- Langflow
- </Button>
- </div>
- </div>
- </div>
- )}
-
- <StickToBottom.Content className="flex flex-col min-h-full overflow-x-hidden p-6">
- <div className="flex flex-col place-self-center space-y-6 max-w-[960px] w-full mx-auto">
- {messages.length === 0 && !streamingMessage ? (
- <div className="flex items-center justify-center h-full text-muted-foreground">
- <div className="text-center">
- {isUploading ? (
- <>
- <Loader2 className="h-12 w-12 mx-auto mb-4 animate-spin" />
- <p>Processing your document...</p>
- <p className="text-sm mt-2">This may take a few moments</p>
- </>
- ) : null}
- </div>
- </div>
- ) : (
- <>
- {messages.map((message, index) =>
- message.role === "user"
- ? (messages[index]?.content.match(FILES_REGEX)?.[0] ??
- null) === null && (
- <div
- key={`${
- message.role
- }-${index}-${message.timestamp?.getTime()}`}
- className="space-y-6 group"
- >
- <UserMessage
- animate={
- message.source
- ? message.source !== "langflow"
- : false
- }
- content={
- index >= 2 &&
- (messages[index - 2]?.content.match(
- FILES_REGEX,
- )?.[0] ??
- undefined) &&
- message.content === FILE_CONFIRMATION
- ? undefined
- : message.content
- }
- files={
- index >= 2
- ? (messages[index - 2]?.content.match(
- FILES_REGEX,
- )?.[0] ?? undefined)
- : undefined
- }
- />
- </div>
- )
- : message.role === "assistant" &&
- (index < 1 ||
- (messages[index - 1]?.content.match(FILES_REGEX)?.[0] ??
- null) === null) && (
- <div
- key={`${
- message.role
- }-${index}-${message.timestamp?.getTime()}`}
- className="space-y-6 group"
- >
- <AssistantMessage
- content={message.content}
- functionCalls={message.functionCalls}
- messageIndex={index}
- expandedFunctionCalls={expandedFunctionCalls}
- onToggle={toggleFunctionCall}
- showForkButton={endpoint === "chat"}
- onFork={(e) => handleForkConversation(index, e)}
- animate={false}
- isInactive={index < messages.length - 1}
- isInitialGreeting={
- index === 0 &&
- messages.length === 1 &&
- message.content === "How can I assist?"
- }
- usage={message.usage}
- />
- </div>
- ),
- )}
-
- {/* Streaming Message Display */}
- {streamingMessage && (
- <AssistantMessage
- content={streamingMessage.content}
- functionCalls={streamingMessage.functionCalls}
- messageIndex={messages.length}
- expandedFunctionCalls={expandedFunctionCalls}
- onToggle={toggleFunctionCall}
- delay={0.4}
- isStreaming
- isCompleted={false}
- />
- )}
-
- {/* Waiting too long indicator */}
- {waitingTooLong && !streamingMessage && loading && (
- <div className="pl-10 space-y-2">
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <Loader2 className="h-4 w-4 animate-spin" />
- <span>The server is taking longer than expected...</span>
- </div>
- <p className="text-xs text-muted-foreground">
- This may be due to high server load. The request will
- timeout after 60 seconds.
- </p>
- </div>
- )}
- </>
- )}
- {!streamingMessage && (
- <div className="pl-10">
- <Nudges
- nudges={loading ? [] : (nudges as string[])}
- handleSuggestionClick={handleSuggestionClick}
- />
- </div>
- )}
- </div>
- </StickToBottom.Content>
- <div className="p-6 pt-0 max-w-[960px] mx-auto w-full">
- {/* Input Area - Fixed at bottom */}
- <ChatInput
- ref={chatInputRef}
- input={input}
- loading={loading}
- isUploading={isUploading}
- selectedFilter={selectedFilter}
- parsedFilterData={parsedFilterData}
- uploadedFile={uploadedFile}
- onSubmit={handleSubmit}
- onChange={setInput}
- onKeyDown={(e) => {
- // Handle backspace for filter clearing
- if (
- e.key === "Backspace" &&
- selectedFilter &&
- input.trim() === ""
- ) {
- e.preventDefault();
- if (isFilterHighlighted) {
- // Second backspace - remove the filter
- setConversationFilter(null);
- setIsFilterHighlighted(false);
- } else {
- // First backspace - highlight the filter
- setIsFilterHighlighted(true);
- }
- return;
- }
-
- // Handle Enter key for form submission
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- if (input.trim() && !loading) {
- // Trigger form submission by finding the form and calling submit
- const form = e.currentTarget.closest("form");
- if (form) {
- form.requestSubmit();
- }
- }
- }
- }}
- onFilterSelect={handleFilterSelect}
- onFilePickerClick={handleFilePickerClick}
- onFileSelected={setUploadedFile}
- setSelectedFilter={setConversationFilter}
- setIsFilterHighlighted={setIsFilterHighlighted}
- />
- </div>
- </>
- );
+ const isDebugMode = process.env.NEXT_PUBLIC_OPENRAG_DEBUG === "true";
+ const {
+ endpoint,
+ setEndpoint,
+ currentConversationId,
+ conversationData,
+ setCurrentConversationId,
+ addConversationDoc,
+ forkFromResponse,
+ refreshConversations,
+ refreshConversationsSilent,
+ refreshTrigger,
+ previousResponseIds,
+ setPreviousResponseIds,
+ placeholderConversation,
+ conversationFilter,
+ setConversationFilter,
+ } = useChat();
+ const [messages, setMessages] = useState<Message[]>([
+ {
+ role: "assistant",
+ content: "How can I assist?",
+ timestamp: new Date(),
+ },
+ ]);
+ const [input, setInput] = useState("");
+ const { loading, setLoading } = useLoadingStore();
+ const { setChatError } = useChat();
+ const [asyncMode, setAsyncMode] = useState(true);
+ const [expandedFunctionCalls, setExpandedFunctionCalls] = useState<
+ Set<string>
+ >(new Set());
+ // previousResponseIds now comes from useChat context
+ const [isUploading, setIsUploading] = useState(false);
+ const [isFilterHighlighted, setIsFilterHighlighted] = useState(false);
+ const [isUserInteracting, setIsUserInteracting] = useState(false);
+ const [isForkingInProgress, setIsForkingInProgress] = useState(false);
+ const [uploadedFile, setUploadedFile] = useState<File | null>(null);
+ const [waitingTooLong, setWaitingTooLong] = useState(false);
+
+ const chatInputRef = useRef<ChatInputHandle>(null);
+
+ const { scrollToBottom } = useStickToBottomContext();
+
+ const lastLoadedConversationRef = useRef<string | null>(null);
+ const { addTask } = useTask();
+
+ // Check if chat history is loading
+ const { isLoading: isConversationsLoading } = useGetConversationsQuery(
+ endpoint,
+ refreshTrigger,
+ );
+
+ // Use conversation-specific filter instead of global filter
+ const selectedFilter = conversationFilter;
+
+ // Parse the conversation filter data
+ const parsedFilterData = useMemo(() => {
+ if (!selectedFilter?.query_data) return null;
+ try {
+ return JSON.parse(selectedFilter.query_data);
+ } catch (error) {
+ console.error("Error parsing filter data:", error);
+ return null;
+ }
+ }, [selectedFilter]);
+
+ // Use the chat streaming hook
+ const apiEndpoint = endpoint === "chat" ? "/api/chat" : "/api/langflow";
+ const {
+ streamingMessage,
+ sendMessage: sendStreamingMessage,
+ abortStream,
+ isLoading: isStreamLoading,
+ } = useChatStreaming({
+ endpoint: apiEndpoint,
+ onComplete: (message, responseId) => {
+ setMessages((prev) => [...prev, message]);
+ setLoading(false);
+ setWaitingTooLong(false);
+ if (responseId) {
+ cancelNudges();
+ setPreviousResponseIds((prev) => ({
+ ...prev,
+ [endpoint]: responseId,
+ }));
+
+ if (!currentConversationId) {
+ setCurrentConversationId(responseId);
+ refreshConversations(true);
+ } else {
+ refreshConversationsSilent();
+ }
+
+ // Save filter association for this response
+ if (conversationFilter && typeof window !== "undefined") {
+ const newKey = `conversation_filter_${responseId}`;
+ localStorage.setItem(newKey, conversationFilter.id);
+ console.log(
+ "[CHAT] Saved filter association:",
+ newKey,
+ "=",
+ conversationFilter.id,
+ );
+ }
+ }
+ },
+ onError: (error) => {
+ console.error("Streaming error:", error);
+ setLoading(false);
+ setWaitingTooLong(false);
+ // Set chat error flag to trigger test_completion=true on health checks
+ setChatError(true);
+ const errorMessage: Message = {
+ role: "assistant",
+ content:
+ "Sorry, I couldn't connect to the chat service. Please try again.",
+ timestamp: new Date(),
+ };
+ setMessages((prev) => [...prev, errorMessage]);
+ },
+ });
+
+ // Show warning if waiting too long (20 seconds)
+ useEffect(() => {
+ let timeoutId: NodeJS.Timeout | null = null;
+
+ if (isStreamLoading && !streamingMessage) {
+ timeoutId = setTimeout(() => {
+ setWaitingTooLong(true);
+ }, 20000); // 20 seconds
+ } else {
+ setWaitingTooLong(false);
+ }
+
+ return () => {
+ if (timeoutId) clearTimeout(timeoutId);
+ };
+ }, [isStreamLoading, streamingMessage]);
+
+ const handleEndpointChange = (newEndpoint: EndpointType) => {
+ setEndpoint(newEndpoint);
+ // Clear the conversation when switching endpoints to avoid response ID conflicts
+ setMessages([]);
+ setPreviousResponseIds({ chat: null, langflow: null });
+ };
+
+ const handleFileUpload = async (file: File) => {
+ console.log("handleFileUpload called with file:", file.name);
+
+ if (isUploading) return;
+
+ setIsUploading(true);
+ setLoading(true);
+
+ try {
+ const formData = new FormData();
+ formData.append("file", file);
+ formData.append("endpoint", endpoint);
+
+ // Add previous_response_id if we have one for this endpoint
+ const currentResponseId = previousResponseIds[endpoint];
+ if (currentResponseId) {
+ formData.append("previous_response_id", currentResponseId);
+ }
+
+ const response = await fetch("/api/upload_context", {
+ method: "POST",
+ body: formData,
+ });
+
+ console.log("Upload response status:", response.status);
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ console.error(
+ "Upload failed with status:",
+ response.status,
+ "Response:",
+ errorText,
+ );
+ throw new Error("Failed to process document");
+ }
+
+ const result = await response.json();
+ console.log("Upload result:", result);
+
+ if (!response.ok) {
+ // Set chat error flag if upload fails
+ setChatError(true);
+ }
+
+ if (response.status === 201) {
+ // New flow: Got task ID, start tracking with centralized system
+ const taskId = result.task_id || result.id;
+
+ if (!taskId) {
+ console.error("No task ID in 201 response:", result);
+ throw new Error("No task ID received from server");
+ }
+
+ // Add task to centralized tracking
+ addTask(taskId);
+
+ return null;
+ } else if (response.ok) {
+ // Original flow: Direct response
+
+ const uploadMessage: Message = {
+ role: "user",
+ content: `I'm uploading a document called "${result.filename}". Here is its content:`,
+ timestamp: new Date(),
+ };
+
+ const confirmationMessage: Message = {
+ role: "assistant",
+ content: `Confirmed`,
+ timestamp: new Date(),
+ };
+
+ setMessages((prev) => [...prev, uploadMessage, confirmationMessage]);
+
+ // Add file to conversation docs
+ if (result.filename) {
+ addConversationDoc(result.filename);
+ }
+
+ // Update the response ID for this endpoint
+ if (result.response_id) {
+ setPreviousResponseIds((prev) => ({
+ ...prev,
+ [endpoint]: result.response_id,
+ }));
+
+ // If this is a new conversation (no currentConversationId), set it now
+ if (!currentConversationId) {
+ setCurrentConversationId(result.response_id);
+ refreshConversations(true);
+ } else {
+ // For existing conversations, do a silent refresh to keep backend in sync
+ refreshConversationsSilent();
+ }
+
+ return result.response_id;
+ }
+ } else {
+ throw new Error(`Upload failed: ${response.status}`);
+ }
+ } catch (error) {
+ console.error("Upload failed:", error);
+ // Set chat error flag to trigger test_completion=true on health checks
+ setChatError(true);
+ const errorMessage: Message = {
+ role: "assistant",
+ content: `❌ Failed to process document. Please try again.`,
+ timestamp: new Date(),
+ };
+ setMessages((prev) => [...prev.slice(0, -1), errorMessage]);
+ } finally {
+ setIsUploading(false);
+ setLoading(false);
+ }
+ };
+
+ const handleFilePickerClick = () => {
+ chatInputRef.current?.clickFileInput();
+ };
+
+ const handleFilterSelect = (filter: KnowledgeFilterData | null) => {
+ // Update conversation-specific filter
+ setConversationFilter(filter);
+ setIsFilterHighlighted(false);
+ };
+
+ // Auto-focus the input on component mount
+ useEffect(() => {
+ chatInputRef.current?.focusInput();
+ }, []);
+
+ // Explicitly handle external new conversation trigger
+ useEffect(() => {
+ const handleNewConversation = () => {
+ // Abort any in-flight streaming so it doesn't bleed into new chat
+ abortStream();
+ // Reset chat UI even if context state was already 'new'
+ setMessages([
+ {
+ role: "assistant",
+ content: "How can I assist?",
+ timestamp: new Date(),
+ },
+ ]);
+ setInput("");
+ setExpandedFunctionCalls(new Set());
+ setIsFilterHighlighted(false);
+ setLoading(false);
+ lastLoadedConversationRef.current = null;
+
+ // Focus input after a short delay to ensure rendering is complete
+ setTimeout(() => {
+ chatInputRef.current?.focusInput();
+ }, 100);
+ };
+
+ const handleFocusInput = () => {
+ chatInputRef.current?.focusInput();
+ };
+
+ window.addEventListener("newConversation", handleNewConversation);
+ window.addEventListener("focusInput", handleFocusInput);
+ return () => {
+ window.removeEventListener("newConversation", handleNewConversation);
+ window.removeEventListener("focusInput", handleFocusInput);
+ };
+ }, [abortStream, setLoading]);
+
+ // Load conversation only when user explicitly selects a conversation
+ useEffect(() => {
+ // Only load conversation data when:
+ // 1. conversationData exists AND
+ // 2. It's different from the last loaded conversation AND
+ // 3. User is not in the middle of an interaction
+ if (
+ conversationData?.messages &&
+ lastLoadedConversationRef.current !== conversationData.response_id &&
+ !isUserInteracting &&
+ !isForkingInProgress
+ ) {
+ console.log(
+ "Loading conversation with",
+ conversationData.messages.length,
+ "messages",
+ );
+ // Convert backend message format to frontend Message interface
+ const convertedMessages: Message[] = conversationData.messages.map(
+ (msg: {
+ role: string;
+ content: string;
+ timestamp?: string;
+ response_id?: string;
+ chunks?: Array<{
+ item?: {
+ type?: string;
+ tool_name?: string;
+ id?: string;
+ inputs?: unknown;
+ results?: unknown;
+ status?: string;
+ };
+ delta?: {
+ tool_calls?: Array<{
+ id?: string;
+ function?: { name?: string; arguments?: string };
+ type?: string;
+ }>;
+ };
+ type?: string;
+ result?: unknown;
+ output?: unknown;
+ response?: unknown;
+ }>;
+ response_data?: unknown;
+ }) => {
+ const message: Message = {
+ role: msg.role as "user" | "assistant",
+ content: msg.content,
+ timestamp: new Date(msg.timestamp || new Date()),
+ };
+
+ // Extract function calls from chunks or response_data
+ if (msg.role === "assistant" && (msg.chunks || msg.response_data)) {
+ const functionCalls: FunctionCall[] = [];
+ console.log("Processing assistant message for function calls:", {
+ hasChunks: !!msg.chunks,
+ chunksLength: msg.chunks?.length,
+ hasResponseData: !!msg.response_data,
+ });
+
+ // Process chunks (streaming data)
+ if (msg.chunks && Array.isArray(msg.chunks)) {
+ for (const chunk of msg.chunks) {
+ // Handle Langflow format: chunks[].item.tool_call
+ if (chunk.item && chunk.item.type === "tool_call") {
+ const toolCall = chunk.item;
+ console.log("Found Langflow tool call:", toolCall);
+ functionCalls.push({
+ id: toolCall.id || "",
+ name: toolCall.tool_name || "unknown",
+ arguments:
+ (toolCall.inputs as Record<string, unknown>) || {},
+ argumentsString: JSON.stringify(toolCall.inputs || {}),
+ result: toolCall.results as
+ | Record<string, unknown>
+ | ToolCallResult[],
+ status:
+ (toolCall.status as "pending" | "completed" | "error") ||
+ "completed",
+ type: "tool_call",
+ });
+ }
+ // Handle OpenAI format: chunks[].delta.tool_calls
+ else if (chunk.delta?.tool_calls) {
+ for (const toolCall of chunk.delta.tool_calls) {
+ if (toolCall.function) {
+ functionCalls.push({
+ id: toolCall.id || "",
+ name: toolCall.function.name || "unknown",
+ arguments: toolCall.function.arguments
+ ? JSON.parse(toolCall.function.arguments)
+ : {},
+ argumentsString: toolCall.function.arguments || "",
+ status: "completed",
+ type: toolCall.type || "function",
+ });
+ }
+ }
+ }
+ // Process tool call results from chunks
+ if (
+ chunk.type === "response.tool_call.result" ||
+ chunk.type === "tool_call_result"
+ ) {
+ const lastCall = functionCalls[functionCalls.length - 1];
+ if (lastCall) {
+ lastCall.result =
+ (chunk.result as
+ | Record<string, unknown>
+ | ToolCallResult[]) ||
+ (chunk as Record<string, unknown>);
+ lastCall.status = "completed";
+ }
+ }
+ }
+ }
+
+ // Process response_data (non-streaming data)
+ if (msg.response_data && typeof msg.response_data === "object") {
+ // Look for tool_calls in various places in the response data
+ const responseData =
+ typeof msg.response_data === "string"
+ ? JSON.parse(msg.response_data)
+ : msg.response_data;
+
+ if (
+ responseData.tool_calls &&
+ Array.isArray(responseData.tool_calls)
+ ) {
+ for (const toolCall of responseData.tool_calls) {
+ functionCalls.push({
+ id: toolCall.id,
+ name: toolCall.function?.name || toolCall.name,
+ arguments:
+ toolCall.function?.arguments || toolCall.arguments,
+ argumentsString:
+ typeof (
+ toolCall.function?.arguments || toolCall.arguments
+ ) === "string"
+ ? toolCall.function?.arguments || toolCall.arguments
+ : JSON.stringify(
+ toolCall.function?.arguments || toolCall.arguments,
+ ),
+ result: toolCall.result,
+ status: "completed",
+ type: toolCall.type || "function",
+ });
+ }
+ }
+ }
+
+ if (functionCalls.length > 0) {
+ console.log("Setting functionCalls on message:", functionCalls);
+ message.functionCalls = functionCalls;
+ } else {
+ console.log("No function calls found in message");
+ }
+
+ // Extract usage data from response_data
+ if (msg.response_data && typeof msg.response_data === "object") {
+ const responseData =
+ typeof msg.response_data === "string"
+ ? JSON.parse(msg.response_data)
+ : msg.response_data;
+ if (responseData.usage) {
+ message.usage = responseData.usage;
+ }
+ }
+ }
+
+ return message;
+ },
+ );
+
+ setMessages(convertedMessages);
+ lastLoadedConversationRef.current = conversationData.response_id;
+
+ // Set the previous response ID for this conversation
+ setPreviousResponseIds((prev) => ({
+ ...prev,
+ [conversationData.endpoint]: conversationData.response_id,
+ }));
+
+ // Focus input when loading a conversation
+ setTimeout(() => {
+ chatInputRef.current?.focusInput();
+ }, 100);
+ } else if (!conversationData) {
+ // No conversation selected (new conversation)
+ lastLoadedConversationRef.current = null;
+ }
+ }, [
+ conversationData,
+ isUserInteracting,
+ isForkingInProgress,
+ setPreviousResponseIds,
+ ]);
+
+ // Handle new conversation creation - only reset messages when placeholderConversation is set
+ useEffect(() => {
+ if (placeholderConversation && currentConversationId === null) {
+ console.log("Starting new conversation");
+ setMessages([
+ {
+ role: "assistant",
+ content: "How can I assist?",
+ timestamp: new Date(),
+ },
+ ]);
+ lastLoadedConversationRef.current = null;
+
+ // Focus input when starting a new conversation
+ setTimeout(() => {
+ chatInputRef.current?.focusInput();
+ }, 100);
+ }
+ }, [placeholderConversation, currentConversationId]);
+
+ // Listen for file upload events from navigation
+ useEffect(() => {
+ const handleFileUploadStart = (event: CustomEvent) => {
+ const { filename } = event.detail;
+ console.log("Chat page received file upload start event:", filename);
+
+ setLoading(true);
+ setIsUploading(true);
+ setUploadedFile(null); // Clear previous file
+ };
+
+ const handleFileUploaded = (event: CustomEvent) => {
+ const { result } = event.detail;
+ console.log("Chat page received file upload event:", result);
+
+ setUploadedFile(null); // Clear file after upload
+
+ // Update the response ID for this endpoint
+ if (result.response_id) {
+ setPreviousResponseIds((prev) => ({
+ ...prev,
+ [endpoint]: result.response_id,
+ }));
+ }
+ };
+
+ const handleFileUploadComplete = () => {
+ console.log("Chat page received file upload complete event");
+ setLoading(false);
+ setIsUploading(false);
+ };
+
+ const handleFileUploadError = (event: CustomEvent) => {
+ const { filename, error } = event.detail;
+ console.log(
+ "Chat page received file upload error event:",
+ filename,
+ error,
+ );
+
+ // Replace the last message with error message
+ const errorMessage: Message = {
+ role: "assistant",
+ content: `❌ Upload failed for **${filename}**: ${error}`,
+ timestamp: new Date(),
+ };
+ setMessages((prev) => [...prev.slice(0, -1), errorMessage]);
+ setUploadedFile(null); // Clear file on error
+ };
+
+ window.addEventListener(
+ "fileUploadStart",
+ handleFileUploadStart as EventListener,
+ );
+ window.addEventListener(
+ "fileUploaded",
+ handleFileUploaded as EventListener,
+ );
+ window.addEventListener(
+ "fileUploadComplete",
+ handleFileUploadComplete as EventListener,
+ );
+ window.addEventListener(
+ "fileUploadError",
+ handleFileUploadError as EventListener,
+ );
+
+ return () => {
+ window.removeEventListener(
+ "fileUploadStart",
+ handleFileUploadStart as EventListener,
+ );
+ window.removeEventListener(
+ "fileUploaded",
+ handleFileUploaded as EventListener,
+ );
+ window.removeEventListener(
+ "fileUploadComplete",
+ handleFileUploadComplete as EventListener,
+ );
+ window.removeEventListener(
+ "fileUploadError",
+ handleFileUploadError as EventListener,
+ );
+ };
+ }, [endpoint, setPreviousResponseIds, setLoading]);
+
+ // Get settings to check onboarding completion
+ const { data: settings } = useGetSettingsQuery();
+
+ // Check if onboarding is complete (current_step >= 4 means complete)
+ const TOTAL_ONBOARDING_STEPS = 4;
+ const isOnboardingComplete =
+ settings?.onboarding?.current_step !== undefined &&
+ settings.onboarding.current_step >= TOTAL_ONBOARDING_STEPS;
+
+ // Prepare filters for nudges (same as chat)
+ const processedFiltersForNudges = parsedFilterData?.filters
+ ? (() => {
+ const filters = parsedFilterData.filters;
+ const processed: SelectedFilters = {
+ data_sources: [],
+ document_types: [],
+ owners: [],
+ };
+ processed.data_sources = filters.data_sources.includes("*")
+ ? []
+ : filters.data_sources;
+ processed.document_types = filters.document_types.includes("*")
+ ? []
+ : filters.document_types;
+ processed.owners = filters.owners.includes("*") ? [] : filters.owners;
+
+ const hasFilters =
+ processed.data_sources.length > 0 ||
+ processed.document_types.length > 0 ||
+ processed.owners.length > 0;
+ return hasFilters ? processed : undefined;
+ })()
+ : undefined;
+
+ const { data: nudges = [], cancel: cancelNudges } = useGetNudgesQuery(
+ {
+ chatId: previousResponseIds[endpoint],
+ filters: processedFiltersForNudges,
+ limit: parsedFilterData?.limit ?? 3,
+ scoreThreshold: parsedFilterData?.scoreThreshold ?? 0,
+ },
+ {
+ enabled: isOnboardingComplete && !isConversationsLoading, // Only fetch nudges after onboarding is complete AND chat history is not loading
+ },
+ );
+
+ const handleSSEStream = async (
+ userMessage: Message,
+ previousResponseId?: string,
+ ) => {
+ // Prepare filters
+ const processedFilters = parsedFilterData?.filters
+ ? (() => {
+ const filters = parsedFilterData.filters;
+ const processed: SelectedFilters = {
+ data_sources: [],
+ document_types: [],
+ owners: [],
+ };
+ processed.data_sources = filters.data_sources.includes("*")
+ ? []
+ : filters.data_sources;
+ processed.document_types = filters.document_types.includes("*")
+ ? []
+ : filters.document_types;
+ processed.owners = filters.owners.includes("*") ? [] : filters.owners;
+
+ const hasFilters =
+ processed.data_sources.length > 0 ||
+ processed.document_types.length > 0 ||
+ processed.owners.length > 0;
+ return hasFilters ? processed : undefined;
+ })()
+ : undefined;
+
+ // Use passed previousResponseId if available, otherwise fall back to state
+ const responseIdToUse = previousResponseId || previousResponseIds[endpoint];
+
+ console.log("[CHAT] Sending streaming message:", {
+ conversationFilter: conversationFilter?.id,
+ currentConversationId,
+ responseIdToUse,
+ });
+
+ // Use the hook to send the message
+ await sendStreamingMessage({
+ prompt: userMessage.content,
+ previousResponseId: responseIdToUse || undefined,
+ filters: processedFilters,
+ filter_id: conversationFilter?.id, // ✅ Add filter_id for this conversation
+ limit: parsedFilterData?.limit ?? 10,
+ scoreThreshold: parsedFilterData?.scoreThreshold ?? 0,
+ });
+ scrollToBottom({
+ animation: "smooth",
+ duration: 1000,
+ });
+ };
+
+ const handleSendMessage = async (
+ inputMessage: string,
+ previousResponseId?: string,
+ ) => {
+ if (!inputMessage.trim() || loading) return;
+
+ const userMessage: Message = {
+ role: "user",
+ content: inputMessage.trim(),
+ timestamp: new Date(),
+ };
+
+ if (messages.length === 1) {
+ setMessages([userMessage]);
+ } else {
+ setMessages((prev) => [...prev, userMessage]);
+ }
+ setInput("");
+ setLoading(true);
+ setIsFilterHighlighted(false);
+
+ scrollToBottom({
+ animation: "smooth",
+ duration: 1000,
+ });
+
+ if (asyncMode) {
+ await handleSSEStream(userMessage, previousResponseId);
+ } else {
+ // Original non-streaming logic
+ try {
+ const apiEndpoint = endpoint === "chat" ? "/api/chat" : "/api/langflow";
+
+ const requestBody: RequestBody = {
+ prompt: userMessage.content,
+ ...(parsedFilterData?.filters &&
+ (() => {
+ const filters = parsedFilterData.filters;
+ const processed: SelectedFilters = {
+ data_sources: [],
+ document_types: [],
+ owners: [],
+ };
+ // Only copy non-wildcard arrays
+ processed.data_sources = filters.data_sources.includes("*")
+ ? []
+ : filters.data_sources;
+ processed.document_types = filters.document_types.includes("*")
+ ? []
+ : filters.document_types;
+ processed.owners = filters.owners.includes("*")
+ ? []
+ : filters.owners;
+
+ // Only include filters if any array has values
+ const hasFilters =
+ processed.data_sources.length > 0 ||
+ processed.document_types.length > 0 ||
+ processed.owners.length > 0;
+ return hasFilters ? { filters: processed } : {};
+ })()),
+ limit: parsedFilterData?.limit ?? 10,
+ scoreThreshold: parsedFilterData?.scoreThreshold ?? 0,
+ };
+
+ // Add previous_response_id if we have one for this endpoint
+ const currentResponseId = previousResponseIds[endpoint];
+ if (currentResponseId) {
+ requestBody.previous_response_id = currentResponseId;
+ }
+
+ // Add filter_id if a filter is selected for this conversation
+ if (conversationFilter) {
+ requestBody.filter_id = conversationFilter.id;
+ }
+
+ // Debug logging
+ console.log("[DEBUG] Sending message with:", {
+ previous_response_id: requestBody.previous_response_id,
+ filter_id: requestBody.filter_id,
+ currentConversationId,
+ previousResponseIds,
+ });
+
+ const response = await fetch(apiEndpoint, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(requestBody),
+ });
+
+ const result = await response.json();
+
+ if (response.ok) {
+ const assistantMessage: Message = {
+ role: "assistant",
+ content: result.response,
+ timestamp: new Date(),
+ usage: result.usage,
+ };
+ setMessages((prev) => [...prev, assistantMessage]);
+ if (result.response_id) {
+ cancelNudges();
+ }
+
+ // Store the response ID if present for this endpoint
+ if (result.response_id) {
+ console.log(
+ "[DEBUG] Received response_id:",
+ result.response_id,
+ "currentConversationId:",
+ currentConversationId,
+ );
+
+ setPreviousResponseIds((prev) => ({
+ ...prev,
+ [endpoint]: result.response_id,
+ }));
+
+ // If this is a new conversation (no currentConversationId), set it now
+ if (!currentConversationId) {
+ console.log(
+ "[DEBUG] Setting currentConversationId to:",
+ result.response_id,
+ );
+ setCurrentConversationId(result.response_id);
+ refreshConversations(true);
+ } else {
+ console.log(
+ "[DEBUG] Existing conversation, doing silent refresh",
+ );
+ // For existing conversations, do a silent refresh to keep backend in sync
+ refreshConversationsSilent();
+ }
+
+ // Carry forward the filter association to the new response_id
+ if (conversationFilter && typeof window !== "undefined") {
+ const newKey = `conversation_filter_${result.response_id}`;
+ localStorage.setItem(newKey, conversationFilter.id);
+ console.log(
+ "[DEBUG] Saved filter association:",
+ newKey,
+ "=",
+ conversationFilter.id,
+ );
+ }
+ }
+ } else {
+ console.error("Chat failed:", result.error);
+ // Set chat error flag to trigger test_completion=true on health checks
+ setChatError(true);
+ const errorMessage: Message = {
+ role: "assistant",
+ content: "Sorry, I encountered an error. Please try again.",
+ timestamp: new Date(),
+ };
+ setMessages((prev) => [...prev, errorMessage]);
+ }
+ } catch (error) {
+ console.error("Chat error:", error);
+ // Set chat error flag to trigger test_completion=true on health checks
+ setChatError(true);
+ const errorMessage: Message = {
+ role: "assistant",
+ content:
+ "Sorry, I couldn't connect to the chat service. Please try again.",
+ timestamp: new Date(),
+ };
+ setMessages((prev) => [...prev, errorMessage]);
+ }
+ }
+
+ setLoading(false);
+ };
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+
+ // Check if there's an uploaded file and upload it first
+ let uploadedResponseId: string | null = null;
+ if (uploadedFile) {
+ // Upload the file first
+ const responseId = await handleFileUpload(uploadedFile);
+ // Clear the file after upload
+ setUploadedFile(null);
+
+ // If the upload resulted in a new conversation, store the response ID
+ if (responseId) {
+ uploadedResponseId = responseId;
+ setPreviousResponseIds((prev) => ({
+ ...prev,
+ [endpoint]: responseId,
+ }));
+ }
+ }
+
+ // Only send message if there's input text
+ if (input.trim() || uploadedFile) {
+ // Pass the responseId from upload (if any) to handleSendMessage
+ handleSendMessage(
+ !input.trim() ? FILE_CONFIRMATION : input,
+ uploadedResponseId || undefined,
+ );
+ }
+ };
+
+ const toggleFunctionCall = (functionCallId: string) => {
+ setExpandedFunctionCalls((prev) => {
+ const newSet = new Set(prev);
+ if (newSet.has(functionCallId)) {
+ newSet.delete(functionCallId);
+ } else {
+ newSet.add(functionCallId);
+ }
+ return newSet;
+ });
+ };
+
+ const handleForkConversation = (
+ messageIndex: number,
+ event?: React.MouseEvent,
+ ) => {
+ // Prevent any default behavior and stop event propagation
+ if (event) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+
+ // Set interaction state to prevent auto-scroll interference
+ setIsUserInteracting(true);
+ setIsForkingInProgress(true);
+
+ console.log("Fork conversation called for message index:", messageIndex);
+
+ // Get messages up to and including the selected assistant message
+ const messagesToKeep = messages.slice(0, messageIndex + 1);
+
+ // The selected message should be an assistant message (since fork button is only on assistant messages)
+ const forkedMessage = messages[messageIndex];
+ if (forkedMessage.role !== "assistant") {
+ console.error("Fork button should only be on assistant messages");
+ setIsUserInteracting(false);
+ setIsForkingInProgress(false);
+ return;
+ }
+
+ // For forking, we want to continue from the response_id of the assistant message we're forking from
+ // Since we don't store individual response_ids per message yet, we'll use the current conversation's response_id
+ // This means we're continuing the conversation thread from that point
+ const responseIdToForkFrom =
+ currentConversationId || previousResponseIds[endpoint];
+
+ // Create a new conversation by properly forking
+ setMessages(messagesToKeep);
+
+ // Use the chat context's fork method which handles creating a new conversation properly
+ if (forkFromResponse) {
+ forkFromResponse(responseIdToForkFrom || "");
+ } else {
+ // Fallback to manual approach
+ setCurrentConversationId(null); // This creates a new conversation thread
+
+ // Set the response_id we want to continue from as the previous response ID
+ // This tells the backend to continue the conversation from this point
+ setPreviousResponseIds((prev) => ({
+ ...prev,
+ [endpoint]: responseIdToForkFrom,
+ }));
+ }
+
+ console.log("Forked conversation with", messagesToKeep.length, "messages");
+
+ // Reset interaction state after a longer delay to ensure all effects complete
+ setTimeout(() => {
+ setIsUserInteracting(false);
+ setIsForkingInProgress(false);
+ console.log("Fork interaction complete, re-enabling auto effects");
+ }, 500);
+
+ // The original conversation remains unchanged in the sidebar
+ // This new forked conversation will get its own response_id when the user sends the next message
+ };
+
+ const handleSuggestionClick = (suggestion: string) => {
+ handleSendMessage(suggestion);
+ };
+
+ return (
+ <>
+ {/* Debug header - only show in debug mode */}
+ {isDebugMode && (
+ <div className="flex items-center justify-between p-6">
+ <div className="flex items-center gap-2"></div>
+ <div className="flex items-center gap-4">
+ {/* Async Mode Toggle */}
+ <div className="flex items-center gap-2 bg-muted/50 rounded-lg p-1">
+ <Button
+ variant={!asyncMode ? "default" : "ghost"}
+ size="sm"
+ onClick={() => setAsyncMode(false)}
+ className="h-7 text-xs"
+ >
+ Streaming Off
+ </Button>
+ <Button
+ variant={asyncMode ? "default" : "ghost"}
+ size="sm"
+ onClick={() => setAsyncMode(true)}
+ className="h-7 text-xs"
+ >
+ <Zap className="h-3 w-3 mr-1" />
+ Streaming On
+ </Button>
+ </div>
+ {/* Endpoint Toggle */}
+ <div className="flex items-center gap-2 bg-muted/50 rounded-lg p-1">
+ <Button
+ variant={endpoint === "chat" ? "default" : "ghost"}
+ size="sm"
+ onClick={() => handleEndpointChange("chat")}
+ className="h-7 text-xs"
+ >
+ Chat
+ </Button>
+ <Button
+ variant={endpoint === "langflow" ? "default" : "ghost"}
+ size="sm"
+ onClick={() => handleEndpointChange("langflow")}
+ className="h-7 text-xs"
+ >
+ Langflow
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ <StickToBottom.Content className="flex flex-col min-h-full overflow-x-hidden p-6">
+ <div className="flex flex-col place-self-center space-y-6 max-w-[960px] w-full mx-auto">
+ {messages.length === 0 && !streamingMessage ? (
+ <div className="flex items-center justify-center h-full text-muted-foreground">
+ <div className="text-center">
+ {isUploading ? (
+ <>
+ <Loader2 className="h-12 w-12 mx-auto mb-4 animate-spin" />
+ <p>Processing your document...</p>
+ <p className="text-sm mt-2">This may take a few moments</p>
+ </>
+ ) : null}
+ </div>
+ </div>
+ ) : (
+ <>
+ {messages.map((message, index) =>
+ message.role === "user"
+ ? (messages[index]?.content.match(FILES_REGEX)?.[0] ??
+ null) === null && (
+ <div
+ key={`${
+ message.role
+ }-${index}-${message.timestamp?.getTime()}`}
+ className="space-y-6 group"
+ >
+ <UserMessage
+ animate={
+ message.source
+ ? message.source !== "langflow"
+ : false
+ }
+ content={
+ index >= 2 &&
+ (messages[index - 2]?.content.match(
+ FILES_REGEX,
+ )?.[0] ??
+ undefined) &&
+ message.content === FILE_CONFIRMATION
+ ? undefined
+ : message.content
+ }
+ files={
+ index >= 2
+ ? (messages[index - 2]?.content.match(
+ FILES_REGEX,
+ )?.[0] ?? undefined)
+ : undefined
+ }
+ />
+ </div>
+ )
+ : message.role === "assistant" &&
+ (index < 1 ||
+ (messages[index - 1]?.content.match(FILES_REGEX)?.[0] ??
+ null) === null) && (
+ <div
+ key={`${
+ message.role
+ }-${index}-${message.timestamp?.getTime()}`}
+ className="space-y-6 group"
+ >
+ <AssistantMessage
+ content={message.content}
+ functionCalls={message.functionCalls}
+ messageIndex={index}
+ expandedFunctionCalls={expandedFunctionCalls}
+ onToggle={toggleFunctionCall}
+ showForkButton={endpoint === "chat"}
+ onFork={(e) => handleForkConversation(index, e)}
+ animate={false}
+ isInactive={index < messages.length - 1}
+ isInitialGreeting={
+ index === 0 &&
+ messages.length === 1 &&
+ message.content === "How can I assist?"
+ }
+ usage={message.usage}
+ />
+ </div>
+ ),
+ )}
+
+ {/* Streaming Message Display */}
+ {streamingMessage && (
+ <AssistantMessage
+ content={streamingMessage.content}
+ functionCalls={streamingMessage.functionCalls}
+ messageIndex={messages.length}
+ expandedFunctionCalls={expandedFunctionCalls}
+ onToggle={toggleFunctionCall}
+ delay={0.4}
+ isStreaming
+ isCompleted={false}
+ />
+ )}
+
+ {/* Waiting too long indicator */}
+ {waitingTooLong && !streamingMessage && loading && (
+ <div className="pl-10 space-y-2">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ <span>The server is taking longer than expected...</span>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ This may be due to high server load. The request will
+ timeout after 60 seconds.
+ </p>
+ </div>
+ )}
+ </>
+ )}
+ {!streamingMessage && (
+ <div className="pl-10">
+ <Nudges
+ nudges={loading ? [] : (nudges as string[])}
+ handleSuggestionClick={handleSuggestionClick}
+ />
+ </div>
+ )}
+ </div>
+ </StickToBottom.Content>
+ <div className="p-6 pt-0 max-w-[960px] mx-auto w-full">
+ {/* Input Area - Fixed at bottom */}
+ <ChatInput
+ ref={chatInputRef}
+ input={input}
+ loading={loading}
+ isUploading={isUploading}
+ selectedFilter={selectedFilter}
+ parsedFilterData={parsedFilterData}
+ uploadedFile={uploadedFile}
+ onSubmit={handleSubmit}
+ onChange={setInput}
+ onKeyDown={(e) => {
+ // Handle backspace for filter clearing
+ if (
+ e.key === "Backspace" &&
+ selectedFilter &&
+ input.trim() === ""
+ ) {
+ e.preventDefault();
+ if (isFilterHighlighted) {
+ // Second backspace - remove the filter
+ setConversationFilter(null);
+ setIsFilterHighlighted(false);
+ } else {
+ // First backspace - highlight the filter
+ setIsFilterHighlighted(true);
+ }
+ return;
+ }
+
+ // Handle Enter key for form submission
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ if (input.trim() && !loading) {
+ // Trigger form submission by finding the form and calling submit
+ const form = e.currentTarget.closest("form");
+ if (form) {
+ form.requestSubmit();
+ }
+ }
+ }
+ }}
+ onFilterSelect={handleFilterSelect}
+ onFilePickerClick={handleFilePickerClick}
+ onFileSelected={setUploadedFile}
+ setSelectedFilter={setConversationFilter}
+ setIsFilterHighlighted={setIsFilterHighlighted}
+ />
+ </div>
+ </>
+ );
}
export default function ProtectedChatPage() {
- return (
- <ProtectedRoute>
- <div className="flex w-full h-full overflow-hidden">
- <StickToBottom
- className="flex h-full flex-1 flex-col"
- resize="smooth"
- initial="instant"
- mass={1}
- >
- <ChatPage />
- </StickToBottom>
- </div>
- </ProtectedRoute>
- );
+ return (
+ <ProtectedRoute>
+ <div className="flex w-full h-full overflow-hidden">
+ <StickToBottom
+ className="flex h-full flex-1 flex-col"
+ resize="smooth"
+ initial="instant"
+ mass={1}
+ >
+ <ChatPage />
+ </StickToBottom>
+ </div>
+ </ProtectedRoute>
+ );
}
diff --git a/frontend/app/connectors/page.tsx b/frontend/app/connectors/page.tsx
index 0adb857bc..bc114962b 100644
--- a/frontend/app/connectors/page.tsx
+++ b/frontend/app/connectors/page.tsx
@@ -1,7 +1,7 @@
"use client";
import React, { useState } from "react";
-import { UnifiedCloudPicker, CloudFile } from "@/components/cloud-picker";
+import { CloudFile, UnifiedCloudPicker } from "@/components/cloud-picker";
import { useTask } from "@/contexts/task-context";
// CloudFile interface is now imported from the unified cloud picker
diff --git a/frontend/app/error.tsx b/frontend/app/error.tsx
index 976b6aaca..006a33a06 100644
--- a/frontend/app/error.tsx
+++ b/frontend/app/error.tsx
@@ -1,7 +1,7 @@
"use client";
-import { isChunkLoadError } from "@/lib/utils";
import { useEffect } from "react";
+import { isChunkLoadError } from "@/lib/utils";
export default function Error({
error,
@@ -20,10 +20,10 @@ export default function Error({
<div className="flex flex-col items-center gap-4 text-center max-w-md px-4">
<h2 className="text-xl font-semibold">Application loading error</h2>
<p className="text-muted-foreground">
- Some application resources failed to load.
- This can occur due to a bad / slow Internet connection,
- the application server not being fully initialized,
- or the browser cache containing old code chunk references.
+ Some application resources failed to load. This can occur due to a
+ bad / slow Internet connection, the application server not being
+ fully initialized, or the browser cache containing old code chunk
+ references.
</p>
{error.digest && (
<p className="text-xs text-muted-foreground/60">
@@ -46,7 +46,8 @@ export default function Error({
<div className="flex flex-col items-center gap-4 text-center max-w-md px-4">
<h2 className="text-xl font-semibold">Component rendering error</h2>
<p className="text-muted-foreground">
- An unexpected component error occurred. See JavaScript Console for further details.
+ An unexpected component error occurred. See JavaScript Console for
+ further details.
</p>
{error.digest && (
<p className="text-xs text-muted-foreground/60">
diff --git a/frontend/app/global-error.tsx b/frontend/app/global-error.tsx
index a741e054f..9ec3a7d57 100644
--- a/frontend/app/global-error.tsx
+++ b/frontend/app/global-error.tsx
@@ -37,15 +37,17 @@ export default function GlobalError({
}}
>
<h2 style={{ fontSize: "1.25rem", fontWeight: 600, margin: 0 }}>
- {isChunkError ? "Application loading error" : "Component rendering error"}
+ {isChunkError
+ ? "Application loading error"
+ : "Component rendering error"}
</h2>
<p style={{ color: "#888", margin: 0 }}>
{isChunkError ? (
<>
- Some application resources failed to load.
- This can occur due to a bad / slow Internet connection,
- the application server not being fully initialized,
- or the browser cache containing old code chunk references.
+ Some application resources failed to load. This can occur due
+ to a bad / slow Internet connection, the application server
+ not being fully initialized, or the browser cache containing
+ old code chunk references.
</>
) : (
"An unexpected component error occurred. See JavaScript Console for further details."
diff --git a/frontend/app/globals.css b/frontend/app/globals.css
index 1e5b8dae6..0c1a4a330 100644
--- a/frontend/app/globals.css
+++ b/frontend/app/globals.css
@@ -158,8 +158,7 @@
"banner banner banner"
"header header header"
"nav main right-panel";
- transition:
- grid-template-columns 0.25s ease-in-out;
+ transition: grid-template-columns 0.25s ease-in-out;
}
.header-start-display {
diff --git a/frontend/app/knowledge/chunks/page.tsx b/frontend/app/knowledge/chunks/page.tsx
index a29472434..ceafe40c0 100644
--- a/frontend/app/knowledge/chunks/page.tsx
+++ b/frontend/app/knowledge/chunks/page.tsx
@@ -5,18 +5,22 @@ import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useCallback, useEffect, useMemo, useState } from "react";
// import { Label } from "@/components/ui/label";
// import { Checkbox } from "@/components/ui/checkbox";
+import { KnowledgeSearchInput } from "@/components/knowledge-search-input";
+// import { Label } from "@/components/ui/label";
+// import { Checkbox } from "@/components/ui/checkbox";
import { ProtectedRoute } from "@/components/protected-route";
import { Button } from "@/components/ui/button";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
import {
type ChunkResult,
type File,
useGetSearchQuery,
} from "../../api/queries/useGetSearchQuery";
-// import { Label } from "@/components/ui/label";
-// import { Checkbox } from "@/components/ui/checkbox";
-import { KnowledgeSearchInput } from "@/components/knowledge-search-input";
-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
const getFileTypeLabel = (mimetype: string) => {
if (mimetype === "application/pdf") return "PDF";
@@ -43,7 +47,7 @@ function ChunksPageContent() {
const averageChunkLength = useMemo(
() =>
chunks.reduce((acc, chunk) => acc + chunk.text.length, 0) /
- chunks.length || 0,
+ chunks.length || 0,
[chunks],
);
@@ -319,8 +323,10 @@ function ChunksPageContent() {
</div>
{(() => {
const hasOwner = Boolean(fileData?.owner);
- const hasAllowedUsers = (fileData?.allowed_users?.length ?? 0) > 0;
- const hasAllowedGroups = (fileData?.allowed_groups?.length ?? 0) > 0;
+ const hasAllowedUsers =
+ (fileData?.allowed_users?.length ?? 0) > 0;
+ const hasAllowedGroups =
+ (fileData?.allowed_groups?.length ?? 0) > 0;
const showAccessControl =
hasOwner || hasAllowedUsers || hasAllowedGroups;
return showAccessControl;
@@ -332,9 +338,7 @@ function ChunksPageContent() {
<dl>
{fileData?.owner && (
<div className="sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0 mb-2.5">
- <dt className="text-sm/6 text-muted-foreground">
- Owner
- </dt>
+ <dt className="text-sm/6 text-muted-foreground">Owner</dt>
<dd className="mt-1 text-sm/6 text-gray-800 dark:text-gray-100 sm:col-span-2 sm:mt-0">
<div className="flex items-center gap-2">
<span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900">
@@ -343,7 +347,9 @@ function ChunksPageContent() {
</span>
</span>
<span className="text-sm break-all">
- {fileData.owner_name || fileData.owner_email || fileData.owner}
+ {fileData.owner_name ||
+ fileData.owner_email ||
+ fileData.owner}
</span>
</div>
</dd>
@@ -369,11 +375,11 @@ function ChunksPageContent() {
</span>
<Tooltip>
<TooltipTrigger asChild>
- <span className="text-sm break-all truncate">{user}</span>
+ <span className="text-sm break-all truncate">
+ {user}
+ </span>
</TooltipTrigger>
- <TooltipContent>
- {user}
- </TooltipContent>
+ <TooltipContent>{user}</TooltipContent>
</Tooltip>
</div>
))}
@@ -400,7 +406,9 @@ function ChunksPageContent() {
{group?.charAt(0).toUpperCase()}
</span>
</span>
- <span className="text-sm break-all">{group}</span>
+ <span className="text-sm break-all">
+ {group}
+ </span>
</div>
))}
</div>
diff --git a/frontend/app/knowledge/page.tsx b/frontend/app/knowledge/page.tsx
index abca9792a..1815ee774 100644
--- a/frontend/app/knowledge/page.tsx
+++ b/frontend/app/knowledge/page.tsx
@@ -29,7 +29,7 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
-import { StatusBadge, type Status } from "@/components/ui/status-badge";
+import { type Status, StatusBadge } from "@/components/ui/status-badge";
import {
Tooltip,
TooltipContent,
@@ -82,7 +82,8 @@ function SearchPage() {
const [selectedRows, setSelectedRows] = useState<File[]>([]);
const [showBulkDeleteDialog, setShowBulkDeleteDialog] = useState(false);
const lastErrorRef = useRef<string | null>(null);
- const [ingestionStatus, setIngestionStatus] = useState<IngestionStatus | null>(null);
+ const [ingestionStatus, setIngestionStatus] =
+ useState<IngestionStatus | null>(null);
const deleteDocumentMutation = useDeleteDocument();
const syncAllConnectorsMutation = useSyncAllConnectors();
@@ -91,15 +92,18 @@ function SearchPage() {
refreshTasks();
}, [refreshTasks]);
- const { data: searchData = [], isFetching, error, isError } = useGetSearchQuery(
- queryOverride,
- parsedFilterData,
- );
+ const {
+ data: searchData = [],
+ isFetching,
+ error,
+ isError,
+ } = useGetSearchQuery(queryOverride, parsedFilterData);
// Show toast notification for search errors
useEffect(() => {
if (isError && error) {
- const errorMessage = error instanceof Error ? error.message : "Search failed";
+ const errorMessage =
+ error instanceof Error ? error.message : "Search failed";
// Avoid showing duplicate toasts for the same error
if (lastErrorRef.current !== errorMessage) {
lastErrorRef.current = errorMessage;
@@ -273,12 +277,11 @@ function SearchPage() {
type="button"
className="inline-flex items-center gap-1 text-red-500 transition hover:text-red-400"
aria-label="View ingestion error"
- onClick={() => {setIngestionStatus({ status, error, data })}}
+ onClick={() => {
+ setIngestionStatus({ status, error, data });
+ }}
>
- <StatusBadge
- status={status}
- className="pointer-events-none"
- />
+ <StatusBadge status={status} className="pointer-events-none" />
</button>
);
}
@@ -389,17 +392,25 @@ function SearchPage() {
toast.info("Syncing all cloud connectors...");
const result = await syncAllConnectorsMutation.mutateAsync();
if (result.status === "no_files") {
- toast.info(result.message || "No cloud files to sync. Add files from cloud connectors first.");
- } else if (result.synced_connectors && result.synced_connectors.length > 0) {
+ toast.info(
+ result.message ||
+ "No cloud files to sync. Add files from cloud connectors first.",
+ );
+ } else if (
+ result.synced_connectors &&
+ result.synced_connectors.length > 0
+ ) {
toast.success(
- `Sync started for ${result.synced_connectors.join(", ")}. Check task notifications for progress.`
+ `Sync started for ${result.synced_connectors.join(", ")}. Check task notifications for progress.`,
);
} else if (result.errors && result.errors.length > 0) {
toast.error("Some connectors failed to sync");
}
} catch (error) {
toast.error(
- error instanceof Error ? error.message : "Failed to sync connectors"
+ error instanceof Error
+ ? error.message
+ : "Failed to sync connectors",
);
}
}}
@@ -462,21 +473,23 @@ function SearchPage() {
{/* Status dialog */}
{ingestionStatus && (
- <Dialog
- open={!!ingestionStatus}
- onOpenChange={(open) => !open && setIngestionStatus(null)}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Ingestion failed</DialogTitle>
- <DialogDescription className="text-sm text-muted-foreground">
- {ingestionStatus.data?.filename || "Unknown file"}
- </DialogDescription>
- </DialogHeader>
- <div className="rounded-md border border-destructive/20 bg-destructive/10 p-4 text-sm text-destructive">
- {ingestionStatus.error}
- </div>
- </DialogContent>
- </Dialog>)}
+ <Dialog
+ open={!!ingestionStatus}
+ onOpenChange={(open) => !open && setIngestionStatus(null)}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Ingestion failed</DialogTitle>
+ <DialogDescription className="text-sm text-muted-foreground">
+ {ingestionStatus.data?.filename || "Unknown file"}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="rounded-md border border-destructive/20 bg-destructive/10 p-4 text-sm text-destructive">
+ {ingestionStatus.error}
+ </div>
+ </DialogContent>
+ </Dialog>
+ )}
{/* Bulk Delete Confirmation Dialog */}
<DeleteConfirmationDialog
@@ -488,7 +501,10 @@ function SearchPage() {
onConfirm={handleBulkDelete}
isLoading={deleteDocumentMutation.isPending}
>
- <p className="my-2">This will remove all chunks and data associated with these documents. This action cannot be undone.</p>
+ <p className="my-2">
+ This will remove all chunks and data associated with these documents.
+ This action cannot be undone.
+ </p>
<p className="my-2">Documents to be deleted:</p>
{formatFilesToDelete(selectedRows)}
</DeleteConfirmationDialog>
diff --git a/frontend/app/onboarding/_components/ibm-onboarding.tsx b/frontend/app/onboarding/_components/ibm-onboarding.tsx
index ebf455b83..2c81f9c9a 100644
--- a/frontend/app/onboarding/_components/ibm-onboarding.tsx
+++ b/frontend/app/onboarding/_components/ibm-onboarding.tsx
@@ -5,9 +5,9 @@ import { LabelInput } from "@/components/label-input";
import { LabelWrapper } from "@/components/label-wrapper";
import { Switch } from "@/components/ui/switch";
import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
} from "@/components/ui/tooltip";
import { useDebouncedValue } from "@/lib/debounce";
import type { OnboardingVariables } from "../../api/mutations/useOnboardingMutation";
@@ -18,263 +18,263 @@ import { AdvancedOnboarding } from "./advanced";
import { ModelSelector } from "./model-selector";
export function IBMOnboarding({
- isEmbedding = false,
- setSettings,
- setIsLoadingModels,
- alreadyConfigured = false,
- existingEndpoint,
- existingProjectId,
- hasEnvApiKey = false,
+ isEmbedding = false,
+ setSettings,
+ setIsLoadingModels,
+ alreadyConfigured = false,
+ existingEndpoint,
+ existingProjectId,
+ hasEnvApiKey = false,
}: {
- isEmbedding?: boolean;
- setSettings: Dispatch<SetStateAction<OnboardingVariables>>;
- setIsLoadingModels?: (isLoading: boolean) => void;
- alreadyConfigured?: boolean;
- existingEndpoint?: string;
- existingProjectId?: string;
- hasEnvApiKey?: boolean;
+ isEmbedding?: boolean;
+ setSettings: Dispatch<SetStateAction<OnboardingVariables>>;
+ setIsLoadingModels?: (isLoading: boolean) => void;
+ alreadyConfigured?: boolean;
+ existingEndpoint?: string;
+ existingProjectId?: string;
+ hasEnvApiKey?: boolean;
}) {
- const [endpoint, setEndpoint] = useState(
- alreadyConfigured
- ? ""
- : existingEndpoint || "https://us-south.ml.cloud.ibm.com",
- );
- const [apiKey, setApiKey] = useState("");
- const [getFromEnv, setGetFromEnv] = useState(
- hasEnvApiKey && !alreadyConfigured,
- );
- const [projectId, setProjectId] = useState(
- alreadyConfigured ? "" : existingProjectId || "",
- );
+ const [endpoint, setEndpoint] = useState(
+ alreadyConfigured
+ ? ""
+ : existingEndpoint || "https://us-south.ml.cloud.ibm.com",
+ );
+ const [apiKey, setApiKey] = useState("");
+ const [getFromEnv, setGetFromEnv] = useState(
+ hasEnvApiKey && !alreadyConfigured,
+ );
+ const [projectId, setProjectId] = useState(
+ alreadyConfigured ? "" : existingProjectId || "",
+ );
- const options = [
- {
- value: "https://us-south.ml.cloud.ibm.com",
- label: "https://us-south.ml.cloud.ibm.com",
- default: true,
- },
- {
- value: "https://eu-de.ml.cloud.ibm.com",
- label: "https://eu-de.ml.cloud.ibm.com",
- default: false,
- },
- {
- value: "https://eu-gb.ml.cloud.ibm.com",
- label: "https://eu-gb.ml.cloud.ibm.com",
- default: false,
- },
- {
- value: "https://au-syd.ml.cloud.ibm.com",
- label: "https://au-syd.ml.cloud.ibm.com",
- default: false,
- },
- {
- value: "https://jp-tok.ml.cloud.ibm.com",
- label: "https://jp-tok.ml.cloud.ibm.com",
- default: false,
- },
- {
- value: "https://ca-tor.ml.cloud.ibm.com",
- label: "https://ca-tor.ml.cloud.ibm.com",
- default: false,
- },
- ];
- const debouncedEndpoint = useDebouncedValue(endpoint, 500);
- const debouncedApiKey = useDebouncedValue(apiKey, 500);
- const debouncedProjectId = useDebouncedValue(projectId, 500);
+ const options = [
+ {
+ value: "https://us-south.ml.cloud.ibm.com",
+ label: "https://us-south.ml.cloud.ibm.com",
+ default: true,
+ },
+ {
+ value: "https://eu-de.ml.cloud.ibm.com",
+ label: "https://eu-de.ml.cloud.ibm.com",
+ default: false,
+ },
+ {
+ value: "https://eu-gb.ml.cloud.ibm.com",
+ label: "https://eu-gb.ml.cloud.ibm.com",
+ default: false,
+ },
+ {
+ value: "https://au-syd.ml.cloud.ibm.com",
+ label: "https://au-syd.ml.cloud.ibm.com",
+ default: false,
+ },
+ {
+ value: "https://jp-tok.ml.cloud.ibm.com",
+ label: "https://jp-tok.ml.cloud.ibm.com",
+ default: false,
+ },
+ {
+ value: "https://ca-tor.ml.cloud.ibm.com",
+ label: "https://ca-tor.ml.cloud.ibm.com",
+ default: false,
+ },
+ ];
+ const debouncedEndpoint = useDebouncedValue(endpoint, 500);
+ const debouncedApiKey = useDebouncedValue(apiKey, 500);
+ const debouncedProjectId = useDebouncedValue(projectId, 500);
- // Fetch models from API when all credentials are provided
- const {
- data: modelsData,
- isLoading: isLoadingModels,
- error: modelsError,
- } = useGetIBMModelsQuery(
- {
- endpoint: debouncedEndpoint ? debouncedEndpoint : undefined,
- apiKey: getFromEnv ? "" : debouncedApiKey ? debouncedApiKey : undefined,
- projectId: debouncedProjectId ? debouncedProjectId : undefined,
- },
- {
- enabled:
- (!!debouncedEndpoint && !!debouncedApiKey && !!debouncedProjectId) ||
- getFromEnv ||
- alreadyConfigured,
- },
- );
+ // Fetch models from API when all credentials are provided
+ const {
+ data: modelsData,
+ isLoading: isLoadingModels,
+ error: modelsError,
+ } = useGetIBMModelsQuery(
+ {
+ endpoint: debouncedEndpoint ? debouncedEndpoint : undefined,
+ apiKey: getFromEnv ? "" : debouncedApiKey ? debouncedApiKey : undefined,
+ projectId: debouncedProjectId ? debouncedProjectId : undefined,
+ },
+ {
+ enabled:
+ (!!debouncedEndpoint && !!debouncedApiKey && !!debouncedProjectId) ||
+ getFromEnv ||
+ alreadyConfigured,
+ },
+ );
- // Use custom hook for model selection logic
- const {
- languageModel,
- embeddingModel,
- setLanguageModel,
- setEmbeddingModel,
- languageModels,
- embeddingModels,
- } = useModelSelection(modelsData, isEmbedding);
+ // Use custom hook for model selection logic
+ const {
+ languageModel,
+ embeddingModel,
+ setLanguageModel,
+ setEmbeddingModel,
+ languageModels,
+ embeddingModels,
+ } = useModelSelection(modelsData, isEmbedding);
- const handleGetFromEnvChange = (fromEnv: boolean) => {
- setGetFromEnv(fromEnv);
- if (fromEnv) {
- setApiKey("");
- }
- setEmbeddingModel?.("");
- setLanguageModel?.("");
- };
+ const handleGetFromEnvChange = (fromEnv: boolean) => {
+ setGetFromEnv(fromEnv);
+ if (fromEnv) {
+ setApiKey("");
+ }
+ setEmbeddingModel?.("");
+ setLanguageModel?.("");
+ };
- useEffect(() => {
- setIsLoadingModels?.(isLoadingModels);
- }, [isLoadingModels, setIsLoadingModels]);
+ useEffect(() => {
+ setIsLoadingModels?.(isLoadingModels);
+ }, [isLoadingModels, setIsLoadingModels]);
- // Update settings when values change
- useUpdateSettings(
- "watsonx",
- {
- endpoint,
- apiKey,
- projectId,
- languageModel,
- embeddingModel,
- },
- setSettings,
- isEmbedding,
- );
+ // Update settings when values change
+ useUpdateSettings(
+ "watsonx",
+ {
+ endpoint,
+ apiKey,
+ projectId,
+ languageModel,
+ embeddingModel,
+ },
+ setSettings,
+ isEmbedding,
+ );
- return (
- <>
- <div className="space-y-4">
- <LabelWrapper
- label="watsonx.ai API Endpoint"
- helperText="Base URL of the API"
- id="api-endpoint"
- required
- >
- <div className="space-y-1">
- <ModelSelector
- options={alreadyConfigured ? [] : options}
- value={endpoint}
- custom
- onValueChange={alreadyConfigured ? () => { } : setEndpoint}
- searchPlaceholder="Search endpoint..."
- noOptionsPlaceholder={
- alreadyConfigured
- ? "https://•••••••••••••••••••••••••••••••••••••••••"
- : "No endpoints available"
- }
- placeholder="Select endpoint..."
- />
- {alreadyConfigured && (
- <p className="text-mmd text-muted-foreground">
- Reusing endpoint from model provider selection.
- </p>
- )}
- </div>
- </LabelWrapper>
+ return (
+ <>
+ <div className="space-y-4">
+ <LabelWrapper
+ label="watsonx.ai API Endpoint"
+ helperText="Base URL of the API"
+ id="api-endpoint"
+ required
+ >
+ <div className="space-y-1">
+ <ModelSelector
+ options={alreadyConfigured ? [] : options}
+ value={endpoint}
+ custom
+ onValueChange={alreadyConfigured ? () => {} : setEndpoint}
+ searchPlaceholder="Search endpoint..."
+ noOptionsPlaceholder={
+ alreadyConfigured
+ ? "https://•••••••••••••••••••••••••••••••••••••••••"
+ : "No endpoints available"
+ }
+ placeholder="Select endpoint..."
+ />
+ {alreadyConfigured && (
+ <p className="text-mmd text-muted-foreground">
+ Reusing endpoint from model provider selection.
+ </p>
+ )}
+ </div>
+ </LabelWrapper>
- <div className="space-y-1">
- <LabelInput
- label="watsonx Project ID"
- helperText="Project ID for the model"
- id="project-id"
- required
- placeholder={
- alreadyConfigured ? "••••••••••••••••••••••••" : "your-project-id"
- }
- value={projectId}
- onChange={(e) => setProjectId(e.target.value)}
- disabled={alreadyConfigured}
- />
- {alreadyConfigured && (
- <p className="text-mmd text-muted-foreground">
- Reusing project ID from model provider selection.
- </p>
- )}
- </div>
- <LabelWrapper
- label="Use environment watsonx API key"
- id="get-api-key"
- description="Reuse the key from your environment config. Turn off to enter a different key."
- flex
- >
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Switch
- checked={getFromEnv}
- onCheckedChange={handleGetFromEnvChange}
- disabled={!hasEnvApiKey || alreadyConfigured}
- />
- </div>
- </TooltipTrigger>
- {!hasEnvApiKey && !alreadyConfigured && (
- <TooltipContent>
- watsonx API key not detected in the environment.
- </TooltipContent>
- )}
- </Tooltip>
- </LabelWrapper>
- {!getFromEnv && !alreadyConfigured && (
- <div className="space-y-1">
- <LabelInput
- label="watsonx API key"
- helperText="API key to access watsonx.ai"
- className={modelsError ? "!border-destructive" : ""}
- id="api-key"
- type="password"
- required
- placeholder="your-api-key"
- value={apiKey}
- onChange={(e) => setApiKey(e.target.value)}
- />
- {isLoadingModels && (
- <p className="text-mmd text-muted-foreground">
- Validating API key...
- </p>
- )}
- {modelsError && (
- <p className="text-mmd text-destructive">
- Invalid watsonx API key. Verify or replace the key.
- </p>
- )}
- </div>
- )}
- {alreadyConfigured && (
- <div className="space-y-1">
- <LabelInput
- label="watsonx API key"
- helperText="API key to access watsonx.ai"
- id="api-key"
- type="password"
- required
- placeholder="•••••••••••••••••••••••••••••••••••••••••"
- value={apiKey}
- onChange={(e) => setApiKey(e.target.value)}
- disabled={true}
- />
- <p className="text-mmd text-muted-foreground">
- Reusing API key from model provider selection.
- </p>
- </div>
- )}
- {getFromEnv && isLoadingModels && (
- <p className="text-mmd text-muted-foreground">
- Validating configuration...
- </p>
- )}
- {getFromEnv && modelsError && (
- <p className="text-mmd text-accent-amber-foreground">
- Connection failed. Check your configuration.
- </p>
- )}
- </div>
- <AdvancedOnboarding
- icon={<IBMLogo className="w-4 h-4" />}
- languageModels={languageModels}
- embeddingModels={embeddingModels}
- languageModel={languageModel}
- embeddingModel={embeddingModel}
- setLanguageModel={setLanguageModel}
- setEmbeddingModel={setEmbeddingModel}
- />
- </>
- );
+ <div className="space-y-1">
+ <LabelInput
+ label="watsonx Project ID"
+ helperText="Project ID for the model"
+ id="project-id"
+ required
+ placeholder={
+ alreadyConfigured ? "••••••••••••••••••••••••" : "your-project-id"
+ }
+ value={projectId}
+ onChange={(e) => setProjectId(e.target.value)}
+ disabled={alreadyConfigured}
+ />
+ {alreadyConfigured && (
+ <p className="text-mmd text-muted-foreground">
+ Reusing project ID from model provider selection.
+ </p>
+ )}
+ </div>
+ <LabelWrapper
+ label="Use environment watsonx API key"
+ id="get-api-key"
+ description="Reuse the key from your environment config. Turn off to enter a different key."
+ flex
+ >
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Switch
+ checked={getFromEnv}
+ onCheckedChange={handleGetFromEnvChange}
+ disabled={!hasEnvApiKey || alreadyConfigured}
+ />
+ </div>
+ </TooltipTrigger>
+ {!hasEnvApiKey && !alreadyConfigured && (
+ <TooltipContent>
+ watsonx API key not detected in the environment.
+ </TooltipContent>
+ )}
+ </Tooltip>
+ </LabelWrapper>
+ {!getFromEnv && !alreadyConfigured && (
+ <div className="space-y-1">
+ <LabelInput
+ label="watsonx API key"
+ helperText="API key to access watsonx.ai"
+ className={modelsError ? "!border-destructive" : ""}
+ id="api-key"
+ type="password"
+ required
+ placeholder="your-api-key"
+ value={apiKey}
+ onChange={(e) => setApiKey(e.target.value)}
+ />
+ {isLoadingModels && (
+ <p className="text-mmd text-muted-foreground">
+ Validating API key...
+ </p>
+ )}
+ {modelsError && (
+ <p className="text-mmd text-destructive">
+ Invalid watsonx API key. Verify or replace the key.
+ </p>
+ )}
+ </div>
+ )}
+ {alreadyConfigured && (
+ <div className="space-y-1">
+ <LabelInput
+ label="watsonx API key"
+ helperText="API key to access watsonx.ai"
+ id="api-key"
+ type="password"
+ required
+ placeholder="•••••••••••••••••••••••••••••••••••••••••"
+ value={apiKey}
+ onChange={(e) => setApiKey(e.target.value)}
+ disabled={true}
+ />
+ <p className="text-mmd text-muted-foreground">
+ Reusing API key from model provider selection.
+ </p>
+ </div>
+ )}
+ {getFromEnv && isLoadingModels && (
+ <p className="text-mmd text-muted-foreground">
+ Validating configuration...
+ </p>
+ )}
+ {getFromEnv && modelsError && (
+ <p className="text-mmd text-accent-amber-foreground">
+ Connection failed. Check your configuration.
+ </p>
+ )}
+ </div>
+ <AdvancedOnboarding
+ icon={<IBMLogo className="w-4 h-4" />}
+ languageModels={languageModels}
+ embeddingModels={embeddingModels}
+ languageModel={languageModel}
+ embeddingModel={embeddingModel}
+ setLanguageModel={setLanguageModel}
+ setEmbeddingModel={setEmbeddingModel}
+ />
+ </>
+ );
}
diff --git a/frontend/app/onboarding/_components/onboarding-card.tsx b/frontend/app/onboarding/_components/onboarding-card.tsx
index 0371a6f6d..964795ee4 100644
--- a/frontend/app/onboarding/_components/onboarding-card.tsx
+++ b/frontend/app/onboarding/_components/onboarding-card.tsx
@@ -89,7 +89,10 @@ const OnboardingCard = ({
) {
setModelProvider("anthropic");
return;
- } else if (provider === "openai" && currentSettings.providers.openai?.has_api_key) {
+ } else if (
+ provider === "openai" &&
+ currentSettings.providers.openai?.has_api_key
+ ) {
setModelProvider("openai");
return;
} else if (
@@ -188,7 +191,9 @@ const OnboardingCard = ({
onError: (error) => {
console.error("Failed to rollback onboarding", error);
// Preserve existing error message if set, otherwise show rollback error
- setError((prevError) => prevError || `Failed to rollback: ${error.message}`);
+ setError(
+ (prevError) => prevError || `Failed to rollback: ${error.message}`,
+ );
// Still reset to provider selection even if rollback fails
setCurrentStep(null);
},
@@ -245,10 +250,7 @@ const OnboardingCard = ({
!isCompleted &&
!handledFailedTasksRef.current.has(taskWithFailure.task_id)
) {
- console.error(
- "Task failed, jumping back one step",
- taskWithFailure,
- );
+ console.error("Task failed, jumping back one step", taskWithFailure);
// Mark this task as handled to prevent infinite loops
handledFailedTasksRef.current.add(taskWithFailure.task_id);
@@ -291,7 +293,6 @@ const OnboardingCard = ({
(tasks.length === 0 && currentStep === totalSteps - 1)) && // Complete because no files were ingested
!isCompleted &&
!taskWithFailure
-
) {
// Set to final step to show "Done"
setCurrentStep(totalSteps);
@@ -300,7 +301,15 @@ const OnboardingCard = ({
onComplete();
}, 1000);
}
- }, [tasks, currentStep, onComplete, isCompleted, isEmbedding, totalSteps, rollbackMutation]);
+ }, [
+ tasks,
+ currentStep,
+ onComplete,
+ isCompleted,
+ isEmbedding,
+ totalSteps,
+ rollbackMutation,
+ ]);
// Mutations
const onboardingMutation = useOnboardingMutation({
@@ -354,8 +363,7 @@ const OnboardingCard = ({
setError(null);
// Prepare onboarding data with provider-specific fields
- const onboardingData: OnboardingVariables = {
- };
+ const onboardingData: OnboardingVariables = {};
// Set the provider field
if (isEmbedding) {
@@ -444,8 +452,8 @@ const OnboardingCard = ({
value="anthropic"
className={cn(
error &&
- modelProvider === "anthropic" &&
- "data-[state=active]:border-destructive",
+ modelProvider === "anthropic" &&
+ "data-[state=active]:border-destructive",
)}
>
<TabTrigger
@@ -477,8 +485,8 @@ const OnboardingCard = ({
value="openai"
className={cn(
error &&
- modelProvider === "openai" &&
- "data-[state=active]:border-destructive",
+ modelProvider === "openai" &&
+ "data-[state=active]:border-destructive",
)}
>
<TabTrigger
@@ -507,8 +515,8 @@ const OnboardingCard = ({
value="watsonx"
className={cn(
error &&
- modelProvider === "watsonx" &&
- "data-[state=active]:border-destructive",
+ modelProvider === "watsonx" &&
+ "data-[state=active]:border-destructive",
)}
>
<TabTrigger
@@ -539,8 +547,8 @@ const OnboardingCard = ({
value="ollama"
className={cn(
error &&
- modelProvider === "ollama" &&
- "data-[state=active]:border-destructive",
+ modelProvider === "ollama" &&
+ "data-[state=active]:border-destructive",
)}
>
<TabTrigger
@@ -587,7 +595,9 @@ const OnboardingCard = ({
hasEnvApiKey={
currentSettings?.providers?.openai?.has_api_key === true
}
- alreadyConfigured={providerAlreadyConfigured && modelProvider === "openai"}
+ alreadyConfigured={
+ providerAlreadyConfigured && modelProvider === "openai"
+ }
/>
</TabsContent>
<TabsContent value="watsonx">
@@ -595,10 +605,18 @@ const OnboardingCard = ({
setSettings={setSettings}
setIsLoadingModels={setIsLoadingModels}
isEmbedding={isEmbedding}
- alreadyConfigured={providerAlreadyConfigured && modelProvider === "watsonx"}
- existingEndpoint={currentSettings?.providers?.watsonx?.endpoint}
- existingProjectId={currentSettings?.providers?.watsonx?.project_id}
- hasEnvApiKey={currentSettings?.providers?.watsonx?.has_api_key === true}
+ alreadyConfigured={
+ providerAlreadyConfigured && modelProvider === "watsonx"
+ }
+ existingEndpoint={
+ currentSettings?.providers?.watsonx?.endpoint
+ }
+ existingProjectId={
+ currentSettings?.providers?.watsonx?.project_id
+ }
+ hasEnvApiKey={
+ currentSettings?.providers?.watsonx?.has_api_key === true
+ }
/>
</TabsContent>
<TabsContent value="ollama">
@@ -606,8 +624,12 @@ const OnboardingCard = ({
setSettings={setSettings}
setIsLoadingModels={setIsLoadingModels}
isEmbedding={isEmbedding}
- alreadyConfigured={providerAlreadyConfigured && modelProvider === "ollama"}
- existingEndpoint={currentSettings?.providers?.ollama?.endpoint}
+ alreadyConfigured={
+ providerAlreadyConfigured && modelProvider === "ollama"
+ }
+ existingEndpoint={
+ currentSettings?.providers?.ollama?.endpoint
+ }
/>
</TabsContent>
</Tabs>
@@ -630,8 +652,8 @@ const OnboardingCard = ({
{isLoadingModels
? "Loading models..."
: !!settings.llm_model &&
- !!settings.embedding_model &&
- !isDoclingHealthy
+ !!settings.embedding_model &&
+ !isDoclingHealthy
? "docling-serve must be running to continue"
: "Please fill in all required fields"}
</TooltipContent>
diff --git a/frontend/app/onboarding/_components/onboarding-content.tsx b/frontend/app/onboarding/_components/onboarding-content.tsx
index e98dc2294..743142884 100644
--- a/frontend/app/onboarding/_components/onboarding-content.tsx
+++ b/frontend/app/onboarding/_components/onboarding-content.tsx
@@ -2,9 +2,9 @@
import { useEffect, useRef, useState } from "react";
import { StickToBottom } from "use-stick-to-bottom";
+import { useUpdateOnboardingStateMutation } from "@/app/api/mutations/useUpdateOnboardingStateMutation";
import { getFilterById } from "@/app/api/queries/useGetFilterByIdQuery";
import { useGetSettingsQuery } from "@/app/api/queries/useGetSettingsQuery";
-import { useUpdateOnboardingStateMutation } from "@/app/api/mutations/useUpdateOnboardingStateMutation";
import { AssistantMessage } from "@/app/chat/_components/assistant-message";
import Nudges from "@/app/chat/_components/nudges";
import { UserMessage } from "@/app/chat/_components/user-message";
@@ -37,12 +37,12 @@ export function OnboardingContent({
const updateOnboardingMutation = useUpdateOnboardingStateMutation();
const parseFailedRef = useRef(false);
const [responseId, setResponseId] = useState<string | null>(null);
-
+
// Initialize from backend settings
const [selectedNudge, setSelectedNudge] = useState<string>(() => {
return settings?.onboarding?.selected_nudge || "";
});
-
+
const [assistantMessage, setAssistantMessage] = useState<Message | null>(
() => {
// Get from backend settings
@@ -91,7 +91,7 @@ export function OnboardingContent({
timestamp: message.timestamp.toISOString(),
},
});
-
+
if (newResponseId) {
setResponseId(newResponseId);
@@ -99,7 +99,8 @@ export function OnboardingContent({
setCurrentConversationId(newResponseId);
// Get filter ID from backend settings
- const openragDocsFilterId = settings?.onboarding?.openrag_docs_filter_id;
+ const openragDocsFilterId =
+ settings?.onboarding?.openrag_docs_filter_id;
if (openragDocsFilterId) {
try {
// Load the filter and set it in the context with explicit responseId
@@ -108,10 +109,18 @@ export function OnboardingContent({
if (filter) {
// Pass explicit newResponseId to ensure correct localStorage association
setConversationFilter(filter, newResponseId);
- console.log("[ONBOARDING] Saved filter association:", `conversation_filter_${newResponseId}`, "=", openragDocsFilterId);
+ console.log(
+ "[ONBOARDING] Saved filter association:",
+ `conversation_filter_${newResponseId}`,
+ "=",
+ openragDocsFilterId,
+ );
}
} catch (error) {
- console.error("Failed to associate filter with conversation:", error);
+ console.error(
+ "Failed to associate filter with conversation:",
+ error,
+ );
}
}
}
@@ -132,13 +141,13 @@ export function OnboardingContent({
const handleNudgeClick = async (nudge: string) => {
setSelectedNudge(nudge);
setAssistantMessage(null);
-
+
// Save selected nudge to backend and clear assistant message
await updateOnboardingMutation.mutateAsync({
selected_nudge: nudge,
assistant_message: null,
});
-
+
setTimeout(async () => {
// Check if we have the OpenRAG docs filter ID (sample data was ingested)
const openragDocsFilterId = settings?.onboarding?.openrag_docs_filter_id;
@@ -160,7 +169,10 @@ export function OnboardingContent({
}
}
- console.log("[ONBOARDING] Sending message with filter_id:", filterToUse?.id);
+ console.log(
+ "[ONBOARDING] Sending message with filter_id:",
+ filterToUse?.id,
+ );
await sendMessage({
prompt: nudge,
previousResponseId: responseId || undefined,
@@ -188,7 +200,10 @@ export function OnboardingContent({
mass={1}
>
<StickToBottom.Content className="flex flex-col min-h-full overflow-x-hidden px-8 py-6">
- <div className="flex flex-col place-self-center w-full space-y-6" data-testid="onboarding-content">
+ <div
+ className="flex flex-col place-self-center w-full space-y-6"
+ data-testid="onboarding-content"
+ >
{/* Step 1 - LLM Provider */}
<OnboardingStep
isVisible={currentStep >= 0}
diff --git a/frontend/app/onboarding/_components/onboarding-upload.tsx b/frontend/app/onboarding/_components/onboarding-upload.tsx
index 591c161dd..8b70381fa 100644
--- a/frontend/app/onboarding/_components/onboarding-upload.tsx
+++ b/frontend/app/onboarding/_components/onboarding-upload.tsx
@@ -7,12 +7,12 @@ import { useUpdateOnboardingStateMutation } from "@/app/api/mutations/useUpdateO
import { useGetNudgesQuery } from "@/app/api/queries/useGetNudgesQuery";
import { useGetTasksQuery } from "@/app/api/queries/useGetTasksQuery";
import { AnimatedProviderSteps } from "@/app/onboarding/_components/animated-provider-steps";
+import { SUPPORTED_EXTENSIONS } from "@/components/knowledge-dropdown";
import { Button } from "@/components/ui/button";
import { uploadFile } from "@/lib/upload-utils";
-import { SUPPORTED_EXTENSIONS } from "@/components/knowledge-dropdown";
interface OnboardingUploadProps {
- onComplete: () => void;
+ onComplete: () => void;
}
const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => {
@@ -108,7 +108,7 @@ const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => {
await updateOnboardingMutation.mutateAsync({
user_doc_filter_id: result.filter.id,
});
-
+
console.log(
"Created knowledge filter for uploaded document",
result.filter.id,
@@ -184,7 +184,8 @@ const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => {
setCurrentStep(1);
}, 1500);
} catch (error) {
- const errorMessage = error instanceof Error ? error.message : "Upload failed";
+ const errorMessage =
+ error instanceof Error ? error.message : "Upload failed";
console.error("Upload failed", errorMessage);
// Dispatch event that chat context can listen to
diff --git a/frontend/app/onboarding/_hooks/useUpdateSettings.ts b/frontend/app/onboarding/_hooks/useUpdateSettings.ts
index a5a20b3fb..dc9ae9e37 100644
--- a/frontend/app/onboarding/_hooks/useUpdateSettings.ts
+++ b/frontend/app/onboarding/_hooks/useUpdateSettings.ts
@@ -1,5 +1,5 @@
-import { useEffect } from "react";
import type { Dispatch, SetStateAction } from "react";
+import { useEffect } from "react";
import type { OnboardingVariables } from "../../api/mutations/useOnboardingMutation";
interface ConfigValues {
diff --git a/frontend/app/page.tsx b/frontend/app/page.tsx
index 43bd94b0e..d84d8f93d 100644
--- a/frontend/app/page.tsx
+++ b/frontend/app/page.tsx
@@ -1,7 +1,7 @@
"use client";
-import { useEffect } from "react";
import { useRouter } from "next/navigation";
+import { useEffect } from "react";
import { ProtectedRoute } from "@/components/protected-route";
function HomePage() {
diff --git a/frontend/app/providers.tsx b/frontend/app/providers.tsx
index ddef392c3..7a765fd04 100644
--- a/frontend/app/providers.tsx
+++ b/frontend/app/providers.tsx
@@ -1,7 +1,7 @@
"use client";
import { QueryClientProvider } from "@tanstack/react-query";
-import { getQueryClient } from "@/app/api/get-query-client";
import type * as React from "react";
+import { getQueryClient } from "@/app/api/get-query-client";
export default function Providers({ children }: { children: React.ReactNode }) {
const queryClient = getQueryClient();
diff --git a/frontend/app/settings/_components/anthropic-settings-dialog.tsx b/frontend/app/settings/_components/anthropic-settings-dialog.tsx
index 0a37afe47..2cc1e2232 100644
--- a/frontend/app/settings/_components/anthropic-settings-dialog.tsx
+++ b/frontend/app/settings/_components/anthropic-settings-dialog.tsx
@@ -1,5 +1,6 @@
import { useQueryClient } from "@tanstack/react-query";
import { AnimatePresence, motion } from "motion/react";
+import { useRouter } from "next/navigation";
import { useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { toast } from "sonner";
@@ -19,7 +20,6 @@ import {
AnthropicSettingsForm,
type AnthropicSettingsFormData,
} from "./anthropic-settings-form";
-import { useRouter } from "next/navigation";
const AnthropicSettingsDialog = ({
open,
diff --git a/frontend/app/settings/_components/connector-card.tsx b/frontend/app/settings/_components/connector-card.tsx
index 00bd6f999..dad0cea59 100644
--- a/frontend/app/settings/_components/connector-card.tsx
+++ b/frontend/app/settings/_components/connector-card.tsx
@@ -1,160 +1,160 @@
"use client";
+import { Loader2, Plus, RefreshCcw, Trash2 } from "lucide-react";
+import Link from "next/link";
import { Button } from "@/components/ui/button";
import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
} from "@/components/ui/card";
import { cn } from "@/lib/utils";
-import { Loader2, Plus, RefreshCcw, Trash2 } from "lucide-react";
-import Link from "next/link";
export interface Connector {
- id: string;
- name: string;
- type: string;
- icon: React.ReactNode;
- available?: boolean;
- status?: string;
- connectionId?: string;
+ id: string;
+ name: string;
+ type: string;
+ icon: React.ReactNode;
+ available?: boolean;
+ status?: string;
+ connectionId?: string;
}
interface ConnectorCardProps {
- connector: Connector;
- isConnecting: boolean;
- isDisconnecting: boolean;
- onConnect: (connector: Connector) => void;
- onDisconnect: (connector: Connector) => void;
- onNavigateToKnowledge: (connector: Connector) => void;
+ connector: Connector;
+ isConnecting: boolean;
+ isDisconnecting: boolean;
+ onConnect: (connector: Connector) => void;
+ onDisconnect: (connector: Connector) => void;
+ onNavigateToKnowledge: (connector: Connector) => void;
}
export default function ConnectorCard({
- connector,
- isConnecting,
- isDisconnecting,
- onConnect,
- onDisconnect,
- onNavigateToKnowledge,
+ connector,
+ isConnecting,
+ isDisconnecting,
+ onConnect,
+ onDisconnect,
+ onNavigateToKnowledge,
}: ConnectorCardProps) {
- console.log(connector)
- const isConnected = connector?.name === "Google Drive" || connector?.status === "connected" && connector?.connectionId;
+ console.log(connector);
+ const isConnected =
+ connector?.name === "Google Drive" ||
+ (connector?.status === "connected" && connector?.connectionId);
- return (
- <Card className="group relative flex flex-col hover:bg-secondary-hover hover:border-muted-foreground transition-colors">
- <CardHeader className="pb-2">
- <div className="flex flex-col items-start justify-between">
- <div className="flex flex-col gap-4 mb-2 w-full">
- <div className="flex items-center justify-between mb-1">
- <div
- className={cn(
- "w-8 h-8 rounded flex items-center justify-center border",
- connector?.available
- ? "bg-white"
- : "bg-muted grayscale",
- )}
- >
- {connector.icon}
- </div>
- {isConnected ? (
- <div className="flex items-center gap-1.5 rounded-full bg-foreground px-2.5 py-1 text-xs font-medium text-muted">
- <span className="h-2 w-2 rounded-full bg-green-500" />
- Active
- </div>
- ) : null}
- </div>
- <div>
- <CardTitle className="flex flex-row items-center">
- {connector.name}
- </CardTitle>
- <CardDescription className="text-sm">
- {connector?.available
- ? `${connector.name} is configured.`
- : "Not configured."}
- </CardDescription>
- </div>
- </div>
+ return (
+ <Card className="group relative flex flex-col hover:bg-secondary-hover hover:border-muted-foreground transition-colors">
+ <CardHeader className="pb-2">
+ <div className="flex flex-col items-start justify-between">
+ <div className="flex flex-col gap-4 mb-2 w-full">
+ <div className="flex items-center justify-between mb-1">
+ <div
+ className={cn(
+ "w-8 h-8 rounded flex items-center justify-center border",
+ connector?.available ? "bg-white" : "bg-muted grayscale",
+ )}
+ >
+ {connector.icon}
+ </div>
+ {isConnected ? (
+ <div className="flex items-center gap-1.5 rounded-full bg-foreground px-2.5 py-1 text-xs font-medium text-muted">
+ <span className="h-2 w-2 rounded-full bg-green-500" />
+ Active
</div>
- </CardHeader>
- <CardContent className="flex-1 flex flex-col justify-end space-y-4">
- {connector?.available ? (
- <div className="space-y-3">
- {isConnected ? (
- <div className="flex gap-2 overflow-hidden w-full">
- <Button
- variant="default"
- onClick={() => onNavigateToKnowledge(connector)}
- disabled={isDisconnecting || isConnecting}
- className="cursor-pointer !text-sm truncate rounded-md"
- size="md"
- >
- <Plus className="h-4 w-4" />
- <span className="text-mmd truncate">Add Knowledge</span>
- </Button>
- <Button
- variant="outline"
- onClick={() => onConnect(connector)}
- disabled={isConnecting || isDisconnecting}
- className="cursor-pointer"
- size="iconMd"
- >
- {isConnecting ? (
- <RefreshCcw className="h-4 w-4 animate-spin" />
- ) : (
- <RefreshCcw className="h-4 w-4" />
- )}
- </Button>
- <Button
- variant="outline"
- onClick={() => onDisconnect(connector)}
- disabled={isDisconnecting || isConnecting}
- className="cursor-pointer text-destructive hover:text-destructive"
- size="iconMd"
- >
- {isDisconnecting ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Trash2 className="h-4 w-4" />
- )}
- </Button>
- </div>
- ) : (
- <Button
- onClick={() => onConnect(connector)}
- disabled={isConnecting}
- className="w-full cursor-pointer group-hover:bg-background group-hover:border-zinc-700 group-hover:text-primary"
- size="sm"
- >
- {isConnecting ? (
- <>
- <Loader2 className="h-4 w-4 animate-spin" />
- Connecting...
- </>
- ) : (
- <>Connect</>
- )}
- </Button>
- )}
- </div>
+ ) : null}
+ </div>
+ <div>
+ <CardTitle className="flex flex-row items-center">
+ {connector.name}
+ </CardTitle>
+ <CardDescription className="text-sm">
+ {connector?.available
+ ? `${connector.name} is configured.`
+ : "Not configured."}
+ </CardDescription>
+ </div>
+ </div>
+ </div>
+ </CardHeader>
+ <CardContent className="flex-1 flex flex-col justify-end space-y-4">
+ {connector?.available ? (
+ <div className="space-y-3">
+ {isConnected ? (
+ <div className="flex gap-2 overflow-hidden w-full">
+ <Button
+ variant="default"
+ onClick={() => onNavigateToKnowledge(connector)}
+ disabled={isDisconnecting || isConnecting}
+ className="cursor-pointer !text-sm truncate rounded-md"
+ size="md"
+ >
+ <Plus className="h-4 w-4" />
+ <span className="text-mmd truncate">Add Knowledge</span>
+ </Button>
+ <Button
+ variant="outline"
+ onClick={() => onConnect(connector)}
+ disabled={isConnecting || isDisconnecting}
+ className="cursor-pointer"
+ size="iconMd"
+ >
+ {isConnecting ? (
+ <RefreshCcw className="h-4 w-4 animate-spin" />
+ ) : (
+ <RefreshCcw className="h-4 w-4" />
+ )}
+ </Button>
+ <Button
+ variant="outline"
+ onClick={() => onDisconnect(connector)}
+ disabled={isDisconnecting || isConnecting}
+ className="cursor-pointer text-destructive hover:text-destructive"
+ size="iconMd"
+ >
+ {isDisconnecting ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Trash2 className="h-4 w-4" />
+ )}
+ </Button>
+ </div>
+ ) : (
+ <Button
+ onClick={() => onConnect(connector)}
+ disabled={isConnecting}
+ className="w-full cursor-pointer group-hover:bg-background group-hover:border-zinc-700 group-hover:text-primary"
+ size="sm"
+ >
+ {isConnecting ? (
+ <>
+ <Loader2 className="h-4 w-4 animate-spin" />
+ Connecting...
+ </>
) : (
- <div className="text-sm text-muted-foreground">
- <p>
- See our{" "}
- <Link
- className="text-accent-pink-foreground"
- href="https://docs.openr.ag/knowledge#oauth-ingestion"
- target="_blank"
- rel="noopener noreferrer"
- >
- Cloud Connectors installation guide
- </Link>{" "}
- for more detail.
- </p>
- </div>
+ <>Connect</>
)}
- </CardContent>
- </Card>
- );
+ </Button>
+ )}
+ </div>
+ ) : (
+ <div className="text-sm text-muted-foreground">
+ <p>
+ See our{" "}
+ <Link
+ className="text-accent-pink-foreground"
+ href="https://docs.openr.ag/knowledge#oauth-ingestion"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ Cloud Connectors installation guide
+ </Link>{" "}
+ for more detail.
+ </p>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ );
}
diff --git a/frontend/app/settings/_components/connector-cards.tsx b/frontend/app/settings/_components/connector-cards.tsx
index f52e5469e..2e9f31a73 100644
--- a/frontend/app/settings/_components/connector-cards.tsx
+++ b/frontend/app/settings/_components/connector-cards.tsx
@@ -1,95 +1,99 @@
"use client";
+import { useRouter } from "next/navigation";
+import { useCallback } from "react";
import { useConnectConnectorMutation } from "@/app/api/mutations/useConnectConnectorMutation";
import { useDisconnectConnectorMutation } from "@/app/api/mutations/useDisconnectConnectorMutation";
-import { useGetConnectorsQuery, type Connector as QueryConnector } from "@/app/api/queries/useGetConnectorsQuery";
+import {
+ type Connector as QueryConnector,
+ useGetConnectorsQuery,
+} from "@/app/api/queries/useGetConnectorsQuery";
import GoogleDriveIcon from "@/components/icons/google-drive-logo";
import OneDriveIcon from "@/components/icons/one-drive-logo";
import SharePointIcon from "@/components/icons/share-point-logo";
import { useAuth } from "@/contexts/auth-context";
-import { useRouter } from "next/navigation";
-import { useCallback } from "react";
import ConnectorCard, { type Connector } from "./connector-card";
import ConnectorsSkeleton from "./connectors-skeleton";
export default function ConnectorCards() {
- const { isAuthenticated, isNoAuthMode } = useAuth();
- const router = useRouter();
+ const { isAuthenticated, isNoAuthMode } = useAuth();
+ const router = useRouter();
- const { data: queryConnectors = [], isLoading: connectorsLoading } = useGetConnectorsQuery({
- enabled: isAuthenticated || isNoAuthMode,
+ const { data: queryConnectors = [], isLoading: connectorsLoading } =
+ useGetConnectorsQuery({
+ enabled: isAuthenticated || isNoAuthMode,
});
- const connectMutation = useConnectConnectorMutation();
- const disconnectMutation = useDisconnectConnectorMutation();
+ const connectMutation = useConnectConnectorMutation();
+ const disconnectMutation = useDisconnectConnectorMutation();
- const getConnectorIcon = useCallback((iconName: string) => {
- const iconMap: { [key: string]: React.ReactElement } = {
- "google-drive": <GoogleDriveIcon />,
- sharepoint: <SharePointIcon />,
- onedrive: <OneDriveIcon />,
- };
- return (
- iconMap[iconName] || (
- <div className="w-8 h-8 bg-gray-500 rounded flex items-center justify-center text-white font-bold leading-none shrink-0">
- ?
- </div>
- )
- );
- }, []);
+ const getConnectorIcon = useCallback((iconName: string) => {
+ const iconMap: { [key: string]: React.ReactElement } = {
+ "google-drive": <GoogleDriveIcon />,
+ sharepoint: <SharePointIcon />,
+ onedrive: <OneDriveIcon />,
+ };
+ return (
+ iconMap[iconName] || (
+ <div className="w-8 h-8 bg-gray-500 rounded flex items-center justify-center text-white font-bold leading-none shrink-0">
+ ?
+ </div>
+ )
+ );
+ }, []);
- const connectors = queryConnectors.map((c) => ({
- ...c,
- icon: getConnectorIcon(c.icon),
- })) as Connector[];
+ const connectors = queryConnectors.map((c) => ({
+ ...c,
+ icon: getConnectorIcon(c.icon),
+ })) as Connector[];
- const handleConnect = async (connector: Connector) => {
- connectMutation.mutate({
- connector: connector as unknown as QueryConnector,
- redirectUri: `${window.location.origin}/auth/callback`,
- });
- };
+ const handleConnect = async (connector: Connector) => {
+ connectMutation.mutate({
+ connector: connector as unknown as QueryConnector,
+ redirectUri: `${window.location.origin}/auth/callback`,
+ });
+ };
- const handleDisconnect = async (connector: Connector) => {
- disconnectMutation.mutate(connector as unknown as QueryConnector);
- };
+ const handleDisconnect = async (connector: Connector) => {
+ disconnectMutation.mutate(connector as unknown as QueryConnector);
+ };
- const navigateToKnowledgePage = (connector: Connector) => {
- const provider = connector.type.replace(/-/g, "_");
- router.push(`/upload/${provider}`);
- };
+ const navigateToKnowledgePage = (connector: Connector) => {
+ const provider = connector.type.replace(/-/g, "_");
+ router.push(`/upload/${provider}`);
+ };
- if (!connectorsLoading && connectors.length === 0) {
- return null;
- }
+ if (!connectorsLoading && connectors.length === 0) {
+ return null;
+ }
- return (
- <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
- {connectorsLoading ? (
- <>
- <ConnectorsSkeleton />
- <ConnectorsSkeleton />
- <ConnectorsSkeleton />
- </>
- ) : (
- connectors.map((connector) => (
- <ConnectorCard
- key={connector.id}
- connector={connector}
- isConnecting={
- connectMutation.isPending &&
- connectMutation.variables?.connector.id === connector.id
- }
- isDisconnecting={
- disconnectMutation.isPending &&
- (disconnectMutation.variables as any)?.type === connector.type
- }
- onConnect={handleConnect}
- onDisconnect={handleDisconnect}
- onNavigateToKnowledge={navigateToKnowledgePage}
- />
- ))
- )}
- </div>
- );
+ return (
+ <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
+ {connectorsLoading ? (
+ <>
+ <ConnectorsSkeleton />
+ <ConnectorsSkeleton />
+ <ConnectorsSkeleton />
+ </>
+ ) : (
+ connectors.map((connector) => (
+ <ConnectorCard
+ key={connector.id}
+ connector={connector}
+ isConnecting={
+ connectMutation.isPending &&
+ connectMutation.variables?.connector.id === connector.id
+ }
+ isDisconnecting={
+ disconnectMutation.isPending &&
+ (disconnectMutation.variables as any)?.type === connector.type
+ }
+ onConnect={handleConnect}
+ onDisconnect={handleDisconnect}
+ onNavigateToKnowledge={navigateToKnowledgePage}
+ />
+ ))
+ )}
+ </div>
+ );
}
diff --git a/frontend/app/settings/_components/connectors-skeleton.tsx b/frontend/app/settings/_components/connectors-skeleton.tsx
index 838906135..2dd61f9d7 100644
--- a/frontend/app/settings/_components/connectors-skeleton.tsx
+++ b/frontend/app/settings/_components/connectors-skeleton.tsx
@@ -2,26 +2,26 @@ import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
export default function ConnectorsSkeleton() {
- return (
- <Card className="relative flex flex-col overflow-hidden">
- <CardHeader className="pb-3">
- <div className="flex flex-col items-start justify-between">
- <div className="flex flex-col gap-4 w-full">
- <div className="mb-1">
- <Skeleton className="w-8 h-8 rounded border" />
- </div>
- <Skeleton className="h-4 w-1/3" />
- <Skeleton className="h-4 w-1/2" />
- </div>
- </div>
- </CardHeader>
- <CardContent className="flex-1 flex flex-col justify-end space-y-4 pt-px">
- <div className="flex gap-2">
- <Skeleton className="h-8 w-24" />
- <Skeleton className="h-8 w-8" />
- <Skeleton className="h-8 w-8" />
- </div>
- </CardContent>
- </Card>
- );
+ return (
+ <Card className="relative flex flex-col overflow-hidden">
+ <CardHeader className="pb-3">
+ <div className="flex flex-col items-start justify-between">
+ <div className="flex flex-col gap-4 w-full">
+ <div className="mb-1">
+ <Skeleton className="w-8 h-8 rounded border" />
+ </div>
+ <Skeleton className="h-4 w-1/3" />
+ <Skeleton className="h-4 w-1/2" />
+ </div>
+ </div>
+ </CardHeader>
+ <CardContent className="flex-1 flex flex-col justify-end space-y-4 pt-px">
+ <div className="flex gap-2">
+ <Skeleton className="h-8 w-24" />
+ <Skeleton className="h-8 w-8" />
+ <Skeleton className="h-8 w-8" />
+ </div>
+ </CardContent>
+ </Card>
+ );
}
diff --git a/frontend/app/settings/_components/ollama-settings-dialog.tsx b/frontend/app/settings/_components/ollama-settings-dialog.tsx
index 0d46def45..e0759600e 100644
--- a/frontend/app/settings/_components/ollama-settings-dialog.tsx
+++ b/frontend/app/settings/_components/ollama-settings-dialog.tsx
@@ -1,5 +1,6 @@
import { useQueryClient } from "@tanstack/react-query";
import { AnimatePresence, motion } from "motion/react";
+import { useRouter } from "next/navigation";
import { useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { toast } from "sonner";
@@ -21,7 +22,6 @@ import {
OllamaSettingsForm,
type OllamaSettingsFormData,
} from "./ollama-settings-form";
-import { useRouter } from "next/navigation";
const OllamaSettingsDialog = ({
open,
diff --git a/frontend/app/settings/_components/openai-settings-dialog.tsx b/frontend/app/settings/_components/openai-settings-dialog.tsx
index 82910c626..6d2ba8736 100644
--- a/frontend/app/settings/_components/openai-settings-dialog.tsx
+++ b/frontend/app/settings/_components/openai-settings-dialog.tsx
@@ -1,5 +1,6 @@
import { useQueryClient } from "@tanstack/react-query";
import { AnimatePresence, motion } from "motion/react";
+import { useRouter } from "next/navigation";
import { useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { toast } from "sonner";
@@ -19,7 +20,6 @@ import {
OpenAISettingsForm,
type OpenAISettingsFormData,
} from "./openai-settings-form";
-import { useRouter } from "next/navigation";
const OpenAISettingsDialog = ({
open,
diff --git a/frontend/app/settings/_components/watsonx-settings-dialog.tsx b/frontend/app/settings/_components/watsonx-settings-dialog.tsx
index 012c868d9..1c781272a 100644
--- a/frontend/app/settings/_components/watsonx-settings-dialog.tsx
+++ b/frontend/app/settings/_components/watsonx-settings-dialog.tsx
@@ -1,5 +1,6 @@
import { useQueryClient } from "@tanstack/react-query";
import { AnimatePresence, motion } from "motion/react";
+import { useRouter } from "next/navigation";
import { useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { toast } from "sonner";
@@ -19,7 +20,6 @@ import {
WatsonxSettingsForm,
type WatsonxSettingsFormData,
} from "./watsonx-settings-form";
-import { useRouter } from "next/navigation";
const WatsonxSettingsDialog = ({
open,
diff --git a/frontend/app/settings/_components/watsonx-settings-form.tsx b/frontend/app/settings/_components/watsonx-settings-form.tsx
index c994413be..d07d2393c 100644
--- a/frontend/app/settings/_components/watsonx-settings-form.tsx
+++ b/frontend/app/settings/_components/watsonx-settings-form.tsx
@@ -1,7 +1,7 @@
-import { useFormContext, Controller } from "react-hook-form";
+import { Controller, useFormContext } from "react-hook-form";
+import { ModelSelector } from "@/app/onboarding/_components/model-selector";
import { LabelWrapper } from "@/components/label-wrapper";
import { Input } from "@/components/ui/input";
-import { ModelSelector } from "@/app/onboarding/_components/model-selector";
export interface WatsonxSettingsFormData {
endpoint: string;
diff --git a/frontend/app/settings/_helpers/model-select-item.tsx b/frontend/app/settings/_helpers/model-select-item.tsx
index a360a1bb1..3fd36727d 100644
--- a/frontend/app/settings/_helpers/model-select-item.tsx
+++ b/frontend/app/settings/_helpers/model-select-item.tsx
@@ -1,8 +1,8 @@
import { SelectItem } from "@/components/ui/select";
import {
getModelLogo,
- type ModelProvider,
type ModelOption,
+ type ModelProvider,
} from "./model-helpers";
interface ModelSelectItemProps {
diff --git a/frontend/app/settings/page.tsx b/frontend/app/settings/page.tsx
index a6e9d5296..e942480ac 100644
--- a/frontend/app/settings/page.tsx
+++ b/frontend/app/settings/page.tsx
@@ -1,39 +1,47 @@
"use client";
-import { ArrowUpRight, Copy, Key, Loader2, Minus, Plus, Trash2 } from "lucide-react";
+import {
+ ArrowUpRight,
+ Copy,
+ Key,
+ Loader2,
+ Minus,
+ Plus,
+ Trash2,
+} from "lucide-react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useEffect, useState } from "react";
import { toast } from "sonner";
-import {
- useGetAnthropicModelsQuery,
- useGetIBMModelsQuery,
- useGetOllamaModelsQuery,
- useGetOpenAIModelsQuery,
-} from "@/app/api/queries/useGetModelsQuery";
-import { useGetApiKeysQuery } from "@/app/api/queries/useGetApiKeysQuery";
import { useCreateApiKeyMutation } from "@/app/api/mutations/useCreateApiKeyMutation";
import { useRevokeApiKeyMutation } from "@/app/api/mutations/useRevokeApiKeyMutation";
+import { useGetApiKeysQuery } from "@/app/api/queries/useGetApiKeysQuery";
+import {
+ useGetAnthropicModelsQuery,
+ useGetIBMModelsQuery,
+ useGetOllamaModelsQuery,
+ useGetOpenAIModelsQuery,
+} from "@/app/api/queries/useGetModelsQuery";
import { useGetSettingsQuery } from "@/app/api/queries/useGetSettingsQuery";
import { ConfirmationDialog } from "@/components/confirmation-dialog";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
import { LabelWrapper } from "@/components/label-wrapper";
import { ProtectedRoute } from "@/components/protected-route";
import { Button } from "@/components/ui/button";
import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
} from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
@@ -41,1225 +49,1221 @@ import { Textarea } from "@/components/ui/textarea";
import { useAuth } from "@/contexts/auth-context";
import { useTask } from "@/contexts/task-context";
import {
- DEFAULT_AGENT_SETTINGS,
- DEFAULT_KNOWLEDGE_SETTINGS,
- UI_CONSTANTS,
+ DEFAULT_AGENT_SETTINGS,
+ DEFAULT_KNOWLEDGE_SETTINGS,
+ UI_CONSTANTS,
} from "@/lib/constants";
import { useDebounce } from "@/lib/debounce";
import { cn } from "@/lib/utils";
import { useUpdateSettingsMutation } from "../api/mutations/useUpdateSettingsMutation";
import { ModelSelector } from "../onboarding/_components/model-selector";
-import ModelProviders from "./_components/model-providers";
import ConnectorCards from "./_components/connector-cards";
+import ModelProviders from "./_components/model-providers";
import { getModelLogo, type ModelProvider } from "./_helpers/model-helpers";
const { MAX_SYSTEM_PROMPT_CHARS } = UI_CONSTANTS;
-
function KnowledgeSourcesPage() {
- const { isAuthenticated, isNoAuthMode } = useAuth();
- const { addTask, tasks } = useTask();
- const searchParams = useSearchParams();
- const router = useRouter();
-
- // Check if we should auto-open the LLM model selector
- const focusLlmModel = searchParams.get("focusLlmModel") === "true";
- // Use a trigger state that changes each time we detect the query param
- const [openLlmSelector, setOpenLlmSelector] = useState(false);
-
- // API Keys state
- const [createKeyDialogOpen, setCreateKeyDialogOpen] = useState(false);
- const [newKeyName, setNewKeyName] = useState("");
- const [newlyCreatedKey, setNewlyCreatedKey] = useState<string | null>(null);
- const [showKeyDialogOpen, setShowKeyDialogOpen] = useState(false);
-
-
- // Only keep systemPrompt state since it needs manual save button
- const [systemPrompt, setSystemPrompt] = useState<string>("");
- const [chunkSize, setChunkSize] = useState<number>(1024);
- const [chunkOverlap, setChunkOverlap] = useState<number>(50);
- const [tableStructure, setTableStructure] = useState<boolean>(true);
- const [ocr, setOcr] = useState<boolean>(false);
- const [pictureDescriptions, setPictureDescriptions] =
- useState<boolean>(false);
-
- // Fetch settings using React Query
- const { data: settings = {} } = useGetSettingsQuery({
- enabled: isAuthenticated || isNoAuthMode,
- });
-
- // Fetch API keys
- const { data: apiKeysData, isLoading: apiKeysLoading } = useGetApiKeysQuery({
- enabled: isAuthenticated || isNoAuthMode,
- });
-
- // API key mutations
- const createApiKeyMutation = useCreateApiKeyMutation({
- onSuccess: (data) => {
- setNewlyCreatedKey(data.api_key);
- setCreateKeyDialogOpen(false);
- setShowKeyDialogOpen(true);
- setNewKeyName("");
- toast.success("API key created");
- },
- onError: (error) => {
- toast.error("Failed to create API key", { description: error.message });
- },
- });
-
- const revokeApiKeyMutation = useRevokeApiKeyMutation({
- onSuccess: () => {
- toast.success("API key revoked");
- },
- onError: (error) => {
- toast.error("Failed to revoke API key", { description: error.message });
- },
- });
-
- // Fetch models for each provider
- const { data: openaiModels, isLoading: openaiLoading } =
- useGetOpenAIModelsQuery(
- { apiKey: "" },
- { enabled: settings?.providers?.openai?.configured === true },
- );
-
- const { data: anthropicModels, isLoading: anthropicLoading } =
- useGetAnthropicModelsQuery(
- { apiKey: "" },
- { enabled: settings?.providers?.anthropic?.configured === true },
- );
-
- const { data: ollamaModels, isLoading: ollamaLoading } =
- useGetOllamaModelsQuery(
- { endpoint: settings?.providers?.ollama?.endpoint },
- {
- enabled:
- settings?.providers?.ollama?.configured === true &&
- !!settings?.providers?.ollama?.endpoint,
- },
- );
-
- const { data: watsonxModels, isLoading: watsonxLoading } =
- useGetIBMModelsQuery(
- {
- endpoint: settings?.providers?.watsonx?.endpoint,
- apiKey: "",
- projectId: settings?.providers?.watsonx?.project_id,
- },
- {
- enabled:
- settings?.providers?.watsonx?.configured === true &&
- !!settings?.providers?.watsonx?.endpoint &&
- !!settings?.providers?.watsonx?.project_id,
- },
- );
-
- // Build grouped LLM model options from all configured providers
- const groupedLlmModels = [
- {
- group: "OpenAI",
- provider: "openai",
- icon: getModelLogo("", "openai"),
- models: openaiModels?.language_models || [],
- configured: settings.providers?.openai?.configured === true,
- },
- {
- group: "Anthropic",
- provider: "anthropic",
- icon: getModelLogo("", "anthropic"),
- models: anthropicModels?.language_models || [],
- configured: settings.providers?.anthropic?.configured === true,
- },
- {
- group: "Ollama",
- provider: "ollama",
- icon: getModelLogo("", "ollama"),
- models: ollamaModels?.language_models || [],
- configured: settings.providers?.ollama?.configured === true,
- },
- {
- group: "IBM watsonx.ai",
- provider: "watsonx",
- icon: getModelLogo("", "watsonx"),
- models: watsonxModels?.language_models || [],
- configured: settings.providers?.watsonx?.configured === true,
- },
- ]
- .filter((provider) => provider.configured)
- .map((provider) => ({
- group: provider.group,
- icon: provider.icon,
- options: provider.models.map((model) => ({
- ...model,
- provider: provider.provider,
- })),
- }));
-
- // Build grouped embedding model options from all configured providers (excluding Anthropic)
- const groupedEmbeddingModels = [
- {
- group: "OpenAI",
- provider: "openai",
- icon: getModelLogo("", "openai"),
- models: openaiModels?.embedding_models || [],
- configured: settings.providers?.openai?.configured === true,
- },
- {
- group: "Ollama",
- provider: "ollama",
- icon: getModelLogo("", "ollama"),
- models: ollamaModels?.embedding_models || [],
- configured: settings.providers?.ollama?.configured === true,
- },
- {
- group: "IBM watsonx.ai",
- provider: "watsonx",
- icon: getModelLogo("", "watsonx"),
- models: watsonxModels?.embedding_models || [],
- configured: settings.providers?.watsonx?.configured === true,
- },
- ]
- .filter((provider) => provider.configured)
- .map((provider) => ({
- group: provider.group,
- icon: provider.icon,
- options: provider.models.map((model) => ({
- ...model,
- provider: provider.provider,
- })),
- }));
-
- const isLoadingAnyLlmModels =
- openaiLoading || anthropicLoading || ollamaLoading || watsonxLoading;
- const isLoadingAnyEmbeddingModels =
- openaiLoading || ollamaLoading || watsonxLoading;
-
- // Mutations
- const updateSettingsMutation = useUpdateSettingsMutation({
- onSuccess: () => {
- toast.success("Settings updated successfully");
- },
- onError: (error) => {
- toast.error("Failed to update settings", {
- description: error.message,
- });
- },
- });
-
- // Debounced update function
- const debouncedUpdate = useDebounce(
- (variables: Parameters<typeof updateSettingsMutation.mutate>[0]) => {
- updateSettingsMutation.mutate(variables);
- },
- 500,
- );
-
- // Sync system prompt state with settings data
- useEffect(() => {
- if (settings.agent?.system_prompt) {
- setSystemPrompt(settings.agent.system_prompt);
- }
- }, [settings.agent?.system_prompt]);
-
- // Sync chunk size and overlap state with settings data
- useEffect(() => {
- if (settings.knowledge?.chunk_size) {
- setChunkSize(settings.knowledge.chunk_size);
- }
- }, [settings.knowledge?.chunk_size]);
-
- useEffect(() => {
- if (settings.knowledge?.chunk_overlap) {
- setChunkOverlap(settings.knowledge.chunk_overlap);
- }
- }, [settings.knowledge?.chunk_overlap]);
-
- // Sync docling settings with settings data
- useEffect(() => {
- if (settings.knowledge?.table_structure !== undefined) {
- setTableStructure(settings.knowledge.table_structure);
- }
- }, [settings.knowledge?.table_structure]);
-
- useEffect(() => {
- if (settings.knowledge?.ocr !== undefined) {
- setOcr(settings.knowledge.ocr);
- }
- }, [settings.knowledge?.ocr]);
-
- useEffect(() => {
- if (settings.knowledge?.picture_descriptions !== undefined) {
- setPictureDescriptions(settings.knowledge.picture_descriptions);
- }
- }, [settings.knowledge?.picture_descriptions]);
-
- // Handle auto-focus on LLM model selector when coming from provider setup
- useEffect(() => {
- if (focusLlmModel) {
- // Trigger the selector to open
- setOpenLlmSelector(true);
-
- // Scroll to the agent card
- const agentCard = document.getElementById("agent-card");
- if (agentCard) {
- agentCard.scrollIntoView({ behavior: "smooth", block: "start" });
- }
-
- // Clear the query parameter
- const newSearchParams = new URLSearchParams(searchParams.toString());
- newSearchParams.delete("focusLlmModel");
- router.replace(`/settings?${newSearchParams.toString()}`, {
- scroll: false,
- });
-
- // Reset the trigger after a brief delay so it can be triggered again
- setTimeout(() => setOpenLlmSelector(false), 100);
- }
- }, [focusLlmModel, searchParams, router]);
-
- // Update model selection immediately (also updates provider)
- const handleModelChange = (newModel: string, provider?: string) => {
- if (newModel && provider) {
- updateSettingsMutation.mutate({
- llm_model: newModel,
- llm_provider: provider,
- });
- } else if (newModel) {
- updateSettingsMutation.mutate({ llm_model: newModel });
- }
- };
-
- // Update system prompt with save button
- const handleSystemPromptSave = () => {
- updateSettingsMutation.mutate({ system_prompt: systemPrompt });
- };
-
- // Update embedding model selection immediately (also updates provider)
- const handleEmbeddingModelChange = (newModel: string, provider?: string) => {
- if (newModel && provider) {
- updateSettingsMutation.mutate({
- embedding_model: newModel,
- embedding_provider: provider,
- });
- } else if (newModel) {
- updateSettingsMutation.mutate({ embedding_model: newModel });
- }
- };
-
- // Update chunk size setting with debounce
- const handleChunkSizeChange = (value: string) => {
- const numValue = Math.max(0, parseInt(value) || 0);
- setChunkSize(numValue);
- debouncedUpdate({ chunk_size: numValue });
- };
-
- // Update chunk overlap setting with debounce
- const handleChunkOverlapChange = (value: string) => {
- const numValue = Math.max(0, parseInt(value) || 0);
- setChunkOverlap(numValue);
- debouncedUpdate({ chunk_overlap: numValue });
- };
-
- // Update docling settings
- const handleTableStructureChange = (checked: boolean) => {
- setTableStructure(checked);
- updateSettingsMutation.mutate({ table_structure: checked });
- };
-
- const handleOcrChange = (checked: boolean) => {
- setOcr(checked);
- updateSettingsMutation.mutate({ ocr: checked });
- };
-
- const handlePictureDescriptionsChange = (checked: boolean) => {
- setPictureDescriptions(checked);
- updateSettingsMutation.mutate({ picture_descriptions: checked });
- };
-
- // API Keys handlers
- const handleCreateApiKey = () => {
- if (!newKeyName.trim()) {
- toast.error("Please enter a name for the API key");
- return;
- }
- createApiKeyMutation.mutate({ name: newKeyName.trim() });
- };
-
- const handleRevokeApiKey = (keyId: string) => {
- revokeApiKeyMutation.mutate({ key_id: keyId });
- };
-
- const handleCopyApiKey = async () => {
- if (newlyCreatedKey) {
- await navigator.clipboard.writeText(newlyCreatedKey);
- toast.success("API key copied to clipboard");
- }
- };
-
- const formatDate = (dateString: string | null) => {
- if (!dateString) return "Never";
- const date = new Date(dateString);
- return date.toLocaleDateString(undefined, {
- year: "numeric",
- month: "short",
- day: "numeric",
- });
- };
-
-
-
-
-
-
- // Check connector status on mount and when returning from OAuth
- useEffect(() => {
- if (searchParams.get("oauth_success") === "true") {
- const url = new URL(window.location.href);
- url.searchParams.delete("oauth_success");
- window.history.replaceState({}, "", url.toString());
- }
- }, [searchParams]);
-
- // Track previous tasks to detect new completions
- const [prevTasks, setPrevTasks] = useState<typeof tasks>([]);
-
- // Watch for task completions and refresh stats
- useEffect(() => {
- // Find newly completed tasks by comparing with previous state
- const newlyCompletedTasks = tasks.filter((task) => {
- const wasCompleted =
- prevTasks.find((prev) => prev.task_id === task.task_id)?.status ===
- "completed";
- return task.status === "completed" && !wasCompleted;
- });
-
- if (newlyCompletedTasks.length > 0) {
- // Task completed - could refresh data here if needed
- const timeoutId = setTimeout(() => {
- // Stats refresh removed
- }, 1000);
-
- // Update previous tasks state
- setPrevTasks(tasks);
-
- return () => clearTimeout(timeoutId);
- } else {
- // Always update previous tasks state
- setPrevTasks(tasks);
- }
- }, [tasks, prevTasks]);
-
- const handleEditInLangflow = (
- flowType: "chat" | "ingest",
- closeDialog: () => void,
- ) => {
- // Select the appropriate flow ID and edit URL based on flow type
- const targetFlowId =
- flowType === "ingest" ? settings.ingest_flow_id : settings.flow_id;
- const editUrl =
- flowType === "ingest"
- ? settings.langflow_ingest_edit_url
- : settings.langflow_edit_url;
-
- const derivedFromWindow =
- typeof window !== "undefined"
- ? `${window.location.protocol}//${window.location.hostname}:7860`
- : "";
- const base = (
- settings.langflow_public_url ||
- derivedFromWindow ||
- "http://localhost:7860"
- ).replace(/\/$/, "");
- const computed = targetFlowId ? `${base}/flow/${targetFlowId}` : base;
-
- const url = editUrl || computed;
-
- window.open(url, "_blank");
- closeDialog(); // Close immediately after opening Langflow
- };
-
- const handleRestoreRetrievalFlow = (closeDialog: () => void) => {
- fetch(`/api/reset-flow/retrieval`, {
- method: "POST",
- })
- .then((response) => {
- if (response.ok) {
- return response.json();
- }
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
- })
- .then(() => {
- // Flow restoration is complete - backend already updated flow with current provider/model
- // Just reset the UI form value for system prompt
- setSystemPrompt(DEFAULT_AGENT_SETTINGS.system_prompt);
- closeDialog(); // Close after successful completion
- })
- .catch((error) => {
- console.error("Error restoring retrieval flow:", error);
- closeDialog(); // Close even on error (could show error toast instead)
- });
- };
-
- const handleRestoreIngestFlow = (closeDialog: () => void) => {
- fetch(`/api/reset-flow/ingest`, {
- method: "POST",
- })
- .then((response) => {
- if (response.ok) {
- return response.json();
- }
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
- })
- .then(() => {
- // Only reset form values if the API call was successful
- setChunkSize(DEFAULT_KNOWLEDGE_SETTINGS.chunk_size);
- setChunkOverlap(DEFAULT_KNOWLEDGE_SETTINGS.chunk_overlap);
- setTableStructure(false);
- setOcr(false);
- setPictureDescriptions(false);
- closeDialog(); // Close after successful completion
- })
- .catch((error) => {
- console.error("Error restoring ingest flow:", error);
- closeDialog(); // Close even on error (could show error toast instead)
- });
- };
-
- return (
- <div className="space-y-8 pb-6">
- {/* Connectors Section */}
- <div className="space-y-6">
- <div>
- <h2 className="text-lg font-semibold tracking-tight mb-2">
- Cloud Connectors
- </h2>
- </div>
-
- {/* Conditional Sync Settings or No-Auth Message */}
- {
- isNoAuthMode ? (
- <Card className="border-accent-amber-foreground">
- <CardHeader>
- <CardTitle className="text-lg">
- Cloud connectors require authentication
- </CardTitle>
- <CardDescription className="text-sm">
- Add the Google OAuth variables below to your <code>.env</code>{" "}
- then restart the OpenRAG containers.
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="bg-muted rounded-md p-4 font-mono text-sm">
- <div className="text-muted-foreground">
- <div>
- <span className="mr-3 text-placeholder-foreground">
- 27
- </span>
- <span># Google OAuth</span>
- </div>
- <div>
- <span className="mr-3 text-placeholder-foreground">
- 28
- </span>
- <span># Create credentials here:</span>
- </div>
- <div>
- <span className="mr-3 text-placeholder-foreground">
- 29
- </span>
- <span>
- # https://console.cloud.google.com/apis/credentials
- </span>
- </div>
- </div>
- <div>
- <span className="mr-3 text-placeholder-foreground">30</span>
- <span>GOOGLE_OAUTH_CLIENT_ID=</span>
- </div>
- <div>
- <span className="mr-3 text-placeholder-foreground">31</span>
- <span>GOOGLE_OAUTH_CLIENT_SECRET=</span>
- </div>
- </div>
- </CardContent>
- </Card>
- ) : null
- // <div className="flex items-center justify-between py-4">
- // <div>
- // <h3 className="text-lg font-medium">Sync Settings</h3>
- // <p className="text-sm text-muted-foreground">
- // Configure how many files to sync when manually triggering a sync
- // </p>
- // </div>
- // <div className="flex items-center gap-4">
- // <div className="flex items-center space-x-2">
- // <Checkbox
- // id="syncAllFiles"
- // checked={syncAllFiles}
- // onCheckedChange={checked => {
- // setSyncAllFiles(!!checked);
- // if (checked) {
- // setMaxFiles(0);
- // } else {
- // setMaxFiles(10);
- // }
- // }}
- // />
- // <Label
- // htmlFor="syncAllFiles"
- // className="font-medium whitespace-nowrap"
- // >
- // Sync all files
- // </Label>
- // </div>
- // <Label
- // htmlFor="maxFiles"
- // className="font-medium whitespace-nowrap"
- // >
- // Max files per sync:
- // </Label>
- // <div className="relative">
- // <Input
- // id="maxFiles"
- // type="number"
- // value={syncAllFiles ? 0 : maxFiles}
- // onChange={e => setMaxFiles(parseInt(e.target.value) || 10)}
- // disabled={syncAllFiles}
- // className="w-16 min-w-16 max-w-16 flex-shrink-0 disabled:opacity-50 disabled:cursor-not-allowed"
- // min="1"
- // max="100"
- // title={
- // syncAllFiles
- // ? "Disabled when 'Sync all files' is checked"
- // : "Leave blank or set to 0 for unlimited"
- // }
- // />
- // </div>
- // </div>
- // </div>
- }
- {/* Connectors Grid */}
- <ConnectorCards />
- </div>
-
- {/* Model Providers Section */}
- <div className="space-y-6">
- <div>
- <h2 className="text-lg font-semibold tracking-tight mb-2">
- Model Providers
- </h2>
- </div>
- <ModelProviders />
- </div>
-
- {/* Agent Behavior Section */}
- <Card id="agent-card">
- <CardHeader>
- <div className="flex items-center justify-between mb-3">
- <CardTitle className="text-lg">Agent</CardTitle>
- <div className="flex gap-2">
- <ConfirmationDialog
- trigger={
- <Button ignoreTitleCase={true} variant="outline">
- Restore flow
- </Button>
- }
- title="Restore default Agent flow"
- description="This restores defaults and discards all custom settings and overrides. This can’t be undone."
- confirmText="Restore"
- variant="destructive"
- onConfirm={handleRestoreRetrievalFlow}
- />
- <ConfirmationDialog
- trigger={
- <Button>
- <svg
- xmlns="http://www.w3.org/2000/svg"
- width="24"
- height="22"
- viewBox="0 0 24 22"
- className="h-4 w-4 mr-2"
- aria-label="Langflow icon"
- >
- <title>Langflow icon</title>
- <path
- fill="currentColor"
- d="M13.0486 0.462158H9.75399C9.44371 0.462158 9.14614 0.586082 8.92674 0.806667L4.03751 5.72232C3.81811 5.9429 3.52054 6.06682 3.21026 6.06682H1.16992C0.511975 6.06682 -0.0165756 6.61212 0.000397655 7.2734L0.0515933 9.26798C0.0679586 9.90556 0.586745 10.4139 1.22111 10.4139H3.59097C3.90124 10.4139 4.19881 10.2899 4.41821 10.0694L9.34823 5.11269C9.56763 4.89211 9.8652 4.76818 10.1755 4.76818H13.0486C13.6947 4.76818 14.2185 4.24157 14.2185 3.59195V1.63839C14.2185 0.988773 13.6947 0.462158 13.0486 0.462158Z"
- ></path>
- <path
- fill="currentColor"
- d="M19.5355 11.5862H22.8301C23.4762 11.5862 24 12.1128 24 12.7624V14.716C24 15.3656 23.4762 15.8922 22.8301 15.8922H19.957C19.6467 15.8922 19.3491 16.0161 19.1297 16.2367L14.1997 21.1934C13.9803 21.414 13.6827 21.5379 13.3725 21.5379H11.0026C10.3682 21.5379 9.84945 21.0296 9.83309 20.392L9.78189 18.3974C9.76492 17.7361 10.2935 17.1908 10.9514 17.1908H12.9918C13.302 17.1908 13.5996 17.0669 13.819 16.8463L18.7082 11.9307C18.9276 11.7101 19.2252 11.5862 19.5355 11.5862Z"
- ></path>
- <path
- fill="currentColor"
- d="M19.5355 2.9796L22.8301 2.9796C23.4762 2.9796 24 3.50622 24 4.15583V6.1094C24 6.75901 23.4762 7.28563 22.8301 7.28563H19.957C19.6467 7.28563 19.3491 7.40955 19.1297 7.63014L14.1997 12.5868C13.9803 12.8074 13.6827 12.9313 13.3725 12.9313H10.493C10.1913 12.9313 9.90126 13.0485 9.68346 13.2583L4.14867 18.5917C3.93087 18.8016 3.64085 18.9187 3.33917 18.9187H1.32174C0.675616 18.9187 0.151832 18.3921 0.151832 17.7425V15.7343C0.151832 15.0846 0.675616 14.558 1.32174 14.558H3.32468C3.63496 14.558 3.93253 14.4341 4.15193 14.2135L9.40827 8.92878C9.62767 8.70819 9.92524 8.58427 10.2355 8.58427H12.9918C13.302 8.58427 13.5996 8.46034 13.819 8.23976L18.7082 3.32411C18.9276 3.10353 19.2252 2.9796 19.5355 2.9796Z"
- ></path>
- </svg>
- Edit in Langflow
- </Button>
- }
- title="Edit Agent flow in Langflow"
- description={
- <>
- <p className="mb-2">
- You&apos;re entering Langflow. You can edit the{" "}
- <b>Agent flow</b> and other underlying flows. Manual
- changes to components, wiring, or I/O can break this
- experience.
- </p>
- <p className="mb-2">
- To enable editing, you need to unlock the flow by clicking
- on its name and disabling the <b>Lock flow</b> option.
- </p>
- <p>You can restore this flow from Settings.</p>
- </>
- }
- confirmText="Proceed"
- confirmIcon={<ArrowUpRight />}
- onConfirm={(closeDialog) =>
- handleEditInLangflow("chat", closeDialog)
- }
- variant="warning"
- />
- </div>
- </div>
- <CardDescription>
- This Agent retrieves from your knowledge and generates chat
- responses. Edit in Langflow for full control.
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="space-y-6">
- <div className="space-y-2">
- <LabelWrapper
- label="Language model"
- helperText="Model used for chat"
- id="language-model"
- required={true}
- >
- <ModelSelector
- groupedOptions={groupedLlmModels}
- noOptionsPlaceholder={
- isLoadingAnyLlmModels
- ? "Loading models..."
- : "No language models detected. Configure a provider first."
- }
- value={settings.agent?.llm_model || ""}
- onValueChange={handleModelChange}
- defaultOpen={openLlmSelector}
- />
- </LabelWrapper>
- </div>
- <div className="space-y-2">
- <LabelWrapper label="Agent Instructions" id="system-prompt">
- <Textarea
- id="system-prompt"
- placeholder="Enter your agent instructions here..."
- value={systemPrompt}
- onChange={(e) => setSystemPrompt(e.target.value)}
- rows={6}
- className={`resize-none ${systemPrompt.length > MAX_SYSTEM_PROMPT_CHARS
- ? "!border-destructive focus:border-destructive"
- : ""
- }`}
- />
- </LabelWrapper>
- <span
- className={`text-xs ${systemPrompt.length > MAX_SYSTEM_PROMPT_CHARS
- ? "text-destructive"
- : "text-muted-foreground"
- }`}
- >
- {systemPrompt.length}/{MAX_SYSTEM_PROMPT_CHARS} characters
- </span>
- </div>
- <div className="flex justify-end pt-2">
- <Button
- onClick={handleSystemPromptSave}
- disabled={
- updateSettingsMutation.isPending ||
- systemPrompt.length > MAX_SYSTEM_PROMPT_CHARS
- }
- className="min-w-[120px]"
- size="sm"
- variant="outline"
- >
- {updateSettingsMutation.isPending ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- Saving...
- </>
- ) : (
- "Save Agent Instructions"
- )}
- </Button>
- </div>
- </div>
- </CardContent>
- </Card>
-
- {/* Knowledge Ingest Section */}
- <Card>
- <CardHeader>
- <div className="flex items-center justify-between mb-3">
- <CardTitle className="text-lg">Knowledge Ingest</CardTitle>
- <div className="flex gap-2">
- <ConfirmationDialog
- trigger={
- <Button ignoreTitleCase={true} variant="outline">
- Restore flow
- </Button>
- }
- title="Restore default Ingest flow"
- description="This restores defaults and discards all custom settings and overrides. This can't be undone."
- confirmText="Restore"
- variant="destructive"
- onConfirm={handleRestoreIngestFlow}
- />
- <ConfirmationDialog
- trigger={
- <Button>
- <svg
- xmlns="http://www.w3.org/2000/svg"
- width="24"
- height="22"
- viewBox="0 0 24 22"
- className="h-4 w-4 mr-2"
- aria-label="Langflow icon"
- >
- <title>Langflow icon</title>
- <path
- fill="currentColor"
- d="M13.0486 0.462158H9.75399C9.44371 0.462158 9.14614 0.586082 8.92674 0.806667L4.03751 5.72232C3.81811 5.9429 3.52054 6.06682 3.21026 6.06682H1.16992C0.511975 6.06682 -0.0165756 6.61212 0.000397655 7.2734L0.0515933 9.26798C0.0679586 9.90556 0.586745 10.4139 1.22111 10.4139H3.59097C3.90124 10.4139 4.19881 10.2899 4.41821 10.0694L9.34823 5.11269C9.56763 4.89211 9.8652 4.76818 10.1755 4.76818H13.0486C13.6947 4.76818 14.2185 4.24157 14.2185 3.59195V1.63839C14.2185 0.988773 13.6947 0.462158 13.0486 0.462158Z"
- ></path>
- <path
- fill="currentColor"
- d="M19.5355 11.5862H22.8301C23.4762 11.5862 24 12.1128 24 12.7624V14.716C24 15.3656 23.4762 15.8922 22.8301 15.8922H19.957C19.6467 15.8922 19.3491 16.0161 19.1297 16.2367L14.1997 21.1934C13.9803 21.414 13.6827 21.5379 13.3725 21.5379H11.0026C10.3682 21.5379 9.84945 21.0296 9.83309 20.392L9.78189 18.3974C9.76492 17.7361 10.2935 17.1908 10.9514 17.1908H12.9918C13.302 17.1908 13.5996 17.0669 13.819 16.8463L18.7082 11.9307C18.9276 11.7101 19.2252 11.5862 19.5355 11.5862Z"
- ></path>
- <path
- fill="currentColor"
- d="M19.5355 2.9796L22.8301 2.9796C23.4762 2.9796 24 3.50622 24 4.15583V6.1094C24 6.75901 23.4762 7.28563 22.8301 7.28563H19.957C19.6467 7.28563 19.3491 7.40955 19.1297 7.63014L14.1997 12.5868C13.9803 12.8074 13.6827 12.9313 13.3725 12.9313H10.493C10.1913 12.9313 9.90126 13.0485 9.68346 13.2583L4.14867 18.5917C3.93087 18.8016 3.64085 18.9187 3.33917 18.9187H1.32174C0.675616 18.9187 0.151832 18.3921 0.151832 17.7425V15.7343C0.151832 15.0846 0.675616 14.558 1.32174 14.558H3.32468C3.63496 14.558 3.93253 14.4341 4.15193 14.2135L9.40827 8.92878C9.62767 8.70819 9.92524 8.58427 10.2355 8.58427H12.9918C13.302 8.58427 13.5996 8.46034 13.819 8.23976L18.7082 3.32411C18.9276 3.10353 19.2252 2.9796 19.5355 2.9796Z"
- ></path>
- </svg>
- Edit in Langflow
- </Button>
- }
- title="Edit Ingest flow in Langflow"
- description={
- <>
- <p className="mb-2">
- You&apos;re entering Langflow. You can edit the{" "}
- <b>Ingest flow</b> and other underlying flows. Manual
- changes to components, wiring, or I/O can break this
- experience.
- </p>
- <p className="mb-2">
- To enable editing, you need to unlock the flow by clicking
- on its name and disabling the <b>Lock flow</b> option.
- </p>
- <p>You can restore this flow from Settings.</p>
- </>
- }
- confirmText="Proceed"
- confirmIcon={<ArrowUpRight />}
- variant="warning"
- onConfirm={(closeDialog) =>
- handleEditInLangflow("ingest", closeDialog)
- }
- />
- </div>
- </div>
- <CardDescription>
- Configure how files are ingested and stored for retrieval. Edit in
- Langflow for full control.
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="space-y-6">
- <div className="space-y-2">
- <LabelWrapper
- helperText="Model used for knowledge ingest and retrieval"
- id="embedding-model-select"
- label="Embedding model"
- required={true}
- >
- <ModelSelector
- groupedOptions={groupedEmbeddingModels}
- noOptionsPlaceholder={
- isLoadingAnyEmbeddingModels
- ? "Loading models..."
- : "No embedding models detected. Configure a provider first."
- }
- value={settings.knowledge?.embedding_model || ""}
- onValueChange={handleEmbeddingModelChange}
- />
- </LabelWrapper>
- </div>
- <div className="grid grid-cols-2 gap-4">
- <div className="space-y-2">
- <LabelWrapper id="chunk-size" label="Chunk size">
- <div className="relative [&:has(input:hover):not(:has(input:focus))_button]:border-muted-foreground [&:has(input:focus)_button]:border-foreground">
- <Input
- id="chunk-size"
- type="number"
- min="1"
- value={chunkSize}
- onChange={(e) => handleChunkSizeChange(e.target.value)}
- className="w-full pr-20 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- <div className="absolute inset-y-0 right-0 flex items-center">
- <span className="text-sm text-placeholder-foreground mr-4 pointer-events-none">
- characters
- </span>
- <div className="flex flex-col">
- <Button
- aria-label="Increase value"
- className="h-5 rounded-l-none rounded-br-none border-input border-b-[0.5px] focus-visible:relative transition-colors"
- variant="outline"
- size="iconSm"
- onClick={() =>
- handleChunkSizeChange((chunkSize + 1).toString())
- }
- >
- <Plus className="text-muted-foreground" size={8} />
- </Button>
- <Button
- aria-label="Decrease value"
- className="h-5 rounded-l-none rounded-tr-none border-input border-t-[0.5px] focus-visible:relative transition-colors"
- variant="outline"
- size="iconSm"
- onClick={() =>
- handleChunkSizeChange((chunkSize - 1).toString())
- }
- >
- <Minus className="text-muted-foreground" size={8} />
- </Button>
- </div>
- </div>
- </div>
- </LabelWrapper>
- </div>
- <div className="space-y-2">
- <LabelWrapper id="chunk-overlap" label="Chunk overlap">
- <div className="relative [&:has(input:hover):not(:has(input:focus))_button]:border-muted-foreground [&:has(input:focus)_button]:border-foreground">
- <Input
- id="chunk-overlap"
- type="number"
- min="0"
- value={chunkOverlap}
- onChange={(e) => handleChunkOverlapChange(e.target.value)}
- className="w-full pr-20 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- <div className="absolute inset-y-0 right-0 flex items-center">
- <span className="text-sm text-placeholder-foreground mr-4 pointer-events-none">
- characters
- </span>
- <div className="flex flex-col">
- <Button
- aria-label="Increase value"
- className="h-5 rounded-l-none rounded-br-none border-input border-b-[0.5px] focus-visible:relative transition-colors"
- variant="outline"
- size="iconSm"
- onClick={() =>
- handleChunkOverlapChange(
- (chunkOverlap + 1).toString(),
- )
- }
- >
- <Plus className="text-muted-foreground" size={8} />
- </Button>
- <Button
- aria-label="Decrease value"
- className="h-5 rounded-l-none rounded-tr-none border-input border-t-[0.5px] focus-visible:relative transition-colors"
- variant="outline"
- size="iconSm"
- onClick={() =>
- handleChunkOverlapChange(
- (chunkOverlap - 1).toString(),
- )
- }
- >
- <Minus className="text-muted-foreground" size={8} />
- </Button>
- </div>
- </div>
- </div>
- </LabelWrapper>
- </div>
- </div>
- <div className="">
- <div className="flex items-center justify-between py-3 border-b border-border">
- <div className="flex-1">
- <Label
- htmlFor="table-structure"
- className="text-base font-medium cursor-pointer pb-3"
- >
- Table Structure
- </Label>
- <div className="text-sm text-muted-foreground">
- Capture table structure during ingest.
- </div>
- </div>
- <Switch
- id="table-structure"
- checked={tableStructure}
- onCheckedChange={handleTableStructureChange}
- />
- </div>
- <div className="flex items-center justify-between py-3 border-b border-border">
- <div className="flex-1">
- <Label
- htmlFor="ocr"
- className="text-base font-medium cursor-pointer pb-3"
- >
- OCR
- </Label>
- <div className="text-sm text-muted-foreground">
- Extracts text from images/PDFs. Ingest is slower when
- enabled.
- </div>
- </div>
- <Switch
- id="ocr"
- checked={ocr}
- onCheckedChange={handleOcrChange}
- />
- </div>
- <div className="flex items-center justify-between py-3">
- <div className="flex-1">
- <Label
- htmlFor="picture-descriptions"
- className="text-base font-medium cursor-pointer pb-3"
- >
- Picture Descriptions
- </Label>
- <div className="text-sm text-muted-foreground">
- Adds captions for images. Ingest is slower when enabled.
- </div>
- </div>
- <Switch
- id="picture-descriptions"
- checked={pictureDescriptions}
- onCheckedChange={handlePictureDescriptionsChange}
- />
- </div>
- </div>
- </div>
- </CardContent>
- </Card>
-
- {/* API Keys Section */}
- {(isAuthenticated || isNoAuthMode) && (
- <Card>
- <CardHeader>
- <div className="flex items-center justify-between mb-3">
- <CardTitle className="text-lg">API Keys</CardTitle>
- <Button
- onClick={() => setCreateKeyDialogOpen(true)}
- size="sm"
- >
- <Plus className="h-4 w-4 mr-2" />
- Create Key
- </Button>
- </div>
- <CardDescription>
- API keys allow programmatic access to OpenRAG via the public API.
- Keep your keys secure and never share them publicly.
- </CardDescription>
- </CardHeader>
- <CardContent>
- {apiKeysLoading ? (
- <div className="flex items-center justify-center py-8">
- <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
- </div>
- ) : apiKeysData?.keys && apiKeysData.keys.length > 0 ? (
- <div className="border rounded-lg overflow-hidden">
- <table className="w-full">
- <thead className="bg-muted/50">
- <tr>
- <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">
- Name
- </th>
- <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">
- Key
- </th>
- <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">
- Created
- </th>
- <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">
- Last Used
- </th>
- <th className="text-right text-sm font-medium text-muted-foreground px-4 py-3">
- Actions
- </th>
- </tr>
- </thead>
- <tbody>
- {apiKeysData.keys.map((key) => (
- <tr key={key.key_id} className="border-t">
- <td className="px-4 py-3 text-sm font-medium">
- {key.name}
- </td>
- <td className="px-4 py-3">
- <code className="text-sm bg-muted px-2 py-1 rounded">
- {key.key_prefix}...
- </code>
- </td>
- <td className="px-4 py-3 text-sm text-muted-foreground">
- {formatDate(key.created_at)}
- </td>
- <td className="px-4 py-3 text-sm text-muted-foreground">
- {formatDate(key.last_used_at)}
- </td>
- <td className="px-4 py-3 text-right">
- <ConfirmationDialog
- trigger={
- <Button
- variant="ghost"
- size="sm"
- className="text-destructive hover:text-destructive hover:bg-destructive/10"
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- }
- title="Revoke API Key"
- description={
- <>
- Are you sure you want to revoke the API key{" "}
- <strong>{key.name}</strong>? This action cannot
- be undone and any applications using this key
- will stop working.
- </>
- }
- confirmText="Revoke"
- variant="destructive"
- onConfirm={(closeDialog) => {
- handleRevokeApiKey(key.key_id);
- closeDialog();
- }}
- />
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- ) : (
- <div className="text-center py-8">
- <Key className="h-12 w-12 mx-auto text-muted-foreground/50 mb-4" />
- <p className="text-muted-foreground mb-4">
- No API keys yet. Create one to get started.
- </p>
- <Button
- variant="outline"
- onClick={() => setCreateKeyDialogOpen(true)}
- size="sm"
- >
- <Plus className="h-4 w-4 mr-2" />
- Create your first API key
- </Button>
- </div>
- )}
- </CardContent>
- </Card>
- )}
-
- {/* Create API Key Dialog */}
- <Dialog open={createKeyDialogOpen} onOpenChange={setCreateKeyDialogOpen}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Create API Key</DialogTitle>
- <DialogDescription>
- Give your API key a name to help you identify it later.
- </DialogDescription>
- </DialogHeader>
- <div className="py-4">
- <LabelWrapper label="Name" id="api-key-name">
- <Input
- id="api-key-name"
- placeholder="e.g., Production App, Development"
- value={newKeyName}
- onChange={(e) => setNewKeyName(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- handleCreateApiKey();
- }
- }}
- />
- </LabelWrapper>
- </div>
- <DialogFooter>
- <Button
- variant="ghost"
- onClick={() => {
- setCreateKeyDialogOpen(false);
- setNewKeyName("");
- }}
- size="sm"
- >
- Cancel
- </Button>
- <Button
- onClick={handleCreateApiKey}
- disabled={createApiKeyMutation.isPending || !newKeyName.trim()}
- size="sm"
- >
- {createApiKeyMutation.isPending ? (
- <>
- <Loader2 className="h-4 w-4 mr-2 animate-spin" />
- Creating...
- </>
- ) : (
- "Create Key"
- )}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
-
- {/* Show Created API Key Dialog */}
- <Dialog
- open={showKeyDialogOpen}
- onOpenChange={(open) => {
- setShowKeyDialogOpen(open);
- if (!open) {
- setNewlyCreatedKey(null);
- }
- }}
- >
- <DialogContent>
- <DialogHeader>
- <DialogTitle>API Key Created</DialogTitle>
- <DialogDescription>
- Copy your API key now. You won&apos;t be able to see it again.
- </DialogDescription>
- </DialogHeader>
- <div className="py-4">
- <div className="bg-muted rounded-lg p-4 font-mono text-sm break-all">
- {newlyCreatedKey}
- </div>
- </div>
- <DialogFooter>
- <Button variant="ghost" onClick={() => setShowKeyDialogOpen(false)} size="sm">
- Close
- </Button>
- <Button onClick={handleCopyApiKey} size="sm">
- <Copy className="h-4 w-4 mr-2" />
- Copy Key
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
+ const { isAuthenticated, isNoAuthMode } = useAuth();
+ const { addTask, tasks } = useTask();
+ const searchParams = useSearchParams();
+ const router = useRouter();
+
+ // Check if we should auto-open the LLM model selector
+ const focusLlmModel = searchParams.get("focusLlmModel") === "true";
+ // Use a trigger state that changes each time we detect the query param
+ const [openLlmSelector, setOpenLlmSelector] = useState(false);
+
+ // API Keys state
+ const [createKeyDialogOpen, setCreateKeyDialogOpen] = useState(false);
+ const [newKeyName, setNewKeyName] = useState("");
+ const [newlyCreatedKey, setNewlyCreatedKey] = useState<string | null>(null);
+ const [showKeyDialogOpen, setShowKeyDialogOpen] = useState(false);
+
+ // Only keep systemPrompt state since it needs manual save button
+ const [systemPrompt, setSystemPrompt] = useState<string>("");
+ const [chunkSize, setChunkSize] = useState<number>(1024);
+ const [chunkOverlap, setChunkOverlap] = useState<number>(50);
+ const [tableStructure, setTableStructure] = useState<boolean>(true);
+ const [ocr, setOcr] = useState<boolean>(false);
+ const [pictureDescriptions, setPictureDescriptions] =
+ useState<boolean>(false);
+
+ // Fetch settings using React Query
+ const { data: settings = {} } = useGetSettingsQuery({
+ enabled: isAuthenticated || isNoAuthMode,
+ });
+
+ // Fetch API keys
+ const { data: apiKeysData, isLoading: apiKeysLoading } = useGetApiKeysQuery({
+ enabled: isAuthenticated || isNoAuthMode,
+ });
+
+ // API key mutations
+ const createApiKeyMutation = useCreateApiKeyMutation({
+ onSuccess: (data) => {
+ setNewlyCreatedKey(data.api_key);
+ setCreateKeyDialogOpen(false);
+ setShowKeyDialogOpen(true);
+ setNewKeyName("");
+ toast.success("API key created");
+ },
+ onError: (error) => {
+ toast.error("Failed to create API key", { description: error.message });
+ },
+ });
+
+ const revokeApiKeyMutation = useRevokeApiKeyMutation({
+ onSuccess: () => {
+ toast.success("API key revoked");
+ },
+ onError: (error) => {
+ toast.error("Failed to revoke API key", { description: error.message });
+ },
+ });
+
+ // Fetch models for each provider
+ const { data: openaiModels, isLoading: openaiLoading } =
+ useGetOpenAIModelsQuery(
+ { apiKey: "" },
+ { enabled: settings?.providers?.openai?.configured === true },
+ );
+
+ const { data: anthropicModels, isLoading: anthropicLoading } =
+ useGetAnthropicModelsQuery(
+ { apiKey: "" },
+ { enabled: settings?.providers?.anthropic?.configured === true },
+ );
+
+ const { data: ollamaModels, isLoading: ollamaLoading } =
+ useGetOllamaModelsQuery(
+ { endpoint: settings?.providers?.ollama?.endpoint },
+ {
+ enabled:
+ settings?.providers?.ollama?.configured === true &&
+ !!settings?.providers?.ollama?.endpoint,
+ },
+ );
+
+ const { data: watsonxModels, isLoading: watsonxLoading } =
+ useGetIBMModelsQuery(
+ {
+ endpoint: settings?.providers?.watsonx?.endpoint,
+ apiKey: "",
+ projectId: settings?.providers?.watsonx?.project_id,
+ },
+ {
+ enabled:
+ settings?.providers?.watsonx?.configured === true &&
+ !!settings?.providers?.watsonx?.endpoint &&
+ !!settings?.providers?.watsonx?.project_id,
+ },
+ );
+
+ // Build grouped LLM model options from all configured providers
+ const groupedLlmModels = [
+ {
+ group: "OpenAI",
+ provider: "openai",
+ icon: getModelLogo("", "openai"),
+ models: openaiModels?.language_models || [],
+ configured: settings.providers?.openai?.configured === true,
+ },
+ {
+ group: "Anthropic",
+ provider: "anthropic",
+ icon: getModelLogo("", "anthropic"),
+ models: anthropicModels?.language_models || [],
+ configured: settings.providers?.anthropic?.configured === true,
+ },
+ {
+ group: "Ollama",
+ provider: "ollama",
+ icon: getModelLogo("", "ollama"),
+ models: ollamaModels?.language_models || [],
+ configured: settings.providers?.ollama?.configured === true,
+ },
+ {
+ group: "IBM watsonx.ai",
+ provider: "watsonx",
+ icon: getModelLogo("", "watsonx"),
+ models: watsonxModels?.language_models || [],
+ configured: settings.providers?.watsonx?.configured === true,
+ },
+ ]
+ .filter((provider) => provider.configured)
+ .map((provider) => ({
+ group: provider.group,
+ icon: provider.icon,
+ options: provider.models.map((model) => ({
+ ...model,
+ provider: provider.provider,
+ })),
+ }));
+
+ // Build grouped embedding model options from all configured providers (excluding Anthropic)
+ const groupedEmbeddingModels = [
+ {
+ group: "OpenAI",
+ provider: "openai",
+ icon: getModelLogo("", "openai"),
+ models: openaiModels?.embedding_models || [],
+ configured: settings.providers?.openai?.configured === true,
+ },
+ {
+ group: "Ollama",
+ provider: "ollama",
+ icon: getModelLogo("", "ollama"),
+ models: ollamaModels?.embedding_models || [],
+ configured: settings.providers?.ollama?.configured === true,
+ },
+ {
+ group: "IBM watsonx.ai",
+ provider: "watsonx",
+ icon: getModelLogo("", "watsonx"),
+ models: watsonxModels?.embedding_models || [],
+ configured: settings.providers?.watsonx?.configured === true,
+ },
+ ]
+ .filter((provider) => provider.configured)
+ .map((provider) => ({
+ group: provider.group,
+ icon: provider.icon,
+ options: provider.models.map((model) => ({
+ ...model,
+ provider: provider.provider,
+ })),
+ }));
+
+ const isLoadingAnyLlmModels =
+ openaiLoading || anthropicLoading || ollamaLoading || watsonxLoading;
+ const isLoadingAnyEmbeddingModels =
+ openaiLoading || ollamaLoading || watsonxLoading;
+
+ // Mutations
+ const updateSettingsMutation = useUpdateSettingsMutation({
+ onSuccess: () => {
+ toast.success("Settings updated successfully");
+ },
+ onError: (error) => {
+ toast.error("Failed to update settings", {
+ description: error.message,
+ });
+ },
+ });
+
+ // Debounced update function
+ const debouncedUpdate = useDebounce(
+ (variables: Parameters<typeof updateSettingsMutation.mutate>[0]) => {
+ updateSettingsMutation.mutate(variables);
+ },
+ 500,
+ );
+
+ // Sync system prompt state with settings data
+ useEffect(() => {
+ if (settings.agent?.system_prompt) {
+ setSystemPrompt(settings.agent.system_prompt);
+ }
+ }, [settings.agent?.system_prompt]);
+
+ // Sync chunk size and overlap state with settings data
+ useEffect(() => {
+ if (settings.knowledge?.chunk_size) {
+ setChunkSize(settings.knowledge.chunk_size);
+ }
+ }, [settings.knowledge?.chunk_size]);
+
+ useEffect(() => {
+ if (settings.knowledge?.chunk_overlap) {
+ setChunkOverlap(settings.knowledge.chunk_overlap);
+ }
+ }, [settings.knowledge?.chunk_overlap]);
+
+ // Sync docling settings with settings data
+ useEffect(() => {
+ if (settings.knowledge?.table_structure !== undefined) {
+ setTableStructure(settings.knowledge.table_structure);
+ }
+ }, [settings.knowledge?.table_structure]);
+
+ useEffect(() => {
+ if (settings.knowledge?.ocr !== undefined) {
+ setOcr(settings.knowledge.ocr);
+ }
+ }, [settings.knowledge?.ocr]);
+
+ useEffect(() => {
+ if (settings.knowledge?.picture_descriptions !== undefined) {
+ setPictureDescriptions(settings.knowledge.picture_descriptions);
+ }
+ }, [settings.knowledge?.picture_descriptions]);
+
+ // Handle auto-focus on LLM model selector when coming from provider setup
+ useEffect(() => {
+ if (focusLlmModel) {
+ // Trigger the selector to open
+ setOpenLlmSelector(true);
+
+ // Scroll to the agent card
+ const agentCard = document.getElementById("agent-card");
+ if (agentCard) {
+ agentCard.scrollIntoView({ behavior: "smooth", block: "start" });
+ }
+
+ // Clear the query parameter
+ const newSearchParams = new URLSearchParams(searchParams.toString());
+ newSearchParams.delete("focusLlmModel");
+ router.replace(`/settings?${newSearchParams.toString()}`, {
+ scroll: false,
+ });
+
+ // Reset the trigger after a brief delay so it can be triggered again
+ setTimeout(() => setOpenLlmSelector(false), 100);
+ }
+ }, [focusLlmModel, searchParams, router]);
+
+ // Update model selection immediately (also updates provider)
+ const handleModelChange = (newModel: string, provider?: string) => {
+ if (newModel && provider) {
+ updateSettingsMutation.mutate({
+ llm_model: newModel,
+ llm_provider: provider,
+ });
+ } else if (newModel) {
+ updateSettingsMutation.mutate({ llm_model: newModel });
+ }
+ };
+
+ // Update system prompt with save button
+ const handleSystemPromptSave = () => {
+ updateSettingsMutation.mutate({ system_prompt: systemPrompt });
+ };
+
+ // Update embedding model selection immediately (also updates provider)
+ const handleEmbeddingModelChange = (newModel: string, provider?: string) => {
+ if (newModel && provider) {
+ updateSettingsMutation.mutate({
+ embedding_model: newModel,
+ embedding_provider: provider,
+ });
+ } else if (newModel) {
+ updateSettingsMutation.mutate({ embedding_model: newModel });
+ }
+ };
+
+ // Update chunk size setting with debounce
+ const handleChunkSizeChange = (value: string) => {
+ const numValue = Math.max(0, parseInt(value) || 0);
+ setChunkSize(numValue);
+ debouncedUpdate({ chunk_size: numValue });
+ };
+
+ // Update chunk overlap setting with debounce
+ const handleChunkOverlapChange = (value: string) => {
+ const numValue = Math.max(0, parseInt(value) || 0);
+ setChunkOverlap(numValue);
+ debouncedUpdate({ chunk_overlap: numValue });
+ };
+
+ // Update docling settings
+ const handleTableStructureChange = (checked: boolean) => {
+ setTableStructure(checked);
+ updateSettingsMutation.mutate({ table_structure: checked });
+ };
+
+ const handleOcrChange = (checked: boolean) => {
+ setOcr(checked);
+ updateSettingsMutation.mutate({ ocr: checked });
+ };
+
+ const handlePictureDescriptionsChange = (checked: boolean) => {
+ setPictureDescriptions(checked);
+ updateSettingsMutation.mutate({ picture_descriptions: checked });
+ };
+
+ // API Keys handlers
+ const handleCreateApiKey = () => {
+ if (!newKeyName.trim()) {
+ toast.error("Please enter a name for the API key");
+ return;
+ }
+ createApiKeyMutation.mutate({ name: newKeyName.trim() });
+ };
+
+ const handleRevokeApiKey = (keyId: string) => {
+ revokeApiKeyMutation.mutate({ key_id: keyId });
+ };
+
+ const handleCopyApiKey = async () => {
+ if (newlyCreatedKey) {
+ await navigator.clipboard.writeText(newlyCreatedKey);
+ toast.success("API key copied to clipboard");
+ }
+ };
+
+ const formatDate = (dateString: string | null) => {
+ if (!dateString) return "Never";
+ const date = new Date(dateString);
+ return date.toLocaleDateString(undefined, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ });
+ };
+
+ // Check connector status on mount and when returning from OAuth
+ useEffect(() => {
+ if (searchParams.get("oauth_success") === "true") {
+ const url = new URL(window.location.href);
+ url.searchParams.delete("oauth_success");
+ window.history.replaceState({}, "", url.toString());
+ }
+ }, [searchParams]);
+
+ // Track previous tasks to detect new completions
+ const [prevTasks, setPrevTasks] = useState<typeof tasks>([]);
+
+ // Watch for task completions and refresh stats
+ useEffect(() => {
+ // Find newly completed tasks by comparing with previous state
+ const newlyCompletedTasks = tasks.filter((task) => {
+ const wasCompleted =
+ prevTasks.find((prev) => prev.task_id === task.task_id)?.status ===
+ "completed";
+ return task.status === "completed" && !wasCompleted;
+ });
+
+ if (newlyCompletedTasks.length > 0) {
+ // Task completed - could refresh data here if needed
+ const timeoutId = setTimeout(() => {
+ // Stats refresh removed
+ }, 1000);
+
+ // Update previous tasks state
+ setPrevTasks(tasks);
+
+ return () => clearTimeout(timeoutId);
+ } else {
+ // Always update previous tasks state
+ setPrevTasks(tasks);
+ }
+ }, [tasks, prevTasks]);
+
+ const handleEditInLangflow = (
+ flowType: "chat" | "ingest",
+ closeDialog: () => void,
+ ) => {
+ // Select the appropriate flow ID and edit URL based on flow type
+ const targetFlowId =
+ flowType === "ingest" ? settings.ingest_flow_id : settings.flow_id;
+ const editUrl =
+ flowType === "ingest"
+ ? settings.langflow_ingest_edit_url
+ : settings.langflow_edit_url;
+
+ const derivedFromWindow =
+ typeof window !== "undefined"
+ ? `${window.location.protocol}//${window.location.hostname}:7860`
+ : "";
+ const base = (
+ settings.langflow_public_url ||
+ derivedFromWindow ||
+ "http://localhost:7860"
+ ).replace(/\/$/, "");
+ const computed = targetFlowId ? `${base}/flow/${targetFlowId}` : base;
+
+ const url = editUrl || computed;
+
+ window.open(url, "_blank");
+ closeDialog(); // Close immediately after opening Langflow
+ };
+
+ const handleRestoreRetrievalFlow = (closeDialog: () => void) => {
+ fetch(`/api/reset-flow/retrieval`, {
+ method: "POST",
+ })
+ .then((response) => {
+ if (response.ok) {
+ return response.json();
+ }
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ })
+ .then(() => {
+ // Flow restoration is complete - backend already updated flow with current provider/model
+ // Just reset the UI form value for system prompt
+ setSystemPrompt(DEFAULT_AGENT_SETTINGS.system_prompt);
+ closeDialog(); // Close after successful completion
+ })
+ .catch((error) => {
+ console.error("Error restoring retrieval flow:", error);
+ closeDialog(); // Close even on error (could show error toast instead)
+ });
+ };
+
+ const handleRestoreIngestFlow = (closeDialog: () => void) => {
+ fetch(`/api/reset-flow/ingest`, {
+ method: "POST",
+ })
+ .then((response) => {
+ if (response.ok) {
+ return response.json();
+ }
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ })
+ .then(() => {
+ // Only reset form values if the API call was successful
+ setChunkSize(DEFAULT_KNOWLEDGE_SETTINGS.chunk_size);
+ setChunkOverlap(DEFAULT_KNOWLEDGE_SETTINGS.chunk_overlap);
+ setTableStructure(false);
+ setOcr(false);
+ setPictureDescriptions(false);
+ closeDialog(); // Close after successful completion
+ })
+ .catch((error) => {
+ console.error("Error restoring ingest flow:", error);
+ closeDialog(); // Close even on error (could show error toast instead)
+ });
+ };
+
+ return (
+ <div className="space-y-8 pb-6">
+ {/* Connectors Section */}
+ <div className="space-y-6">
+ <div>
+ <h2 className="text-lg font-semibold tracking-tight mb-2">
+ Cloud Connectors
+ </h2>
+ </div>
+
+ {/* Conditional Sync Settings or No-Auth Message */}
+ {
+ isNoAuthMode ? (
+ <Card className="border-accent-amber-foreground">
+ <CardHeader>
+ <CardTitle className="text-lg">
+ Cloud connectors require authentication
+ </CardTitle>
+ <CardDescription className="text-sm">
+ Add the Google OAuth variables below to your <code>.env</code>{" "}
+ then restart the OpenRAG containers.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="bg-muted rounded-md p-4 font-mono text-sm">
+ <div className="text-muted-foreground">
+ <div>
+ <span className="mr-3 text-placeholder-foreground">
+ 27
+ </span>
+ <span># Google OAuth</span>
+ </div>
+ <div>
+ <span className="mr-3 text-placeholder-foreground">
+ 28
+ </span>
+ <span># Create credentials here:</span>
+ </div>
+ <div>
+ <span className="mr-3 text-placeholder-foreground">
+ 29
+ </span>
+ <span>
+ # https://console.cloud.google.com/apis/credentials
+ </span>
+ </div>
+ </div>
+ <div>
+ <span className="mr-3 text-placeholder-foreground">30</span>
+ <span>GOOGLE_OAUTH_CLIENT_ID=</span>
+ </div>
+ <div>
+ <span className="mr-3 text-placeholder-foreground">31</span>
+ <span>GOOGLE_OAUTH_CLIENT_SECRET=</span>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ ) : null
+ // <div className="flex items-center justify-between py-4">
+ // <div>
+ // <h3 className="text-lg font-medium">Sync Settings</h3>
+ // <p className="text-sm text-muted-foreground">
+ // Configure how many files to sync when manually triggering a sync
+ // </p>
+ // </div>
+ // <div className="flex items-center gap-4">
+ // <div className="flex items-center space-x-2">
+ // <Checkbox
+ // id="syncAllFiles"
+ // checked={syncAllFiles}
+ // onCheckedChange={checked => {
+ // setSyncAllFiles(!!checked);
+ // if (checked) {
+ // setMaxFiles(0);
+ // } else {
+ // setMaxFiles(10);
+ // }
+ // }}
+ // />
+ // <Label
+ // htmlFor="syncAllFiles"
+ // className="font-medium whitespace-nowrap"
+ // >
+ // Sync all files
+ // </Label>
+ // </div>
+ // <Label
+ // htmlFor="maxFiles"
+ // className="font-medium whitespace-nowrap"
+ // >
+ // Max files per sync:
+ // </Label>
+ // <div className="relative">
+ // <Input
+ // id="maxFiles"
+ // type="number"
+ // value={syncAllFiles ? 0 : maxFiles}
+ // onChange={e => setMaxFiles(parseInt(e.target.value) || 10)}
+ // disabled={syncAllFiles}
+ // className="w-16 min-w-16 max-w-16 flex-shrink-0 disabled:opacity-50 disabled:cursor-not-allowed"
+ // min="1"
+ // max="100"
+ // title={
+ // syncAllFiles
+ // ? "Disabled when 'Sync all files' is checked"
+ // : "Leave blank or set to 0 for unlimited"
+ // }
+ // />
+ // </div>
+ // </div>
+ // </div>
+ }
+ {/* Connectors Grid */}
+ <ConnectorCards />
+ </div>
+
+ {/* Model Providers Section */}
+ <div className="space-y-6">
+ <div>
+ <h2 className="text-lg font-semibold tracking-tight mb-2">
+ Model Providers
+ </h2>
+ </div>
+ <ModelProviders />
+ </div>
+
+ {/* Agent Behavior Section */}
+ <Card id="agent-card">
+ <CardHeader>
+ <div className="flex items-center justify-between mb-3">
+ <CardTitle className="text-lg">Agent</CardTitle>
+ <div className="flex gap-2">
+ <ConfirmationDialog
+ trigger={
+ <Button ignoreTitleCase={true} variant="outline">
+ Restore flow
+ </Button>
+ }
+ title="Restore default Agent flow"
+ description="This restores defaults and discards all custom settings and overrides. This can’t be undone."
+ confirmText="Restore"
+ variant="destructive"
+ onConfirm={handleRestoreRetrievalFlow}
+ />
+ <ConfirmationDialog
+ trigger={
+ <Button>
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="22"
+ viewBox="0 0 24 22"
+ className="h-4 w-4 mr-2"
+ aria-label="Langflow icon"
+ >
+ <title>Langflow icon</title>
+ <path
+ fill="currentColor"
+ d="M13.0486 0.462158H9.75399C9.44371 0.462158 9.14614 0.586082 8.92674 0.806667L4.03751 5.72232C3.81811 5.9429 3.52054 6.06682 3.21026 6.06682H1.16992C0.511975 6.06682 -0.0165756 6.61212 0.000397655 7.2734L0.0515933 9.26798C0.0679586 9.90556 0.586745 10.4139 1.22111 10.4139H3.59097C3.90124 10.4139 4.19881 10.2899 4.41821 10.0694L9.34823 5.11269C9.56763 4.89211 9.8652 4.76818 10.1755 4.76818H13.0486C13.6947 4.76818 14.2185 4.24157 14.2185 3.59195V1.63839C14.2185 0.988773 13.6947 0.462158 13.0486 0.462158Z"
+ ></path>
+ <path
+ fill="currentColor"
+ d="M19.5355 11.5862H22.8301C23.4762 11.5862 24 12.1128 24 12.7624V14.716C24 15.3656 23.4762 15.8922 22.8301 15.8922H19.957C19.6467 15.8922 19.3491 16.0161 19.1297 16.2367L14.1997 21.1934C13.9803 21.414 13.6827 21.5379 13.3725 21.5379H11.0026C10.3682 21.5379 9.84945 21.0296 9.83309 20.392L9.78189 18.3974C9.76492 17.7361 10.2935 17.1908 10.9514 17.1908H12.9918C13.302 17.1908 13.5996 17.0669 13.819 16.8463L18.7082 11.9307C18.9276 11.7101 19.2252 11.5862 19.5355 11.5862Z"
+ ></path>
+ <path
+ fill="currentColor"
+ d="M19.5355 2.9796L22.8301 2.9796C23.4762 2.9796 24 3.50622 24 4.15583V6.1094C24 6.75901 23.4762 7.28563 22.8301 7.28563H19.957C19.6467 7.28563 19.3491 7.40955 19.1297 7.63014L14.1997 12.5868C13.9803 12.8074 13.6827 12.9313 13.3725 12.9313H10.493C10.1913 12.9313 9.90126 13.0485 9.68346 13.2583L4.14867 18.5917C3.93087 18.8016 3.64085 18.9187 3.33917 18.9187H1.32174C0.675616 18.9187 0.151832 18.3921 0.151832 17.7425V15.7343C0.151832 15.0846 0.675616 14.558 1.32174 14.558H3.32468C3.63496 14.558 3.93253 14.4341 4.15193 14.2135L9.40827 8.92878C9.62767 8.70819 9.92524 8.58427 10.2355 8.58427H12.9918C13.302 8.58427 13.5996 8.46034 13.819 8.23976L18.7082 3.32411C18.9276 3.10353 19.2252 2.9796 19.5355 2.9796Z"
+ ></path>
+ </svg>
+ Edit in Langflow
+ </Button>
+ }
+ title="Edit Agent flow in Langflow"
+ description={
+ <>
+ <p className="mb-2">
+ You&apos;re entering Langflow. You can edit the{" "}
+ <b>Agent flow</b> and other underlying flows. Manual
+ changes to components, wiring, or I/O can break this
+ experience.
+ </p>
+ <p className="mb-2">
+ To enable editing, you need to unlock the flow by clicking
+ on its name and disabling the <b>Lock flow</b> option.
+ </p>
+ <p>You can restore this flow from Settings.</p>
+ </>
+ }
+ confirmText="Proceed"
+ confirmIcon={<ArrowUpRight />}
+ onConfirm={(closeDialog) =>
+ handleEditInLangflow("chat", closeDialog)
+ }
+ variant="warning"
+ />
+ </div>
+ </div>
+ <CardDescription>
+ This Agent retrieves from your knowledge and generates chat
+ responses. Edit in Langflow for full control.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-6">
+ <div className="space-y-2">
+ <LabelWrapper
+ label="Language model"
+ helperText="Model used for chat"
+ id="language-model"
+ required={true}
+ >
+ <ModelSelector
+ groupedOptions={groupedLlmModels}
+ noOptionsPlaceholder={
+ isLoadingAnyLlmModels
+ ? "Loading models..."
+ : "No language models detected. Configure a provider first."
+ }
+ value={settings.agent?.llm_model || ""}
+ onValueChange={handleModelChange}
+ defaultOpen={openLlmSelector}
+ />
+ </LabelWrapper>
+ </div>
+ <div className="space-y-2">
+ <LabelWrapper label="Agent Instructions" id="system-prompt">
+ <Textarea
+ id="system-prompt"
+ placeholder="Enter your agent instructions here..."
+ value={systemPrompt}
+ onChange={(e) => setSystemPrompt(e.target.value)}
+ rows={6}
+ className={`resize-none ${
+ systemPrompt.length > MAX_SYSTEM_PROMPT_CHARS
+ ? "!border-destructive focus:border-destructive"
+ : ""
+ }`}
+ />
+ </LabelWrapper>
+ <span
+ className={`text-xs ${
+ systemPrompt.length > MAX_SYSTEM_PROMPT_CHARS
+ ? "text-destructive"
+ : "text-muted-foreground"
+ }`}
+ >
+ {systemPrompt.length}/{MAX_SYSTEM_PROMPT_CHARS} characters
+ </span>
+ </div>
+ <div className="flex justify-end pt-2">
+ <Button
+ onClick={handleSystemPromptSave}
+ disabled={
+ updateSettingsMutation.isPending ||
+ systemPrompt.length > MAX_SYSTEM_PROMPT_CHARS
+ }
+ className="min-w-[120px]"
+ size="sm"
+ variant="outline"
+ >
+ {updateSettingsMutation.isPending ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ Saving...
+ </>
+ ) : (
+ "Save Agent Instructions"
+ )}
+ </Button>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+
+ {/* Knowledge Ingest Section */}
+ <Card>
+ <CardHeader>
+ <div className="flex items-center justify-between mb-3">
+ <CardTitle className="text-lg">Knowledge Ingest</CardTitle>
+ <div className="flex gap-2">
+ <ConfirmationDialog
+ trigger={
+ <Button ignoreTitleCase={true} variant="outline">
+ Restore flow
+ </Button>
+ }
+ title="Restore default Ingest flow"
+ description="This restores defaults and discards all custom settings and overrides. This can't be undone."
+ confirmText="Restore"
+ variant="destructive"
+ onConfirm={handleRestoreIngestFlow}
+ />
+ <ConfirmationDialog
+ trigger={
+ <Button>
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="22"
+ viewBox="0 0 24 22"
+ className="h-4 w-4 mr-2"
+ aria-label="Langflow icon"
+ >
+ <title>Langflow icon</title>
+ <path
+ fill="currentColor"
+ d="M13.0486 0.462158H9.75399C9.44371 0.462158 9.14614 0.586082 8.92674 0.806667L4.03751 5.72232C3.81811 5.9429 3.52054 6.06682 3.21026 6.06682H1.16992C0.511975 6.06682 -0.0165756 6.61212 0.000397655 7.2734L0.0515933 9.26798C0.0679586 9.90556 0.586745 10.4139 1.22111 10.4139H3.59097C3.90124 10.4139 4.19881 10.2899 4.41821 10.0694L9.34823 5.11269C9.56763 4.89211 9.8652 4.76818 10.1755 4.76818H13.0486C13.6947 4.76818 14.2185 4.24157 14.2185 3.59195V1.63839C14.2185 0.988773 13.6947 0.462158 13.0486 0.462158Z"
+ ></path>
+ <path
+ fill="currentColor"
+ d="M19.5355 11.5862H22.8301C23.4762 11.5862 24 12.1128 24 12.7624V14.716C24 15.3656 23.4762 15.8922 22.8301 15.8922H19.957C19.6467 15.8922 19.3491 16.0161 19.1297 16.2367L14.1997 21.1934C13.9803 21.414 13.6827 21.5379 13.3725 21.5379H11.0026C10.3682 21.5379 9.84945 21.0296 9.83309 20.392L9.78189 18.3974C9.76492 17.7361 10.2935 17.1908 10.9514 17.1908H12.9918C13.302 17.1908 13.5996 17.0669 13.819 16.8463L18.7082 11.9307C18.9276 11.7101 19.2252 11.5862 19.5355 11.5862Z"
+ ></path>
+ <path
+ fill="currentColor"
+ d="M19.5355 2.9796L22.8301 2.9796C23.4762 2.9796 24 3.50622 24 4.15583V6.1094C24 6.75901 23.4762 7.28563 22.8301 7.28563H19.957C19.6467 7.28563 19.3491 7.40955 19.1297 7.63014L14.1997 12.5868C13.9803 12.8074 13.6827 12.9313 13.3725 12.9313H10.493C10.1913 12.9313 9.90126 13.0485 9.68346 13.2583L4.14867 18.5917C3.93087 18.8016 3.64085 18.9187 3.33917 18.9187H1.32174C0.675616 18.9187 0.151832 18.3921 0.151832 17.7425V15.7343C0.151832 15.0846 0.675616 14.558 1.32174 14.558H3.32468C3.63496 14.558 3.93253 14.4341 4.15193 14.2135L9.40827 8.92878C9.62767 8.70819 9.92524 8.58427 10.2355 8.58427H12.9918C13.302 8.58427 13.5996 8.46034 13.819 8.23976L18.7082 3.32411C18.9276 3.10353 19.2252 2.9796 19.5355 2.9796Z"
+ ></path>
+ </svg>
+ Edit in Langflow
+ </Button>
+ }
+ title="Edit Ingest flow in Langflow"
+ description={
+ <>
+ <p className="mb-2">
+ You&apos;re entering Langflow. You can edit the{" "}
+ <b>Ingest flow</b> and other underlying flows. Manual
+ changes to components, wiring, or I/O can break this
+ experience.
+ </p>
+ <p className="mb-2">
+ To enable editing, you need to unlock the flow by clicking
+ on its name and disabling the <b>Lock flow</b> option.
+ </p>
+ <p>You can restore this flow from Settings.</p>
+ </>
+ }
+ confirmText="Proceed"
+ confirmIcon={<ArrowUpRight />}
+ variant="warning"
+ onConfirm={(closeDialog) =>
+ handleEditInLangflow("ingest", closeDialog)
+ }
+ />
+ </div>
+ </div>
+ <CardDescription>
+ Configure how files are ingested and stored for retrieval. Edit in
+ Langflow for full control.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-6">
+ <div className="space-y-2">
+ <LabelWrapper
+ helperText="Model used for knowledge ingest and retrieval"
+ id="embedding-model-select"
+ label="Embedding model"
+ required={true}
+ >
+ <ModelSelector
+ groupedOptions={groupedEmbeddingModels}
+ noOptionsPlaceholder={
+ isLoadingAnyEmbeddingModels
+ ? "Loading models..."
+ : "No embedding models detected. Configure a provider first."
+ }
+ value={settings.knowledge?.embedding_model || ""}
+ onValueChange={handleEmbeddingModelChange}
+ />
+ </LabelWrapper>
+ </div>
+ <div className="grid grid-cols-2 gap-4">
+ <div className="space-y-2">
+ <LabelWrapper id="chunk-size" label="Chunk size">
+ <div className="relative [&:has(input:hover):not(:has(input:focus))_button]:border-muted-foreground [&:has(input:focus)_button]:border-foreground">
+ <Input
+ id="chunk-size"
+ type="number"
+ min="1"
+ value={chunkSize}
+ onChange={(e) => handleChunkSizeChange(e.target.value)}
+ className="w-full pr-20 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ />
+ <div className="absolute inset-y-0 right-0 flex items-center">
+ <span className="text-sm text-placeholder-foreground mr-4 pointer-events-none">
+ characters
+ </span>
+ <div className="flex flex-col">
+ <Button
+ aria-label="Increase value"
+ className="h-5 rounded-l-none rounded-br-none border-input border-b-[0.5px] focus-visible:relative transition-colors"
+ variant="outline"
+ size="iconSm"
+ onClick={() =>
+ handleChunkSizeChange((chunkSize + 1).toString())
+ }
+ >
+ <Plus className="text-muted-foreground" size={8} />
+ </Button>
+ <Button
+ aria-label="Decrease value"
+ className="h-5 rounded-l-none rounded-tr-none border-input border-t-[0.5px] focus-visible:relative transition-colors"
+ variant="outline"
+ size="iconSm"
+ onClick={() =>
+ handleChunkSizeChange((chunkSize - 1).toString())
+ }
+ >
+ <Minus className="text-muted-foreground" size={8} />
+ </Button>
+ </div>
+ </div>
+ </div>
+ </LabelWrapper>
+ </div>
+ <div className="space-y-2">
+ <LabelWrapper id="chunk-overlap" label="Chunk overlap">
+ <div className="relative [&:has(input:hover):not(:has(input:focus))_button]:border-muted-foreground [&:has(input:focus)_button]:border-foreground">
+ <Input
+ id="chunk-overlap"
+ type="number"
+ min="0"
+ value={chunkOverlap}
+ onChange={(e) => handleChunkOverlapChange(e.target.value)}
+ className="w-full pr-20 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ />
+ <div className="absolute inset-y-0 right-0 flex items-center">
+ <span className="text-sm text-placeholder-foreground mr-4 pointer-events-none">
+ characters
+ </span>
+ <div className="flex flex-col">
+ <Button
+ aria-label="Increase value"
+ className="h-5 rounded-l-none rounded-br-none border-input border-b-[0.5px] focus-visible:relative transition-colors"
+ variant="outline"
+ size="iconSm"
+ onClick={() =>
+ handleChunkOverlapChange(
+ (chunkOverlap + 1).toString(),
+ )
+ }
+ >
+ <Plus className="text-muted-foreground" size={8} />
+ </Button>
+ <Button
+ aria-label="Decrease value"
+ className="h-5 rounded-l-none rounded-tr-none border-input border-t-[0.5px] focus-visible:relative transition-colors"
+ variant="outline"
+ size="iconSm"
+ onClick={() =>
+ handleChunkOverlapChange(
+ (chunkOverlap - 1).toString(),
+ )
+ }
+ >
+ <Minus className="text-muted-foreground" size={8} />
+ </Button>
+ </div>
+ </div>
+ </div>
+ </LabelWrapper>
+ </div>
+ </div>
+ <div className="">
+ <div className="flex items-center justify-between py-3 border-b border-border">
+ <div className="flex-1">
+ <Label
+ htmlFor="table-structure"
+ className="text-base font-medium cursor-pointer pb-3"
+ >
+ Table Structure
+ </Label>
+ <div className="text-sm text-muted-foreground">
+ Capture table structure during ingest.
+ </div>
+ </div>
+ <Switch
+ id="table-structure"
+ checked={tableStructure}
+ onCheckedChange={handleTableStructureChange}
+ />
+ </div>
+ <div className="flex items-center justify-between py-3 border-b border-border">
+ <div className="flex-1">
+ <Label
+ htmlFor="ocr"
+ className="text-base font-medium cursor-pointer pb-3"
+ >
+ OCR
+ </Label>
+ <div className="text-sm text-muted-foreground">
+ Extracts text from images/PDFs. Ingest is slower when
+ enabled.
+ </div>
+ </div>
+ <Switch
+ id="ocr"
+ checked={ocr}
+ onCheckedChange={handleOcrChange}
+ />
+ </div>
+ <div className="flex items-center justify-between py-3">
+ <div className="flex-1">
+ <Label
+ htmlFor="picture-descriptions"
+ className="text-base font-medium cursor-pointer pb-3"
+ >
+ Picture Descriptions
+ </Label>
+ <div className="text-sm text-muted-foreground">
+ Adds captions for images. Ingest is slower when enabled.
+ </div>
+ </div>
+ <Switch
+ id="picture-descriptions"
+ checked={pictureDescriptions}
+ onCheckedChange={handlePictureDescriptionsChange}
+ />
+ </div>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+
+ {/* API Keys Section */}
+ {(isAuthenticated || isNoAuthMode) && (
+ <Card>
+ <CardHeader>
+ <div className="flex items-center justify-between mb-3">
+ <CardTitle className="text-lg">API Keys</CardTitle>
+ <Button onClick={() => setCreateKeyDialogOpen(true)} size="sm">
+ <Plus className="h-4 w-4 mr-2" />
+ Create Key
+ </Button>
+ </div>
+ <CardDescription>
+ API keys allow programmatic access to OpenRAG via the public API.
+ Keep your keys secure and never share them publicly.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ {apiKeysLoading ? (
+ <div className="flex items-center justify-center py-8">
+ <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
+ </div>
+ ) : apiKeysData?.keys && apiKeysData.keys.length > 0 ? (
+ <div className="border rounded-lg overflow-hidden">
+ <table className="w-full">
+ <thead className="bg-muted/50">
+ <tr>
+ <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">
+ Name
+ </th>
+ <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">
+ Key
+ </th>
+ <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">
+ Created
+ </th>
+ <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">
+ Last Used
+ </th>
+ <th className="text-right text-sm font-medium text-muted-foreground px-4 py-3">
+ Actions
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {apiKeysData.keys.map((key) => (
+ <tr key={key.key_id} className="border-t">
+ <td className="px-4 py-3 text-sm font-medium">
+ {key.name}
+ </td>
+ <td className="px-4 py-3">
+ <code className="text-sm bg-muted px-2 py-1 rounded">
+ {key.key_prefix}...
+ </code>
+ </td>
+ <td className="px-4 py-3 text-sm text-muted-foreground">
+ {formatDate(key.created_at)}
+ </td>
+ <td className="px-4 py-3 text-sm text-muted-foreground">
+ {formatDate(key.last_used_at)}
+ </td>
+ <td className="px-4 py-3 text-right">
+ <ConfirmationDialog
+ trigger={
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-destructive hover:text-destructive hover:bg-destructive/10"
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ }
+ title="Revoke API Key"
+ description={
+ <>
+ Are you sure you want to revoke the API key{" "}
+ <strong>{key.name}</strong>? This action cannot
+ be undone and any applications using this key
+ will stop working.
+ </>
+ }
+ confirmText="Revoke"
+ variant="destructive"
+ onConfirm={(closeDialog) => {
+ handleRevokeApiKey(key.key_id);
+ closeDialog();
+ }}
+ />
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ ) : (
+ <div className="text-center py-8">
+ <Key className="h-12 w-12 mx-auto text-muted-foreground/50 mb-4" />
+ <p className="text-muted-foreground mb-4">
+ No API keys yet. Create one to get started.
+ </p>
+ <Button
+ variant="outline"
+ onClick={() => setCreateKeyDialogOpen(true)}
+ size="sm"
+ >
+ <Plus className="h-4 w-4 mr-2" />
+ Create your first API key
+ </Button>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ )}
+
+ {/* Create API Key Dialog */}
+ <Dialog open={createKeyDialogOpen} onOpenChange={setCreateKeyDialogOpen}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Create API Key</DialogTitle>
+ <DialogDescription>
+ Give your API key a name to help you identify it later.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="py-4">
+ <LabelWrapper label="Name" id="api-key-name">
+ <Input
+ id="api-key-name"
+ placeholder="e.g., Production App, Development"
+ value={newKeyName}
+ onChange={(e) => setNewKeyName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ handleCreateApiKey();
+ }
+ }}
+ />
+ </LabelWrapper>
+ </div>
+ <DialogFooter>
+ <Button
+ variant="ghost"
+ onClick={() => {
+ setCreateKeyDialogOpen(false);
+ setNewKeyName("");
+ }}
+ size="sm"
+ >
+ Cancel
+ </Button>
+ <Button
+ onClick={handleCreateApiKey}
+ disabled={createApiKeyMutation.isPending || !newKeyName.trim()}
+ size="sm"
+ >
+ {createApiKeyMutation.isPending ? (
+ <>
+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />
+ Creating...
+ </>
+ ) : (
+ "Create Key"
+ )}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ {/* Show Created API Key Dialog */}
+ <Dialog
+ open={showKeyDialogOpen}
+ onOpenChange={(open) => {
+ setShowKeyDialogOpen(open);
+ if (!open) {
+ setNewlyCreatedKey(null);
+ }
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>API Key Created</DialogTitle>
+ <DialogDescription>
+ Copy your API key now. You won&apos;t be able to see it again.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="py-4">
+ <div className="bg-muted rounded-lg p-4 font-mono text-sm break-all">
+ {newlyCreatedKey}
+ </div>
+ </div>
+ <DialogFooter>
+ <Button
+ variant="ghost"
+ onClick={() => setShowKeyDialogOpen(false)}
+ size="sm"
+ >
+ Close
+ </Button>
+ <Button onClick={handleCopyApiKey} size="sm">
+ <Copy className="h-4 w-4 mr-2" />
+ Copy Key
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
}
export default function ProtectedKnowledgeSourcesPage() {
- return (
- <ProtectedRoute>
- <Suspense fallback={<div>Loading knowledge sources...</div>}>
- <KnowledgeSourcesPage />
- </Suspense>
- </ProtectedRoute>
- );
+ return (
+ <ProtectedRoute>
+ <Suspense fallback={<div>Loading knowledge sources...</div>}>
+ <KnowledgeSourcesPage />
+ </Suspense>
+ </ProtectedRoute>
+ );
}
diff --git a/frontend/app/upload/[provider]/page.tsx b/frontend/app/upload/[provider]/page.tsx
index 111d88ac6..bf96214f7 100644
--- a/frontend/app/upload/[provider]/page.tsx
+++ b/frontend/app/upload/[provider]/page.tsx
@@ -3,19 +3,18 @@
import { AlertCircle, ArrowLeft } from "lucide-react";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
+import { useSyncConnector } from "@/app/api/mutations/useSyncConnector";
+import { useGetConnectorsQuery } from "@/app/api/queries/useGetConnectorsQuery";
+import { useGetConnectorTokenQuery } from "@/app/api/queries/useGetConnectorTokenQuery";
import { type CloudFile, UnifiedCloudPicker } from "@/components/cloud-picker";
import type { IngestSettings } from "@/components/cloud-picker/types";
import { Button } from "@/components/ui/button";
-import { useTask } from "@/contexts/task-context";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
-
-import { useSyncConnector } from "@/app/api/mutations/useSyncConnector";
-import { useGetConnectorsQuery } from "@/app/api/queries/useGetConnectorsQuery";
-import { useGetConnectorTokenQuery } from "@/app/api/queries/useGetConnectorTokenQuery";
+import { useTask } from "@/contexts/task-context";
// CloudFile interface is now imported from the unified cloud picker
@@ -25,20 +24,27 @@ export default function UploadProviderPage() {
const provider = params.provider as string;
const { addTask, tasks } = useTask();
- const { data: connectors = [], isLoading: connectorsLoading, error: connectorsError } = useGetConnectorsQuery();
+ const {
+ data: connectors = [],
+ isLoading: connectorsLoading,
+ error: connectorsError,
+ } = useGetConnectorsQuery();
const connector = connectors.find((c) => c.type === provider);
- const { data: tokenData, isLoading: tokenLoading } = useGetConnectorTokenQuery(
- {
- connectorType: provider,
- connectionId: connector?.connectionId,
- resource:
- provider === "sharepoint" ? (connector?.baseUrl as string) : undefined,
- },
- {
- enabled: !!connector && connector.status === "connected",
- },
- );
+ const { data: tokenData, isLoading: tokenLoading } =
+ useGetConnectorTokenQuery(
+ {
+ connectorType: provider,
+ connectionId: connector?.connectionId,
+ resource:
+ provider === "sharepoint"
+ ? (connector?.baseUrl as string)
+ : undefined,
+ },
+ {
+ enabled: !!connector && connector.status === "connected",
+ },
+ );
const syncMutation = useSyncConnector();
@@ -65,7 +71,6 @@ export default function UploadProviderPage() {
? `Cloud provider "${provider}" is not available or configured.`
: null;
-
const handleFileSelected = (files: CloudFile[]) => {
setSelectedFiles(files);
console.log(`Selected ${files.length} item(s) from ${provider}:`, files);
@@ -209,7 +214,8 @@ export default function UploadProviderPage() {
Access Token Required
</h2>
<p className="text-muted-foreground mb-4">
- Unable to get access token for {connector.name}. Try reconnecting your account.
+ Unable to get access token for {connector.name}. Try reconnecting
+ your account.
</p>
<Button onClick={() => router.push("/settings")}>
Reconnect {connector.name}
diff --git a/frontend/biome.json b/frontend/biome.json
index 8cda3adcf..c9c4d59e1 100644
--- a/frontend/biome.json
+++ b/frontend/biome.json
@@ -1,5 +1,5 @@
{
- "$schema": "https://biomejs.dev/schemas/2.1.1/schema.json",
+ "$schema": "https://biomejs.dev/schemas/2.3.5/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
diff --git a/frontend/components/AgGrid/registerAgGridModules.ts b/frontend/components/AgGrid/registerAgGridModules.ts
index 0d8bbb226..486a76ba7 100644
--- a/frontend/components/AgGrid/registerAgGridModules.ts
+++ b/frontend/components/AgGrid/registerAgGridModules.ts
@@ -1,17 +1,17 @@
import {
- ModuleRegistry,
- ValidationModule,
- ColumnAutoSizeModule,
- ColumnApiModule,
- PaginationModule,
CellStyleModule,
- QuickFilterModule,
ClientSideRowModelModule,
- TextFilterModule,
+ ColumnApiModule,
+ ColumnAutoSizeModule,
DateFilterModule,
EventApiModule,
GridStateModule,
+ ModuleRegistry,
+ PaginationModule,
+ QuickFilterModule,
RowSelectionModule,
+ TextFilterModule,
+ ValidationModule,
} from "ag-grid-community";
// Importing necessary modules from ag-grid-community
diff --git a/frontend/components/chat-renderer.tsx b/frontend/components/chat-renderer.tsx
index b717aff98..d427cda63 100644
--- a/frontend/components/chat-renderer.tsx
+++ b/frontend/components/chat-renderer.tsx
@@ -4,13 +4,13 @@ import { useQueryClient } from "@tanstack/react-query";
import { motion } from "framer-motion";
import { usePathname, useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
+import { useUpdateOnboardingStateMutation } from "@/app/api/mutations/useUpdateOnboardingStateMutation";
import {
type ChatConversation,
useGetConversationsQuery,
} from "@/app/api/queries/useGetConversationsQuery";
import { getFilterById } from "@/app/api/queries/useGetFilterByIdQuery";
import type { Settings } from "@/app/api/queries/useGetSettingsQuery";
-import { useUpdateOnboardingStateMutation } from "@/app/api/mutations/useUpdateOnboardingStateMutation";
import { OnboardingContent } from "@/app/onboarding/_components/onboarding-content";
import { ProgressBar } from "@/app/onboarding/_components/progress-bar";
import { AnimatedConditional } from "@/components/animated-conditional";
@@ -96,7 +96,9 @@ export function ChatRenderer({
}
// Check if we already have a default filter set
- const existingDefault = localStorage.getItem("default_conversation_filter_id");
+ const existingDefault = localStorage.getItem(
+ "default_conversation_filter_id",
+ );
if (existingDefault) {
// Try to apply it to context state (don't save to localStorage to avoid overwriting)
@@ -108,7 +110,10 @@ export function ChatRenderer({
return; // Successfully loaded and set, we're done
}
} catch (error) {
- console.error("Failed to load existing default filter, will set new one:", error);
+ console.error(
+ "Failed to load existing default filter, will set new one:",
+ error,
+ );
// Filter doesn't exist anymore, clear it and continue to set a new one
localStorage.removeItem("default_conversation_filter_id");
}
@@ -127,7 +132,6 @@ export function ChatRenderer({
filterId = currentSettings?.onboarding?.openrag_docs_filter_id || null;
}
-
if (filterId) {
// Store this as the default filter for new conversations
localStorage.setItem("default_conversation_filter_id", filterId);
@@ -145,7 +149,11 @@ export function ChatRenderer({
}
}
},
- [setConversationFilter, settings?.onboarding?.user_doc_filter_id, settings?.onboarding?.openrag_docs_filter_id]
+ [
+ setConversationFilter,
+ settings?.onboarding?.user_doc_filter_id,
+ settings?.onboarding?.openrag_docs_filter_id,
+ ],
);
// Note: Current step is now saved to backend via handleStepComplete
@@ -160,13 +168,14 @@ export function ChatRenderer({
// Save step to backend
await updateOnboardingMutation.mutateAsync({ current_step: nextStep });
} else {
-
// IMPORTANT: Refetch settings to get the latest filter IDs that were saved during onboarding
// The filter IDs are saved asynchronously by mutations, so we need fresh data
await queryClient.refetchQueries({ queryKey: ["settings"] });
// Get the fresh settings after refetch
- const freshSettings = queryClient.getQueryData(["settings"]) as Settings | undefined;
+ const freshSettings = queryClient.getQueryData(["settings"]) as
+ | Settings
+ | undefined;
// Store the user document filter as default for new conversations
// Pass fresh settings to ensure we have the latest filter IDs
@@ -237,7 +246,10 @@ export function ChatRenderer({
return (
<>
{/* Sidebar Navigation */}
- <div className="shrink-0 overflow-hidden" style={{ width: SIDEBAR_WIDTH }}>
+ <div
+ className="shrink-0 overflow-hidden"
+ style={{ width: SIDEBAR_WIDTH }}
+ >
<AnimatedConditional
isOpen={showLayout}
slide
@@ -281,7 +293,7 @@ export function ChatRenderer({
className={cn(
"flex h-full w-full max-w-full max-h-full items-center justify-center overflow-y-auto",
!showLayout &&
- "absolute max-h-[calc(100vh-190px)] shadow-[0px_2px_4px_-2px_#0000001A,0px_4px_6px_-1px_#0000001A]",
+ "absolute max-h-[calc(100vh-190px)] shadow-[0px_2px_4px_-2px_#0000001A,0px_4px_6px_-1px_#0000001A]",
showLayout && !isOnChatPage && "bg-background",
)}
>
diff --git a/frontend/components/cloud-picker/file-list.tsx b/frontend/components/cloud-picker/file-list.tsx
index 8cf2b728b..ca3553653 100644
--- a/frontend/components/cloud-picker/file-list.tsx
+++ b/frontend/components/cloud-picker/file-list.tsx
@@ -1,8 +1,8 @@
"use client";
import { Button } from "@/components/ui/button";
-import { CloudFile } from "./types";
import { FileItem } from "./file-item";
+import { CloudFile } from "./types";
interface FileListProps {
provider: string;
diff --git a/frontend/components/cloud-picker/index.ts b/frontend/components/cloud-picker/index.ts
index ef7aa74b8..4b31a1e15 100644
--- a/frontend/components/cloud-picker/index.ts
+++ b/frontend/components/cloud-picker/index.ts
@@ -1,7 +1,7 @@
-export { UnifiedCloudPicker } from "./unified-cloud-picker";
-export { PickerHeader } from "./picker-header";
-export { FileList } from "./file-list";
export { FileItem } from "./file-item";
+export { FileList } from "./file-list";
export { IngestSettings } from "./ingest-settings";
-export * from "./types";
+export { PickerHeader } from "./picker-header";
export * from "./provider-handlers";
+export * from "./types";
+export { UnifiedCloudPicker } from "./unified-cloud-picker";
diff --git a/frontend/components/cloud-picker/onedrive-v8-handler.ts b/frontend/components/cloud-picker/onedrive-v8-handler.ts
index 511a8a655..1227677f2 100644
--- a/frontend/components/cloud-picker/onedrive-v8-handler.ts
+++ b/frontend/components/cloud-picker/onedrive-v8-handler.ts
@@ -4,10 +4,10 @@ import { CloudFile } from "./types";
/**
* OneDrive File Picker v8 Handler for Personal OneDrive
- *
+ *
* Uses Microsoft's File Picker v8 which communicates via postMessage.
* This is for personal Microsoft accounts (consumer OneDrive).
- *
+ *
* Reference: https://learn.microsoft.com/en-us/onedrive/developer/controls/file-pickers/
*/
@@ -72,7 +72,11 @@ interface CloseCommand {
command: "close";
}
-type PickerCommand = PickCommand | AuthenticateCommand | CloseCommand | { command: string };
+type PickerCommand =
+ | PickCommand
+ | AuthenticateCommand
+ | CloseCommand
+ | { command: string };
export class OneDriveV8Handler {
private win: Window | null = null;
@@ -85,12 +89,13 @@ export class OneDriveV8Handler {
private messageListener: ((event: MessageEvent) => void) | null = null;
// OneDrive personal picker URL
- private static readonly ONEDRIVE_PICKER_URL = "https://onedrive.live.com/picker";
+ private static readonly ONEDRIVE_PICKER_URL =
+ "https://onedrive.live.com/picker";
constructor(
accessToken: string,
clientId: string,
- onPickerStateChange?: (isOpen: boolean) => void
+ onPickerStateChange?: (isOpen: boolean) => void,
) {
this.accessToken = accessToken;
this.clientId = clientId;
@@ -125,7 +130,9 @@ export class OneDriveV8Handler {
this.win = window.open("", "OneDrivePicker", "width=1080,height=680");
if (!this.win) {
- console.error("Failed to open OneDrive picker popup - popup may be blocked");
+ console.error(
+ "Failed to open OneDrive picker popup - popup may be blocked",
+ );
this.onPickerStateChange?.(false);
return;
}
@@ -222,7 +229,10 @@ export class OneDriveV8Handler {
if (this.port) {
// Setup port message handler
- this.port.addEventListener("message", this.handlePortMessage.bind(this));
+ this.port.addEventListener(
+ "message",
+ this.handlePortMessage.bind(this),
+ );
this.port.start();
// Activate the picker
@@ -294,7 +304,10 @@ export class OneDriveV8Handler {
}
private handleAuthenticate(id: string, command: AuthenticateCommand): void {
- console.log("OneDrive v8 picker: Auth request for resource:", command.resource);
+ console.log(
+ "OneDrive v8 picker: Auth request for resource:",
+ command.resource,
+ );
// For now, we use the same token for all requests
// The token should be a Microsoft Graph token with Files.Read scope
@@ -317,7 +330,8 @@ export class OneDriveV8Handler {
result: "error",
error: {
code: "unableToObtainToken",
- message: error instanceof Error ? error.message : "Failed to obtain token",
+ message:
+ error instanceof Error ? error.message : "Failed to obtain token",
},
},
});
@@ -338,7 +352,9 @@ export class OneDriveV8Handler {
// Log the download URL for debugging
const downloadUrl = item["@microsoft.graph.downloadUrl"] || "";
- console.log(`OneDrive v8 picker: File "${item.name}" downloadUrl: ${downloadUrl ? "present" : "MISSING"}`);
+ console.log(
+ `OneDrive v8 picker: File "${item.name}" downloadUrl: ${downloadUrl ? "present" : "MISSING"}`,
+ );
return {
id: item.id,
@@ -378,7 +394,10 @@ export class OneDriveV8Handler {
result: "error",
error: {
code: "unusableItem",
- message: error instanceof Error ? error.message : "Failed to process picked items",
+ message:
+ error instanceof Error
+ ? error.message
+ : "Failed to process picked items",
},
},
});
diff --git a/frontend/components/cloud-picker/picker-header.tsx b/frontend/components/cloud-picker/picker-header.tsx
index d907174ec..65738a2ec 100644
--- a/frontend/components/cloud-picker/picker-header.tsx
+++ b/frontend/components/cloud-picker/picker-header.tsx
@@ -1,8 +1,8 @@
"use client";
+import { Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
-import { Plus } from "lucide-react";
import { CloudProvider } from "./types";
interface PickerHeaderProps {
diff --git a/frontend/components/cloud-picker/provider-handlers.ts b/frontend/components/cloud-picker/provider-handlers.ts
index 6b0300fd6..b64808918 100644
--- a/frontend/components/cloud-picker/provider-handlers.ts
+++ b/frontend/components/cloud-picker/provider-handlers.ts
@@ -1,12 +1,12 @@
"use client";
+import { SharePointV8Handler } from "./sharepoint-v8-handler";
import {
CloudFile,
CloudProvider,
GooglePickerData,
GooglePickerDocument,
} from "./types";
-import { SharePointV8Handler } from "./sharepoint-v8-handler";
export class GoogleDriveHandler {
private accessToken: string;
@@ -189,9 +189,10 @@ export class OneDriveHandler {
// For SharePoint, use the SharePoint site URL as endpoint hint
// For OneDrive, use the default OneDrive API endpoint
- const endpointHint = this.provider === "sharepoint" && this.baseUrl
- ? this.baseUrl
- : "api.onedrive.com";
+ const endpointHint =
+ this.provider === "sharepoint" && this.baseUrl
+ ? this.baseUrl
+ : "api.onedrive.com";
window.OneDrive.open({
clientId: this.clientId,
@@ -207,7 +208,7 @@ export class OneDriveHandler {
console.warn("OneDrive picker returned no value");
return;
}
-
+
const newFiles: CloudFile[] =
response.value?.map((item: any) => {
// Extract mimeType from file object or infer from name
@@ -277,9 +278,12 @@ export const createProviderHandler = (
console.log("Provider:", provider);
console.log("Client ID:", clientId);
console.log("Base URL:", baseUrl);
- console.log("Access Token (first 20 chars):", accessToken?.substring(0, 20) + "...");
+ console.log(
+ "Access Token (first 20 chars):",
+ accessToken?.substring(0, 20) + "...",
+ );
console.log("Access Token length:", accessToken?.length);
-
+
switch (provider) {
case "google_drive":
return new GoogleDriveHandler(accessToken, onPickerStateChange);
@@ -293,7 +297,12 @@ export const createProviderHandler = (
throw new Error("Base URL required for SharePoint v8 picker");
}
console.log("Creating SharePointV8Handler with baseUrl:", baseUrl);
- return new SharePointV8Handler(baseUrl, accessToken, clientId, onPickerStateChange);
+ return new SharePointV8Handler(
+ baseUrl,
+ accessToken,
+ clientId,
+ onPickerStateChange,
+ );
case "onedrive":
// Use v7.2 (OneDrive.js) for personal OneDrive - v8 doesn't work for consumer accounts
diff --git a/frontend/components/cloud-picker/sharepoint-v8-handler.ts b/frontend/components/cloud-picker/sharepoint-v8-handler.ts
index 3434a4835..0a868f6b1 100644
--- a/frontend/components/cloud-picker/sharepoint-v8-handler.ts
+++ b/frontend/components/cloud-picker/sharepoint-v8-handler.ts
@@ -4,10 +4,10 @@ import { CloudFile } from "./types";
/**
* SharePoint File Picker v8 Handler
- *
+ *
* Uses Microsoft's newer File Picker v8 which communicates via postMessage
* instead of the deprecated OneDrive.js SDK (v7.2) that has bugs with SharePoint.
- *
+ *
* Reference: https://learn.microsoft.com/en-us/onedrive/developer/controls/file-pickers/
*/
@@ -80,7 +80,11 @@ interface CloseCommand {
command: "close";
}
-type PickerCommand = PickCommand | AuthenticateCommand | CloseCommand | { command: string };
+type PickerCommand =
+ | PickCommand
+ | AuthenticateCommand
+ | CloseCommand
+ | { command: string };
function tryParseUrl(value?: string | null): URL | null {
if (!value) return null;
@@ -122,7 +126,7 @@ export class SharePointV8Handler {
baseUrl: string,
accessToken: string,
clientId: string,
- onPickerStateChange?: (isOpen: boolean) => void
+ onPickerStateChange?: (isOpen: boolean) => void,
) {
this.baseUrl = baseUrl;
this.accessToken = accessToken;
@@ -154,7 +158,10 @@ export class SharePointV8Handler {
console.log("=== SharePoint v8 Picker Diagnostics ===");
console.log("Base URL:", this.baseUrl);
console.log("Client ID:", this.clientId);
- console.log("Token (first 20 chars):", this.accessToken?.substring(0, 20) + "...");
+ console.log(
+ "Token (first 20 chars):",
+ this.accessToken?.substring(0, 20) + "...",
+ );
console.log("Token length:", this.accessToken?.length);
console.log("Window origin:", window.location.origin);
// === DIAGNOSTIC LOGGING END ===
@@ -213,7 +220,7 @@ export class SharePointV8Handler {
});
const pickerUrl = `${this.baseUrl}/_layouts/15/FilePicker.aspx?${queryString}`;
-
+
// === DIAGNOSTIC: Log picker URL and options ===
console.log("Picker URL (full):", pickerUrl);
console.log("Picker options:", JSON.stringify(options, null, 2));
@@ -222,11 +229,15 @@ export class SharePointV8Handler {
// OPTION A FIX: Don't POST the token via form - let picker request it via authenticate command
// The form-posted token might be causing "invalid_client" errors
// Reference: https://learn.microsoft.com/en-us/onedrive/developer/controls/file-pickers/
-
+
// === DIAGNOSTIC: Token delivery method ===
- console.log("Token delivery method: authenticate command only (no form POST)");
- console.log("Token will be provided when picker sends 'authenticate' command");
-
+ console.log(
+ "Token delivery method: authenticate command only (no form POST)",
+ );
+ console.log(
+ "Token will be provided when picker sends 'authenticate' command",
+ );
+
// Use GET request instead of POST with token
// Simply navigate to the picker URL - token will be provided via messaging
this.win.location.href = pickerUrl;
@@ -251,23 +262,32 @@ export class SharePointV8Handler {
private handleWindowMessage(event: MessageEvent): void {
// === DIAGNOSTIC: Log all messages from picker window (before filtering) ===
if (event.source === this.win) {
- console.log("SharePoint v8 picker: Window message received:", event.data?.type || "unknown");
+ console.log(
+ "SharePoint v8 picker: Window message received:",
+ event.data?.type || "unknown",
+ );
}
-
+
// Verify the message is from our picker window
if (event.source !== this.win) {
return;
}
const message = event.data;
-
+
// === DIAGNOSTIC: Log full message data ===
- console.log("SharePoint v8 picker: Message data:", JSON.stringify(message, null, 2));
+ console.log(
+ "SharePoint v8 picker: Message data:",
+ JSON.stringify(message, null, 2),
+ );
// Handle initialization message
if (message.type === "initialize" && message.channelId === this.channelId) {
console.log("SharePoint v8 picker: Received initialize message");
- console.log("SharePoint v8 picker: Channel ID match:", message.channelId === this.channelId);
+ console.log(
+ "SharePoint v8 picker: Channel ID match:",
+ message.channelId === this.channelId,
+ );
// Get the MessagePort for further communication
this.port = event.ports[0];
@@ -275,20 +295,33 @@ export class SharePointV8Handler {
if (this.port) {
// Setup port message handler
- this.port.addEventListener("message", this.handlePortMessage.bind(this));
+ this.port.addEventListener(
+ "message",
+ this.handlePortMessage.bind(this),
+ );
this.port.start();
// Activate the picker
this.port.postMessage({ type: "activate" });
console.log("SharePoint v8 picker: Activated, sent activate message");
} else {
- console.error("SharePoint v8 picker: No MessagePort received in initialize message!");
+ console.error(
+ "SharePoint v8 picker: No MessagePort received in initialize message!",
+ );
}
} else if (message.type === "error") {
// === DIAGNOSTIC: Handle error messages from picker ===
- console.error("SharePoint v8 picker: Error message from picker window:", message);
+ console.error(
+ "SharePoint v8 picker: Error message from picker window:",
+ message,
+ );
} else if (message.channelId && message.channelId !== this.channelId) {
- console.warn("SharePoint v8 picker: Channel ID mismatch! Expected:", this.channelId, "Got:", message.channelId);
+ console.warn(
+ "SharePoint v8 picker: Channel ID mismatch! Expected:",
+ this.channelId,
+ "Got:",
+ message.channelId,
+ );
}
}
@@ -296,7 +329,10 @@ export class SharePointV8Handler {
const payload = event.data;
console.log("SharePoint v8 picker: Port message received:", payload.type);
// === DIAGNOSTIC: Log full payload for debugging ===
- console.log("SharePoint v8 picker: Full payload:", JSON.stringify(payload, null, 2));
+ console.log(
+ "SharePoint v8 picker: Full payload:",
+ JSON.stringify(payload, null, 2),
+ );
switch (payload.type) {
case "notification":
@@ -306,19 +342,25 @@ export class SharePointV8Handler {
case "command":
this.handleCommand(payload.id, payload.data);
break;
-
+
case "error":
// === DIAGNOSTIC: Log any error type messages ===
console.error("SharePoint v8 picker: Error message received:", payload);
break;
-
+
default:
- console.log("SharePoint v8 picker: Unknown payload type:", payload.type);
+ console.log(
+ "SharePoint v8 picker: Unknown payload type:",
+ payload.type,
+ );
}
}
private handleNotification(notification: { notification: string }): void {
- console.log("SharePoint v8 picker: Notification:", notification.notification);
+ console.log(
+ "SharePoint v8 picker: Notification:",
+ notification.notification,
+ );
if (notification.notification === "page-loaded") {
console.log("SharePoint v8 picker: Page loaded and ready");
@@ -370,13 +412,17 @@ export class SharePointV8Handler {
console.log("Auth request resource:", command.resource);
console.log("Auth request type:", command.type);
console.log("Full auth command:", JSON.stringify(command, null, 2));
-
+
// Check if resource matches our base URL or is Microsoft Graph using URL parsing
const resourceUrl = tryParseUrl(command.resource);
const baseUrl = tryParseUrl(this.baseUrl);
- const isGraphResource = resourceUrl ? isGraphHostname(resourceUrl.hostname) : false;
- const isSharePointResource = resourceUrl ? isSharePointHostname(resourceUrl.hostname) : false;
+ const isGraphResource = resourceUrl
+ ? isGraphHostname(resourceUrl.hostname)
+ : false;
+ const isSharePointResource = resourceUrl
+ ? isSharePointHostname(resourceUrl.hostname)
+ : false;
const resourceMatchesBase = hostnamesMatch(resourceUrl, baseUrl);
console.log("Resource analysis:");
@@ -384,21 +430,30 @@ export class SharePointV8Handler {
console.log(" - Is SharePoint resource:", isSharePointResource);
console.log(" - Resource matches our baseUrl:", resourceMatchesBase);
console.log(" - Our baseUrl:", this.baseUrl);
-
+
// IMPORTANT: Our token is for Microsoft Graph API (audience: https://graph.microsoft.com)
// If the picker requests a SharePoint-specific resource, the token might not work
- console.log("Token audience: https://graph.microsoft.com (Microsoft Graph)");
-
+ console.log(
+ "Token audience: https://graph.microsoft.com (Microsoft Graph)",
+ );
+
if (isSharePointResource && !isGraphResource) {
- console.warn("⚠️ POTENTIAL ISSUE: Picker requested SharePoint resource, but our token is for Microsoft Graph!");
+ console.warn(
+ "⚠️ POTENTIAL ISSUE: Picker requested SharePoint resource, but our token is for Microsoft Graph!",
+ );
console.warn("⚠️ This mismatch could cause 'invalid_client' errors.");
- console.warn("⚠️ The token audience might need to be the SharePoint domain instead.");
+ console.warn(
+ "⚠️ The token audience might need to be the SharePoint domain instead.",
+ );
}
-
+
// Log token details (safely)
- console.log("Token to provide (first 30 chars):", this.accessToken?.substring(0, 30) + "...");
+ console.log(
+ "Token to provide (first 30 chars):",
+ this.accessToken?.substring(0, 30) + "...",
+ );
console.log("Token to provide (length):", this.accessToken?.length);
-
+
// Decode JWT header to show audience (if present)
try {
const tokenParts = this.accessToken?.split(".");
@@ -408,7 +463,10 @@ export class SharePointV8Handler {
console.log(" - aud (audience):", payload.aud);
console.log(" - iss (issuer):", payload.iss);
console.log(" - scp (scopes):", payload.scp);
- console.log(" - exp (expiry):", new Date(payload.exp * 1000).toISOString());
+ console.log(
+ " - exp (expiry):",
+ new Date(payload.exp * 1000).toISOString(),
+ );
}
} catch (e) {
console.log("Could not decode token (may not be JWT):", e);
@@ -425,9 +483,14 @@ export class SharePointV8Handler {
token: this.accessToken,
},
});
- console.log("SharePoint v8 picker: Successfully sent auth token response");
+ console.log(
+ "SharePoint v8 picker: Successfully sent auth token response",
+ );
} catch (error) {
- console.error("SharePoint v8 picker: Failed to provide auth token:", error);
+ console.error(
+ "SharePoint v8 picker: Failed to provide auth token:",
+ error,
+ );
this.port?.postMessage({
type: "result",
id: id,
@@ -435,7 +498,8 @@ export class SharePointV8Handler {
result: "error",
error: {
code: "unableToObtainToken",
- message: error instanceof Error ? error.message : "Failed to obtain token",
+ message:
+ error instanceof Error ? error.message : "Failed to obtain token",
},
},
});
@@ -492,7 +556,10 @@ export class SharePointV8Handler {
result: "error",
error: {
code: "unusableItem",
- message: error instanceof Error ? error.message : "Failed to process picked items",
+ message:
+ error instanceof Error
+ ? error.message
+ : "Failed to process picked items",
},
},
});
diff --git a/frontend/components/cloud-picker/unified-cloud-picker.tsx b/frontend/components/cloud-picker/unified-cloud-picker.tsx
index 50e1a29ff..7f91225c0 100644
--- a/frontend/components/cloud-picker/unified-cloud-picker.tsx
+++ b/frontend/components/cloud-picker/unified-cloud-picker.tsx
@@ -1,15 +1,15 @@
"use client";
-import { useState, useEffect } from "react";
+import { useEffect, useState } from "react";
+import { FileList } from "./file-list";
+import { IngestSettings } from "./ingest-settings";
+import { PickerHeader } from "./picker-header";
+import { createProviderHandler } from "./provider-handlers";
import {
- UnifiedCloudPickerProps,
CloudFile,
IngestSettings as IngestSettingsType,
+ UnifiedCloudPickerProps,
} from "./types";
-import { PickerHeader } from "./picker-header";
-import { FileList } from "./file-list";
-import { IngestSettings } from "./ingest-settings";
-import { createProviderHandler } from "./provider-handlers";
export const UnifiedCloudPicker = ({
provider,
@@ -107,9 +107,14 @@ export const UnifiedCloudPicker = ({
console.log("Effective Base URL:", effectiveBaseUrl);
console.log("Is Picker Loaded:", isPickerLoaded);
console.log("Has Access Token:", !!accessToken);
-
+
if (!isPickerLoaded || !accessToken) {
- console.error("Cannot open picker: isPickerLoaded=", isPickerLoaded, "hasAccessToken=", !!accessToken);
+ console.error(
+ "Cannot open picker: isPickerLoaded=",
+ isPickerLoaded,
+ "hasAccessToken=",
+ !!accessToken,
+ );
return;
}
@@ -179,8 +184,9 @@ export const UnifiedCloudPicker = ({
if (provider === "sharepoint" && !baseUrl && isAuthenticated) {
return (
<div className="text-sm text-muted-foreground p-4 bg-muted/20 rounded-md">
- Configuration required: A site URL has not been configured for this connector.
- Please update your connector settings with a valid site URL for your organization and try again.
+ Configuration required: A site URL has not been configured for this
+ connector. Please update your connector settings with a valid site URL
+ for your organization and try again.
</div>
);
}
diff --git a/frontend/components/confirmation-dialog.tsx b/frontend/components/confirmation-dialog.tsx
index 51d263359..1eb9f569f 100644
--- a/frontend/components/confirmation-dialog.tsx
+++ b/frontend/components/confirmation-dialog.tsx
@@ -1,6 +1,7 @@
"use client";
import { ReactNode, useState } from "react";
+import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
@@ -10,7 +11,6 @@ import {
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
interface ConfirmationDialogProps {
trigger: ReactNode;
diff --git a/frontend/components/delete-confirmation-dialog.tsx b/frontend/components/delete-confirmation-dialog.tsx
index 688c31704..3653300d2 100644
--- a/frontend/components/delete-confirmation-dialog.tsx
+++ b/frontend/components/delete-confirmation-dialog.tsx
@@ -1,6 +1,8 @@
"use client";
+import { AlertTriangle } from "lucide-react";
import React, { ReactNode } from "react";
+import { Button } from "./ui/button";
import {
Dialog,
DialogContent,
@@ -9,8 +11,6 @@ import {
DialogHeader,
DialogTitle,
} from "./ui/dialog";
-import { Button } from "./ui/button";
-import { AlertTriangle } from "lucide-react";
/**
* Formats a list of files to be deleted, truncating if necessary.
@@ -26,10 +26,17 @@ export function formatFilesToDelete(
const remainingCount = files.length - maxVisible;
return (
<ul className="list-disc list-inside max-w-[29rem] sm:max-w-[calc(425px-3rem)]">
- {visibleFiles.map((file) => <li className="my-2 truncate">{file.filename}</li>)}
- {remainingCount > 0 ? <li>&hellip; and {remainingCount} more document{
- remainingCount > 1 ? "s" : ""
- }</li> : "" }
+ {visibleFiles.map((file) => (
+ <li className="my-2 truncate">{file.filename}</li>
+ ))}
+ {remainingCount > 0 ? (
+ <li>
+ &hellip; and {remainingCount} more document
+ {remainingCount > 1 ? "s" : ""}
+ </li>
+ ) : (
+ ""
+ )}
</ul>
);
}
@@ -84,9 +91,7 @@ export const DeleteConfirmationDialog: React.FC<
</div>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
- <div className="text-sm text-muted-foreground">
- {children}
- </div>
+ <div className="text-sm text-muted-foreground">{children}</div>
<DialogFooter>
<Button
type="button"
diff --git a/frontend/components/filter-icon-popover.tsx b/frontend/components/filter-icon-popover.tsx
index a87946b2c..b37109e89 100644
--- a/frontend/components/filter-icon-popover.tsx
+++ b/frontend/components/filter-icon-popover.tsx
@@ -1,40 +1,40 @@
"use client";
-import React, { type SVGProps } from "react";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover";
import {
+ Archive,
+ Bolt,
Book,
- Scroll,
- Library,
- Map,
- FileImage,
- Layers3,
+ Cable,
+ Check,
Database,
+ FileImage,
+ Filter,
Folder,
- Archive,
- MessagesSquare,
- SquareStack,
- Ghost,
Gem,
- Swords,
- Bolt,
- Shield,
- Hammer,
+ Ghost,
Globe,
+ Hammer,
HardDrive,
- Upload,
- Cable,
- ShoppingCart,
+ Layers3,
+ Library,
+ Map,
+ MessagesSquare,
+ Scroll,
+ Shield,
ShoppingBag,
- Check,
- Filter,
+ ShoppingCart,
+ SquareStack,
+ Swords,
+ Upload,
} from "lucide-react";
-import { filterAccentClasses } from "./knowledge-filter-panel";
+import React, { type SVGProps } from "react";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
+import { filterAccentClasses } from "./knowledge-filter-panel";
const ICON_MAP = {
filter: Filter,
diff --git a/frontend/components/knowledge-actions-dropdown.tsx b/frontend/components/knowledge-actions-dropdown.tsx
index 8099a84a1..60bf4719b 100644
--- a/frontend/components/knowledge-actions-dropdown.tsx
+++ b/frontend/components/knowledge-actions-dropdown.tsx
@@ -1,8 +1,8 @@
"use client";
-import { EllipsisVertical, RefreshCw, AlertCircle } from "lucide-react";
+import { AlertCircle, EllipsisVertical, RefreshCw } from "lucide-react";
import { useRouter } from "next/navigation";
-import { useState, useMemo } from "react";
+import { useMemo, useState } from "react";
import { toast } from "sonner";
import { useDeleteDocument } from "@/app/api/mutations/useDeleteDocument";
import { useSyncConnector } from "@/app/api/mutations/useSyncConnector";
@@ -13,10 +13,15 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import { DeleteConfirmationDialog } from "./delete-confirmation-dialog";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
import { formatFilesToDelete } from "@/lib/format-files-to-delete";
+import { DeleteConfirmationDialog } from "./delete-confirmation-dialog";
import { Button } from "./ui/button";
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
interface KnowledgeActionsDropdownProps {
filename: string;
@@ -24,7 +29,11 @@ interface KnowledgeActionsDropdownProps {
}
// Cloud connector types that support sync
-const CLOUD_CONNECTOR_TYPES = new Set(["google_drive", "onedrive", "sharepoint"]);
+const CLOUD_CONNECTOR_TYPES = new Set([
+ "google_drive",
+ "onedrive",
+ "sharepoint",
+]);
export const KnowledgeActionsDropdown = ({
filename,
@@ -68,12 +77,14 @@ export const KnowledgeActionsDropdown = ({
toast.info(result.message || `No ${connectorType} files to sync.`);
} else if (result.task_ids && result.task_ids.length > 0) {
toast.success(
- `Sync started for ${connectorType}. Check task notifications for progress.`
+ `Sync started for ${connectorType}. Check task notifications for progress.`,
);
}
} catch (error) {
toast.error(
- error instanceof Error ? error.message : `Failed to sync ${connectorType}`,
+ error instanceof Error
+ ? error.message
+ : `Failed to sync ${connectorType}`,
);
}
};
@@ -133,7 +144,9 @@ export const KnowledgeActionsDropdown = ({
{!isConnected && (
<TooltipContent side="right">
<p className="max-w-[200px] text-xs">
- {connectorType.charAt(0).toUpperCase() + connectorType.slice(1)} is not connected. Connect it in Settings to enable sync.
+ {connectorType.charAt(0).toUpperCase() +
+ connectorType.slice(1)}{" "}
+ is not connected. Connect it in Settings to enable sync.
</p>
</TooltipContent>
)}
@@ -158,7 +171,10 @@ export const KnowledgeActionsDropdown = ({
onConfirm={handleDelete}
isLoading={deleteDocumentMutation.isPending}
>
- <p className="my-2">This will remove all chunks and data associated with this document. This action cannot be undone.</p>
+ <p className="my-2">
+ This will remove all chunks and data associated with this document.
+ This action cannot be undone.
+ </p>
<p className="my-2">Document to be deleted:</p>
{formatFilesToDelete([{ filename }])}
</DeleteConfirmationDialog>
diff --git a/frontend/components/knowledge-dropdown.tsx b/frontend/components/knowledge-dropdown.tsx
index 1c8ab1845..1eba42fba 100644
--- a/frontend/components/knowledge-dropdown.tsx
+++ b/frontend/components/knowledge-dropdown.tsx
@@ -39,8 +39,8 @@ import { Label } from "@/components/ui/label";
import { useTask } from "@/contexts/task-context";
import {
duplicateCheck,
- uploadFile as uploadFileUtil,
uploadFiles,
+ uploadFile as uploadFileUtil,
} from "@/lib/upload-utils";
import { cn } from "@/lib/utils";
@@ -50,19 +50,25 @@ export const SUPPORTED_FILE_TYPES = {
"image/*": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".webp"],
"application/pdf": [".pdf"],
"application/msword": [".doc"],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [".docx"],
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [
+ ".docx",
+ ],
"application/vnd.ms-powerpoint": [".ppt"],
- "application/vnd.openxmlformats-officedocument.presentationml.presentation": [".pptx"],
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": [
+ ".pptx",
+ ],
"application/vnd.ms-excel": [".xls"],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [".xlsx"],
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [
+ ".xlsx",
+ ],
"text/csv": [".csv"],
"text/plain": [".txt"],
"text/markdown": [".md"],
"text/html": [".html", ".htm"],
"application/rtf": [".rtf"],
"application/vnd.oasis.opendocument.text": [".odt"],
- "text/asciidoc": [".adoc", ".asciidoc"]
-}
+ "text/asciidoc": [".adoc", ".asciidoc"],
+};
export const SUPPORTED_EXTENSIONS = Object.values(SUPPORTED_FILE_TYPES).flat();
diff --git a/frontend/components/knowledge-filter-list.tsx b/frontend/components/knowledge-filter-list.tsx
index f93fa518e..d77ef2a34 100644
--- a/frontend/components/knowledge-filter-list.tsx
+++ b/frontend/components/knowledge-filter-list.tsx
@@ -6,166 +6,166 @@ import type { KnowledgeFilter } from "@/app/api/queries/useGetFiltersSearchQuery
import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
import { cn } from "@/lib/utils";
import {
- type FilterColor,
- type IconKey,
- iconKeyToComponent,
+ type FilterColor,
+ type IconKey,
+ iconKeyToComponent,
} from "./filter-icon-popover";
import { filterAccentClasses } from "./knowledge-filter-panel";
interface ParsedQueryData {
- query: string;
- filters: {
- data_sources: string[];
- document_types: string[];
- owners: string[];
- };
- limit: number;
- scoreThreshold: number;
- color: FilterColor;
- icon: IconKey;
+ query: string;
+ filters: {
+ data_sources: string[];
+ document_types: string[];
+ owners: string[];
+ };
+ limit: number;
+ scoreThreshold: number;
+ color: FilterColor;
+ icon: IconKey;
}
interface KnowledgeFilterListProps {
- selectedFilter: KnowledgeFilter | null;
- onFilterSelect: (filter: KnowledgeFilter | null) => void;
+ selectedFilter: KnowledgeFilter | null;
+ onFilterSelect: (filter: KnowledgeFilter | null) => void;
}
export function KnowledgeFilterList({
- selectedFilter,
- onFilterSelect,
+ selectedFilter,
+ onFilterSelect,
}: KnowledgeFilterListProps) {
- const { startCreateMode } = useKnowledgeFilter();
+ const { startCreateMode } = useKnowledgeFilter();
- const { data, isFetching: loading } = useGetAllFiltersQuery();
+ const { data, isFetching: loading } = useGetAllFiltersQuery();
- const filters = data || [];
+ const filters = data || [];
- const handleFilterSelect = (filter: KnowledgeFilter) => {
- if (filter.id === selectedFilter?.id) {
- onFilterSelect(null);
- return;
- }
- onFilterSelect(filter);
- };
+ const handleFilterSelect = (filter: KnowledgeFilter) => {
+ if (filter.id === selectedFilter?.id) {
+ onFilterSelect(null);
+ return;
+ }
+ onFilterSelect(filter);
+ };
- const handleCreateNew = () => {
- startCreateMode();
- };
+ const handleCreateNew = () => {
+ 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",
- };
- };
+ 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">
- <div className="flex-shrink-0">
- <div className="flex items-center justify-between mb-3 mr-2 ml-4">
- <h3 className="text-xs font-medium text-muted-foreground">
- Knowledge Filters
- </h3>
- <button
- type="button"
- className="p-1 hover:bg-accent rounded"
- onClick={handleCreateNew}
- title="Create New Filter"
- >
- <Plus className="h-4 w-4 text-muted-foreground" />
- </button>
- </div>
- <div className="overflow-y-auto scrollbar-hide space-y-1">
- {loading ? (
- <div className="text-[13px] text-muted-foreground p-2 ml-2">
- Loading...
- </div>
- ) : filters.length === 0 ? (
- <div className="text-[13px] text-muted-foreground pb-2 pt-3 ml-4">
- No saved filters
- </div>
- ) : (
- filters.map((filter) => (
- <div
- key={filter.id}
- onClick={() => handleFilterSelect(filter)}
- className={cn(
- "flex items-center gap-3 px-3 py-2 w-full rounded-lg hover:bg-accent hover:text-accent-foreground cursor-pointer group transition-colors",
- selectedFilter?.id === filter.id &&
- "active bg-accent text-accent-foreground",
- )}
- >
- <div className="flex flex-col gap-1 flex-1 min-w-0">
- <div className="flex items-center gap-2">
- {(() => {
- const parsed = parseQueryData(
- filter.query_data,
- ) as ParsedQueryData;
- const Icon = iconKeyToComponent(parsed.icon);
- return (
- <div
- className={cn(
- "flex items-center justify-center w-5 h-5 rounded transition-colors",
- filterAccentClasses[parsed.color],
- parsed.color === "zinc" &&
- "group-hover:bg-background group-[.active]:bg-background",
- )}
- >
- {Icon && <Icon className="h-3 w-3" />}
- </div>
- );
- })()}
- <div className="text-sm font-medium truncate group-hover:text-accent-foreground">
- {filter.name}
- </div>
- </div>
- {filter.description && (
- <div className="text-xs text-muted-foreground line-clamp-2">
- {filter.description}
- </div>
- )}
- <div className="flex items-center gap-2">
- <div className="text-xs text-muted-foreground">
- {new Date(filter.created_at).toLocaleDateString(
- undefined,
- {
- month: "short",
- day: "numeric",
- year: "numeric",
- },
- )}
- </div>
- <span className="text-xs bg-muted text-muted-foreground px-1 py-0.5 rounded-sm group-hover:bg-background group-[.active]:bg-background transition-colors">
- {(() => {
- const dataSources = parseQueryData(filter.query_data)
- .filters.data_sources;
- if (dataSources[0] === "*") return "All sources";
- const count = dataSources.length;
- return `${count} ${
- count === 1 ? "source" : "sources"
- }`;
- })()}
- </span>
- </div>
- </div>
- </div>
- ))
- )}
- </div>
- </div>
- {/* Create flow moved to panel create mode */}
- </div>
- </div>
- );
+ return (
+ <div className="flex-1 min-h-0 flex flex-col">
+ <div className="px-3 flex-1 min-h-0 flex flex-col">
+ <div className="flex-shrink-0">
+ <div className="flex items-center justify-between mb-3 mr-2 ml-4">
+ <h3 className="text-xs font-medium text-muted-foreground">
+ Knowledge Filters
+ </h3>
+ <button
+ type="button"
+ className="p-1 hover:bg-accent rounded"
+ onClick={handleCreateNew}
+ title="Create New Filter"
+ >
+ <Plus className="h-4 w-4 text-muted-foreground" />
+ </button>
+ </div>
+ <div className="overflow-y-auto scrollbar-hide space-y-1">
+ {loading ? (
+ <div className="text-[13px] text-muted-foreground p-2 ml-2">
+ Loading...
+ </div>
+ ) : filters.length === 0 ? (
+ <div className="text-[13px] text-muted-foreground pb-2 pt-3 ml-4">
+ No saved filters
+ </div>
+ ) : (
+ filters.map((filter) => (
+ <div
+ key={filter.id}
+ onClick={() => handleFilterSelect(filter)}
+ className={cn(
+ "flex items-center gap-3 px-3 py-2 w-full rounded-lg hover:bg-accent hover:text-accent-foreground cursor-pointer group transition-colors",
+ selectedFilter?.id === filter.id &&
+ "active bg-accent text-accent-foreground",
+ )}
+ >
+ <div className="flex flex-col gap-1 flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ {(() => {
+ const parsed = parseQueryData(
+ filter.query_data,
+ ) as ParsedQueryData;
+ const Icon = iconKeyToComponent(parsed.icon);
+ return (
+ <div
+ className={cn(
+ "flex items-center justify-center w-5 h-5 rounded transition-colors",
+ filterAccentClasses[parsed.color],
+ parsed.color === "zinc" &&
+ "group-hover:bg-background group-[.active]:bg-background",
+ )}
+ >
+ {Icon && <Icon className="h-3 w-3" />}
+ </div>
+ );
+ })()}
+ <div className="text-sm font-medium truncate group-hover:text-accent-foreground">
+ {filter.name}
+ </div>
+ </div>
+ {filter.description && (
+ <div className="text-xs text-muted-foreground line-clamp-2">
+ {filter.description}
+ </div>
+ )}
+ <div className="flex items-center gap-2">
+ <div className="text-xs text-muted-foreground">
+ {new Date(filter.created_at).toLocaleDateString(
+ undefined,
+ {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ },
+ )}
+ </div>
+ <span className="text-xs bg-muted text-muted-foreground px-1 py-0.5 rounded-sm group-hover:bg-background group-[.active]:bg-background transition-colors">
+ {(() => {
+ const dataSources = parseQueryData(filter.query_data)
+ .filters.data_sources;
+ if (dataSources[0] === "*") return "All sources";
+ const count = dataSources.length;
+ return `${count} ${
+ count === 1 ? "source" : "sources"
+ }`;
+ })()}
+ </span>
+ </div>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ {/* Create flow moved to panel create mode */}
+ </div>
+ </div>
+ );
}
diff --git a/frontend/components/layout-wrapper.tsx b/frontend/components/layout-wrapper.tsx
index 83cbd8e23..0446b2e90 100644
--- a/frontend/components/layout-wrapper.tsx
+++ b/frontend/components/layout-wrapper.tsx
@@ -1,8 +1,8 @@
"use client";
+import { AnimatePresence, motion } from "framer-motion";
import { usePathname, useRouter } from "next/navigation";
import { useEffect } from "react";
-import { AnimatePresence, motion } from "framer-motion";
import { useGetSettingsQuery } from "@/app/api/queries/useGetSettingsQuery";
import {
DoclingHealthBanner,
diff --git a/frontend/components/navigation.tsx b/frontend/components/navigation.tsx
index 68ffa4e67..f25b7cfc0 100644
--- a/frontend/components/navigation.tsx
+++ b/frontend/components/navigation.tsx
@@ -403,7 +403,8 @@ export function Navigation({
// 2. currentConversationId exists but isn't in conversations yet (gap between response and list update)
const conversationExists = currentConversationId
? conversations.some(
- (conv) => conv.response_id === currentConversationId,
+ (conv) =>
+ conv.response_id === currentConversationId,
)
: false;
@@ -416,26 +417,25 @@ export function Navigation({
// Use placeholderConversation if available
// Otherwise create a placeholder with currentConversationId if it exists
// Or use a temporary ID if we're loading but don't have an ID yet
- const placeholderToShow =
- placeholderConversation
- ? placeholderConversation
- : currentConversationId
+ const placeholderToShow = placeholderConversation
+ ? placeholderConversation
+ : currentConversationId
+ ? {
+ response_id: currentConversationId,
+ title: "",
+ endpoint: endpoint,
+ messages: [],
+ total_messages: 0,
+ }
+ : loading
? {
- response_id: currentConversationId,
+ response_id: `loading-${Date.now()}`,
title: "",
endpoint: endpoint,
messages: [],
total_messages: 0,
}
- : loading
- ? {
- response_id: `loading-${Date.now()}`,
- title: "",
- endpoint: endpoint,
- messages: [],
- total_messages: 0,
- }
- : null;
+ : null;
return (
shouldShowPlaceholder &&
@@ -459,81 +459,81 @@ export function Navigation({
})()}
{conversations.map((conversation) => (
<button
- key={conversation.response_id}
- type="button"
- className={`w-full px-3 h-11 rounded-lg group relative text-left ${
- loading || isConversationsLoading
- ? "opacity-50 cursor-not-allowed"
- : "hover:bg-accent cursor-pointer"
- } ${
- currentConversationId === conversation.response_id
- ? "bg-accent"
- : ""
- }`}
- onClick={() => {
- if (loading || isConversationsLoading) return;
- loadConversation(conversation);
- // Don't refresh - just loading an existing conversation
- }}
- disabled={loading || isConversationsLoading}
- >
- <div className="flex items-center justify-between">
- <div className="flex-1 min-w-0">
- <div className="text-sm font-medium text-foreground truncate">
- {conversation.title}
+ key={conversation.response_id}
+ type="button"
+ className={`w-full px-3 h-11 rounded-lg group relative text-left ${
+ loading || isConversationsLoading
+ ? "opacity-50 cursor-not-allowed"
+ : "hover:bg-accent cursor-pointer"
+ } ${
+ currentConversationId === conversation.response_id
+ ? "bg-accent"
+ : ""
+ }`}
+ onClick={() => {
+ if (loading || isConversationsLoading) return;
+ loadConversation(conversation);
+ // Don't refresh - just loading an existing conversation
+ }}
+ disabled={loading || isConversationsLoading}
+ >
+ <div className="flex items-center justify-between">
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-medium text-foreground truncate">
+ {conversation.title}
+ </div>
</div>
- </div>
- <DropdownMenu>
- <DropdownMenuTrigger
- disabled={
- loading ||
- isConversationsLoading ||
- deleteSessionMutation.isPending
- }
- asChild
- >
- <div
- className="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();
- }
- }}
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ disabled={
+ loading ||
+ isConversationsLoading ||
+ deleteSessionMutation.isPending
+ }
+ asChild
>
- <EllipsisVertical className="h-4 w-4" />
- </div>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- side="bottom"
- align="end"
- className="w-48"
- onClick={(e) => e.stopPropagation()}
- >
- <DropdownMenuItem
- onClick={(e) => {
- e.stopPropagation();
- handleContextMenuAction(
- "delete",
- conversation,
- );
- }}
- className="cursor-pointer text-destructive focus:text-destructive"
+ <div
+ className="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>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ side="bottom"
+ align="end"
+ className="w-48"
+ onClick={(e) => e.stopPropagation()}
>
- <Trash2 className="mr-2 h-4 w-4" />
- Delete conversation
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </button>
- ))}
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ handleContextMenuAction(
+ "delete",
+ conversation,
+ );
+ }}
+ className="cursor-pointer text-destructive focus:text-destructive"
+ >
+ <Trash2 className="mr-2 h-4 w-4" />
+ Delete conversation
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </button>
+ ))}
</>
)}
</>
diff --git a/frontend/components/provider-health-banner.tsx b/frontend/components/provider-health-banner.tsx
index 3bf5cfb1d..6061a7f9d 100644
--- a/frontend/components/provider-health-banner.tsx
+++ b/frontend/components/provider-health-banner.tsx
@@ -10,126 +10,126 @@ import { cn } from "@/lib/utils";
import { Button } from "./ui/button";
interface ProviderHealthBannerProps {
- className?: string;
+ className?: string;
}
// Custom hook to check provider health status
export function useProviderHealth() {
- const { hasChatError } = useChat();
- const {
- data: health,
- isLoading,
- isFetching,
- error,
- isError,
- } = useProviderHealthQuery({
- test_completion: hasChatError, // Use test_completion=true when chat errors occur
- });
+ const { hasChatError } = useChat();
+ const {
+ data: health,
+ isLoading,
+ isFetching,
+ error,
+ isError,
+ } = useProviderHealthQuery({
+ test_completion: hasChatError, // Use test_completion=true when chat errors occur
+ });
- const isHealthy = health?.status === "healthy" && !isError;
- // Only consider unhealthy if backend is up but provider validation failed
- // Don't show banner if backend is unavailable
- const isUnhealthy =
- health?.status === "unhealthy" || health?.status === "error";
- const isBackendUnavailable =
- health?.status === "backend-unavailable" || isError;
+ const isHealthy = health?.status === "healthy" && !isError;
+ // Only consider unhealthy if backend is up but provider validation failed
+ // Don't show banner if backend is unavailable
+ const isUnhealthy =
+ health?.status === "unhealthy" || health?.status === "error";
+ const isBackendUnavailable =
+ health?.status === "backend-unavailable" || isError;
- return {
- health,
- isLoading,
- isFetching,
- error,
- isError,
- isHealthy,
- isUnhealthy,
- isBackendUnavailable,
- };
+ return {
+ health,
+ isLoading,
+ isFetching,
+ error,
+ isError,
+ isHealthy,
+ isUnhealthy,
+ isBackendUnavailable,
+ };
}
const providerTitleMap: Record<ModelProvider, string> = {
- openai: "OpenAI",
- anthropic: "Anthropic",
- ollama: "Ollama",
- watsonx: "IBM watsonx.ai",
+ openai: "OpenAI",
+ anthropic: "Anthropic",
+ ollama: "Ollama",
+ watsonx: "IBM watsonx.ai",
};
export function ProviderHealthBanner({ className }: ProviderHealthBannerProps) {
- const { isLoading, isHealthy, isUnhealthy, health } = useProviderHealth();
- const router = useRouter();
+ const { isLoading, isHealthy, isUnhealthy, health } = useProviderHealth();
+ const router = useRouter();
- // Only show banner when provider is unhealthy (not when backend is unavailable)
- if (isLoading || isHealthy) {
- return null;
- }
+ // Only show banner when provider is unhealthy (not when backend is unavailable)
+ if (isLoading || isHealthy) {
+ return null;
+ }
- if (isUnhealthy) {
- const llmProvider = health?.llm_provider || health?.provider;
- const embeddingProvider = health?.embedding_provider;
- const llmError = health?.llm_error;
- const embeddingError = health?.embedding_error;
+ if (isUnhealthy) {
+ const llmProvider = health?.llm_provider || health?.provider;
+ const embeddingProvider = health?.embedding_provider;
+ const llmError = health?.llm_error;
+ const embeddingError = health?.embedding_error;
- // Determine which provider has the error
- let errorProvider: string | undefined;
- let errorMessage: string;
+ // Determine which provider has the error
+ let errorProvider: string | undefined;
+ let errorMessage: string;
- if (llmError && embeddingError) {
- // Both have errors - check if they're the same
- if (llmError === embeddingError) {
- // Same error for both - show once
- errorMessage = llmError;
- } else {
- // Different errors - show both
- errorMessage = `${llmError}; ${embeddingError}`;
- }
- errorProvider = undefined; // Don't link to a specific provider
- } else if (llmError) {
- // Only LLM has error
- errorProvider = llmProvider;
- errorMessage = llmError;
- } else if (embeddingError) {
- // Only embedding has error
- errorProvider = embeddingProvider;
- errorMessage = embeddingError;
- } else {
- // Fallback to original message
- errorMessage = health?.message || "Provider validation failed";
- errorProvider = llmProvider;
- }
+ if (llmError && embeddingError) {
+ // Both have errors - check if they're the same
+ if (llmError === embeddingError) {
+ // Same error for both - show once
+ errorMessage = llmError;
+ } else {
+ // Different errors - show both
+ errorMessage = `${llmError}; ${embeddingError}`;
+ }
+ errorProvider = undefined; // Don't link to a specific provider
+ } else if (llmError) {
+ // Only LLM has error
+ errorProvider = llmProvider;
+ errorMessage = llmError;
+ } else if (embeddingError) {
+ // Only embedding has error
+ errorProvider = embeddingProvider;
+ errorMessage = embeddingError;
+ } else {
+ // Fallback to original message
+ errorMessage = health?.message || "Provider validation failed";
+ errorProvider = llmProvider;
+ }
- const providerTitle = errorProvider
- ? providerTitleMap[errorProvider as ModelProvider] || errorProvider
- : "Provider";
+ const providerTitle = errorProvider
+ ? providerTitleMap[errorProvider as ModelProvider] || errorProvider
+ : "Provider";
- const settingsUrl = errorProvider
- ? `/settings?setup=${errorProvider}`
- : "/settings";
+ const settingsUrl = errorProvider
+ ? `/settings?setup=${errorProvider}`
+ : "/settings";
- return (
- <Banner
- className={cn(
- "bg-red-50 dark:bg-red-950 text-foreground border-accent-red border-b w-full",
- className,
- )}
- >
- <BannerIcon
- className="text-accent-red-foreground"
- icon={AlertTriangle}
- />
- <BannerTitle className="font-medium flex items-center gap-2">
- {llmError && embeddingError ? (
- <>Provider errors - {errorMessage}</>
- ) : (
- <>
- {providerTitle} error - {errorMessage}
- </>
- )}
- </BannerTitle>
- <Button size="sm" onClick={() => router.push(settingsUrl)}>
- Fix Setup
- </Button>
- </Banner>
- );
- }
+ return (
+ <Banner
+ className={cn(
+ "bg-red-50 dark:bg-red-950 text-foreground border-accent-red border-b w-full",
+ className,
+ )}
+ >
+ <BannerIcon
+ className="text-accent-red-foreground"
+ icon={AlertTriangle}
+ />
+ <BannerTitle className="font-medium flex items-center gap-2">
+ {llmError && embeddingError ? (
+ <>Provider errors - {errorMessage}</>
+ ) : (
+ <>
+ {providerTitle} error - {errorMessage}
+ </>
+ )}
+ </BannerTitle>
+ <Button size="sm" onClick={() => router.push(settingsUrl)}>
+ Fix Setup
+ </Button>
+ </Banner>
+ );
+ }
- return null;
+ return null;
}
diff --git a/frontend/components/task-notification-menu.tsx b/frontend/components/task-notification-menu.tsx
index 159d9eccc..6fbe9ed6d 100644
--- a/frontend/components/task-notification-menu.tsx
+++ b/frontend/components/task-notification-menu.tsx
@@ -1,16 +1,17 @@
"use client";
-import { useEffect, useState } from "react";
import {
Bell,
CheckCircle,
- XCircle,
- Clock,
- Loader2,
ChevronDown,
ChevronUp,
+ Clock,
+ Loader2,
X,
+ XCircle,
} from "lucide-react";
+import { useEffect, useState } from "react";
+import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Card,
@@ -19,8 +20,7 @@ import {
CardHeader,
CardTitle,
} from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
-import { useTask, Task } from "@/contexts/task-context";
+import { Task, useTask } from "@/contexts/task-context";
export function TaskNotificationMenu() {
const { tasks, isFetching, isMenuOpen, isRecentTasksExpanded, cancelTask } =
diff --git a/frontend/components/theme-provider.tsx b/frontend/components/theme-provider.tsx
index 984415a20..7c68d1f8b 100644
--- a/frontend/components/theme-provider.tsx
+++ b/frontend/components/theme-provider.tsx
@@ -1,8 +1,10 @@
"use client";
+import {
+ ThemeProvider as NextThemesProvider,
+ type ThemeProviderProps,
+} from "next-themes";
import * as React from "react";
-import { ThemeProvider as NextThemesProvider } from "next-themes";
-import { type ThemeProviderProps } from "next-themes";
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
diff --git a/frontend/components/theme-switcher-buttons.tsx b/frontend/components/theme-switcher-buttons.tsx
index f6e993291..59b14447d 100644
--- a/frontend/components/theme-switcher-buttons.tsx
+++ b/frontend/components/theme-switcher-buttons.tsx
@@ -1,6 +1,6 @@
-import { useEffect, useState } from "react";
import { Monitor, Moon, Sun } from "lucide-react";
import { useTheme } from "next-themes";
+import { useEffect, useState } from "react";
export const ThemeSwitcherButtons = () => {
const { theme, setTheme } = useTheme();
diff --git a/frontend/components/ui/avatar.tsx b/frontend/components/ui/avatar.tsx
index 09cd14df8..9b121d26b 100644
--- a/frontend/components/ui/avatar.tsx
+++ b/frontend/components/ui/avatar.tsx
@@ -1,7 +1,7 @@
"use client";
-import * as React from "react";
import * as AvatarPrimitive from "@radix-ui/react-avatar";
+import * as React from "react";
import { cn } from "@/lib/utils";
diff --git a/frontend/components/ui/button.tsx b/frontend/components/ui/button.tsx
index dadcb7ae4..23177a25f 100644
--- a/frontend/components/ui/button.tsx
+++ b/frontend/components/ui/button.tsx
@@ -53,7 +53,7 @@ function toTitleCase(text: string) {
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
- VariantProps<typeof buttonVariants> {
+ VariantProps<typeof buttonVariants> {
asChild?: boolean;
loading?: boolean;
ignoreTitleCase?: boolean;
diff --git a/frontend/components/ui/command.tsx b/frontend/components/ui/command.tsx
index 0a5faac48..02fcf6007 100644
--- a/frontend/components/ui/command.tsx
+++ b/frontend/components/ui/command.tsx
@@ -1,12 +1,11 @@
"use client";
-import * as React from "react";
import { DialogProps } from "@radix-ui/react-dialog";
import { Command as CommandPrimitive } from "cmdk";
import { Search } from "lucide-react";
-
-import { cn } from "@/lib/utils";
+import * as React from "react";
import { Dialog, DialogContent } from "@/components/ui/dialog";
+import { cn } from "@/lib/utils";
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
diff --git a/frontend/components/ui/dialog.tsx b/frontend/components/ui/dialog.tsx
index e72c2b5d0..b8661a688 100644
--- a/frontend/components/ui/dialog.tsx
+++ b/frontend/components/ui/dialog.tsx
@@ -1,8 +1,8 @@
"use client";
-import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
+import * as React from "react";
import { cn } from "@/lib/utils";
diff --git a/frontend/components/ui/dropdown-menu.tsx b/frontend/components/ui/dropdown-menu.tsx
index 3a0c7fed7..f0aaafabb 100644
--- a/frontend/components/ui/dropdown-menu.tsx
+++ b/frontend/components/ui/dropdown-menu.tsx
@@ -1,8 +1,8 @@
"use client";
-import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { Check, ChevronRight, Circle } from "lucide-react";
+import * as React from "react";
import { cn } from "@/lib/utils";
diff --git a/frontend/components/ui/inputs/number-input.tsx b/frontend/components/ui/inputs/number-input.tsx
index b312292f0..3a5969560 100644
--- a/frontend/components/ui/inputs/number-input.tsx
+++ b/frontend/components/ui/inputs/number-input.tsx
@@ -1,7 +1,7 @@
+import { Minus, Plus } from "lucide-react";
import { LabelWrapper } from "@/components/label-wrapper";
import { Button } from "../button";
import { Input } from "../input";
-import { Minus, Plus } from "lucide-react";
interface NumberInputProps {
id: string;
diff --git a/frontend/components/ui/label.tsx b/frontend/components/ui/label.tsx
index 79d77b4b0..6166bcb63 100644
--- a/frontend/components/ui/label.tsx
+++ b/frontend/components/ui/label.tsx
@@ -1,7 +1,7 @@
"use client";
-import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
+import * as React from "react";
import { cn } from "@/lib/utils";
diff --git a/frontend/components/ui/multi-select.tsx b/frontend/components/ui/multi-select.tsx
index 472b68351..e5e1a8ace 100644
--- a/frontend/components/ui/multi-select.tsx
+++ b/frontend/components/ui/multi-select.tsx
@@ -1,8 +1,7 @@
"use client";
+import { Check, ChevronDown } from "lucide-react";
import * as React from "react";
-import { ChevronDown, Check } from "lucide-react";
-import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Command,
@@ -17,6 +16,7 @@ import {
PopoverTrigger,
} from "@/components/ui/popover";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { cn } from "@/lib/utils";
interface Option {
value: string;
diff --git a/frontend/components/ui/select.tsx b/frontend/components/ui/select.tsx
index 4321e9acf..3c92a9bd2 100644
--- a/frontend/components/ui/select.tsx
+++ b/frontend/components/ui/select.tsx
@@ -1,6 +1,5 @@
"use client";
-import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import {
Check,
@@ -9,6 +8,7 @@ import {
ChevronUp,
LockIcon,
} from "lucide-react";
+import * as React from "react";
import { cn } from "@/lib/utils";
diff --git a/frontend/components/ui/separator.tsx b/frontend/components/ui/separator.tsx
index 12d81c4a8..3cc446d24 100644
--- a/frontend/components/ui/separator.tsx
+++ b/frontend/components/ui/separator.tsx
@@ -1,9 +1,9 @@
-"use client"
+"use client";
-import * as React from "react"
-import * as SeparatorPrimitive from "@radix-ui/react-separator"
+import * as SeparatorPrimitive from "@radix-ui/react-separator";
+import * as React from "react";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
@@ -11,7 +11,7 @@ const Separator = React.forwardRef<
>(
(
{ className, orientation = "horizontal", decorative = true, ...props },
- ref
+ ref,
) => (
<SeparatorPrimitive.Root
ref={ref}
@@ -20,12 +20,12 @@ const Separator = React.forwardRef<
className={cn(
"shrink-0 bg-border",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
- className
+ className,
)}
{...props}
/>
- )
-)
-Separator.displayName = SeparatorPrimitive.Root.displayName
+ ),
+);
+Separator.displayName = SeparatorPrimitive.Root.displayName;
-export { Separator }
+export { Separator };
diff --git a/frontend/components/ui/sheet.tsx b/frontend/components/ui/sheet.tsx
index a37f17ba0..236010b64 100644
--- a/frontend/components/ui/sheet.tsx
+++ b/frontend/components/ui/sheet.tsx
@@ -1,19 +1,19 @@
-"use client"
+"use client";
-import * as React from "react"
-import * as SheetPrimitive from "@radix-ui/react-dialog"
-import { cva, type VariantProps } from "class-variance-authority"
-import { X } from "lucide-react"
+import * as SheetPrimitive from "@radix-ui/react-dialog";
+import { cva, type VariantProps } from "class-variance-authority";
+import { X } from "lucide-react";
+import * as React from "react";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
-const Sheet = SheetPrimitive.Root
+const Sheet = SheetPrimitive.Root;
-const SheetTrigger = SheetPrimitive.Trigger
+const SheetTrigger = SheetPrimitive.Trigger;
-const SheetClose = SheetPrimitive.Close
+const SheetClose = SheetPrimitive.Close;
-const SheetPortal = SheetPrimitive.Portal
+const SheetPortal = SheetPrimitive.Portal;
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
@@ -22,13 +22,13 @@ const SheetOverlay = React.forwardRef<
<SheetPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
- className
+ className,
)}
{...props}
ref={ref}
/>
-))
-SheetOverlay.displayName = SheetPrimitive.Overlay.displayName
+));
+SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
const sheetVariants = cva(
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
@@ -46,8 +46,8 @@ const sheetVariants = cva(
defaultVariants: {
side: "right",
},
- }
-)
+ },
+);
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
@@ -71,8 +71,8 @@ const SheetContent = React.forwardRef<
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
-))
-SheetContent.displayName = SheetPrimitive.Content.displayName
+));
+SheetContent.displayName = SheetPrimitive.Content.displayName;
const SheetHeader = ({
className,
@@ -81,12 +81,12 @@ const SheetHeader = ({
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
- className
+ className,
)}
{...props}
/>
-)
-SheetHeader.displayName = "SheetHeader"
+);
+SheetHeader.displayName = "SheetHeader";
const SheetFooter = ({
className,
@@ -95,12 +95,12 @@ const SheetFooter = ({
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
- className
+ className,
)}
{...props}
/>
-)
-SheetFooter.displayName = "SheetFooter"
+);
+SheetFooter.displayName = "SheetFooter";
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
@@ -111,8 +111,8 @@ const SheetTitle = React.forwardRef<
className={cn("text-lg font-semibold text-foreground", className)}
{...props}
/>
-))
-SheetTitle.displayName = SheetPrimitive.Title.displayName
+));
+SheetTitle.displayName = SheetPrimitive.Title.displayName;
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
@@ -123,8 +123,8 @@ const SheetDescription = React.forwardRef<
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
-))
-SheetDescription.displayName = SheetPrimitive.Description.displayName
+));
+SheetDescription.displayName = SheetPrimitive.Description.displayName;
export {
Sheet,
@@ -137,4 +137,4 @@ export {
SheetFooter,
SheetTitle,
SheetDescription,
-}
+};
diff --git a/frontend/components/ui/sidebar.tsx b/frontend/components/ui/sidebar.tsx
index 3fe6567e3..2bb08a8ba 100644
--- a/frontend/components/ui/sidebar.tsx
+++ b/frontend/components/ui/sidebar.tsx
@@ -1,64 +1,63 @@
-"use client"
-
-import * as React from "react"
-import { Slot } from "@radix-ui/react-slot"
-import { cva, type VariantProps } from "class-variance-authority"
-import { PanelLeft } from "lucide-react"
-
-import { useIsMobile } from "@/hooks/use-mobile"
-import { cn } from "@/lib/utils"
-import { Button } from "@/components/ui/button"
-import { Input } from "@/components/ui/input"
-import { Separator } from "@/components/ui/separator"
+"use client";
+
+import { Slot } from "@radix-ui/react-slot";
+import { cva, type VariantProps } from "class-variance-authority";
+import { PanelLeft } from "lucide-react";
+import * as React from "react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Separator } from "@/components/ui/separator";
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
-} from "@/components/ui/sheet"
-import { Skeleton } from "@/components/ui/skeleton"
+} from "@/components/ui/sheet";
+import { Skeleton } from "@/components/ui/skeleton";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
-} from "@/components/ui/tooltip"
+} from "@/components/ui/tooltip";
+import { useIsMobile } from "@/hooks/use-mobile";
+import { cn } from "@/lib/utils";
-const SIDEBAR_COOKIE_NAME = "sidebar_state"
-const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
-const SIDEBAR_WIDTH = "16rem"
-const SIDEBAR_WIDTH_MOBILE = "18rem"
-const SIDEBAR_WIDTH_ICON = "3rem"
-const SIDEBAR_KEYBOARD_SHORTCUT = "b"
+const SIDEBAR_COOKIE_NAME = "sidebar_state";
+const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
+const SIDEBAR_WIDTH = "16rem";
+const SIDEBAR_WIDTH_MOBILE = "18rem";
+const SIDEBAR_WIDTH_ICON = "3rem";
+const SIDEBAR_KEYBOARD_SHORTCUT = "b";
type SidebarContextProps = {
- state: "expanded" | "collapsed"
- open: boolean
- setOpen: (open: boolean) => void
- openMobile: boolean
- setOpenMobile: (open: boolean) => void
- isMobile: boolean
- toggleSidebar: () => void
-}
+ state: "expanded" | "collapsed";
+ open: boolean;
+ setOpen: (open: boolean) => void;
+ openMobile: boolean;
+ setOpenMobile: (open: boolean) => void;
+ isMobile: boolean;
+ toggleSidebar: () => void;
+};
-const SidebarContext = React.createContext<SidebarContextProps | null>(null)
+const SidebarContext = React.createContext<SidebarContextProps | null>(null);
function useSidebar() {
- const context = React.useContext(SidebarContext)
+ const context = React.useContext(SidebarContext);
if (!context) {
- throw new Error("useSidebar must be used within a SidebarProvider.")
+ throw new Error("useSidebar must be used within a SidebarProvider.");
}
- return context
+ return context;
}
const SidebarProvider = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
- defaultOpen?: boolean
- open?: boolean
- onOpenChange?: (open: boolean) => void
+ defaultOpen?: boolean;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
}
>(
(
@@ -71,36 +70,36 @@ const SidebarProvider = React.forwardRef<
children,
...props
},
- ref
+ ref,
) => {
- const isMobile = useIsMobile()
- const [openMobile, setOpenMobile] = React.useState(false)
+ const isMobile = useIsMobile();
+ const [openMobile, setOpenMobile] = React.useState(false);
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
- const [_open, _setOpen] = React.useState(defaultOpen)
- const open = openProp ?? _open
+ const [_open, _setOpen] = React.useState(defaultOpen);
+ const open = openProp ?? _open;
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
- const openState = typeof value === "function" ? value(open) : value
+ const openState = typeof value === "function" ? value(open) : value;
if (setOpenProp) {
- setOpenProp(openState)
+ setOpenProp(openState);
} else {
- _setOpen(openState)
+ _setOpen(openState);
}
// This sets the cookie to keep the sidebar state.
- document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
+ document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
},
- [setOpenProp, open]
- )
+ [setOpenProp, open],
+ );
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile
? setOpenMobile((open) => !open)
- : setOpen((open) => !open)
- }, [isMobile, setOpen, setOpenMobile])
+ : setOpen((open) => !open);
+ }, [isMobile, setOpen, setOpenMobile]);
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
@@ -109,18 +108,18 @@ const SidebarProvider = React.forwardRef<
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
) {
- event.preventDefault()
- toggleSidebar()
+ event.preventDefault();
+ toggleSidebar();
}
- }
+ };
- window.addEventListener("keydown", handleKeyDown)
- return () => window.removeEventListener("keydown", handleKeyDown)
- }, [toggleSidebar])
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [toggleSidebar]);
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
- const state = open ? "expanded" : "collapsed"
+ const state = open ? "expanded" : "collapsed";
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
@@ -132,8 +131,16 @@ const SidebarProvider = React.forwardRef<
setOpenMobile,
toggleSidebar,
}),
- [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
- )
+ [
+ state,
+ open,
+ setOpen,
+ isMobile,
+ openMobile,
+ setOpenMobile,
+ toggleSidebar,
+ ],
+ );
return (
<SidebarContext.Provider value={contextValue}>
@@ -148,7 +155,7 @@ const SidebarProvider = React.forwardRef<
}
className={cn(
"group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",
- className
+ className,
)}
ref={ref}
{...props}
@@ -157,17 +164,17 @@ const SidebarProvider = React.forwardRef<
</div>
</TooltipProvider>
</SidebarContext.Provider>
- )
- }
-)
-SidebarProvider.displayName = "SidebarProvider"
+ );
+ },
+);
+SidebarProvider.displayName = "SidebarProvider";
const Sidebar = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
- side?: "left" | "right"
- variant?: "sidebar" | "floating" | "inset"
- collapsible?: "offcanvas" | "icon" | "none"
+ side?: "left" | "right";
+ variant?: "sidebar" | "floating" | "inset";
+ collapsible?: "offcanvas" | "icon" | "none";
}
>(
(
@@ -179,23 +186,23 @@ const Sidebar = React.forwardRef<
children,
...props
},
- ref
+ ref,
) => {
- const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
+ const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
if (collapsible === "none") {
return (
<div
className={cn(
"flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",
- className
+ className,
)}
ref={ref}
{...props}
>
{children}
</div>
- )
+ );
}
if (isMobile) {
@@ -219,7 +226,7 @@ const Sidebar = React.forwardRef<
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
- )
+ );
}
return (
@@ -242,8 +249,8 @@ const Sidebar = React.forwardRef<
"group-data-[collapsible=offcanvas]:w-0",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]"
- : "group-data-[collapsible=icon]:w-[--sidebar-width-icon]"
- )
+ : "group-data-[collapsible=icon]:w-[--sidebar-width-icon]",
+ ),
)}
/>
<div
@@ -256,7 +263,7 @@ const Sidebar = React.forwardRef<
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]"
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",
- className
+ className,
)}
{...props}
>
@@ -268,16 +275,16 @@ const Sidebar = React.forwardRef<
</div>
</div>
</div>
- )
- }
-)
-Sidebar.displayName = "Sidebar"
+ );
+ },
+);
+Sidebar.displayName = "Sidebar";
const SidebarTrigger = React.forwardRef<
React.ElementRef<typeof Button>,
React.ComponentProps<typeof Button>
>(({ className, onClick, ...props }, ref) => {
- const { toggleSidebar } = useSidebar()
+ const { toggleSidebar } = useSidebar();
return (
<Button
@@ -287,23 +294,23 @@ const SidebarTrigger = React.forwardRef<
size="icon"
className={cn("h-7 w-7", className)}
onClick={(event) => {
- onClick?.(event)
- toggleSidebar()
+ onClick?.(event);
+ toggleSidebar();
}}
{...props}
>
<PanelLeft />
<span className="sr-only">Toggle Sidebar</span>
</Button>
- )
-})
-SidebarTrigger.displayName = "SidebarTrigger"
+ );
+});
+SidebarTrigger.displayName = "SidebarTrigger";
const SidebarRail = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button">
>(({ className, ...props }, ref) => {
- const { toggleSidebar } = useSidebar()
+ const { toggleSidebar } = useSidebar();
return (
<button
@@ -320,13 +327,13 @@ const SidebarRail = React.forwardRef<
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
- className
+ className,
)}
{...props}
/>
- )
-})
-SidebarRail.displayName = "SidebarRail"
+ );
+});
+SidebarRail.displayName = "SidebarRail";
const SidebarInset = React.forwardRef<
HTMLDivElement,
@@ -338,13 +345,13 @@ const SidebarInset = React.forwardRef<
className={cn(
"relative flex w-full flex-1 flex-col bg-background",
"md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",
- className
+ className,
)}
{...props}
/>
- )
-})
-SidebarInset.displayName = "SidebarInset"
+ );
+});
+SidebarInset.displayName = "SidebarInset";
const SidebarInput = React.forwardRef<
React.ElementRef<typeof Input>,
@@ -356,13 +363,13 @@ const SidebarInput = React.forwardRef<
data-sidebar="input"
className={cn(
"h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",
- className
+ className,
)}
{...props}
/>
- )
-})
-SidebarInput.displayName = "SidebarInput"
+ );
+});
+SidebarInput.displayName = "SidebarInput";
const SidebarHeader = React.forwardRef<
HTMLDivElement,
@@ -375,9 +382,9 @@ const SidebarHeader = React.forwardRef<
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
- )
-})
-SidebarHeader.displayName = "SidebarHeader"
+ );
+});
+SidebarHeader.displayName = "SidebarHeader";
const SidebarFooter = React.forwardRef<
HTMLDivElement,
@@ -390,9 +397,9 @@ const SidebarFooter = React.forwardRef<
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
- )
-})
-SidebarFooter.displayName = "SidebarFooter"
+ );
+});
+SidebarFooter.displayName = "SidebarFooter";
const SidebarSeparator = React.forwardRef<
React.ElementRef<typeof Separator>,
@@ -405,9 +412,9 @@ const SidebarSeparator = React.forwardRef<
className={cn("mx-2 w-auto bg-sidebar-border", className)}
{...props}
/>
- )
-})
-SidebarSeparator.displayName = "SidebarSeparator"
+ );
+});
+SidebarSeparator.displayName = "SidebarSeparator";
const SidebarContent = React.forwardRef<
HTMLDivElement,
@@ -419,13 +426,13 @@ const SidebarContent = React.forwardRef<
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
- className
+ className,
)}
{...props}
/>
- )
-})
-SidebarContent.displayName = "SidebarContent"
+ );
+});
+SidebarContent.displayName = "SidebarContent";
const SidebarGroup = React.forwardRef<
HTMLDivElement,
@@ -438,15 +445,15 @@ const SidebarGroup = React.forwardRef<
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
- )
-})
-SidebarGroup.displayName = "SidebarGroup"
+ );
+});
+SidebarGroup.displayName = "SidebarGroup";
const SidebarGroupLabel = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & { asChild?: boolean }
>(({ className, asChild = false, ...props }, ref) => {
- const Comp = asChild ? Slot : "div"
+ const Comp = asChild ? Slot : "div";
return (
<Comp
@@ -455,19 +462,19 @@ const SidebarGroupLabel = React.forwardRef<
className={cn(
"flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
- className
+ className,
)}
{...props}
/>
- )
-})
-SidebarGroupLabel.displayName = "SidebarGroupLabel"
+ );
+});
+SidebarGroupLabel.displayName = "SidebarGroupLabel";
const SidebarGroupAction = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button"> & { asChild?: boolean }
>(({ className, asChild = false, ...props }, ref) => {
- const Comp = asChild ? Slot : "button"
+ const Comp = asChild ? Slot : "button";
return (
<Comp
@@ -478,13 +485,13 @@ const SidebarGroupAction = React.forwardRef<
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 after:md:hidden",
"group-data-[collapsible=icon]:hidden",
- className
+ className,
)}
{...props}
/>
- )
-})
-SidebarGroupAction.displayName = "SidebarGroupAction"
+ );
+});
+SidebarGroupAction.displayName = "SidebarGroupAction";
const SidebarGroupContent = React.forwardRef<
HTMLDivElement,
@@ -496,8 +503,8 @@ const SidebarGroupContent = React.forwardRef<
className={cn("w-full text-sm", className)}
{...props}
/>
-))
-SidebarGroupContent.displayName = "SidebarGroupContent"
+));
+SidebarGroupContent.displayName = "SidebarGroupContent";
const SidebarMenu = React.forwardRef<
HTMLUListElement,
@@ -509,8 +516,8 @@ const SidebarMenu = React.forwardRef<
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
-))
-SidebarMenu.displayName = "SidebarMenu"
+));
+SidebarMenu.displayName = "SidebarMenu";
const SidebarMenuItem = React.forwardRef<
HTMLLIElement,
@@ -522,8 +529,8 @@ const SidebarMenuItem = React.forwardRef<
className={cn("group/menu-item relative", className)}
{...props}
/>
-))
-SidebarMenuItem.displayName = "SidebarMenuItem"
+));
+SidebarMenuItem.displayName = "SidebarMenuItem";
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
@@ -544,15 +551,15 @@ const sidebarMenuButtonVariants = cva(
variant: "default",
size: "default",
},
- }
-)
+ },
+);
const SidebarMenuButton = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button"> & {
- asChild?: boolean
- isActive?: boolean
- tooltip?: string | React.ComponentProps<typeof TooltipContent>
+ asChild?: boolean;
+ isActive?: boolean;
+ tooltip?: string | React.ComponentProps<typeof TooltipContent>;
} & VariantProps<typeof sidebarMenuButtonVariants>
>(
(
@@ -565,10 +572,10 @@ const SidebarMenuButton = React.forwardRef<
className,
...props
},
- ref
+ ref,
) => {
- const Comp = asChild ? Slot : "button"
- const { isMobile, state } = useSidebar()
+ const Comp = asChild ? Slot : "button";
+ const { isMobile, state } = useSidebar();
const button = (
<Comp
@@ -579,16 +586,16 @@ const SidebarMenuButton = React.forwardRef<
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
- )
+ );
if (!tooltip) {
- return button
+ return button;
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
- }
+ };
}
return (
@@ -601,19 +608,19 @@ const SidebarMenuButton = React.forwardRef<
{...tooltip}
/>
</Tooltip>
- )
- }
-)
-SidebarMenuButton.displayName = "SidebarMenuButton"
+ );
+ },
+);
+SidebarMenuButton.displayName = "SidebarMenuButton";
const SidebarMenuAction = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button"> & {
- asChild?: boolean
- showOnHover?: boolean
+ asChild?: boolean;
+ showOnHover?: boolean;
}
>(({ className, asChild = false, showOnHover = false, ...props }, ref) => {
- const Comp = asChild ? Slot : "button"
+ const Comp = asChild ? Slot : "button";
return (
<Comp
@@ -629,13 +636,13 @@ const SidebarMenuAction = React.forwardRef<
"group-data-[collapsible=icon]:hidden",
showOnHover &&
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
- className
+ className,
)}
{...props}
/>
- )
-})
-SidebarMenuAction.displayName = "SidebarMenuAction"
+ );
+});
+SidebarMenuAction.displayName = "SidebarMenuAction";
const SidebarMenuBadge = React.forwardRef<
HTMLDivElement,
@@ -651,23 +658,23 @@ const SidebarMenuBadge = React.forwardRef<
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
- className
+ className,
)}
{...props}
/>
-))
-SidebarMenuBadge.displayName = "SidebarMenuBadge"
+));
+SidebarMenuBadge.displayName = "SidebarMenuBadge";
const SidebarMenuSkeleton = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
- showIcon?: boolean
+ showIcon?: boolean;
}
>(({ className, showIcon = false, ...props }, ref) => {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
- return `${Math.floor(Math.random() * 40) + 50}%`
- }, [])
+ return `${Math.floor(Math.random() * 40) + 50}%`;
+ }, []);
return (
<div
@@ -692,9 +699,9 @@ const SidebarMenuSkeleton = React.forwardRef<
}
/>
</div>
- )
-})
-SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton"
+ );
+});
+SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton";
const SidebarMenuSub = React.forwardRef<
HTMLUListElement,
@@ -706,28 +713,28 @@ const SidebarMenuSub = React.forwardRef<
className={cn(
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
- className
+ className,
)}
{...props}
/>
-))
-SidebarMenuSub.displayName = "SidebarMenuSub"
+));
+SidebarMenuSub.displayName = "SidebarMenuSub";
const SidebarMenuSubItem = React.forwardRef<
HTMLLIElement,
React.ComponentProps<"li">
->(({ ...props }, ref) => <li ref={ref} {...props} />)
-SidebarMenuSubItem.displayName = "SidebarMenuSubItem"
+>(({ ...props }, ref) => <li ref={ref} {...props} />);
+SidebarMenuSubItem.displayName = "SidebarMenuSubItem";
const SidebarMenuSubButton = React.forwardRef<
HTMLAnchorElement,
React.ComponentProps<"a"> & {
- asChild?: boolean
- size?: "sm" | "md"
- isActive?: boolean
+ asChild?: boolean;
+ size?: "sm" | "md";
+ isActive?: boolean;
}
>(({ asChild = false, size = "md", isActive, className, ...props }, ref) => {
- const Comp = asChild ? Slot : "a"
+ const Comp = asChild ? Slot : "a";
return (
<Comp
@@ -741,13 +748,13 @@ const SidebarMenuSubButton = React.forwardRef<
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
- className
+ className,
)}
{...props}
/>
- )
-})
-SidebarMenuSubButton.displayName = "SidebarMenuSubButton"
+ );
+});
+SidebarMenuSubButton.displayName = "SidebarMenuSubButton";
export {
Sidebar,
@@ -774,4 +781,4 @@ export {
SidebarSeparator,
SidebarTrigger,
useSidebar,
-}
+};
diff --git a/frontend/components/ui/skeleton.tsx b/frontend/components/ui/skeleton.tsx
index c5c1274c5..2cdf440dc 100644
--- a/frontend/components/ui/skeleton.tsx
+++ b/frontend/components/ui/skeleton.tsx
@@ -1,15 +1,15 @@
import { cn } from "@/lib/utils";
function Skeleton({
- className,
- ...props
+ className,
+ ...props
}: React.HTMLAttributes<HTMLDivElement>) {
- return (
- <div
- className={cn("animate-pulse rounded-md bg-muted", className)}
- {...props}
- />
- );
+ return (
+ <div
+ className={cn("animate-pulse rounded-md bg-muted", className)}
+ {...props}
+ />
+ );
}
export { Skeleton };
diff --git a/frontend/components/ui/slider.tsx b/frontend/components/ui/slider.tsx
index d36ab754e..e12cab8ad 100644
--- a/frontend/components/ui/slider.tsx
+++ b/frontend/components/ui/slider.tsx
@@ -1,7 +1,7 @@
"use client";
-import * as React from "react";
import * as SliderPrimitive from "@radix-ui/react-slider";
+import * as React from "react";
import { cn } from "@/lib/utils";
diff --git a/frontend/contexts/auth-context.tsx b/frontend/contexts/auth-context.tsx
index 0bdd6688a..004045314 100644
--- a/frontend/contexts/auth-context.tsx
+++ b/frontend/contexts/auth-context.tsx
@@ -2,11 +2,11 @@
import React, {
createContext,
+ ReactNode,
+ useCallback,
useContext,
- useState,
useEffect,
- useCallback,
- ReactNode,
+ useState,
} from "react";
interface User {
diff --git a/frontend/contexts/chat-context.tsx b/frontend/contexts/chat-context.tsx
index 5803cde40..10147a3db 100644
--- a/frontend/contexts/chat-context.tsx
+++ b/frontend/contexts/chat-context.tsx
@@ -79,7 +79,10 @@ interface ChatContextType {
setConversationLoaded: (loaded: boolean) => void;
conversationFilter: KnowledgeFilter | null;
// responseId: undefined = use currentConversationId, null = don't save to localStorage
- setConversationFilter: (filter: KnowledgeFilter | null, responseId?: string | null) => void;
+ setConversationFilter: (
+ filter: KnowledgeFilter | null,
+ responseId?: string | null,
+ ) => void;
hasChatError: boolean;
setChatError: (hasError: boolean) => void;
isOnboardingComplete: boolean;
@@ -114,10 +117,10 @@ export function ChatProvider({ children }: ChatProviderProps) {
const [conversationFilter, setConversationFilterState] =
useState<KnowledgeFilter | null>(null);
const [hasChatError, setChatError] = useState(false);
-
+
// Get settings to check if onboarding was completed (settings.edited)
const { data: settings } = useGetSettingsQuery();
-
+
// Check if onboarding is complete
// Onboarding is complete if:
// 1. settings.edited is true (backend confirms onboarding was completed)
@@ -212,7 +215,9 @@ export function ChatProvider({ children }: ChatProviderProps) {
if (isDifferentConversation && typeof window !== "undefined") {
// Try to load the saved filter from localStorage
- const savedFilterId = localStorage.getItem(`conversation_filter_${conversation.response_id}`);
+ const savedFilterId = localStorage.getItem(
+ `conversation_filter_${conversation.response_id}`,
+ );
console.log("[CONVERSATION] Looking for filter:", {
conversationId: conversation.response_id,
savedFilterId,
@@ -220,12 +225,18 @@ export function ChatProvider({ children }: ChatProviderProps) {
if (savedFilterId) {
// Import getFilterById dynamically to avoid circular dependency
- const { getFilterById } = await import("@/app/api/queries/useGetFilterByIdQuery");
+ const { getFilterById } = await import(
+ "@/app/api/queries/useGetFilterByIdQuery"
+ );
try {
const filter = await getFilterById(savedFilterId);
if (filter) {
- console.log("[CONVERSATION] Loaded filter:", filter.name, filter.id);
+ console.log(
+ "[CONVERSATION] Loaded filter:",
+ filter.name,
+ filter.id,
+ );
setConversationFilterState(filter);
// Update conversation data with the loaded filter
setConversationData((prev) => {
@@ -236,7 +247,9 @@ export function ChatProvider({ children }: ChatProviderProps) {
} catch (error) {
console.error("[CONVERSATION] Failed to load filter:", error);
// Filter was deleted, clean up localStorage
- localStorage.removeItem(`conversation_filter_${conversation.response_id}`);
+ localStorage.removeItem(
+ `conversation_filter_${conversation.response_id}`,
+ );
setConversationFilterState(null);
}
} else {
@@ -260,8 +273,9 @@ export function ChatProvider({ children }: ChatProviderProps) {
// Check if there's existing conversation data - if so, this is a manual "new conversation" action
// Check state values before clearing them
- const hasExistingConversation = conversationData !== null || placeholderConversation !== null;
-
+ const hasExistingConversation =
+ conversationData !== null || placeholderConversation !== null;
+
// Clear current conversation data and reset state
setCurrentConversationId(null);
setPreviousResponseIds({ chat: null, langflow: null });
@@ -271,7 +285,9 @@ export function ChatProvider({ children }: ChatProviderProps) {
// Load default filter if available (and clear it after first use)
if (typeof window !== "undefined") {
- const defaultFilterId = localStorage.getItem("default_conversation_filter_id");
+ const defaultFilterId = localStorage.getItem(
+ "default_conversation_filter_id",
+ );
console.log("[CONVERSATION] Default filter ID:", defaultFilterId);
if (defaultFilterId) {
@@ -280,11 +296,17 @@ export function ChatProvider({ children }: ChatProviderProps) {
console.log("[CONVERSATION] Cleared default filter (used once)");
try {
- const { getFilterById } = await import("@/app/api/queries/useGetFilterByIdQuery");
+ const { getFilterById } = await import(
+ "@/app/api/queries/useGetFilterByIdQuery"
+ );
const filter = await getFilterById(defaultFilterId);
if (filter) {
- console.log("[CONVERSATION] Loaded default filter:", filter.name, filter.id);
+ console.log(
+ "[CONVERSATION] Loaded default filter:",
+ filter.name,
+ filter.id,
+ );
setConversationFilterState(filter);
} else {
// Default filter was deleted
@@ -298,12 +320,16 @@ export function ChatProvider({ children }: ChatProviderProps) {
// No default filter in localStorage
if (hasExistingConversation) {
// User is manually starting a new conversation - clear the filter
- console.log("[CONVERSATION] Manual new conversation - clearing filter");
+ console.log(
+ "[CONVERSATION] Manual new conversation - clearing filter",
+ );
setConversationFilterState(null);
} else {
// First time after onboarding - preserve existing filter if set
// This prevents clearing the filter when startNewConversation is called multiple times during onboarding
- console.log("[CONVERSATION] No default filter set, preserving existing filter if any");
+ console.log(
+ "[CONVERSATION] No default filter set, preserving existing filter if any",
+ );
// Don't clear the filter - it may have been set by storeDefaultFilterForNewConversations
}
}
@@ -328,7 +354,12 @@ export function ChatProvider({ children }: ChatProviderProps) {
setPlaceholderConversation(newPlaceholderConversation);
// Force immediate refresh to ensure sidebar shows correct state
refreshConversations(true);
- }, [endpoint, refreshConversations, conversationData, placeholderConversation]);
+ }, [
+ endpoint,
+ refreshConversations,
+ conversationData,
+ placeholderConversation,
+ ]);
const addConversationDoc = useCallback((filename: string) => {
setConversationDocs((prev) => [
@@ -374,7 +405,8 @@ export function ChatProvider({ children }: ChatProviderProps) {
// - undefined: use currentConversationId (default behavior)
// - null: explicitly skip saving to localStorage
// - string: use the provided responseId
- const targetId = responseId === undefined ? currentConversationId : responseId;
+ const targetId =
+ responseId === undefined ? currentConversationId : responseId;
// Save filter association for the target conversation
if (typeof window !== "undefined" && targetId) {
diff --git a/frontend/contexts/knowledge-filter-context.tsx b/frontend/contexts/knowledge-filter-context.tsx
index 6740af2a5..a05380327 100644
--- a/frontend/contexts/knowledge-filter-context.tsx
+++ b/frontend/contexts/knowledge-filter-context.tsx
@@ -1,6 +1,5 @@
"use client";
-import { FilterColor, IconKey } from "@/components/filter-icon-popover";
import React, {
createContext,
type ReactNode,
@@ -9,6 +8,7 @@ import React, {
useEffect,
useState,
} from "react";
+import { FilterColor, IconKey } from "@/components/filter-icon-popover";
interface KnowledgeFilter {
id: string;
diff --git a/frontend/contexts/task-context.tsx b/frontend/contexts/task-context.tsx
index 9f2fe90df..3ac3aee90 100644
--- a/frontend/contexts/task-context.tsx
+++ b/frontend/contexts/task-context.tsx
@@ -12,12 +12,12 @@ import {
} from "react";
import { toast } from "sonner";
import { useCancelTaskMutation } from "@/app/api/mutations/useCancelTaskMutation";
+import { useGetSettingsQuery } from "@/app/api/queries/useGetSettingsQuery";
import {
type Task,
type TaskFileEntry,
useGetTasksQuery,
} from "@/app/api/queries/useGetTasksQuery";
-import { useGetSettingsQuery } from "@/app/api/queries/useGetSettingsQuery";
import { useAuth } from "@/contexts/auth-context";
// Task interface is now imported from useGetTasksQuery
diff --git a/frontend/eslint.config.mjs b/frontend/eslint.config.mjs
index 5e2dc2761..a7a8de03b 100644
--- a/frontend/eslint.config.mjs
+++ b/frontend/eslint.config.mjs
@@ -1,6 +1,6 @@
+import { FlatCompat } from "@eslint/eslintrc";
import { dirname } from "path";
import { fileURLToPath } from "url";
-import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -9,15 +9,6 @@ const compat = new FlatCompat({
baseDirectory: __dirname,
});
-const eslintConfig = [
- ...compat.extends("next/core-web-vitals", "next/typescript"),
- {
- rules: {
- "@typescript-eslint/no-unused-vars": "warn",
- "@typescript-eslint/no-explicit-any": "off",
- "react-hooks/exhaustive-deps": "off",
- },
- },
-];
+const eslintConfig = [...compat.extends("next/core-web-vitals")];
export default eslintConfig;
diff --git a/frontend/hooks/use-mobile.tsx b/frontend/hooks/use-mobile.tsx
index 2b0fe1dfe..a93d58393 100644
--- a/frontend/hooks/use-mobile.tsx
+++ b/frontend/hooks/use-mobile.tsx
@@ -1,19 +1,21 @@
-import * as React from "react"
+import * as React from "react";
-const MOBILE_BREAKPOINT = 768
+const MOBILE_BREAKPOINT = 768;
export function useIsMobile() {
- const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
+ const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
+ undefined,
+ );
React.useEffect(() => {
- const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
+ const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => {
- setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
- }
- mql.addEventListener("change", onChange)
- setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
- return () => mql.removeEventListener("change", onChange)
- }, [])
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
+ };
+ mql.addEventListener("change", onChange);
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
+ return () => mql.removeEventListener("change", onChange);
+ }, []);
- return !!isMobile
+ return !!isMobile;
}
diff --git a/frontend/hooks/useChatStreaming.ts b/frontend/hooks/useChatStreaming.ts
index 6d19ac086..13144e910 100644
--- a/frontend/hooks/useChatStreaming.ts
+++ b/frontend/hooks/useChatStreaming.ts
@@ -101,7 +101,10 @@ export function useChatStreaming({
requestBody.filter_id = filter_id;
}
- console.log("[useChatStreaming] Sending request:", { filter_id, requestBody });
+ console.log("[useChatStreaming] Sending request:", {
+ filter_id,
+ requestBody,
+ });
const response = await fetch(endpoint, {
method: "POST",
@@ -164,18 +167,23 @@ export function useChatStreaming({
if (line.trim()) {
try {
const chunk = JSON.parse(line);
-
+
// Investigation logging for Granite 3.3 8b tool call detection
const chunkKeys = Object.keys(chunk);
- const toolRelatedKeys = chunkKeys.filter(key =>
- key.toLowerCase().includes('tool') ||
- key.toLowerCase().includes('call') ||
- key.toLowerCase().includes('retrieval') ||
- key.toLowerCase().includes('function') ||
- key.toLowerCase().includes('result')
+ const toolRelatedKeys = chunkKeys.filter(
+ (key) =>
+ key.toLowerCase().includes("tool") ||
+ key.toLowerCase().includes("call") ||
+ key.toLowerCase().includes("retrieval") ||
+ key.toLowerCase().includes("function") ||
+ key.toLowerCase().includes("result"),
);
if (toolRelatedKeys.length > 0) {
- console.log('[Tool Detection] Found tool-related keys:', toolRelatedKeys, chunk);
+ console.log(
+ "[Tool Detection] Found tool-related keys:",
+ toolRelatedKeys,
+ chunk,
+ );
}
// Extract response ID if present
@@ -451,7 +459,10 @@ export function useChatStreaming({
currentContent += chunk.delta || "";
}
// Handle response.completed event - capture usage
- else if (chunk.type === "response.completed" && chunk.response?.usage) {
+ else if (
+ chunk.type === "response.completed" &&
+ chunk.response?.usage
+ ) {
usageData = chunk.response.usage;
}
// Handle OpenRAG backend format
@@ -468,32 +479,43 @@ export function useChatStreaming({
}
}
}
-
+
// Heuristic detection for implicit tool calls (Granite 3.3 8b workaround)
// Check if chunk contains retrieval results without explicit tool call markers
- const hasImplicitToolCall = (
+ const hasImplicitToolCall =
// Check for various result indicators in the chunk
- (chunk.results && Array.isArray(chunk.results) && chunk.results.length > 0) ||
- (chunk.outputs && Array.isArray(chunk.outputs) && chunk.outputs.length > 0) ||
+ (chunk.results &&
+ Array.isArray(chunk.results) &&
+ chunk.results.length > 0) ||
+ (chunk.outputs &&
+ Array.isArray(chunk.outputs) &&
+ chunk.outputs.length > 0) ||
// Check for retrieval-related fields
chunk.retrieved_documents ||
chunk.retrieval_results ||
// Check for nested data structures that might contain results
- (chunk.data && typeof chunk.data === 'object' && (
- chunk.data.results ||
- chunk.data.retrieved_documents ||
- chunk.data.retrieval_results
- ))
- );
-
+ (chunk.data &&
+ typeof chunk.data === "object" &&
+ (chunk.data.results ||
+ chunk.data.retrieved_documents ||
+ chunk.data.retrieval_results));
+
if (hasImplicitToolCall && currentFunctionCalls.length === 0) {
- console.log('[Heuristic Detection] Detected implicit tool call:', chunk);
-
+ console.log(
+ "[Heuristic Detection] Detected implicit tool call:",
+ chunk,
+ );
+
// Create a synthetic function call for the UI
- const results = chunk.results || chunk.outputs || chunk.retrieved_documents ||
- chunk.retrieval_results || chunk.data?.results ||
- chunk.data?.retrieved_documents || [];
-
+ const results =
+ chunk.results ||
+ chunk.outputs ||
+ chunk.retrieved_documents ||
+ chunk.retrieval_results ||
+ chunk.data?.results ||
+ chunk.data?.retrieved_documents ||
+ [];
+
const syntheticFunctionCall: FunctionCall = {
name: "Retrieval",
arguments: { implicit: true, detected_heuristically: true },
@@ -502,7 +524,9 @@ export function useChatStreaming({
result: results,
};
currentFunctionCalls.push(syntheticFunctionCall);
- console.log('[Heuristic Detection] Created synthetic function call');
+ console.log(
+ "[Heuristic Detection] Created synthetic function call",
+ );
}
// Update streaming message in real-time
@@ -541,22 +565,30 @@ export function useChatStreaming({
"No response received from the server. Please try again.",
);
}
-
+
// Post-processing: Heuristic detection based on final content
// If no explicit tool calls detected but content shows RAG indicators
if (currentFunctionCalls.length === 0 && currentContent) {
// Check for citation patterns that indicate RAG usage
- const hasCitations = /\(Source:|\[Source:|\bSource:|filename:|document:/i.test(currentContent);
+ const hasCitations =
+ /\(Source:|\[Source:|\bSource:|filename:|document:/i.test(
+ currentContent,
+ );
// Check for common RAG response patterns
- const hasRAGPattern = /based on.*(?:document|file|information|data)|according to.*(?:document|file)/i.test(currentContent);
-
+ const hasRAGPattern =
+ /based on.*(?:document|file|information|data)|according to.*(?:document|file)/i.test(
+ currentContent,
+ );
+
if (hasCitations || hasRAGPattern) {
- console.log('[Post-Processing] Detected RAG usage from content patterns');
+ console.log(
+ "[Post-Processing] Detected RAG usage from content patterns",
+ );
const syntheticFunctionCall: FunctionCall = {
name: "Retrieval",
- arguments: {
- implicit: true,
- detected_from: hasCitations ? "citations" : "content_patterns"
+ arguments: {
+ implicit: true,
+ detected_from: hasCitations ? "citations" : "content_patterns",
},
status: "completed",
type: "retrieval_call",
diff --git a/frontend/knip.config.ts b/frontend/knip.config.ts
index 4606d4204..f5b562597 100644
--- a/frontend/knip.config.ts
+++ b/frontend/knip.config.ts
@@ -1,18 +1,9 @@
-import type { KnipConfig } from 'knip';
+import type { KnipConfig } from "knip";
const config: KnipConfig = {
- entry: [
- 'app/**/*.{ts,tsx}',
- 'next.config.ts',
- ],
- project: ['**/*.{ts,tsx}'],
- ignore: [
- '**/*.d.ts',
- '**/node_modules/**',
- '.next/**',
- 'public/**',
- ],
+ entry: ["app/**/*.{ts,tsx}", "next.config.ts"],
+ project: ["**/*.{ts,tsx}"],
+ ignore: ["**/*.d.ts", "**/node_modules/**", ".next/**", "public/**"],
};
export default config;
-
diff --git a/frontend/lib/debounce.ts b/frontend/lib/debounce.ts
index d2e70441f..6fed65f3c 100644
--- a/frontend/lib/debounce.ts
+++ b/frontend/lib/debounce.ts
@@ -1,4 +1,4 @@
-import { useCallback, useRef, useState, useEffect } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
export function useDebounce<T extends (...args: never[]) => void>(
callback: T,
diff --git a/frontend/lib/format-files-to-delete.tsx b/frontend/lib/format-files-to-delete.tsx
index d8ce474c8..5ebb79904 100644
--- a/frontend/lib/format-files-to-delete.tsx
+++ b/frontend/lib/format-files-to-delete.tsx
@@ -8,10 +8,19 @@ export function formatFilesToDelete(
const remainingCount = files.length - maxVisible;
return (
<ul className="list-disc list-inside max-w-[29rem] sm:max-w-[calc(425px-3rem)]">
- {visibleFiles.map((file) => <li key={file.filename} className="my-2 truncate">{file.filename}</li>)}
- {remainingCount > 0 ? <li>&hellip; and {remainingCount} more document{
- remainingCount > 1 ? "s" : ""
- }</li> : "" }
+ {visibleFiles.map((file) => (
+ <li key={file.filename} className="my-2 truncate">
+ {file.filename}
+ </li>
+ ))}
+ {remainingCount > 0 ? (
+ <li>
+ &hellip; and {remainingCount} more document
+ {remainingCount > 1 ? "s" : ""}
+ </li>
+ ) : (
+ ""
+ )}
</ul>
);
}
diff --git a/frontend/lib/upload-utils.ts b/frontend/lib/upload-utils.ts
index 04e5dfa9d..8d11a33d8 100644
--- a/frontend/lib/upload-utils.ts
+++ b/frontend/lib/upload-utils.ts
@@ -227,8 +227,7 @@ export async function uploadFile(
const shouldCreateFilter = (uploadIngestJson as { create_filter?: boolean })
.create_filter;
- const filename = (uploadIngestJson as { filename?: string })
- .filename;
+ const filename = (uploadIngestJson as { filename?: string }).filename;
const result: UploadFileResult = {
fileId,
diff --git a/frontend/lib/utils.ts b/frontend/lib/utils.ts
index 98480f3d0..13855578b 100644
--- a/frontend/lib/utils.ts
+++ b/frontend/lib/utils.ts
@@ -1,4 +1,4 @@
-import { clsx, type ClassValue } from "clsx";
+import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
diff --git a/frontend/next.config.ts b/frontend/next.config.ts
index a9d95bba5..c40c0c133 100644
--- a/frontend/next.config.ts
+++ b/frontend/next.config.ts
@@ -1,5 +1,5 @@
-import type { NextConfig } from "next";
import dotenv from "dotenv";
+import type { NextConfig } from "next";
import path from "path";
// Load environment variables from root .env file
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index bdb24b680..b63e210ed 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -54,7 +54,6 @@
},
"devDependencies": {
"@biomejs/biome": "2.3.5",
- "@eslint/eslintrc": "^3",
"@playwright/test": "^1.57.0",
"@types/node": "^20",
"@types/react": "^19",
@@ -284,30 +283,6 @@
"tslib": "^2.4.0"
}
},
- "node_modules/@eslint/eslintrc": {
- "version": "3.3.1",
- "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.1.tgz",
- "integrity": "sha512-gtF186CXhIl1p4pJNGZw8Yc6RlshoePRvE0X91oPGb3vZ8pM3qOS9W9NGPat9LziaBV7XrJWGylNQXkGcnM3IQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "ajv": "^6.12.4",
- "debug": "^4.3.2",
- "espree": "^10.0.1",
- "globals": "^14.0.0",
- "ignore": "^5.2.0",
- "import-fresh": "^3.2.1",
- "js-yaml": "^4.1.0",
- "minimatch": "^3.1.2",
- "strip-json-comments": "^3.1.1"
- },
- "engines": {
- "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
- },
- "funding": {
- "url": "https://opencollective.com/eslint"
- }
- },
"node_modules/@floating-ui/core": {
"version": "1.7.3",
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.3.tgz",
@@ -1301,7 +1276,6 @@
"integrity": "sha512-6TyEnHgd6SArQO8UO2OMTxshln3QMWBtPGrOCgs3wVEmQmwyuNtB10IZMfmYDE0riwNR1cu4q+pPcxMVtaG3TA==",
"devOptional": true,
"license": "Apache-2.0",
- "peer": true,
"dependencies": {
"playwright": "1.57.0"
},
@@ -2553,7 +2527,6 @@
"integrity": "sha512-yCAeZl7a0DxgNVteXFHt9+uyFbqXGy/ShC4BlcHkoE0AfGXYv/BUiplV72DjMYXHDBXFjhvr6DD1NiRVfB4j8g==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"undici-types": "~6.21.0"
}
@@ -2569,7 +2542,6 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.12.tgz",
"integrity": "sha512-cMoR+FoAf/Jyq6+Df2/Z41jISvGZZ2eTlnsaJRptmZ76Caldwy1odD4xTr/gNV9VLj0AWgg/nmkevIyUfIIq5w==",
"license": "MIT",
- "peer": true,
"dependencies": {
"csstype": "^3.0.2"
}
@@ -2580,7 +2552,6 @@
"integrity": "sha512-qXRuZaOsAdXKFyOhRBg6Lqqc0yay13vN7KrIg4L7N4aaHN68ma9OK3NE1BoDFgFOTfM7zg+3/8+2n8rLUH3OKQ==",
"devOptional": true,
"license": "MIT",
- "peer": true,
"peerDependencies": {
"@types/react": "^19.0.0"
}
@@ -2614,30 +2585,6 @@
"node": ">=14.6"
}
},
- "node_modules/acorn": {
- "version": "8.15.0",
- "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
- "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
- "dev": true,
- "license": "MIT",
- "peer": true,
- "bin": {
- "acorn": "bin/acorn"
- },
- "engines": {
- "node": ">=0.4.0"
- }
- },
- "node_modules/acorn-jsx": {
- "version": "5.3.2",
- "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
- "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
- "dev": true,
- "license": "MIT",
- "peerDependencies": {
- "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
- }
- },
"node_modules/ag-charts-types": {
"version": "12.2.0",
"resolved": "https://registry.npmjs.org/ag-charts-types/-/ag-charts-types-12.2.0.tgz",
@@ -2664,23 +2611,6 @@
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
- "node_modules/ajv": {
- "version": "6.12.6",
- "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
- "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "fast-deep-equal": "^3.1.1",
- "fast-json-stable-stringify": "^2.0.0",
- "json-schema-traverse": "^0.4.1",
- "uri-js": "^4.2.2"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/epoberezkin"
- }
- },
"node_modules/ansi-regex": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
@@ -2826,17 +2756,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/brace-expansion": {
- "version": "1.1.12",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
- "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "balanced-match": "^1.0.0",
- "concat-map": "0.0.1"
- }
- },
"node_modules/braces": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
@@ -2869,7 +2788,6 @@
}
],
"license": "MIT",
- "peer": true,
"dependencies": {
"caniuse-lite": "^1.0.30001737",
"electron-to-chromium": "^1.5.211",
@@ -2883,16 +2801,6 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
- "node_modules/callsites": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
- "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=6"
- }
- },
"node_modules/camelcase-css": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz",
@@ -3102,13 +3010,6 @@
"node": ">=18"
}
},
- "node_modules/concat-map": {
- "version": "0.0.1",
- "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
- "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -3282,19 +3183,6 @@
"node": ">=6"
}
},
- "node_modules/eslint-visitor-keys": {
- "version": "4.2.1",
- "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz",
- "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==",
- "dev": true,
- "license": "Apache-2.0",
- "engines": {
- "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
- },
- "funding": {
- "url": "https://opencollective.com/eslint"
- }
- },
"node_modules/esm": {
"version": "3.2.25",
"resolved": "https://registry.npmjs.org/esm/-/esm-3.2.25.tgz",
@@ -3304,24 +3192,6 @@
"node": ">=6"
}
},
- "node_modules/espree": {
- "version": "10.4.0",
- "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz",
- "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==",
- "dev": true,
- "license": "BSD-2-Clause",
- "dependencies": {
- "acorn": "^8.15.0",
- "acorn-jsx": "^5.3.2",
- "eslint-visitor-keys": "^4.2.1"
- },
- "engines": {
- "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
- },
- "funding": {
- "url": "https://opencollective.com/eslint"
- }
- },
"node_modules/estree-util-is-identifier-name": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz",
@@ -3337,20 +3207,6 @@
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
"license": "MIT"
},
- "node_modules/fast-deep-equal": {
- "version": "3.1.3",
- "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
- "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/fast-json-stable-stringify": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
- "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/fastq": {
"version": "1.19.1",
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz",
@@ -3584,19 +3440,6 @@
"url": "https://github.com/sponsors/isaacs"
}
},
- "node_modules/globals": {
- "version": "14.0.0",
- "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",
- "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=18"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
@@ -3827,33 +3670,6 @@
"url": "https://github.com/sponsors/wooorm"
}
},
- "node_modules/ignore": {
- "version": "5.3.2",
- "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
- "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 4"
- }
- },
- "node_modules/import-fresh": {
- "version": "3.3.1",
- "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
- "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "parent-module": "^1.0.0",
- "resolve-from": "^4.0.0"
- },
- "engines": {
- "node": ">=6"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
"node_modules/inline-style-parser": {
"version": "0.2.4",
"resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.4.tgz",
@@ -4037,13 +3853,6 @@
"js-yaml": "bin/js-yaml.js"
}
},
- "node_modules/json-schema-traverse": {
- "version": "0.4.1",
- "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
- "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/knip": {
"version": "5.73.1",
"resolved": "https://registry.npmjs.org/knip/-/knip-5.73.1.tgz",
@@ -5114,19 +4923,6 @@
"mini-svg-data-uri": "cli.js"
}
},
- "node_modules/minimatch": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
- "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
- "dev": true,
- "license": "ISC",
- "dependencies": {
- "brace-expansion": "^1.1.7"
- },
- "engines": {
- "node": "*"
- }
- },
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
@@ -5400,19 +5196,6 @@
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
"license": "BlueOak-1.0.0"
},
- "node_modules/parent-module": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
- "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "callsites": "^3.0.0"
- },
- "engines": {
- "node": ">=6"
- }
- },
"node_modules/parse-entities": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",
@@ -5576,7 +5359,6 @@
}
],
"license": "MIT",
- "peer": true,
"dependencies": {
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
@@ -5708,16 +5490,6 @@
"url": "https://github.com/sponsors/wooorm"
}
},
- "node_modules/punycode": {
- "version": "2.3.1",
- "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
- "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=6"
- }
- },
"node_modules/queue-microtask": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
@@ -5743,7 +5515,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.1.1.tgz",
"integrity": "sha512-w8nqGImo45dmMIfljjMwOGtbmC/mk4CMYhWIicdSflH91J9TyCyczcPFXJzrZ/ZXcgGRFeP6BU0BEJTw6tZdfQ==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -5753,7 +5524,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.1.1.tgz",
"integrity": "sha512-Dlq/5LAZgF0Gaz6yiqZCf6VCcZs1ghAJyrsu84Q/GT0gV+mCxbfmKNoGRKBYMJ8IEdGPqu49YWXD02GCknEDkw==",
"license": "MIT",
- "peer": true,
"dependencies": {
"scheduler": "^0.26.0"
},
@@ -6082,16 +5852,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/resolve-from": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
- "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=4"
- }
- },
"node_modules/reusify": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
@@ -6395,19 +6155,6 @@
"node": ">=8"
}
},
- "node_modules/strip-json-comments": {
- "version": "3.1.1",
- "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
- "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=8"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
"node_modules/style-to-js": {
"version": "1.1.17",
"resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.17.tgz",
@@ -6505,7 +6252,6 @@
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
"license": "MIT",
- "peer": true,
"dependencies": {
"@alloc/quick-lru": "^5.2.0",
"arg": "^5.0.2",
@@ -6693,7 +6439,6 @@
"integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==",
"dev": true,
"license": "Apache-2.0",
- "peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -6869,16 +6614,6 @@
"browserslist": ">= 4.21.0"
}
},
- "node_modules/uri-js": {
- "version": "4.4.1",
- "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
- "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
- "dev": true,
- "license": "BSD-2-Clause",
- "dependencies": {
- "punycode": "^2.1.0"
- }
- },
"node_modules/use-callback-ref": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index 226ca35a0..45ebc111a 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -9,10 +9,11 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
- "lint": "next lint",
- "check-format": "npx @biomejs/biome check",
- "format": "npx @biomejs/biome format --write",
- "knip": "knip"
+ "lint": "biome check && next lint",
+ "lint:fix": "biome check --write",
+ "format": "biome format --write",
+ "knip": "knip",
+ "prepare": "cd .. && npx husky frontend/.husky || true"
},
"dependencies": {
"@radix-ui/react-accordion": "^1.2.12",
@@ -62,6 +63,8 @@
"devDependencies": {
"@biomejs/biome": "2.3.5",
"@eslint/eslintrc": "^3",
+ "husky": "^9.0.0",
+ "lint-staged": "^15.0.0",
"@playwright/test": "^1.57.0",
"@types/node": "^20",
"@types/react": "^19",
@@ -72,5 +75,8 @@
"postcss": "^8.5.6",
"tailwindcss": "^3.4.17",
"typescript": "^5"
+ },
+ "lint-staged": {
+ "**/*.{js,ts,jsx,tsx,json,jsonc,css}": "biome check --write --files-ignore-unknown=true"
}
}
diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts
index e6c8118fb..1e36343d7 100644
--- a/frontend/playwright.config.ts
+++ b/frontend/playwright.config.ts
@@ -15,7 +15,7 @@ export default defineConfig({
workers: process.env.CI ? 1 : undefined,
reporter: "html",
timeout: 5 * 60 * 1000,
-
+
// Setup hook to run before all tests
use: {
@@ -37,7 +37,7 @@ export default defineConfig({
{
command: "make backend ENV_FILE=frontend/.env.test",
cwd: path.resolve(__dirname, ".."),
- url: "http://127.0.0.1:8000/health",
+ url: "http://127.0.0.1:8000/health",
reuseExistingServer: !process.env.CI,
stdout: "pipe",
stderr: "pipe",
@@ -58,7 +58,8 @@ export default defineConfig({
LANGFLOW_URL: process.env.LANGFLOW_URL || "http://localhost:7860",
LANGFLOW_AUTO_LOGIN: process.env.LANGFLOW_AUTO_LOGIN || "True",
LANGFLOW_SUPERUSER: process.env.LANGFLOW_SUPERUSER || "",
- LANGFLOW_SUPERUSER_PASSWORD: process.env.LANGFLOW_SUPERUSER_PASSWORD || "",
+ LANGFLOW_SUPERUSER_PASSWORD:
+ process.env.LANGFLOW_SUPERUSER_PASSWORD || "",
LANGFLOW_CHAT_FLOW_ID: process.env.LANGFLOW_CHAT_FLOW_ID || "",
LANGFLOW_INGEST_FLOW_ID: process.env.LANGFLOW_INGEST_FLOW_ID || "",
@@ -75,9 +76,10 @@ export default defineConfig({
OLLAMA_BASE_URL: process.env.OLLAMA_BASE_URL || "",
// Ingestion
- DISABLE_INGEST_WITH_LANGFLOW: process.env.DISABLE_INGEST_WITH_LANGFLOW || "false",
+ DISABLE_INGEST_WITH_LANGFLOW:
+ process.env.DISABLE_INGEST_WITH_LANGFLOW || "false",
INGEST_SAMPLE_DATA: process.env.INGEST_SAMPLE_DATA || "true",
- }
+ },
},
{
command: "npm run dev",
@@ -85,9 +87,9 @@ export default defineConfig({
reuseExistingServer: !process.env.CI,
env: {
PORT: String(PORT),
- VITE_PROXY_TARGET: process.env.VITE_PROXY_TARGET || "http://127.0.0.1:8000",
- }
- }
+ VITE_PROXY_TARGET:
+ process.env.VITE_PROXY_TARGET || "http://127.0.0.1:8000",
+ },
+ },
],
});
-
diff --git a/frontend/tailwind.config.ts b/frontend/tailwind.config.ts
index 0adc59bb4..0ab91f16a 100644
--- a/frontend/tailwind.config.ts
+++ b/frontend/tailwind.config.ts
@@ -13,183 +13,174 @@ const config = {
"./app/**/*.{ts,tsx}",
],
theme: {
- container: {
- center: true,
- screens: {
- '2xl': '1400px',
- '3xl': '1500px'
- }
- },
- extend: {
- screens: {
- xl: '1200px',
- '2xl': '1400px',
- '3xl': '1500px'
- },
- keyframes: {
- overlayShow: {
- from: {
- opacity: 0
- },
- to: {
- opacity: 1
- }
- },
- contentShow: {
- from: {
- opacity: 0,
- transform: 'translate(-50%, -50%) scale(0.95)',
- clipPath: 'inset(50% 0)'
- },
- to: {
- opacity: 1,
- transform: 'translate(-50%, -50%) scale(1)',
- clipPath: 'inset(0% 0)'
- }
- },
- wiggle: {
- '0%, 100%': {
- transform: 'scale(100%)'
- },
- '50%': {
- transform: 'scale(120%)'
- }
- },
- 'accordion-down': {
- from: {
- height: '0'
- },
- to: {
- height: 'var(--radix-accordion-content-height)'
- }
- },
- 'accordion-up': {
- from: {
- height: 'var(--radix-accordion-content-height)'
- },
- to: {
- height: '0'
- }
- },
- shimmer: {
- '0%': {
- backgroundPosition: '200% 0'
- },
- '100%': {
- backgroundPosition: '-200% 0'
- }
- }
- },
- animation: {
- overlayShow: 'overlayShow 400ms cubic-bezier(0.16, 1, 0.3, 1)',
- contentShow: 'contentShow 400ms cubic-bezier(0.16, 1, 0.3, 1)',
- wiggle: 'wiggle 150ms ease-in-out 1',
- 'accordion-down': 'accordion-down 0.2s ease-out',
- 'accordion-up': 'accordion-up 0.2s ease-out',
- shimmer: 'shimmer 3s ease-in-out infinite'
- },
- colors: {
- border: 'hsl(var(--border))',
- input: 'hsl(var(--input))',
- ring: 'hsl(var(--ring))',
- background: 'hsl(var(--background))',
- foreground: 'hsl(var(--foreground))',
- primary: {
- DEFAULT: 'hsl(var(--primary))',
- foreground: 'hsl(var(--primary-foreground))',
- hover: 'hsl(var(--primary-hover))'
- },
- secondary: {
- DEFAULT: 'hsl(var(--secondary))',
- foreground: 'hsl(var(--secondary-foreground))',
- hover: 'hsl(var(--secondary-hover))'
- },
- destructive: {
- DEFAULT: 'hsl(var(--destructive))',
- foreground: 'hsl(var(--destructive-foreground))'
- },
- muted: {
- DEFAULT: 'hsl(var(--muted))',
- foreground: 'hsl(var(--muted-foreground))'
- },
- accent: {
- DEFAULT: 'hsl(var(--accent))',
- foreground: 'hsl(var(--accent-foreground))'
- },
- 'accent-emerald': {
- DEFAULT: 'hsl(var(--accent-emerald))',
- foreground: 'hsl(var(--accent-emerald-foreground))'
- },
- 'accent-pink': {
- DEFAULT: 'hsl(var(--accent-pink))',
- foreground: 'hsl(var(--accent-pink-foreground))'
- },
- 'accent-amber': {
- DEFAULT: 'hsl(var(--accent-amber))',
- foreground: 'hsl(var(--accent-amber-foreground))'
- },
- 'accent-purple': {
- DEFAULT: 'hsl(var(--accent-purple))',
- foreground: 'hsl(var(--accent-purple-foreground))'
- },
- 'accent-indigo': {
- DEFAULT: 'hsl(var(--accent-indigo))',
- foreground: 'hsl(var(--accent-indigo-foreground))'
- },
- 'accent-red': {
- DEFAULT: 'hsl(var(--accent-red))',
- foreground: 'hsl(var(--accent-red-foreground))'
- },
- popover: {
- DEFAULT: 'hsl(var(--popover))',
- foreground: 'hsl(var(--popover-foreground))'
- },
- card: {
- DEFAULT: 'hsl(var(--card))',
- foreground: 'hsl(var(--card-foreground))'
- },
- 'component-icon': 'var(--component-icon)',
- 'flow-icon': 'var(--flow-icon)',
- 'placeholder-foreground': 'hsl(var(--placeholder-foreground))',
- warning: {
- DEFAULT: 'hsl(var(--warning))',
- foreground: 'hsl(var(--warning-foreground))'
- },
- sidebar: {
- DEFAULT: 'hsl(var(--sidebar-background))',
- foreground: 'hsl(var(--sidebar-foreground))',
- primary: 'hsl(var(--sidebar-primary))',
- 'primary-foreground': 'hsl(var(--sidebar-primary-foreground))',
- accent: 'hsl(var(--sidebar-accent))',
- 'accent-foreground': 'hsl(var(--sidebar-accent-foreground))',
- border: 'hsl(var(--sidebar-border))',
- ring: 'hsl(var(--sidebar-ring))'
- }
- },
- borderRadius: {
- lg: 'var(--radius)',
- md: 'calc(var(--radius) - 2px)',
- sm: 'calc(var(--radius) - 4px)'
- },
- fontFamily: {
- sans: [
- 'var(--font-sans)',
- ...fontFamily.sans
- ],
- mono: [
- 'var(--font-mono)',
- ...fontFamily.mono
- ],
- chivo: [
- 'var(--font-chivo)',
- ...fontFamily.sans
- ]
- },
- fontSize: {
- xxs: '11px',
- mmd: '13px'
- }
- }
+ container: {
+ center: true,
+ screens: {
+ "2xl": "1400px",
+ "3xl": "1500px",
+ },
+ },
+ extend: {
+ screens: {
+ xl: "1200px",
+ "2xl": "1400px",
+ "3xl": "1500px",
+ },
+ keyframes: {
+ overlayShow: {
+ from: {
+ opacity: 0,
+ },
+ to: {
+ opacity: 1,
+ },
+ },
+ contentShow: {
+ from: {
+ opacity: 0,
+ transform: "translate(-50%, -50%) scale(0.95)",
+ clipPath: "inset(50% 0)",
+ },
+ to: {
+ opacity: 1,
+ transform: "translate(-50%, -50%) scale(1)",
+ clipPath: "inset(0% 0)",
+ },
+ },
+ wiggle: {
+ "0%, 100%": {
+ transform: "scale(100%)",
+ },
+ "50%": {
+ transform: "scale(120%)",
+ },
+ },
+ "accordion-down": {
+ from: {
+ height: "0",
+ },
+ to: {
+ height: "var(--radix-accordion-content-height)",
+ },
+ },
+ "accordion-up": {
+ from: {
+ height: "var(--radix-accordion-content-height)",
+ },
+ to: {
+ height: "0",
+ },
+ },
+ shimmer: {
+ "0%": {
+ backgroundPosition: "200% 0",
+ },
+ "100%": {
+ backgroundPosition: "-200% 0",
+ },
+ },
+ },
+ animation: {
+ overlayShow: "overlayShow 400ms cubic-bezier(0.16, 1, 0.3, 1)",
+ contentShow: "contentShow 400ms cubic-bezier(0.16, 1, 0.3, 1)",
+ wiggle: "wiggle 150ms ease-in-out 1",
+ "accordion-down": "accordion-down 0.2s ease-out",
+ "accordion-up": "accordion-up 0.2s ease-out",
+ shimmer: "shimmer 3s ease-in-out infinite",
+ },
+ colors: {
+ border: "hsl(var(--border))",
+ input: "hsl(var(--input))",
+ ring: "hsl(var(--ring))",
+ background: "hsl(var(--background))",
+ foreground: "hsl(var(--foreground))",
+ primary: {
+ DEFAULT: "hsl(var(--primary))",
+ foreground: "hsl(var(--primary-foreground))",
+ hover: "hsl(var(--primary-hover))",
+ },
+ secondary: {
+ DEFAULT: "hsl(var(--secondary))",
+ foreground: "hsl(var(--secondary-foreground))",
+ hover: "hsl(var(--secondary-hover))",
+ },
+ destructive: {
+ DEFAULT: "hsl(var(--destructive))",
+ foreground: "hsl(var(--destructive-foreground))",
+ },
+ muted: {
+ DEFAULT: "hsl(var(--muted))",
+ foreground: "hsl(var(--muted-foreground))",
+ },
+ accent: {
+ DEFAULT: "hsl(var(--accent))",
+ foreground: "hsl(var(--accent-foreground))",
+ },
+ "accent-emerald": {
+ DEFAULT: "hsl(var(--accent-emerald))",
+ foreground: "hsl(var(--accent-emerald-foreground))",
+ },
+ "accent-pink": {
+ DEFAULT: "hsl(var(--accent-pink))",
+ foreground: "hsl(var(--accent-pink-foreground))",
+ },
+ "accent-amber": {
+ DEFAULT: "hsl(var(--accent-amber))",
+ foreground: "hsl(var(--accent-amber-foreground))",
+ },
+ "accent-purple": {
+ DEFAULT: "hsl(var(--accent-purple))",
+ foreground: "hsl(var(--accent-purple-foreground))",
+ },
+ "accent-indigo": {
+ DEFAULT: "hsl(var(--accent-indigo))",
+ foreground: "hsl(var(--accent-indigo-foreground))",
+ },
+ "accent-red": {
+ DEFAULT: "hsl(var(--accent-red))",
+ foreground: "hsl(var(--accent-red-foreground))",
+ },
+ popover: {
+ DEFAULT: "hsl(var(--popover))",
+ foreground: "hsl(var(--popover-foreground))",
+ },
+ card: {
+ DEFAULT: "hsl(var(--card))",
+ foreground: "hsl(var(--card-foreground))",
+ },
+ "component-icon": "var(--component-icon)",
+ "flow-icon": "var(--flow-icon)",
+ "placeholder-foreground": "hsl(var(--placeholder-foreground))",
+ warning: {
+ DEFAULT: "hsl(var(--warning))",
+ foreground: "hsl(var(--warning-foreground))",
+ },
+ sidebar: {
+ DEFAULT: "hsl(var(--sidebar-background))",
+ foreground: "hsl(var(--sidebar-foreground))",
+ primary: "hsl(var(--sidebar-primary))",
+ "primary-foreground": "hsl(var(--sidebar-primary-foreground))",
+ accent: "hsl(var(--sidebar-accent))",
+ "accent-foreground": "hsl(var(--sidebar-accent-foreground))",
+ border: "hsl(var(--sidebar-border))",
+ ring: "hsl(var(--sidebar-ring))",
+ },
+ },
+ borderRadius: {
+ lg: "var(--radius)",
+ md: "calc(var(--radius) - 2px)",
+ sm: "calc(var(--radius) - 4px)",
+ },
+ fontFamily: {
+ sans: ["var(--font-sans)", ...fontFamily.sans],
+ mono: ["var(--font-mono)", ...fontFamily.mono],
+ chivo: ["var(--font-chivo)", ...fontFamily.sans],
+ },
+ fontSize: {
+ xxs: "11px",
+ mmd: "13px",
+ },
+ },
},
plugins: [
tailwindcssAnimate,
diff --git a/frontend/tests/core/onboarding.spec.ts b/frontend/tests/core/onboarding.spec.ts
index 9e7a5bc5e..28e663a7b 100644
--- a/frontend/tests/core/onboarding.spec.ts
+++ b/frontend/tests/core/onboarding.spec.ts
@@ -1,4 +1,4 @@
-import { test, expect } from "@playwright/test";
+import { expect, test } from "@playwright/test";
test("has onboarding content", async ({ page }) => {
// Go to the base URL (frontend)
@@ -8,5 +8,7 @@ test("has onboarding content", async ({ page }) => {
await expect(page).toHaveTitle(/OpenRAG/);
// Expect the onboarding content to be visible using the test id.
- await expect(page.getByTestId("onboarding-content")).toBeVisible({ timeout: 30000 });
+ await expect(page.getByTestId("onboarding-content")).toBeVisible({
+ timeout: 30000,
+ });
});