Merge pull request #71 from shumaiOne/feat/remove-includecount-and-enhance-search-dialog

feat(search): remove includeCount and add infinite scroll to search dialog
This commit is contained in:
Yiling-J
2026-06-07 23:29:14 +08:00
committed by GitHub
10 changed files with 268 additions and 152 deletions
+1 -1
View File
@@ -824,7 +824,7 @@ export async function executeAgentToolActivity(params: ExecuteAgentToolParams):
})
},
async () => prisma.asset.count({ where }),
{ first: limit, after, includeCount: true },
{ first: limit, after },
)
// return asset id, asset name, asset type, asset size (sizeByte or size)
+6 -3
View File
@@ -77,7 +77,8 @@ export class AuthzService {
},
})
if (!pm) throw new HTTPException(403, { message: `User is not a member of project ${projectId}` })
if (!pm)
throw new HTTPException(403, { message: `User is not a member of project ${projectId}` })
return this.checkRole(pm.role, req.permission)
}
@@ -174,7 +175,8 @@ export class AuthzService {
})
return { teamId: proj!.teamId, projectId: field.projectId }
}
if (!field.teamId) throw new HTTPException(403, { message: 'Metadata field has no context' })
if (!field.teamId)
throw new HTTPException(403, { message: 'Metadata field has no context' })
return { teamId: field.teamId }
}
@@ -211,7 +213,8 @@ export class AuthzService {
include: { asset: { include: { project: true } } },
})
if (!comment) throw new HTTPException(404, { message: 'Comment not found' })
if (!comment.asset.project) throw new HTTPException(403, { message: 'Comment asset has no project' })
if (!comment.asset.project)
throw new HTTPException(403, { message: 'Comment asset has no project' })
return { teamId: comment.asset.project.teamId, projectId: comment.asset.projectId! }
}
@@ -99,7 +99,6 @@ describe('CollectionService', () => {
// List first page
const list1 = await collectionService.listCollections(project.id, {
first: 2,
includeCount: true,
})
expect(list1.data.length).toBe(2)
expect(list1.pageInfo.total).toBe(5)
@@ -283,7 +283,6 @@ export class NotificationService {
{
after: params.after,
first: params.pageSize,
includeCount: false,
},
)
}
+1 -2
View File
@@ -8,7 +8,6 @@ const key = new Uint8Array([
export interface PaginationParams {
first?: number
after?: string
includeCount?: boolean
}
export interface PageInfo {
@@ -41,7 +40,7 @@ export async function paginateQuery<T>(
): Promise<PaginatedData<T[]>> {
const info: PageInfo = {}
if (params.includeCount && countFn) {
if (countFn) {
info.total = await countFn()
}
+59 -67
View File
@@ -154,43 +154,39 @@ export class SearchService {
}
const pageInfo: PageInfo = {}
if (req.includeCount) {
const countBuilder = new SqlQueryBuilder()
.select(Prisma.sql`COUNT(*)`)
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
const countBuilder = new SqlQueryBuilder()
.select(Prisma.sql`COUNT(*)`)
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
countBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
countBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
countBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
if (nameCond) {
const valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
countBuilder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else {
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
}
const countRes = await this.prismaClient.$queryRaw<{ count: bigint }[]>(
countBuilder.build(),
)
pageInfo.total = Number(countRes[0]?.count || 0)
if (targetFolderIds.length > 0) {
countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
countBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
countBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
countBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
if (nameCond) {
const valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
countBuilder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else {
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
}
const countRes = await this.prismaClient.$queryRaw<{ count: bigint }[]>(countBuilder.build())
pageInfo.total = Number(countRes[0]?.count || 0)
if (hasNextPage) {
pageInfo.cursor = encodeCursor(offset + limit)
@@ -342,40 +338,36 @@ export class SearchService {
}
const pageInfo: PageInfo = {}
if (req.includeCount) {
if (countOverride !== undefined) {
pageInfo.total = countOverride
} else {
const countBuilder = new SqlQueryBuilder()
.select(Prisma.sql`COUNT(*)`)
.from(Prisma.sql`assets a`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (countOverride !== undefined) {
pageInfo.total = countOverride
} else {
const countBuilder = new SqlQueryBuilder()
.select(Prisma.sql`COUNT(*)`)
.from(Prisma.sql`assets a`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
countBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
countBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
countBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
if (nameCond) {
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
const countRes = await this.prismaClient.$queryRaw<{ count: bigint }[]>(
countBuilder.build(),
)
pageInfo.total = Number(countRes[0]?.count || 0)
if (targetFolderIds.length > 0) {
countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
countBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
countBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
countBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
if (nameCond) {
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
const countRes = await this.prismaClient.$queryRaw<{ count: bigint }[]>(countBuilder.build())
pageInfo.total = Number(countRes[0]?.count || 0)
}
if (hasNextPage) {
-4
View File
@@ -10,10 +10,6 @@ export type PaginationPageInfo = z.infer<typeof paginationPageInfoSchema>
export const paginationParamsSchema = z.object({
first: z.coerce.number().optional(),
after: z.string().optional(),
includeCount: z
.union([z.boolean(), z.string()])
.transform((v) => v === true || v === 'true')
.optional(),
})
export type PaginationParams = z.infer<typeof paginationParamsSchema>
@@ -1,15 +1,16 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { s3Service } from '@shumai/core/src/s3/s3'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { transcodeService } from '../transcode'
import {
getMediaInfoActivity,
overlayAnnotationsActivity,
takeScreenshotsActivity,
transcodeVideoActivity,
updateAssetMediaActivity,
takeScreenshotsActivity,
overlayAnnotationsActivity,
} from './transcode'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '../transcode'
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
@@ -17,6 +18,7 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
putObject: vi.fn(),
headObject: vi.fn(),
presign: vi.fn(),
downloadToFile: vi.fn(),
},
}))
@@ -32,11 +34,20 @@ vi.mock('../transcode', () => ({
},
}))
vi.mock('@shumai/core/src/metadata/metadata', () => ({
metadataService: {
updateAssetMetadata: vi.fn(),
},
}))
vi.mock('fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('fs')>()
return {
...actual,
readFileSync: vi.fn().mockReturnValue(Buffer.from('fake data')),
existsSync: vi.fn().mockReturnValue(true),
mkdirSync: vi.fn(),
unlinkSync: vi.fn(),
}
})
@@ -47,7 +58,7 @@ describe('Transcode Activities', () => {
vi.clearAllMocks()
})
it('should call getVideoInfo for video assets', async () => {
it('should call getVideoInfo and set file_type to video', async () => {
const asset = await prisma.asset.create({
data: { name: 'v.mp4', type: 'file', status: 'uploaded' },
})
@@ -80,9 +91,14 @@ describe('Transcode Activities', () => {
expect(result.metadata?.audioChannels).toBe(2)
expect(result.metadata?.audioSampleRate).toBe(48000)
expect(result.metadata?.audioBitDepth).toBe(16)
expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith(
asset.id,
expect.arrayContaining([{ key: 'file_type', value: 'video' }]),
true,
)
})
it('should call getImageInfo for image assets', async () => {
it('should call getImageInfo and set file_type to image', async () => {
const asset = await prisma.asset.create({
data: { name: 'i.png', type: 'file', status: 'uploaded' },
})
@@ -105,6 +121,65 @@ describe('Transcode Activities', () => {
expect(transcodeService.getImageInfo).toHaveBeenCalledWith('/tmp/i.png')
expect(result.metadata?.originalWidth).toBe(800)
expect(result.metadata?.duration).toBe(0)
expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith(
asset.id,
expect.arrayContaining([{ key: 'file_type', value: 'image' }]),
true,
)
})
it('should set file_type to audio for audio files', async () => {
const asset = await prisma.asset.create({
data: { name: 'a.mp3', type: 'file', status: 'uploaded' },
})
await getMediaInfoActivity({
assetId: asset.id,
filePath: '/tmp/a.mp3',
mediaType: 'audio/mpeg',
})
expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith(
asset.id,
expect.arrayContaining([{ key: 'file_type', value: 'audio' }]),
true,
)
})
it('should set file_type to document for pdf/text files', async () => {
const asset = await prisma.asset.create({
data: { name: 'd.pdf', type: 'file', status: 'uploaded' },
})
await getMediaInfoActivity({
assetId: asset.id,
filePath: '/tmp/d.pdf',
mediaType: 'application/pdf',
})
expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith(
asset.id,
expect.arrayContaining([{ key: 'file_type', value: 'document' }]),
true,
)
})
it('should set file_type to file for unknown types', async () => {
const asset = await prisma.asset.create({
data: { name: 'u.xyz', type: 'file', status: 'uploaded' },
})
await getMediaInfoActivity({
assetId: asset.id,
filePath: '/tmp/u.xyz',
mediaType: 'application/octet-stream',
})
expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith(
asset.id,
expect.arrayContaining([{ key: 'file_type', value: 'file' }]),
true,
)
})
it('should update asset media field', async () => {
+28 -11
View File
@@ -19,6 +19,23 @@ export async function getMediaInfoActivity(params: {
}): Promise<PrismaJson.MediaInfo> {
const isVideo = params.mediaType.startsWith('video/')
const isImage = params.mediaType.startsWith('image/')
const isAudio = params.mediaType.startsWith('audio/')
const isDocument =
params.mediaType.startsWith('text/') ||
params.mediaType === 'application/pdf' ||
params.mediaType.includes('msword') ||
params.mediaType.includes('officedocument') ||
params.mediaType.includes('vnd.ms-')
const fileType = isVideo
? 'video'
: isAudio
? 'audio'
: isImage
? 'image'
: isDocument
? 'document'
: 'file'
const mediaInfo: PrismaJson.MediaInfo = {
duration: 0,
@@ -39,6 +56,10 @@ export async function getMediaInfoActivity(params: {
},
}
const metadataUpdates: { key: string; value: string | number }[] = [
{ key: 'file_type', value: fileType },
]
if (isVideo) {
const info = await transcodeService.getVideoInfo(params.filePath)
mediaInfo.duration = info.duration
@@ -57,13 +78,13 @@ export async function getMediaInfoActivity(params: {
audioBitDepth: info.audioBitDepth,
format: {},
}
const metadataUpdates: { key: string; value: string | number }[] = [
metadataUpdates.push(
{ key: 'resolution_width', value: info.originalWidth },
{ key: 'resolution_height', value: info.originalHeight },
{ key: 'duration', value: info.duration },
{ key: 'bitRate', value: info.bitRate / 1000 },
{ key: 'frame_rate', value: info.frameRate },
]
)
if (info.videoCodec) metadataUpdates.push({ key: 'video_codec', value: info.videoCodec })
if (info.audioCodec) metadataUpdates.push({ key: 'audio_codec', value: info.audioCodec })
if (info.audioChannels !== undefined)
@@ -72,8 +93,6 @@ export async function getMediaInfoActivity(params: {
metadataUpdates.push({ key: 'audio_sample_rate', value: info.audioSampleRate })
if (info.audioBitDepth !== undefined)
metadataUpdates.push({ key: 'audio_bit_depth', value: info.audioBitDepth })
await metadataService.updateAssetMetadata(params.assetId, metadataUpdates, true)
} else if (isImage) {
const info = await transcodeService.getImageInfo(params.filePath)
mediaInfo.metadata = {
@@ -85,16 +104,14 @@ export async function getMediaInfoActivity(params: {
hasAudio: false,
format: {},
}
await metadataService.updateAssetMetadata(
params.assetId,
[
{ key: 'resolution_width', value: info.originalWidth },
{ key: 'resolution_height', value: info.originalHeight },
],
true,
metadataUpdates.push(
{ key: 'resolution_width', value: info.originalWidth },
{ key: 'resolution_height', value: info.originalHeight },
)
}
await metadataService.updateAssetMetadata(params.assetId, metadataUpdates, true)
return mediaInfo
}
@@ -9,7 +9,7 @@ import { Label } from '@/ui/components/ui/label'
import { Switch } from '@/ui/components/ui/switch'
import { formatSize } from '@/ui/lib/format'
import { cn } from '@/ui/lib/utils'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import {
AlertCircle,
@@ -22,6 +22,7 @@ import {
X,
} from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { useInView } from 'react-intersection-observer'
import { toast } from 'sonner'
import { FilterPanel } from './filter-panel'
@@ -155,13 +156,18 @@ export function SearchFilterDialog({
},
})
const { ref, inView } = useInView()
const {
data: searchResults,
isLoading,
isFetchingNextPage,
fetchNextPage,
hasNextPage,
error: searchError,
} = useQuery({
} = useInfiniteQuery({
queryKey: ['search-preview', teamId, assetId, combinedConditions, isSemantic, triggerQuery],
queryFn: async () => {
queryFn: async ({ pageParam }) => {
const activeText = triggerQuery
const res = await client.api.folders[':folderId'].search.$post({
param: { folderId: assetId },
@@ -172,19 +178,42 @@ export function SearchFilterDialog({
query: activeText.trim(),
isSemantic: isSemantic,
first: 20,
after: pageParam as string | undefined,
},
})
if (!res.ok) {
const errorData = (await res.json().catch(() => ({}))) as Record<string, unknown>
throw new Error((errorData.message as string) || 'Search failed')
}
return (await res.json()) as { data: AssetInfo[] }
return (await res.json()) as {
data: AssetInfo[]
pageInfo?: { total?: number; cursor?: string }
}
},
enabled: open && hasActiveCriteria,
staleTime: 500,
retry: false,
initialPageParam: '',
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
})
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage) {
fetchNextPage()
}
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
const flattenedResults = useMemo(() => {
return searchResults?.pages.flatMap((page) => page.data) || []
}, [searchResults])
const totalCount = searchResults?.pages[0]?.pageInfo?.total || 0
const formatMatchedCount = (count: number) => {
if (count === 10001) return '10000+'
return count.toString()
}
const handleApply = () => {
onApply(combinedConditions)
onOpenChange(false)
@@ -395,7 +424,7 @@ export function SearchFilterDialog({
</div>
</div>
))
) : searchResults?.data?.length === 0 ? (
) : flattenedResults.length === 0 ? (
<div className="py-12 px-4 text-center flex flex-col items-center justify-center bg-muted/20">
<AlertCircle className="w-10 h-10 text-muted-foreground/30 mb-2" />
<h3 className="text-sm font-semibold text-foreground/80">
@@ -406,62 +435,69 @@ export function SearchFilterDialog({
</p>
</div>
) : (
searchResults?.data?.map((record) => (
<div
key={record.id}
onClick={() => handleResultClick(record)}
className="p-3.5 flex items-center gap-3 hover:bg-muted/40 transition-colors group/record cursor-pointer"
>
<>
{flattenedResults.map((record) => (
<div
className={cn(
'shrink-0 w-11 h-11 rounded-xl shadow-xs flex items-center justify-center text-white font-bold relative group-hover/record:scale-105 transition-transform bg-muted overflow-hidden',
record.type === 'folder' ? 'bg-primary/5' : '',
)}
key={record.id}
onClick={() => handleResultClick(record)}
className="p-3.5 flex items-center gap-3 hover:bg-muted/40 transition-colors group/record cursor-pointer"
>
{record.preview?.thumbnailUrl ? (
<img
src={record.preview.thumbnailUrl}
alt=""
className="w-full h-full object-cover rounded-xl"
/>
) : record.type === 'folder' ? (
<FolderIcon className="h-6 w-6 text-primary/70" />
) : (
<FileIcon className="h-6 w-6 text-muted-foreground" />
)}
</div>
<div
className={cn(
'shrink-0 w-11 h-11 rounded-xl shadow-xs flex items-center justify-center text-white font-bold relative group-hover/record:scale-105 transition-transform bg-muted overflow-hidden',
record.type === 'folder' ? 'bg-primary/5' : '',
)}
>
{record.preview?.thumbnailUrl ? (
<img
src={record.preview.thumbnailUrl}
alt=""
className="w-full h-full object-cover rounded-xl"
/>
) : record.type === 'folder' ? (
<FolderIcon className="h-6 w-6 text-primary/70" />
) : (
<FileIcon className="h-6 w-6 text-muted-foreground" />
)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-3">
<div className="truncate">
<span className="font-medium text-sm text-foreground group-hover/record:text-primary transition-colors block truncate">
{record.name}
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-3">
<div className="truncate">
<span className="font-medium text-sm text-foreground group-hover/record:text-primary transition-colors block truncate">
{record.name}
</span>
<span className="text-xs text-muted-foreground block mt-0.5 truncate">
{record.type === 'folder'
? 'Folder'
: `Size: ${formatSize(record.sizeByte || 0)}`}
</span>
{record.startTime !== undefined &&
record.startTime !== null &&
record.endTime !== undefined &&
record.endTime !== null && (
<span className="text-[10px] font-semibold text-primary bg-primary/10 border border-primary/20 px-1.5 py-0.5 rounded mt-1 inline-block">
Match found at {formatTimestamp(record.startTime)} -{' '}
{formatTimestamp(record.endTime)}
</span>
)}
</div>
<span className="text-xs text-muted-foreground font-mono shrink-0">
{new Date(record.createdAt).toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
})}
</span>
<span className="text-xs text-muted-foreground block mt-0.5 truncate">
{record.type === 'folder'
? 'Folder'
: `Size: ${formatSize(record.sizeByte || 0)}`}
</span>
{record.startTime !== undefined &&
record.startTime !== null &&
record.endTime !== undefined &&
record.endTime !== null && (
<span className="text-[10px] font-semibold text-primary bg-primary/10 border border-primary/20 px-1.5 py-0.5 rounded mt-1 inline-block">
Match found at {formatTimestamp(record.startTime)} -{' '}
{formatTimestamp(record.endTime)}
</span>
)}
</div>
<span className="text-xs text-muted-foreground font-mono shrink-0">
{new Date(record.createdAt).toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
})}
</span>
</div>
</div>
</div>
))
))}
{(hasNextPage || isFetchingNextPage) && (
<div ref={ref} className="p-4 flex justify-center items-center">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
)}
</>
)}
</div>
</div>
@@ -472,7 +508,7 @@ export function SearchFilterDialog({
<span>
Matched{' '}
<strong className="font-mono font-bold text-foreground">
{searchResults?.data?.length || 0}
{formatMatchedCount(totalCount)}
</strong>{' '}
items
</span>