hooks.ts
Overview
This file, hooks.ts, provides a collection of React custom hooks primarily focused on searching, retrieving, testing, and managing question-answering workflows within a knowledge base or chat-based application. It integrates with backend services to fetch data such as mind maps, testing chunks, related questions, and manages state and side effects associated with sending questions and handling responses.
The hooks encapsulate complex logic involving pagination, API mutations (using react-query), URL parameter extraction, and UI interaction management, thus providing reusable and composable utilities for components that require knowledge retrieval, search, and question-answering functionalities.
Detailed Explanation of Hooks
Interfaces
ISearchingPropsInput properties for the
useSearchinghook.interface ISearchingProps { searchText?: string; data: ISearchAppDetailProps; setIsSearching?: Dispatch<SetStateAction<boolean>>; setSearchText?: Dispatch<SetStateAction<string>>; }ISearchReturnPropsReturn type of
useSearchinghook inferred from the hook's return value.
Hook: useGetSharedSearchParams
Purpose:
Extracts and parses search-related parameters from the URL search query string. It handles prefixed data keys (data_) and standard parameters such as from, shared_id, locale, tenantId, and avatar visibility.
Returns:
{
from: SharedFrom | null;
sharedId: string | null;
locale: string | null;
tenantId: string | null;
data: Record<string, string>;
visibleAvatar: boolean;
}
Usage example:
const { from, sharedId, tenantId, data, visibleAvatar } = useGetSharedSearchParams();
Hook: useSearchFetchMindMap
Purpose:
Fetches a mind map related to a search query or shared content using a mutation pattern (react-query useMutation). It selects the API endpoint conditionally based on the presence of a shared_id in the URL.
Returns:
{
data: any; // Mind map data returned from the backend
loading: boolean; // Loading state of the fetch
fetchMindMap: (params: IAskRequestBody) => Promise<any>; // Function to trigger fetching mind map
}
Implementation details:
Uses
useMutationwith a key'fetchMindMap'.Handles errors by displaying them using a UI message component.
Returns empty array on failure.
Hook: useTestChunkRetrieval
Purpose:
Fetches a paginated test chunk retrieval response, which includes chunks of documents and metadata used for testing retrieval from a knowledge base.
Parameters:
tenantId?: string— Optional tenant identifier.
Returns:
ResponsePostType<ITestingResult> & {
testChunk: (...params: any[]) => void; // Function to trigger the test chunk retrieval
loading: boolean;
data: {
chunks: any[];
documents: any[];
total: number;
};
}
Implementation details:
Selects the API endpoint based on URL parameter
shared_id.Uses pagination parameters from
useSetPaginationParams.Handles successful responses by transforming
doc_aggstodocuments.Returns default empty structure if no data.
Hook: useTestChunkAllRetrieval
Purpose:
Similar to useTestChunkRetrieval but retrieves all chunks without filtering by document IDs, useful for full retrieval tests.
Parameters & Returns:
Same as useTestChunkRetrieval but exposes testChunkAll method instead.
Hook: useTestRetrieval
Purpose:
Manages the state and effect of testing chunk retrieval based on a search string and selected documents, handling pagination and loading state.
Parameters:
kbIds: string[]— Knowledge base IDs to query.searchStr: string— Current search string.sendingLoading: boolean— Indicates if a sending operation is in progress.
Returns:
{
loading: boolean;
selectedDocumentIds: string[];
setSelectedDocumentIds: Dispatch<SetStateAction<string[]>>;
}
Implementation details:
Uses
useTestChunkRetrievalinternally.Automatically triggers chunk retrieval on search string or selection change.
Ensures no operation if the search string is empty or loading is ongoing.
Hook: useFetchRelatedQuestions
Purpose:
Fetches related questions for a given question string, optionally scoped by tenant and search identifiers.
Parameters:
tenantId?: stringsearchId?: string
Returns:
{
data: string[]; // Array of related question strings
loading: boolean;
fetchRelatedQuestions: (question: string) => Promise<string[]>;
}
Implementation details:
Differentiates API endpoint if
shared_idis present.Uses
useMutationto fetch related questions.
Hook: useSendQuestion
Purpose:
Manages the full lifecycle of sending a question to the backend, receiving streamed answers, testing chunk retrievals, fetching related questions, and managing UI state.
Parameters:
kbIds: string[]— Knowledge base IDs.tenantId?: string— Optional tenant ID.searchId?: string— Optional search session ID.related_search?: boolean— Whether to fetch related questions.
Returns:
A comprehensive object containing:
Functions to send questions, change input, handle clicks on related questions, and test chunk retrieval.
State variables such as loading, sendingLoading, current answer, related questions, selected documents, search string, etc.
Utility to stop ongoing message output.
Example usage:
const {
sendQuestion,
handleSearchStrChange,
handleClickRelatedQuestion,
answer,
relatedQuestions,
searchStr,
sendingLoading,
} = useSendQuestion(['kb1', 'kb2'], 'tenant123', 'search456', true);
sendQuestion('What is AI?');
Implementation details:
Uses
useSendMessageWithSseto send question and receive streamed answers.Calls
testChunkandtestChunkAllto fetch related document chunks.Controls loading and selection state.
Fetches related questions if enabled.
Resets pagination and answer state on new queries.
Hook: useSearching
Purpose:
High-level hook combining multiple other hooks to manage searching, question sending, pagination, mind map display, document preview, and related UI interactions in a cohesive manner.
Parameters:
ISearchingPropsobject containing optional initial search text, search data, and setters.
Returns:
A large object containing:
All handlers and state from
useSendQuestion.Modal visibility and handlers for document preview and mind map.
Pagination controls.
Search results chunks and totals.
Methods to handle search input changes and pagination changes.
Usage example:
const searchData = {...}; // ISearchAppDetailProps
const { sendQuestion, answer, loading, mindMapVisible } = useSearching({
searchText: 'initial query',
data: searchData,
});
Implementation details:
Integrates
useSendQuestion,useClickDrawer(for document modal),useShowMindMapDrawer, and pagination hooks.Automatically triggers search on initial search text.
Manages UI states and side effects for complex search workflows.
Hook: useCheckSettings
Purpose:
Simple utility hook to determine if the search settings are valid (e.g., knowledge base IDs and name are set).
Parameters:
data: ISearchAppDetailProps
Returns:
{
openSetting: boolean; // True if settings are incomplete and UI should open settings modal
}
Implementation details:
Returns
openSetting: trueifkb_idsis empty or name is missing.
Important Implementation Details and Algorithms
API interaction is largely done via
useMutationfrom@tanstack/react-query, enabling optimistic updates, caching, and background refetching.Conditional API endpoint selection is based on URL query parameter
shared_id, allowing support for shared or regular data sources.Pagination is managed through custom hooks (
useSetPaginationParams,useGetPaginationWithRouter) and integrated into data retrieval hooks.Streaming responses for answers use SSE (Server-Sent Events) handled by
useSendMessageWithSse.Search input and related questions are tightly coupled to provide instant feedback and suggestions.
State management is primarily via React's
useStateanduseEffecthooks, with memoization viauseCallbackto optimize performance.Data transformations such as mapping
doc_aggstodocumentsare done on API responses for consistency.
Interactions with Other Parts of the System
UI Components:
The hooks are designed for use in React components related to chat, knowledge base search, and mind map visualization. For example, components utilizeuseSearchingto manage the entire search lifecycle.Services:
chatService,kbService,searchServiceprovide backend API functions.apiutility provides endpoints for question asking.messageUI component is used for error notifications.
Routing:
UsesuseSearchParamsfromumito read URL parameters influencing hook behavior.Other Hooks:
Logic hooks:
useSendMessageWithSse,useGetPaginationWithRouterKnowledge base hooks:
useKnowledgeBaseId,useSelectTestingResultUI hooks:
useShowMindMapDrawer,useClickDrawer
Mermaid Diagram: Hook Structure and Relationships
flowchart TD
A[useGetSharedSearchParams]
B[useSearchFetchMindMap]
C[useTestChunkRetrieval]
D[useTestChunkAllRetrieval]
E[useTestRetrieval]
F[useFetchRelatedQuestions]
G[useSendQuestion]
H[useSearching]
I[useCheckSettings]
A --> G
C --> G
D --> G
F --> G
G --> H
B --> H
E --> H
H --> I
Diagram explanation:
useSendQuestiondepends onuseGetSharedSearchParams,useTestChunkRetrieval,useTestChunkAllRetrieval, anduseFetchRelatedQuestions.useSearchingis a high-level hook that usesuseSendQuestion,useSearchFetchMindMap, anduseTestRetrieval.useCheckSettingscan be used independently but is related to the search configuration.
Summary
The hooks.ts file is a core utility module that encapsulates complex logic for managing search and Q&A functionalities in a chat or knowledge base application. It abstracts API calls, state management, pagination, and UI interactions into composable React hooks, enabling maintainable and reusable code. It is integral to the system's search and retrieval workflows, linking frontend components with backend services and URL-driven state.