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(tags): filter files and tasks by tag in soup and search (#4438)
gbirmanbcec1282b5ca
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.tsindex a90d1ee770..1e48e9d771 100644--- 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.ts@@ -45,7 +45,10 @@ type DateRangeFieldName =| 'folderUpdatedAt'| 'emailUpdatedAt';-type CompiledFieldName = Exclude<FieldName, 'properties' | DateRangeFieldName>;+type CompiledFieldName = Exclude<+ FieldName,+ 'properties' | 'tagFilters' | DateRangeFieldName+>;const AST = {or(asts: BackendAst[]): BackendAst {@@ -372,6 +375,14 @@ export function compileToAst(state: QueryState): TargetAstMap {}}+ // Tags: one OR group across every selected tag, regardless of which+ // definition owns it. Pushed as a single propf entry so it ANDs with the+ // status/priority groups but ORs internally (match any selected tag).+ const includeTags = state.include.tagFilters ?? [];+ if (includeTags.length) {+ byTarget.propf.push(AST.or(includeTags.map(propertyToAst)));+ }+pushDateRangeFiltersToTargets(byTarget, state.include, state.exclude);for (const expression of state.documentWhere ?? []) {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.tsindex aa5cf6d138..ea7f51f640 100644--- 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.ts@@ -52,6 +52,11 @@ export type ArrayFieldFilters = {foreignEntitySource?: string[];crmCompanyId?: string[];properties?: PropertyFilter[];+ // Selected tags. Kept separate from `properties` because tags combine as a+ // single OR across all tag definitions (personal + team), whereas `properties`+ // AND across distinct definitions. Each entry carries its owning definition id+ // (needed for the soup literal) and option id.+ tagFilters?: PropertyFilter[];};export type ScalarFieldFilters = {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 1b3c14fe1c..41b200d47a 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@@ -183,6 +183,12 @@ function filterDataToQueryFilters(data: QueryState): EntityFilters {filters.property_filters = propertyFilters;}+ // Tags: match on the option ids alone (globally unique), OR'd across all tag+ // definitions. No definition id is sent — the backend matches values only.+ if (include.tagFilters?.length) {+ filters.tag_option_ids = include.tagFilters.map((t) => t.value);+ }+return filters;}diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-facets.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-facets.tsxindex b697ed4db8..87d05e2a42 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-facets.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-facets.tsx@@ -1,4 +1,7 @@-import type { CallStatus } from '@app/component/next-soup/filters/filter-store/types';+import type {+ CallStatus,+ PropertyFilter,+} from '@app/component/next-soup/filters/filter-store/types';import { EntityIcon } from '@core/component/EntityIcon';import { UserIcon } from '@core/component/UserIcon';import { useQuickAccess } from '@core/context/quickAccess';@@ -9,6 +12,7 @@ import { PROPERTY_OPTION_IDS } from '@property/constants';import { type Accessor, createMemo, type JSX } from 'solid-js';import { useInboxPicker } from '../inbox-picker';import type { SearchableOption } from '../searchable-multi-select';+import { useTagOptions } from '../tag-filter';import type {SearchFiltersController,SearchIndexId,@@ -283,6 +287,8 @@ export function useSearchFacets(setSelectedIds: controller.setEmailInbox,});+ const tagSource = useTagOptions();+const type = singleFacet({id: 'type',label: 'Type',@@ -438,6 +444,30 @@ export function useSearchFacets(onChange: controller.setTaskCreatedBy,});+ const tags = multiFacet({+ id: 'tags',+ label: 'Tags',+ neutralLabel: 'Any tag',+ placeholder: 'Filter by tag...',+ options: tagSource.options,+ activeIds: () => controller.tags().map((t) => t.value),+ onChange: (ids) => {+ const byOption = tagSource.defByOption();+ controller.setTags(+ ids.reduce<PropertyFilter[]>((acc, id) => {+ const propertyId = byOption.get(id);+ if (propertyId) acc.push({ propertyId, type: 'select', value: id });+ return acc;+ }, [])+ );+ },+ });++ // Tags show only where tagging applies (documents/tasks), gated behind the+ // tags feature flag, and hidden when the caller has no tags defined.+ const tagFacets = (): SearchFacetVM[] =>+ tagSource.enabled() && tagSource.hasTags() ? [tags] : [];+return createMemo(() => {switch (controller.type()) {case 'email':@@ -449,7 +479,16 @@ export function useSearchFacets(case 'calls':return [type, callIn, callFrom, callStatus];case 'task':- return [type, taskStatus, taskPriority, taskAssignee, taskCreatedBy];+ return [+ type,+ taskStatus,+ taskPriority,+ taskAssignee,+ taskCreatedBy,+ ...tagFacets(),+ ];+ case 'document-or-file':+ return [type, ...tagFacets()];default:return [type];}diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-filters-state.ts b/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-filters-state.tsindex e599755fe3..ee10123469 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-filters-state.ts+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/search/search-filters-state.ts@@ -25,6 +25,12 @@ export type SearchIndexId =export type SearchTypeValue = SearchIndexId | 'all';+/** Search types whose results are documents/tasks, where tag filtering applies. */+export const TAG_SEARCH_TYPES = new Set<SearchTypeValue>([+ 'task',+ 'document-or-file',+]);+/*** Server-side narrowing for each index type. `defineQueryFilters` NIL-fills* the id field of every target the input doesn't reference, so each seed@@ -57,6 +63,11 @@ export type SearchFiltersSections = {export type SearchFiltersState = SearchFiltersSections & {type: SearchTypeValue;+ // Selected tags. Applied only on the document/task types (TAG_SEARCH_TYPES)+ // and read live from the compiled query, so they persist across those types+ // but clear when switching to a type where tags do not apply (all/email/etc).+ // Each entry carries its owning definition id and option id; combined as one OR.+ tags: PropertyFilter[];};export const DEFAULT_SECTIONS: SearchFiltersSections = {@@ -86,6 +97,12 @@ export function compileSearchQuery(state: SearchFiltersState): Query {Object.assign(include, seed.include);Object.assign(exclude, seed.exclude);+ // Tags only apply where results are already narrowed to documents/tasks, so a+ // tag filter never silently empties an email/channel/call search.+ if (TAG_SEARCH_TYPES.has(state.type) && state.tags.length) {+ include.tagFilters = state.tags;+ }+if (state.type === 'email') {if (state.email.importance !== undefined) {include.emailImportance = state.email.importance;@@ -178,6 +195,7 @@ export function createSearchFiltersController() {taskProperty(SYSTEM_PROPERTY_IDS.ASSIGNEES));const taskCreatedBy = createMemo(() => withoutNil(include().documentOwnerId));+ const tags = createMemo<PropertyFilter[]>(() => include().tagFilters ?? []);const currentSections = (): SearchFiltersSections => ({email: { importance: emailImportance(), inboxIds: emailInbox() },@@ -194,6 +212,10 @@ export function createSearchFiltersController() {// Per-index values are remembered for the lifetime of the view: switching// the type away stashes the active section, switching back rehydrates it.let stash: SearchFiltersSections = structuredClone(DEFAULT_SECTIONS);+ // Tags aren't a per-type section but are still remembered across type+ // switches (they compile only for TAG_SEARCH_TYPES, so `tags()` reads empty+ // on other types — snapshot them on switch-away so the selection survives).+ let stashedTags: PropertyFilter[] = [];const apply = (state: SearchFiltersState) =>batch(() => {@@ -205,7 +227,7 @@ export function createSearchFiltersController() {});const applySections = (sections: Partial<SearchFiltersSections>) =>- apply({ type: type(), ...currentSections(), ...sections });+ apply({ type: type(), tags: tags(), ...currentSections(), ...sections });const setType = (next: SearchTypeValue) => {const current = type();@@ -235,12 +257,19 @@ export function createSearchFiltersController() {};}- apply({ type: next, ...stash });+ // Refresh the tag snapshot from the live value only while leaving a type+ // that compiles tags; other types read empty and would clobber it.+ if (TAG_SEARCH_TYPES.has(current)) stashedTags = tags();++ apply({ type: next, tags: stashedTags, ...stash });};return {type,setType,+ tags,+ setTags: (filters: PropertyFilter[]) =>+ apply({ type: type(), tags: filters, ...currentSections() }),emailImportance,setEmailImportance: (importance: boolean | undefined) =>applySections({ email: { importance, inboxIds: emailInbox() } }),diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/tag-filter.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/tag-filter.tsxnew file mode 100644index 0000000000..44eeae7830--- /dev/null+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/tag-filter.tsx@@ -0,0 +1,101 @@+import type { PropertyFilter } from '@app/component/next-soup/filters/filter-store';+import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-context';+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import {+ ENABLE_TAGS_FE_FLAG,+ ENABLE_TAGS_FE_OVERRIDE,+} from '@core/constant/featureFlags';+import { TagDot } from '@property/tags/TagDot';+import { useTagsQuery } from '@queries/properties/tags';+import { batch, createMemo } from 'solid-js';+import type { SearchableOption } from './searchable-multi-select';++/**+ * The caller's tags as pickable options, plus the flag/availability gating.+ * Shared by every tag-filter surface (search facet, filter dropdown, chip bar)+ * so option labels, colors, and the owning-definition mapping stay in sync.+ */+export function useTagOptions() {+ const tagsFlag = useFeatureFlag(ENABLE_TAGS_FE_FLAG, {+ enabledOverride: ENABLE_TAGS_FE_OVERRIDE,+ });+ const tagsQuery = useTagsQuery();++ const defByOption = createMemo(() => {+ const map = new Map<string, string>();+ for (const set of tagsQuery.data ?? []) {+ for (const option of set.options) {+ map.set(option.id, option.propertyDefinitionId);+ }+ }+ return map;+ });++ const options = createMemo<SearchableOption[]>(() =>+ (tagsQuery.data ?? []).flatMap((set) =>+ set.options.map((option) => ({+ id: option.id,+ label: option.value.type === 'string' ? option.value.value : option.id,+ icon: () => <TagDot color={option.color ?? undefined} />,+ }))+ )+ );++ const optionsById = createMemo(() => {+ const map = new Map<string, SearchableOption>();+ for (const option of options()) map.set(option.id, option);+ return map;+ });++ const enabled = () => tagsFlag().enabled;+ const hasTags = () => options().length > 0;++ return { enabled, hasTags, options, optionsById, defByOption };+}++/**+ * Tag-filter state for the list-view surfaces (the filter dropdown and the+ * active-filters chip bar). Tags are written to `queryFilters.tagFilters` as+ * PropertyFilters carrying their owning definition id (soup needs it for the+ * literal); the search request maps them to option ids alone. Multiple tags OR+ * together across definitions.+ */+export function useTagFilter() {+ const { queryFilters } = useSoupView();+ const tags = useTagOptions();++ const activeIds = createMemo(() =>+ (queryFilters.state.include.tagFilters ?? []).map((t) => t.value)+ );++ const onChange = (ids: string[]) => {+ const byOption = tags.defByOption();+ const current = activeIds();+ const currentFilters = queryFilters.state.include.tagFilters ?? [];+ const addProps = ids.reduce<PropertyFilter[]>((acc, id) => {+ if (current.includes(id)) return acc;+ const propertyId = byOption.get(id);+ if (propertyId) acc.push({ propertyId, type: 'select', value: id });+ return acc;+ }, []);+ // Remove from the stored filters, not from freshly-derived ones: the stored+ // entry keeps its definition id even if the tag was deleted or the tag list+ // has not loaded, so deselecting always clears the filter.+ const removeProps = currentFilters.filter((f) => !ids.includes(f.value));+ batch(() => {+ if (removeProps.length)+ queryFilters.remove({ include: { tagFilters: removeProps } });+ if (addProps.length)+ queryFilters.add({ include: { tagFilters: addProps } });+ });+ };++ return {+ enabled: tags.enabled,+ hasTags: tags.hasTags,+ options: tags.options,+ optionsById: tags.optionsById,+ activeIds,+ onChange,+ };+}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 5dd2936194..b494e3574f 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@@ -61,6 +61,7 @@ import {SearchableMultiSelectInline,type SearchableOption,} from './searchable-multi-select';+import { useTagFilter } from './tag-filter';export type { FilterCategory, FilterOption } from './filter-categories';@@ -702,6 +703,13 @@ export const UnifiedFilterDropdown = (};const isTasksView = () => currentView() === 'tasks';+ const isDocumentsView = () => currentView() === 'documents';++ const tagFilter = useTagFilter();+ const showTagsFilter = () =>+ tagFilter.enabled() &&+ tagFilter.hasTags() &&+ (isTasksView() || isDocumentsView());registerHotkey({hotkey: 'f',@@ -740,7 +748,14 @@ export const UnifiedFilterDropdown = (};return (- <Show when={categories().length > 0 || isTasksView() || isNewInbox()}>+ <Show+ when={+ categories().length > 0 ||+ isTasksView() ||+ isNewInbox() ||+ showTagsFilter()+ }+ ><Dropdownopen={open()}onOpenChange={handleOpenChange}@@ -865,6 +880,16 @@ export const UnifiedFilterDropdown = (}}</For></Show>++ <Show when={showTagsFilter()}>+ <SearchableFilterSubmenu+ label="Tags"+ options={tagFilter.options}+ activeIds={tagFilter.activeIds}+ onChange={tagFilter.onChange}+ placeholder="Filter by tag..."+ />+ </Show></Dropdown.Group></Dropdown.Content></Dropdown>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 ca1d279f10..3a96ff0768 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@@ -34,6 +34,7 @@ import type {FilterValue,} from './consolidated-filter-chip';import type { SearchableOption } from './searchable-multi-select';+import { useTagFilter } from './tag-filter';import {TASK_STATUS_FILTER_IDS,useTaskStatusFilter,@@ -77,6 +78,7 @@ export function useFilterRefinements() {const contacts = useContacts();const currentUserId = useUserId();const taskStatus = useTaskStatusFilter();+ const tagFilter = useTagFilter();const getPresetContext = (): PresetContext => ({userId: user.userId(),@@ -543,8 +545,54 @@ export function useFilterRefinements() {);};+ // Tags chip (consolidated, searchable) for the documents/tasks views.+ const pushTagsConsolidatedChip = () => {+ if (view !== 'tasks' && view !== 'documents') return;+ if (!tagFilter.enabled() || !tagFilter.hasTags()) return;++ const key = 'tags';+ const popupOpen =+ consolidatedChipCache.get(key)?.isPopupOpen?.() ?? false;+ if (tagFilter.activeIds().length === 0 && !popupOpen) return;++ seenKeys.add(key);++ const getValues = (): FilterValue[] =>+ tagFilter.activeIds().map((id) => {+ const opt = tagFilter.optionsById().get(id);+ return { id, label: opt?.label ?? id, icon: opt?.icon };+ });++ filters.push(+ getOrCreateConsolidatedChip(key, () => {+ const [isPopupOpen, _setPopupOpen] = createSignal(false);+ const setPopupOpen = (v: boolean) => {+ if (!v) {+ queueMicrotask(() =>+ panel.panelRef()?.focus({ preventScroll: true })+ );+ }+ _setPopupOpen(v);+ };+ return {+ key,+ categoryLabel: 'Tags',+ values: getValues,+ searchableOptions: tagFilter.options,+ activeSearchableIds: tagFilter.activeIds,+ onSearchableChange: tagFilter.onChange,+ searchPlaceholder: 'Filter by tag...',+ isPopupOpen,+ setPopupOpen,+ onRemoveAll: () => tagFilter.onChange([]),+ };+ })+ );+ };+pushTaskStatusChip();pushAssigneeConsolidatedChip();+ pushTagsConsolidatedChip();// Evict stale chipsfor (const key of consolidatedChipCache.keys()) {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 f5f80af4b5..f5c66c45bd 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@@ -31,6 +31,7 @@ import {isListViewID,type ListView,soupItemMatchesListView,+ soupItemMatchesTagFilter,} from '@app/constants/list-views';import { useFeatureFlag } from '@app/lib/analytics/posthog';import {@@ -466,6 +467,12 @@ export const SoupViewContextProvider: FlowComponent<};};+ // Active tag option ids, used to gate optimistic websocket inserts so an+ // active tag filter is honored even on the grouped render path.+ const activeTagOptionIds = createMemo(() =>+ (queryFilters.state.include.tagFilters ?? []).map((t) => t.value)+ );+const itemsQuery = useSoupAstItemsQuery(() => ({params: soupParams(),@@ -478,7 +485,9 @@ export const SoupViewContextProvider: FlowComponent<enabled: !search.isSearching(),showSupportedForeignEntities: showSupportedForeignEntitiesFF().enabled,meta: {- itemFilter: (item) => soupItemMatchesListView(item, view),+ itemFilter: (item) =>+ soupItemMatchesListView(item, view) &&+ soupItemMatchesTagFilter(item, activeTagOptionIds()),},};}@@ -601,7 +610,9 @@ export const SoupViewContextProvider: FlowComponent<return {enabled: enabled() && !search.isSearching(),meta: {- itemFilter: (item) => soupItemMatchesListView(item, view),+ itemFilter: (item) =>+ soupItemMatchesListView(item, view) &&+ soupItemMatchesTagFilter(item, activeTagOptionIds()),},};},diff --git a/js/app/packages/app/constants/list-views.ts b/js/app/packages/app/constants/list-views.tsindex d009de43fc..d1d5416c93 100644--- a/js/app/packages/app/constants/list-views.ts+++ b/js/app/packages/app/constants/list-views.ts@@ -69,3 +69,30 @@ export const soupItemMatchesListView = (.with('inbox', 'search', undefined, () => true).with('companies', () => item.tag === 'crmCompany').exhaustive();++/**+ * Whether a soup item carries at least one of the given tag option ids. Tags are+ * SelectOption property values on the item and option ids are globally unique, so+ * the owning definition is not consulted. An empty filter matches everything.+ * Used to gate optimistic websocket inserts so the grouped render (which skips+ * client predicates) still honors an active tag filter.+ */+export const soupItemMatchesTagFilter = (+ item: SoupApiItem,+ tagOptionIds: readonly string[]+): boolean => {+ if (tagOptionIds.length === 0) return true;+ const properties =+ 'properties' in item.data ? item.data.properties : undefined;+ if (!properties?.length) return false;+ const wanted = new Set(tagOptionIds);+ for (const { value } of properties) {+ if (+ value?.type === 'SelectOption' &&+ value.value.some((id) => wanted.has(id))+ ) {+ return true;+ }+ }+ return false;+};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.tsindex a9ef797e9f..9aee9f04e4 100644--- a/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts+++ b/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts@@ -39,4 +39,8 @@ export interface EntityFilters {project_filters?: ProjectFilters;/** property-based filters applied across entity types */property_filters?: PropertyFilter[];+ /** tag option ids matched against `properties.values`, OR'd together across+all tag definitions. Option ids are globally unique, so the match ignores+the owning definition id (personal and team tags combine into one OR). */+ tag_option_ids?: string[];}diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex afe9594f7e..771909fd2f 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -1642,6 +1642,13 @@"$ref": "#/components/schemas/PropertyFilter"},"description": "property-based filters applied across entity types"+ },+ "tag_option_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "tag option ids matched against `properties.values`, OR'd together across\nall tag definitions. Option ids are globally unique, so the match ignores\nthe owning definition id (personal and team tags combine into one OR)."}}},diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.tsindex fb9942f7cf..63a0fb71df 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts@@ -39,4 +39,8 @@ export interface EntityFilters {project_filters?: ProjectFilters;/** property-based filters applied across entity types */property_filters?: PropertyFilter[];+ /** tag option ids matched against `properties.values`, OR'd together across+all tag definitions. Option ids are globally unique, so the match ignores+the owning definition id (personal and team tags combine into one OR). */+ tag_option_ids?: string[];}diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex 49fec4b10f..fcce18e4cd 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -8760,6 +8760,12 @@ export const postItemsSoupBody = zod).optional().describe('property-based filters applied across entity types'),+ tag_option_ids: zod+ .array(zod.string())+ .optional()+ .describe(+ "tag option ids matched against `properties.values`, OR'd together across\nall tag definitions. Option ids are globally unique, so the match ignores\nthe owning definition id (personal and team tags combine into one OR)."+ ),}).describe('a bundle of all of the filters for each entity type').and(diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 0f5ef78458..8b7b6dcb1a 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -13870,6 +13870,13 @@"$ref": "#/components/schemas/PropertyFilter"},"description": "property-based filters applied across entity types"+ },+ "tag_option_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "tag option ids matched against `properties.values`, OR'd together across\nall tag definitions. Option ids are globally unique, so the match ignores\nthe owning definition id (personal and team tags combine into one OR)."}}},diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rsindex 461ef8cf7c..6661bed564 100644--- a/rust/cloud-storage/item_filters/src/lib.rs+++ b/rust/cloud-storage/item_filters/src/lib.rs@@ -642,6 +642,11 @@ pub struct EntityFilters {/// property-based filters applied across entity types#[serde(default, skip_serializing_if = "Vec::is_empty")]pub property_filters: Vec<PropertyFilter>,+ /// tag option ids matched against `properties.values`, OR'd together across+ /// all tag definitions. Option ids are globally unique, so the match ignores+ /// the owning definition id (personal and team tags combine into one OR).+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub tag_option_ids: Vec<String>,}impl IsEmpty for EntityFilters {@@ -657,6 +662,7 @@ impl IsEmpty for EntityFilters {crm_company_filters,foreign_entity_filters,property_filters,+ tag_option_ids,} = self;project_filters.is_empty()&& document_filters.is_empty()@@ -668,5 +674,6 @@ impl IsEmpty for EntityFilters {&& crm_company_filters.is_empty()&& foreign_entity_filters.is_empty()&& property_filters.iter().all(IsEmpty::is_empty)+ && tag_option_ids.is_empty()}}diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rsindex e912cded6a..4fca9f31f5 100644--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs@@ -84,6 +84,7 @@ pub(crate) struct DocumentQueryBuilder {sub_types: Vec<String>,mode: DocumentSearchMode,property_filters: Vec<PropertyFilterArg>,+ tag_option_ids: Vec<String>,}impl DocumentQueryBuilder {@@ -93,6 +94,7 @@ impl DocumentQueryBuilder {sub_types: Vec::new(),mode: DocumentSearchMode::default(),property_filters: Vec::new(),+ tag_option_ids: Vec::new(),}}@@ -122,6 +124,11 @@ impl DocumentQueryBuilder {self}+ pub fn tag_option_ids(mut self, tag_option_ids: Vec<String>) -> Self {+ self.tag_option_ids = tag_option_ids;+ self+ }+/// Parent/child join query: one `has_child` clause per term, ANDed/// inside `bool.must`. Parent metadata filters (owner, ids,/// sub_type) sit on `bool.filter` directly because they live on@@ -166,6 +173,13 @@ impl DocumentQueryBuilder {}}+ // Tag filter: a single nested clause matching any of the option ids in+ // `properties.values`, with no definition_id constraint. Option ids are+ // globally unique, so this ORs tags across definitions in one clause.+ if let Some(nested) = build_tag_filter(&self.tag_option_ids) {+ bool_query.filter(nested);+ }+// Match clause(s) per mode: the parent `document_name` (Name), child// chunk `content` via has_child (Content), or either (NameContent).let include_name = matches!(@@ -275,6 +289,25 @@ fn build_property_filter<'a>(filter: &PropertyFilterArg) -> Option<QueryType<'a>)}+/// Build a `nested` query over `properties` matching parents that have any+/// nested entry whose `values` contains one of `option_ids`. Unlike+/// [`build_property_filter`] there is no `definition_id` constraint: tag option+/// ids are globally unique, so this matches a tag regardless of which+/// definition owns it. Returns `None` when there are no option ids.+fn build_tag_filter<'a>(option_ids: &[String]) -> Option<QueryType<'a>> {+ if option_ids.is_empty() {+ return None;+ }+ Some(+ NestedQuery::new(+ PROPERTIES_PATH,+ QueryType::terms(format!("{PROPERTIES_PATH}.values"), option_ids.to_vec()),+ )+ .ignore_unmapped(true)+ .into(),+ )+}+/// Highlight config attached to each `has_child` inner_hits block./// Matches the top-level documents highlight (plain highlighter,/// `<macro_em>` tags, single fragment) so chunk hits come back with@@ -363,6 +396,7 @@ pub struct DocumentSearchArgs {pub sub_types: Vec<String>,pub mode: DocumentSearchMode,pub property_filters: Vec<PropertyFilterArg>,+ pub tag_option_ids: Vec<String>,}impl From<DocumentSearchArgs> for DocumentQueryBuilder {@@ -378,6 +412,7 @@ impl From<DocumentSearchArgs> for DocumentQueryBuilder {.sub_types(args.sub_types).mode(args.mode).property_filters(args.property_filters)+ .tag_option_ids(args.tag_option_ids)}}diff --git a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs b/rust/cloud-storage/opensearch_client/src/search/documents/test.rsindex 7a110f4e3d..7f8d5a3e32 100644--- a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/documents/test.rs@@ -288,6 +288,62 @@ fn test_build_bool_query_property_filter_empty_values_skipped() -> anyhow::ResulOk(())}+#[test]+fn test_build_bool_query_tag_filter_emits_flat_terms() -> anyhow::Result<()> {+ let builder = DocumentQueryBuilder::new(vec!["foo".to_string()])+ .match_type("partial")+ .user_id("alice")+ .tag_option_ids(vec![+ "00000001-0000-0000-0003-000000000001".to_string(),+ "00000001-0000-0000-0003-000000000002".to_string(),+ ]);++ let json = builder.build_bool_query()?.build().to_json();+ let filter = json["bool"]["filter"].as_array().expect("filter array");++ let nested: Vec<&serde_json::Value> = filter+ .iter()+ .filter(|f| f.get("nested").is_some())+ .collect();+ assert_eq!(+ nested.len(),+ 1,+ "tags collapse to one nested clause: {filter:?}"+ );++ let tags = &nested[0]["nested"];+ assert_eq!(tags["path"], "properties");+ assert_eq!(tags["ignore_unmapped"], true);+ // No definition_id term: match is on the globally-unique option ids alone.+ assert_eq!(+ tags["query"],+ serde_json::json!({+ "terms": {"properties.values": [+ "00000001-0000-0000-0003-000000000001",+ "00000001-0000-0000-0003-000000000002"+ ]}+ })+ );++ Ok(())+}++#[test]+fn test_build_bool_query_tag_filter_empty_skipped() -> anyhow::Result<()> {+ let builder = DocumentQueryBuilder::new(vec!["foo".to_string()])+ .match_type("partial")+ .user_id("alice")+ .tag_option_ids(vec![]);++ let json = builder.build_bool_query()?.build().to_json();+ let filter = json["bool"]["filter"].as_array().expect("filter array");+ assert!(+ !filter.iter().any(|f| f.get("nested").is_some()),+ "empty tag_option_ids should emit no nested clause: {filter:?}"+ );+ Ok(())+}+#[test]fn document_index_deserializes_parent_shape() {// Parent docs carry only parent-level metadata in `_source`; thediff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rsindex 32a85bface..49b2f54e68 100644--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs@@ -80,6 +80,7 @@ impl From<UnifiedSearchArgs> for DocumentSearchArgs {sub_types: args.document_search_args.sub_types,mode: args.document_search_args.mode,property_filters: args.document_search_args.property_filters,+ tag_option_ids: args.document_search_args.tag_option_ids,}}}@@ -176,6 +177,7 @@ pub struct UnifiedDocumentSearchArgs {pub sub_types: Vec<String>,pub mode: DocumentSearchMode,pub property_filters: Vec<PropertyFilterArg>,+ pub tag_option_ids: Vec<String>,}#[derive(Debug, Default, Clone)]diff --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 c1787b7cda..8b989c0cd1 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@@ -240,6 +240,7 @@ pub(in crate::api::search) async fn perform_unified_search(// the OpenSearch documents index, so capture them before the conversion// (which drops them) and attach them to the document search args below.let property_filter_args = to_property_filter_args(&req.filters.property_filters);+ let tag_option_ids = req.filters.tag_option_ids.clone();let search_filters = SearchEntityFilters::from(req.filters);let channel_filters = search_filters.channel_filters;@@ -315,6 +316,7 @@ pub(in crate::api::search) async fn perform_unified_search(// has_child clause ANDed via bool.must.filter_document_response.terms = search_terms.clone();filter_document_response.property_filters = property_filter_args;+ filter_document_response.tag_option_ids = tag_option_ids;filter_channel_response.terms = search_terms.clone();filter_chat_response.terms = search_terms.clone();filter_email_response.terms = email_terms.clone();