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(search): unify search filters with soup (#2230)
gbirmane6d2f23f1ddc
diff --git a/js/app/packages/app/component/next-soup/filters/configs.ts b/js/app/packages/app/component/next-soup/filters/configs.tsindex 5483338c45..da5ad2a917 100644--- a/js/app/packages/app/component/next-soup/filters/configs.ts+++ b/js/app/packages/app/component/next-soup/filters/configs.ts@@ -427,4 +427,4 @@ export const SOUP_FILTER_GROUPS: FilterGroupConfig[] = [type SoupFilter = ReturnType<typeof createSoupFilters>[number];-export type FilterID = Extract<SoupFilter, { id: string & {} }>['id'];+export type FilterID = Extract<SoupFilter, { id: string }>['id'];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 9471536dbd..6f6c6bf422 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,4 +1,3 @@-import { codeFileExtensions } from '@block-code/util/languageSupport';import type { SoupItemsQueryFilters, SoupBody } from '@queries/soup/items';import { ChannelTypeEnum } from '@service-comms/client';import type { SoupApiItem } from '@service-storage/generated/schemas';@@ -68,24 +67,9 @@ export function filterSoupItemByRequestBody(.exhaustive();}-export const FILE_ASSOCIATION_TYPES = [- 'code',- 'image',- 'pdf',- 'unknown',-] as const;--/** Expands file association types to file extensions for soup or search */-export const getFileAssociations = (type: 'soup' | 'search') => {- return FILE_ASSOCIATION_TYPES.flatMap((fileType) => {- if (fileType === 'code')- return type === 'soup' ? ['assoc:code'] : codeFileExtensions;- if (fileType === 'image')- return type === 'soup' ? ['assoc:image'] : [NIL_UUID];- if (fileType === 'unknown')- return type === 'soup' ? ['assoc:other'] : [NIL_UUID];- return [fileType];- });+/** File types or associations for soup */+export const getFileAssociations = () => {+ return ['assoc:code', 'assoc:image', 'assoc:other', 'pdf'];};export const QUERY_FILTERS = {@@ -147,7 +131,7 @@ export const QUERY_FILTERS = {channel_filters: { channel_ids: EXCLUDE },chat_filters: { chat_ids: EXCLUDE },email_filters: { recipients: EXCLUDE },- document_filters: { file_types: getFileAssociations('soup') },+ document_filters: { file_types: getFileAssociations() },},documentAndFile: {@@ -155,7 +139,7 @@ export const QUERY_FILTERS = {chat_filters: { chat_ids: EXCLUDE },email_filters: { recipients: EXCLUDE },document_filters: {- file_types: ['md', 'canvas', 'docx', ...getFileAssociations('soup')],+ file_types: ['md', 'canvas', 'docx', ...getFileAssociations()],},},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 c8c59a907a..1e6086877e 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,6 +1,4 @@import type { SoupState } from '@app/component/next-soup/create-soup-state';-import type { FilterID } from '@app/component/next-soup/filters/configs';-import { getFileAssociations } from '@app/component/next-soup/filters/query-filters';import { useSearchContext } from '@app/component/next-soup/search-context';import {createSoupFreshSearch,@@ -8,7 +6,6 @@ import {intersectEntityPools,nameFuzzySearchFilter,} from '@app/component/next-soup/search-utils';-import { arrayEquals } from '@core/util/compareUtils';import { debouncedDependent } from '@core/util/debounce';import type { EntityData } from '@entity';import type { SoupItemsQueryFilters } from '@queries/soup/items';@@ -16,12 +13,8 @@ import {useSearchSoupQuery,validateSearchServiceText,} from '@queries/soup/search';-import type {- UnifiedSearchIndex,- UnifiedSearchRequest,-} from '@service-search/generated/models';+import type { UnifiedSearchRequest } from '@service-search/generated/models';import { type Accessor, createMemo, createSignal, on } from 'solid-js';-import { match } from 'ts-pattern';const SEARCH_SERVICE_DEBOUNCE_MS = 300;const LOCAL_FUZZY_SEARCH_DEBOUNCE_MS = 20;@@ -58,80 +51,17 @@ export const createSearchState = ({() => trimmedSearchText() === debouncedSearchForService());- const unifiedSearchIncludeArray = createMemo<UnifiedSearchIndex[]>(- () => {- const types = soup.filters.activeIds() as FilterID[];- const includeArray: UnifiedSearchIndex[] = [];- for (const type of types) {- match(type)- .with('file-folder', () => {- // TODO: distinguish between document and project requests- includeArray.push('documents');- includeArray.push('projects');- })- .with('document', 'task', () => {- includeArray.push('documents');- })- .with('agent', () => {- includeArray.push('chats');- })- .with('people', 'teams', 'channels', () => {- includeArray.push('channels');- })- .with('email', () => {- includeArray.push('emails');- })- .otherwise(() => {});- }- return Array.from(new Set(includeArray));- },- [],- { equals: arrayEquals }- );-const isSearchServiceDisabled = createMemo(() => !validateSearchServiceText(debouncedSearchForService()));- const searchFilters = createMemo(() => {- const {- channel_filters,- chat_filters,- document_filters,- email_filters,- project_filters,- } = queryFilters();-- let fileTypes = document_filters?.file_types;-- if (soup.filters.isActive('file-folder')) {- fileTypes = getFileAssociations('search');- }-- // NOTE: the garbage UUID filters are excluded by the include array anyways so they no-op- return {- channel: channel_filters,- chat: chat_filters,- document: { ...document_filters, file_types: fileTypes },- email: email_filters,- project: project_filters,- };- });-const searchUnifiedNameContentRequest = createMemo(- (): UnifiedSearchRequest => {- const query = debouncedSearchForService();- const include = unifiedSearchIncludeArray();- const filters = searchFilters();-- return {- search_on: 'name_content',- match_type: 'partial',- query,- include,- filters,- };- }+ (): UnifiedSearchRequest => ({+ search_on: 'name_content',+ match_type: 'partial',+ query: debouncedSearchForService(),+ filters: queryFilters(),+ }));const searchQuery = useSearchSoupQuery(diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/filter-controls.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/filter-controls.tsxindex d6308bdae4..4a0ace426d 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/filter-controls.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/filter-controls.tsx@@ -151,7 +151,7 @@ const getEntityTypeQueryFilters = (fileTypes.push('md');}if (includesFiles) {- fileTypes.push(...getFileAssociations('soup'));+ fileTypes.push(...getFileAssociations());}result.document_filters = {...currentFilters.document_filters,diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEmailSearchMention.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEmailSearchMention.tsindex 2f69627f66..aa88cf0d67 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEmailSearchMention.ts+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEmailSearchMention.ts@@ -2,6 +2,7 @@ import type { Accessor } from 'solid-js';import { createLazyMemo } from '@solid-primitives/memo';import type { EntityItem } from '@core/context/quickAccess';import { createFreshSearch } from '@core/util/freshSort';+import { QUERY_FILTERS_BASE } from '@app/component/next-soup/filters/query-filters';import {type SearchSoupQueryArgs,useSearchSoupQuery,@@ -34,8 +35,11 @@ export function useEmailSearchMention(body: {match_type: 'partial',search_on: 'name',- include: ['emails'],query: searchTerm(),+ filters: {+ ...QUERY_FILTERS_BASE,+ email_filters: undefined,+ },},};});diff --git a/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts b/js/app/packages/service-clients/service-search/generated/models/entityFilters.tsnew file mode 100644index 0000000000..d050177011--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts@@ -0,0 +1,30 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { ChannelFilters } from './channelFilters';+import type { ChatFilters } from './chatFilters';+import type { DocumentFilters } from './documentFilters';+import type { EmailFilters } from './emailFilters';+import type { ProjectFilters } from './projectFilters';+import type { PropertyFilter } from './propertyFilter';++/**+ * a bundle of all of the filters for each entity type+ */+export interface EntityFilters {+ /** the bundled [ChannelFilters] */+ channel_filters?: ChannelFilters;+ /** the bundled [ChatFilters] */+ chat_filters?: ChatFilters;+ /** the bundled [DocumentFilters] */+ document_filters?: DocumentFilters;+ /** the bundled [EmailFilters] */+ email_filters?: EmailFilters;+ /** the bundled [ProjectFilters] */+ project_filters?: ProjectFilters;+ /** property-based filters applied across entity types */+ property_filters?: PropertyFilter[];+}diff --git a/js/app/packages/service-clients/service-search/generated/models/index.ts b/js/app/packages/service-clients/service-search/generated/models/index.tsindex 7995c047eb..192b49d4c2 100644--- a/js/app/packages/service-clients/service-search/generated/models/index.ts+++ b/js/app/packages/service-clients/service-search/generated/models/index.ts@@ -102,6 +102,7 @@ export * from './emailSearchResultMessageId';export * from './emailSearchResultScore';export * from './emailSearchResultSentAt';export * from './emptyResponse';+export * from './entityFilters';export * from './entityReference';export * from './entityReferenceSpecificMessageId';export * from './entityType';@@ -132,6 +133,8 @@ export * from './projectSearchResult';export * from './projectSearchResultScore';export * from './propertyDefinition';export * from './propertyDefinitionSpecificEntityType';+export * from './propertyFilter';+export * from './propertyFilterEntityType';export * from './propertyOwner';export * from './propertyOwnerOneOf';export * from './propertyOwnerOneOfFive';@@ -226,17 +229,9 @@ export * from './soupProperty';export * from './soupPropertyValue';export * from './taskFilters';export * from './taskFiltersIncludeCbmAtmNc';-export * from './unifiedSearchFilters';-export * from './unifiedSearchFiltersChannel';-export * from './unifiedSearchFiltersChat';-export * from './unifiedSearchFiltersDocument';-export * from './unifiedSearchFiltersEmail';-export * from './unifiedSearchFiltersProject';-export * from './unifiedSearchIndex';export * from './unifiedSearchParams';export * from './unifiedSearchRequest';export * from './unifiedSearchRequestCollapse';-export * from './unifiedSearchRequestFilters';export * from './unifiedSearchResponse';export * from './unifiedSearchResponseItem';export * from './unifiedSearchResponseItemOneOf';diff --git a/js/app/packages/service-clients/service-search/generated/models/propertyFilter.ts b/js/app/packages/service-clients/service-search/generated/models/propertyFilter.tsnew file mode 100644index 0000000000..ffd37959cb--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/propertyFilter.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { PropertyFilterEntityType } from './propertyFilterEntityType';++/**+ * A single property-based filter condition.++Each filter targets a specific property definition on entities of a given type,+matching against select option UUIDs or entity reference IDs.+Multiple values within a single filter are OR'd together.+Multiple filters are AND'd together.+ */+export interface PropertyFilter {+ /** Entity reference IDs to match. Multiple values are OR'd together. */+ entity_ids?: string[];+ /** The entity type for the property lookup (e.g., "TASK", "DOCUMENT", "PROJECT").+When None, matches across all entity types. */+ entity_type?: PropertyFilterEntityType;+ /** Select option UUIDs to match. Multiple values are OR'd together. */+ option_ids?: string[];+ /** The UUID of the property definition to filter on. */+ property_definition_id: string;+}diff --git a/js/app/packages/service-clients/service-search/generated/models/propertyFilterEntityType.ts b/js/app/packages/service-clients/service-search/generated/models/propertyFilterEntityType.tsnew file mode 100644index 0000000000..8eea60886b--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/propertyFilterEntityType.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The entity type for the property lookup (e.g., "TASK", "DOCUMENT", "PROJECT").+When None, matches across all entity types.+ */+export type PropertyFilterEntityType = string | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFilters.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFilters.tsdeleted file mode 100644index d71272b1be..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFilters.ts+++ /dev/null@@ -1,19 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */-import type { UnifiedSearchFiltersChannel } from './unifiedSearchFiltersChannel';-import type { UnifiedSearchFiltersChat } from './unifiedSearchFiltersChat';-import type { UnifiedSearchFiltersDocument } from './unifiedSearchFiltersDocument';-import type { UnifiedSearchFiltersEmail } from './unifiedSearchFiltersEmail';-import type { UnifiedSearchFiltersProject } from './unifiedSearchFiltersProject';--export interface UnifiedSearchFilters {- channel?: UnifiedSearchFiltersChannel;- chat?: UnifiedSearchFiltersChat;- document?: UnifiedSearchFiltersDocument;- email?: UnifiedSearchFiltersEmail;- project?: UnifiedSearchFiltersProject;-}diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersChannel.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersChannel.tsdeleted file mode 100644index 7076e6440a..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersChannel.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */-import type { ChannelFilters } from './channelFilters';--export type UnifiedSearchFiltersChannel = null | ChannelFilters;diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersChat.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersChat.tsdeleted file mode 100644index d231f791f5..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersChat.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */-import type { ChatFilters } from './chatFilters';--export type UnifiedSearchFiltersChat = null | ChatFilters;diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersDocument.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersDocument.tsdeleted file mode 100644index cf75dda6cb..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersDocument.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */-import type { DocumentFilters } from './documentFilters';--export type UnifiedSearchFiltersDocument = null | DocumentFilters;diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersEmail.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersEmail.tsdeleted file mode 100644index c8c56b73c1..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersEmail.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */-import type { EmailFilters } from './emailFilters';--export type UnifiedSearchFiltersEmail = null | EmailFilters;diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersProject.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersProject.tsdeleted file mode 100644index 8fe2cd127e..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchFiltersProject.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */-import type { ProjectFilters } from './projectFilters';--export type UnifiedSearchFiltersProject = null | ProjectFilters;diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchIndex.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchIndex.tsdeleted file mode 100644index abf4739162..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchIndex.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */--export type UnifiedSearchIndex =- (typeof UnifiedSearchIndex)[keyof typeof UnifiedSearchIndex];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const UnifiedSearchIndex = {- documents: 'documents',- chats: 'chats',- emails: 'emails',- channels: 'channels',- projects: 'projects',-} as const;diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequest.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequest.tsindex 570ea36edb..6df00bef2d 100644--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequest.ts+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequest.ts@@ -5,17 +5,15 @@* OpenAPI spec version: 0.1.0*/+import type { EntityFilters } from './entityFilters';import type { MatchType } from './matchType';import type { SearchOn } from './searchOn';-import type { UnifiedSearchIndex } from './unifiedSearchIndex';import type { UnifiedSearchRequestCollapse } from './unifiedSearchRequestCollapse';-import type { UnifiedSearchRequestFilters } from './unifiedSearchRequestFilters';export interface UnifiedSearchRequest {collapse?: UnifiedSearchRequestCollapse;- filters?: UnifiedSearchRequestFilters;- /** Include specific entity types from search. If empty, all entity types will be searched over. If you are unsure which types to search, use an empty array to search all. */- include?: UnifiedSearchIndex[];+ /** Entity filters in the same shape as soup. Entity types with a NIL UUID in their primary ID field are excluded from search. */+ filters?: EntityFilters;/** How to match the search terms. 'exact' for precise case-sensitive phrase matches, 'partial' for prefix/partial matches. REQUIRED field. */match_type: MatchType;/** The search query string. Must be at least 3 characters. */diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequestFilters.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequestFilters.tsdeleted file mode 100644index 3a69b426a3..0000000000--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchRequestFilters.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * search_service- * OpenAPI spec version: 0.1.0- */-import type { UnifiedSearchFilters } from './unifiedSearchFilters';--export type UnifiedSearchRequestFilters = null | UnifiedSearchFilters;diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex 3d62e97388..58f9d559f3 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -1220,6 +1220,39 @@"type": "object","description": "Empty response is required due to custom fetch forcing `response.json()`"},+ "EntityFilters": {+ "type": "object",+ "description": "a bundle of all of the filters for each entity type",+ "properties": {+ "channel_filters": {+ "$ref": "#/components/schemas/ChannelFilters",+ "description": "the bundled [ChannelFilters]"+ },+ "chat_filters": {+ "$ref": "#/components/schemas/ChatFilters",+ "description": "the bundled [ChatFilters]"+ },+ "document_filters": {+ "$ref": "#/components/schemas/DocumentFilters",+ "description": "the bundled [DocumentFilters]"+ },+ "email_filters": {+ "$ref": "#/components/schemas/EmailFilters",+ "description": "the bundled [EmailFilters]"+ },+ "project_filters": {+ "$ref": "#/components/schemas/ProjectFilters",+ "description": "the bundled [ProjectFilters]"+ },+ "property_filters": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/PropertyFilter"+ },+ "description": "property-based filters applied across entity types"+ }+ }+ },"EntityReference": {"type": "object","description": "Entity reference for entity-type property values.",@@ -1974,6 +2007,35 @@}}},+ "PropertyFilter": {+ "type": "object",+ "description": "A single property-based filter condition.\n\nEach filter targets a specific property definition on entities of a given type,\nmatching against select option UUIDs or entity reference IDs.\nMultiple values within a single filter are OR'd together.\nMultiple filters are AND'd together.",+ "required": ["property_definition_id"],+ "properties": {+ "entity_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Entity reference IDs to match. Multiple values are OR'd together."+ },+ "entity_type": {+ "type": ["string", "null"],+ "description": "The entity type for the property lookup (e.g., \"TASK\", \"DOCUMENT\", \"PROJECT\").\nWhen None, matches across all entity types."+ },+ "option_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Select option UUIDs to match. Multiple values are OR'd together."+ },+ "property_definition_id": {+ "type": "string",+ "description": "The UUID of the property definition to filter on."+ }+ }+ },"PropertyOwner": {"oneOf": [{@@ -3147,70 +3209,6 @@}}},- "UnifiedSearchFilters": {- "type": "object",- "properties": {- "channel": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/ChannelFilters",- "description": "Channel filters. `null` to not filter channels searched over."- }- ]- },- "chat": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/ChatFilters",- "description": "Chat filters. `null` to not filter chats searched over."- }- ]- },- "document": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/DocumentFilters",- "description": "Document filters. `null` to not filter documents searched over."- }- ]- },- "email": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/EmailFilters",- "description": "Email filters. `null` to not filter emails searched over."- }- ]- },- "project": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/ProjectFilters",- "description": "Project filters. `null` to not filter projects searched over."- }- ]- }- }- },- "UnifiedSearchIndex": {- "type": "string",- "enum": ["documents", "chats", "emails", "channels", "projects"]- },"UnifiedSearchRequest": {"type": "object","required": ["query", "match_type"],@@ -3219,22 +3217,8 @@"type": ["boolean", "null"]},"filters": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/UnifiedSearchFilters",- "description": "Search filters for various kinds of items. Set the entire filters property as `null` if you do not have specific filters for a given type, e.g. bcc for email filters."- }- ]- },- "include": {- "type": "array",- "items": {- "$ref": "#/components/schemas/UnifiedSearchIndex"- },- "description": "Include specific entity types from search. If empty, all entity types will be searched over. If you are unsure which types to search, use an empty array to search all."+ "$ref": "#/components/schemas/EntityFilters",+ "description": "Entity filters in the same shape as soup. Entity types with a NIL UUID in their primary ID field are excluded from search."},"match_type": {"$ref": "#/components/schemas/MatchType",diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 23262db6ec..dc774419b9 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -4382,6 +4382,7 @@ dependencies = ["models_email","regex","reqwest",+ "serde","serde_json","tokio","tracing",@@ -6467,6 +6468,7 @@ dependencies = ["chrono","document_sub_type","item_filters",+ "model_file_type","models_opensearch","models_soup","opensearch_client",diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs b/rust/cloud-storage/ai_tools/src/search/search_service/content.rsindex d5c21b57d1..1c4e522a95 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs@@ -1,10 +1,10 @@use super::types::{PAGE_SIZE, SearchToolResponse};use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;-use item_filters::EmailFilters;+use item_filters::{EmailFilters, EntityFilters};use models_search::{MatchType,- unified::{UnifiedSearchFilters, UnifiedSearchIndex, UnifiedSearchRequest},+ unified::{UnifiedSearchIndex, UnifiedSearchRequest, entity_filters_from_include},};use schemars::JsonSchema;use search_service_client::SearchServiceClient;@@ -49,19 +49,19 @@ impl AsyncTool<Arc<SearchServiceClient>> for ContentSearch {});}+ let base_filters = EntityFilters {+ email_filters: EmailFilters {+ importance: Some(true),+ ..Default::default()+ },+ ..Default::default()+ };let search_request = UnifiedSearchRequest {query: self.query.to_owned(),match_type: MatchType::Partial,- filters: Some(UnifiedSearchFilters {- email: Some(EmailFilters {- importance: Some(true),- ..Default::default()- }),- ..Default::default()- }),+ filters: entity_filters_from_include(self.entity_types.clone(), base_filters),search_on: models_search::SearchOn::Content,collapse: Some(true),- include: self.entity_types.clone(),};let response = search_clientdiff --git a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs b/rust/cloud-storage/ai_tools/src/search/search_service/name.rsindex a57070f058..cb4fd087aa 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs@@ -1,10 +1,10 @@use super::types::{PAGE_SIZE, SearchToolResponse};use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;-use item_filters::EmailFilters;+use item_filters::{EmailFilters, EntityFilters};use models_search::{MatchType,- unified::{UnifiedSearchFilters, UnifiedSearchIndex, UnifiedSearchRequest},+ unified::{UnifiedSearchIndex, UnifiedSearchRequest, entity_filters_from_include},};use schemars::JsonSchema;use search_service_client::SearchServiceClient;@@ -49,19 +49,19 @@ impl AsyncTool<Arc<SearchServiceClient>> for NameSearch {});}+ let base_filters = EntityFilters {+ email_filters: EmailFilters {+ importance: Some(true),+ ..Default::default()+ },+ ..Default::default()+ };let search_request = UnifiedSearchRequest {query: self.name.to_owned(),match_type: MatchType::Partial,- filters: Some(UnifiedSearchFilters {- email: Some(EmailFilters {- importance: Some(true),- ..Default::default()- }),- ..Default::default()- }),+ filters: entity_filters_from_include(self.entity_types.clone(), base_filters),search_on: models_search::SearchOn::Name,collapse: Some(true),- include: self.entity_types.clone(),};let response = search_clientdiff --git a/rust/cloud-storage/item_filters/src/ast/document.rs b/rust/cloud-storage/item_filters/src/ast/document.rsindex c6be04b464..7cb2d246ff 100644--- a/rust/cloud-storage/item_filters/src/ast/document.rs+++ b/rust/cloud-storage/item_filters/src/ast/document.rs@@ -126,6 +126,20 @@ fn format(s: &str) -> IResult<&str, impl Iterator<Item = FileType>> {Ok((rest, out))}+/// Resolve a file type string to concrete [FileType] variants.+/// Handles both plain extensions (e.g. `"md"`, `"pdf"`) and `assoc:*` prefixes+/// (e.g. `"assoc:code"`, `"assoc:other"`). Returns an empty vec if the string+/// is not a recognized extension or association.+pub fn resolve_file_types(s: &str) -> Vec<FileType> {+ if let Ok(ft) = FileType::from_str(s) {+ return vec![ft];+ }+ match format(s) {+ Ok((_, iter)) => iter.collect(),+ Err(_) => vec![],+ }+}+fn create_file_iter(s: &str) -> impl Iterator<Item = Result<FileType, ValueError<FileType>>> {match FileType::from_str(s) {Ok(f) => Either::Left(Some(Ok(f)).into_iter()),diff --git a/rust/cloud-storage/models_search/Cargo.toml b/rust/cloud-storage/models_search/Cargo.tomlindex e4e02982ff..2171bc631d 100644--- a/rust/cloud-storage/models_search/Cargo.toml+++ b/rust/cloud-storage/models_search/Cargo.toml@@ -7,6 +7,7 @@ version = "0.1.0"[dependencies]chrono = { workspace = true }item_filters = { path = "../item_filters", features = ["schema"] }+model_file_type = { path = "../model_file_type" }models_opensearch = { path = "../models_opensearch" }opensearch_client = { path = "../opensearch_client" }schemars = { workspace = true }diff --git a/rust/cloud-storage/models_search/src/unified.rs b/rust/cloud-storage/models_search/src/unified.rsindex acd6f0477a..5769d7218c 100644--- a/rust/cloud-storage/models_search/src/unified.rs+++ b/rust/cloud-storage/models_search/src/unified.rs@@ -1,5 +1,4 @@use chrono::{DateTime, Utc};-use std::collections::HashSet;use uuid::Uuid;use crate::channel::ChannelSearchResponseItemWithMetadata;@@ -12,7 +11,11 @@ use crate::{chat::SimpleChatSearchResponseBaseItem, document::SimpleDocumentSearchResponseBaseItem,email::SimpleEmailSearchResponseBaseItem, project::SimpleProjectSearchResponseBaseItem,};-use item_filters::{ChannelFilters, ChatFilters, DocumentFilters, EmailFilters, ProjectFilters};+use item_filters::{+ ChannelFilters, ChatFilters, DocumentFilters, EmailFilters, EntityFilters, ProjectFilters,+ ast::document::resolve_file_types,+};+use model_file_type::FileAssociation;use schemars::JsonSchema;use serde::{Deserialize, Serialize};use utoipa::ToSchema;@@ -27,6 +30,38 @@ pub enum UnifiedSearchIndex {Projects,}+const NIL_UUID: &str = "00000000-0000-0000-0000-000000000000";++/// Build an [EntityFilters] from a list of [UnifiedSearchIndex] to include.+/// Entity types not in the list are excluded via NIL UUID.+/// If the list is empty, all entity types are included.+pub fn entity_filters_from_include(+ include: Vec<UnifiedSearchIndex>,+ base: EntityFilters,+) -> EntityFilters {+ if include.is_empty() {+ return base;+ }+ let exclude = vec![NIL_UUID.to_string()];+ let mut filters = base;+ if !include.contains(&UnifiedSearchIndex::Documents) {+ filters.document_filters.document_ids = exclude.clone();+ }+ if !include.contains(&UnifiedSearchIndex::Chats) {+ filters.chat_filters.chat_ids = exclude.clone();+ }+ if !include.contains(&UnifiedSearchIndex::Emails) {+ filters.email_filters.recipients = exclude.clone();+ }+ if !include.contains(&UnifiedSearchIndex::Channels) {+ filters.channel_filters.channel_ids = exclude.clone();+ }+ if !include.contains(&UnifiedSearchIndex::Projects) {+ filters.project_filters.project_ids = exclude;+ }+ filters+}+// TODO: query, match_type are common to all requests. consolidate.#[derive(Debug, Serialize, Deserialize, ToSchema, Clone, JsonSchema)]pub struct UnifiedSearchRequest {@@ -36,8 +71,9 @@ pub struct UnifiedSearchRequest {/// How to match the search terms. 'exact' for precise case-sensitive phrase matches, 'partial' for prefix/partial matches. REQUIRED field.pub match_type: MatchType,- /// Search filters for various kinds of items. Set the entire filters property as `null` if you do not have specific filters for a given type, e.g. bcc for email filters.- pub filters: Option<UnifiedSearchFilters>,+ /// Entity filters in the same shape as soup. Entity types with a NIL UUID in their primary ID field are excluded from search.+ #[serde(default)]+ pub filters: EntityFilters,/// Fields to search on (Name, Content, NameContent). Defaults to Content#[serde(default)]@@ -45,70 +81,100 @@ pub struct UnifiedSearchRequest {#[schemars(skip)]pub collapse: Option<bool>,+}- /// Include specific entity types from search. If empty, all entity types will be searched over. If you are unsure which types to search, use an empty array to search all.- #[serde(default)]- pub include: Vec<UnifiedSearchIndex>,+/// Whether a [FileAssociation] is indexed by the search processing service.+pub fn is_searchable_association(assoc: &FileAssociation) -> bool {+ matches!(+ assoc,+ FileAssociation::Pdf(_)+ | FileAssociation::Write(_)+ | FileAssociation::Code(_)+ | FileAssociation::Canvas(_)+ | FileAssociation::Md(_)+ )}-impl From<UnifiedSearchIndex> for models_opensearch::SearchEntityType {- fn from(index: UnifiedSearchIndex) -> Self {- match index {- UnifiedSearchIndex::Channels => Self::Channels,- UnifiedSearchIndex::Chats => Self::Chats,- UnifiedSearchIndex::Documents => Self::Documents,- UnifiedSearchIndex::Emails => Self::Emails,- UnifiedSearchIndex::Projects => Self::Projects,- }- }+/// Converted entity filters for the search service.+/// Determines which entity types to include based on NIL UUID exclusion+/// and expands file association prefixes (e.g. `assoc:code`) to concrete extensions.+#[derive(Debug, Clone)]+pub struct SearchEntityFilters {+ /// Whether to include documents in search results+ pub should_include_documents: bool,+ /// Whether to include chats in search results+ pub should_include_chats: bool,+ /// Whether to include emails in search results+ pub should_include_emails: bool,+ /// Whether to include channels in search results+ pub should_include_channels: bool,+ /// Whether to include projects in search results+ pub should_include_projects: bool,+ /// Document filters with file associations expanded+ pub document_filters: DocumentFilters,+ /// Chat filters+ pub chat_filters: ChatFilters,+ /// Email filters+ pub email_filters: EmailFilters,+ /// Channel filters+ pub channel_filters: ChannelFilters,+ /// Project filters+ pub project_filters: ProjectFilters,}-/// Generates the search indices to search over for unified search-pub fn generate_unified_search_indices(- include: Vec<UnifiedSearchIndex>,-) -> HashSet<models_opensearch::SearchEntityType> {- if include.is_empty() {- let include: Vec<models_opensearch::SearchEntityType> = [- UnifiedSearchIndex::Channels,- UnifiedSearchIndex::Chats,- UnifiedSearchIndex::Documents,- UnifiedSearchIndex::Emails,- UnifiedSearchIndex::Projects,- ]- .into_iter()- .map(|i| i.into())- .collect();-- include.into_iter().collect()- } else {- include.into_iter().map(|i| i.into()).collect()- }+fn contains_nil_uuid(ids: &[String]) -> bool {+ ids.iter().any(|id| id == NIL_UUID)}-// TODO: there's a data correlation between Filters and Response Item. Can this be consolidated?-// None means do not search this entity, Some(_::default()) means search all for this entity-#[derive(Debug, Serialize, Deserialize, ToSchema, Clone, JsonSchema)]-pub struct UnifiedSearchFilters {- /// Document filters. `null` to not filter documents searched over.- pub document: Option<DocumentFilters>,- /// Chat filters. `null` to not filter chats searched over.- pub chat: Option<ChatFilters>,- /// Email filters. `null` to not filter emails searched over.- pub email: Option<EmailFilters>,- /// Channel filters. `null` to not filter channels searched over.- pub channel: Option<ChannelFilters>,- /// Project filters. `null` to not filter projects searched over.- pub project: Option<ProjectFilters>,+fn strip_nil_uuids(ids: &mut Vec<String>) {+ ids.retain(|id| id != NIL_UUID);}-impl Default for UnifiedSearchFilters {- fn default() -> Self {+/// Resolve file type strings to concrete extensions for search, dropping+/// non-searchable types. Handles both plain extensions (`"md"`) and `assoc:*`+/// prefixes (`"assoc:code"`).+fn expand_file_types_for_search(file_types: Vec<String>) -> Vec<String> {+ file_types+ .iter()+ .flat_map(|ft| resolve_file_types(ft))+ .filter(|ty| is_searchable_association(&ty.macro_app_path()))+ .map(|ty| ty.as_str().to_string())+ .collect()+}++impl From<EntityFilters> for SearchEntityFilters {+ fn from(filters: EntityFilters) -> Self {+ let mut document_filters = filters.document_filters;+ let mut chat_filters = filters.chat_filters;+ let mut email_filters = filters.email_filters;+ let mut channel_filters = filters.channel_filters;+ let mut project_filters = filters.project_filters;++ let should_include_documents = !contains_nil_uuid(&document_filters.document_ids);+ let should_include_chats = !contains_nil_uuid(&chat_filters.chat_ids);+ let should_include_emails = !contains_nil_uuid(&email_filters.recipients);+ let should_include_channels = !contains_nil_uuid(&channel_filters.channel_ids);+ let should_include_projects = !contains_nil_uuid(&project_filters.project_ids);++ strip_nil_uuids(&mut document_filters.document_ids);+ strip_nil_uuids(&mut chat_filters.chat_ids);+ strip_nil_uuids(&mut email_filters.recipients);+ strip_nil_uuids(&mut channel_filters.channel_ids);+ strip_nil_uuids(&mut project_filters.project_ids);++ document_filters.file_types = expand_file_types_for_search(document_filters.file_types);+Self {- document: Some(DocumentFilters::default()),- chat: Some(ChatFilters::default()),- email: Some(EmailFilters::default()),- channel: Some(ChannelFilters::default()),- project: Some(ProjectFilters::default()),+ should_include_documents,+ should_include_chats,+ should_include_emails,+ should_include_channels,+ should_include_projects,+ document_filters,+ chat_filters,+ email_filters,+ channel_filters,+ project_filters,}}}diff --git a/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs b/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rsindex d85a3d3d7f..d65b23e53a 100644--- a/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs+++ b/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs@@ -3,8 +3,8 @@ use std::str::FromStr;use anyhow::Context;use chrono::Utc;use model::document::{DocumentMetadata, FileType};-use model_file_type::FileAssociation;use models_search::document::MarkdownParseResult;+use models_search::unified::is_searchable_association;use opensearch_client::{OpensearchClient, date_format::EpochSeconds, upsert::document::UpsertDocumentArgs,};@@ -70,18 +70,9 @@ pub async fn update_search_with_raw_document(document_storage_bucket: &str,search_extractor_message: &SearchExtractorMessage,) -> anyhow::Result<()> {- // Early exit if we do not support search on the file type- // TODO: support other documents- match search_extractor_message.file_type.macro_app_path() {- FileAssociation::Pdf(_)- | FileAssociation::Write(_)- | FileAssociation::Code(_)- | model_file_type::FileAssociation::Canvas(_)- | model_file_type::FileAssociation::Md(_) => {}- _ => {- tracing::warn!("unsupported file type");- return Ok(());- }+ if !is_searchable_association(&search_extractor_message.file_type.macro_app_path()) {+ tracing::warn!("unsupported file type");+ return Ok(());}// This ensures we only process the latest versiondiff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rsindex 73133823dd..6145490c24 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs@@ -12,10 +12,10 @@ use axum::{};use macro_user_id::user_id::MacroUserId;use model::{response::ErrorResponse, user::UserContext};-use models_search::unified::generate_unified_search_indices;+use models_search::unified::SearchEntityFilters;use models_search::{SearchOn, SimpleSearchResponse,- unified::{SimpleUnifiedSearchResponse, UnifiedSearchIndex, UnifiedSearchRequest},+ unified::{SimpleUnifiedSearchResponse, UnifiedSearchRequest},};use models_search_cursor::{SearchCursor, SearchCursorOption, SearchMethodCursor};use opensearch_client::search::model::SearchHit;@@ -163,23 +163,19 @@ pub(in crate::api::search) async fn perform_unified_search(let terms: Vec<String> = vec![query];let match_type = req.match_type;- let include = req.include;-- let filters = req.filters.unwrap_or_default();- let channel_filters = filters.channel.unwrap_or_default();- let email_filters = filters.email.unwrap_or_default();- let chat_filters = filters.chat.unwrap_or_default();- let doc_filters = filters.document.unwrap_or_default();- let project_filters = filters.project.unwrap_or_default();-- let should_include_documents =- include.is_empty() || include.contains(&UnifiedSearchIndex::Documents);- let should_include_channels =- include.is_empty() || include.contains(&UnifiedSearchIndex::Channels);- let should_include_chats = include.is_empty() || include.contains(&UnifiedSearchIndex::Chats);- let should_include_projects =- include.is_empty() || include.contains(&UnifiedSearchIndex::Projects);- let should_include_emails = include.is_empty() || include.contains(&UnifiedSearchIndex::Emails);++ let search_filters = SearchEntityFilters::from(req.filters);+ let channel_filters = search_filters.channel_filters;+ let email_filters = search_filters.email_filters;+ let chat_filters = search_filters.chat_filters;+ let doc_filters = search_filters.document_filters;+ let project_filters = search_filters.project_filters;++ let should_include_documents = search_filters.should_include_documents;+ let should_include_channels = search_filters.should_include_channels;+ let should_include_chats = search_filters.should_include_chats;+ let should_include_projects = search_filters.should_include_projects;+ let should_include_emails = search_filters.should_include_emails;let email_terms = split_search_terms(&terms);let is_email_multi_term = email_terms.len() > 1;@@ -277,7 +273,25 @@ pub(in crate::api::search) async fn perform_unified_search(cursor: content_cursor_for_search,match_type: match_type.to_string(),collapse,- search_indices: generate_unified_search_indices(include),+ search_indices: {+ let mut indices = std::collections::HashSet::new();+ if should_include_documents {+ indices.insert(models_opensearch::SearchEntityType::Documents);+ }+ if should_include_chats {+ indices.insert(models_opensearch::SearchEntityType::Chats);+ }+ if should_include_emails {+ indices.insert(models_opensearch::SearchEntityType::Emails);+ }+ if should_include_channels {+ indices.insert(models_opensearch::SearchEntityType::Channels);+ }+ if should_include_projects {+ indices.insert(models_opensearch::SearchEntityType::Projects);+ }+ indices+ },document_search_args: filter_document_response.clone(),email_search_args: filter_email_response.clone(),channel_message_search_args: filter_channel_response,diff --git a/rust/cloud-storage/search_service/src/api/swagger.rs b/rust/cloud-storage/search_service/src/api/swagger.rsindex fd112f53ed..449db3ae1d 100644--- a/rust/cloud-storage/search_service/src/api/swagger.rs+++ b/rust/cloud-storage/search_service/src/api/swagger.rs@@ -3,6 +3,10 @@ use utoipa::OpenApi;use crate::api::search;+use item_filters::{+ ChannelFilters, ChatFilters, DocumentFilters, EmailFilters, EntityFilters, NotificationFilters,+ ProjectFilters, PropertyFilter, SharedEmailFilter, TaskFilters,+};use model::{document::FileType, response::EmptyResponse};use models_search::channel::{ChannelSearchRequest, ChannelSearchResponse, ChannelSearchResponseItem, ChannelSearchResult,@@ -21,8 +25,8 @@ use models_search::email::{SimpleEmailSearchResponse, SimpleEmailSearchResponseItem,};use models_search::unified::{- SimpleUnifiedSearchResponse, SimpleUnifiedSearchResponseItem, UnifiedSearchFilters,- UnifiedSearchIndex, UnifiedSearchRequest, UnifiedSearchResponse, UnifiedSearchResponseItem,+ SimpleUnifiedSearchResponse, SimpleUnifiedSearchResponseItem, UnifiedSearchRequest,+ UnifiedSearchResponse, UnifiedSearchResponseItem,};use models_search::project::{@@ -64,7 +68,11 @@ use models_search::{MatchType, SearchHighlight};ChannelSearchRequest, ChannelSearchResponse, ChannelSearchResponseItem, ChannelSearchResult,// Unified- UnifiedSearchIndex, UnifiedSearchRequest, UnifiedSearchResponseItem, UnifiedSearchResponse, UnifiedSearchFilters,+ UnifiedSearchRequest, UnifiedSearchResponseItem, UnifiedSearchResponse,++ // Entity filters (shared with soup)+ EntityFilters, DocumentFilters, ChatFilters, EmailFilters, ChannelFilters, ProjectFilters,+ PropertyFilter, NotificationFilters, TaskFilters, SharedEmailFilter,// ProjectProjectSearchRequest, ProjectSearchResponse, ProjectSearchResponseItem, ProjectSearchResult, ProjectSearchMetadata,