🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(resource): filter library resources by origin (#18170)
Arvin Xu7de6a8cb2861
diff --git a/apps/server/src/routers/lambda/__tests__/file.test.ts b/apps/server/src/routers/lambda/__tests__/file.test.tsindex 44004815e3f..5dc39061364 100644--- a/apps/server/src/routers/lambda/__tests__/file.test.ts+++ b/apps/server/src/routers/lambda/__tests__/file.test.ts@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { KnowledgeRepo } from '@/database/repositories/knowledge';import { fileRouter } from '@/server/routers/lambda/file';import { AsyncTaskStatus } from '@/types/asyncTask';+import { FileSource } from '@/types/files';import { TransferErrorCode } from '@/types/transferError';const buildMockFileAccessUrl = ({ id }: { id: string }) => `https://lobehub.com/f/${id}`;@@ -363,6 +364,48 @@ describe('fileRouter', () => {});});+ it('should persist a known upload source so the origin filter can see it', async () => {+ mockFileModelCheckHash.mockResolvedValue({ isExist: false });+ mockFileModelCreate.mockResolvedValue({ id: 'new-file-id' });++ await caller.createFile({+ hash: 'test-hash',+ fileType: 'image/png',+ metadata: {},+ name: 'pasted.png',+ size: 100,+ source: FileSource.PageEditor,+ url: 'files/pasted.png',+ });++ expect(mockFileModelCreate).toHaveBeenCalledWith(+ expect.objectContaining({ source: FileSource.PageEditor }),+ true,+ routerMocks.transactionClient,+ );+ });++ it('should drop an unrecognised source instead of failing the upload', async () => {+ mockFileModelCheckHash.mockResolvedValue({ isExist: false });+ mockFileModelCreate.mockResolvedValue({ id: 'new-file-id' });++ await caller.createFile({+ hash: 'test-hash',+ fileType: 'image/png',+ metadata: {},+ name: 'pasted.png',+ size: 100,+ source: 'some-future-client',+ url: 'files/pasted.png',+ });++ expect(mockFileModelCreate).toHaveBeenCalledWith(+ expect.objectContaining({ source: undefined }),+ true,+ routerMocks.transactionClient,+ );+ });+it('should refresh global file metadata when an existing hash points to a missing object', async () => {mockFileModelCheckHash.mockResolvedValue({isExist: true,diff --git a/apps/server/src/routers/lambda/file.ts b/apps/server/src/routers/lambda/file.tsindex fce026f7715..00f7fd6d577 100644--- a/apps/server/src/routers/lambda/file.ts+++ b/apps/server/src/routers/lambda/file.ts@@ -24,7 +24,7 @@ import { assertCanPerformResourceAction } from '@/server/services/resourcePermisimport { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';import { AsyncTaskStatus, AsyncTaskType, type IAsyncTaskError } from '@/types/asyncTask';import type { FileListItem, KnowledgeItemStatus } from '@/types/files';-import { QueryFileListSchema, UploadFileSchema } from '@/types/files';+import { QueryFileListSchema, toFileSource, UploadFileSchema } from '@/types/files';import { TransferErrorCode } from '@/types/transferError';import {@@ -280,6 +280,11 @@ export const fileRouter = router({name: input.name,parentId: resolvedParentId,size: actualSize,+ // Attribution the caller supplied (e.g. a page-editor paste). The+ // wire type is a loose string for older clients, so unknown values+ // are dropped rather than persisted — `source` drives the resource+ // library's origin filter and its hidden-source exclusion.+ source: toFileSource(input.source),url: input.url,...(resolvedVisibility ? { visibility: resolvedVisibility } : {}),},diff --git a/locales/en-US/components.json b/locales/en-US/components.jsonindex 0c4a07b383c..6d777f85b38 100644--- a/locales/en-US/components.json+++ b/locales/en-US/components.json@@ -52,6 +52,8 @@"FileManager.emptyStatus.actions.file": "Upload File","FileManager.emptyStatus.actions.folder": "Upload Folder","FileManager.emptyStatus.actions.knowledgeBase": "Create Library",+ "FileManager.emptyStatus.actions.showAllSources": "Show all sources",+ "FileManager.emptyStatus.filteredTitle": "Nothing from this source yet","FileManager.emptyStatus.or": "or","FileManager.emptyStatus.title": "Drag files or folders here","FileManager.image.loadFailed": "Preview unavailable",@@ -62,6 +64,10 @@"FileManager.sort.dateAdded": "Date Added","FileManager.sort.name": "Name","FileManager.sort.size": "Size",+ "FileManager.source.acceptance": "Acceptance",+ "FileManager.source.all": "All",+ "FileManager.source.generated": "AI Generated",+ "FileManager.source.uploaded": "Uploaded","FileManager.title.createdAt": "Created At","FileManager.title.size": "Size","FileManager.title.title": "File",diff --git a/locales/zh-CN/components.json b/locales/zh-CN/components.jsonindex 66d81dbf254..84e2a980f6a 100644--- a/locales/zh-CN/components.json+++ b/locales/zh-CN/components.json@@ -52,6 +52,8 @@"FileManager.emptyStatus.actions.file": "上传文件","FileManager.emptyStatus.actions.folder": "上传文件夹","FileManager.emptyStatus.actions.knowledgeBase": "新建资源库",+ "FileManager.emptyStatus.actions.showAllSources": "查看全部来源",+ "FileManager.emptyStatus.filteredTitle": "该来源下暂无内容","FileManager.emptyStatus.or": "或者","FileManager.emptyStatus.title": "把文件或文件夹拖到这里","FileManager.image.loadFailed": "预览暂时加载不出来",@@ -62,6 +64,10 @@"FileManager.sort.dateAdded": "添加日期","FileManager.sort.name": "名称","FileManager.sort.size": "大小",+ "FileManager.source.acceptance": "验收",+ "FileManager.source.all": "全部",+ "FileManager.source.generated": "AI 生成",+ "FileManager.source.uploaded": "上传","FileManager.title.createdAt": "创建时间","FileManager.title.size": "大小","FileManager.title.title": "文件",diff --git a/packages/database/src/repositories/knowledge/index.test.ts b/packages/database/src/repositories/knowledge/index.test.tsindex f423f5e1b8a..b3bae592f60 100644--- a/packages/database/src/repositories/knowledge/index.test.ts+++ b/packages/database/src/repositories/knowledge/index.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { FileSource, FilesTabs } from '@lobechat/types';+import { FileSource, FilesTabs, ResourceSourceFilter } from '@lobechat/types';import { beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';@@ -1359,6 +1359,104 @@ describe('KnowledgeRepo', () => {});});+ describe('query - source filtering', () => {+ beforeEach(async () => {+ await serverDB.insert(files).values([+ {+ id: 'uploaded-image',+ fileType: 'image/png',+ name: 'screenshot.png',+ size: 100,+ url: 'uploaded-url',+ userId,+ },+ {+ id: 'pasted-image',+ fileType: 'image/png',+ name: 'pasted.png',+ size: 100,+ source: FileSource.PageEditor,+ url: 'pasted-url',+ userId,+ },+ {+ id: 'generated-image',+ fileType: 'image/png',+ name: 'generated.png',+ size: 100,+ source: FileSource.ImageGeneration,+ url: 'generated-url',+ userId,+ },+ {+ id: 'evidence-image',+ fileType: 'image/png',+ name: 'evidence.png',+ size: 100,+ source: FileSource.Acceptance,+ url: 'evidence-url',+ userId,+ },+ ]);+ });++ const queryImageIds = async (sourceFilter?: ResourceSourceFilter) => {+ const result = await knowledgeRepo.query({ category: FilesTabs.Images, sourceFilter });++ return result.map((item) => item.fileId);+ };++ it('should keep the historical pool when the filter is all', async () => {+ const ids = await queryImageIds(ResourceSourceFilter.All);++ expect(ids).toContain('uploaded-image');+ expect(ids).toContain('pasted-image');+ expect(ids).toContain('generated-image');+ expect(ids).not.toContain('evidence-image');+ });++ it('should return only model output when the filter is generated', async () => {+ const ids = await queryImageIds(ResourceSourceFilter.Generated);++ expect(ids).toEqual(['generated-image']);+ });++ it('should treat page-editor images as uploads and exclude generated output', async () => {+ const ids = await queryImageIds(ResourceSourceFilter.Uploaded);++ expect(ids).toContain('uploaded-image');+ expect(ids).toContain('pasted-image');+ expect(ids).not.toContain('generated-image');+ expect(ids).not.toContain('evidence-image');+ });++ it('should surface otherwise-hidden evidence when the filter is acceptance', async () => {+ const ids = await queryImageIds(ResourceSourceFilter.Acceptance);++ expect(ids).toEqual(['evidence-image']);+ });++ it('should drop documents from the union once the filter narrows', async () => {+ await serverDB.insert(documents).values({+ content: 'note body',+ fileType: 'custom/document',+ id: 'source-filter-note',+ source: 'note-source',+ sourceType: 'api',+ title: 'a note',+ totalCharCount: 9,+ totalLineCount: 1,+ userId,+ } as NewDocument);++ const all = await knowledgeRepo.query({ sourceFilter: ResourceSourceFilter.All });+ const generated = await knowledgeRepo.query({ sourceFilter: ResourceSourceFilter.Generated });++ expect(all.map((item) => item.id)).toContain('source-filter-note');+ expect(generated.map((item) => item.id)).not.toContain('source-filter-note');+ });+ });+describe('findById', () => {beforeEach(async () => {await serverDB.insert(files).values({diff --git a/packages/database/src/repositories/knowledge/index.ts b/packages/database/src/repositories/knowledge/index.tsindex f9b41170a07..8468e64906a 100644--- a/packages/database/src/repositories/knowledge/index.ts+++ b/packages/database/src/repositories/knowledge/index.ts@@ -1,12 +1,20 @@import { CUSTOM_DOCUMENT_FILE_TYPE, CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';import type { FileUploader, QueryFileListParams } from '@lobechat/types';-import { FilesTabs, LIBRARY_HIDDEN_FILE_SOURCES, SortType } from '@lobechat/types';+import {+ AI_GENERATED_FILE_SOURCES,+ FileSource,+ FilesTabs,+ LIBRARY_HIDDEN_FILE_SOURCES,+ ResourceSourceFilter,+ SortType,+} from '@lobechat/types';import {and,asc,desc,eq,ilike,+ inArray,isNull,ne,notExists,@@ -249,11 +257,17 @@ export class KnowledgeRepo {* sources that belong to another surface (acceptance evidence). Kept as one* helper so a new listing can't accidentally pick up ownership alone and* start leaking hundreds of verification artifacts back into the library.+ *+ * `sourceFilter` is the only opt-out: asking for `acceptance` explicitly is a+ * request for exactly the rows this predicate otherwise hides, so the+ * exclusion is dropped and `fileSourceFilter` narrows to them instead.*/- private fileScope = () =>+ private fileScope = (sourceFilter?: ResourceSourceFilter) =>and(buildWorkspaceWhere(this.scope(), f),- or(isNull(f.source), notInArray(f.source, LIBRARY_HIDDEN_FILE_SOURCES)),+ sourceFilter === ResourceSourceFilter.Acceptance+ ? undefined+ : or(isNull(f.source), notInArray(f.source, LIBRARY_HIDDEN_FILE_SOURCES)),);private documentScope = () => buildWorkspaceWhere(this.scope(), d);@@ -284,7 +298,11 @@ export class KnowledgeRepo {: undefined,];- private fileArm = (where: (SQL | undefined)[], knowledgeBaseId?: string) => {+ private fileArm = (+ where: (SQL | undefined)[],+ knowledgeBaseId?: string,+ sourceFilter?: ResourceSourceFilter,+ ) => {let query = this.db.select(fileArmColumns).from(f).$dynamic();if (knowledgeBaseId) {@@ -300,7 +318,7 @@ export class KnowledgeRepo {return query.leftJoin(d, eq(d.fileId, f.id)).leftJoin(users, eq(users.id, f.userId))- .where(and(this.fileScope(), ...where));+ .where(and(this.fileScope(sourceFilter), ...where));};private documentArm = (where: (SQL | undefined)[]) =>@@ -324,6 +342,7 @@ export class KnowledgeRepo {parentId,limit = 50,offset = 0,+ sourceFilter,visibility,}: KnowledgeQueryParams = {}): Promise<KnowledgeItem[]> {// If parentId is provided, check if it's a slug and resolve it to an ID@@ -356,10 +375,12 @@ export class KnowledgeRepo {visibility: f.visibility,}),this.fileCategoryFilter(category),+ this.fileSourceFilter(sourceFilter),// Exclude files in knowledge base if needed!knowledgeBaseId && !showFilesInKnowledgeBase ? this.notInAnyKnowledgeBase() : undefined,],knowledgeBaseId,+ sourceFilter,);const documentArm = this.documentArm([@@ -370,6 +391,7 @@ export class KnowledgeRepo {visibility: d.visibility,}),this.documentCategoryFilter(category),+ this.documentSourceFilter(sourceFilter),// Inside a knowledge base only standalone rows (folders and notes with no// backing file) belong to the document arm — documents that do have a file// already come back through the file arm.@@ -496,6 +518,40 @@ export class KnowledgeRepo {return filter === 'none' ? sql`false` : filter;};+ /**+ * Origin narrowing on `files.source`. Uploads are defined by exclusion rather+ * than by `IS NULL` alone: an image pasted into the page editor carries+ * `page-editor` and is still something the user put there, so anything that+ * isn't machine-generated or foreign-owned counts as an upload.+ */+ private fileSourceFilter = (sourceFilter?: ResourceSourceFilter): SQL | undefined => {+ switch (sourceFilter) {+ case ResourceSourceFilter.Acceptance: {+ return eq(f.source, FileSource.Acceptance);+ }+ case ResourceSourceFilter.Generated: {+ return inArray(f.source, AI_GENERATED_FILE_SOURCES);+ }+ case ResourceSourceFilter.Uploaded: {+ return or(+ isNull(f.source),+ notInArray(f.source, [...AI_GENERATED_FILE_SOURCES, ...LIBRARY_HIDDEN_FILE_SOURCES]),+ );+ }+ default: {+ return undefined;+ }+ }+ };++ /**+ * Origin is a file-level notion — documents have no `source` of this kind — so+ * any narrowing at all drops the document arm from the UNION. `all` leaves it+ * untouched.+ */+ private documentSourceFilter = (sourceFilter?: ResourceSourceFilter): SQL | undefined =>+ !sourceFilter || sourceFilter === ResourceSourceFilter.All ? undefined : sql`false`;+/*** Document rows only surface under All and Pages; every file-oriented category* (Documents included) excludes the table entirely.diff --git a/packages/locales/src/default/components.ts b/packages/locales/src/default/components.tsindex 507eba8a6b1..b9b1f2bdab7 100644--- a/packages/locales/src/default/components.ts+++ b/packages/locales/src/default/components.ts@@ -63,6 +63,8 @@ export default {'FileManager.emptyStatus.actions.file': 'Upload File','FileManager.emptyStatus.actions.folder': 'Upload Folder','FileManager.emptyStatus.actions.knowledgeBase': 'Create Library',+ 'FileManager.emptyStatus.actions.showAllSources': 'Show all sources',+ 'FileManager.emptyStatus.filteredTitle': 'Nothing from this source yet','FileManager.emptyStatus.or': 'or','FileManager.emptyStatus.title': 'Drag files or folders here','FileManager.image.loadFailed': 'Preview unavailable',@@ -73,6 +75,10 @@ export default {'FileManager.sort.dateAdded': 'Date Added','FileManager.sort.name': 'Name','FileManager.sort.size': 'Size',+ 'FileManager.source.acceptance': 'Acceptance',+ 'FileManager.source.all': 'All',+ 'FileManager.source.generated': 'AI Generated',+ 'FileManager.source.uploaded': 'Uploaded','FileManager.title.createdAt': 'Created At','FileManager.title.size': 'Size','FileManager.title.title': 'File',diff --git a/packages/types/src/files/index.ts b/packages/types/src/files/index.tsindex d01ee8fc67e..54260d909bd 100644--- a/packages/types/src/files/index.ts+++ b/packages/types/src/files/index.ts@@ -32,9 +32,30 @@ export enum FileSource {* acceptance report renders its evidence via `verify_evidence.file_id`), but* never show up in the resource library listings — a single verification run* uploads hundreds of artifacts and would otherwise bury real content.+ *+ * The one way back in is an explicit `ResourceSourceFilter.Acceptance` request:+ * the user asked for evidence, so burying it no longer applies.*/export const LIBRARY_HIDDEN_FILE_SOURCES: FileSource[] = [FileSource.Acceptance];+/** Sources a generation model wrote, as opposed to anything a human put there. */+export const AI_GENERATED_FILE_SOURCES: FileSource[] = [+ FileSource.ImageGeneration,+ FileSource.VideoGeneration,+];++const FILE_SOURCE_VALUES = new Set<string>(Object.values(FileSource));++/**+ * Narrow a caller-supplied source to a known value.+ *+ * Uploads carry `source` as a free-form string on the wire (older clients are+ * out there and a rejected upload over an attribution hint is a bad trade), so+ * an unrecognised value is dropped rather than persisted or thrown on.+ */+export const toFileSource = (source?: string | null): FileSource | undefined =>+ source && FILE_SOURCE_VALUES.has(source) ? (source as FileSource) : undefined;+export interface FileItem {content?: string;createdAt: Date;diff --git a/packages/types/src/files/list.ts b/packages/types/src/files/list.tsindex d0a1171758a..2765ab5327c 100644--- a/packages/types/src/files/list.ts+++ b/packages/types/src/files/list.ts@@ -63,6 +63,21 @@ export enum SortType {Desc = 'desc',}+/**+ * How a resource came to exist, as the explorer lets the user narrow it.+ * Reads `files.source`, which is NULL for everything a human put there.+ *+ * `Acceptance` is the one value that widens the result set rather than+ * narrowing it: verification evidence is hidden from every listing by default+ * (`LIBRARY_HIDDEN_FILE_SOURCES`) and only comes back when explicitly asked for.+ */+export enum ResourceSourceFilter {+ Acceptance = 'acceptance',+ All = 'all',+ Generated = 'generated',+ Uploaded = 'uploaded',+}+export const QueryFileListSchema = z.object({category: z.string().optional(),knowledgeBaseId: z.string().optional(),@@ -73,6 +88,11 @@ export const QueryFileListSchema = z.object({showFilesInKnowledgeBase: z.boolean().default(false),sortType: z.enum(['desc', 'asc']).optional(),sorter: z.enum(['createdAt', 'size']).optional(),+ /**+ * Origin narrowing driven by the explorer's source filter. Absent / `all`+ * keeps the historical pool (everything except hidden sources).+ */+ sourceFilter: z.nativeEnum(ResourceSourceFilter).optional(),/*** Workspace-mode visibility filter. Absent / undefined means "all"* (already ownership-filtered by the server). `'private'` narrows to@@ -94,6 +114,7 @@ export interface QueryFileListParams {showFilesInKnowledgeBase?: boolean;sorter?: string;sortType?: string;+ sourceFilter?: ResourceSourceFilter;visibility?: 'private' | 'public';}diff --git a/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.test.tsx b/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.test.tsxindex 7275ae95cd7..d5864e04e3a 100644--- a/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.test.tsx+++ b/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.test.tsx@@ -1,12 +1,18 @@import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { FilesTabs, ResourceSourceFilter } from '@/types/files';+import EmptyPlaceholder from './EmptyPlaceholder';const mockOpen = vi.fn();const mockPushDockFileList = vi.fn();+const mockSetSourceFilter = vi.fn();let canCreate = true;+let category: FilesTabs = FilesTabs.All;let libraryId: string | undefined;+let sourceFilter: ResourceSourceFilter | undefined;vi.mock('react-i18next', () => ({useTranslation: () => ({@@ -27,8 +33,8 @@ vi.mock('@/features/ResourceManager/hooks/useCurrentFolderId', () => ({}));vi.mock('@/features/ResourceManager/store', () => ({- useResourceManagerStore: (selector: (state: { libraryId?: string }) => unknown) =>- selector({ libraryId }),+ useResourceManagerStore: (selector: (state: any) => unknown) =>+ selector({ category, libraryId, setSourceFilter: mockSetSourceFilter, sourceFilter }),}));vi.mock('@/store/file', () => ({@@ -39,10 +45,28 @@ vi.mock('@/store/file', () => ({describe('EmptyPlaceholder', () => {beforeEach(() => {canCreate = true;+ category = FilesTabs.All;libraryId = undefined;+ sourceFilter = undefined;vi.clearAllMocks();});+ it('should blame the source filter instead of prompting onboarding when it narrows', async () => {+ // Images defaults to AI-generated, so a library of uploads lands here.+ category = FilesTabs.Images;++ render(<EmptyPlaceholder />);++ expect(screen.getByText('FileManager.emptyStatus.filteredTitle')).toBeInTheDocument();+ expect(+ screen.queryByText('FileManager.emptyStatus.actions.knowledgeBase'),+ ).not.toBeInTheDocument();++ await userEvent.click(screen.getByText('FileManager.emptyStatus.actions.showAllSources'));++ expect(mockSetSourceFilter).toHaveBeenCalledWith(ResourceSourceFilter.All);+ });+it('should render create actions when the user can create resources', () => {render(<EmptyPlaceholder />);diff --git a/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.tsx b/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.tsxindex 07d4370f2e6..58c4e2ced7d 100644--- a/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.tsx+++ b/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.tsx@@ -1,4 +1,5 @@import { Center, FileTypeIcon, Flexbox, Icon, Text } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';import { Upload } from 'antd';import { createStaticStyles, cssVar } from 'antd-style';import { ArrowUpIcon, PlusIcon } from 'lucide-react';@@ -8,8 +9,10 @@ import { useCreateNewModal } from '@/features/LibraryModal';import { useCurrentFolderId } from '@/features/ResourceManager/hooks/useCurrentFolderId';import { useTopLevelFileUpload } from '@/features/ResourceManager/hooks/useTopLevelFileUpload';import { useResourceManagerStore } from '@/features/ResourceManager/store';+import { getResourceSourceFilter } from '@/features/ResourceManager/store/selectors';import { usePermission } from '@/hooks/usePermission';import { useFileStore } from '@/store/file';+import { ResourceSourceFilter } from '@/types/files';const ICON_SIZE = 80;@@ -70,11 +73,30 @@ const EmptyPlaceholder = () => {const uploadTopLevel = useTopLevelFileUpload();const libraryId = useResourceManagerStore((s) => s.libraryId);+ const [sourceFilter, setSourceFilter] = useResourceManagerStore((s) => [+ getResourceSourceFilter(s),+ s.setSourceFilter,+ ]);const currentFolderId = useCurrentFolderId();const { open } = useCreateNewModal();const { allowed: canCreate } = usePermission('create_content');+ // A narrowed source can empty a category that is not actually empty — the+ // images view opens on generated output, so a library of uploads would+ // otherwise read as "you have nothing yet". Name the filter and offer the+ // way back instead of the onboarding prompt.+ if (sourceFilter !== ResourceSourceFilter.All) {+ return (+ <Center gap={12} height={'100%'} style={{ paddingBottom: 100 }} width={'100%'}>+ <Text as={'h4'}>{t('FileManager.emptyStatus.filteredTitle')}</Text>+ <Button size={'small'} onClick={() => setSourceFilter(ResourceSourceFilter.All)}>+ {t('FileManager.emptyStatus.actions.showAllSources')}+ </Button>+ </Center>+ );+ }+if (!canCreate) {return (<Center height={'100%'} style={{ paddingBottom: 100 }} width={'100%'}>diff --git a/src/features/ResourceManager/components/Explorer/Header/index.tsx b/src/features/ResourceManager/components/Explorer/Header/index.tsxindex bc89dfd8ff6..449b4deeb84 100644--- a/src/features/ResourceManager/components/Explorer/Header/index.tsx+++ b/src/features/ResourceManager/components/Explorer/Header/index.tsx@@ -21,6 +21,7 @@ import { FilesTabs } from '@/types/files';import AddButton from '../../Header/AddButton';import BatchActionsDropdown from '../ToolBar/BatchActionsDropdown';import SortDropdown from '../ToolBar/SortDropdown';+import SourceFilter from '../ToolBar/SourceFilter';import ViewSwitcher from '../ToolBar/ViewSwitcher';import Breadcrumb from './Breadcrumb';import SearchInput from './SearchInput';@@ -34,15 +35,23 @@ const Header = memo(() => {const activeWorkspaceId = useActiveWorkspaceId();// Get state and actions from store- const [libraryId, category, onActionClick, selectAllState, selectFileIds, selectionTotal] =- useResourceManagerStore((s) => [- s.libraryId,- s.category,- s.onActionClick,- s.selectAllState,- s.selectedFileIds,- s.selectionTotal,- ]);+ const [+ libraryId,+ category,+ onActionClick,+ selectAllState,+ selectFileIds,+ selectionTotal,+ viewMode,+ ] = useResourceManagerStore((s) => [+ s.libraryId,+ s.category,+ s.onActionClick,+ s.selectAllState,+ s.selectedFileIds,+ s.selectionTotal,+ s.viewMode,+ ]);const isWorkspaceOwner = useIsWorkspaceOwner();const { allowed: canEditResources, reason } = usePermission('edit_own_content');const total = useFileStore((s) => s.total);@@ -184,6 +193,14 @@ const Header = memo(() => {left={leftContent}right={<>+ {/*+ Grid view carries the source chips on its item-count row (where the+ count and the pool it counts belong together). The list view has no+ such row — its header is a horizontally scrolling column strip — so+ the chips live here instead, and a standing filter stays visible in+ both views.+ */}+ {viewMode === 'list' && <SourceFilter />}<SearchInput /><SortDropdown /><BatchActionsDropdown selectCount={selectCount} onActionClick={onActionClick} />diff --git a/src/features/ResourceManager/components/Explorer/ListView/useExplorerListData.ts b/src/features/ResourceManager/components/Explorer/ListView/useExplorerListData.tsindex 0a471e07238..d8215b96544 100644--- a/src/features/ResourceManager/components/Explorer/ListView/useExplorerListData.ts+++ b/src/features/ResourceManager/components/Explorer/ListView/useExplorerListData.ts@@ -13,6 +13,8 @@ import type { AsyncTaskStatus } from '@/types/asyncTask';import type { FileListItem } from '@/types/files';import type { ResourceQueryParams } from '@/types/resource';+import { isQueryNavigation } from '../isQueryNavigation';+interface UseExplorerListDataParams {isLoading?: boolean;isValidating?: boolean;@@ -36,19 +38,10 @@ export const useExplorerListData = ({resourceList: s.resourceList,}));- const isNavigating = useMemo(() => {- if (!currentQueryParams) return false;-- // `visibility` is part of navigation identity too: switching the Sidebar- // mode toggle is a "space switch" and needs the same skeleton treatment- // as changing folder / category / library so the list flip is legible.- return (- currentQueryParams.libraryId !== queryParams.libraryId ||- currentQueryParams.parentId !== queryParams.parentId ||- currentQueryParams.category !== queryParams.category ||- currentQueryParams.visibility !== queryParams.visibility- );- }, [currentQueryParams, queryParams]);+ const isNavigating = useMemo(+ () => isQueryNavigation(currentQueryParams, queryParams),+ [currentQueryParams, queryParams],+ );const rawData = useMemo(() =>diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsxindex 1fea6219700..92a624136c7 100644--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx@@ -3,7 +3,7 @@ import { Button } from '@lobehub/ui/base-ui';import { Image } from 'antd';import { createStaticStyles, cx, keyframes } from 'antd-style';import { isNull } from 'es-toolkit/compat';-import { FileBoxIcon, ImageIcon } from 'lucide-react';+import { FileBoxIcon } from 'lucide-react';import { memo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -14,6 +14,7 @@ import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';import ChunksBadge from '../../ListView/ListItem/ChunkTag';import { FALLBACK_ASPECT_RATIO, readAspectRatio } from './imageAspectRatio';+import { readPlaceholderIcon } from './placeholderIcon';const pulse = keyframes`0%,@@ -222,7 +223,11 @@ const ImageFileItem = memo<ImageFileItemProps>(<divclassName={cx(styles.placeholder, status === 'loading' && styles.placeholderLoading)}>- <Icon className={styles.placeholderIcon} icon={ImageIcon} size={28} />+ <Icon+ className={styles.placeholderIcon}+ icon={readPlaceholderIcon(status)}+ size={28}+ />{status === 'error' && (<><div className={styles.placeholderReason}>diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/placeholderIcon.test.ts b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/placeholderIcon.test.tsnew file mode 100644index 00000000000..4f8b960f2aa--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/placeholderIcon.test.ts@@ -0,0 +1,21 @@+import { ImageIcon, ImageOffIcon } from 'lucide-react';+import { describe, expect, it } from 'vitest';++import { readPlaceholderIcon } from './placeholderIcon';++describe('readPlaceholderIcon', () => {+ it('should mark a failed thumbnail with the struck-through frame', () => {+ expect(readPlaceholderIcon('error')).toBe(ImageOffIcon);+ });++ it('should keep the plain frame while the thumbnail is still coming', () => {+ expect(readPlaceholderIcon('loading')).toBe(ImageIcon);+ expect(readPlaceholderIcon('loaded')).toBe(ImageIcon);+ });++ it('should not reuse one icon for both waiting and failed', () => {+ // The whole point of the distinction: a permanently missing bitmap must not+ // read as a slow one.+ expect(readPlaceholderIcon('error')).not.toBe(readPlaceholderIcon('loading'));+ });+});diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/placeholderIcon.ts b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/placeholderIcon.tsnew file mode 100644index 00000000000..2bcd21ae5a0--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/placeholderIcon.ts@@ -0,0 +1,15 @@+import { ImageIcon, ImageOffIcon, type LucideIcon } from 'lucide-react';++/** Thumbnail load states the placeholder has to speak for. */+export type ThumbnailStatus = 'loading' | 'loaded' | 'error';++/**+ * Icon standing in for a thumbnail that is not on screen.+ *+ * A pending thumbnail and a failed one are different messages: the plain frame+ * reads as "still coming", which stops being true the moment the load fails.+ * The struck-through frame is the icon language for "this image cannot be+ * shown", so a permanently missing bitmap stops looking like a slow one.+ */+export const readPlaceholderIcon = (status: ThumbnailStatus): LucideIcon =>+ status === 'error' ? ImageOffIcon : ImageIcon;diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/index.tsxindex 7f383c08b08..724bd3eb455 100644--- a/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx+++ b/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx@@ -18,6 +18,8 @@ import {useExplorerSelectionActions,useExplorerSelectionSummary,} from '../hooks/useExplorerSelection';+import { isQueryNavigation } from '../isQueryNavigation';+import SourceFilter from '../ToolBar/SourceFilter';import { useMasonryColumnCount } from '../useMasonryColumnCount';import MasonryItemWrapper from './MasonryItem/MasonryItemWrapper';import MasonryViewSkeleton from './Skeleton';@@ -80,18 +82,10 @@ const MasonryView = memo(function MasonryView({const { queryParams: currentQueryParams, hasMore, loadMoreResources } = useFileStore();- const isNavigating = useMemo(() => {- if (!currentQueryParams || !queryParams) return false;-- // Sidebar mode toggle is a "space switch" — treat visibility change as- // navigation so the skeleton shows while the new fetch is in flight.- return (- currentQueryParams.libraryId !== queryParams.libraryId ||- currentQueryParams.parentId !== queryParams.parentId ||- currentQueryParams.category !== queryParams.category ||- currentQueryParams.visibility !== queryParams.visibility- );- }, [currentQueryParams, queryParams]);+ const isNavigating = useMemo(+ () => isQueryNavigation(currentQueryParams, queryParams),+ [currentQueryParams, queryParams],+ );// Map ResourceItem[] to FileListItem[] for compatibility// Spread `item` first so file-backed fields (e.g. `fileId`) are preserved —@@ -248,6 +242,8 @@ const MasonryView = memo(function MasonryView({ns: 'components',})}</span>+ <Flexbox flex={1} />+ <SourceFilter /></Flexbox>{showSelectAllHint && (<Flexboxdiff --git a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsxindex a1b0bc568e0..4b194a647f4 100644--- a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx+++ b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx@@ -12,7 +12,10 @@ import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceimport AsyncError from '@/components/AsyncError';import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';import { useResourceManagerStore } from '@/features/ResourceManager/store';-import { getResourceQueryVisibility } from '@/features/ResourceManager/store/selectors';+import {+ getResourceQueryVisibility,+ getResourceSourceFilter,+} from '@/features/ResourceManager/store/selectors';import { useClientDataSWR } from '@/libs/swr';import { resourceKeys } from '@/libs/swr/keys';import { resourceService } from '@/services/resource';@@ -22,7 +25,7 @@ import {INITIAL_STATUS,} from '@/store/global/initialState';import type { AsyncTaskStatus } from '@/types/asyncTask';-import type { FileListItem } from '@/types/files';+import { type FileListItem, type ResourceSourceFilter } from '@/types/files';import { useExplorerSelectionEligibility } from './hooks/useExplorerSelection';import FileListItemComponent from './ListView/ListItem';@@ -32,9 +35,15 @@ import { useMasonryColumnCount } from './useMasonryColumnCount';const SearchResultsOverlay = memo(() => {const { t } = useTranslation('components');- const [searchQuery, libraryId, category, viewMode, listVisibility] = useResourceManagerStore(- (s) => [s.searchQuery, s.libraryId, s.category, s.viewMode, s.listVisibility],- );+ const [searchQuery, libraryId, category, viewMode, listVisibility, sourceFilter] =+ useResourceManagerStore((s) => [+ s.searchQuery,+ s.libraryId,+ s.category,+ s.viewMode,+ s.listVisibility,+ getResourceSourceFilter(s),+ ]);const [selectedFileIds, setSelectedFileIds] = useState<string[]>([]);const { isItemSelectable } = useExplorerSelectionEligibility();@@ -63,12 +72,24 @@ const SearchResultsOverlay = memo(() => {category: libraryId ? undefined : category,libraryId,q: searchQuery,+ // Search narrows the list the user is looking at, so it has to honour+ // the source they picked. Omitting it left the chip visibly selected+ // while results came back from every non-hidden source — and made+ // `Acceptance` search unusable, since that source is hidden unless+ // explicitly asked for.+ sourceFilter,visibility,}): null,async ([, params]: [string,- { category?: string; libraryId?: string; q: string; visibility?: 'private' | 'public' },+ {+ category?: string;+ libraryId?: string;+ q: string;+ sourceFilter?: ResourceSourceFilter;+ visibility?: 'private' | 'public';+ },]) => {const response = await resourceService.queryResources({...params,diff --git a/src/features/ResourceManager/components/Explorer/ToolBar/SourceFilter.tsx b/src/features/ResourceManager/components/Explorer/ToolBar/SourceFilter.tsxnew file mode 100644index 00000000000..24e0cafa11a--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/ToolBar/SourceFilter.tsx@@ -0,0 +1,82 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useResourceManagerStore } from '@/features/ResourceManager/store';+import {+ canFilterResourceSource,+ getResourceSourceFilter,+} from '@/features/ResourceManager/store/selectors';+import { ResourceSourceFilter } from '@/types/files';++const styles = createStaticStyles(({ css }) => ({+ option: css`+ flex: none;++ height: 24px;+ padding-inline: 10px;+ border-radius: 999px;++ font-size: 12px;+ color: ${cssVar.colorTextDescription};+ `,+ optionActive: css`+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ `,+}));++const OPTIONS: Array<{ key: ResourceSourceFilter; labelKey: string }> = [+ { key: ResourceSourceFilter.All, labelKey: 'FileManager.source.all' },+ { key: ResourceSourceFilter.Generated, labelKey: 'FileManager.source.generated' },+ { key: ResourceSourceFilter.Uploaded, labelKey: 'FileManager.source.uploaded' },+ { key: ResourceSourceFilter.Acceptance, labelKey: 'FileManager.source.acceptance' },+];++/**+ * Origin chips for the explorer list: All / AI generated / Uploaded /+ * Acceptance. Sits on the item-count row so the count and the pool it counts+ * read as one statement.+ *+ * Renders nothing where origin is meaningless (inside a library, on Pages or+ * Home) — see `canFilterResourceSource`.+ */+const SourceFilter = memo(() => {+ const { t } = useTranslation('components');+ const [canFilter, activeFilter, setSourceFilter] = useResourceManagerStore((s) => [+ canFilterResourceSource(s),+ getResourceSourceFilter(s),+ s.setSourceFilter,+ ]);++ if (!canFilter) return null;++ return (+ <Flexbox horizontal align={'center'} gap={2}>+ {OPTIONS.map((option) => {+ const isActive = activeFilter === option.key;++ return (+ <Button+ aria-pressed={isActive}+ className={cx(styles.option, isActive && styles.optionActive)}+ key={option.key}+ size={'small'}+ type={'text'}+ onClick={() => setSourceFilter(option.key)}+ >+ {t(option.labelKey as never)}+ </Button>+ );+ })}+ </Flexbox>+ );+});++SourceFilter.displayName = 'SourceFilter';++export default SourceFilter;diff --git a/src/features/ResourceManager/components/Explorer/index.test.tsx b/src/features/ResourceManager/components/Explorer/index.test.tsxindex 0aea1bea15c..8236366332e 100644--- a/src/features/ResourceManager/components/Explorer/index.test.tsx+++ b/src/features/ResourceManager/components/Explorer/index.test.tsx@@ -2,7 +2,7 @@ import { render } from '@testing-library/react';import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { FilesTabs, SortType } from '@/types/files';+import { FilesTabs, ResourceSourceFilter, SortType } from '@/types/files';import ResourceExplorer from './index';@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({searchQuery: null as string | null,sorter: 'createdAt' as const,sortType: 'desc' as SortType,+ sourceFilter: undefined as ResourceSourceFilter | undefined,viewMode: 'list' as const,},useFetchResources: vi.fn(),@@ -32,12 +33,12 @@ vi.mock('@/features/ResourceManager/store', () => ({selector(mocks.resourceManagerState),}));-vi.mock('@/features/ResourceManager/store/selectors', () => ({- getResourceQueryVisibility: (- libraryId: string | undefined,- visibility: 'private' | 'workspace',- ) => (libraryId ? undefined : visibility === 'private' ? 'private' : 'public'),- sortFileList: (items: unknown[]) => items,+// Real selectors: the query params under test (visibility narrowing, source+// defaults) are exactly what those selectors decide, so stubbing them would+// assert the stub.+vi.mock(import('@/features/ResourceManager/store/selectors'), async (importOriginal) => ({+ ...(await importOriginal()),+ sortFileList: (items: any) => items,}));vi.mock('@/store/file/slices/resource/hooks', () => ({@@ -86,6 +87,7 @@ describe('ResourceExplorer', () => {mocks.resourceManagerState.searchQuery = null;mocks.resourceManagerState.sorter = 'createdAt';mocks.resourceManagerState.sortType = SortType.Desc;+ mocks.resourceManagerState.sourceFilter = undefined;mocks.resourceManagerState.viewMode = 'list';mocks.useFetchResources.mockReturnValue({ isLoading: false, isValidating: false });});@@ -103,6 +105,30 @@ describe('ResourceExplorer', () => {);});+ it('opens the images category on generated output without an explicit pick', () => {+ mocks.resourceManagerState.category = FilesTabs.Images;++ render(<ResourceExplorer />);++ expect(mocks.useFetchResources).toHaveBeenCalledWith(+ expect.objectContaining({+ category: FilesTabs.Images,+ sourceFilter: ResourceSourceFilter.Generated,+ }),+ );+ });++ it('sends the explicit source pick over the category default', () => {+ mocks.resourceManagerState.category = FilesTabs.Images;+ mocks.resourceManagerState.sourceFilter = ResourceSourceFilter.Uploaded;++ render(<ResourceExplorer />);++ expect(mocks.useFetchResources).toHaveBeenCalledWith(+ expect.objectContaining({ sourceFilter: ResourceSourceFilter.Uploaded }),+ );+ });+it('does not reuse the resource-home visibility filter inside a library', () => {mocks.resourceManagerState.libraryId = 'kb-shared';mocks.resourceManagerState.listVisibility = 'private';diff --git a/src/features/ResourceManager/components/Explorer/index.tsx b/src/features/ResourceManager/components/Explorer/index.tsxindex 14b3c5fc47e..2ff03e45c54 100644--- a/src/features/ResourceManager/components/Explorer/index.tsx+++ b/src/features/ResourceManager/components/Explorer/index.tsx@@ -9,6 +9,7 @@ import { useResourceManagerUrlSync } from '@/features/ResourceManager/hooks/useRimport { useResourceManagerStore } from '@/features/ResourceManager/store';import {getResourceQueryVisibility,+ getResourceSourceFilter,sortFileList,} from '@/features/ResourceManager/store/selectors';import { useFetchResources, useResourceStore } from '@/store/file/slices/resource/hooks';@@ -35,16 +36,25 @@ const ResourceExplorer = memo(() => {useResourceManagerUrlSync();// Get state from Resource Manager store- const [libraryId, category, viewMode, searchQuery, sorter, sortType, listVisibility] =- useResourceManagerStore((s) => [- s.libraryId,- s.category,- s.viewMode,- s.searchQuery,- s.sorter,- s.sortType,- s.listVisibility,- ]);+ const [+ libraryId,+ category,+ viewMode,+ searchQuery,+ sorter,+ sortType,+ listVisibility,+ sourceFilter,+ ] = useResourceManagerStore((s) => [+ s.libraryId,+ s.category,+ s.viewMode,+ s.searchQuery,+ s.sorter,+ s.sortType,+ s.listVisibility,+ getResourceSourceFilter(s),+ ]);// Get folder path for empty state checkconst { currentFolderSlug } = useFolderPath();@@ -60,12 +70,13 @@ const ResourceExplorer = memo(() => {showFilesInKnowledgeBase: false,sortType,sorter,+ sourceFilter,// The two-mode narrowing belongs to the resource home. A concrete// library supplies its own visibility boundary and must not inherit the// user's last home filter.visibility: getResourceQueryVisibility(libraryId, listVisibility),}),- [category, libraryId, currentFolderSlug, sortType, sorter, listVisibility],+ [category, libraryId, currentFolderSlug, sortType, sorter, listVisibility, sourceFilter],);// Use SWR for data fetching with automatic caching and revalidation.diff --git a/src/features/ResourceManager/components/Explorer/isQueryNavigation.test.ts b/src/features/ResourceManager/components/Explorer/isQueryNavigation.test.tsnew file mode 100644index 00000000000..a49fca33b4f--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/isQueryNavigation.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';++import { FilesTabs, ResourceSourceFilter, SortType } from '@/types/files';+import type { ResourceQueryParams } from '@/types/resource';++import { isQueryNavigation } from './isQueryNavigation';++const base: ResourceQueryParams = {+ category: FilesTabs.Images,+ libraryId: undefined,+ parentId: null,+ sortType: SortType.Desc,+ sorter: 'createdAt',+ sourceFilter: ResourceSourceFilter.Generated,+ visibility: 'public',+};++describe('isQueryNavigation', () => {+ it('should treat a source change as navigation', () => {+ // Regression: both views used to compare four fields and omit this one, so+ // switching source kept the previous source's rows on screen — and+ // interactive — until the new fetch landed.+ expect(isQueryNavigation(base, { ...base, sourceFilter: ResourceSourceFilter.Uploaded })).toBe(+ true,+ );+ });++ it('should treat every other pool-selecting field as navigation', () => {+ expect(isQueryNavigation(base, { ...base, category: FilesTabs.Videos })).toBe(true);+ expect(isQueryNavigation(base, { ...base, libraryId: 'kb-1' })).toBe(true);+ expect(isQueryNavigation(base, { ...base, parentId: 'folder-1' })).toBe(true);+ expect(isQueryNavigation(base, { ...base, visibility: 'private' })).toBe(true);+ });++ it('should not treat re-sorting the same pool as navigation', () => {+ // Sorting rearranges the rows already loaded, so a skeleton there would be+ // a flash for nothing.+ expect(isQueryNavigation(base, { ...base, sortType: SortType.Asc })).toBe(false);+ expect(isQueryNavigation(base, { ...base, sorter: 'name' })).toBe(false);+ });++ it('should report no navigation for identical params or a missing side', () => {+ expect(isQueryNavigation(base, { ...base })).toBe(false);+ expect(isQueryNavigation(undefined, base)).toBe(false);+ expect(isQueryNavigation(base, undefined)).toBe(false);+ });+});diff --git a/src/features/ResourceManager/components/Explorer/isQueryNavigation.ts b/src/features/ResourceManager/components/Explorer/isQueryNavigation.tsnew file mode 100644index 00000000000..ec5d74efe3f--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/isQueryNavigation.ts@@ -0,0 +1,35 @@+import type { ResourceQueryParams } from '@/types/resource';++/**+ * Query fields that select a different *pool* of resources rather than a+ * different arrangement of the same one. Changing any of them is a navigation:+ * the rows on screen stop being an answer to the question now being asked, so+ * the views show a skeleton instead of the stale list.+ *+ * `sorter` / `sortType` are deliberately absent — they reorder the same pool+ * and re-sort locally, so a skeleton there would be a flash for nothing.+ */+const POOL_KEYS = [+ 'libraryId',+ 'parentId',+ 'category',+ 'visibility',+ 'sourceFilter',+] as const satisfies readonly (keyof ResourceQueryParams)[];++/**+ * Whether the explorer is moving between two different resource pools.+ *+ * Both the list and the masonry view need this, and they used to carry their+ * own copies of the comparison — which is exactly how `sourceFilter` came to be+ * missing from both at once. Keep it here so a new pool-selecting field is+ * added in one place.+ */+export const isQueryNavigation = (+ current: ResourceQueryParams | undefined,+ next: ResourceQueryParams | undefined,+): boolean => {+ if (!current || !next) return false;++ return POOL_KEYS.some((key) => current[key] !== next[key]);+};diff --git a/src/features/ResourceManager/store/action.test.ts b/src/features/ResourceManager/store/action.test.tsindex 9b8484bdd0e..b0862b5078b 100644--- a/src/features/ResourceManager/store/action.test.ts+++ b/src/features/ResourceManager/store/action.test.ts@@ -42,6 +42,45 @@ describe('resource manager store actions', () => {});});+ it('should drop the previous source rows when the source filter changes', () => {+ // Regression: the pick used to update ResourceManager state only, leaving+ // the previous source's rows on screen and interactive until the fetch+ // landed — and a "select all" fired in that window resolved against the+ // stale queryParams, so the next batch action targeted the wrong source.+ useFileStore.setState({+ queryParams: { category: 'images', sourceFilter: 'generated' } as any,+ resourceList: [{ id: 'file-1' }, { id: 'file-2' }] as any,+ resourceMap: new Map([['file-1', { id: 'file-1' } as any]]),+ selectAllState: 'all',+ } as any);+ useResourceManagerStore.setState({+ selectAllState: 'all',+ selectedFileIds: ['file-9'],+ selectionTotal: 12,+ sourceFilter: 'generated' as any,+ });++ useResourceManagerStore.getState().setSourceFilter('uploaded' as any);++ expect(useResourceManagerStore.getState()).toMatchObject({+ selectAllState: 'none',+ selectedFileIds: [],+ sourceFilter: 'uploaded',+ });+ expect(useResourceManagerStore.getState().selectionTotal).toBeUndefined();+ expect(useFileStore.getState().resourceList).toEqual([]);+ });++ it('should ignore re-picking the already active source filter', () => {+ useFileStore.setState({ resourceList: [{ id: 'file-1' }] as any } as any);+ useResourceManagerStore.setState({ sourceFilter: 'uploaded' as any });++ useResourceManagerStore.getState().setSourceFilter('uploaded' as any);++ // No clear, so clicking the active chip does not flash the list.+ expect(useFileStore.getState().resourceList).toEqual([{ id: 'file-1' }]);+ });+it('should exclude deselected ids when resolving all-selected resources', async () => {useResourceManagerStore.setState({selectAllState: 'all',diff --git a/src/features/ResourceManager/store/action.ts b/src/features/ResourceManager/store/action.tsindex fa438a2147e..94b37431e29 100644--- a/src/features/ResourceManager/store/action.ts+++ b/src/features/ResourceManager/store/action.ts@@ -4,7 +4,7 @@ import type { ResourceManagerMode } from '@/features/ResourceManager';import { useFileStore } from '@/store/file';import type { StoreSetter } from '@/store/types';import { flattenActions } from '@/store/utils/flattenActions';-import type { FilesTabs, SortType } from '@/types/files';+import type { FilesTabs, ResourceSourceFilter, SortType } from '@/types/files';import type { ResourceListVisibilityFilter, SelectAllState, State, ViewMode } from './initialState';import { DEFAULT_WORKSPACE_LIST_VISIBILITY, initialState } from './initialState';@@ -154,7 +154,31 @@ export class ResourceManagerStoreActionImpl {};setCategory = (category: FilesTabs): void => {- this.#set({ category });+ // Drop any explicit source pick so the new category falls back to its own+ // default — an "AI generated" choice made under Images must not silently+ // hide every uploaded file under Documents.+ this.#set({ category, sourceFilter: undefined });+ };++ setSourceFilter = (sourceFilter: ResourceSourceFilter): void => {+ if (this.#get().sourceFilter === sourceFilter) return;++ // The visible pool changes, so a standing "select all" would target rows+ // that are no longer on screen — same reset as the visibility toggle.+ this.#set({+ selectAllState: 'none',+ selectedFileIds: [],+ selectionTotal: undefined,+ sourceFilter,+ });++ // Drop the previous source's rows immediately, exactly as the visibility+ // toggle does. Without this the old rows stay on screen and interactive+ // under the newly active chip until the fetch lands — and a "select all"+ // fired in that window resolves against `useFileStore.queryParams`, which+ // still carries the previous source, so the following batch action would+ // target rows the user is no longer looking at.+ useFileStore.getState().clearCurrentQueryResources();};setCurrentViewItemId = (currentViewItemId?: string): void => {diff --git a/src/features/ResourceManager/store/initialState.ts b/src/features/ResourceManager/store/initialState.tsindex 0d120802ca7..e9b4a25dbdc 100644--- a/src/features/ResourceManager/store/initialState.ts+++ b/src/features/ResourceManager/store/initialState.ts@@ -1,5 +1,5 @@import { type ResourceManagerMode } from '@/features/ResourceManager';-import { FilesTabs, SortType } from '@/types/files';+import { FilesTabs, type ResourceSourceFilter, SortType } from '@/types/files';export type ViewMode = 'list' | 'masonry';export type SelectAllState = 'all' | 'loaded' | 'none';@@ -74,6 +74,14 @@ export interface State {* Sort direction (ascending or descending)*/sortType: SortType;+ /**+ * Explicit origin narrowing picked by the user. `undefined` means "not+ * chosen here", which resolves to the category's own default (see+ * `getResourceSourceFilter`) — Images opens on AI-generated, everything else+ * on All. Cleared whenever the category changes so each category comes back+ * to its own default rather than inheriting the previous one's choice.+ */+ sourceFilter?: ResourceSourceFilter;/*** File explorer view mode (list or masonry)*/@@ -95,5 +103,6 @@ export const initialState: State = {selectedFileIds: [],sortType: SortType.Desc,sorter: 'createdAt',+ sourceFilter: undefined,viewMode: 'list',};diff --git a/src/features/ResourceManager/store/selectors.test.ts b/src/features/ResourceManager/store/selectors.test.tsindex eb259bb5775..dee6a60732d 100644--- a/src/features/ResourceManager/store/selectors.test.ts+++ b/src/features/ResourceManager/store/selectors.test.ts@@ -1,13 +1,71 @@import { describe, expect, it } from 'vitest';+import { FilesTabs, ResourceSourceFilter } from '@/types/files';++import { initialState, type State } from './initialState';import {+ canFilterResourceSource,getExplorerSelectAllUiState,getExplorerSelectedCount,getResourceQueryVisibility,+ getResourceSourceFilter,isExplorerItemSelected,} from './selectors';+const stateWith = (patch: Partial<State>): State => ({ ...initialState, ...patch });+describe('resource manager selectors', () => {+ it('should open the images category on generated output and the other media categories on all', () => {+ expect(getResourceSourceFilter(stateWith({ category: FilesTabs.Images }))).toBe(+ ResourceSourceFilter.Generated,+ );+ expect(getResourceSourceFilter(stateWith({ category: FilesTabs.Videos }))).toBe(+ ResourceSourceFilter.All,+ );+ expect(getResourceSourceFilter(stateWith({ category: FilesTabs.Audios }))).toBe(+ ResourceSourceFilter.All,+ );+ });++ it('should offer the source filter on media categories only', () => {+ for (const category of [FilesTabs.Images, FilesTabs.Videos, FilesTabs.Audios]) {+ expect(canFilterResourceSource(stateWith({ category }))).toBe(true);+ }++ // Documents and raw files have no generated counterpart, and All is a+ // cross-category overview — the filter could only ever partition those one+ // way, so it is not offered at all.+ for (const category of [+ FilesTabs.All,+ FilesTabs.Documents,+ FilesTabs.Files,+ FilesTabs.Pages,+ FilesTabs.Home,+ ]) {+ expect(canFilterResourceSource(stateWith({ category }))).toBe(false);+ expect(getResourceSourceFilter(stateWith({ category }))).toBe(ResourceSourceFilter.All);+ }+ });++ it('should let an explicit pick override the category default', () => {+ expect(+ getResourceSourceFilter(+ stateWith({ category: FilesTabs.Images, sourceFilter: ResourceSourceFilter.Uploaded }),+ ),+ ).toBe(ResourceSourceFilter.Uploaded);+ });++ it('should not narrow by source inside a library, even on a media category', () => {+ const inLibrary = stateWith({+ category: FilesTabs.Images,+ libraryId: 'kb-1',+ sourceFilter: ResourceSourceFilter.Generated,+ });++ expect(canFilterResourceSource(inLibrary)).toBe(false);+ expect(getResourceSourceFilter(inLibrary)).toBe(ResourceSourceFilter.All);+ });+it('should apply the home visibility filter only outside a concrete library', () => {expect(getResourceQueryVisibility(undefined, 'private')).toBe('private');expect(getResourceQueryVisibility(undefined, 'workspace')).toBe('public');diff --git a/src/features/ResourceManager/store/selectors.ts b/src/features/ResourceManager/store/selectors.tsindex 90eed392d0e..66ff60b1513 100644--- a/src/features/ResourceManager/store/selectors.ts+++ b/src/features/ResourceManager/store/selectors.ts@@ -1,5 +1,5 @@import { fileManagerSelectors, useFileStore } from '@/store/file';-import { type FileListItem } from '@/types/files';+import { type FileListItem, FilesTabs, ResourceSourceFilter } from '@/types/files';import { SortType } from '@/types/files';import type { ResourceListVisibilityFilter, SelectAllState, State } from './initialState';@@ -18,6 +18,47 @@ export const getResourceQueryVisibility = (return listVisibility === 'private' ? 'private' : 'public';};+/**+ * Categories where "where did this come from" is a question worth asking: the+ * media categories, and only those. Generation produces images, video and+ * audio — so those are the lists where uploads and model output actually mix+ * and need separating.+ *+ * Documents and raw files have no generated counterpart, and the All view is a+ * cross-category overview rather than a place to narrow by origin; offering the+ * filter there would be four controls that can only ever partition the list one+ * way. Pages hold no files and Home is a dashboard.+ */+export const SOURCE_FILTER_CATEGORIES: FilesTabs[] = [+ FilesTabs.Audios,+ FilesTabs.Images,+ FilesTabs.Videos,+];++/**+ * The images category is dominated by generation output — a few uploaded+ * screenshots against hundreds of generated images — so it opens on the+ * generated set. Every other category opens on everything.+ */+const DEFAULT_SOURCE_FILTER_BY_CATEGORY: Partial<Record<FilesTabs, ResourceSourceFilter>> = {+ [FilesTabs.Images]: ResourceSourceFilter.Generated,+};++export const canFilterResourceSource = ({ category, libraryId }: State): boolean =>+ !libraryId && SOURCE_FILTER_CATEGORIES.includes(category);++/**+ * The origin narrowing actually in effect: the user's explicit pick, else the+ * category default. A library defines its own pool and never narrows by origin.+ */+export const getResourceSourceFilter = (s: State): ResourceSourceFilter => {+ if (!canFilterResourceSource(s)) return ResourceSourceFilter.All;++ return (+ s.sourceFilter ?? DEFAULT_SOURCE_FILTER_BY_CATEGORY[s.category] ?? ResourceSourceFilter.All+ );+};+/*** Sort a file list based on sort settings* This is a pure function that can be used with any file listdiff --git a/src/types/resource.ts b/src/types/resource.tsindex 8b036de09b9..9fbe7e56dd6 100644--- a/src/types/resource.ts+++ b/src/types/resource.ts@@ -1,4 +1,9 @@-import { type FilesTabs, type FileUploader, type SortType } from '@/types/files';+import {+ type FilesTabs,+ type FileUploader,+ type ResourceSourceFilter,+ type SortType,+} from '@/types/files';/*** Unified resource item that represents both files and documents@@ -76,6 +81,11 @@ export interface ResourceQueryParams {showFilesInKnowledgeBase?: boolean;sorter?: 'name' | 'createdAt' | 'size';sortType?: SortType;+ /**+ * Origin narrowing driven by the explorer's source filter chips+ * (all / AI-generated / uploaded / acceptance evidence).+ */+ sourceFilter?: ResourceSourceFilter;/*** Workspace-mode visibility narrowing driven by the Sidebar mode toggle.* `'private'` shows the caller's own private rows; `'public'` shows