Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(soup): migrate to AST filters & use filters for all supported filter options (#2639)
dev-rbf2a185ffcede
diff --git a/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts b/js/app/packages/app/component/app-sidebar/soup-filter-presets.tsindex c5bd81cfc7..e0982b40da 100644--- a/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts+++ b/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts@@ -1,53 +1,20 @@+import type { FilterID } from '@app/component/next-soup/filters';import {- EXCLUDE,- QUERY_FILTERS,-} from '@app/component/next-soup/filters/query-filters';-import type { FilterID } from '@app/component/next-soup/filters/configs';-import {- applyInboxQueryFilters,- applyOtherQueryFilters,-} from '@app/component/next-soup/filters/inbox-query-filters';+ NIL_UUID,+ defineQueryFilters,+ type Query,+} from '@app/component/next-soup/filters/filter-store';import type { ListView } from '@app/constants/list-views';-import type { SoupBody } from '@queries/soup/items';-import { SharedEmailFilter } from '@service-storage/generated/schemas';import {PROPERTY_OPTION_IDS,SYSTEM_PROPERTY_IDS,} from '@core/component/Properties/constants';-/** Shared query filters for the "Signal" tab across Inbox and Email views. */-export const SIGNAL_QUERY_FILTERS = {- email_filters: {- importance: true as const,- shared: SharedEmailFilter.exclude,- },- emailView: 'inbox' as const,-};--/** Shared query filters for the "Noise" tab across Inbox and Email views. */-export const NOISE_QUERY_FILTERS = {- email_filters: {- importance: false as const,- shared: SharedEmailFilter.exclude,- },- emailView: 'inbox' as const,-};--/** Query filters for the "Calendar" tab — returns only threads with an iCalendar attachment. */-export const CALENDAR_QUERY_FILTERS = {- email_filters: {- calendar_only: true as const,- shared: SharedEmailFilter.exclude,- },- emailView: 'inbox' as const,-};-export type SoupFiltersPreset = {- queryFilters: SoupBody;- clientFilters: {- and?: FilterID[];- or?: FilterID[];- };+ /** Filter data for server query */+ filters: Query;+ /** Client filters to apply */+ clientFilters: { and?: FilterID[]; or?: FilterID[] };};// Tab preset configuration types@@ -67,38 +34,55 @@ export type ViewTabConfig = {tabs: TabConfig;};+/** Filters for inbox/signal: not done, importance=true for emails */+const INBOX_SIGNAL_FILTERS = defineQueryFilters({+ include: {+ documentDone: false,+ emailDone: false,+ emailImportance: true,+ channelDone: false,+ chatDone: false,+ folderDone: false,+ emailShared: 'exclude',+ },+ emailView: 'inbox',+});++/** Filters for inbox/noise: not done, importance=false for emails */+const INBOX_NOISE_FILTERS = defineQueryFilters({+ include: {+ documentDone: false,+ emailDone: false,+ emailImportance: false,+ channelDone: false,+ chatDone: false,+ folderDone: false,+ emailShared: 'exclude',+ },+ emailView: 'inbox',+});+export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {inbox: {default: 'signal',tabs: {- signal: () => {- const filters = applyInboxQueryFilters({- document_filters: { is_email_attachment: false },- });- return {- queryFilters: {- ...filters,- ...SIGNAL_QUERY_FILTERS,- },- clientFilters: { and: ['signal', 'not-done'] },- };- },- noise: () => {- const filters = applyOtherQueryFilters({- document_filters: { is_email_attachment: false },- });- return {- queryFilters: {- ...filters,- ...NOISE_QUERY_FILTERS,- },- clientFilters: { and: ['noise', 'not-done'] },- };- },+ signal: () => ({+ filters: INBOX_SIGNAL_FILTERS,+ clientFilters: { and: ['inbox'] },+ }),+ noise: () => ({+ filters: INBOX_NOISE_FILTERS,+ clientFilters: { and: ['noise'] },+ }),all: () => ({- queryFilters: {- document_filters: { is_email_attachment: false },- email_filters: { shared: SharedEmailFilter.include },+ filters: {+ exclude: {+ documentId: [NIL_UUID],+ threadId: [NIL_UUID],+ channelId: [NIL_UUID],+ chatId: [NIL_UUID],+ folderId: [NIL_UUID],+ },emailView: 'all',},clientFilters: { and: ['explicit-noise'] },@@ -111,25 +95,34 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {owned: (ctx) => {if (!ctx.userId) return undefined;return {- queryFilters: {- ...QUERY_FILTERS.agent,- chat_filters: { owners: [ctx.userId] },- },+ filters: defineQueryFilters({+ include: { chatOwnerId: [ctx.userId] },+ }),clientFilters: { and: ['agent'] },};},- running: () => ({- queryFilters: QUERY_FILTERS.agent,- clientFilters: { and: ['agent'] },- }),- shared: () => ({- queryFilters: QUERY_FILTERS.agent,- clientFilters: { and: ['agent', 'shared-agent'] },- }),+ running: (ctx) => {+ if (!ctx.userId) return undefined;+ return {+ filters: defineQueryFilters({+ include: { chatOwnerId: [ctx.userId] },+ }),+ clientFilters: { and: ['agent', 'owned-entity'] },+ };+ },+ shared: (ctx) => {+ if (!ctx.userId) return undefined;+ return {+ filters: defineQueryFilters({+ exclude: { chatOwnerId: [ctx.userId] },+ }),+ clientFilters: { and: ['agent', 'shared-entity'] },+ };+ },automations: () => ({// Server returns nothing useful here — automations are merged// into the soup client-side via `additionalEntities`.- queryFilters: QUERY_FILTERS.agent,+ filters: defineQueryFilters({}),clientFilters: { and: ['automation'] },}),},@@ -138,62 +131,67 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {default: 'important',tabs: {important: () => ({- queryFilters: {- ...QUERY_FILTERS.email,- ...SIGNAL_QUERY_FILTERS,- },+ filters: defineQueryFilters({+ include: {+ emailImportance: true,++ emailShared: 'exclude',+ },+ emailView: 'inbox',+ }),clientFilters: { and: ['email', 'no-drafts'] },}),noise: () => ({- queryFilters: {- ...QUERY_FILTERS.email,- ...NOISE_QUERY_FILTERS,- },+ filters: defineQueryFilters({+ include: {+ emailImportance: false,++ emailShared: 'exclude',+ },+ emailView: 'inbox',+ }),clientFilters: { and: ['email', 'no-drafts'] },}),calendar: () => ({- queryFilters: {- ...QUERY_FILTERS.email,- ...CALENDAR_QUERY_FILTERS,- },+ filters: defineQueryFilters({+ include: {+ emailShared: 'exclude',+ emailCalendarOnly: true,+ },+ emailView: 'inbox',+ }),+clientFilters: { and: ['email', 'no-drafts'] },}),drafts: () => ({- queryFilters: {- ...QUERY_FILTERS.email,- email_filters: { shared: SharedEmailFilter.exclude },+ filters: defineQueryFilters({+ exclude: { threadId: [NIL_UUID] },emailView: 'drafts',- },+ }),clientFilters: { and: ['email-drafts'] },}),sent: (ctx) => {if (!ctx.email) return undefined;return {- queryFilters: {- ...QUERY_FILTERS.email,- email_filters: {- senders: [ctx.email],- shared: SharedEmailFilter.exclude,- },+ filters: defineQueryFilters({+ include: { emailSender: [ctx.email] },emailView: 'sent',- },+ }),clientFilters: { and: ['email', 'no-drafts'] },};},shared: () => ({- queryFilters: {- ...QUERY_FILTERS.email,- email_filters: { shared: SharedEmailFilter.only },+ filters: defineQueryFilters({+ include: { emailShared: 'only' },emailView: 'all',- },- clientFilters: { and: ['email'] },+ }),+ clientFilters: { and: ['email', 'shared-entity'] },}),all: () => ({- queryFilters: {- ...QUERY_FILTERS.email,- email_filters: { shared: SharedEmailFilter.include },+ filters: defineQueryFilters({+ exclude: { threadId: [NIL_UUID] },emailView: 'all',- },+ }),clientFilters: { and: ['email'] },}),},@@ -204,44 +202,32 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {owned: (ctx) => {if (!ctx.userId) return undefined;return {- queryFilters: {- ...QUERY_FILTERS.documentAndFile,- document_filters: {- ...QUERY_FILTERS.documentAndFile.document_filters,- is_email_attachment: false,- owners: [ctx.userId],- },- project_filters: { project_ids: EXCLUDE },- },- clientFilters: { and: ['document-or-file'] },+ filters: defineQueryFilters({+ include: { documentOwnerId: [ctx.userId] },+ exclude: { subType: ['task'] },+ }),+ clientFilters: { and: ['document-or-file', 'owned-entity'] },+ };+ },+ shared: (ctx) => {+ if (!ctx.userId) return undefined;+ return {+ filters: defineQueryFilters({+ exclude: { subType: ['task'], documentOwnerId: [ctx.userId] },+ }),+ clientFilters: { and: ['document-or-file', 'shared-entity'] },};},- shared: () => ({- queryFilters: {- ...QUERY_FILTERS.documentAndFile,- document_filters: {- ...QUERY_FILTERS.documentAndFile.document_filters,- is_email_attachment: false,- },- project_filters: { project_ids: EXCLUDE },- },- clientFilters: { and: ['document-or-file', 'shared-entity'] },- }),attachments: () => ({- queryFilters: {- ...QUERY_FILTERS.documentAndFile,- document_filters: {- is_email_attachment: true,- },- project_filters: { project_ids: EXCLUDE },- },+ filters: defineQueryFilters({+ include: { isEmailAttachment: true },+ }),clientFilters: { and: ['document-or-file'] },}),all: () => ({- queryFilters: {- ...QUERY_FILTERS.documentAndFile,- project_filters: { project_ids: EXCLUDE },- },+ filters: defineQueryFilters({+ exclude: { subType: ['task'] },+ }),clientFilters: { and: ['document-or-file'] },}),},@@ -252,43 +238,48 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {'assigned-to-me': (ctx) => {if (!ctx.userId) return undefined;return {- queryFilters: {- ...QUERY_FILTERS.task,- property_filters: [- {- property_definition_id: SYSTEM_PROPERTY_IDS.ASSIGNEES,- entity_type: 'TASK',- entity_ids: [ctx.userId],- },- {- property_definition_id: SYSTEM_PROPERTY_IDS.STATUS,- entity_type: 'TASK',- option_ids: [- PROPERTY_OPTION_IDS.STATUS.NOT_STARTED,- PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS,- PROPERTY_OPTION_IDS.STATUS.IN_REVIEW,- ],- },- ],- },+ filters: defineQueryFilters({+ include: {+ subType: ['task'],+ properties: [+ {+ propertyId: SYSTEM_PROPERTY_IDS.ASSIGNEES,+ type: 'entity',+ value: ctx.userId,+ },+ ],+ },+ exclude: {+ properties: [+ {+ propertyId: SYSTEM_PROPERTY_IDS.STATUS,+ type: 'select',+ value: PROPERTY_OPTION_IDS.STATUS.COMPLETED,+ },+ {+ propertyId: SYSTEM_PROPERTY_IDS.STATUS,+ type: 'select',+ value: PROPERTY_OPTION_IDS.STATUS.CANCELED,+ },+ ],+ },+ }),clientFilters: { and: ['task', 'assigned-to', 'active-task'] },};},'created-by-me': (ctx) => {if (!ctx.userId) return undefined;return {- queryFilters: {- ...QUERY_FILTERS.task,- document_filters: {- ...QUERY_FILTERS.task.document_filters,- owners: [ctx.userId],- },- },- clientFilters: { and: ['task', 'active-task'] },+ filters: defineQueryFilters({+ include: { subType: ['task'], documentOwnerId: [ctx.userId] },+ }),+ clientFilters: { and: ['task', 'active-task', 'owned-entity'] },};},all: () => ({- queryFilters: QUERY_FILTERS.task,+ filters: defineQueryFilters({+ include: { subType: ['task'] },+ }),clientFilters: { and: ['task'] },}),},@@ -297,18 +288,21 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {default: 'recent',tabs: {recent: () => ({- queryFilters: {- ...QUERY_FILTERS.channels,- channel_filters: { importance: true },- },+ filters: defineQueryFilters({+ include: { channelImportance: true },+ }),clientFilters: { and: ['channels'] },}),people: () => ({- queryFilters: QUERY_FILTERS.people,+ filters: defineQueryFilters({+ include: { channelType: ['direct_message'] },+ }),clientFilters: { and: ['people'] },}),teams: () => ({- queryFilters: QUERY_FILTERS.teams,+ filters: defineQueryFilters({+ exclude: { channelType: ['direct_message'] },+ }),clientFilters: { and: ['teams'] },}),},@@ -317,14 +311,16 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {default: 'all',tabs: {all: () => ({- queryFilters: QUERY_FILTERS.calls,+ filters: defineQueryFilters({}, { skipTargets: ['callf'] }),clientFilters: { and: ['calls'] },}),unattended: () => ({- queryFilters: {- ...QUERY_FILTERS.calls,- call_filters: { attended: false },- },+ filters: defineQueryFilters(+ {+ include: { callAttended: false },+ },+ { skipTargets: ['callf'] }+ ),clientFilters: { and: ['calls'] },}),},@@ -335,15 +331,16 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {owned: (ctx) => {if (!ctx.userId) return undefined;return {- queryFilters: {- ...QUERY_FILTERS.folders,- project_filters: { owners: [ctx.userId] },- },- clientFilters: { and: ['folders'] },+ filters: defineQueryFilters({+ include: { folderOwnerId: [ctx.userId] },+ }),+ clientFilters: { and: ['folders', 'owned-entity'] },};},all: () => ({- queryFilters: QUERY_FILTERS.folders,+ filters: defineQueryFilters({+ exclude: { folderId: [NIL_UUID] },+ }),clientFilters: { and: ['folders'] },}),},@@ -352,11 +349,8 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {default: 'all',tabs: {all: () => ({- queryFilters: {- ...QUERY_FILTERS.default,- email_filters: { importance: true },- },- clientFilters: { and: [], or: [] },+ filters: {},+ clientFilters: {},}),},},@@ -368,39 +362,50 @@ type ContextRequiredView = 'agents' | 'documents' | 'tasks' | 'folders';/** Views whose default tab works without user context */type ContextOptionalView = Exclude<ListView, ContextRequiredView>;-/**- * Returns the default filter preset for a list view.- * Uses the view's default tab, falling back to the first available tab- * if the default requires context values that aren't provided.- *- * @param view - The list view to get the preset for- * @param ctx - User context (required for agents, documents, tasks, folders)- */-export function getDefaultListViewPreset(+/** Overload: views that don't require context */+export function getViewPreset(+ view: ContextOptionalView,+ tab?: string+): SoupFiltersPreset | undefined;++/** Overload: views that require user context */+export function getViewPreset(view: ContextRequiredView,+ tab: string | undefined,ctx: PresetContext-): SoupFiltersPreset;-export function getDefaultListViewPreset(- view: ContextOptionalView,- ctx?: PresetContext-): SoupFiltersPreset;-export function getDefaultListViewPreset(+): SoupFiltersPreset | undefined;++/** Overload: any view with context */+export function getViewPreset(view: ListView,- ctx: PresetContext = { userId: undefined, email: undefined }-): SoupFiltersPreset {+ tab: string | undefined,+ ctx: PresetContext+): SoupFiltersPreset | undefined;++export function getViewPreset(+ view: ListView,+ tab?: string,+ ctx?: PresetContext+): SoupFiltersPreset | undefined {const config = VIEW_TAB_PRESETS[view];- const defaultResolver = config.tabs[config.default];+ if (!config) return undefined;- // Try default tab with provided context- const resolved = defaultResolver(ctx);+ const tabId = tab ?? config.default;+ const resolver = config.tabs[tabId];+ if (!resolver) return undefined;++ const presetCtx: PresetContext = ctx ?? {+ userId: undefined,+ email: undefined,+ };+ const resolved = resolver(presetCtx);if (resolved) return resolved;// Fallback: find first tab that works with provided context- for (const resolver of Object.values(config.tabs)) {- const fallback = resolver(ctx);+ for (const fallbackResolver of Object.values(config.tabs)) {+ const fallback = fallbackResolver(presetCtx);if (fallback) return fallback;}- // Last resort: empty filters- return { queryFilters: {}, clientFilters: {} };+ return undefined;}diff --git a/js/app/packages/app/component/next-soup/create-soup-state.ts b/js/app/packages/app/component/next-soup/create-soup-state.tsindex eaa27d4ff1..7e379197af 100644--- a/js/app/packages/app/component/next-soup/create-soup-state.ts+++ b/js/app/packages/app/component/next-soup/create-soup-state.ts@@ -1,16 +1,14 @@-import { useGlobalNotificationSource } from '@app/component/GlobalAppState';import { createSortState } from '@app/component/next-soup/create-sort-state';import {- createFilterState,- createSoupFilters,- SOUP_FILTER_GROUPS,- type FilterConfig,- type FilterGroupConfig,+ SOUP_FILTERS,type FilterID,-} from '@app/component/next-soup/filters';+} from '@app/component/next-soup/filters/configs/';+import {+ createPredicatesStore,+ type PredicateConfig,+} from '@app/component/next-soup/filters/filter-store/predicates-store';import { createSelectionState } from '@app/component/next-soup/selection-state';import { SORT_CONFIGS } from '@app/component/next-soup/soup-view/sort-options';-import { useUserContext } from '@core/context/user';import { isModality } from '@core/mobile/inputModality';import { isTouchDevice } from '@core/mobile/isTouchDevice';import type { EntityData, WithSearch } from '@entity';@@ -32,39 +30,27 @@ export type SortConfig<T> = {interface SoupContextOptions<TId extends string = FilterID> {initialData?: SoupEntity[];- initialFilters?: TId[];- filterConfigs?: FilterConfig<SoupEntity>[];- filterGroups?: FilterGroupConfig[];+ initialPredicates?: {+ and?: TId[];+ or?: TId[];+ };+ predicateConfigs?: PredicateConfig<SoupEntity, string>[];wrapNavigation?: boolean;}export const createSoupState = <TId extends string = FilterID>(options: SoupContextOptions<TId> = { wrapNavigation: false }) => {- const {- wrapNavigation,- initialData,- initialFilters,- filterConfigs,- filterGroups,- } = options;+ const { wrapNavigation, initialData, initialPredicates, predicateConfigs } =+ options;const selection = createSelectionState<SoupEntity>({getItemId: (i) => i.id,});- const notificationSource = useGlobalNotificationSource();- const user = useUserContext();-- const filters = createFilterState({- filters:- filterConfigs ??- (createSoupFilters(- notificationSource,- user.userId- ) as FilterConfig<SoupEntity>[]),- groups: filterGroups ?? SOUP_FILTER_GROUPS,- initialFilters,+ const predicates = createPredicatesStore({+ configs: predicateConfigs ?? SOUP_FILTERS,+ initial: initialPredicates,});const sort = createSortState(SORT_CONFIGS, ['updated_at']);@@ -158,7 +144,7 @@ export const createSoupState = <TId extends string = FilterID>(return {data,setData,- filters,+ predicates,selection,sort,groups,@@ -203,7 +189,7 @@ export const createSoupState = <TId extends string = FilterID>(set: setCollapseEntityCallback,shouldCollapse: () => {return (- filters.isActive('not-done') &&+ predicates.isActive('not-done') &&collapseEntityCallback() !== undefined &&isModality('touch'));diff --git a/js/app/packages/app/component/next-soup/filters/configs.ts b/js/app/packages/app/component/next-soup/filters/configs.tsdeleted file mode 100644index 08eba4b6c8..0000000000--- a/js/app/packages/app/component/next-soup/filters/configs.ts+++ /dev/null@@ -1,448 +0,0 @@-import type {- FilterConfig,- FilterGroupConfig,-} from '@app/component/next-soup/filters/create-filter-state';-import {- isNotStarted,- isInProgress,- isInReview,- isCompleted,- isCanceled,- isUrgentPriority,- isHighPriority,- isMediumPriority,- isLowPriority,- hasNoPriority,- hasAssignees,- isUnassigned,- callsFilter,- channelsFilter,- filesAndFolderFilter,- activeAgentFilter,- emailDraftsFilter,- noDraftsFilter,- hasCalendarInviteFilter,- hasAttachmentFilter,- hasPdfAttachmentFilter,- hasImageAttachmentFilter,- hasDocumentAttachmentFilter,- sharedEntity,- ownedAgentFilter,- sharedAgentFilter,- taskAssignedToUserFilter,- agentFilter,- documentFilter,- emailFilter,- fileFilter,- notDoneFilter,- peopleFilter,- projectFilter,- automationFilter,- taskFilter,- teamsFilter,- unreadFilter,-} from '@app/component/next-soup/filters/predicates';-import {- signalFilter,- noiseFilter,- explicitNoiseFilter,-} from '@app/component/next-soup/filters/inbox-filters';-import { codeFileExtensions } from '@block-code/util/languageSupport';-import {- type EntityData,- isEmailEntity,- isDocumentEntity,- getEntityProjectId,-} from '@entity';-import type { NotificationSource } from '@notifications';--type EntityFilterConfig = FilterConfig<EntityData> & { label?: string };--export const ENTITY_TYPE_FILTER_CONFIGS = [- {- id: 'document',- label: 'Docs',- predicate: documentFilter,- group: 'entity-type',- },- {- id: 'agent',- label: 'Agents',- predicate: agentFilter,- group: 'entity-type',- },- {- id: 'automation',- label: 'Scheduled',- predicate: automationFilter,- group: 'entity-type',- },- {- id: 'people',- label: 'People',- predicate: peopleFilter,- group: 'entity-type',- },- {- id: 'teams',- label: 'Teams',- predicate: teamsFilter,- group: 'entity-type',- },- {- id: 'task',- label: 'Tasks',- predicate: taskFilter,- group: 'entity-type',- },- {- id: 'email',- label: 'Mail',- predicate: emailFilter,- group: 'entity-type',- },- {- id: 'file',- label: 'Files',- predicate: fileFilter,- group: 'entity-type',- },-] as const satisfies EntityFilterConfig[];--export const EMAIL_CONTEXTUAL_FILTERS = [- {- id: 'email-unread',- label: 'Unread',- predicate: (entity) => isEmailEntity(entity) && !entity.isRead,- },- {- id: 'email-read',- label: 'Read',- predicate: (entity) => isEmailEntity(entity) && entity.isRead,- },- {- id: 'email-done',- label: 'Done',- predicate: (entity) => isEmailEntity(entity) && entity.done,- },- {- id: 'email-not-done',- label: 'Not Done',- predicate: (entity) => isEmailEntity(entity) && !entity.done,- },-] as const satisfies EntityFilterConfig[];--export const TASK_STATUS_FILTERS = [- {- id: 'task-not-started',- label: 'Not Started',- predicate: isNotStarted,- },- {- id: 'task-in-progress',- label: 'In Progress',- predicate: isInProgress,- },- {- id: 'task-in-review',- label: 'In Review',- predicate: isInReview,- },- {- id: 'task-completed',- label: 'Completed',- predicate: isCompleted,- },- {- id: 'task-canceled',- label: 'Canceled',- predicate: isCanceled,- },-] as const satisfies EntityFilterConfig[];--export const TASK_PRIORITY_FILTERS = [- {- id: 'task-critical',- label: 'Critical',- predicate: isUrgentPriority,- },- {- id: 'task-high-priority',- label: 'High Priority',- predicate: isHighPriority,- },- {- id: 'task-medium-priority',- label: 'Medium Priority',- predicate: isMediumPriority,- },- {- id: 'task-low-priority',- label: 'Low Priority',- predicate: isLowPriority,- },- {- id: 'task-no-priority',- label: 'No Priority',- predicate: hasNoPriority,- },-] as const satisfies EntityFilterConfig[];--export const TASK_ASSIGNEE_FILTERS = [- {- id: 'task-has-assignee',- label: 'Has Assignee',- predicate: hasAssignees,- },- {- id: 'task-unassigned',- label: 'Unassigned',- predicate: isUnassigned,- },-] as const satisfies EntityFilterConfig[];--export const TASK_CONTEXTUAL_FILTERS = [- ...TASK_STATUS_FILTERS,- ...TASK_PRIORITY_FILTERS,- ...TASK_ASSIGNEE_FILTERS,-] as const satisfies EntityFilterConfig[];--const DOCUMENT_CONTEXTUAL_FILTERS = [- {- id: 'in-folder',- label: 'In Folder',- predicate: (entity) => !!getEntityProjectId(entity),- },- {- id: 'doc-markdown',- label: 'Markdown',- predicate: (entity) => isDocumentEntity(entity) && entity.fileType === 'md',- },- {- id: 'doc-canvas',- label: 'Canvas',- predicate: (entity) =>- isDocumentEntity(entity) && entity.fileType === 'canvas',- },-] as const satisfies EntityFilterConfig[];--const IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'] as const;--export const FILE_TYPE_FILTERS = [- {- id: 'file-code',- label: 'Code',- predicate: (entity) => {- if (entity.type !== 'document') return false;- const fileType = entity.fileType ?? '';- return (codeFileExtensions as readonly string[]).includes(fileType);- },- },- {- id: 'file-image',- label: 'Images',- predicate: (entity) => {- if (entity.type !== 'document') return false;- const fileType = entity.fileType ?? '';- return (IMAGE_EXTENSIONS as readonly string[]).includes(fileType);- },- },- {- id: 'file-pdf',- label: 'PDFs',- predicate: (entity) => {- if (entity.type !== 'document') return false;- return entity.fileType === 'pdf';- },- },- {- id: 'file-docx',- label: 'DOCX',- predicate: (entity) => {- if (entity.type !== 'document') return false;- return entity.fileType === 'docx';- },- },- {- id: 'file-other',- label: 'Other',- predicate: (entity) => {- if (entity.type !== 'document') return false;- const fileType = entity.fileType ?? '';- // Exclude markdown, canvas, code, images, PDFs, and DOCX- if (['md', 'canvas'].includes(fileType)) return false;- if ((codeFileExtensions as readonly string[]).includes(fileType))- return false;- if ((IMAGE_EXTENSIONS as readonly string[]).includes(fileType))- return false;- if (fileType === 'pdf') return false;- if (fileType === 'docx') return false;- return true;- },- },-] as const satisfies EntityFilterConfig[];--export const createSoupFilters = (- notificationSource: NotificationSource,- getUserID: () => string | undefined-) => {- const list = [- {- id: 'signal',- label: 'Inbox',- predicate: signalFilter,- group: 'focus',- },- {- id: 'noise',- label: 'Other',- predicate: noiseFilter,- group: 'focus',- },- {- id: 'explicit-noise',- label: 'Explicit Noise',- predicate: (entity: EntityData) => !explicitNoiseFilter(entity),- group: 'focus',- },- {- id: 'unread',- label: 'Unread',- predicate: unreadFilter(notificationSource),- },- {- id: 'read',- label: 'Read',- predicate: (entity: EntityData) =>- !unreadFilter(notificationSource)(entity),- },- {- id: 'not-done',- label: 'Not done',- predicate: notDoneFilter(notificationSource),- },- {- id: 'done',- label: 'Done',- predicate: (entity: EntityData) =>- !notDoneFilter(notificationSource)(entity),- },- ...ENTITY_TYPE_FILTER_CONFIGS,- {- id: 'channels',- label: 'Channels',- predicate: channelsFilter,- },- {- id: 'calls',- label: 'Calls',- predicate: callsFilter,- },- {- id: 'file-folder',- label: 'Files & Folders',- predicate: filesAndFolderFilter,- },- {- id: 'folders',- label: 'Folders',- predicate: projectFilter,- },- {- id: 'active-agent',- label: 'Running agents',- predicate: activeAgentFilter,- },- {- id: 'email-drafts',- label: 'Email drafts',- predicate: emailDraftsFilter,- },- {- id: 'no-drafts',- label: 'No drafts',- predicate: noDraftsFilter,- },- {- id: 'has-calendar-invite',- label: 'Has calendar invite',- predicate: hasCalendarInviteFilter,- },- {- id: 'has-attachment',- label: 'Has attachment',- predicate: hasAttachmentFilter,- },- {- id: 'attachment-pdf',- label: 'PDF attachment',- predicate: hasPdfAttachmentFilter,- },- {- id: 'attachment-image',- label: 'Image attachment',- predicate: hasImageAttachmentFilter,- },- {- id: 'attachment-document',- label: 'Document attachment',- predicate: hasDocumentAttachmentFilter,- },- {- id: 'shared-entity',- label: 'Shared entities',- predicate: sharedEntity(getUserID),- },- {- id: 'owned-agent',- label: 'Owned by me',- predicate: ownedAgentFilter(getUserID),- },- {- id: 'shared-agent',- label: 'Shared with me',- predicate: sharedAgentFilter(getUserID),- },- {- id: 'assigned-to',- label: 'Task assigned to user',- predicate: taskAssignedToUserFilter(getUserID),- },- {- id: 'not-task',- label: 'Not Task',- predicate: (entity) => !taskFilter(entity),- },- {- id: 'document-or-file',- label: 'Documents & Files',- predicate: (entity) => entity.type === 'document' && !taskFilter(entity),- },- {- id: 'active-task',- label: 'Task active',- predicate: (entity) =>- taskFilter(entity) && !isCompleted(entity) && !isCanceled(entity),- },- ...TASK_STATUS_FILTERS,- ...TASK_PRIORITY_FILTERS,- ...DOCUMENT_CONTEXTUAL_FILTERS,- ...FILE_TYPE_FILTERS,- ] as const satisfies EntityFilterConfig[];-- return list;-};--/**- * Default filter group configurations for soup filters.- * - 'focus': Mutually exclusive (signal/noise/explicit-noise)- * - 'entity-type': Mutually exclusive by default- */-export const SOUP_FILTER_GROUPS: FilterGroupConfig[] = [- { id: 'focus', allowMultiple: false },- { id: 'entity-type', allowMultiple: true },-];--type SoupFilter = ReturnType<typeof createSoupFilters>[number];--export type FilterID = Extract<SoupFilter, { id: string }>['id'];diff --git a/js/app/packages/app/component/next-soup/filters/configs/base.ts b/js/app/packages/app/component/next-soup/filters/configs/base.tsnew file mode 100644index 0000000000..115e68a667--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/configs/base.ts@@ -0,0 +1,68 @@+import type { EntityData } from '@entity';+import type { NotificationSource } from '@notifications';+import type { Query, PropertyFilter } from '../filter-store';++export const NO_ASSIGNEE = 'NO_ASSIGNEE';++export const NIL_UUID = '00000000-0000-0000-0000-000000000000';++export const IMAGE_EXTENSIONS = [+ 'png',+ 'jpg',+ 'jpeg',+ 'gif',+ 'svg',+ 'webp',+] as const;++export const isEmail = { exclude: { threadId: [NIL_UUID] } };+export const isAgent = { exclude: { chatId: [NIL_UUID] } };+export const isTask = { include: { subType: ['task'] } };+export const isNotTask = { exclude: { subType: ['task'] } };+export const isEmailAttachment = { include: { isEmailAttachment: true } };+export const isChannel = { exclude: { channelId: [NIL_UUID] } };+export const isFolder = { exclude: { folderId: [NIL_UUID] } };++export type FilterContext = {+ userId?: string;+ notificationSource?: NotificationSource;+ assignees?: string[];+};++export type Predicate = (entity: EntityData, ctx: FilterContext) => boolean;++export type QueryInput = Query;+export type QueryFn = (ctx: FilterContext) => QueryInput;++export type FilterDefinition<TId extends string = string> = {+ id: TId;+ group?: string;+ predicate: Predicate;+ query: QueryInput | QueryFn;+};++export type FilterGroupConfig = { id: string; allowMultiple: boolean };++export function config<TId extends string>(opts: {+ id: TId;+ query: QueryInput | QueryFn;+ predicate: Predicate;+ group?: string;+}): FilterDefinition<TId> {+ return {+ id: opts.id,+ group: opts.group,+ predicate: opts.predicate,+ query: opts.query,+ };+}++export const propFilter = (+ propertyId: string,+ type: 'select' | 'entity',+ value: string+): PropertyFilter => ({+ propertyId,+ type,+ value,+});diff --git a/js/app/packages/app/component/next-soup/filters/configs/document.ts b/js/app/packages/app/component/next-soup/filters/configs/document.tsnew file mode 100644index 0000000000..6c46c25770--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/configs/document.ts@@ -0,0 +1,85 @@+import { codeFileExtensions } from '@block-code/util/languageSupport';+import { isDocumentEntity } from '@entity';+import { config, IMAGE_EXTENSIONS, isEmailAttachment } from './base';++export const docMarkdownFilter = config({+ id: 'doc-markdown',+ predicate: (e) => isDocumentEntity(e) && e.fileType === 'md',+ query: { include: { fileAssoc: ['assoc:md'] } },+});++export const docCanvasFilter = config({+ id: 'doc-canvas',+ predicate: (e) => isDocumentEntity(e) && e.fileType === 'canvas',+ query: { include: { fileAssoc: ['assoc:canvas'] } },+});++/**+ * Email attachments filter - filters for documents that are email attachments.+ * Server-side only: `isEmailAttachment` is not available on client entity.+ */+export const emailAttachmentsFilter = config({+ id: 'email-attachments',+ predicate: (e) => e.type === 'document', // Server handles actual filtering via `iea`+ query: isEmailAttachment,+});++export const DOCUMENT_CONTEXTUAL_FILTERS = [+ docMarkdownFilter,+ docCanvasFilter,+ emailAttachmentsFilter,+] as const;++export const fileCodeFilter = config({+ id: 'file-code',+ predicate: (e) => {+ if (e.type !== 'document') return false;+ return (codeFileExtensions as readonly string[]).includes(e.fileType ?? '');+ },+ query: { include: { fileAssoc: ['assoc:code'] } },+});++export const fileImageFilter = config({+ id: 'file-image',+ predicate: (e) => {+ if (e.type !== 'document') return false;+ return (IMAGE_EXTENSIONS as readonly string[]).includes(e.fileType ?? '');+ },+ query: { include: { fileAssoc: ['assoc:image'] } },+});++export const filePdfFilter = config({+ id: 'file-pdf',+ predicate: (e) => e.type === 'document' && e.fileType === 'pdf',+ query: { include: { fileAssoc: ['assoc:pdf'] } },+});++export const fileDocxFilter = config({+ id: 'file-docx',+ predicate: (e) => e.type === 'document' && e.fileType === 'docx',+ query: { include: { fileAssoc: ['assoc:document'] } },+});++export const fileOtherFilter = config({+ id: 'file-other',+ predicate: (e) => {+ if (e.type !== 'document') return false;+ const ft = e.fileType ?? '';+ if (['md', 'canvas', 'pdf', 'docx'].includes(ft)) return false;+ if ((codeFileExtensions as readonly string[]).includes(ft)) return false;+ if ((IMAGE_EXTENSIONS as readonly string[]).includes(ft)) return false;+ return true;+ },+ query: {+ include: { fileAssoc: ['assoc:other'] },+ exclude: { fileAssoc: ['assoc:document', 'assoc:image'] },+ },+});++export const FILE_TYPE_FILTERS = [+ fileCodeFilter,+ fileImageFilter,+ filePdfFilter,+ fileDocxFilter,+ fileOtherFilter,+] as const;diff --git a/js/app/packages/app/component/next-soup/filters/configs/email.ts b/js/app/packages/app/component/next-soup/filters/configs/email.tsnew file mode 100644index 0000000000..6801211cee--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/configs/email.ts@@ -0,0 +1,52 @@+import {+ emailDraftsFilter as emailDraftsPredicate,+ noDraftsFilter as noDraftsPredicate,+ hasCalendarInviteFilter as hasCalendarInvitePredicate,+ hasAttachmentFilter as hasAttachmentPredicate,+ hasPdfAttachmentFilter as hasPdfAttachmentPredicate,+ hasImageAttachmentFilter as hasImageAttachmentPredicate,+ hasDocumentAttachmentFilter as hasDocumentAttachmentPredicate,+} from '../predicates';+import { config, isEmail } from './base';++export const emailDraftsFilter = config({+ id: 'email-drafts',+ predicate: emailDraftsPredicate,+ query: { ...isEmail, emailView: 'drafts' },+});++export const noDraftsFilter = config({+ id: 'no-drafts',+ predicate: noDraftsPredicate,+ query: isEmail,+});++export const hasCalendarInviteFilter = config({+ id: 'has-calendar-invite',+ predicate: hasCalendarInvitePredicate,+ query: isEmail,+});++export const hasAttachmentFilter = config({+ id: 'has-attachment',+ predicate: hasAttachmentPredicate,+ query: isEmail,+});++export const attachmentPdfFilter = config({+ id: 'attachment-pdf',+ predicate: hasPdfAttachmentPredicate,+ query: isEmail,+});++export const attachmentImageFilter = config({+ id: 'attachment-image',+ predicate: hasImageAttachmentPredicate,+ query: isEmail,+});++export const attachmentDocumentFilter = config({+ id: 'attachment-document',+ predicate: hasDocumentAttachmentPredicate,+ query: isEmail,+});diff --git a/js/app/packages/app/component/next-soup/filters/configs/entity-type.ts b/js/app/packages/app/component/next-soup/filters/configs/entity-type.tsnew file mode 100644index 0000000000..43f65e0756--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/configs/entity-type.ts@@ -0,0 +1,83 @@+import {+ documentFilter as documentPredicate,+ taskFilter as taskPredicate,+ emailFilter as emailPredicate,+ peopleFilter as peoplePredicate,+ teamsFilter as teamsPredicate,+ agentFilter as agentPredicate,+ automationFilter as automationPredicate,+ fileFilter as filePredicate,+} from '../predicates';+import { config, isAgent, isEmail, isTask } from './base';++export const documentFilter = config({+ id: 'document',+ group: 'entity-type',+ predicate: documentPredicate,+ query: {+ include: { fileAssoc: ['assoc:md', 'assoc:canvas'] },+ exclude: { subType: ['task'] },+ },+});++export const agentFilter = config({+ id: 'agent',+ group: 'entity-type',+ predicate: agentPredicate,+ query: isAgent,+});++export const automationFilter = config({+ id: 'automation',+ group: 'entity-type',+ predicate: automationPredicate,+ query: {}, // No server query - automations are merged client-side via additionalEntities+});++export const peopleFilter = config({+ id: 'people',+ group: 'entity-type',+ predicate: peoplePredicate,+ query: { include: { channelType: ['direct_message'] } },+});++export const teamsFilter = config({+ id: 'teams',+ group: 'entity-type',+ predicate: teamsPredicate,+ query: { exclude: { channelType: ['direct_message'] } },+});++export const taskFilter = config({+ id: 'task',+ group: 'entity-type',+ predicate: taskPredicate,+ query: isTask,+});++export const emailFilter = config({+ id: 'email',+ group: 'entity-type',+ predicate: emailPredicate,+ query: isEmail,+});++export const fileFilter = config({+ id: 'file',+ group: 'entity-type',+ predicate: filePredicate,+ query: {+ exclude: { fileAssoc: ['assoc:md', 'assoc:canvas'], subType: ['task'] },+ },+});++export const ENTITY_TYPE_FILTERS = [+ documentFilter,+ agentFilter,+ automationFilter,+ peopleFilter,+ teamsFilter,+ taskFilter,+ emailFilter,+ fileFilter,+] as const;diff --git a/js/app/packages/app/component/next-soup/filters/configs/entity.ts b/js/app/packages/app/component/next-soup/filters/configs/entity.tsnew file mode 100644index 0000000000..8da4bda056--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/configs/entity.ts@@ -0,0 +1,61 @@+import { getEntityProjectId } from '@entity';+import {+ channelsFilter as channelsPredicate,+ filesAndFolderFilter as filesAndFolderPredicate,+ projectFilter as projectPredicate,+ activeAgentFilter as activeAgentPredicate,+ taskFilter as taskPredicate,+ callsFilter as callsPredicate,+} from '../predicates';+import { defineQueryFilters } from '../filter-store/compile';+import { config, isAgent, isNotTask, NIL_UUID } from './base';++export const channelsFilter = config({+ id: 'channels',+ predicate: channelsPredicate,+ query: { exclude: { channelId: [NIL_UUID] } },+});++export const filesAndFolderFilter = config({+ id: 'file-folder',+ predicate: filesAndFolderPredicate,+ query: {+ exclude: { fileAssoc: ['assoc:md', 'assoc:canvas'], folderId: [NIL_UUID] },+ },+});++export const foldersFilter = config({+ id: 'folders',+ predicate: projectPredicate,+ query: { exclude: { folderId: [NIL_UUID] } },+});++export const activeAgentFilter = config({+ id: 'active-agent',+ predicate: activeAgentPredicate,+ query: isAgent,+});++export const notTaskFilter = config({+ id: 'not-task',+ predicate: (e) => !taskPredicate(e),+ query: isNotTask,+});++export const documentOrFileFilter = config({+ id: 'document-or-file',+ predicate: (e) => e.type === 'document' && !taskPredicate(e),+ query: isNotTask,+});++export const inFolderFilter = config({+ id: 'in-folder',+ predicate: (e) => !!getEntityProjectId(e),+ query: { exclude: { projectId: [NIL_UUID] } },+});++export const callsFilter = config({+ id: 'calls',+ predicate: callsPredicate,+ query: defineQueryFilters({}, { skipTargets: ['callf'] }),+});diff --git a/js/app/packages/app/component/next-soup/filters/configs/general.ts b/js/app/packages/app/component/next-soup/filters/configs/general.tsnew file mode 100644index 0000000000..755b709834--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/configs/general.ts@@ -0,0 +1,155 @@+import {+ unreadFilter as unreadPredicate,+ notDoneFilter as notDonePredicate,+ sharedEntity as sharedEntityPredicate,+} from '../predicates';+import {+ signalFilter,+ noiseFilter,+ explicitNoiseFilter,+} from '../inbox-filters';+import { config, NIL_UUID } from './base';++export const inboxFilter = config({+ id: 'inbox',+ group: 'focus',+ predicate: (e, ctx) =>+ signalFilter(e) &&+ (ctx.notificationSource+ ? notDonePredicate(ctx.notificationSource)(e)+ : false),+ query: {+ include: {+ documentDone: false,+ emailDone: false,+ emailImportance: true,+ channelDone: false,+ chatDone: false,+ folderDone: false,+ },+ emailView: 'inbox',+ },+});++export const noiseFilterDef = config({+ id: 'noise',+ group: 'focus',+ predicate: (e) => noiseFilter(e),+ query: {+ include: {+ documentDone: false,+ emailDone: false,+ emailImportance: false,+ channelDone: false,+ chatDone: false,+ folderDone: false,+ },+ emailView: 'inbox',+ },+});++export const explicitNoiseFilterDef = config({+ id: 'explicit-noise',+ group: 'focus',+ predicate: (e) => !explicitNoiseFilter(e),+ query: {+ exclude: {+ documentId: [NIL_UUID],+ channelId: [NIL_UUID],+ chatId: [NIL_UUID],+ folderId: [NIL_UUID],+ threadId: [NIL_UUID],+ },+ emailView: 'all',+ },+});++export const unreadFilter = config({+ id: 'unread',+ predicate: (e, ctx) =>+ ctx.notificationSource ? unreadPredicate(ctx.notificationSource)(e) : false,+ query: {+ include: {+ documentSeen: false,+ emailSeen: false,+ channelSeen: false,+ chatSeen: false,+ folderSeen: false,+ },+ },+});++export const readFilter = config({+ id: 'read',+ predicate: (e, ctx) =>+ ctx.notificationSource+ ? !unreadPredicate(ctx.notificationSource)(e)+ : false,+ query: {+ include: {+ documentSeen: true,+ emailSeen: true,+ channelSeen: true,+ chatSeen: true,+ folderSeen: true,+ },+ },+});++export const notDoneFilter = config({+ id: 'not-done',+ predicate: (e, ctx) =>+ ctx.notificationSource+ ? notDonePredicate(ctx.notificationSource)(e)+ : false,+ query: {+ include: {+ documentDone: false,+ emailDone: false,+ channelDone: false,+ chatDone: false,+ folderDone: false,+ },+ },+});++export const doneFilter = config({+ id: 'done',+ predicate: (e, ctx) =>+ ctx.notificationSource+ ? !notDonePredicate(ctx.notificationSource)(e)+ : false,+ query: {+ include: {+ documentDone: true,+ emailDone: true,+ channelDone: true,+ chatDone: true,+ folderDone: true,+ },+ },+});++export const sharedEntityFilter = config({+ id: 'shared-entity',+ predicate: (e, ctx) => sharedEntityPredicate(() => ctx.userId)(e),+ query: (ctx) => ({+ exclude: {+ documentOwnerId: [ctx.userId ?? ''],+ chatOwnerId: [ctx.userId ?? ''],+ folderOwnerId: [ctx.userId ?? ''],+ },+ }),+});++export const ownedEntityFilter = config({+ id: 'owned-entity',+ predicate: (e, ctx) => !sharedEntityPredicate(() => ctx.userId)(e),+ query: (ctx) => ({+ include: {+ documentOwnerId: [ctx.userId ?? ''],+ chatOwnerId: [ctx.userId ?? ''],+ folderOwnerId: [ctx.userId ?? ''],+ },+ }),+});diff --git a/js/app/packages/app/component/next-soup/filters/configs/index.ts b/js/app/packages/app/component/next-soup/filters/configs/index.tsnew file mode 100644index 0000000000..64fc9cbf38--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/configs/index.ts@@ -0,0 +1,98 @@+export * from './base';+export * from './entity-type';+export * from './entity';+export * from './document';+export * from './email';+export * from './task';+export * from './general';++export type { FilterContext } from './base';+export { ENTITY_TYPE_FILTERS } from './entity-type';+export { TASK_STATUS_FILTERS, TASK_PRIORITY_FILTERS } from './task';+import { ENTITY_TYPE_FILTERS } from './entity-type';+import {+ channelsFilter,+ filesAndFolderFilter,+ foldersFilter,+ activeAgentFilter,+ notTaskFilter,+ documentOrFileFilter,+ callsFilter,+ inFolderFilter,+} from './entity';+import {+ DOCUMENT_CONTEXTUAL_FILTERS,+ FILE_TYPE_FILTERS,+ emailAttachmentsFilter,+} from './document';+import {+ TASK_STATUS_FILTERS,+ TASK_PRIORITY_FILTERS,+ activeTaskFilter,+ assignedToMeFilter,+ assigneeFilter,+} from './task';+import {+ emailDraftsFilter,+ noDraftsFilter,+ hasCalendarInviteFilter,+ hasAttachmentFilter,+ attachmentPdfFilter,+ attachmentImageFilter,+ attachmentDocumentFilter,+} from './email';+import {+ inboxFilter,+ noiseFilterDef,+ explicitNoiseFilterDef,+ unreadFilter,+ readFilter,+ notDoneFilter,+ doneFilter,+ sharedEntityFilter,+ ownedEntityFilter,+} from './general';+import type { FilterGroupConfig } from './base';++export const SOUP_FILTERS = [+ inboxFilter,+ noiseFilterDef,+ explicitNoiseFilterDef,+ unreadFilter,+ readFilter,+ notDoneFilter,+ doneFilter,+ channelsFilter,+ filesAndFolderFilter,+ foldersFilter,+ activeAgentFilter,+ emailDraftsFilter,+ noDraftsFilter,+ hasCalendarInviteFilter,+ hasAttachmentFilter,+ attachmentPdfFilter,+ attachmentImageFilter,+ attachmentDocumentFilter,+ sharedEntityFilter,+ ownedEntityFilter,+ assignedToMeFilter,+ assigneeFilter,+ notTaskFilter,+ documentOrFileFilter,+ activeTaskFilter,+ callsFilter,+ emailAttachmentsFilter,+ inFolderFilter,+ ...ENTITY_TYPE_FILTERS,+ ...TASK_STATUS_FILTERS,+ ...TASK_PRIORITY_FILTERS,+ ...DOCUMENT_CONTEXTUAL_FILTERS,+ ...FILE_TYPE_FILTERS,+] as const;++export const SOUP_FILTER_GROUPS: FilterGroupConfig[] = [+ { id: 'focus', allowMultiple: false },+ { id: 'entity-type', allowMultiple: true },+];++export type FilterID = (typeof SOUP_FILTERS)[number]['id'];diff --git a/js/app/packages/app/component/next-soup/filters/configs/task.ts b/js/app/packages/app/component/next-soup/filters/configs/task.tsnew file mode 100644index 0000000000..ae815fbfe5--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/configs/task.ts@@ -0,0 +1,223 @@+import {+ PROPERTY_OPTION_IDS,+ SYSTEM_PROPERTY_IDS,+} from '@core/component/Properties/constants';+import {+ type TaskEntityWithProperties,+ isTaskEntity,+ getTaskAssigneeIds,+} from '@entity';+import {+ isNotStarted,+ isInProgress,+ isInReview,+ isCompleted,+ isCanceled,+ isOpen,+ isUrgentPriority,+ isHighPriority,+ isMediumPriority,+ isLowPriority,+ hasNoPriority,+ taskFilter as taskPredicate,+ taskAssignedToUserFilter as taskAssignedToUserPredicate,+} from '../predicates';+import {+ config,+ propFilter,+ isTask,+ NO_ASSIGNEE,+ type Predicate,+} from './base';++const statusFilter = <TId extends string>(+ id: TId,+ status: string,+ predicate: Predicate+) =>+ config({+ id,+ predicate,+ query: {+ include: {+ properties: [propFilter(SYSTEM_PROPERTY_IDS.STATUS, 'select', status)],+ },+ },+ });++const priorityFilter = <TId extends string>(+ id: TId,+ priority: string,+ predicate: Predicate+) =>+ config({+ id,+ predicate,+ query: {+ include: {+ properties: [+ propFilter(SYSTEM_PROPERTY_IDS.PRIORITY, 'select', priority),+ ],+ },+ },+ });++export const taskNotStartedFilter = statusFilter(+ 'task-not-started',+ PROPERTY_OPTION_IDS.STATUS.NOT_STARTED,+ isNotStarted+);++export const taskInProgressFilter = statusFilter(+ 'task-in-progress',+ PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS,+ isInProgress+);++export const taskInReviewFilter = statusFilter(+ 'task-in-review',+ PROPERTY_OPTION_IDS.STATUS.IN_REVIEW,+ isInReview+);++export const taskCompletedFilter = statusFilter(+ 'task-completed',+ PROPERTY_OPTION_IDS.STATUS.COMPLETED,+ isCompleted+);++export const taskCanceledFilter = statusFilter(+ 'task-canceled',+ PROPERTY_OPTION_IDS.STATUS.CANCELED,+ isCanceled+);++export const activeTaskFilter = config({+ id: 'active-task',+ predicate: (e) => taskPredicate(e) && isOpen(e),+ query: {+ include: { subType: ['task'] },+ exclude: {+ properties: [+ propFilter(+ SYSTEM_PROPERTY_IDS.STATUS,+ 'select',+ PROPERTY_OPTION_IDS.STATUS.COMPLETED+ ),+ propFilter(+ SYSTEM_PROPERTY_IDS.STATUS,+ 'select',+ PROPERTY_OPTION_IDS.STATUS.CANCELED+ ),+ ],+ },+ },+});++export const TASK_STATUS_FILTERS = [+ taskNotStartedFilter,+ taskInProgressFilter,+ taskInReviewFilter,+ taskCompletedFilter,+ taskCanceledFilter,+] as const;++export const taskCriticalFilter = priorityFilter(+ 'task-critical',+ PROPERTY_OPTION_IDS.PRIORITY.URGENT,+ isUrgentPriority+);++export const taskHighPriorityFilter = priorityFilter(+ 'task-high-priority',+ PROPERTY_OPTION_IDS.PRIORITY.HIGH,+ isHighPriority+);++export const taskMediumPriorityFilter = priorityFilter(+ 'task-medium-priority',+ PROPERTY_OPTION_IDS.PRIORITY.MEDIUM,+ isMediumPriority+);++export const taskLowPriorityFilter = priorityFilter(+ 'task-low-priority',+ PROPERTY_OPTION_IDS.PRIORITY.LOW,+ isLowPriority+);++export const taskNoPriorityFilter = config({+ id: 'task-no-priority',+ predicate: hasNoPriority,+ query: {+ ...isTask,+ exclude: {+ properties: [+ propFilter(+ SYSTEM_PROPERTY_IDS.PRIORITY,+ 'select',+ PROPERTY_OPTION_IDS.PRIORITY.URGENT+ ),+ propFilter(+ SYSTEM_PROPERTY_IDS.PRIORITY,+ 'select',+ PROPERTY_OPTION_IDS.PRIORITY.HIGH+ ),+ propFilter(+ SYSTEM_PROPERTY_IDS.PRIORITY,+ 'select',+ PROPERTY_OPTION_IDS.PRIORITY.MEDIUM+ ),+ propFilter(+ SYSTEM_PROPERTY_IDS.PRIORITY,+ 'select',+ PROPERTY_OPTION_IDS.PRIORITY.LOW+ ),+ ],+ },+ },+});++export const TASK_PRIORITY_FILTERS = [+ taskCriticalFilter,+ taskHighPriorityFilter,+ taskMediumPriorityFilter,+ taskLowPriorityFilter,+ taskNoPriorityFilter,+] as const;++export const assignedToMeFilter = config({+ id: 'assigned-to',+ predicate: (e, ctx) => taskAssignedToUserPredicate(() => ctx.userId)(e),+ query: (ctx) => ({+ include: {+ properties: [+ propFilter(SYSTEM_PROPERTY_IDS.ASSIGNEES, 'entity', ctx.userId ?? ''),+ ],+ },+ }),+});++export const assigneeFilter = config({+ id: 'assignee',+ predicate: (e, ctx) => {+ if (!ctx.assignees?.length || !isTaskEntity(e)) return true;+ const ids = getTaskAssigneeIds(e as unknown as TaskEntityWithProperties);+ return ctx.assignees.some((id: string) =>+ id === NO_ASSIGNEE ? ids.length === 0 : ids.includes(id)+ );+ },+ query: (ctx) => {+ if (!ctx.assignees?.length) return {};+ const userIds = ctx.assignees.filter((id: string) => id !== NO_ASSIGNEE);+ if (userIds.length === 0) return isTask;+ return {+ ...isTask,+ include: {+ properties: userIds.map((id: string) =>+ propFilter(SYSTEM_PROPERTY_IDS.ASSIGNEES, 'entity', id)+ ),+ },+ };+ },+});diff --git a/js/app/packages/app/component/next-soup/filters/create-filter-state.ts b/js/app/packages/app/component/next-soup/filters/create-filter-state.tsdeleted file mode 100644index 5235f30fce..0000000000--- a/js/app/packages/app/component/next-soup/filters/create-filter-state.ts+++ /dev/null@@ -1,263 +0,0 @@-import { createMemo, createSignal, type Accessor } from 'solid-js';--export type FilterPredicate<T> = (entity: T) => boolean;--export type FilterConfig<T, TId extends string = string> = {- readonly id: TId;- readonly predicate: FilterPredicate<T>;- readonly group?: string;-};--export type FilterGroupConfig = {- readonly id: string;- readonly allowMultiple?: boolean;-};--type FilterIdInput<TId extends string> = TId | (string & {});--export type SetFiltersInput<- TFilter extends FilterConfig<unknown>,- TId extends string = TFilter['id'],-> = {- /** Filters that must ALL pass (AND logic) */- readonly and?: readonly (TFilter | FilterIdInput<TId>)[];- /** Filters where ANY must pass (OR logic) */- readonly or?: readonly (TFilter | FilterIdInput<TId>)[];-};--export type CurrentFilterState<TId extends string> = {- readonly andIds: readonly TId[];- readonly orIds: readonly TId[];-};--/**- * Callback function for updating filters based on current state.- */-export type SetFiltersCallback<- TFilter extends FilterConfig<unknown>,- TId extends string,-> = (current: CurrentFilterState<TId>) => SetFiltersInput<TFilter, TId>;--/** Internal representation of active filters */-type ActiveFiltersState<TFilter> = {- readonly andFilters: readonly TFilter[];- readonly orFilters: readonly TFilter[];-};--export type FilterStateOptions<T, TFilter extends FilterConfig<T, string>> = {- /** All available filter configurations */- readonly filters: readonly TFilter[];- /** Filter group configurations for controlling mutual exclusivity */- readonly groups?: readonly FilterGroupConfig[];- /** Initial active filter IDs (applied as AND filters) */- readonly initialFilters?: readonly string[];-};--export type FilterState<- T,- TFilter extends FilterConfig<T, string>,- TId extends string = TFilter['id'],-> = {- /** Currently active AND filter configs */- readonly andFilters: Accessor<readonly TFilter[]>;- /** Currently active OR filter configs */- readonly orFilters: Accessor<readonly TFilter[]>;- /** All currently active filter configs (both AND and OR) */- readonly active: Accessor<readonly TFilter[]>;- /** IDs of currently active filters */- readonly activeIds: Accessor<readonly TId[]>;- /** Check if a filter is active by ID */- readonly isActive: (id: FilterIdInput<TId>) => boolean;- /** Clear all active filters */- readonly clear: () => void;- /** Toggle filters on/off. Respects group exclusivity. */- readonly toggle: (- input: SetFiltersInput<TFilter, TId> | SetFiltersCallback<TFilter, TId>- ) => void;- /** Set filters with explicit AND/OR grouping. Replaces all current filters. */- readonly set: (- input: SetFiltersInput<TFilter, TId> | SetFiltersCallback<TFilter, TId>- ) => void;- /** Get a filter config by ID */- readonly getFilter: (id: FilterIdInput<TId>) => TFilter | undefined;- /** All available filter configs */- readonly available: readonly TFilter[];- /** Test if an entity passes the active filters. */- readonly test: (entity: T) => boolean;-};--export function createFilterState<- T,- TFilter extends FilterConfig<T>,- TId extends string = TFilter['id'],->(options: FilterStateOptions<T, TFilter>): FilterState<T, TFilter, TId> {- const {- filters: availableFilters,- groups = [],- initialFilters = [],- } = options;-- const filterMap = new Map<string, TFilter>(- availableFilters.map((f) => [f.id, f])- );-- const groupMap = new Map<string, FilterGroupConfig>(- groups.map((g) => [g.id, g])- );-- // Initialize with initial filters (as AND filters)- const initialAndFilters = initialFilters- .map((id) => filterMap.get(id))- .filter((f): f is TFilter => f !== undefined);-- const [state, setState] = createSignal<ActiveFiltersState<TFilter>>({- andFilters: initialAndFilters,- orFilters: [],- });-- const andFilters = createMemo(() => state().andFilters);- const orFilters = createMemo(() => state().orFilters);-- const active = createMemo(() => [- ...state().andFilters,- ...state().orFilters,- ]);- const activeIds = createMemo(() => active().map((f) => f.id) as TId[]);-- const getFilter = (id: FilterIdInput<TId>): TFilter | undefined =>- filterMap.get(id);-- const isActive = (id: FilterIdInput<TId>): boolean =>- activeIds().includes(id as TId);-- const resolveFilters = (- input: readonly (TFilter | FilterIdInput<TId>)[] | undefined- ): TFilter[] => {- if (!input) return [];-- const resolved: TFilter[] = [];- for (const item of input) {- if (typeof item === 'string') {- const filter = getFilter(item);- if (filter) resolved.push(filter);- } else {- resolved.push(item);- }- }- return resolved;- };-- const set = (- input: SetFiltersInput<TFilter, TId> | SetFiltersCallback<TFilter, TId>- ) => {- const resolved =- typeof input === 'function'- ? input({- andIds: state().andFilters.map((f) => f.id) as TId[],- orIds: state().orFilters.map((f) => f.id) as TId[],- })- : input;-- const newState: ActiveFiltersState<TFilter> = {- andFilters: resolveFilters(resolved.and),- orFilters: resolveFilters(resolved.or),- };- setState(newState);- };-- const toggleFilters = (- currentFilters: readonly TFilter[],- toToggle: readonly TFilter[]- ): TFilter[] => {- let result = [...currentFilters];-- for (const filter of toToggle) {- const isCurrentlyActive = result.some((f) => f.id === filter.id);-- if (isCurrentlyActive) {- // Deactivate- result = result.filter((f) => f.id !== filter.id);- } else {- // Activate - handle group exclusivity based on allowMultiple- if (filter.group) {- const groupConfig = groupMap.get(filter.group);- const allowMultiple = groupConfig?.allowMultiple ?? false;-- if (!allowMultiple) {- // Remove other filters in the same group- result = result.filter((f) => f.group !== filter.group);- }- }- result.push(filter);- }- }-- return result;- };-- const toggle = (- input: SetFiltersInput<TFilter, TId> | SetFiltersCallback<TFilter, TId>- ) => {- const resolved =- typeof input === 'function'- ? input({- andIds: state().andFilters.map((f) => f.id) as TId[],- orIds: state().orFilters.map((f) => f.id) as TId[],- })- : input;-- const andToToggle = resolveFilters(resolved.and);- const orToToggle = resolveFilters(resolved.or);-- const current = state();-- setState({- andFilters: toggleFilters(current.andFilters, andToToggle),- orFilters: toggleFilters(current.orFilters, orToToggle),- });- };-- const clear = () => {- setState({- andFilters: [],- orFilters: [],- });- };-- const test = (entity: T): boolean => {- const { andFilters: andList, orFilters: orList } = state();-- // If no filters are active, everything passes- if (andList.length === 0 && orList.length === 0) {- return true;- }-- // All AND filters must pass- if (andList.length > 0) {- const passesAnd = andList.every((f) => f.predicate(entity));- if (!passesAnd) return false;- }-- // At least one OR filter must pass (if any OR filters are active)- if (orList.length > 0) {- const passesOr = orList.some((f) => f.predicate(entity));- if (!passesOr) return false;- }-- return true;- };-- return {- andFilters,- orFilters,- active,- activeIds,- isActive,- toggle,- clear,- set,- getFilter,- available: availableFilters,- test,- };-}diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts b/js/app/packages/app/component/next-soup/filters/filter-store/compile.tsnew file mode 100644index 0000000000..9ae613f7db--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts@@ -0,0 +1,259 @@+import type {+ FieldFilters,+ FieldName,+ PropertyFilter,+ Query,+ QueryState,+ EmailView,+} from './types';++const NIL_UUID = '00000000-0000-0000-0000-000000000000';++type BackendAst =+ | { '&': [BackendAst, BackendAst] }+ | { '|': [BackendAst, BackendAst] }+ | { '!': BackendAst }+ | { l: unknown };++type QueryTarget = 'df' | 'ef' | 'chanf' | 'cf' | 'pf' | 'callf' | 'propf';++export type TargetAstMap = {+ [K in QueryTarget]?: BackendAst;+} & {+ emailView?: EmailView;+};++type CompiledFieldName = Exclude<FieldName, 'properties'>;++const AST = {+ or(asts: BackendAst[]): BackendAst {+ if (asts.length === 0) return { l: {} };+ if (asts.length === 1) return asts[0];+ return asts.reduceRight((acc, ast) => ({ '|': [ast, acc] }));+ },+ and(asts: BackendAst[]): BackendAst {+ if (asts.length === 0) return { l: {} };+ if (asts.length === 1) return asts[0];+ return asts.reduceRight((acc, ast) => ({ '&': [ast, acc] }));+ },+ not(ast: BackendAst): BackendAst {+ return { '!': ast };+ },+ literal(field: string, value: unknown): BackendAst {+ return { l: { [field]: value } };+ },+};++const FIELD_CONFIG: Record<+ CompiledFieldName,+ {+ target: QueryTarget;+ field: string;+ formatValue?: (value: unknown) => unknown;+ }+> = {+ documentId: { target: 'df', field: 'id' },+ fileType: { target: 'df', field: 'ft' },+ fileAssoc: { target: 'df', field: 'fa' },+ subType: { target: 'df', field: 'dst' },+ projectId: { target: 'df', field: 'pid' },+ documentOwnerId: { target: 'df', field: 'o' },+ documentSeen: { target: 'df', field: 'ns' },+ documentDone: { target: 'df', field: 'nd' },+ isEmailAttachment: { target: 'df', field: 'iea' },+ threadId: { target: 'ef', field: 'ThreadId' },+ emailSeen: { target: 'ef', field: 'NotificationSeen' },+ emailDone: { target: 'ef', field: 'NotificationDone' },+ emailImportance: { target: 'ef', field: 'Importance' },+ emailProjectId: { target: 'ef', field: 'ProjectId' },+ emailSender: {+ target: 'ef',+ field: 'Sender',+ formatValue: (v) => ({ Partial: v }),+ },+ emailShared: { target: 'ef', field: 'Shared' },+ emailCalendarOnly: { target: 'ef', field: 'CalendarOnly' },+ channelId: { target: 'chanf', field: 'ChannelId' },+ channelType: { target: 'chanf', field: 'ChannelType' },+ channelSeen: { target: 'chanf', field: 'NotificationSeen' },+ channelDone: { target: 'chanf', field: 'NotificationDone' },+ channelImportance: { target: 'chanf', field: 'Importance' },+ channelSenderId: { target: 'chanf', field: 'Sender' },+ chatId: { target: 'cf', field: 'ChatId' },+ chatOwnerId: { target: 'cf', field: 'Owner' },+ chatProjectId: { target: 'cf', field: 'ProjectId' },+ chatSeen: { target: 'cf', field: 'NotificationSeen' },+ chatDone: { target: 'cf', field: 'NotificationDone' },+ folderId: { target: 'pf', field: 'ProjectId' },+ folderOwnerId: { target: 'pf', field: 'Owner' },+ folderSeen: { target: 'pf', field: 'NotificationSeen' },+ folderDone: { target: 'pf', field: 'NotificationDone' },+ callChannelId: { target: 'callf', field: 'ChannelId' },+ callSpeakerId: { target: 'callf', field: 'Speaker' },+ callAttended: { target: 'callf', field: 'Attended' },+};++const propertyToAst = (p: PropertyFilter): BackendAst =>+ p.type === 'select'+ ? { l: { pd: p.propertyId, v: { so: p.value } } }+ : { l: { pd: p.propertyId, v: { er: p.value } } };++const propertyEquals = (a: PropertyFilter, b: PropertyFilter): boolean =>+ a.propertyId === b.propertyId && a.type === b.type && a.value === b.value;++export function compileToAst(state: QueryState): TargetAstMap {+ const byTarget: Record<QueryTarget, BackendAst[]> = {+ df: [],+ ef: [],+ chanf: [],+ cf: [],+ pf: [],+ callf: [],+ propf: [],+ };++ for (const fieldName of Object.keys(FIELD_CONFIG) as CompiledFieldName[]) {+ const config = FIELD_CONFIG[fieldName];+ const includeVal = state.include[fieldName];+ const excludeVal = state.exclude[fieldName];++ const format = config.formatValue ?? ((v: unknown) => v);++ if (Array.isArray(includeVal) || Array.isArray(excludeVal)) {+ const includeVals = includeVal as unknown[] | undefined;+ const excludeVals = excludeVal as unknown[] | undefined;++ if (includeVals?.length) {+ byTarget[config.target].push(+ AST.or(includeVals.map((v) => AST.literal(config.field, format(v))))+ );+ }++ if (excludeVals?.length) {+ const filtered = includeVals?.length+ ? excludeVals.filter((v) => !includeVals.includes(v))+ : excludeVals;++ if (filtered.length > 0) {+ byTarget[config.target].push(+ AST.not(+ AST.or(filtered.map((v) => AST.literal(config.field, format(v))))+ )+ );+ }+ }+ } else {+ if (includeVal !== undefined) {+ byTarget[config.target].push(+ AST.literal(config.field, format(includeVal))+ );+ } else if (excludeVal !== undefined) {+ byTarget[config.target].push(+ AST.not(AST.literal(config.field, format(excludeVal)))+ );+ }+ }+ }++ const includeProps = state.include.properties ?? [];+ const excludeProps = state.exclude.properties ?? [];++ const groupByPropId = (props: PropertyFilter[]) => {+ const map = new Map<string, PropertyFilter[]>();+ for (const p of props) {+ const existing = map.get(p.propertyId);+ if (existing) {+ existing.push(p);+ } else {+ map.set(p.propertyId, [p]);+ }+ }+ return map;+ };++ const includeByPropId = groupByPropId(includeProps);+ const excludeByPropId = groupByPropId(excludeProps);++ const allPropIds = new Set([+ ...includeByPropId.keys(),+ ...excludeByPropId.keys(),+ ]);++ for (const propId of allPropIds) {+ const includeVals = includeByPropId.get(propId);+ const excludeVals = excludeByPropId.get(propId);++ if (includeVals?.length) {+ byTarget.propf.push(AST.or(includeVals.map(propertyToAst)));+ }++ if (excludeVals?.length) {+ const filtered = includeVals?.length+ ? excludeVals.filter(+ (ev) => !includeVals.some((iv) => propertyEquals(iv, ev))+ )+ : excludeVals;++ if (filtered.length > 0) {+ byTarget.propf.push(AST.not(AST.or(filtered.map(propertyToAst))));+ }+ }+ }++ const result: TargetAstMap = {};+ for (const [target, asts] of Object.entries(byTarget)) {+ if (asts.length > 0) {+ result[target as QueryTarget] = AST.and(asts);+ }+ }++ if (state.emailView) {+ result.emailView = state.emailView;+ }++ return result;+}++const ID_FIELD_NAMES: Partial<Record<QueryTarget, FieldName>> = {+ df: 'documentId',+ ef: 'threadId',+ chanf: 'channelId',+ cf: 'chatId',+ pf: 'folderId',+ callf: 'callChannelId',+};++type DefineQueryFiltersOptions = {+ skipTargets?: QueryTarget[];+};++export function defineQueryFilters(+ input: Query,+ options: DefineQueryFiltersOptions = {}+): Query {+ const { skipTargets = [] } = options;+ const referencedTargets = new Set<QueryTarget>(skipTargets);++ for (const field of Object.keys(input.include ?? {}) as CompiledFieldName[]) {+ if (field in FIELD_CONFIG) {+ referencedTargets.add(FIELD_CONFIG[field].target);+ }+ }++ for (const field of Object.keys(input.exclude ?? {}) as CompiledFieldName[]) {+ if (field in FIELD_CONFIG) {+ referencedTargets.add(FIELD_CONFIG[field].target);+ }+ }++ const include: FieldFilters = { ...input.include };++ for (const [target, idFieldName] of Object.entries(ID_FIELD_NAMES)) {+ if (referencedTargets.has(target as QueryTarget)) continue;+ if (idFieldName) {+ (include as Record<string, unknown[]>)[idFieldName] = [NIL_UUID];+ }+ }++ return { ...input, include };+}diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/field-values.ts b/js/app/packages/app/component/next-soup/filters/filter-store/field-values.tsnew file mode 100644index 0000000000..e58223fe40--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/filter-store/field-values.ts@@ -0,0 +1,70 @@+import { deepEqual } from '@core/util/compareUtils';+import type { FieldFilters, FieldName } from './types';++export const addFieldValues = (+ target: FieldFilters,+ source: FieldFilters | undefined+): FieldFilters => {+ if (!source) return target;++ const result: Record<string, unknown> = { ...target };++ for (const key of Object.keys(source) as FieldName[]) {+ const value = source[key];+ if (value === undefined) continue;++ if (!Array.isArray(value)) {+ result[key] = value;+ continue;+ }++ if (!value.length) continue;++ const existing = (target[key] ?? []) as unknown[];+ const updated = [...existing];++ for (const v of value) {+ if (!updated.some((e) => deepEqual(e, v))) updated.push(v);+ }++ result[key] = updated;+ }++ return result as FieldFilters;+};++export const removeFieldValues = (+ target: FieldFilters,+ source: FieldFilters | undefined+): FieldFilters => {+ if (!source) return target;++ const result: Record<string, unknown> = { ...target };++ for (const key of Object.keys(source) as FieldName[]) {+ const value = source[key];+ if (value === undefined) continue;++ if (!Array.isArray(value)) {+ if (target[key] === value) delete result[key];+ continue;+ }++ const existing = target[key] as unknown[];+ if (!value.length || !Array.isArray(existing)) continue;++ const toRemove = value as unknown[];+ const filtered = existing.filter(+ (e) => !toRemove.some((v) => deepEqual(e, v))+ );++ if (filtered.length === 0) {+ delete result[key];+ continue;+ }++ result[key] = filtered;+ }++ return result as FieldFilters;+};diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/index.ts b/js/app/packages/app/component/next-soup/filters/filter-store/index.tsnew file mode 100644index 0000000000..185a627b8a--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/filter-store/index.ts@@ -0,0 +1,5 @@+export type { PropertyFilter, QueryState, Query } from './types';++export { defineQueryFilters } from './compile';++export const NIL_UUID = '00000000-0000-0000-0000-000000000000';diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/predicates-store.ts b/js/app/packages/app/component/next-soup/filters/filter-store/predicates-store.tsnew file mode 100644index 0000000000..535d78687b--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/filter-store/predicates-store.ts@@ -0,0 +1,149 @@+import { createMemo, createSignal } from 'solid-js';++export type FilterPredicate<T> = (entity: T, ctx?: unknown) => boolean;++export type PredicateConfig<T, TId extends string = string> = {+ id: TId;+ predicate: FilterPredicate<T>;+ query?: unknown;+};++type IdInput<TId extends string> = TId | (string & {});++export type SetPredicatesInput<TId extends string> = {+ and?: readonly IdInput<TId>[];+ or?: readonly IdInput<TId>[];+};++export type CurrentPredicatesState<TId extends string> = {+ andIds: TId[];+ orIds: TId[];+};++export type SetPredicatesCallback<TId extends string> = (+ current: CurrentPredicatesState<TId>+) => SetPredicatesInput<TId>;++export type PredicatesStoreOptions<+ T,+ TConfig extends PredicateConfig<T>,+ TId extends string = TConfig['id'],+> = {+ configs: readonly TConfig[];+ initial?: {+ and?: TId[];+ or?: TId[];+ };+};++export function createPredicatesStore<+ T,+ TConfig extends PredicateConfig<T>,+ TId extends string = TConfig['id'],+>(options: PredicatesStoreOptions<T, TConfig, TId>) {+ const { configs, initial = {} } = options;++ const configMap = new Map<string, TConfig>(configs.map((c) => [c.id, c]));++ const validIds = (ids: readonly IdInput<TId>[] | undefined): TId[] =>+ (ids?.filter((id) => configMap.has(id)) as TId[]) ?? [];++ const [andIds, setAndIds] = createSignal<TId[]>(validIds(initial.and));+ const [orIds, setOrIds] = createSignal<TId[]>(validIds(initial.or));++ const activeIds = createMemo(() => [...andIds(), ...orIds()]);++ const activeConfigs = createMemo(() =>+ activeIds()+ .map((id) => configMap.get(id))+ .filter((c): c is TConfig => c !== undefined)+ );++ const getConfig = (id: IdInput<TId>): TConfig | undefined =>+ configMap.get(id);++ const isActive = (id: IdInput<TId>): boolean =>+ activeIds().includes(id as TId);++ const currentState = (): CurrentPredicatesState<TId> => ({+ andIds: andIds(),+ orIds: orIds(),+ });++ const set = (input: SetPredicatesInput<TId> | SetPredicatesCallback<TId>) => {+ const resolved =+ typeof input === 'function' ? input(currentState()) : input;++ setAndIds(validIds(resolved.and));+ setOrIds(validIds(resolved.or));+ };++ const toggleIds = (current: TId[], toToggle: TId[]): TId[] => {+ let result = [...current];++ for (const id of toToggle) {+ if (result.includes(id)) {+ result = result.filter((i) => i !== id);+ } else {+ result.push(id);+ }+ }++ return result;+ };++ const toggle = (+ input: SetPredicatesInput<TId> | SetPredicatesCallback<TId>+ ) => {+ const resolved =+ typeof input === 'function' ? input(currentState()) : input;++ setAndIds((prev) => toggleIds([...prev], validIds(resolved.and)));+ setOrIds((prev) => toggleIds([...prev], validIds(resolved.or)));+ };++ const clear = () => {+ setAndIds([]);+ setOrIds([]);+ };++ const test = (entity: T, ctx?: unknown): boolean => {+ const andList = andIds();+ const orList = orIds();++ if (andList.length === 0 && orList.length === 0) return true;++ for (const id of andList) {+ const config = configMap.get(id);+ if (config && !config.predicate(entity, ctx)) return false;+ }++ if (orList.length > 0) {+ let anyMatch = false;+ for (const id of orList) {+ const config = configMap.get(id);+ if (config?.predicate(entity, ctx)) {+ anyMatch = true;+ break;+ }+ }+ if (!anyMatch) return false;+ }++ return true;+ };++ return {+ andIds,+ orIds,+ activeIds,+ activeConfigs,+ isActive,+ toggle,+ clear,+ set,+ getConfig,+ available: configs,+ test,+ };+}diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/query-store.ts b/js/app/packages/app/component/next-soup/filters/filter-store/query-store.tsnew file mode 100644index 0000000000..bd3c6000f3--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/filter-store/query-store.ts@@ -0,0 +1,104 @@+import { batch } from 'solid-js';+import { createStore } from 'solid-js/store';+import { compileToAst, type TargetAstMap } from './compile';+import { addFieldValues, removeFieldValues } from './field-values';+import type { FieldFilters, QueryState, Query } from './types';++export type { TargetAstMap } from './compile';+export type { FieldFilters, QueryState, Query, EmailView } from './types';++export type QueryStoreOptions = {+ readonly initial?: Query;+};++const emptyQueryState = (): QueryState => ({+ include: {},+ exclude: {},+ emailView: undefined,+});++const mergeFields = (+ prev: FieldFilters,+ updates: FieldFilters | undefined+): FieldFilters => {+ if (!updates) return prev;+ const result: Record<string, unknown> = { ...prev };+ for (const [key, value] of Object.entries(updates)) {+ if (value === undefined || (Array.isArray(value) && value.length === 0)) {+ delete result[key];+ } else {+ result[key] = value;+ }+ }+ return result as FieldFilters;+};++const mergeQuery = (base: QueryState, query: Query): QueryState => ({+ include: addFieldValues(base.include, query.include),+ exclude: addFieldValues(base.exclude, query.exclude),+ emailView: query.emailView ?? base.emailView,+});++export function createQueryStore(options: QueryStoreOptions = {}) {+ const { initial } = options;++ const [state, setState] = createStore<QueryState>(+ initial ? mergeQuery(emptyQueryState(), initial) : emptyQueryState()+ );++ const add = (query: Query | undefined) => {+ if (!query) return;+ setState((prev) => mergeQuery(prev, query));+ };++ const remove = (query: Query | undefined) => {+ if (!query) return;+ setState((prev) => ({+ include: removeFieldValues(prev.include, query.include),+ exclude: removeFieldValues(prev.exclude, query.exclude),+ emailView:+ query.emailView && prev.emailView === query.emailView+ ? undefined+ : prev.emailView,+ }));+ };++ const replace = (query: Query | null) => {+ if (query === null) {+ setState(emptyQueryState());+ return;+ }+ setState({+ include: mergeFields({}, query.include),+ exclude: mergeFields({}, query.exclude),+ emailView: query.emailView,+ });+ };++ const set = (query: Query) => {+ batch(() => {+ if (query.include) {+ setState('include', (prev) => mergeFields(prev, query.include));+ }+ if (query.exclude) {+ setState('exclude', (prev) => mergeFields(prev, query.exclude));+ }+ if (query.emailView !== undefined) {+ setState('emailView', query.emailView);+ }+ });+ };++ const compile = (): TargetAstMap => compileToAst(state);++ return {+ state,+ set,+ replace,+ add,+ remove,+ compile,+ };+}++export type QueryStore = ReturnType<typeof createQueryStore>;diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/types.ts b/js/app/packages/app/component/next-soup/filters/filter-store/types.tsnew file mode 100644index 0000000000..2345343b03--- /dev/null+++ b/js/app/packages/app/component/next-soup/filters/filter-store/types.ts@@ -0,0 +1,93 @@+export type EmailView = 'inbox' | 'drafts' | 'sent' | 'all';++export type PropertyFilter = {+ propertyId: string;+ type: 'select' | 'entity';+ value: string;+};++export type ArrayFieldFilters = {+ documentId?: string[];+ fileType?: string[];+ fileAssoc?: string[];+ subType?: string[];+ projectId?: string[];+ documentOwnerId?: string[];+ threadId?: string[];+ emailProjectId?: string[];+ emailSender?: string[];+ channelId?: string[];+ channelType?: string[];+ channelSenderId?: string[];+ chatId?: string[];+ chatOwnerId?: string[];+ chatProjectId?: string[];+ folderId?: string[];+ folderOwnerId?: string[];+ callChannelId?: string[];+ callSpeakerId?: string[];+ properties?: PropertyFilter[];+};++export type ScalarFieldFilters = {+ documentSeen?: boolean;+ documentDone?: boolean;+ isEmailAttachment?: boolean;+ emailSeen?: boolean;+ emailDone?: boolean;+ emailImportance?: boolean;+ emailShared?: 'exclude' | 'include' | 'only';+ emailCalendarOnly?: boolean;+ channelSeen?: boolean;+ channelDone?: boolean;+ channelImportance?: boolean;+ chatSeen?: boolean;+ chatDone?: boolean;+ folderSeen?: boolean;+ folderDone?: boolean;+ callAttended?: boolean;+};++export type FieldFilters = ArrayFieldFilters & ScalarFieldFilters;++export type FieldName = keyof FieldFilters;++export type QueryState = {+ include: FieldFilters;+ exclude: FieldFilters;+ emailView?: EmailView;+};++export type Query = {+ include?: FieldFilters;+ exclude?: FieldFilters;+ emailView?: EmailView;+};++export type FilterPredicate<T> = (entity: T, ctx?: unknown) => boolean;++export type FilterConfig<T, TId extends string = string> = {+ readonly id: TId;+ readonly predicate: FilterPredicate<T>;+ readonly query?: Query | ((ctx: unknown) => Query);+};++export type FilterStoreOptions<+ T,+ TFilter extends FilterConfig<T>,+ TId extends string = TFilter['id'],+> = {+ readonly filters: readonly TFilter[];+ readonly initialFilters?: {+ readonly and?: readonly TId[];+ readonly or?: readonly TId[];+ };+ readonly initialQuery?: Query;+};++export type FilterIdInput<TId extends string> = TId | (string & {});++export type SetFiltersInput<TId extends string> = {+ readonly and?: readonly FilterIdInput<TId>[];+ readonly or?: readonly FilterIdInput<TId>[];+};diff --git a/js/app/packages/app/component/next-soup/filters/index.ts b/js/app/packages/app/component/next-soup/filters/index.tsindex f620e6bddc..025aed009c 100644--- a/js/app/packages/app/component/next-soup/filters/index.ts+++ b/js/app/packages/app/component/next-soup/filters/index.ts@@ -5,20 +5,15 @@ export {} from './inbox-filters';export {- createFilterState,- type FilterState,- type FilterStateOptions,- type SetFiltersInput,- type SetFiltersCallback,- type CurrentFilterState,- type FilterConfig,- type FilterGroupConfig,- type FilterPredicate,-} from './create-filter-state';--export {- createSoupFilters,+ SOUP_FILTERS,SOUP_FILTER_GROUPS,- ENTITY_TYPE_FILTER_CONFIGS,+ ENTITY_TYPE_FILTERS,+ TASK_STATUS_FILTERS,+ TASK_PRIORITY_FILTERS,+ NO_ASSIGNEE,+ assigneeFilter,+ assignedToMeFilter,type FilterID,-} from './configs';+ type FilterDefinition,+ type FilterContext,+} from './configs/index';diff --git a/js/app/packages/app/component/next-soup/filters/query-filters.ts b/js/app/packages/app/component/next-soup/filters/query-filters.tsindex 6cb836694b..e95bed4814 100644--- a/js/app/packages/app/component/next-soup/filters/query-filters.ts+++ b/js/app/packages/app/component/next-soup/filters/query-filters.ts@@ -1,5 +1,4 @@import type { SoupItemsQueryFilters, SoupBody } from '@queries/soup/items';-import { ChannelTypeEnum } from '@service-comms/client';import type { SoupApiItem } from '@service-storage/generated/schemas';import { match } from 'ts-pattern';@@ -81,119 +80,3 @@ export function filterSoupItemByRequestBody().exhaustive();}--/** File types or associations for soup */-export const getFileAssociations = () => {- return ['assoc:code', 'assoc:image', 'assoc:other', 'pdf'];-};--export const QUERY_FILTERS = {- document: {- channel_filters: { channel_ids: EXCLUDE },- chat_filters: { chat_ids: EXCLUDE },- email_filters: { email_thread_ids: EXCLUDE },- project_filters: { project_ids: EXCLUDE },- call_filters: { channel_ids: EXCLUDE },- document_filters: { file_types: ['md', 'canvas'] },- },-- task: {- channel_filters: { channel_ids: EXCLUDE },- chat_filters: { chat_ids: EXCLUDE },- email_filters: { email_thread_ids: EXCLUDE },- project_filters: { project_ids: EXCLUDE },- call_filters: { channel_ids: EXCLUDE },- document_filters: { sub_types: ['task'] },- },-- email: {- channel_filters: { channel_ids: EXCLUDE },- chat_filters: { chat_ids: EXCLUDE },- document_filters: { document_ids: EXCLUDE },- project_filters: { project_ids: EXCLUDE },- call_filters: { channel_ids: EXCLUDE },- email_filters: { importance: true },- },-- people: {- chat_filters: { chat_ids: EXCLUDE },- document_filters: { document_ids: EXCLUDE },- email_filters: { email_thread_ids: EXCLUDE },- project_filters: { project_ids: EXCLUDE },- call_filters: { channel_ids: EXCLUDE },- channel_filters: { channel_types: [ChannelTypeEnum.DirectMessage] },- },-- teams: {- chat_filters: { chat_ids: EXCLUDE },- document_filters: { document_ids: EXCLUDE },- email_filters: { email_thread_ids: EXCLUDE },- project_filters: { project_ids: EXCLUDE },- call_filters: { channel_ids: EXCLUDE },- channel_filters: {- channel_types: [- ChannelTypeEnum.Private,- ChannelTypeEnum.Organization,- ChannelTypeEnum.Public,- ],- },- },-- agent: {- channel_filters: { channel_ids: EXCLUDE },- document_filters: { document_ids: EXCLUDE },- email_filters: { email_thread_ids: EXCLUDE },- project_filters: { project_ids: EXCLUDE },- call_filters: { channel_ids: EXCLUDE },- chat_filters: {},- },-- file: {- channel_filters: { channel_ids: EXCLUDE },- chat_filters: { chat_ids: EXCLUDE },- email_filters: { email_thread_ids: EXCLUDE },- project_filters: { project_ids: EXCLUDE },- call_filters: { channel_ids: EXCLUDE },- document_filters: { file_types: getFileAssociations() },- },-- documentAndFile: {- channel_filters: { channel_ids: EXCLUDE },- chat_filters: { chat_ids: EXCLUDE },- email_filters: { email_thread_ids: EXCLUDE },- project_filters: { project_ids: EXCLUDE },- call_filters: { channel_ids: EXCLUDE },- document_filters: {- file_types: ['md', 'canvas', 'docx', ...getFileAssociations()],- },- },-- channels: {- chat_filters: { chat_ids: EXCLUDE },- document_filters: { document_ids: EXCLUDE },- email_filters: { email_thread_ids: EXCLUDE },- project_filters: { project_ids: EXCLUDE },- call_filters: { channel_ids: EXCLUDE },- channel_filters: {},- },-- calls: {- chat_filters: { chat_ids: EXCLUDE },- document_filters: { document_ids: EXCLUDE },- email_filters: { email_thread_ids: EXCLUDE },- project_filters: { project_ids: EXCLUDE },- channel_filters: { channel_ids: EXCLUDE },- call_filters: {},- },-- folders: {- channel_filters: { channel_ids: EXCLUDE },- chat_filters: { chat_ids: EXCLUDE },- email_filters: { email_thread_ids: EXCLUDE },- document_filters: { document_ids: EXCLUDE },- call_filters: { channel_ids: EXCLUDE },- project_filters: {},- },-- default: {},-} satisfies Record<string, SoupItemsQueryFilters>;diff --git a/js/app/packages/app/component/next-soup/search-utils.ts b/js/app/packages/app/component/next-soup/search-utils.tsindex f45776b673..eaa382f341 100644--- a/js/app/packages/app/component/next-soup/search-utils.ts+++ b/js/app/packages/app/component/next-soup/search-utils.ts@@ -2,11 +2,11 @@ import { fuzzyMatch } from '@core/util/fuzzy';import { mergeAdjacentMacroEmTags } from '@core/util/searchHighlight';import { createFreshSearch } from '@core/util/freshSort';import type { EntityData, WithSearch } from '@entity';-import type { FilterConfig } from './filters/create-filter-state';+import type { PredicateConfig } from './filters/filter-store/predicates-store';import type { SearchPoolItem } from './search-context';export const getValidSearchFilters = <T>(- filters: readonly FilterConfig<T>[]+ filters: readonly PredicateConfig<T>[]) => {return filters.filter((f) => f.id !== 'explicit-noise');};diff --git a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts b/js/app/packages/app/component/next-soup/soup-view/create-search-state.tsindex 043ec67748..d886bf24f1 100644--- a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts+++ b/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts@@ -1,22 +1,103 @@+import { useGlobalNotificationSource } from '@app/component/GlobalAppState';import type { SoupState } from '@app/component/next-soup/create-soup-state';+import type { FilterContext } from '@app/component/next-soup/filters/configs/base';+import type { QueryState } from '@app/component/next-soup/filters/filter-store';import { useSearchContext } from '@app/component/next-soup/search-context';import {createSoupFreshSearch,- getValidSearchFilters,intersectEntityPools,nameFuzzySearchFilter,} from '@app/component/next-soup/search-utils';import { arrayEquals } from '@core/util/compareUtils';+import { useUserId } from '@core/context/user';import { debouncedDependent } from '@core/util/debounce';import { isChannelEntity, type EntityData } from '@entity';-import type { SoupItemsQueryFilters } from '@queries/soup/items';import {useSearchSoupQuery,validateSearchServiceText,} from '@queries/soup/search';+import type { EntityFilters } from '@service-search/generated/models';import type { UnifiedSearchRequest } from '@service-search/generated/models';import { type Accessor, createMemo, createSignal, on } from 'solid-js';+function filterDataToQueryFilters(data: QueryState): EntityFilters {+ const filters: EntityFilters = {};+ const { include } = data;++ // Document filters+ if (+ include.documentId?.length ||+ include.fileType?.length ||+ include.subType?.length ||+ include.projectId?.length ||+ include.documentOwnerId?.length+ ) {+ filters.document_filters = {+ document_ids: include.documentId,+ file_types: include.fileType,+ sub_types: include.subType,+ project_ids: include.projectId,+ owners: include.documentOwnerId,+ };+ }++ // Email filters+ if (+ include.threadId?.length ||+ include.emailSender?.length ||+ include.emailShared+ ) {+ filters.email_filters = {+ email_thread_ids: include.threadId,+ senders: include.emailSender,+ shared: include.emailShared,+ };+ }++ // Channel filters+ if (+ include.channelId?.length ||+ include.channelType?.length ||+ include.channelSenderId?.length+ ) {+ filters.channel_filters = {+ channel_ids: include.channelId,+ channel_types: include.channelType,+ sender_ids: include.channelSenderId,+ };+ }++ // Chat filters+ if (+ include.chatId?.length ||+ include.chatOwnerId?.length ||+ include.chatProjectId?.length+ ) {+ filters.chat_filters = {+ chat_ids: include.chatId,+ owners: include.chatOwnerId,+ project_ids: include.chatProjectId,+ };+ }++ // Project/folder filters+ if (include.folderId?.length || include.folderOwnerId?.length) {+ filters.project_filters = {+ project_ids: include.folderId,+ owners: include.folderOwnerId,+ };+ }++ // Call filters+ if (include.callChannelId?.length) {+ filters.call_filters = {+ channel_ids: include.callChannelId,+ };+ }++ return filters;+}+const SEARCH_SERVICE_DEBOUNCE_MS = 300;const LOCAL_FUZZY_SEARCH_DEBOUNCE_MS = 20;// Max number of non-channel local results to feature. Channels bypass this@@ -27,7 +108,8 @@ const freshSearch = createSoupFreshSearch();interface CreateSearchStateArgs {soup: SoupState;- queryFilters: Accessor<SoupItemsQueryFilters>;+ filters: Accessor<QueryState>;+ assignees: Accessor<string[]>;disableLocalSearch?: boolean;searchPaused?: Accessor<boolean>;searchMentions?: Accessor<string[]>;@@ -35,13 +117,23 @@ interface CreateSearchStateArgs {export const createSearchState = ({soup,- queryFilters,+ filters,+ assignees,disableLocalSearch,searchPaused,searchMentions,}: CreateSearchStateArgs) => {const [searchText, setSearchText] = createSignal('');+ const notificationSource = useGlobalNotificationSource();+ const userId = useUserId();++ const getFilterContext = (): FilterContext => ({+ userId: userId(),+ notificationSource,+ assignees: assignees(),+ });+const trimmedSearchText = createMemo(() => searchText().trim());const debouncedSearchForLocal = debouncedDependent(@@ -66,26 +158,28 @@ export const createSearchState = ({const searchUnifiedNameContentRequest = createMemo((): UnifiedSearchRequest => {- const filters = queryFilters();const query = debouncedSearchForService();const mentionIds =isSearchServiceDebounceSettled() && !isSearchServiceDisabled()? searchMentions?.(): undefined;++ // Translate FilterData to legacy EntityFilters format for search service+ const baseFilters = filterDataToQueryFilters(filters());++ // Merge mention filters into channel_filters if present+ if (mentionIds && mentionIds.length > 0) {+ baseFilters.channel_filters = {+ ...baseFilters.channel_filters,+ mentions: mentionIds,+ };+ }+return {search_on: 'name_content',match_type: 'partial',query,- filters:- mentionIds && mentionIds.length > 0- ? {- ...filters,- channel_filters: {- ...filters.channel_filters,- mentions: mentionIds,- },- }- : filters,+ filters: baseFilters,};});@@ -129,12 +223,12 @@ export const createSearchState = ({const allFiltersResults = createMemo((): Map<string, EntityData[]> => {if (!localFuzzyResults()) return new Map();- const allFilters = getValidSearchFilters(soup.filters.available);const filterToResultMap = new Map<string, EntityData[]>();- for (const filter of allFilters) {+ const ctx = getFilterContext();+ for (const filter of soup.predicates.available) {filterToResultMap.set(filter.id,- localFuzzyResults().filter((e) => filter.predicate(e))+ localFuzzyResults().filter((e) => filter.predicate(e, ctx)));}return filterToResultMap;@@ -142,19 +236,23 @@ export const createSearchState = ({// we will hide local results if there are channel filters because we only want message resultsconst hasChannelQueryFilters = () => {- const cf = queryFilters().channel_filters;- return !!(cf?.channel_ids?.length || cf?.sender_ids?.length);+ const filters_ = filters().include;+ const channelIds = filters_.channelId ?? [];+ const senderIds = filters_.channelSenderId ?? [];+ return channelIds.length > 0 || senderIds.length > 0;};const filteredLocalFuzzyResults = createMemo(() => {if (!localFuzzyResults()) return [];if (hasChannelQueryFilters()) return [];- const activeFilters = getValidSearchFilters(soup.filters.active());+ const activeIds = soup.predicates+ .activeIds()+ .filter((id) => id !== 'explicit-noise');const results =- activeFilters.length === 0+ activeIds.length === 0? localFuzzyResults(): intersectEntityPools(- activeFilters.map((f) => allFiltersResults().get(f.id) ?? [])+ activeIds.map((id) => allFiltersResults().get(id) ?? []));const channels = results.filter((e) => isChannelEntity(e));const nonChannels = resultsdiff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/filter-primitives.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/filter-primitives.tsxdeleted file mode 100644index ba60e708a3..0000000000--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/filter-primitives.tsx+++ /dev/null@@ -1,456 +0,0 @@-import ChevronDownIcon from '@icon/regular/caret-down.svg';-import CheckIcon from '@icon/regular/check.svg';-import SearchIcon from '@icon/regular/magnifying-glass.svg';-import { Combobox } from '@kobalte/core/combobox';-import { Select as KSelect } from '@kobalte/core/select';-import { cn } from '@ui/utils/classname';-import { Button } from '@app/component/next-soup/soup-view/filters-bar/button';-import { Tooltip } from '@core/component/Tooltip';-import { createMemo, createSignal, For, type JSX, Show } from 'solid-js';-import type { CollectionNode } from '@kobalte/core';-import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';--export type Option = {- value: string;- label: string;- icon?: () => JSX.Element;-};--interface FilterSelectProps {- label: string;- options: Option[];- active: Option[];- onChange: (options: Option[]) => void;- multiple?: boolean;- open?: boolean;- onOpenChange?: (open: boolean) => void;- tooltip?: JSX.Element;- hideClear?: boolean;- accentActive?: boolean;-}--export const FilterSelect = (props: FilterSelectProps) => {- const multiple = () => props.multiple ?? true;-- const activeFilters = createMemo(() => props.active);- const activeCount = createMemo(() => activeFilters().length);- const hasActiveFilters = createMemo(() =>- props.accentActive !== undefined ? props.accentActive : activeCount() > 0- );-- const renderItem = (itemProps: { item: CollectionNode<Option> }) => (- <KSelect.Item- item={itemProps.item}- class="w-full flex items-center gap-2.5 p-2 rounded-xs text-left text-xs hover:bg-ink/5 group"- >- <span- class={cn(- 'size-4 flex items-center justify-center shrink-0 border border-edge-muted group-data-selected:bg-accent group-data-selected:border-accent',- multiple() ? 'rounded-xs' : 'rounded-full'- )}- >- <KSelect.ItemIndicator>- <CheckIcon class="size-2.5 text-page" />- </KSelect.ItemIndicator>- </span>-- <Show when={itemProps.item.rawValue.icon}>- {(icon) => (- <span class="size-4 flex items-center justify-center shrink-0">- {icon()()}- </span>- )}- </Show>-- <KSelect.ItemLabel class="flex-1 truncate text-ink-muted group-data-selected:text-ink">- {itemProps.item.rawValue.label}- </KSelect.ItemLabel>- </KSelect.Item>- );-- // For single select: convert to/from array format- const value = () =>- multiple() ? activeFilters() : (activeFilters()[0] ?? null);- const handleChange = (selected: Option | Option[] | null) => {- if (multiple()) {- props.onChange(selected as Option[]);- } else {- if (!selected) return;- props.onChange([selected as Option]);- }- };-- const triggerContent = () => (- <>- <span class="font-medium">{props.label}</span>- <Show when={multiple() && hasActiveFilters()}>- <span class="absolute -top-2 -right-2 flex items-center justify-center size-4 z-user-highlight rounded-full text-xs font-semibold bg-accent text-page">- {activeCount()}- </span>- </Show>- <ChevronDownIcon class="size-3" />- </>- );-- const triggerClass = () =>- cn(- 'relative transition-none rounded-xs h-full',- hasActiveFilters() &&- 'bg-accent/15 text-accent border border-accent/30 hover:bg-accent/25'- );-- return (- <KSelect<Option>- options={props.options}- value={value() as Option & Option[]}- onChange={handleChange as (value: Option & Option[]) => void}- open={props.open}- onOpenChange={props.onOpenChange}- optionTextValue="label"- optionValue="value"- gutter={4}- multiple={multiple()}- placement="bottom-start"- itemComponent={renderItem}- >- <Show- when={props.tooltip}- fallback={- <KSelect.Trigger- as={Button}- variant="secondary"- size="sm"- class={triggerClass()}- >- {triggerContent()}- </KSelect.Trigger>- }- >- {(tooltip) => (- <Tooltip tooltip={tooltip()}>- <KSelect.Trigger- as={Button}- variant="secondary"- size="sm"- class={triggerClass()}- >- {triggerContent()}- </KSelect.Trigger>- </Tooltip>- )}- </Show>- <KSelect.Portal>- <KSelect.Content class="z-action-menu bg-surface-0 border border-edge-muted rounded-sm shadow min-w-(--kb-popper-anchor-width) p-1">- <KSelect.Listbox />- <Show when={!props.hideClear}>- <div class="w-full pt-1 mt-1 flex items-center border-t border-t-edge-muted">- <Button- variant="ghost"- size="sm"- class="ml-auto rounded-xs w-full"- onClick={() => props.onChange([])}- >- Clear- </Button>- </div>- </Show>- </KSelect.Content>- </KSelect.Portal>- </KSelect>- );-};--interface FilterComboboxProps {- label: string;- options: Option[];- active: Option[];- onChange: (options: Option[]) => void;- placeholder?: string;- virtualized?: boolean;- estimatedItemHeight?: number;-}--const COMBOBOX_ITEM_HEIGHT = 36;--const ComboboxItem = (itemProps: { item: CollectionNode<Option> }) => (- <Combobox.Item- item={itemProps.item}- class="w-full flex items-center gap-2.5 px-3 py-2 rounded-xs text-left text-xs data-highlighted:bg-ink/5 group"- >- <span class="size-4 flex items-center justify-center shrink-0 rounded-xs border border-edge group-data-selected:bg-accent group-data-selected:border-accent">- <Combobox.ItemIndicator>- <CheckIcon class="size-2.5 text-page" />- </Combobox.ItemIndicator>- </span>-- <Show when={itemProps.item.rawValue.icon}>- {(icon) => (- <span class="size-4 flex items-center justify-center shrink-0">- {icon()()}- </span>- )}- </Show>-- <Combobox.ItemLabel class="flex-1 truncate text-ink-muted group-data-selected:text-ink">- {itemProps.item.rawValue.label}- </Combobox.ItemLabel>- </Combobox.Item>-);--interface VirtualizedListboxProps {- options: Option[];- estimatedItemHeight: number;- setListboxRef: (el: HTMLElement | undefined) => void;-}--const VirtualizedListbox = (props: VirtualizedListboxProps) => {- let virtualizerHandle: VirtualizerHandle | undefined;-- return (- <Combobox.Listbox<Option>- ref={props.setListboxRef}- scrollToItem={(key) => {- const index = props.options.findIndex((opt) => opt.value === key);- if (index !== -1) {- virtualizerHandle?.scrollToIndex(index, { align: 'nearest' });- }- }}- class="max-h-[200px] overflow-y-auto"- >- {(items) => (- <Virtualizer- ref={(handle) => {- virtualizerHandle = handle;- }}- data={[...items()]}- itemSize={props.estimatedItemHeight}- >- {(item) => <ComboboxItem item={item} />}- </Virtualizer>- )}- </Combobox.Listbox>- );-};--export const FilterCombobox = (props: FilterComboboxProps) => {- const [searchQuery, setSearchQuery] = createSignal('');- const [listboxRef, setListboxRef] = createSignal<HTMLElement | undefined>();-- const virtualized = () => props.virtualized ?? false;- const estimatedItemHeight = () =>- props.estimatedItemHeight ?? COMBOBOX_ITEM_HEIGHT;-- const activeFilters = createMemo(() => props.active);- const activeCount = createMemo(() => activeFilters().length);- const hasActiveFilters = createMemo(() => activeCount() > 0);-- const filteredOptions = createMemo(() => {- const query = searchQuery().toLowerCase().trim();- if (!query) return props.options;- return props.options.filter((opt) =>- opt.label.toLowerCase().includes(query)- );- });-- const dispatchKeyToListbox = (key: string) => {- listboxRef()?.dispatchEvent(- new KeyboardEvent('keydown', { bubbles: true, key })- );- };-- const handleKeyDown = (e: KeyboardEvent) => {- switch (e.key) {- case 'j': {- if (!e.ctrlKey) return;- e.preventDefault();- dispatchKeyToListbox('ArrowDown');- break;- }- case 'k': {- if (!e.ctrlKey) return;- e.preventDefault();- dispatchKeyToListbox('ArrowUp');- break;- }- }- };-- const onInputChange = (value: string) => {- setSearchQuery(value);- queueMicrotask(() => {- dispatchKeyToListbox('ArrowDown');- });- };-- const onOpenChange = (open: boolean) => {- if (!open) {- setSearchQuery('');- }- };-- return (- <Combobox<Option>- class="max-h-full"- multiple- options={filteredOptions()}- value={activeFilters()}- onChange={props.onChange}- onOpenChange={onOpenChange}- onInputChange={onInputChange}- optionValue="value"- optionTextValue="label"- optionLabel="label"- allowsEmptyCollection- placement="bottom-start"- gutter={4}- virtualized={virtualized()}- itemComponent={virtualized() ? undefined : ComboboxItem}- >- <Combobox.Control class="flex h-full">- <Combobox.Trigger- as={Button}- variant="secondary"- size="sm"- class={cn(- 'relative transition-none rounded-xs h-full',- hasActiveFilters() &&- 'bg-accent/15 text-accent border border-accent/30 hover:bg-accent/25'- )}- >- <span class="font-medium">{props.label}</span>- <Show when={hasActiveFilters()}>- <span class="absolute -top-2 -right-2 flex items-center justify-center size-4 z-user-highlight rounded-full text-xs font-semibold bg-accent text-page">- {activeCount()}- </span>- </Show>- <ChevronDownIcon class="size-3" />- </Combobox.Trigger>- <Combobox.Input class="sr-only" />- </Combobox.Control>-- <Combobox.Portal>- <Combobox.Content- class="z-action-menu bg-surface-0 border border-edge-muted rounded-sm shadow-md min-w-[220px] overflow-hidden"- on:keydown={handleKeyDown}- >- <div class="flex items-center gap-2 px-3 py-2 border-b border-edge-muted">- <SearchIcon class="size-3.5 text-ink-muted shrink-0" />- <Combobox.Input- class="flex-1 text-xs bg-transparent outline-none caret-accent placeholder:text-ink-faint"- placeholder={- props.placeholder ?? `Search ${props.label.toLowerCase()}...`- }- />- </div>-- <div class="p-1">- <Show- when={filteredOptions().length > 0}- fallback={- <div class="py-3 px-2 text-center text-xs text-ink-muted whitespace-break-spaces wrap-break-word">- No options match "{searchQuery()}"- </div>- }- >- <Show- when={virtualized()}- fallback={- <Combobox.Listbox- ref={setListboxRef}- class="max-h-[200px] overflow-y-auto"- />- }- >- <VirtualizedListbox- options={filteredOptions()}- estimatedItemHeight={estimatedItemHeight()}- setListboxRef={setListboxRef}- />- </Show>- </Show>- </div>-- <Show when={hasActiveFilters()}>- <div class="w-full pt-1 px-1 pb-1 flex items-center border-t border-t-edge-muted">- <Button- variant="ghost"- size="sm"- class="ml-auto rounded-xs w-full"- onClick={() => props.onChange([])}- >- Clear- </Button>- </div>- </Show>- </Combobox.Content>- </Combobox.Portal>- </Combobox>- );-};--interface FilterChipGroupProps {- options: Option[];- active: Option[];- onChange: (options: Option[]) => void;- multiple?: boolean;-}--export const FilterChipGroup = (props: FilterChipGroupProps) => {- const multiple = () => props.multiple ?? true;-- const activeSet = createMemo(() => new Set(props.active.map((o) => o.value)));-- const isActive = (value: string) => activeSet().has(value);-- const handleClick = (option: Option) => {- const currentlyActive = isActive(option.value);-- if (!multiple()) {- props.onChange(currentlyActive ? [] : [option]);- return;- }-- if (currentlyActive) {- props.onChange(props.active.filter((o) => o.value !== option.value));- } else {- props.onChange([...props.active, option]);- }- };-- return (- <div class="flex items-center gap-1 flex-wrap">- <For each={props.options}>- {(option) => (- <button- type="button"- class={cn(- 'flex items-center gap-1.5 px-3 py-1 text-xs rounded-xs h-full border',- isActive(option.value)- ? 'bg-accent/6 text-accent border-accent/30 hover:bg-accent/25'- : 'bg-ink/3 text-ink border-edge-muted/50 hover:bg-ink/12 hover:text-ink'- )}- onClick={() => handleClick(option)}- >- <Show- when={option.icon}- fallback={- <Show when={isActive(option.value)}>- <CheckIcon class="size-3.5 shrink-0" />- </Show>- }- >- {(icon) => (- <span class="size-3.5 flex items-center justify-center shrink-0">- <Show when={isActive(option.value)} fallback={icon()()}>- <CheckIcon class="size-3.5" />- </Show>- </span>- )}- </Show>- <span class="font-medium">{option.label}</span>- </button>- )}- </For>- </div>- );-};diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsxindex 92739fdda7..2ba6f0e2cf 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx@@ -25,7 +25,6 @@ import type { ListView } from '@app/constants/list-views';import { isListViewID } from '@app/constants/list-views';import { useContacts } from '@queries/contacts/contacts';import { useUserId } from '@core/context/user';-import { NO_ASSIGNEE } from '@app/component/next-soup/soup-view/task-sub-filter-matcher';import { UserIcon } from '@core/component/UserIcon';import {DEFAULT_SORT_OPTIONS,@@ -36,6 +35,10 @@ import {type SystemSortOption,type SortOption,} from '@app/component/next-soup/soup-view/sort-options';+import {+ NO_ASSIGNEE,+ type FilterContext,+} from '@app/component/next-soup/filters';function scrollAccordionItemToTop(e: MouseEvent,@@ -66,7 +69,8 @@ export const MobileFilterDrawer = () => {isOptionActive,} = useFilterRefinements();- const { soup, assigneeFilter, setAssigneeFilter } = useSoupView();+ const { soup, queryFilters, assigneeFilter, setAssigneeFilter } =+ useSoupView();const panel = useSplitPanelOrThrow();const contacts = useContacts();const userId = useUserId();@@ -113,7 +117,24 @@ export const MobileFilterDrawer = () => {categories().length > 0 || isTasksView() || sortOptions().length > 0;const toggleFilter = (optionId: FilterOption['id']) => {- soup.filters.toggle({ or: [optionId] });+ const wasActive = soup.predicates.isActive(optionId);+ soup.predicates.toggle({ or: [optionId] });++ const filter = soup.predicates.getConfig(optionId);+ if (!filter?.query) return;++ const ctx: FilterContext = {+ userId: userId(),+ assignees: assigneeFilter(),+ };+ const query =+ typeof filter.query === 'function' ? filter.query(ctx) : filter.query;++ if (wasActive) {+ queryFilters.remove(query);+ } else {+ queryFilters.add(query);+ }};const toggleAssignee = (id: string) => {@@ -287,7 +308,7 @@ export const MobileFilterDrawer = () => {const activeCount = createMemo(() =>category.options.filter((o) =>- soup.filters.isActive(o.id)+ soup.predicates.isActive(o.id)).length);return (@@ -320,7 +341,7 @@ export const MobileFilterDrawer = () => {<For each={category.options}>{(option) => {const active = () =>- soup.filters.isActive(option.id);+ soup.predicates.isActive(option.id);return (<buttontype="button"diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/search-filter-controls.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/search-filter-controls.tsxindex d036999049..daefeb9cea 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/search-filter-controls.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/search-filter-controls.tsx@@ -3,7 +3,6 @@ import { EntityIcon as EntityIconWithAvatar } from '@entity/extractors/entity-icimport { UserIcon } from '@core/component/UserIcon';import { useQuickAccess } from '@core/context/quickAccess';import { useUserId } from '@core/context/user';-import { QUERY_FILTERS } from '@app/component/next-soup/filters/query-filters';import type { FilterID } from '@app/component/next-soup/filters/configs';import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-context';import {@@ -11,7 +10,11 @@ import {activeSoupViewCounts,} from '@app/component/next-soup/soup-view/soup-view-cache-key';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';-import type { SoupBody } from '@queries/soup/items';+import {+ NIL_UUID,+ defineQueryFilters,+ type Query,+} from '@app/component/next-soup/filters/filter-store';import {type Accessor,batch,@@ -19,7 +22,6 @@ import {createMemo,type JSX,} from 'solid-js';-import type { Option } from './filter-primitives';import type {ChannelFilters,EmailFilters,@@ -221,27 +223,16 @@ type SearchFilterHookOpts = {/** Channel-message search filters (in:, from:). */export function useChannelSearchFilter(opts: SearchFilterHookOpts) {- const { soup, queryFilters, setQueryFilters } = useSoupView();+ const { soup, queryFilters } = useSoupView();const { changeIndex } = useSearchIndexController();- const isActive = () => soup.filters.isActive('channels');- const mutate = <K extends keyof ChannelFilters>(- field: K,- value: ChannelFilters[K]- ) =>- batch(() => {- if (!isActive()) changeIndex('channels');- setQueryFilters((prev) => ({- ...prev,- channel_filters: { ...prev.channel_filters, [field]: value },- }));- });+ const isActive = () => soup.predicates.isActive('channels');const channelIds = createMemo(- () => queryFilters().channel_filters?.channel_ids ?? []+ () => queryFilters.state.include.channelId ?? []);const senderIds = createMemo(- () => queryFilters().channel_filters?.sender_ids ?? []+ () => queryFilters.state.include?.channelSenderId ?? []);createEffect(() => {@@ -255,29 +246,48 @@ export function useChannelSearchFilter(opts: SearchFilterHookOpts) {return {isActive,channelIds,- setChannelIds: (ids: string[]) =>- mutate('channel_ids', ids.length ? ids : undefined),+ setChannelIds: (ids: string[]) => {+ if (!isActive()) changeIndex('channels');+ queryFilters.set({+ include: {+ channelId: ids,+ },+ });+ },senderIds,- setSenderIds: (ids: string[]) =>- mutate('sender_ids', ids.length ? ids : undefined),+ setSenderIds: (ids: string[]) => {+ if (!isActive()) changeIndex('channels');++ queryFilters.set({+ include: {+ channelSenderId: ids,+ },+ });+ },};}/** Email search filters (importance). */export function useEmailSearchFilter(opts: SearchFilterHookOpts) {- const { soup, queryFilters, setQueryFilters } = useSoupView();+ const { soup, queryFilters } = useSoupView();const { changeIndex } = useSearchIndexController();- const isActive = () => soup.filters.isActive('email');- const importance = createMemo(() => queryFilters().email_filters?.importance);+ const isActive = () => soup.predicates.isActive('email');+ const importance = createMemo(+ () => queryFilters.state.include.emailImportance+ );const setImportance = (val: boolean | undefined) =>batch(() => {if (!isActive()) changeIndex('email');- setQueryFilters((prev) => ({- ...prev,- email_filters: { ...prev.email_filters, importance: val },- }));+ queryFilters.set({+ include: {+ emailImportance: val,+ },+ exclude: {+ emailImportance: undefined,+ },+ });});createEffect(() => {@@ -289,36 +299,37 @@ export function useEmailSearchFilter(opts: SearchFilterHookOpts) {}type CallFieldMap = {- channel_ids: string[] | undefined;- speaker_ids: string[] | undefined;- attended: boolean | undefined;+ callChannelId: string[] | undefined;+ callSpeakerId: string[] | undefined;+ callAttended: boolean | undefined;};/** Call-record search filters (in:, from:, attended). */export function useCallSearchFilter(opts: SearchFilterHookOpts) {- const { soup, queryFilters, setQueryFilters } = useSoupView();+ const { soup, queryFilters } = useSoupView();const { changeIndex } = useSearchIndexController();- const isActive = () => soup.filters.isActive('calls');+ const isActive = () => soup.predicates.isActive('calls');const mutate = <K extends keyof CallFieldMap>(field: K,value: CallFieldMap[K]) =>batch(() => {if (!isActive()) changeIndex('calls');- setQueryFilters((prev) => ({- ...prev,- call_filters: { ...prev.call_filters, [field]: value },- }));+ queryFilters.set({+ include: {+ [field]: value,+ },+ });});const channelIds = createMemo(- () => queryFilters().call_filters?.channel_ids ?? []+ () => queryFilters.state.include.callChannelId ?? []);const speakerIds = createMemo(- () => queryFilters().call_filters?.speaker_ids ?? []+ () => queryFilters.state.include.callSpeakerId ?? []);- const attended = createMemo(() => queryFilters().call_filters?.attended);+ const attended = createMemo(() => queryFilters.state.include.callAttended);createEffect(() => {if (!opts.isSearchView() || !isActive()) return;@@ -334,80 +345,84 @@ export function useCallSearchFilter(opts: SearchFilterHookOpts) {isActive,channelIds,setChannelIds: (ids: string[]) =>- mutate('channel_ids', ids.length ? ids : undefined),+ mutate('callChannelId', ids.length ? ids : undefined),speakerIds,setSpeakerIds: (ids: string[]) =>- mutate('speaker_ids', ids.length ? ids : undefined),+ mutate('callSpeakerId', ids.length ? ids : undefined),attended,- setAttended: (val: boolean | undefined) => mutate('attended', val),+ setAttended: (val: boolean | undefined) => mutate('callAttended', val),};}export function useSearchIndexController() {- const { soup, setQueryFilters } = useSoupView();+ const { soup, queryFilters } = useSoupView();const panel = useSplitPanelOrThrow();const contentId = panel.handle.content().id;const changeIndex = (newValue: string) => {batch(() => {for (const opt of INDEX_OPTIONS) {- if (soup.filters.isActive(opt.value)) {- soup.filters.toggle({ or: [opt.value as FilterID] });+ if (soup.predicates.isActive(opt.value)) {+ soup.predicates.toggle({ or: [opt.value as FilterID] });}}if (newValue === 'all') {cacheChannelSubFilters(contentId, {});- setQueryFilters({- ...QUERY_FILTERS.default,- email_filters: { importance: true },- });+ queryFilters.replace({ include: { emailImportance: true } });return;}const opt = INDEX_OPTIONS.find((o) => o.value === newValue);if (!opt) return;- soup.filters.toggle({ or: [opt.value as FilterID] });+ soup.predicates.toggle({ or: [opt.value as FilterID] });if (opt.value === 'channels') {const cached = getCachedChannelSubFilters(contentId);- setQueryFilters({- ...opt.queryFilters,- channel_filters: {- ...opt.queryFilters.channel_filters,- ...cached,++ queryFilters.replace({+ include: {+ ...opt.queryFilters.include,+ channelId: cached.channel_ids,+ channelSenderId: cached.sender_ids,},+ exclude: opt.queryFilters.exclude,});} else if (opt.value === 'email') {const cached = getCachedEmailSubFilters(contentId);const importance ='importance' in cached? (cached.importance ?? undefined)- : opt.queryFilters.email_filters?.importance;- setQueryFilters({- ...opt.queryFilters,- email_filters: {- ...opt.queryFilters.email_filters,- importance,+ : opt.queryFilters.include?.emailImportance;++ queryFilters.replace({+ include: {+ ...opt.queryFilters.include,+ emailImportance: importance,},+ exclude: opt.queryFilters.exclude,});} else if (opt.value === 'calls') {const cached = getCachedCallSubFilters(contentId);const attended ='attended' in cached? (cached.attended ?? undefined)- : opt.queryFilters.call_filters?.attended;- setQueryFilters({- ...opt.queryFilters,- call_filters: {- ...opt.queryFilters.call_filters,- channel_ids: cached.channel_ids,- speaker_ids: cached.speaker_ids,- attended,+ : opt.queryFilters.include?.callAttended;++ queryFilters.replace({+ include: {+ ...opt.queryFilters.include,+ callChannelId: cached.channel_ids,+ callSpeakerId: cached.speaker_ids,+ callAttended: attended,},+ exclude: opt.queryFilters.exclude,});} else {- setQueryFilters({ ...opt.queryFilters });+ queryFilters.replace({+ include: opt.queryFilters.include,+ exclude: opt.queryFilters.exclude,+ });}});};@@ -415,38 +430,48 @@ export function useSearchIndexController() {return { changeIndex };}-export const INDEX_OPTIONS: (Option & { queryFilters: SoupBody })[] = [+export const INDEX_OPTIONS: {+ label: string;+ value: string;+ icon: () => JSX.Element;+ queryFilters: Query;+}[] = [{value: 'channels',label: 'Channels',icon: () => (<EntityIcon targetType="channel" size="xs" theme="monochrome" />),- queryFilters: QUERY_FILTERS.channels,+ queryFilters: defineQueryFilters({ exclude: { channelId: [NIL_UUID] } }),},{value: 'document-or-file',label: 'Documents',icon: () => <EntityIcon targetType="md" size="xs" theme="monochrome" />,- queryFilters: QUERY_FILTERS.documentAndFile,+ queryFilters: defineQueryFilters({ exclude: { subType: ['task'] } }),},{value: 'task',label: 'Tasks',icon: () => <EntityIcon targetType="task" size="xs" theme="monochrome" />,- queryFilters: QUERY_FILTERS.task,+ queryFilters: defineQueryFilters({ include: { subType: ['task'] } }),},{value: 'email',label: 'Email',icon: () => <EntityIcon targetType="email" size="xs" theme="monochrome" />,- queryFilters: QUERY_FILTERS.email,+ queryFilters: defineQueryFilters({+ exclude: { threadId: [NIL_UUID] },+ include: { emailImportance: true },+ }),},{value: 'calls',label: 'Calls',icon: () => <EntityIcon targetType="call" size="xs" theme="monochrome" />,- queryFilters: QUERY_FILTERS.calls,+ queryFilters: defineQueryFilters({+ exclude: { callChannelId: [NIL_UUID] },+ }),},{value: 'folders',@@ -454,12 +479,12 @@ export const INDEX_OPTIONS: (Option & { queryFilters: SoupBody })[] = [icon: () => (<EntityIcon targetType="project" size="xs" theme="monochrome" />),- queryFilters: QUERY_FILTERS.folders,+ queryFilters: defineQueryFilters({ exclude: { folderId: [NIL_UUID] } }),},{value: 'agent',label: 'Agents',icon: () => <EntityIcon targetType="chat" size="xs" theme="monochrome" />,- queryFilters: QUERY_FILTERS.agent,+ queryFilters: defineQueryFilters({ exclude: { chatId: [NIL_UUID] } }),},];diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsxindex 4c58eafc48..06a41b1178 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx@@ -7,6 +7,7 @@ import { isListViewID } from '@app/constants/list-views';import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-context';import {type Accessor,+ batch,createEffect,createMemo,createSignal,@@ -30,7 +31,12 @@ import { useContacts } from '@queries/contacts/contacts';import { useUserId } from '@core/context/user';import { UserIcon } from '@core/component/UserIcon';import type { FilterID } from '@app/component/next-soup/filters';-import { NO_ASSIGNEE } from '@app/component/next-soup/soup-view/task-sub-filter-matcher';+import {+ NO_ASSIGNEE,+ type FilterContext,+} from '@app/component/next-soup/filters/configs/';+import type { PropertyFilter } from '@app/component/next-soup/filters/filter-store';+import { SYSTEM_PROPERTY_IDS } from '@core/component/Properties/constants';import { registerHotkey } from '@core/hotkey/hotkeys';import { LabelAndHotKey, Tooltip } from '@core/component/Tooltip';import {@@ -644,7 +650,8 @@ const SearchIndexSubRow = (props: {export const UnifiedFilterDropdown = () => {const [open, setOpen] = createSignal(false);const panel = useSplitPanelOrThrow();- const { soup, assigneeFilter, setAssigneeFilter } = useSoupView();+ const { soup, queryFilters, assigneeFilter, setAssigneeFilter } =+ useSoupView();const contacts = useContacts();const userId = useUserId();const contentId = panel.handle.content().id;@@ -663,11 +670,28 @@ export const UnifiedFilterDropdown = () => {});const isOptionActive = (optionId: string) => {- return soup.filters.isActive(optionId);+ return soup.predicates.isActive(optionId);};const toggleFilter = (optionId: string) => {- soup.filters.toggle({ or: [optionId] });+ const wasActive = soup.predicates.isActive(optionId);+ soup.predicates.toggle({ or: [optionId] });++ const filter = soup.predicates.getConfig(optionId);+ if (!filter?.query) return;++ const ctx: FilterContext = {+ userId: userId(),+ assignees: assigneeFilter(),+ };+ const query =+ typeof filter.query === 'function' ? filter.query(ctx) : filter.query;++ if (wasActive) {+ queryFilters.remove(query);+ } else {+ queryFilters.add(query);+ }};// Assignee options for tasks view@@ -706,10 +730,43 @@ export const UnifiedFilterDropdown = () => {];});+ const handleAssigneeChange = (ids: string[]) => {+ const current = assigneeFilter();+ const toAdd = ids.filter((id) => !current.includes(id));+ const toRemove = current.filter((id) => !ids.includes(id));++ // Exclude NO_ASSIGNEE from backend queries - it's handled client-side only+ const toProps = (list: string[]): PropertyFilter[] =>+ list+ .filter((id) => id !== NO_ASSIGNEE)+ .map((id) => ({+ propertyId: SYSTEM_PROPERTY_IDS.ASSIGNEES,+ type: 'entity',+ value: id,+ }));++ batch(() => {+ setAssigneeFilter(ids);++ // Activate/deactivate the assignee predicate based on selection+ const shouldBeActive = ids.length > 0;+ if (shouldBeActive !== soup.predicates.isActive('assignee')) {+ soup.predicates.toggle({ and: ['assignee'] });+ }++ const removeProps = toProps(toRemove);+ const addProps = toProps(toAdd);+ if (removeProps.length)+ queryFilters.remove({ include: { properties: removeProps } });+ if (addProps.length)+ queryFilters.add({ include: { properties: addProps } });+ });+ };+const isTasksView = () => currentView() === 'tasks';- const isSearchView = createMemo(() => currentView() === 'search');+ const isSearchView = () => currentView() === 'search';const hasActiveIndex = () =>- INDEX_OPTIONS.some((opt) => soup.filters.isActive(opt.value));+ INDEX_OPTIONS.some((opt) => soup.predicates.isActive(opt.value));const { changeIndex: handleIndexChange } = useSearchIndexController();@@ -817,7 +874,7 @@ export const UnifiedFilterDropdown = () => {label="Assignee"options={assigneeOptions}activeIds={assigneeFilter}- onChange={setAssigneeFilter}+ onChange={handleAssigneeChange}placeholder="Search assignees..."/></Show>@@ -828,7 +885,7 @@ export const UnifiedFilterDropdown = () => {{(option) => {const rowProps = {option,- active: () => soup.filters.isActive(option.value),+ active: () => soup.predicates.isActive(option.value),onSelect: () => handleIndexChange(option.value),closeRoot: () => setOpen(false),};diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsxindex 28d94989d7..1690e74aeb 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx@@ -1,20 +1,24 @@import {- VIEW_TAB_PRESETS,type PresetContext,+ getViewPreset,+ VIEW_TAB_PRESETS,} from '@app/component/app-sidebar/soup-filter-presets';-import type { FilterID } from '@app/component/next-soup/filters/configs';-import { NIL_UUID } from '@app/component/next-soup/filters/query-filters';-import { NO_ASSIGNEE } from '@app/component/next-soup/soup-view/task-sub-filter-matcher';+import {+ type FilterID,+ type FilterContext,+ NO_ASSIGNEE,+} from '@app/component/next-soup/filters';+import { NIL_UUID } from '@app/component/next-soup/filters/filter-store';+import { SYSTEM_PROPERTY_IDS } from '@core/component/Properties/constants';import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-context';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';import type { ListView } from '@app/constants/list-views';import { isListViewID } from '@app/constants/list-views';import { useUserContext, useUserId } from '@core/context/user';-import { deepEqual } from '@core/util/compareUtils';import { useContacts } from '@queries/contacts/contacts';import { type Accessor, batch, createMemo, createSignal } from 'solid-js';import type { ActiveFilter } from './active-filter-chips';-import { INDEX_OPTIONS } from './search-operator-autocomplete';+import { INDEX_OPTIONS } from './search-filter-controls';import {type SearchableOption,useSearchFilterOptions,@@ -24,10 +28,11 @@ import {buildContactLabel,VIEW_FILTER_CATEGORIES,} from './unified-filter-dropdown';+import { deepEqual } from '@core/util/compareUtils';// Filter IDs that are set by tabs and should not be shown as removable chipsconst TAB_ONLY_FILTERS = new Set([- 'signal',+ 'inbox','noise','explicit-noise','channels',@@ -45,14 +50,9 @@ const TAB_ONLY_FILTERS = new Set([* and a function to reset filters to the current tab's default state.*/export function useFilterRefinements() {- const {- soup,- queryFilters,- setQueryFilters,- assigneeFilter,- setAssigneeFilter,- activeTab,- } = useSoupView();+ const { soup, queryFilters, assigneeFilter, setAssigneeFilter, activeTab } =+ useSoupView();+ const filterData = () => queryFilters.state;const panel = useSplitPanelOrThrow();const user = useUserContext();const contacts = useContacts();@@ -77,15 +77,9 @@ export function useFilterRefinements() {const currentPreset = createMemo(() => {const view = currentView();if (!view) return undefined;-- const viewConfig = VIEW_TAB_PRESETS[view];- if (!viewConfig) return undefined;-- const tab = activeTab() ?? viewConfig.default;- const resolver = viewConfig.tabs[tab];- if (!resolver) return undefined;-- return resolver(getPresetContext());+ const tab = activeTab() ?? VIEW_TAB_PRESETS[view]?.default;+ if (!tab) return undefined;+ return getViewPreset(view, tab, getPresetContext());});const hasActiveRefinements = createMemo(() => {@@ -97,13 +91,19 @@ export function useFilterRefinements() {...(preset.clientFilters.or ?? []),]);- const currentIds = new Set(soup.filters.activeIds() as FilterID[]);+ const currentIds = new Set(soup.predicates.activeIds() as FilterID[]);const hasClientFilterDiff =expectedIds.size !== currentIds.size ||[...expectedIds].some((id) => !currentIds.has(id as FilterID));- const hasQueryFilterDiff = !deepEqual(queryFilters(), preset.queryFilters);+ // Check if there are any external filters set (normalize undefined vs {} for comparison)+ const currentFilterData = filterData();+ const presetFilters = preset.filters;+ const hasQueryFilterDiff =+ !deepEqual(currentFilterData.include, presetFilters.include ?? {}) ||+ !deepEqual(currentFilterData.exclude, presetFilters.exclude ?? {}) ||+ currentFilterData.emailView !== presetFilters.emailView;const hasSubFilters = assigneeFilter().length > 0;@@ -145,15 +145,15 @@ export function useFilterRefinements() {};const setFilterIds =- (filterKey: 'channel_filters' | 'call_filters', field: string) =>+ (+ field: 'callChannelId' | 'callSpeakerId' | 'channelId' | 'channelSenderId'+ ) =>(ids: string[]) =>- setQueryFilters((prev) => ({- ...prev,- [filterKey]: {- ...(prev[filterKey] ?? {}),- [field]: ids.length > 0 ? ids : undefined,+ queryFilters.set({+ include: {+ [field]: ids,},- }));+ });/*** Cache of chip objects keyed by a stable id derived from the chip's category@@ -192,7 +192,7 @@ export function useFilterRefinements() {for (const category of viewCategories()) {for (const option of category.options) {if (- !soup.filters.isActive(option.id) ||+ !soup.predicates.isActive(option.id) ||TAB_ONLY_FILTERS.has(option.id) ||presetFilterIds.has(option.id as FilterID)) {@@ -213,27 +213,31 @@ export function useFilterRefinements() {}// Search operator filters: index: (entity type toggles)- const coveredByView = new Set(+ const coveredByView = new Set<string>(viewCategories().flatMap((c) => c.options.map((o) => o.id)));for (const option of INDEX_OPTIONS) {- const optionId = option.id as FilterID;+ const optionId = option.value as FilterID;if (- !soup.filters.isActive(optionId) ||+ !soup.predicates.isActive(optionId) ||coveredByView.has(optionId) ||presetFilterIds.has(optionId)) {continue;}- const key = `Type|${option.id}`;+ const key = `Type|${option.value}`;seenKeys.add(key);filters.push(getOrCreateChip(key, () => ({categoryLabel: 'Type',- optionId: () => option.id,+ optionId: () => option.value,optionLabel: () => option.label,icon: option.icon,- categoryOptions: INDEX_OPTIONS as ActiveFilter['categoryOptions'],+ categoryOptions: INDEX_OPTIONS.map((o) => ({+ id: o.value,+ label: o.label,+ icon: o.icon,+ })) as ActiveFilter['categoryOptions'],multiple: false,onRemove: () => changeIndex('all'),onReplace: (newOptionId) => changeIndex(newOptionId),@@ -283,8 +287,22 @@ export function useFilterRefinements() {categoryLabel: 'Assignee',optionId: () => id,optionLabel: () => assigneeOptionsMap().get(id)?.label ?? id,- onRemove: () =>- setAssigneeFilter(assigneeFilter().filter((a) => a !== id)),+ onRemove: () => {+ batch(() => {+ setAssigneeFilter(assigneeFilter().filter((a) => a !== id));+ queryFilters.remove({+ include: {+ properties: [+ {+ propertyId: SYSTEM_PROPERTY_IDS.ASSIGNEES,+ type: 'entity',+ value: id,+ },+ ],+ },+ });+ });+ },})));}@@ -294,12 +312,12 @@ export function useFilterRefinements() {categoryLabel: 'In',optionIdPrefix: 'channel-in',getIds: () =>- (queryFilters().channel_filters?.channel_ids ?? []).filter(+ (queryFilters.state.include.channelId ?? []).filter((id) => id !== NIL_UUID),searchableOptions: channelOptions,labelMap: channelLabelMap,- onChange: setFilterIds('channel_filters', 'channel_ids'),+ onChange: setFilterIds('channelId'),searchPlaceholder: 'Search channels...',});@@ -307,26 +325,26 @@ export function useFilterRefinements() {key: 'ChannelFrom',categoryLabel: 'From',optionIdPrefix: 'channel-from',- getIds: () => queryFilters().channel_filters?.sender_ids ?? [],+ getIds: () => queryFilters.state.include.channelSenderId ?? [],searchableOptions: senderOptions,labelMap: senderLabelMap,- onChange: setFilterIds('channel_filters', 'sender_ids'),+ onChange: setFilterIds('channelSenderId'),searchPlaceholder: 'Search senders...',});if (currentView() === 'search') {- if (soup.filters.isActive('calls')) {+ if (soup.predicates.isActive('calls')) {pushSearchableChip({key: 'CallIn',categoryLabel: 'In',optionIdPrefix: 'call-in',getIds: () =>- (queryFilters().call_filters?.channel_ids ?? []).filter(+ (queryFilters.state.include.callChannelId ?? []).filter((id) => id !== NIL_UUID),searchableOptions: channelOptions,labelMap: channelLabelMap,- onChange: setFilterIds('call_filters', 'channel_ids'),+ onChange: setFilterIds('callChannelId'),searchPlaceholder: 'Search channels...',});@@ -334,14 +352,14 @@ export function useFilterRefinements() {key: 'CallFrom',categoryLabel: 'From',optionIdPrefix: 'call-from',- getIds: () => queryFilters().call_filters?.speaker_ids ?? [],+ getIds: () => queryFilters.state.include.callSpeakerId ?? [],searchableOptions: senderOptions,labelMap: senderLabelMap,- onChange: setFilterIds('call_filters', 'speaker_ids'),+ onChange: setFilterIds('callSpeakerId'),searchPlaceholder: 'Search speakers...',});- const callAttended = queryFilters().call_filters?.attended;+ const callAttended = queryFilters.state.include.callAttended;if (callAttended !== undefined && callAttended !== null) {const ATTENDED_YES = 'attended:yes';const ATTENDED_NO = 'attended:no';@@ -352,11 +370,11 @@ export function useFilterRefinements() {categoryLabel: 'Attended',hideCategoryLabel: true,optionId: () =>- queryFilters().call_filters?.attended+ queryFilters.state.include.callAttended? ATTENDED_YES: ATTENDED_NO,optionLabel: () =>- queryFilters().call_filters?.attended+ queryFilters.state.include.callAttended? 'Attended': 'Unattended',categoryOptions: [@@ -366,25 +384,21 @@ export function useFilterRefinements() {multiple: false,isOptionActive: (optionId) =>optionId ===- (queryFilters().call_filters?.attended+ (queryFilters.state.include.callAttended? ATTENDED_YES: ATTENDED_NO),onRemove: () =>- setQueryFilters((prev) => ({- ...prev,- call_filters: {- ...prev.call_filters,- attended: undefined,+ queryFilters.remove({+ include: {+ callAttended: queryFilters.state.include.callAttended,},- })),+ }),onReplace: (newOptionId) =>- setQueryFilters((prev) => ({- ...prev,- call_filters: {- ...prev.call_filters,- attended: newOptionId === ATTENDED_YES,+ queryFilters.add({+ include: {+ callAttended: newOptionId === ATTENDED_YES,},- })),+ }),})));}@@ -392,8 +406,8 @@ export function useFilterRefinements() {// undefined importance means "All" — no chip.if (- soup.filters.isActive('email') &&- queryFilters().email_filters?.importance !== undefined+ soup.predicates.isActive('email') &&+ queryFilters.state.include.emailImportance !== undefined) {const IMPORTANCE_SIGNAL = 'importance:signal';const IMPORTANCE_NOISE = 'importance:noise';@@ -403,11 +417,11 @@ export function useFilterRefinements() {getOrCreateChip(key, () => ({categoryLabel: 'Importance',optionId: () =>- queryFilters().email_filters?.importance+ filterData().include.emailImportance? IMPORTANCE_SIGNAL: IMPORTANCE_NOISE,optionLabel: () =>- queryFilters().email_filters?.importance ? 'Signal' : 'Noise',+ filterData().include.emailImportance ? 'Signal' : 'Noise',categoryOptions: [{ id: IMPORTANCE_SIGNAL, label: 'Signal' },{ id: IMPORTANCE_NOISE, label: 'Noise' },@@ -415,25 +429,19 @@ export function useFilterRefinements() {multiple: false,isOptionActive: (optionId) =>optionId ===- (queryFilters().email_filters?.importance+ (filterData().include.emailImportance? IMPORTANCE_SIGNAL: IMPORTANCE_NOISE),onRemove: () =>- setQueryFilters((prev) => ({- ...prev,- email_filters: {- ...prev.email_filters,- importance: undefined,+ queryFilters.remove({+ include: {+ emailImportance: queryFilters.state.include.emailImportance,},- })),+ }),onReplace: (newOptionId) =>- setQueryFilters((prev) => ({- ...prev,- email_filters: {- ...prev.email_filters,- importance: newOptionId === IMPORTANCE_SIGNAL,- },- })),+ queryFilters.add({+ include: { emailImportance: newOptionId === IMPORTANCE_SIGNAL },+ }),})));}@@ -449,18 +457,46 @@ export function useFilterRefinements() {});const isOptionActive = (optionId: string) => {- return soup.filters.isActive(optionId);+ return soup.predicates.isActive(optionId);+ };++ const getFilterContext = (): FilterContext => ({+ userId: currentUserId(),+ assignees: assigneeFilter(),+ });++ const getFilterQuery = (optionId: string) => {+ const filter = soup.predicates.getConfig(optionId);+ if (!filter?.query) return undefined;+ return typeof filter.query === 'function'+ ? filter.query(getFilterContext())+ : filter.query;};const removeFilter = (optionId: string) => {- soup.filters.toggle({ or: [optionId as FilterID] });+ const query = getFilterQuery(optionId);+ batch(() => {+ soup.predicates.toggle({ or: [optionId as FilterID] });+ if (query) {+ queryFilters.remove(query);+ }+ });};const replaceFilter = (oldOptionId: string, newOptionId: string) => {- // Toggle off the old filter and toggle on the new one+ const oldQuery = getFilterQuery(oldOptionId);+ const newQuery = getFilterQuery(newOptionId);batch(() => {- soup.filters.toggle({ or: [oldOptionId as FilterID] });- soup.filters.toggle({ or: [newOptionId as FilterID] });+ if (soup.predicates.isActive(oldOptionId)) {+ soup.predicates.toggle({ or: [oldOptionId as FilterID] });+ }++ if (!soup.predicates.isActive(newOptionId)) {+ soup.predicates.toggle({ or: [newOptionId as FilterID] });+ }++ if (oldQuery) queryFilters.remove(oldQuery);+ if (newQuery) queryFilters.add(newQuery);});};@@ -469,8 +505,8 @@ export function useFilterRefinements() {if (!preset) return;batch(() => {- soup.filters.set(preset.clientFilters);- setQueryFilters(preset.queryFilters);+ soup.predicates.set(preset.clientFilters);+ queryFilters.replace(preset.filters ?? null);setAssigneeFilter([]);});};diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsxindex 46c192d6ef..b7cccbcff5 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx@@ -6,20 +6,14 @@ import {import { createSearchState } from '@app/component/next-soup/soup-view/create-search-state';import { deduplicateEntities } from '@app/component/next-soup/utils';import {- isTaskEntity,isWithNotification,type EntityData,- type TaskEntityWithProperties,type WithNotification,type WithSearch,} from '@entity';import { ENABLE_FEATURED_SEARCH_RESULTS } from '@core/constant/featureFlags';import { useNotificationsForEntity } from '@notifications';-import {- type SoupParams,- useSoupItemsQuery,- type SoupBody,-} from '@queries/soup/items';+import { type SoupParams, useSoupAstItemsQuery } from '@queries/soup/items';import {type Accessor,createContext,@@ -33,7 +27,13 @@ import {Suspense,useContext,} from 'solid-js';-import { matchesTaskSubFilters } from './task-sub-filter-matcher';+import type { FilterContext } from '@app/component/next-soup/filters/configs/';+import {+ createQueryStore,+ type Query,+ type QueryStore,+} from '@app/component/next-soup/filters/filter-store/query-store';+import { useUserId } from '@core/context/user';import { useQueryClient } from '@queries/client';import { soupKeys } from '@queries/soup/keys';import type { InfiniteData } from '@tanstack/solid-query';@@ -76,8 +76,7 @@ interface SoupViewContextValues {rows: Accessor<SoupRow[]>;isSearchServiceLoading: Accessor<boolean>;isLocalSearchSettling: Accessor<boolean>;- queryFilters: Accessor<SoupBody>;- setQueryFilters: Setter<SoupBody>;+ queryFilters: QueryStore;assigneeFilter: Accessor<string[]>;setAssigneeFilter: Setter<string[]>;activeTab: Accessor<string | undefined>;@@ -102,7 +101,7 @@ export const useMaybeSoupView = () => useContext(SoupViewContext);interface SoupViewContextProviderProps {soup?: SoupState;- queryFilters?: SoupBody;+ initialQuery?: Query;disableLocalSearch?: boolean;/*** Additional client-side entities to merge into the soup item stream.@@ -140,8 +139,44 @@ export const SoupViewContextProvider: FlowComponent<};});- const [internalQueryFilters, setInternalQueryFilters] =- createSignal<SoupBody>({ ...(props.queryFilters ?? {}) });+ const store = createQueryStore({ initial: props.initialQuery });++ const invalidateCache = () => {+ queryClient.setQueryData(+ soupKeys.astItems({+ params: soupParams(),+ body: soupBody(),+ }).queryKey,+ (prev: InfiniteData<SoupPage> | SoupPage | undefined) => {+ if (!prev) return;+ if ('pages' in prev) {+ prev.pages.splice(1, prev.pages.length);+ return prev;+ }+ return prev;+ }+ );+ };++ const queryFilters: QueryStore = {+ ...store,+ set: (query) => {+ invalidateCache();+ store.set(query);+ },+ replace: (query) => {+ invalidateCache();+ store.replace(query);+ },+ add: (query) => {+ invalidateCache();+ store.add(query);+ },+ remove: (query) => {+ invalidateCache();+ store.remove(query);+ },+ };const [searchPaused, setSearchPaused] = createSignal(false);const [searchMentions, setSearchMentions] = createSignal<string[]>([]);@@ -150,34 +185,32 @@ export const SoupViewContextProvider: FlowComponent<// Clear sub-filters when task filter is deactivatedcreateEffect(() => {- if (!soup.filters.isActive('task')) {+ if (!soup.predicates.isActive('task')) {setAssigneeFilter([]);}});- const queryFilters = createMemo(() => {- const base = internalQueryFilters();-- return {- ...base,- };- });-- const soupBody = createMemo(- (): SoupBody => ({- ...queryFilters(),- })- );+ // soupBody is derived from the query filter store's compiled AST+ const soupBody = createMemo(() => queryFilters.compile());const search = createSearchState({soup,- queryFilters,+ filters: () => queryFilters.state,+ assignees: assigneeFilter,disableLocalSearch: props.disableLocalSearch,searchPaused,searchMentions,});const notificationSource = useGlobalNotificationSource();+ const userId = useUserId();++ // Create filter context for context-aware filter predicates+ const getFilterContext = (): FilterContext => ({+ userId: userId(),+ notificationSource,+ assignees: assigneeFilter(),+ });const attachNotifications = (entity: EntityData) => {return {@@ -212,7 +245,7 @@ export const SoupViewContextProvider: FlowComponent<};};- const itemsQuery = useSoupItemsQuery(+ const itemsQuery = useSoupAstItemsQuery(() => ({params: soupParams(),body: soupBody(),@@ -222,32 +255,6 @@ export const SoupViewContextProvider: FlowComponent<}));- const setQueryFilters: Setter<SoupBody> = (next) => {- // To avoid fetching all pages again when coming back to the current query filters,- // we set the query cache to only contain the first page of data which is the only- // one to be refetched- queryClient.setQueryData(- soupKeys.items({- params: soupParams(),- body: soupBody(),- }).queryKey,- (prev: InfiniteData<SoupPage> | SoupPage) => {- if (!prev) return;-- if ('pages' in prev) {- // Just to avoid spreading and new array creation, works the same but slightly- // better performance- prev.pages.splice(1, prev.pages.length);- return prev;- }-- return prev;- }- );-- setInternalQueryFilters(next);- };-const items = createMemo<SoupEntity[]>((prev) => {const searching = search.isSearching();@@ -295,28 +302,13 @@ export const SoupViewContextProvider: FlowComponent<const baseEntities = () => {let transformed = items();+ const ctx = getFilterContext();const next = [];-- const currentAssigneeFilter = assigneeFilter();-for (const entity of transformed) {- if (!soup.filters.test(entity)) {+ if (!soup.predicates.test(entity, ctx)) {continue;}-- // Apply task sub-filters- if (currentAssigneeFilter.length > 0 && isTaskEntity(entity)) {- const taskEntity = entity as unknown as TaskEntityWithProperties;- if (- !matchesTaskSubFilters(taskEntity, {- assigneeFilter: currentAssigneeFilter,- })- ) {- continue;- }- }-next.push(entity);}@@ -394,7 +386,6 @@ export const SoupViewContextProvider: FlowComponent<isSearchServiceLoading: search.isSearchServiceLoading,isLocalSearchSettling: search.isLocalSearchSettling,queryFilters,- setQueryFilters,assigneeFilter,setAssigneeFilter,activeTab,diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsxindex b7b319a49d..2ff787753c 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx@@ -1,9 +1,8 @@import {VIEW_TAB_PRESETS,type PresetContext,+ getViewPreset,} from '@app/component/app-sidebar/soup-filter-presets';-import type { FilterID } from '@app/component/next-soup/filters/configs';-import type { SoupItemsQueryFilters } from '@queries/soup/items';import { useSoup } from '@app/component/next-soup/soup-context';import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-context';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';@@ -89,7 +88,7 @@ const useCurrentListView = () => {export const useApplyPreset = () => {const soup = useSoup();- const { setQueryFilters, setActiveTab } = useSoupView();+ const { queryFilters, setActiveTab } = useSoupView();const user = useUserContext();const getPresetContext = (): PresetContext => ({@@ -97,27 +96,15 @@ export const useApplyPreset = () => {email: user.email(),});- const applyPreset = (preset: {- queryFilters: SoupItemsQueryFilters;- clientFilters: { and?: FilterID[]; or?: FilterID[] };- }) => {- batch(() => {- setQueryFilters(preset.queryFilters);- soup.filters.set(preset.clientFilters);- });- };-const applyTabPreset = (view: ListView, tabId: string): boolean => {- const config = VIEW_TAB_PRESETS[view];- if (!config) return false;- const resolver = config.tabs[tabId];- if (!resolver) return false;+ const preset = getViewPreset(view, tabId, getPresetContext());+ if (!preset) return false;- const resolved = resolver(getPresetContext());- if (!resolved) return false;-- setActiveTab(tabId);- applyPreset(resolved);+ batch(() => {+ setActiveTab(tabId);+ queryFilters.replace(preset.filters);+ soup.predicates.set(preset.clientFilters);+ });return true;};diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsxindex aa6e74a788..532ddfbd13 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx@@ -84,8 +84,7 @@ import { SoupChatInput } from '@app/component/SoupChatInput';import { ENABLE_UNIFIED_LIST_AI_INPUT } from '@core/constant/featureFlags';import { isMobile } from '@core/mobile/isMobile';-import type { SoupItemsQueryFilters } from '@queries/soup/items';-import type { FilterID } from '@app/component/next-soup/filters';+import type { QueryState } from '@app/component/next-soup/filters/filter-store';import {SoupViewTabs,CollapsedSoupViewTabs,@@ -112,7 +111,8 @@ import {import { Button } from '@app/component/next-soup/soup-view/filters-bar/button';import { LabelAndHotKey, Tooltip } from '@core/component/Tooltip';import SearchIcon from '@macro-icons/macro-magnifying-glass.svg';-import { QUERY_FILTERS } from '../filters/query-filters';+import type { SetPredicatesInput } from '@app/component/next-soup/filters/filter-store/predicates-store';+import { VIEW_TAB_PRESETS } from '@app/component/app-sidebar/soup-filter-presets';const useSoupNotificationInvalidators = () => {const notificationSource = useGlobalNotificationSource();@@ -167,14 +167,14 @@ const useSoupNotificationInvalidators = () => {type PersistedSoupViewState = {version?: number;activeTab: string | undefined;- filters: { and: string[]; or: string[] };- queryFilters: SoupItemsQueryFilters;+ filters: SetPredicatesInput<string>;+ queryFilters: Partial<QueryState>;sort: SystemSortOption[];previewEntity: string | undefined;assigneeFilter: string[];};-const PERSISTED_STATE_VERSION = 3;+const PERSISTED_STATE_VERSION = 4;const listStateCache = new Map<string,@@ -188,8 +188,8 @@ const listStateCache = new Map<interface SoupViewProps {viewName: string;- initialClientFilters?: { and?: FilterID[]; or?: FilterID[] };- queryFilters?: SoupItemsQueryFilters;+ initialClientFilters?: SetPredicatesInput<string>;+ initialFilters?: Partial<QueryState>;disableLocalSearch?: boolean;/*** Client-side entities to merge into the soup results. Useful for entity@@ -269,7 +269,7 @@ export const SoupView = (props: SoupViewProps) => {><SoupViewContextProvidersoup={soup}- queryFilters={props.queryFilters}+ initialQuery={props.initialFilters}disableLocalSearch={props.disableLocalSearch}additionalEntities={props.additionalEntities}>@@ -391,7 +391,7 @@ export const SoupView = (props: SoupViewProps) => {interface SoupViewListProps {customScrollbarHidden?: boolean;scopeId?: string;- initialClientFilters?: { and?: FilterID[]; or?: FilterID[] };+ initialClientFilters?: SetPredicatesInput<string>;}export const SoupViewList = (props: SoupViewListProps) => {@@ -402,7 +402,6 @@ export const SoupViewList = (props: SoupViewListProps) => {rows,searchText,setSearchText,- setQueryFilters,queryFilters,featuredIds,isSearchServiceLoading,@@ -451,7 +450,7 @@ export const SoupViewList = (props: SoupViewListProps) => {// Focus first entity on filter/search changescreateEffect(on(- () => [soup.filters.activeIds(), searchText(), featuredIds()] as const,+ () => [soup.predicates.activeIds(), searchText(), featuredIds()] as const,() => {if (!focusEffectsEnabled()) return;focusFirstEntity();@@ -705,17 +704,27 @@ export const SoupViewList = (props: SoupViewListProps) => {applyTabPreset(contentId, initialPersistedState.activeTab);if (!applied) {batch(() => {- soup.filters.set(+ soup.predicates.set(isStale- ? (props.initialClientFilters ?? { and: [], or: [] })- : (initialPersistedState.filters ?? { and: [], or: [] })+ ? (props.initialClientFilters ?? {})+ : initialPersistedState.filters);- setQueryFilters(- isStale- ? QUERY_FILTERS.default- : (initialPersistedState.queryFilters ?? QUERY_FILTERS.default)- );- setActiveTab(initialPersistedState.activeTab);+ const persistedFilterData = isStale+ ? {}+ : (initialPersistedState.queryFilters ?? {});+ queryFilters.replace({+ include: persistedFilterData.include,+ exclude: persistedFilterData.exclude,+ emailView: persistedFilterData.emailView,+ });+ if (isListViewID(contentId)) {+ const tab =+ initialPersistedState.activeTab ??+ VIEW_TAB_PRESETS[contentId].default;+ if (tab) {+ setActiveTab(tab);+ }+ }});}batch(() => {@@ -724,7 +733,14 @@ export const SoupViewList = (props: SoupViewListProps) => {});} else {if (props.initialClientFilters) {- soup.filters.set(props.initialClientFilters);+ soup.predicates.set(props.initialClientFilters);+ }+ // Set default tab for list views when no persisted state exists+ if (isListViewID(contentId)) {+ const defaultTab = VIEW_TAB_PRESETS[contentId].default;+ if (defaultTab) {+ setActiveTab(defaultTab);+ }}}});@@ -736,10 +752,10 @@ export const SoupViewList = (props: SoupViewListProps) => {version: PERSISTED_STATE_VERSION,activeTab: activeTab(),filters: {- and: soup.filters.andFilters().map((f) => f.id),- or: soup.filters.orFilters().map((f) => f.id),+ and: [...soup.predicates.andIds()],+ or: [...soup.predicates.orIds()],},- queryFilters: queryFilters(),+ queryFilters: JSON.parse(JSON.stringify(queryFilters.state)),sort: soup.sort.active().map((s) => s.id),previewEntity: soup.previewEntity(),assigneeFilter: assigneeFilter(),@@ -926,8 +942,8 @@ export const SoupViewList = (props: SoupViewListProps) => {soup.focus.set(row.original.id);}}showUnrollNotifications={- soup.filters.isActive('signal') &&- !soup.filters.isActive('noise')+ soup.predicates.isActive('inbox') &&+ !soup.predicates.isActive('noise')}checked={row.isSelected()}onChecked={(diff --git a/js/app/packages/app/component/next-soup/soup-view/task-sub-filter-matcher.test.ts b/js/app/packages/app/component/next-soup/soup-view/task-sub-filter-matcher.test.tsdeleted file mode 100644index dd7c0569b4..0000000000--- a/js/app/packages/app/component/next-soup/soup-view/task-sub-filter-matcher.test.ts+++ /dev/null@@ -1,164 +0,0 @@-import { describe, expect, it } from 'vitest';-import { SYSTEM_PROPERTY_IDS } from '@core/component/Properties/constants';-import type { SoupProperty } from '@service-storage/generated/schemas';-import type { TaskEntityWithProperties } from '@entity/types/entity';-import { matchesTaskSubFilters, NO_ASSIGNEE } from './task-sub-filter-matcher';--const createSoupProperty = (- definitionId: string,- value: unknown-): SoupProperty => {- return {- definition: { id: definitionId },- value,- } as unknown as SoupProperty;-};--const createTask = (props?: {- properties?: SoupProperty[];-}): TaskEntityWithProperties => {- return {- id: 'task-1',- name: 'Task',- ownerId: 'owner-1',- type: 'document',- fileType: 'md',- subType: { type: 'task' },- ...(props?.properties ? { properties: props.properties } : {}),- };-};--describe('matchesTaskSubFilters', () => {- it('filters out tasks with non-matching assignee when properties exist', () => {- const task = createTask({- properties: [- createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {- type: 'EntityReference',- value: [{ entity_type: 'USER', entity_id: 'user-2' }],- }),- ],- });-- expect(- matchesTaskSubFilters(task, {- assigneeFilter: ['user-1'],- })- ).toBe(false);- });-- it('matches any assignee when multiple assignees are in filter', () => {- const taskUser1 = createTask({- properties: [- createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {- type: 'EntityReference',- value: [{ entity_type: 'USER', entity_id: 'user-1' }],- }),- ],- });-- const taskUser2 = createTask({- properties: [- createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {- type: 'EntityReference',- value: [{ entity_type: 'USER', entity_id: 'user-2' }],- }),- ],- });-- const taskUser3 = createTask({- properties: [- createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {- type: 'EntityReference',- value: [{ entity_type: 'USER', entity_id: 'user-3' }],- }),- ],- });-- const multiAssigneeFilter = ['user-1', 'user-2'];-- expect(- matchesTaskSubFilters(taskUser1, { assigneeFilter: multiAssigneeFilter })- ).toBe(true);- expect(- matchesTaskSubFilters(taskUser2, { assigneeFilter: multiAssigneeFilter })- ).toBe(true);- expect(- matchesTaskSubFilters(taskUser3, { assigneeFilter: multiAssigneeFilter })- ).toBe(false);- });-- it('matches unassigned tasks when NO_ASSIGNEE filter is active', () => {- const taskWithNoAssignees = createTask({- properties: [- createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {- type: 'EntityReference',- value: [],- }),- ],- });-- const taskWithAssignee = createTask({- properties: [- createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {- type: 'EntityReference',- value: [{ entity_type: 'USER', entity_id: 'user-1' }],- }),- ],- });-- expect(- matchesTaskSubFilters(taskWithNoAssignees, {- assigneeFilter: [NO_ASSIGNEE],- })- ).toBe(true);-- expect(- matchesTaskSubFilters(taskWithAssignee, { assigneeFilter: [NO_ASSIGNEE] })- ).toBe(false);- });-- it('matches both unassigned and specific assignees when both filters are active', () => {- const taskWithNoAssignees = createTask({- properties: [- createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {- type: 'EntityReference',- value: [],- }),- ],- });-- const taskWithUser1 = createTask({- properties: [- createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {- type: 'EntityReference',- value: [{ entity_type: 'USER', entity_id: 'user-1' }],- }),- ],- });-- const taskWithUser2 = createTask({- properties: [- createSoupProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES, {- type: 'EntityReference',- value: [{ entity_type: 'USER', entity_id: 'user-2' }],- }),- ],- });-- const combinedFilter = [NO_ASSIGNEE, 'user-1'];-- expect(- matchesTaskSubFilters(taskWithNoAssignees, {- assigneeFilter: combinedFilter,- })- ).toBe(true);-- expect(- matchesTaskSubFilters(taskWithUser1, { assigneeFilter: combinedFilter })- ).toBe(true);-- expect(- matchesTaskSubFilters(taskWithUser2, { assigneeFilter: combinedFilter })- ).toBe(false);- });-});diff --git a/js/app/packages/app/component/next-soup/soup-view/task-sub-filter-matcher.ts b/js/app/packages/app/component/next-soup/soup-view/task-sub-filter-matcher.tsdeleted file mode 100644index 690f180899..0000000000--- a/js/app/packages/app/component/next-soup/soup-view/task-sub-filter-matcher.ts+++ /dev/null@@ -1,45 +0,0 @@-import { getTaskAssigneeIds } from '@entity/utils/task-properties';-import type { TaskEntityWithProperties } from '@entity/types/entity';--export const NO_ASSIGNEE = 'NO_ASSIGNEE';--type TaskSubFilters = {- assigneeFilter?: string[];-};--export const matchesTaskSubFilters = (- taskEntity: TaskEntityWithProperties,- filters: TaskSubFilters-): boolean => {- const { assigneeFilter } = filters;-- const hasAssigneeFilter = assigneeFilter && assigneeFilter.length > 0;-- if (!hasAssigneeFilter) {- return true;- }-- // Search-service task entities can be returned without properties.- // Keep them until property data is available so valid search hits aren't dropped.- if (!taskEntity.properties) {- return true;- }-- if (hasAssigneeFilter) {- const taskAssignees = getTaskAssigneeIds(taskEntity);- const includesNoAssignee = assigneeFilter.includes(NO_ASSIGNEE);- const hasNoAssignees = taskAssignees.length === 0;-- // Match if task has no assignees and NO_ASSIGNEE filter is active- if (includesNoAssignee && hasNoAssignees) {- return true;- }-- // Match if any of the task's assignees are in the filter- if (!taskAssignees.some((id) => assigneeFilter.includes(id))) {- return false;- }- }-- return true;-};diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsxindex 2cc1ca248b..f07a523a8e 100644--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx@@ -1,5 +1,5 @@import { useAnalytics } from '@app/component/analytics-context';-import { getDefaultListViewPreset } from '@app/component/app-sidebar/soup-filter-presets';+import { getViewPreset } from '@app/component/app-sidebar/soup-filter-presets';import { SoupView } from '@app/component/next-soup/soup-view/soup-view';import { ChannelCompose } from '@block-channel/component/Compose';import { ComposeTask } from '@block-md/component/ComposeTask';@@ -104,12 +104,12 @@ registerComponent('inbox',withAuth(() => {usePageViewTracking('inbox');- const preset = getDefaultListViewPreset('inbox');+ const preset = getViewPreset('inbox');return (<SoupViewviewName="Inbox"- queryFilters={preset.queryFilters}- initialClientFilters={preset.clientFilters}+ initialFilters={preset?.filters}+ initialClientFilters={preset?.clientFilters}disableLocalSearch/>);@@ -121,7 +121,7 @@ registerComponent(withAuth(() => {usePageViewTracking('agents');const user = useUserContext();- const preset = getDefaultListViewPreset('agents', {+ const preset = getViewPreset('agents', undefined, {userId: user.userId(),email: user.email(),});@@ -129,8 +129,8 @@ registerComponent(return (<SoupViewviewName="Agents"- queryFilters={preset.queryFilters}- initialClientFilters={preset.clientFilters}+ initialFilters={preset?.filters}+ initialClientFilters={preset?.clientFilters}additionalEntities={automationEntities}/>);@@ -141,12 +141,12 @@ registerComponent('mail',withAuth(() => {usePageViewTracking('mail');- const preset = getDefaultListViewPreset('mail');+ const preset = getViewPreset('mail');return (<SoupViewviewName="Email"- queryFilters={preset.queryFilters}- initialClientFilters={preset.clientFilters}+ initialFilters={preset?.filters}+ initialClientFilters={preset?.clientFilters}/>);})@@ -157,15 +157,15 @@ registerComponent(withAuth(() => {usePageViewTracking('documents');const user = useUserContext();- const preset = getDefaultListViewPreset('documents', {+ const preset = getViewPreset('documents', undefined, {userId: user.userId(),email: user.email(),});return (<SoupViewviewName="Documents"- queryFilters={preset.queryFilters}- initialClientFilters={preset.clientFilters}+ initialFilters={preset?.filters}+ initialClientFilters={preset?.clientFilters}/>);})@@ -176,15 +176,15 @@ registerComponent(withAuth(() => {usePageViewTracking('tasks');const user = useUserContext();- const preset = getDefaultListViewPreset('tasks', {+ const preset = getViewPreset('tasks', undefined, {userId: user.userId(),email: user.email(),});return (<SoupViewviewName="Tasks"- queryFilters={preset.queryFilters}- initialClientFilters={preset.clientFilters}+ initialFilters={preset?.filters}+ initialClientFilters={preset?.clientFilters}/>);})@@ -194,12 +194,12 @@ registerComponent('channels',withAuth(() => {usePageViewTracking('channels');- const preset = getDefaultListViewPreset('channels');+ const preset = getViewPreset('channels');return (<SoupViewviewName="Channels"- queryFilters={preset.queryFilters}- initialClientFilters={preset.clientFilters}+ initialFilters={preset?.filters}+ initialClientFilters={preset?.clientFilters}/>);})@@ -209,12 +209,12 @@ registerComponent('calls',withAuth(() => {usePageViewTracking('calls');- const preset = getDefaultListViewPreset('calls');+ const preset = getViewPreset('calls');return (<SoupViewviewName="Calls"- queryFilters={preset.queryFilters}- initialClientFilters={preset.clientFilters}+ initialFilters={preset?.filters}+ initialClientFilters={preset?.clientFilters}/>);})@@ -225,15 +225,15 @@ registerComponent(withAuth(() => {usePageViewTracking('folders');const user = useUserContext();- const preset = getDefaultListViewPreset('folders', {+ const preset = getViewPreset('folders', undefined, {userId: user.userId(),email: user.email(),});return (<SoupViewviewName="Folders"- queryFilters={preset.queryFilters}- initialClientFilters={preset.clientFilters}+ initialFilters={preset?.filters}+ initialClientFilters={preset?.clientFilters}/>);})@@ -243,16 +243,12 @@ registerComponent('search',withAuth(() => {usePageViewTracking('search');- const user = useUserContext();- const preset = getDefaultListViewPreset('search', {- userId: user.userId(),- email: user.email(),- });+ const preset = getViewPreset('search');return (<SoupViewviewName="Search"- queryFilters={preset.queryFilters}- initialClientFilters={preset.clientFilters}+ initialFilters={preset?.filters}+ initialClientFilters={preset?.clientFilters}/>);})diff --git a/js/app/packages/app/component/split-layout/components/SplitPanel.tsx b/js/app/packages/app/component/split-layout/components/SplitPanel.tsxindex 22271b7d24..04166d5da3 100644--- a/js/app/packages/app/component/split-layout/components/SplitPanel.tsx+++ b/js/app/packages/app/component/split-layout/components/SplitPanel.tsx@@ -62,7 +62,7 @@ export function SplitPanel(props: SplitPanelProps) {});const nextSoup = createSoupState({- initialFilters: ['explicit-noise'],+ initialPredicates: { and: ['explicit-noise'] },});return (diff --git a/js/app/packages/block-project/component/Block.tsx b/js/app/packages/block-project/component/Block.tsxindex 07978d0329..37b2d0689d 100644--- a/js/app/packages/block-project/component/Block.tsx+++ b/js/app/packages/block-project/component/Block.tsx@@ -29,8 +29,7 @@ import {} from '@app/component/next-soup/create-soup-state';import { SoupViewContextProvider } from '@app/component/next-soup/soup-view/soup-view-context';import { SoupViewList } from '@app/component/next-soup/soup-view/soup-view';-import { NIL_UUID } from '@app/component/next-soup/filters/query-filters';-import { SharedEmailFilter } from '@service-storage/generated/schemas';+import { defineQueryFilters } from '@app/component/next-soup/filters/filter-store';// HACK: prevent lint error on custom directivefalse && fileFolderDrop;@@ -112,14 +111,14 @@ const Block: Component = () => {}const projectSoup = createSoupState({- initialFilters: ['project-content'],- filterConfigs: [+ initialPredicates: { and: ['project-content'] },+ predicateConfigs: [{id: 'project-content',- predicate: (entity) => PROJECT_ENTITY_TYPES.includes(entity.type),+ predicate: (entity: { type: string }) =>+ PROJECT_ENTITY_TYPES.includes(entity.type),},],- filterGroups: [],});const [attachHotkeys, projectViewScope] = useHotkeyDOMScope('project-view');@@ -184,24 +183,18 @@ const ProjectEntityList = (props: {<SoupContextProvider soup={props.soup}><SoupViewContextProvidersoup={props.soup}- queryFilters={{- channel_filters: {- channel_ids: [NIL_UUID],+ initialQuery={defineQueryFilters({+ include: {+ // Filter documents by project+ projectId: [props.projectId],+ // Filter chats by project+ chatProjectId: [props.projectId],+ // Filter projects by project (current project only)+ folderId: [props.projectId],+ // Filter emails by project+ emailProjectId: [props.projectId],},- chat_filters: {- project_ids: [props.projectId],- },- project_filters: {- project_ids: [props.projectId],- },- document_filters: {- project_ids: [props.projectId],- },- email_filters: {- project_ids: [props.projectId],- shared: SharedEmailFilter.include,- },- }}+ })}><SoupViewList customScrollbarHidden={true} scopeId={props.scopeId} /></SoupViewContextProvider>diff --git a/js/app/packages/queries/soup/items.ts b/js/app/packages/queries/soup/items.tsindex 22d190f9d8..750f279691 100644--- a/js/app/packages/queries/soup/items.ts+++ b/js/app/packages/queries/soup/items.ts@@ -6,8 +6,10 @@ import { mapSoupPageToEntityList } from '@queries/soup/transform-utils';import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';import { storageServiceClient } from '@service-storage/client';import type { SoupApiItem } from '@service-storage/generated/schemas';+import type { EntityFilterAst } from '@service-storage/generated/schemas/entityFilterAst';import type { EntityFilters } from '@service-storage/generated/schemas/entityFilters';import type { Params } from '@service-storage/generated/schemas/params';+import type { PostSoupAstRequestAllOf } from '@service-storage/generated/schemas/postSoupAstRequestAllOf';import type { PostSoupRequest } from '@service-storage/generated/schemas/postSoupRequest';import {useInfiniteQuery,@@ -27,6 +29,15 @@ export type SoupItemsQueryArgs = {body: SoupBody;};+export type SoupAstParams = Params;++export type SoupAstBody = EntityFilterAst & PostSoupAstRequestAllOf;++export type SoupAstItemsQueryArgs = {+ params: SoupAstParams;+ body: SoupAstBody;+};+export type UseSoupQueryResult = UseInfiniteQueryResult<EntityData[], Error>;export type SoupApiItemFilter = (item: SoupApiItem) => boolean;@@ -79,3 +90,41 @@ export const useSoupItemsQuery = (meta: { itemFilter, normalize: true },}));};++export const useSoupAstItemsQuery = (+ args: Accessor<SoupAstItemsQueryArgs>,+ options?: Accessor<SoupItemsQueryOptions>+) => {+ const instructionsIdQuery = useInstructionsMdIdQuery();++ return useInfiniteQuery(() => ({+ queryKey: soupKeys.astItems(args()).queryKey,+ queryFn: async (ctx) => {+ const { params, body } = args();++ return throwOnErr(+ async () =>+ await storageServiceClient.getSoupAstItems({+ params: { cursor: ctx.pageParam },+ body: {+ ...body,+ ...params,+ },+ })+ );+ },+ initialPageParam: null as string | null,+ getNextPageParam: (lastPage) => {+ return lastPage.next_cursor;+ },+ select: (data) => {+ return data.pages.flatMap((page) => {+ return mapSoupPageToEntityList(page, { instructionsIdQuery });+ });+ },+ enabled: options?.().enabled,+ staleTime: options?.().staleTime,+ placeholderData: (p) => p,+ meta: { normalize: true },+ }));+};diff --git a/js/app/packages/queries/soup/keys.ts b/js/app/packages/queries/soup/keys.tsindex b3324797c5..f6209be225 100644--- a/js/app/packages/queries/soup/keys.ts+++ b/js/app/packages/queries/soup/keys.ts@@ -1,11 +1,14 @@import { createQueryKeys } from '@lukemorales/query-key-factory';-import type { SoupItemsQueryArgs } from './items';+import type { SoupAstItemsQueryArgs, SoupItemsQueryArgs } from './items';import type { SearchSoupQueryArgs } from './search';export const soupKeys = createQueryKeys('soup', {items: (args: SoupItemsQueryArgs) => ({queryKey: [args.params, args.body],}),+ astItems: (args: SoupAstItemsQueryArgs) => ({+ queryKey: [args.params, args.body],+ }),search: (args: SearchSoupQueryArgs) => ({queryKey: [args.params, args.body],}),diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.tsindex 84643d5ff8..8a290386ab 100644--- a/js/app/packages/service-clients/service-storage/client.ts+++ b/js/app/packages/service-clients/service-storage/client.ts@@ -34,6 +34,7 @@ import type { IDocumentStorageServiceFile } from '@filesystem/file';import { platformFetch } from 'core/util/platformFetch';import type {AccessLevel,+ PostSoupAstRequest,CallRecordPreview,PostSoupRequest,SoupPage,@@ -235,6 +236,20 @@ export const storageServiceClient = {});},+ async getSoupAstItems(args: {+ params: { cursor?: string | null };+ body: PostSoupAstRequest;+ }) {+ const searchParams = args.params.cursor+ ? `?cursor=${args.params.cursor}`+ : '';++ return await dssFetch<SoupPage>(`/items/soup/ast${searchParams}`, {+ method: 'POST',+ body: JSON.stringify(args.body),+ });+ },+permissionsTokens: {// Uses SYNC_PERMISSION_TOKEN_DSS_HOST instead of dssFetch so that tokens are// always signed by the DSS whose JWT secret matches the sync service's secret.