Skip to content

Commit 8e6b599

Browse files
committed
removed dead code
1 parent b453d11 commit 8e6b599

File tree

8 files changed

+120
-437
lines changed

8 files changed

+120
-437
lines changed

apps/sim/app/workspace/[workspaceId]/knowledge/[id]/[documentId]/components/edit-chunk-modal/edit-chunk-modal.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ export function EditChunkModal({
5050
totalPages = 1,
5151
onNavigateToChunk,
5252
onNavigateToPage,
53-
maxChunkSize = 1024,
53+
maxChunkSize,
5454
}: EditChunkModalProps) {
5555
const queryClient = useQueryClient()
5656
const userPermissions = useUserPermissionsContext()
@@ -339,7 +339,8 @@ export function EditChunkModal({
339339
<Switch checked={tokenizerOn} onCheckedChange={setTokenizerOn} />
340340
</div>
341341
<span className='text-[12px] text-[var(--text-secondary)]'>
342-
{tokenCount.toLocaleString()}/{maxChunkSize.toLocaleString()}
342+
{tokenCount.toLocaleString()}
343+
{maxChunkSize !== undefined && `/${maxChunkSize.toLocaleString()}`} tokens
343344
</span>
344345
</div>
345346
</ModalBody>

apps/sim/app/workspace/[workspaceId]/knowledge/[id]/[documentId]/document.tsx

Lines changed: 17 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ import {
3535
import { Input } from '@/components/ui/input'
3636
import { SearchHighlight } from '@/components/ui/search-highlight'
3737
import { Skeleton } from '@/components/ui/skeleton'
38-
import type { ChunkData, DocumentData } from '@/lib/knowledge/types'
38+
import type { ChunkData } from '@/lib/knowledge/types'
3939
import {
4040
CreateChunkModal,
4141
DeleteChunkModal,
@@ -45,11 +45,7 @@ import {
4545
import { ActionBar } from '@/app/workspace/[workspaceId]/knowledge/[id]/components'
4646
import { useUserPermissionsContext } from '@/app/workspace/[workspaceId]/providers/workspace-permissions-provider'
4747
import { knowledgeKeys } from '@/hooks/queries/knowledge'
48-
import {
49-
useCachedDocuments,
50-
useCachedKnowledgeBase,
51-
useDocumentChunks,
52-
} from '@/hooks/use-knowledge'
48+
import { useDocument, useDocumentChunks, useKnowledgeBase } from '@/hooks/use-knowledge'
5349

5450
const logger = createLogger('Document')
5551

@@ -271,15 +267,12 @@ export function Document({
271267
const currentPageFromURL = Number.parseInt(searchParams.get('page') || '1', 10)
272268
const userPermissions = useUserPermissionsContext()
273269

274-
const cachedKnowledgeBase = useCachedKnowledgeBase(knowledgeBaseId)
275-
const cachedDocumentsData = useCachedDocuments(knowledgeBaseId)
276-
277-
/**
278-
* Get cached document synchronously for immediate render
279-
*/
280-
const getInitialCachedDocument = useCallback(() => {
281-
return cachedDocumentsData?.documents?.find((d: DocumentData) => d.id === documentId) || null
282-
}, [cachedDocumentsData, documentId])
270+
const { knowledgeBase } = useKnowledgeBase(knowledgeBaseId)
271+
const {
272+
document: documentData,
273+
isLoading: isLoadingDocument,
274+
error: documentError,
275+
} = useDocument(knowledgeBaseId, documentId)
283276

284277
const [showTagsModal, setShowTagsModal] = useState(false)
285278

@@ -298,9 +291,7 @@ export function Document({
298291
refreshChunks: initialRefreshChunks,
299292
updateChunk: initialUpdateChunk,
300293
isFetching: isFetchingChunks,
301-
} = useDocumentChunks(knowledgeBaseId, documentId, currentPageFromURL, '', {
302-
enableClientSearch: false,
303-
})
294+
} = useDocumentChunks(knowledgeBaseId, documentId, currentPageFromURL)
304295

305296
const [searchResults, setSearchResults] = useState<ChunkData[]>([])
306297
const [isLoadingSearch, setIsLoadingSearch] = useState(false)
@@ -436,67 +427,16 @@ export function Document({
436427
const refreshChunks = showingSearch ? async () => {} : initialRefreshChunks
437428
const updateChunk = showingSearch ? (id: string, updates: any) => {} : initialUpdateChunk
438429

439-
const initialCachedDoc = getInitialCachedDocument()
440-
const [documentData, setDocumentData] = useState<DocumentData | null>(initialCachedDoc)
441-
const [isLoadingDocument, setIsLoadingDocument] = useState(!initialCachedDoc)
442-
const [error, setError] = useState<string | null>(null)
443-
444430
const [isCreateChunkModalOpen, setIsCreateChunkModalOpen] = useState(false)
445431
const [chunkToDelete, setChunkToDelete] = useState<ChunkData | null>(null)
446432
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
447433
const [isBulkOperating, setIsBulkOperating] = useState(false)
448434
const [showDeleteDocumentDialog, setShowDeleteDocumentDialog] = useState(false)
449435
const [isDeletingDocument, setIsDeletingDocument] = useState(false)
450436

451-
const combinedError = error || searchError || initialError
437+
const combinedError = documentError || searchError || initialError
452438

453-
useEffect(() => {
454-
const fetchDocument = async () => {
455-
const cachedDoc = cachedDocumentsData?.documents?.find(
456-
(d: DocumentData) => d.id === documentId
457-
)
458-
459-
if (cachedDoc) {
460-
setDocumentData(cachedDoc)
461-
setIsLoadingDocument(false)
462-
return
463-
}
464-
465-
setIsLoadingDocument(true)
466-
setError(null)
467-
468-
try {
469-
const response = await fetch(`/api/knowledge/${knowledgeBaseId}/documents/${documentId}`)
470-
471-
if (!response.ok) {
472-
if (response.status === 404) {
473-
throw new Error('Document not found')
474-
}
475-
throw new Error(`Failed to fetch document: ${response.statusText}`)
476-
}
477-
478-
const result = await response.json()
479-
480-
if (result.success) {
481-
setDocumentData(result.data)
482-
} else {
483-
throw new Error(result.error || 'Failed to fetch document')
484-
}
485-
} catch (err) {
486-
logger.error('Error fetching document:', err)
487-
setError(err instanceof Error ? err.message : 'An error occurred')
488-
} finally {
489-
setIsLoadingDocument(false)
490-
}
491-
}
492-
493-
if (knowledgeBaseId && documentId) {
494-
fetchDocument()
495-
}
496-
}, [knowledgeBaseId, documentId, cachedDocumentsData])
497-
498-
const effectiveKnowledgeBaseName =
499-
cachedKnowledgeBase?.name || knowledgeBaseName || 'Knowledge Base'
439+
const effectiveKnowledgeBaseName = knowledgeBase?.name || knowledgeBaseName || 'Knowledge Base'
500440
const effectiveDocumentName = documentData?.filename || documentName || 'Document'
501441

502442
const breadcrumbItems = [
@@ -702,15 +642,11 @@ export function Document({
702642

703643
const isAllSelected = displayChunks.length > 0 && selectedChunks.size === displayChunks.length
704644

705-
const handleDocumentTagsUpdate = useCallback(
706-
(tagData: Record<string, string>) => {
707-
setDocumentData((prev) => (prev ? { ...prev, ...tagData } : null))
708-
queryClient.invalidateQueries({
709-
queryKey: knowledgeKeys.detail(knowledgeBaseId),
710-
})
711-
},
712-
[knowledgeBaseId, queryClient]
713-
)
645+
const handleDocumentTagsUpdate = useCallback(() => {
646+
queryClient.invalidateQueries({
647+
queryKey: knowledgeKeys.document(knowledgeBaseId, documentId),
648+
})
649+
}, [knowledgeBaseId, documentId, queryClient])
714650

715651
const prevDocumentIdRef = useRef<string>(documentId)
716652
const isNavigatingToNewDoc = prevDocumentIdRef.current !== documentId
@@ -1139,7 +1075,7 @@ export function Document({
11391075
onNavigateToChunk={(chunk: ChunkData) => {
11401076
setSelectedChunk(chunk)
11411077
}}
1142-
maxChunkSize={cachedKnowledgeBase?.chunkingConfig?.maxSize}
1078+
maxChunkSize={knowledgeBase?.chunkingConfig?.maxSize}
11431079
onNavigateToPage={async (page: number, selectChunk: 'first' | 'last') => {
11441080
await goToPage(page)
11451081

apps/sim/app/workspace/[workspaceId]/knowledge/[id]/base.tsx

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -593,7 +593,6 @@ export function KnowledgeBase({
593593

594594
const newEnabled = !document.enabled
595595

596-
// Optimistic update - immediately update the UI
597596
updateDocument(docId, { enabled: newEnabled })
598597

599598
try {
@@ -614,11 +613,9 @@ export function KnowledgeBase({
614613
const result = await response.json()
615614

616615
if (!result.success) {
617-
// Revert on failure
618616
updateDocument(docId, { enabled: !newEnabled })
619617
}
620618
} catch (err) {
621-
// Revert on error
622619
updateDocument(docId, { enabled: !newEnabled })
623620
logger.error('Error updating document:', err)
624621
}
@@ -842,15 +839,13 @@ export function KnowledgeBase({
842839
const result = await response.json()
843840

844841
if (result.success) {
845-
// Update successful documents in the store
846842
result.data.updatedDocuments.forEach((updatedDoc: { id: string; enabled: boolean }) => {
847843
updateDocument(updatedDoc.id, { enabled: updatedDoc.enabled })
848844
})
849845

850846
logger.info(`Successfully enabled ${result.data.successCount} documents`)
851847
}
852848

853-
// Clear selection after successful operation
854849
setSelectedDocuments(new Set())
855850
} catch (err) {
856851
logger.error('Error enabling documents:', err)
@@ -960,20 +955,15 @@ export function KnowledgeBase({
960955
const enabledCount = selectedDocumentsList.filter((doc) => doc.enabled).length
961956
const disabledCount = selectedDocumentsList.filter((doc) => !doc.enabled).length
962957

963-
// Track previous KB id to detect navigation between different knowledge bases
964958
const prevKnowledgeBaseIdRef = useRef<string>(id)
965959
const isNavigatingToNewKB = prevKnowledgeBaseIdRef.current !== id
966960

967-
// Update ref when KB data loads successfully
968961
useEffect(() => {
969962
if (knowledgeBase && knowledgeBase.id === id) {
970963
prevKnowledgeBaseIdRef.current = id
971964
}
972965
}, [knowledgeBase, id])
973966

974-
// Show full page skeleton when:
975-
// 1. Initial load (no KB data yet), OR
976-
// 2. Navigating to a different KB (showing placeholder data from previous KB)
977967
const isInitialLoad = isLoadingKnowledgeBase && !knowledgeBase
978968
const isFetchingNewKB = isNavigatingToNewKB && isFetchingDocuments
979969

apps/sim/app/workspace/[workspaceId]/knowledge/components/knowledge-header/knowledge-header.tsx

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,12 +125,10 @@ export function KnowledgeHeader({ breadcrumbs, options }: KnowledgeHeaderProps)
125125
`Knowledge base workspace updated: ${options.knowledgeBaseId} -> ${workspaceId}`
126126
)
127127

128-
// Invalidate React Query cache
129128
await queryClient.invalidateQueries({
130129
queryKey: knowledgeKeys.detail(options.knowledgeBaseId),
131130
})
132131

133-
// Notify parent component of the change to refresh data
134132
await options.onWorkspaceChange?.(workspaceId)
135133
} else {
136134
throw new Error(result.error || 'Failed to update workspace')

apps/sim/hooks/queries/knowledge.ts

Lines changed: 34 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { createLogger } from '@sim/logger'
2-
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
1+
import { keepPreviousData, useQuery } from '@tanstack/react-query'
32
import type {
43
ChunkData,
54
ChunksPagination,
@@ -8,23 +7,17 @@ import type {
87
KnowledgeBaseData,
98
} from '@/lib/knowledge/types'
109

11-
const logger = createLogger('KnowledgeQueries')
12-
1310
export const knowledgeKeys = {
1411
all: ['knowledge'] as const,
1512
list: (workspaceId?: string) => [...knowledgeKeys.all, 'list', workspaceId ?? 'all'] as const,
1613
detail: (knowledgeBaseId?: string) =>
1714
[...knowledgeKeys.all, 'detail', knowledgeBaseId ?? ''] as const,
1815
documents: (knowledgeBaseId: string, paramsKey: string) =>
1916
[...knowledgeKeys.detail(knowledgeBaseId), 'documents', paramsKey] as const,
17+
document: (knowledgeBaseId: string, documentId: string) =>
18+
[...knowledgeKeys.detail(knowledgeBaseId), 'document', documentId] as const,
2019
chunks: (knowledgeBaseId: string, documentId: string, paramsKey: string) =>
21-
[
22-
...knowledgeKeys.detail(knowledgeBaseId),
23-
'document',
24-
documentId,
25-
'chunks',
26-
paramsKey,
27-
] as const,
20+
[...knowledgeKeys.document(knowledgeBaseId, documentId), 'chunks', paramsKey] as const,
2821
}
2922

3023
export async function fetchKnowledgeBases(workspaceId?: string): Promise<KnowledgeBaseData[]> {
@@ -58,6 +51,27 @@ export async function fetchKnowledgeBase(knowledgeBaseId: string): Promise<Knowl
5851
return result.data
5952
}
6053

54+
export async function fetchDocument(
55+
knowledgeBaseId: string,
56+
documentId: string
57+
): Promise<DocumentData> {
58+
const response = await fetch(`/api/knowledge/${knowledgeBaseId}/documents/${documentId}`)
59+
60+
if (!response.ok) {
61+
if (response.status === 404) {
62+
throw new Error('Document not found')
63+
}
64+
throw new Error(`Failed to fetch document: ${response.status} ${response.statusText}`)
65+
}
66+
67+
const result = await response.json()
68+
if (!result?.success || !result?.data) {
69+
throw new Error(result?.error || 'Failed to fetch document')
70+
}
71+
72+
return result.data
73+
}
74+
6175
export interface KnowledgeDocumentsParams {
6276
knowledgeBaseId: string
6377
search?: string
@@ -192,6 +206,15 @@ export function useKnowledgeBaseQuery(knowledgeBaseId?: string) {
192206
})
193207
}
194208

209+
export function useDocumentQuery(knowledgeBaseId?: string, documentId?: string) {
210+
return useQuery({
211+
queryKey: knowledgeKeys.document(knowledgeBaseId ?? '', documentId ?? ''),
212+
queryFn: () => fetchDocument(knowledgeBaseId as string, documentId as string),
213+
enabled: Boolean(knowledgeBaseId && documentId),
214+
staleTime: 60 * 1000,
215+
})
216+
}
217+
195218
export const serializeDocumentParams = (params: KnowledgeDocumentsParams) =>
196219
JSON.stringify({
197220
search: params.search ?? '',
@@ -239,61 +262,3 @@ export function useKnowledgeChunksQuery(
239262
placeholderData: keepPreviousData,
240263
})
241264
}
242-
243-
interface UpdateDocumentPayload {
244-
knowledgeBaseId: string
245-
documentId: string
246-
updates: Partial<DocumentData>
247-
}
248-
249-
export function useMutateKnowledgeDocument() {
250-
const queryClient = useQueryClient()
251-
return useMutation({
252-
mutationFn: async ({ knowledgeBaseId, documentId, updates }: UpdateDocumentPayload) => {
253-
const response = await fetch(`/api/knowledge/${knowledgeBaseId}/documents/${documentId}`, {
254-
method: 'PUT',
255-
headers: {
256-
'Content-Type': 'application/json',
257-
},
258-
body: JSON.stringify(updates),
259-
})
260-
261-
if (!response.ok) {
262-
const errorData = await response.json().catch(() => ({}))
263-
throw new Error(errorData.error || 'Failed to update document')
264-
}
265-
266-
const result = await response.json()
267-
if (!result?.success) {
268-
throw new Error(result?.error || 'Failed to update document')
269-
}
270-
271-
return result
272-
},
273-
onMutate: async ({ knowledgeBaseId, documentId, updates }) => {
274-
await queryClient.cancelQueries({ queryKey: knowledgeKeys.detail(knowledgeBaseId) })
275-
276-
const documentQueries = queryClient
277-
.getQueriesData<KnowledgeDocumentsResponse>({
278-
queryKey: knowledgeKeys.detail(knowledgeBaseId),
279-
})
280-
.filter(([key]) => Array.isArray(key) && key.includes('documents'))
281-
282-
documentQueries.forEach(([key, data]) => {
283-
if (!data) return
284-
queryClient.setQueryData(key, {
285-
...data,
286-
documents: data.documents.map((doc) =>
287-
doc.id === documentId ? { ...doc, ...updates } : doc
288-
),
289-
})
290-
})
291-
},
292-
onError: (error) => {
293-
logger.error('Failed to mutate document', error)
294-
},
295-
onSettled: (_data, _error, variables) => {
296-
queryClient.invalidateQueries({ queryKey: knowledgeKeys.detail(variables.knowledgeBaseId) })
297-
},
298-
})
299-
}

0 commit comments

Comments
 (0)