chore: init monorepo snapshot
This commit is contained in:
@@ -0,0 +1,382 @@
|
||||
import { create } from 'zustand'
|
||||
import { createSelectors } from '@/lib/utils'
|
||||
import { DirectedGraph } from 'graphology'
|
||||
import MiniSearch from 'minisearch'
|
||||
import { resolveNodeColor, DEFAULT_NODE_COLOR } from '@/utils/graphColor'
|
||||
|
||||
export type RawNodeType = {
|
||||
// for NetworkX: id is identical to properties['entity_id']
|
||||
// for Neo4j: id is unique identifier for each node
|
||||
id: string
|
||||
labels: string[]
|
||||
properties: Record<string, any>
|
||||
|
||||
size: number
|
||||
x: number
|
||||
y: number
|
||||
color: string
|
||||
|
||||
degree: number
|
||||
}
|
||||
|
||||
export type RawEdgeType = {
|
||||
// for NetworkX: id is "source-target"
|
||||
// for Neo4j: id is unique identifier for each edge
|
||||
id: string
|
||||
source: string
|
||||
target: string
|
||||
type?: string
|
||||
properties: Record<string, any>
|
||||
// dynamicId: key for sigmaGraph
|
||||
dynamicId: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface for tracking edges that need updating when a node ID changes
|
||||
*/
|
||||
interface EdgeToUpdate {
|
||||
originalDynamicId: string
|
||||
newEdgeId: string
|
||||
edgeIndex: number
|
||||
}
|
||||
|
||||
export class RawGraph {
|
||||
nodes: RawNodeType[] = []
|
||||
edges: RawEdgeType[] = []
|
||||
// nodeIDMap: map node id to index in nodes array (SigmaGraph has nodeId as key)
|
||||
nodeIdMap: Record<string, number> = {}
|
||||
// edgeIDMap: map edge id to index in edges array (SigmaGraph not use id as key)
|
||||
edgeIdMap: Record<string, number> = {}
|
||||
// edgeDynamicIdMap: map edge dynamic id to index in edges array (SigmaGraph has DynamicId as key)
|
||||
edgeDynamicIdMap: Record<string, number> = {}
|
||||
|
||||
getNode = (nodeId: string) => {
|
||||
const nodeIndex = this.nodeIdMap[nodeId]
|
||||
if (nodeIndex !== undefined) {
|
||||
return this.nodes[nodeIndex]
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
getEdge = (edgeId: string, dynamicId: boolean = true) => {
|
||||
const edgeIndex = dynamicId ? this.edgeDynamicIdMap[edgeId] : this.edgeIdMap[edgeId]
|
||||
if (edgeIndex !== undefined) {
|
||||
return this.edges[edgeIndex]
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
buildDynamicMap = () => {
|
||||
this.edgeDynamicIdMap = {}
|
||||
for (let i = 0; i < this.edges.length; i++) {
|
||||
const edge = this.edges[i]
|
||||
this.edgeDynamicIdMap[edge.dynamicId] = i
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface GraphState {
|
||||
selectedNode: string | null
|
||||
focusedNode: string | null
|
||||
selectedEdge: string | null
|
||||
focusedEdge: string | null
|
||||
|
||||
rawGraph: RawGraph | null
|
||||
sigmaGraph: DirectedGraph | null
|
||||
sigmaInstance: any | null
|
||||
|
||||
searchEngine: MiniSearch | null
|
||||
|
||||
moveToSelectedNode: boolean
|
||||
isFetching: boolean
|
||||
graphIsEmpty: boolean
|
||||
lastSuccessfulQueryLabel: string
|
||||
|
||||
typeColorMap: Map<string, string>
|
||||
|
||||
// Global flags to track data fetching attempts
|
||||
graphDataFetchAttempted: boolean
|
||||
labelsFetchAttempted: boolean
|
||||
|
||||
setSigmaInstance: (instance: any) => void
|
||||
setSelectedNode: (nodeId: string | null, moveToSelectedNode?: boolean) => void
|
||||
setFocusedNode: (nodeId: string | null) => void
|
||||
setSelectedEdge: (edgeId: string | null) => void
|
||||
setFocusedEdge: (edgeId: string | null) => void
|
||||
clearSelection: () => void
|
||||
reset: () => void
|
||||
|
||||
setMoveToSelectedNode: (moveToSelectedNode: boolean) => void
|
||||
setGraphIsEmpty: (isEmpty: boolean) => void
|
||||
setLastSuccessfulQueryLabel: (label: string) => void
|
||||
|
||||
setRawGraph: (rawGraph: RawGraph | null) => void
|
||||
setSigmaGraph: (sigmaGraph: DirectedGraph | null) => void
|
||||
setIsFetching: (isFetching: boolean) => void
|
||||
|
||||
// Legend color mapping methods
|
||||
setTypeColorMap: (typeColorMap: Map<string, string>) => void
|
||||
|
||||
// Search engine methods
|
||||
setSearchEngine: (engine: MiniSearch | null) => void
|
||||
resetSearchEngine: () => void
|
||||
|
||||
// Methods to set global flags
|
||||
setGraphDataFetchAttempted: (attempted: boolean) => void
|
||||
setLabelsFetchAttempted: (attempted: boolean) => void
|
||||
|
||||
// Event trigger methods for node operations
|
||||
triggerNodeExpand: (nodeId: string | null) => void
|
||||
triggerNodePrune: (nodeId: string | null) => void
|
||||
|
||||
// Node operation state
|
||||
nodeToExpand: string | null
|
||||
nodeToPrune: string | null
|
||||
|
||||
// Version counter to trigger data refresh
|
||||
graphDataVersion: number
|
||||
incrementGraphDataVersion: () => void
|
||||
|
||||
// Methods for updating graph elements and UI state together
|
||||
updateNodeAndSelect: (nodeId: string, entityId: string, propertyName: string, newValue: string) => Promise<void>
|
||||
updateEdgeAndSelect: (edgeId: string, dynamicId: string, sourceId: string, targetId: string, propertyName: string, newValue: string) => Promise<void>
|
||||
}
|
||||
|
||||
const useGraphStoreBase = create<GraphState>()((set, get) => ({
|
||||
selectedNode: null,
|
||||
focusedNode: null,
|
||||
selectedEdge: null,
|
||||
focusedEdge: null,
|
||||
|
||||
moveToSelectedNode: false,
|
||||
isFetching: false,
|
||||
graphIsEmpty: false,
|
||||
lastSuccessfulQueryLabel: '', // Initialize as empty to ensure fetchAllDatabaseLabels runs on first query
|
||||
|
||||
// Initialize global flags
|
||||
graphDataFetchAttempted: false,
|
||||
labelsFetchAttempted: false,
|
||||
|
||||
rawGraph: null,
|
||||
sigmaGraph: null,
|
||||
sigmaInstance: null,
|
||||
|
||||
typeColorMap: new Map<string, string>(),
|
||||
|
||||
searchEngine: null,
|
||||
|
||||
setGraphIsEmpty: (isEmpty: boolean) => set({ graphIsEmpty: isEmpty }),
|
||||
setLastSuccessfulQueryLabel: (label: string) => set({ lastSuccessfulQueryLabel: label }),
|
||||
|
||||
|
||||
setIsFetching: (isFetching: boolean) => set({ isFetching }),
|
||||
setSelectedNode: (nodeId: string | null, moveToSelectedNode?: boolean) =>
|
||||
set({ selectedNode: nodeId, moveToSelectedNode }),
|
||||
setFocusedNode: (nodeId: string | null) => set({ focusedNode: nodeId }),
|
||||
setSelectedEdge: (edgeId: string | null) => set({ selectedEdge: edgeId }),
|
||||
setFocusedEdge: (edgeId: string | null) => set({ focusedEdge: edgeId }),
|
||||
clearSelection: () =>
|
||||
set({
|
||||
selectedNode: null,
|
||||
focusedNode: null,
|
||||
selectedEdge: null,
|
||||
focusedEdge: null
|
||||
}),
|
||||
reset: () => {
|
||||
set({
|
||||
selectedNode: null,
|
||||
focusedNode: null,
|
||||
selectedEdge: null,
|
||||
focusedEdge: null,
|
||||
rawGraph: null,
|
||||
sigmaGraph: null, // to avoid other components from acccessing graph objects
|
||||
searchEngine: null,
|
||||
moveToSelectedNode: false,
|
||||
graphIsEmpty: false
|
||||
});
|
||||
},
|
||||
|
||||
setRawGraph: (rawGraph: RawGraph | null) =>
|
||||
set({
|
||||
rawGraph
|
||||
}),
|
||||
|
||||
setSigmaGraph: (sigmaGraph: DirectedGraph | null) => {
|
||||
// Replace graph instance, no need to keep WebGL context
|
||||
set({ sigmaGraph });
|
||||
},
|
||||
|
||||
setMoveToSelectedNode: (moveToSelectedNode?: boolean) => set({ moveToSelectedNode }),
|
||||
|
||||
setSigmaInstance: (instance: any) => set({ sigmaInstance: instance }),
|
||||
|
||||
setTypeColorMap: (typeColorMap: Map<string, string>) => set({ typeColorMap }),
|
||||
|
||||
setSearchEngine: (engine: MiniSearch | null) => set({ searchEngine: engine }),
|
||||
resetSearchEngine: () => set({ searchEngine: null }),
|
||||
|
||||
// Methods to set global flags
|
||||
setGraphDataFetchAttempted: (attempted: boolean) => set({ graphDataFetchAttempted: attempted }),
|
||||
setLabelsFetchAttempted: (attempted: boolean) => set({ labelsFetchAttempted: attempted }),
|
||||
|
||||
// Node operation state
|
||||
nodeToExpand: null,
|
||||
nodeToPrune: null,
|
||||
|
||||
// Event trigger methods for node operations
|
||||
triggerNodeExpand: (nodeId: string | null) => set({ nodeToExpand: nodeId }),
|
||||
triggerNodePrune: (nodeId: string | null) => set({ nodeToPrune: nodeId }),
|
||||
|
||||
// Version counter implementation
|
||||
graphDataVersion: 0,
|
||||
incrementGraphDataVersion: () => set((state) => ({ graphDataVersion: state.graphDataVersion + 1 })),
|
||||
|
||||
// Methods for updating graph elements and UI state together
|
||||
updateNodeAndSelect: async (nodeId: string, entityId: string, propertyName: string, newValue: string) => {
|
||||
// Get current state
|
||||
const state = get()
|
||||
const { sigmaGraph, rawGraph } = state
|
||||
|
||||
// Validate graph state
|
||||
if (!sigmaGraph || !rawGraph || !sigmaGraph.hasNode(nodeId)) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const nodeAttributes = sigmaGraph.getNodeAttributes(nodeId)
|
||||
|
||||
console.log('updateNodeAndSelect', nodeId, entityId, propertyName, newValue)
|
||||
|
||||
// For entity_id changes (node renaming) with raw graph storage
|
||||
if ((nodeId === entityId) && (propertyName === 'entity_id')) {
|
||||
// Create new node with updated ID but same attributes
|
||||
sigmaGraph.addNode(newValue, { ...nodeAttributes, label: newValue })
|
||||
|
||||
const edgesToUpdate: EdgeToUpdate[] = []
|
||||
|
||||
// Process all edges connected to this node
|
||||
sigmaGraph.forEachEdge(nodeId, (edge, attributes, source, target) => {
|
||||
const otherNode = source === nodeId ? target : source
|
||||
const isOutgoing = source === nodeId
|
||||
|
||||
// Get original edge dynamic ID for later reference
|
||||
const originalEdgeDynamicId = edge
|
||||
const edgeIndexInRawGraph = rawGraph.edgeDynamicIdMap[originalEdgeDynamicId]
|
||||
|
||||
// Create new edge with updated node reference
|
||||
const newEdgeId = sigmaGraph.addEdge(
|
||||
isOutgoing ? newValue : otherNode,
|
||||
isOutgoing ? otherNode : newValue,
|
||||
attributes
|
||||
)
|
||||
|
||||
// Track edges that need updating in the raw graph
|
||||
if (edgeIndexInRawGraph !== undefined) {
|
||||
edgesToUpdate.push({
|
||||
originalDynamicId: originalEdgeDynamicId,
|
||||
newEdgeId: newEdgeId,
|
||||
edgeIndex: edgeIndexInRawGraph
|
||||
})
|
||||
}
|
||||
|
||||
// Remove the old edge
|
||||
sigmaGraph.dropEdge(edge)
|
||||
})
|
||||
|
||||
// Remove the old node after all edges are processed
|
||||
sigmaGraph.dropNode(nodeId)
|
||||
|
||||
// Update node reference in raw graph data
|
||||
const nodeIndex = rawGraph.nodeIdMap[nodeId]
|
||||
if (nodeIndex !== undefined) {
|
||||
rawGraph.nodes[nodeIndex].id = newValue
|
||||
rawGraph.nodes[nodeIndex].labels = [newValue]
|
||||
rawGraph.nodes[nodeIndex].properties.entity_id = newValue
|
||||
delete rawGraph.nodeIdMap[nodeId]
|
||||
rawGraph.nodeIdMap[newValue] = nodeIndex
|
||||
}
|
||||
|
||||
// Update all edge references in raw graph data
|
||||
edgesToUpdate.forEach(({ originalDynamicId, newEdgeId, edgeIndex }) => {
|
||||
if (rawGraph.edges[edgeIndex]) {
|
||||
// Update source/target references
|
||||
if (rawGraph.edges[edgeIndex].source === nodeId) {
|
||||
rawGraph.edges[edgeIndex].source = newValue
|
||||
}
|
||||
if (rawGraph.edges[edgeIndex].target === nodeId) {
|
||||
rawGraph.edges[edgeIndex].target = newValue
|
||||
}
|
||||
|
||||
// Update dynamic ID mappings
|
||||
rawGraph.edges[edgeIndex].dynamicId = newEdgeId
|
||||
delete rawGraph.edgeDynamicIdMap[originalDynamicId]
|
||||
rawGraph.edgeDynamicIdMap[newEdgeId] = edgeIndex
|
||||
}
|
||||
})
|
||||
|
||||
// Update selected node in store
|
||||
set({ selectedNode: newValue, moveToSelectedNode: true })
|
||||
} else {
|
||||
// For non-NetworkX nodes or non-entity_id changes
|
||||
const nodeIndex = rawGraph.nodeIdMap[String(nodeId)]
|
||||
if (nodeIndex !== undefined) {
|
||||
const nodeRef = rawGraph.nodes[nodeIndex]
|
||||
nodeRef.properties[propertyName] = newValue
|
||||
if (propertyName === 'entity_id') {
|
||||
nodeRef.labels = [newValue]
|
||||
sigmaGraph.setNodeAttribute(String(nodeId), 'label', newValue)
|
||||
}
|
||||
if (propertyName === 'entity_type') {
|
||||
const { color, map, updated } = resolveNodeColor(newValue, state.typeColorMap)
|
||||
const resolvedColor = color || DEFAULT_NODE_COLOR
|
||||
nodeRef.color = resolvedColor
|
||||
sigmaGraph.setNodeAttribute(String(nodeId), 'color', resolvedColor)
|
||||
if (updated) {
|
||||
set({ typeColorMap: map })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Trigger a re-render by incrementing the version counter
|
||||
set((state) => ({ graphDataVersion: state.graphDataVersion + 1 }))
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating node in graph:', error)
|
||||
throw new Error('Failed to update node in graph')
|
||||
}
|
||||
},
|
||||
|
||||
updateEdgeAndSelect: async (edgeId: string, dynamicId: string, sourceId: string, targetId: string, propertyName: string, newValue: string) => {
|
||||
// Get current state
|
||||
const state = get()
|
||||
const { sigmaGraph, rawGraph } = state
|
||||
|
||||
// Validate graph state
|
||||
if (!sigmaGraph || !rawGraph) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const edgeIndex = rawGraph.edgeIdMap[String(edgeId)]
|
||||
if (edgeIndex !== undefined && rawGraph.edges[edgeIndex]) {
|
||||
rawGraph.edges[edgeIndex].properties[propertyName] = newValue
|
||||
if(dynamicId !== undefined && propertyName === 'keywords') {
|
||||
sigmaGraph.setEdgeAttribute(dynamicId, 'label', newValue)
|
||||
}
|
||||
}
|
||||
|
||||
// Trigger a re-render by incrementing the version counter
|
||||
set((state) => ({ graphDataVersion: state.graphDataVersion + 1 }))
|
||||
|
||||
// Update selected edge in store to ensure UI reflects changes
|
||||
set({ selectedEdge: dynamicId })
|
||||
} catch (error) {
|
||||
console.error(`Error updating edge ${sourceId}->${targetId} in graph:`, error)
|
||||
throw new Error('Failed to update edge in graph')
|
||||
}
|
||||
}
|
||||
}))
|
||||
|
||||
const useGraphStore = createSelectors(useGraphStoreBase)
|
||||
|
||||
export { useGraphStore }
|
||||
@@ -0,0 +1,352 @@
|
||||
import { create } from 'zustand'
|
||||
import { persist, createJSONStorage } from 'zustand/middleware'
|
||||
import { createSelectors } from '@/lib/utils'
|
||||
import { defaultQueryLabel } from '@/lib/constants'
|
||||
import { Message, QueryRequest } from '@/api/lightrag'
|
||||
|
||||
type Theme = 'dark' | 'light' | 'system'
|
||||
type Language = 'en' | 'zh' | 'fr' | 'ar' | 'zh_TW'
|
||||
type Tab = 'documents' | 'knowledge-graph' | 'retrieval' | 'api'
|
||||
|
||||
interface SettingsState {
|
||||
// Document manager settings
|
||||
showFileName: boolean
|
||||
setShowFileName: (show: boolean) => void
|
||||
|
||||
documentsPageSize: number
|
||||
setDocumentsPageSize: (size: number) => void
|
||||
|
||||
// User prompt history
|
||||
userPromptHistory: string[]
|
||||
addUserPromptToHistory: (prompt: string) => void
|
||||
setUserPromptHistory: (history: string[]) => void
|
||||
|
||||
// Graph viewer settings
|
||||
showPropertyPanel: boolean
|
||||
showNodeSearchBar: boolean
|
||||
showLegend: boolean
|
||||
setShowLegend: (show: boolean) => void
|
||||
|
||||
showNodeLabel: boolean
|
||||
enableNodeDrag: boolean
|
||||
|
||||
showEdgeLabel: boolean
|
||||
enableHideUnselectedEdges: boolean
|
||||
enableEdgeEvents: boolean
|
||||
|
||||
minEdgeSize: number
|
||||
setMinEdgeSize: (size: number) => void
|
||||
|
||||
maxEdgeSize: number
|
||||
setMaxEdgeSize: (size: number) => void
|
||||
|
||||
graphQueryMaxDepth: number
|
||||
setGraphQueryMaxDepth: (depth: number) => void
|
||||
|
||||
graphMaxNodes: number
|
||||
setGraphMaxNodes: (nodes: number, triggerRefresh?: boolean) => void
|
||||
|
||||
backendMaxGraphNodes: number | null
|
||||
setBackendMaxGraphNodes: (maxNodes: number | null) => void
|
||||
|
||||
graphLayoutMaxIterations: number
|
||||
setGraphLayoutMaxIterations: (iterations: number) => void
|
||||
|
||||
// Retrieval settings
|
||||
queryLabel: string
|
||||
setQueryLabel: (queryLabel: string) => void
|
||||
|
||||
retrievalHistory: Message[]
|
||||
setRetrievalHistory: (history: Message[]) => void
|
||||
|
||||
querySettings: Omit<QueryRequest, 'query'>
|
||||
updateQuerySettings: (settings: Partial<QueryRequest>) => void
|
||||
|
||||
// Auth settings
|
||||
apiKey: string | null
|
||||
setApiKey: (key: string | null) => void
|
||||
|
||||
// App settings
|
||||
theme: Theme
|
||||
setTheme: (theme: Theme) => void
|
||||
|
||||
language: Language
|
||||
setLanguage: (lang: Language) => void
|
||||
|
||||
enableHealthCheck: boolean
|
||||
setEnableHealthCheck: (enable: boolean) => void
|
||||
|
||||
currentTab: Tab
|
||||
setCurrentTab: (tab: Tab) => void
|
||||
|
||||
// Search label dropdown refresh trigger (non-persistent, runtime only)
|
||||
searchLabelDropdownRefreshTrigger: number
|
||||
triggerSearchLabelDropdownRefresh: () => void
|
||||
}
|
||||
|
||||
const useSettingsStoreBase = create<SettingsState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
theme: 'system',
|
||||
language: 'en',
|
||||
showPropertyPanel: true,
|
||||
showNodeSearchBar: true,
|
||||
showLegend: false,
|
||||
|
||||
showNodeLabel: true,
|
||||
enableNodeDrag: true,
|
||||
|
||||
showEdgeLabel: false,
|
||||
enableHideUnselectedEdges: true,
|
||||
enableEdgeEvents: false,
|
||||
|
||||
minEdgeSize: 1,
|
||||
maxEdgeSize: 1,
|
||||
|
||||
graphQueryMaxDepth: 3,
|
||||
graphMaxNodes: 1000,
|
||||
backendMaxGraphNodes: null,
|
||||
graphLayoutMaxIterations: 15,
|
||||
|
||||
queryLabel: defaultQueryLabel,
|
||||
|
||||
enableHealthCheck: true,
|
||||
|
||||
apiKey: null,
|
||||
|
||||
currentTab: 'documents',
|
||||
showFileName: false,
|
||||
documentsPageSize: 10,
|
||||
|
||||
retrievalHistory: [],
|
||||
userPromptHistory: [],
|
||||
|
||||
querySettings: {
|
||||
mode: 'global',
|
||||
top_k: 40,
|
||||
chunk_top_k: 20,
|
||||
max_entity_tokens: 6000,
|
||||
max_relation_tokens: 8000,
|
||||
max_total_tokens: 30000,
|
||||
only_need_context: false,
|
||||
only_need_prompt: false,
|
||||
stream: true,
|
||||
history_turns: 0,
|
||||
user_prompt: '',
|
||||
enable_rerank: true
|
||||
},
|
||||
|
||||
setTheme: (theme: Theme) => set({ theme }),
|
||||
|
||||
setLanguage: (language: Language) => {
|
||||
set({ language })
|
||||
},
|
||||
|
||||
setGraphLayoutMaxIterations: (iterations: number) =>
|
||||
set({
|
||||
graphLayoutMaxIterations: iterations
|
||||
}),
|
||||
|
||||
setQueryLabel: (queryLabel: string) =>
|
||||
set({
|
||||
queryLabel
|
||||
}),
|
||||
|
||||
setGraphQueryMaxDepth: (depth: number) => set({ graphQueryMaxDepth: depth }),
|
||||
|
||||
setGraphMaxNodes: (nodes: number, triggerRefresh: boolean = false) => {
|
||||
const state = useSettingsStore.getState();
|
||||
if (state.graphMaxNodes === nodes) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (triggerRefresh) {
|
||||
const currentLabel = state.queryLabel;
|
||||
// Atomically update both the node count and the query label to trigger a refresh.
|
||||
set({ graphMaxNodes: nodes, queryLabel: '' });
|
||||
|
||||
// Restore the label after a short delay.
|
||||
setTimeout(() => {
|
||||
set({ queryLabel: currentLabel });
|
||||
}, 300);
|
||||
} else {
|
||||
set({ graphMaxNodes: nodes });
|
||||
}
|
||||
},
|
||||
|
||||
setBackendMaxGraphNodes: (maxNodes: number | null) => set({ backendMaxGraphNodes: maxNodes }),
|
||||
|
||||
setMinEdgeSize: (size: number) => set({ minEdgeSize: size }),
|
||||
|
||||
setMaxEdgeSize: (size: number) => set({ maxEdgeSize: size }),
|
||||
|
||||
setEnableHealthCheck: (enable: boolean) => set({ enableHealthCheck: enable }),
|
||||
|
||||
setApiKey: (apiKey: string | null) => set({ apiKey }),
|
||||
|
||||
setCurrentTab: (tab: Tab) => set({ currentTab: tab }),
|
||||
|
||||
setRetrievalHistory: (history: Message[]) => set({ retrievalHistory: history }),
|
||||
|
||||
updateQuerySettings: (settings: Partial<QueryRequest>) => {
|
||||
// Filter out history_turns to prevent changes, always keep it as 0
|
||||
const filteredSettings = { ...settings }
|
||||
delete filteredSettings.history_turns
|
||||
set((state) => ({
|
||||
querySettings: { ...state.querySettings, ...filteredSettings, history_turns: 0 }
|
||||
}))
|
||||
},
|
||||
|
||||
setShowFileName: (show: boolean) => set({ showFileName: show }),
|
||||
setShowLegend: (show: boolean) => set({ showLegend: show }),
|
||||
setDocumentsPageSize: (size: number) => set({ documentsPageSize: size }),
|
||||
|
||||
// User prompt history methods
|
||||
addUserPromptToHistory: (prompt: string) => {
|
||||
if (!prompt.trim()) return
|
||||
|
||||
set((state) => {
|
||||
const newHistory = [...state.userPromptHistory]
|
||||
|
||||
// Remove existing occurrence if found
|
||||
const existingIndex = newHistory.indexOf(prompt)
|
||||
if (existingIndex !== -1) {
|
||||
newHistory.splice(existingIndex, 1)
|
||||
}
|
||||
|
||||
// Add to beginning
|
||||
newHistory.unshift(prompt)
|
||||
|
||||
// Keep only last 12 items
|
||||
if (newHistory.length > 12) {
|
||||
newHistory.splice(12)
|
||||
}
|
||||
|
||||
return { userPromptHistory: newHistory }
|
||||
})
|
||||
},
|
||||
|
||||
setUserPromptHistory: (history: string[]) => set({ userPromptHistory: history }),
|
||||
|
||||
// Search label dropdown refresh trigger (not persisted)
|
||||
searchLabelDropdownRefreshTrigger: 0,
|
||||
triggerSearchLabelDropdownRefresh: () =>
|
||||
set((state) => ({
|
||||
searchLabelDropdownRefreshTrigger: state.searchLabelDropdownRefreshTrigger + 1
|
||||
}))
|
||||
}),
|
||||
{
|
||||
name: 'settings-storage',
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
version: 19,
|
||||
migrate: (state: any, version: number) => {
|
||||
if (version < 2) {
|
||||
state.showEdgeLabel = false
|
||||
}
|
||||
if (version < 3) {
|
||||
state.queryLabel = defaultQueryLabel
|
||||
}
|
||||
if (version < 4) {
|
||||
state.showPropertyPanel = true
|
||||
state.showNodeSearchBar = true
|
||||
state.showNodeLabel = true
|
||||
state.enableHealthCheck = true
|
||||
state.apiKey = null
|
||||
}
|
||||
if (version < 5) {
|
||||
state.currentTab = 'documents'
|
||||
}
|
||||
if (version < 6) {
|
||||
state.querySettings = {
|
||||
mode: 'global',
|
||||
response_type: 'Multiple Paragraphs',
|
||||
top_k: 10,
|
||||
max_token_for_text_unit: 4000,
|
||||
max_token_for_global_context: 4000,
|
||||
max_token_for_local_context: 4000,
|
||||
only_need_context: false,
|
||||
only_need_prompt: false,
|
||||
stream: true,
|
||||
history_turns: 0,
|
||||
hl_keywords: [],
|
||||
ll_keywords: []
|
||||
}
|
||||
state.retrievalHistory = []
|
||||
}
|
||||
if (version < 7) {
|
||||
state.graphQueryMaxDepth = 3
|
||||
state.graphLayoutMaxIterations = 15
|
||||
}
|
||||
if (version < 8) {
|
||||
state.graphMinDegree = 0
|
||||
state.language = 'en'
|
||||
}
|
||||
if (version < 9) {
|
||||
state.showFileName = false
|
||||
}
|
||||
if (version < 10) {
|
||||
delete state.graphMinDegree // 删除废弃参数
|
||||
state.graphMaxNodes = 1000 // 添加新参数
|
||||
}
|
||||
if (version < 11) {
|
||||
state.minEdgeSize = 1
|
||||
state.maxEdgeSize = 1
|
||||
}
|
||||
if (version < 12) {
|
||||
// Clear retrieval history to avoid compatibility issues with MessageWithError type
|
||||
state.retrievalHistory = []
|
||||
}
|
||||
if (version < 13) {
|
||||
// Add user_prompt field for older versions
|
||||
if (state.querySettings) {
|
||||
state.querySettings.user_prompt = ''
|
||||
}
|
||||
}
|
||||
if (version < 14) {
|
||||
// Add backendMaxGraphNodes field for older versions
|
||||
state.backendMaxGraphNodes = null
|
||||
}
|
||||
if (version < 15) {
|
||||
// Add new querySettings
|
||||
state.querySettings = {
|
||||
...state.querySettings,
|
||||
mode: 'mix',
|
||||
response_type: 'Multiple Paragraphs',
|
||||
top_k: 40,
|
||||
chunk_top_k: 10,
|
||||
max_entity_tokens: 10000,
|
||||
max_relation_tokens: 10000,
|
||||
max_total_tokens: 32000,
|
||||
enable_rerank: true,
|
||||
history_turns: 0,
|
||||
}
|
||||
}
|
||||
if (version < 16) {
|
||||
// Add documentsPageSize field for older versions
|
||||
state.documentsPageSize = 10
|
||||
}
|
||||
if (version < 17) {
|
||||
// Force history_turns to 0 for all users
|
||||
if (state.querySettings) {
|
||||
state.querySettings.history_turns = 0
|
||||
}
|
||||
}
|
||||
if (version < 18) {
|
||||
// Add userPromptHistory field for older versions
|
||||
state.userPromptHistory = []
|
||||
}
|
||||
if (version < 19) {
|
||||
// Remove deprecated response_type parameter
|
||||
if (state.querySettings) {
|
||||
delete state.querySettings.response_type
|
||||
}
|
||||
}
|
||||
return state
|
||||
}
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
const useSettingsStore = createSelectors(useSettingsStoreBase)
|
||||
|
||||
export { useSettingsStore, type Theme }
|
||||
@@ -0,0 +1,316 @@
|
||||
import { create } from 'zustand'
|
||||
import { createSelectors } from '@/lib/utils'
|
||||
import { checkHealth, LightragStatus } from '@/api/lightrag'
|
||||
import { useSettingsStore } from './settings'
|
||||
import { healthCheckInterval } from '@/lib/constants'
|
||||
|
||||
interface BackendState {
|
||||
health: boolean
|
||||
message: string | null
|
||||
messageTitle: string | null
|
||||
status: LightragStatus | null
|
||||
lastCheckTime: number
|
||||
pipelineBusy: boolean
|
||||
healthCheckIntervalId: ReturnType<typeof setInterval> | null
|
||||
healthCheckFunction: (() => void) | null
|
||||
healthCheckIntervalValue: number
|
||||
|
||||
check: () => Promise<boolean>
|
||||
clear: () => void
|
||||
setErrorMessage: (message: string, messageTitle: string) => void
|
||||
setPipelineBusy: (busy: boolean) => void
|
||||
setHealthCheckFunction: (fn: () => void) => void
|
||||
resetHealthCheckTimer: () => void
|
||||
resetHealthCheckTimerDelayed: (delayMs: number) => void
|
||||
clearHealthCheckTimer: () => void
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
isAuthenticated: boolean;
|
||||
isGuestMode: boolean; // Add guest mode flag
|
||||
coreVersion: string | null;
|
||||
apiVersion: string | null;
|
||||
username: string | null; // login username
|
||||
webuiTitle: string | null; // Custom title
|
||||
webuiDescription: string | null; // Title description
|
||||
|
||||
login: (token: string, isGuest?: boolean, coreVersion?: string | null, apiVersion?: string | null, webuiTitle?: string | null, webuiDescription?: string | null) => void;
|
||||
logout: () => void;
|
||||
setVersion: (coreVersion: string | null, apiVersion: string | null) => void;
|
||||
setCustomTitle: (webuiTitle: string | null, webuiDescription: string | null) => void;
|
||||
}
|
||||
|
||||
const useBackendStateStoreBase = create<BackendState>()((set, get) => ({
|
||||
health: true,
|
||||
message: null,
|
||||
messageTitle: null,
|
||||
lastCheckTime: Date.now(),
|
||||
status: null,
|
||||
pipelineBusy: false,
|
||||
healthCheckIntervalId: null,
|
||||
healthCheckFunction: null,
|
||||
healthCheckIntervalValue: healthCheckInterval * 1000, // Use constant from lib/constants
|
||||
|
||||
check: async () => {
|
||||
const health = await checkHealth()
|
||||
if (health.status === 'healthy') {
|
||||
// Update version information if health check returns it
|
||||
if (health.core_version || health.api_version) {
|
||||
useAuthStore.getState().setVersion(
|
||||
health.core_version || null,
|
||||
health.api_version || null
|
||||
);
|
||||
}
|
||||
|
||||
// Update custom title information if health check returns it
|
||||
if ('webui_title' in health || 'webui_description' in health) {
|
||||
useAuthStore.getState().setCustomTitle(
|
||||
'webui_title' in health ? (health.webui_title ?? null) : null,
|
||||
'webui_description' in health ? (health.webui_description ?? null) : null
|
||||
);
|
||||
}
|
||||
|
||||
// Extract and store backend max graph nodes limit
|
||||
if (health.configuration?.max_graph_nodes) {
|
||||
const maxNodes = parseInt(health.configuration.max_graph_nodes, 10)
|
||||
if (!isNaN(maxNodes) && maxNodes > 0) {
|
||||
const currentBackendMaxNodes = useSettingsStore.getState().backendMaxGraphNodes
|
||||
|
||||
// Only update if the backend limit has actually changed
|
||||
if (currentBackendMaxNodes !== maxNodes) {
|
||||
useSettingsStore.getState().setBackendMaxGraphNodes(maxNodes)
|
||||
|
||||
// Auto-adjust current graphMaxNodes if it exceeds the new backend limit
|
||||
const currentMaxNodes = useSettingsStore.getState().graphMaxNodes
|
||||
if (currentMaxNodes > maxNodes) {
|
||||
useSettingsStore.getState().setGraphMaxNodes(maxNodes, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
set({
|
||||
health: true,
|
||||
message: null,
|
||||
messageTitle: null,
|
||||
lastCheckTime: Date.now(),
|
||||
status: health,
|
||||
pipelineBusy: health.pipeline_busy
|
||||
})
|
||||
return true
|
||||
}
|
||||
set({
|
||||
health: false,
|
||||
message: health.message,
|
||||
messageTitle: 'Backend Health Check Error!',
|
||||
lastCheckTime: Date.now(),
|
||||
status: null
|
||||
})
|
||||
return false
|
||||
},
|
||||
|
||||
clear: () => {
|
||||
set({ health: true, message: null, messageTitle: null })
|
||||
},
|
||||
|
||||
setErrorMessage: (message: string, messageTitle: string) => {
|
||||
set({ health: false, message, messageTitle })
|
||||
},
|
||||
|
||||
setPipelineBusy: (busy: boolean) => {
|
||||
set({ pipelineBusy: busy })
|
||||
},
|
||||
|
||||
setHealthCheckFunction: (fn: () => void) => {
|
||||
set({ healthCheckFunction: fn })
|
||||
},
|
||||
|
||||
resetHealthCheckTimer: () => {
|
||||
const { healthCheckIntervalId, healthCheckFunction, healthCheckIntervalValue } = get()
|
||||
if (healthCheckIntervalId) {
|
||||
clearInterval(healthCheckIntervalId)
|
||||
}
|
||||
if (healthCheckFunction) {
|
||||
healthCheckFunction() // run health check immediately
|
||||
const newIntervalId = setInterval(healthCheckFunction, healthCheckIntervalValue)
|
||||
set({ healthCheckIntervalId: newIntervalId })
|
||||
}
|
||||
},
|
||||
|
||||
resetHealthCheckTimerDelayed: (delayMs: number) => {
|
||||
setTimeout(() => {
|
||||
get().resetHealthCheckTimer()
|
||||
}, delayMs)
|
||||
},
|
||||
|
||||
clearHealthCheckTimer: () => {
|
||||
const { healthCheckIntervalId } = get()
|
||||
if (healthCheckIntervalId) {
|
||||
clearInterval(healthCheckIntervalId)
|
||||
set({ healthCheckIntervalId: null })
|
||||
}
|
||||
}
|
||||
}))
|
||||
|
||||
const useBackendState = createSelectors(useBackendStateStoreBase)
|
||||
|
||||
export { useBackendState }
|
||||
|
||||
const parseTokenPayload = (token: string): { sub?: string; role?: string } => {
|
||||
try {
|
||||
// JWT tokens are in the format: header.payload.signature
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) return {};
|
||||
const payload = JSON.parse(atob(parts[1]));
|
||||
return payload;
|
||||
} catch (e) {
|
||||
console.error('Error parsing token payload:', e);
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
const getUsernameFromToken = (token: string): string | null => {
|
||||
const payload = parseTokenPayload(token);
|
||||
return payload.sub || null;
|
||||
};
|
||||
|
||||
const isGuestToken = (token: string): boolean => {
|
||||
const payload = parseTokenPayload(token);
|
||||
return payload.role === 'guest';
|
||||
};
|
||||
|
||||
const initAuthState = (): { isAuthenticated: boolean; isGuestMode: boolean; coreVersion: string | null; apiVersion: string | null; username: string | null; webuiTitle: string | null; webuiDescription: string | null } => {
|
||||
const token = localStorage.getItem('LIGHTRAG-API-TOKEN');
|
||||
const coreVersion = localStorage.getItem('LIGHTRAG-CORE-VERSION');
|
||||
const apiVersion = localStorage.getItem('LIGHTRAG-API-VERSION');
|
||||
const webuiTitle = localStorage.getItem('LIGHTRAG-WEBUI-TITLE');
|
||||
const webuiDescription = localStorage.getItem('LIGHTRAG-WEBUI-DESCRIPTION');
|
||||
const username = token ? getUsernameFromToken(token) : null;
|
||||
|
||||
if (!token) {
|
||||
return {
|
||||
isAuthenticated: false,
|
||||
isGuestMode: false,
|
||||
coreVersion: coreVersion,
|
||||
apiVersion: apiVersion,
|
||||
username: null,
|
||||
webuiTitle: webuiTitle,
|
||||
webuiDescription: webuiDescription,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
isAuthenticated: true,
|
||||
isGuestMode: isGuestToken(token),
|
||||
coreVersion: coreVersion,
|
||||
apiVersion: apiVersion,
|
||||
username: username,
|
||||
webuiTitle: webuiTitle,
|
||||
webuiDescription: webuiDescription,
|
||||
};
|
||||
};
|
||||
|
||||
export const useAuthStore = create<AuthState>(set => {
|
||||
// Get initial state from localStorage
|
||||
const initialState = initAuthState();
|
||||
|
||||
return {
|
||||
isAuthenticated: initialState.isAuthenticated,
|
||||
isGuestMode: initialState.isGuestMode,
|
||||
coreVersion: initialState.coreVersion,
|
||||
apiVersion: initialState.apiVersion,
|
||||
username: initialState.username,
|
||||
webuiTitle: initialState.webuiTitle,
|
||||
webuiDescription: initialState.webuiDescription,
|
||||
|
||||
login: (token, isGuest = false, coreVersion = null, apiVersion = null, webuiTitle = null, webuiDescription = null) => {
|
||||
localStorage.setItem('LIGHTRAG-API-TOKEN', token);
|
||||
|
||||
if (coreVersion) {
|
||||
localStorage.setItem('LIGHTRAG-CORE-VERSION', coreVersion);
|
||||
}
|
||||
if (apiVersion) {
|
||||
localStorage.setItem('LIGHTRAG-API-VERSION', apiVersion);
|
||||
}
|
||||
|
||||
if (webuiTitle) {
|
||||
localStorage.setItem('LIGHTRAG-WEBUI-TITLE', webuiTitle);
|
||||
} else {
|
||||
localStorage.removeItem('LIGHTRAG-WEBUI-TITLE');
|
||||
}
|
||||
|
||||
if (webuiDescription) {
|
||||
localStorage.setItem('LIGHTRAG-WEBUI-DESCRIPTION', webuiDescription);
|
||||
} else {
|
||||
localStorage.removeItem('LIGHTRAG-WEBUI-DESCRIPTION');
|
||||
}
|
||||
|
||||
const username = getUsernameFromToken(token);
|
||||
set({
|
||||
isAuthenticated: true,
|
||||
isGuestMode: isGuest,
|
||||
username: username,
|
||||
coreVersion: coreVersion,
|
||||
apiVersion: apiVersion,
|
||||
webuiTitle: webuiTitle,
|
||||
webuiDescription: webuiDescription,
|
||||
});
|
||||
},
|
||||
|
||||
logout: () => {
|
||||
localStorage.removeItem('LIGHTRAG-API-TOKEN');
|
||||
|
||||
const coreVersion = localStorage.getItem('LIGHTRAG-CORE-VERSION');
|
||||
const apiVersion = localStorage.getItem('LIGHTRAG-API-VERSION');
|
||||
const webuiTitle = localStorage.getItem('LIGHTRAG-WEBUI-TITLE');
|
||||
const webuiDescription = localStorage.getItem('LIGHTRAG-WEBUI-DESCRIPTION');
|
||||
|
||||
set({
|
||||
isAuthenticated: false,
|
||||
isGuestMode: false,
|
||||
username: null,
|
||||
coreVersion: coreVersion,
|
||||
apiVersion: apiVersion,
|
||||
webuiTitle: webuiTitle,
|
||||
webuiDescription: webuiDescription,
|
||||
});
|
||||
},
|
||||
|
||||
setVersion: (coreVersion, apiVersion) => {
|
||||
// Update localStorage
|
||||
if (coreVersion) {
|
||||
localStorage.setItem('LIGHTRAG-CORE-VERSION', coreVersion);
|
||||
}
|
||||
if (apiVersion) {
|
||||
localStorage.setItem('LIGHTRAG-API-VERSION', apiVersion);
|
||||
}
|
||||
|
||||
// Update state
|
||||
set({
|
||||
coreVersion: coreVersion,
|
||||
apiVersion: apiVersion
|
||||
});
|
||||
},
|
||||
|
||||
setCustomTitle: (webuiTitle, webuiDescription) => {
|
||||
// Update localStorage
|
||||
if (webuiTitle) {
|
||||
localStorage.setItem('LIGHTRAG-WEBUI-TITLE', webuiTitle);
|
||||
} else {
|
||||
localStorage.removeItem('LIGHTRAG-WEBUI-TITLE');
|
||||
}
|
||||
|
||||
if (webuiDescription) {
|
||||
localStorage.setItem('LIGHTRAG-WEBUI-DESCRIPTION', webuiDescription);
|
||||
} else {
|
||||
localStorage.removeItem('LIGHTRAG-WEBUI-DESCRIPTION');
|
||||
}
|
||||
|
||||
// Update state
|
||||
set({
|
||||
webuiTitle: webuiTitle,
|
||||
webuiDescription: webuiDescription
|
||||
});
|
||||
}
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user