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): add server-side channel name search for ai tools (#5072)
gbirmandc49f7e58151
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex d5e97264a0..a15d516200 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -3800,11 +3800,69 @@"crates/workspace-hack"],"name_search": [+ "crates/agent",+ "crates/ai_toolset",+ "crates/ai_usage",+ "crates/attachment",+ "crates/authentication_service_client",+ "crates/bot_id",+ "crates/channel_sender",+ "crates/channels",+ "crates/connection_gateway_client",+ "crates/connection_gateway_models",+ "crates/contacts","crates/cowlike",+ "crates/crm",+ "crates/document_sub_type",+ "crates/email",+ "crates/email_db_client",+ "crates/email_utils",+ "crates/entity_access",+ "crates/entity_access_db_utils",+ "crates/entity_access_management",+ "crates/filter_ast",+ "crates/frecency",+ "crates/invite_email",+ "crates/item_filters",+ "crates/last_online_tracker",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_event_broker",+ "crates/macro_event_topics",+ "crates/macro_service_urls","crates/macro_user_id",+ "crates/macro_uuid",+ "crates/mention_utils",+ "crates/model",+ "crates/model-entity",+ "crates/model-error-response",+ "crates/model_file_type",+ "crates/model_notifications",+ "crates/model_user",+ "crates/models_ai_projection",+ "crates/models_bulk_upload",+ "crates/models_email",+ "crates/models_entity_access_management","crates/models_opensearch",+ "crates/models_pagination",+ "crates/models_permissions",+ "crates/models_properties","crates/models_search_cursor","crates/name_search",+ "crates/non_empty",+ "crates/notification",+ "crates/prompt",+ "crates/properties",+ "crates/rate_limit",+ "crates/remote_env_var",+ "crates/s3_key",+ "crates/share_permission_db_utils",+ "crates/sqs_client",+ "crates/sqs_worker",+ "crates/system_properties",+ "crates/unfurl","crates/workspace-hack"],"native_app_server": [diff --git a/.sqlx/query-b2a90ac44fc610837910a4911b23929b64d00021f63415a03e5a110510181b25.json b/.sqlx/query-b2a90ac44fc610837910a4911b23929b64d00021f63415a03e5a110510181b25.jsonnew file mode 100644index 0000000000..e7e2bf490b--- /dev/null+++ b/.sqlx/query-b2a90ac44fc610837910a4911b23929b64d00021f63415a03e5a110510181b25.json@@ -0,0 +1,39 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n c.id as entity_id,\n c.name,\n c.updated_at\n FROM comms_channels c\n INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id\n WHERE cp.user_id = $1\n AND cp.left_at IS NULL\n AND c.id = ANY($2::uuid[])\n AND (\n $3::timestamptz IS NULL\n OR (c.updated_at, c.id) < ($3, $4)\n )\n AND (\n NULLIF(BTRIM(c.name), '') IS NULL\n OR c.name ~* $5\n )\n ORDER BY c.updated_at DESC, c.id DESC\n LIMIT $6\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "entity_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Varchar"+ },+ {+ "ordinal": 2,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "UuidArray",+ "Timestamptz",+ "Uuid",+ "Text",+ "Int8"+ ]+ },+ "nullable": [+ false,+ true,+ false+ ]+ },+ "hash": "b2a90ac44fc610837910a4911b23929b64d00021f63415a03e5a110510181b25"+}diff --git a/Cargo.lock b/Cargo.lockindex 08efd709b6..5728c9dd9f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -9349,6 +9349,7 @@ version = "0.1.0"dependencies = ["anyhow","cached",+ "channels","chrono","macro_db_migrator","macro_user_id",@@ -16176,7 +16177,6 @@ dependencies = ["flate2","foldhash 0.2.0","form_urlencoded",- "futures","futures-channel","futures-core","futures-executor",diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.tsindex 8c53d2965b..62c49b1c04 100644--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts@@ -676,6 +676,7 @@ function getSearchResultId(result: UnifiedSearchResponseItem): string {return match(result).with({ type: 'document' }, (r) => r.document_id).with({ type: 'chat' }, (r) => r.chat_id)+ .with({ type: 'channel' }, (r) => r.channel_id).with({ type: 'channelMessage' }, (r) => `${r.channel_id}:${r.message_id}`).with({ type: 'email' }, (r) => r.thread_id).with({ type: 'project' }, (r) => r.id)diff --git a/apps/web/src/lib/queries/soup/transform-utils.ts b/apps/web/src/lib/queries/soup/transform-utils.tsindex c026b36456..5abca70712 100644--- a/apps/web/src/lib/queries/soup/transform-utils.ts+++ b/apps/web/src/lib/queries/soup/transform-utils.ts@@ -450,6 +450,38 @@ export const useSearchResponseItemMapper = () => {},];}+ case 'channel': {+ if (!result.metadata) return [];+ const nameHighlight = result.highlight.name+ ? mergeAdjacentMacroEmTags(result.highlight.name)+ : null;+ const search: SearchData = {+ nameHighlight,+ senderHighlightTerms: null,+ contentHitData: null,+ source: 'service',+ };+ const channelName =+ channels().find((channel) => channel.id === result.channel_id)+ ?.name ??+ (search.nameHighlight+ ? extractSearchSnippet(search.nameHighlight)+ : blockNameToDefaultFile('channel'));+ return [+ {+ type: 'channel',+ id: result.channel_id,+ name: channelName,+ ownerId: result.owner_id ?? '',+ channelType: result.channel_type as ChannelType,+ createdAt: result.metadata.created_at,+ updatedAt: result.metadata.updated_at,+ viewedAt: result.metadata.viewed_at,+ interactedAt: result.metadata.interacted_at,+ search,+ },+ ];+ }case 'channelMessage': {const channelName =channels().find((c) => c.id === result.channel_id)?.name ??diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex 63a19071dc..e288a78b60 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -437,6 +437,46 @@ export const SearchToolResponse = z.object({}),z.object({ type: z.literal('channelMessage') })),+ z.intersection(+ z.object({+ channel_id: z.string().uuid(),+ channel_type: z.string(),+ highlight: z.object({+ bcc: z.array(z.string()).optional(),+ cc: z.array(z.string()).optional(),+ content: z.array(z.string()).optional(),+ name: z.union([z.string(), z.null()]).optional(),+ recipients: z.array(z.string()).optional(),+ sender: z.union([z.string(), z.null()]).optional(),+ user_id: z.union([z.string(), z.null()]).optional(),+ }),+ id: z.string().uuid(),+ metadata: z+ .union([+ z.object({+ created_at: z.string().datetime({ offset: true }),+ interacted_at: z+ .union([+ z.string().datetime({ offset: true }),+ z.null(),+ ])+ .optional(),+ updated_at: z.string().datetime({ offset: true }),+ viewed_at: z+ .union([+ z.string().datetime({ offset: true }),+ z.null(),+ ])+ .optional(),+ }),+ z.null(),+ ])+ .optional(),+ owner_id: z.union([z.string(), z.null()]).optional(),+ score: z.union([z.number(), z.null()]).optional(),+ }),+ z.object({ type: z.literal('channel') })+ ),z.intersection(z.object({created_at: z.string().datetime({ offset: true }),diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex efe34fdb87..b7304b06a0 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -422,6 +422,9 @@ export type TaggedSearchResult1 =| (ChannelMessageSearchResponseItem & {type: 'channelMessage';})+ | (ChannelNameSearchResponseItem & {+ type: 'channel';+ })| (ProjectSearchResponseItemWithMetadata & {type: 'project';})@@ -823,6 +826,45 @@ export interface ChannelMessageSearchResponseItem {*/updated_at: string;}+/**+ * Metadata for a channel fetched from the database+ */+export interface ChannelMetadata {+ created_at: string;+ interacted_at?: string | null;+ updated_at: string;+ viewed_at?: string | null;+}+/**+ * A channel-name search hit.+ */+export interface ChannelNameSearchResponseItem {+ /**+ * The channel id.+ */+ channel_id: string;+ /**+ * The type of channel.+ */+ channel_type: string;+ highlight: SearchHighlight;+ /**+ * Standardized id field shared by all item types; the channel id.+ */+ id: string;+ /**+ * Metadata for the channel.+ */+ metadata?: ChannelMetadata | null;+ /**+ * The channel owner.+ */+ owner_id?: string | null;+ /**+ * The score of the result.+ */+ score?: number | null;+}/*** A single message in the tool response.*/@@ -2378,7 +2420,7 @@ export interface MarkNotificationsSeen {notificationIds: string[];}/**- * Search items by their name or title: document name, email subject, chat title, project name, the channel name a call belongs to. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, AI chats, projects, and call records include the tags visible to the user as {label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist).+ * Search items by their name or title: document name, email subject, chat title, channel name, project name, or call-record name. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, AI chats, projects, and call records include the tags visible to the user as {label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist).*/export interface NameSearch {/**diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/channelNameSearchResponseItem.ts b/apps/web/src/lib/service-clients/service-search/generated/models/channelNameSearchResponseItem.tsnew file mode 100644index 0000000000..fe247cb493--- /dev/null+++ b/apps/web/src/lib/service-clients/service-search/generated/models/channelNameSearchResponseItem.ts@@ -0,0 +1,30 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++import type { ChannelNameSearchResponseItemMetadata } from './channelNameSearchResponseItemMetadata';+import type { ChannelNameSearchResponseItemOwnerId } from './channelNameSearchResponseItemOwnerId';+import type { ChannelNameSearchResponseItemScore } from './channelNameSearchResponseItemScore';+import type { SearchHighlight } from './searchHighlight';++/**+ * A channel-name search hit.+ */+export interface ChannelNameSearchResponseItem {+ /** The channel id. */+ channel_id: string;+ /** The type of channel. */+ channel_type: string;+ /** The matched channel-name highlight. */+ highlight: SearchHighlight;+ /** Standardized id field shared by all item types; the channel id. */+ id: string;+ metadata?: ChannelNameSearchResponseItemMetadata;+ /** The channel owner. */+ owner_id?: ChannelNameSearchResponseItemOwnerId;+ /** The score of the result. */+ score?: ChannelNameSearchResponseItemScore;+}diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/channelNameSearchResponseItemMetadata.ts b/apps/web/src/lib/service-clients/service-search/generated/models/channelNameSearchResponseItemMetadata.tsnew file mode 100644index 0000000000..f27a8bafb2--- /dev/null+++ b/apps/web/src/lib/service-clients/service-search/generated/models/channelNameSearchResponseItemMetadata.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { ChannelMetadata } from './channelMetadata';++export type ChannelNameSearchResponseItemMetadata = null | ChannelMetadata;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/channelNameSearchResponseItemOwnerId.ts b/apps/web/src/lib/service-clients/service-search/generated/models/channelNameSearchResponseItemOwnerId.tsnew file mode 100644index 0000000000..e3f42ad0f9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-search/generated/models/channelNameSearchResponseItemOwnerId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The channel owner.+ */+export type ChannelNameSearchResponseItemOwnerId = string | null;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/channelNameSearchResponseItemScore.ts b/apps/web/src/lib/service-clients/service-search/generated/models/channelNameSearchResponseItemScore.tsnew file mode 100644index 0000000000..560fa91748--- /dev/null+++ b/apps/web/src/lib/service-clients/service-search/generated/models/channelNameSearchResponseItemScore.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The score of the result.+ */+export type ChannelNameSearchResponseItemScore = number | null;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/index.ts b/apps/web/src/lib/service-clients/service-search/generated/models/index.tsindex d382326f73..ebbece3287 100644--- a/apps/web/src/lib/service-clients/service-search/generated/models/index.ts+++ b/apps/web/src/lib/service-clients/service-search/generated/models/index.ts@@ -37,6 +37,10 @@ export * from './channelMessageSearchResponseItemThreadId';export * from './channelMetadata';export * from './channelMetadataInteractedAt';export * from './channelMetadataViewedAt';+export * from './channelNameSearchResponseItem';+export * from './channelNameSearchResponseItemMetadata';+export * from './channelNameSearchResponseItemOwnerId';+export * from './channelNameSearchResponseItemScore';export * from './channelSearchRequest';export * from './channelSearchRequestAllOf';export * from './channelSearchRequestAllOfTwo';@@ -303,4 +307,7 @@ export * from './unifiedSearchResponseItemOneOfOnezeroAllOfType';export * from './unifiedSearchResponseItemOneOfSeven';export * from './unifiedSearchResponseItemOneOfSevenAllOf';export * from './unifiedSearchResponseItemOneOfSevenAllOfType';+export * from './unifiedSearchResponseItemOneOfTwotwo';+export * from './unifiedSearchResponseItemOneOfTwotwoAllOf';+export * from './unifiedSearchResponseItemOneOfTwotwoAllOfType';export * from './unifiedSearchResponseNextCursor';diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItem.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItem.tsindex d17f9d3a85..5bc3a01b8b 100644--- a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItem.ts+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItem.ts@@ -11,6 +11,7 @@ import type { UnifiedSearchResponseItemOneOfOnesix } from './unifiedSearchResponimport type { UnifiedSearchResponseItemOneOfOnethree } from './unifiedSearchResponseItemOneOfOnethree';import type { UnifiedSearchResponseItemOneOfOnezero } from './unifiedSearchResponseItemOneOfOnezero';import type { UnifiedSearchResponseItemOneOfSeven } from './unifiedSearchResponseItemOneOfSeven';+import type { UnifiedSearchResponseItemOneOfTwotwo } from './unifiedSearchResponseItemOneOfTwotwo';export type UnifiedSearchResponseItem =| UnifiedSearchResponseItemOneOf@@ -19,4 +20,5 @@ export type UnifiedSearchResponseItem =| UnifiedSearchResponseItemOneOfOnezero| UnifiedSearchResponseItemOneOfOnethree| UnifiedSearchResponseItemOneOfOnesix- | UnifiedSearchResponseItemOneOfOnenine;+ | UnifiedSearchResponseItemOneOfOnenine+ | UnifiedSearchResponseItemOneOfTwotwo;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenine.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenine.tsindex ba38e65c1b..42f95ba205 100644--- a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenine.ts+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenine.ts@@ -4,8 +4,9 @@* search_service* OpenAPI spec version: 0.1.0*/-import type { CrmCompanySearchResponseItem } from './crmCompanySearchResponseItem';+import type { CallRecordSearchResponseItemWithMetadata } from './callRecordSearchResponseItemWithMetadata';import type { UnifiedSearchResponseItemOneOfOnenineAllOf } from './unifiedSearchResponseItemOneOfOnenineAllOf';export type UnifiedSearchResponseItemOneOfOnenine =- CrmCompanySearchResponseItem & UnifiedSearchResponseItemOneOfOnenineAllOf;+ CallRecordSearchResponseItemWithMetadata &+ UnifiedSearchResponseItemOneOfOnenineAllOf;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenineAllOfType.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenineAllOfType.tsindex 338d2ce383..afef6291c5 100644--- a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenineAllOfType.ts+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnenineAllOfType.ts@@ -10,5 +10,5 @@ export type UnifiedSearchResponseItemOneOfOnenineAllOfType =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const UnifiedSearchResponseItemOneOfOnenineAllOfType = {- company: 'company',+ call: 'call',} as const;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesix.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesix.tsindex d74d0cb189..f70bd9858e 100644--- a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesix.ts+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesix.ts@@ -4,9 +4,9 @@* search_service* OpenAPI spec version: 0.1.0*/-import type { CallRecordSearchResponseItemWithMetadata } from './callRecordSearchResponseItemWithMetadata';+import type { ProjectSearchResponseItemWithMetadata } from './projectSearchResponseItemWithMetadata';import type { UnifiedSearchResponseItemOneOfOnesixAllOf } from './unifiedSearchResponseItemOneOfOnesixAllOf';export type UnifiedSearchResponseItemOneOfOnesix =- CallRecordSearchResponseItemWithMetadata &+ ProjectSearchResponseItemWithMetadata &UnifiedSearchResponseItemOneOfOnesixAllOf;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesixAllOfType.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesixAllOfType.tsindex 4b2a0fba5a..dedb77dd35 100644--- a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesixAllOfType.ts+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesixAllOfType.ts@@ -10,5 +10,5 @@ export type UnifiedSearchResponseItemOneOfOnesixAllOfType =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const UnifiedSearchResponseItemOneOfOnesixAllOfType = {- call: 'call',+ project: 'project',} as const;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnethree.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnethree.tsindex 93ac656620..930922a33e 100644--- a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnethree.ts+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnethree.ts@@ -4,9 +4,8 @@* search_service* OpenAPI spec version: 0.1.0*/-import type { ProjectSearchResponseItemWithMetadata } from './projectSearchResponseItemWithMetadata';+import type { ChannelNameSearchResponseItem } from './channelNameSearchResponseItem';import type { UnifiedSearchResponseItemOneOfOnethreeAllOf } from './unifiedSearchResponseItemOneOfOnethreeAllOf';export type UnifiedSearchResponseItemOneOfOnethree =- ProjectSearchResponseItemWithMetadata &- UnifiedSearchResponseItemOneOfOnethreeAllOf;+ ChannelNameSearchResponseItem & UnifiedSearchResponseItemOneOfOnethreeAllOf;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnethreeAllOfType.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnethreeAllOfType.tsindex b7bf407a6d..0a2eea29c2 100644--- a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnethreeAllOfType.ts+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnethreeAllOfType.ts@@ -10,5 +10,5 @@ export type UnifiedSearchResponseItemOneOfOnethreeAllOfType =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const UnifiedSearchResponseItemOneOfOnethreeAllOfType = {- project: 'project',+ channel: 'channel',} as const;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwotwo.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwotwo.tsnew file mode 100644index 0000000000..f6bbaa8fc8--- /dev/null+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwotwo.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { CrmCompanySearchResponseItem } from './crmCompanySearchResponseItem';+import type { UnifiedSearchResponseItemOneOfTwotwoAllOf } from './unifiedSearchResponseItemOneOfTwotwoAllOf';++export type UnifiedSearchResponseItemOneOfTwotwo =+ CrmCompanySearchResponseItem & UnifiedSearchResponseItemOneOfTwotwoAllOf;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwotwoAllOf.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwotwoAllOf.tsnew file mode 100644index 0000000000..b8e7199d35--- /dev/null+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwotwoAllOf.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { UnifiedSearchResponseItemOneOfTwotwoAllOfType } from './unifiedSearchResponseItemOneOfTwotwoAllOfType';++export type UnifiedSearchResponseItemOneOfTwotwoAllOf = {+ type: UnifiedSearchResponseItemOneOfTwotwoAllOfType;+};diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwotwoAllOfType.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwotwoAllOfType.tsnew file mode 100644index 0000000000..eaa754ccf4--- /dev/null+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwotwoAllOfType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++export type UnifiedSearchResponseItemOneOfTwotwoAllOfType =+ (typeof UnifiedSearchResponseItemOneOfTwotwoAllOfType)[keyof typeof UnifiedSearchResponseItemOneOfTwotwoAllOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const UnifiedSearchResponseItemOneOfTwotwoAllOfType = {+ company: 'company',+} as const;diff --git a/apps/web/src/lib/service-clients/service-search/openapi.json b/apps/web/src/lib/service-clients/service-search/openapi.jsonindex fceb8f59df..8fd5341d4c 100644--- a/apps/web/src/lib/service-clients/service-search/openapi.json+++ b/apps/web/src/lib/service-clients/service-search/openapi.json@@ -524,6 +524,51 @@}}},+ "ChannelNameSearchResponseItem": {+ "type": "object",+ "description": "A channel-name search hit.",+ "required": ["id", "channel_type", "channel_id", "highlight"],+ "properties": {+ "channel_id": {+ "type": "string",+ "format": "uuid",+ "description": "The channel id."+ },+ "channel_type": {+ "type": "string",+ "description": "The type of channel."+ },+ "highlight": {+ "$ref": "#/components/schemas/SearchHighlight",+ "description": "The matched channel-name highlight."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Standardized id field shared by all item types; the channel id."+ },+ "metadata": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ChannelMetadata",+ "description": "Metadata for the channel."+ }+ ]+ },+ "owner_id": {+ "type": ["string", "null"],+ "description": "The channel owner."+ },+ "score": {+ "type": ["number", "null"],+ "format": "double",+ "description": "The score of the result."+ }+ }+ },"ChannelSearchRequest": {"allOf": [{@@ -3948,6 +3993,23 @@}]},+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/ChannelNameSearchResponseItem"+ },+ {+ "type": "object",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["channel"]+ }+ }+ }+ ]+ },{"allOf": [{diff --git a/crates/ai_tools/src/search/search_service/name.rs b/crates/ai_tools/src/search/search_service/name.rsindex 860f6ee44e..76adcb752a 100644--- a/crates/ai_tools/src/search/search_service/name.rs+++ b/crates/ai_tools/src/search/search_service/name.rs@@ -9,8 +9,10 @@ use email::domain::ports::EmailService;use item_filters::{EmailFilters, EntityFilters};use macro_user_id::user_id::MacroUserIdStr;use models_properties::service::tag_sets::{TagFilter, TagMatch};+use models_search::channel::ChannelNameSearchRequest;use models_search::unified::{- UnifiedSearchIndex, UnifiedSearchRequest, entity_filters_from_include,+ UnifiedSearchIndex, UnifiedSearchRequest, UnifiedSearchResponseItem,+ entity_filters_from_include,};use schemars::JsonSchema;use serde::Deserialize;@@ -18,7 +20,7 @@ use serde::Deserialize;#[derive(Debug, JsonSchema, Deserialize, Clone)]#[serde(rename_all = "camelCase")]#[schemars(- description = "Search items by their name or title: document name, email subject, chat title, project name, the channel name a call belongs to. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like \"what happened today\", \"what's going on\", \"catch me up\", or \"what happened in standup today\"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, AI chats, projects, and call records include the tags visible to the user as {label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist).",+ description = "Search items by their name or title: document name, email subject, chat title, channel name, project name, or call-record name. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like \"what happened today\", \"what's going on\", \"catch me up\", or \"what happened in standup today\"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, AI chats, projects, and call records include the tags visible to the user as {label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist).",title = "NameSearch")]pub struct NameSearch {@@ -110,6 +112,7 @@ impl AsyncTool<SearchToolContext> for NameSearch {)?;email_filters.link_ids = vec![link.id.to_string()];}+ let tag_filter_active = self.tags.as_ref().is_some_and(|tags| !tags.is_empty());let mut tag_sets = None;let mut tag_option_ids = Vec::new();if let Some(filters) = self.tags.as_deref().filter(|t| !t.is_empty()) {@@ -130,32 +133,86 @@ impl AsyncTool<SearchToolContext> for NameSearch {tag_filter_mode: tag_filter_mode(self.tags_match),..Default::default()};- let search_request = UnifiedSearchRequest {+ let non_channel_types = if self.entity_types.is_empty() {+ vec![+ UnifiedSearchIndex::Documents,+ UnifiedSearchIndex::Chats,+ UnifiedSearchIndex::Emails,+ UnifiedSearchIndex::Projects,+ UnifiedSearchIndex::CallRecords,+ ]+ } else {+ self.entity_types+ .iter()+ .filter(|entity_type| **entity_type != UnifiedSearchIndex::Channels)+ .cloned()+ .collect()+ };+ let include_channels = !tag_filter_active+ && (self.entity_types.is_empty()+ || self.entity_types.contains(&UnifiedSearchIndex::Channels));+ let search_request = (!non_channel_types.is_empty()).then(|| UnifiedSearchRequest {query: self.name.to_owned(),match_type: self.match_type.into(),- filters: entity_filters_from_include(self.entity_types.clone(), base_filters),+ filters: entity_filters_from_include(non_channel_types, base_filters),search_on: models_search::SearchOn::Name,include_crm: false,collapse: None,- };+ });+ let channel_request = include_channels.then(|| ChannelNameSearchRequest {+ query: self.name.to_owned(),+ match_type: self.match_type.into(),+ });+ let user_id = (*request_context.user_id).as_ref();- let response = search_context- .search_client- .search_unified(- (*request_context.user_id).as_ref(),- search_request,- None,- PAGE_SIZE,- )- .await- .map_err(|e| ToolCallError {- description: format!("failed to perform name search: {}", e),- internal_error: e,- })?;+ let (response, channel_response) = tokio::try_join!(+ async {+ let Some(search_request) = search_request else {+ return Ok(None);+ };+ search_context+ .search_client+ .search_unified(user_id, search_request, None, PAGE_SIZE)+ .await+ .map(Some)+ .map_err(|e| ToolCallError {+ description: format!("failed to perform name search: {e}"),+ internal_error: e,+ })+ },+ async {+ let Some(channel_request) = channel_request else {+ return Ok(None);+ };+ search_context+ .search_client+ .search_channel_names(user_id, channel_request, None, PAGE_SIZE)+ .await+ .map(Some)+ .map_err(|e| ToolCallError {+ description: format!("failed to search channel names: {e}"),+ internal_error: e,+ })+ },+ )?;// Drop the chat the agent is currently running inside so it never// surfaces itself in its own search results.- let mut results = response.results;+ let mut results = response+ .map(|response| response.results)+ .unwrap_or_default();+ results.extend(+ channel_response+ .into_iter()+ .flat_map(|response| response.results)+ .map(UnifiedSearchResponseItem::Channel),+ );+ results.sort_by(|a, b| {+ b.updated_at()+ .cmp(&a.updated_at())+ .then_with(|| b.entity_id().cmp(&a.entity_id()))+ });+ results.truncate(PAGE_SIZE as usize);if let Some(self_chat_id) = search_context.self_chat_id {results.retain(|item| item.entity_id() != self_chat_id);}diff --git a/crates/ai_tools/src/search/search_service/types.rs b/crates/ai_tools/src/search/search_service/types.rsindex 4a503c2fce..fd8519b7d2 100644--- a/crates/ai_tools/src/search/search_service/types.rs+++ b/crates/ai_tools/src/search/search_service/types.rs@@ -169,9 +169,9 @@ fn item_properties(item: &UnifiedSearchResponseItem) -> Option<&Vec<SoupPropertyUnifiedSearchResponseItem::Email(i) => i.properties.as_ref(),UnifiedSearchResponseItem::Project(i) => i.properties.as_ref(),UnifiedSearchResponseItem::Call(i) => i.properties.as_ref(),- UnifiedSearchResponseItem::ChannelMessage(_) | UnifiedSearchResponseItem::Company(_) => {- None- }+ UnifiedSearchResponseItem::Channel(_)+ | UnifiedSearchResponseItem::ChannelMessage(_)+ | UnifiedSearchResponseItem::Company(_) => None,}}@@ -182,8 +182,8 @@ fn item_properties_mut(item: &mut UnifiedSearchResponseItem) -> Option<&mut Vec<UnifiedSearchResponseItem::Email(i) => i.properties.as_mut(),UnifiedSearchResponseItem::Project(i) => i.properties.as_mut(),UnifiedSearchResponseItem::Call(i) => i.properties.as_mut(),- UnifiedSearchResponseItem::ChannelMessage(_) | UnifiedSearchResponseItem::Company(_) => {- None- }+ UnifiedSearchResponseItem::Channel(_)+ | UnifiedSearchResponseItem::ChannelMessage(_)+ | UnifiedSearchResponseItem::Company(_) => None,}}diff --git a/crates/models_search/src/channel.rs b/crates/models_search/src/channel.rsindex 9b37b163f1..66da311d61 100644--- a/crates/models_search/src/channel.rs+++ b/crates/models_search/src/channel.rs@@ -83,6 +83,44 @@ pub struct ChannelSearchResponseItemWithMetadata {pub extra: ChannelSearchResponseItem,}+/// Request for viewer-aware channel name search.+#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]+pub struct ChannelNameSearchRequest {+ /// Channel name prefix or exact token to search for.+ pub query: String,+ /// Whether to use prefix or exact-token matching.+ pub match_type: MatchType,+}++/// A channel-name search hit.+#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]+pub struct ChannelNameSearchResponseItem {+ /// Metadata for the channel.+ pub metadata: Option<ChannelMetadata>,+ /// Standardized id field shared by all item types; the channel id.+ pub id: uuid::Uuid,+ /// The channel owner.+ pub owner_id: Option<String>,+ /// The type of channel.+ pub channel_type: String,+ /// The channel id.+ pub channel_id: uuid::Uuid,+ /// The matched channel-name highlight.+ pub highlight: SearchHighlight,+ /// The score of the result.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub score: Option<f64>,+}++/// Response from viewer-aware channel name search.+#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]+pub struct ChannelNameSearchResponse {+ /// Matching channels in descending update order.+ pub results: Vec<ChannelNameSearchResponseItem>,+ /// Cursor for the next page, if one exists.+ pub next_cursor: Option<String>,+}+/// A single channel-message content hit in the unified search response./// One item per matching message, timestamped by the message itself, so the/// unified sort interleaves channel messages with other entity types bydiff --git a/crates/models_search/src/unified.rs b/crates/models_search/src/unified.rsindex 306c8ff377..3135adc189 100644--- a/crates/models_search/src/unified.rs+++ b/crates/models_search/src/unified.rs@@ -2,7 +2,7 @@ use chrono::{DateTime, Utc};use uuid::Uuid;use crate::call_record::CallRecordSearchResponseItemWithMetadata;-use crate::channel::ChannelMessageSearchResponseItem;+use crate::channel::{ChannelMessageSearchResponseItem, ChannelNameSearchResponseItem};use crate::chat::ChatSearchResponseItemWithMetadata;use crate::document::DocumentSearchResponseItemWithMetadata;use crate::email::EmailSearchResponseItemWithMetadata;@@ -210,6 +210,7 @@ pub enum UnifiedSearchResponseItem {Chat(ChatSearchResponseItemWithMetadata),Email(EmailSearchResponseItemWithMetadata),ChannelMessage(ChannelMessageSearchResponseItem),+ Channel(ChannelNameSearchResponseItem),Project(ProjectSearchResponseItemWithMetadata),Call(CallRecordSearchResponseItemWithMetadata),Company(crate::crm_company::CrmCompanySearchResponseItem),@@ -222,6 +223,7 @@ impl UnifiedSearchResponseItem {Self::Chat(item) => item.extra.id,Self::Email(item) => item.extra.id,Self::ChannelMessage(item) => item.channel_id,+ Self::Channel(item) => item.channel_id,Self::Project(item) => item.extra.id,Self::Call(item) => item.extra.id,Self::Company(item) => item.id,@@ -234,6 +236,7 @@ impl UnifiedSearchResponseItem {Self::Chat(item) => item.metadata.as_ref().map(|m| m.updated_at),Self::Email(item) => Some(item.updated_at),Self::ChannelMessage(item) => Some(item.updated_at),+ Self::Channel(item) => item.metadata.as_ref().map(|metadata| metadata.updated_at),Self::Project(item) => item.metadata.as_ref().map(|m| m.updated_at),Self::Call(item) => item.metadata.as_ref().map(|m| m.updated_at),Self::Company(item) => Some(item.updated_at),@@ -270,3 +273,6 @@ pub struct SimpleUnifiedSearchBaseResponse<T> {pub type SimpleUnifiedSearchResponse =SimpleUnifiedSearchBaseResponse<crate::HumanReadableTimestamp>;++#[cfg(test)]+mod test;diff --git a/crates/models_search/src/unified/test.rs b/crates/models_search/src/unified/test.rsnew file mode 100644index 0000000000..2a40729c89--- /dev/null+++ b/crates/models_search/src/unified/test.rs@@ -0,0 +1,26 @@+use super::*;++#[test]+fn empty_entity_type_filter_includes_channels() {+ let filters = SearchEntityFilters::from(entity_filters_from_include(+ vec![],+ EntityFilters::default(),+ ));++ assert!(filters.should_include_channels);+}++#[test]+fn channel_only_entity_type_filter_excludes_other_types() {+ let filters = SearchEntityFilters::from(entity_filters_from_include(+ vec![UnifiedSearchIndex::Channels],+ EntityFilters::default(),+ ));++ assert!(filters.should_include_channels);+ assert!(!filters.should_include_documents);+ assert!(!filters.should_include_chats);+ assert!(!filters.should_include_emails);+ assert!(!filters.should_include_projects);+ assert!(!filters.should_include_call_records);+}diff --git a/crates/name_search/Cargo.toml b/crates/name_search/Cargo.tomlindex 9961b62dee..b0bfde1007 100644--- a/crates/name_search/Cargo.toml+++ b/crates/name_search/Cargo.toml@@ -6,6 +6,7 @@ version = "0.1.0"[dependencies]cached = { workspace = true }+channels = { path = "../channels", default-features = false, features = ["outbound"] }chrono = { workspace = true }macro_user_id = { path = "../macro_user_id" }models_opensearch = { path = "../models_opensearch" }diff --git a/crates/name_search/fixtures/channel.sql b/crates/name_search/fixtures/channel.sqlnew file mode 100644index 0000000000..a0078f2377--- /dev/null+++ b/crates/name_search/fixtures/channel.sql@@ -0,0 +1,18 @@+INSERT INTO comms_channels (id, name, channel_type, owner_id, created_at, updated_at)+VALUES+ ('11111111-1111-1111-1111-111111111111', 'Macro', 'private', 'macro|[email protected]', '2024-01-01 10:00:00+00', '2024-12-01 10:00:00+00'),+ ('22222222-2222-2222-2222-222222222222', 'Macro Planning', 'private', 'macro|[email protected]', '2024-01-02 10:00:00+00', '2024-12-02 10:00:00+00'),+ ('33333333-3333-3333-3333-333333333333', 'Macaroni', 'private', 'macro|[email protected]', '2024-01-03 10:00:00+00', '2024-12-03 10:00:00+00'),+ ('44444444-4444-4444-4444-444444444444', 'Macro Secret', 'private', 'macro|[email protected]', '2024-01-04 10:00:00+00', '2024-12-04 10:00:00+00'),+ ('55555555-5555-5555-5555-555555555555', 'Macro Former', 'private', 'macro|[email protected]', '2024-01-05 10:00:00+00', '2024-12-05 10:00:00+00'),+ ('66666666-6666-6666-6666-666666666666', NULL, 'direct_message', 'macro|[email protected]', '2024-01-06 10:00:00+00', '2024-12-06 10:00:00+00');++INSERT INTO comms_channel_participants (channel_id, role, user_id, left_at)+VALUES+ ('11111111-1111-1111-1111-111111111111', 'owner', 'macro|[email protected]', NULL),+ ('22222222-2222-2222-2222-222222222222', 'owner', 'macro|[email protected]', NULL),+ ('33333333-3333-3333-3333-333333333333', 'owner', 'macro|[email protected]', NULL),+ ('44444444-4444-4444-4444-444444444444', 'owner', 'macro|[email protected]', NULL),+ ('55555555-5555-5555-5555-555555555555', 'owner', 'macro|[email protected]', '2024-06-01 10:00:00+00'),+ ('66666666-6666-6666-6666-666666666666', 'owner', 'macro|[email protected]', NULL),+ ('66666666-6666-6666-6666-666666666666', 'member', 'macro|[email protected]', NULL);diff --git a/crates/name_search/src/channel.rs b/crates/name_search/src/channel.rsnew file mode 100644index 0000000000..ddf72392d9--- /dev/null+++ b/crates/name_search/src/channel.rs@@ -0,0 +1,184 @@+//! This module contains logic for searching channels by name.++#[cfg(not(test))]+use cached::proc_macro::cached;+use channels::outbound::channel_name::batch_resolve_channel_names;+use macro_user_id::{+ lowercased::Lowercase,+ user_id::{MacroUserId, MacroUserIdStr},+};+use models_search_cursor::{SearchCursorOption, SearchMethodCursor};+use sqlx::{Pool, Postgres};+use uuid::Uuid;++use crate::{+ NameSearchError, NameSearchResult, PaginatedResult, SearchEntityType, escape_regex,+ highlight_name,+};++const CANDIDATE_BATCH_SIZE: i64 = 256;++/// Searches the names of channels in which the user is an active participant.+#[tracing::instrument(skip(db), err)]+#[cfg_attr(+ not(test),+ cached(+ time = 30,+ result = true,+ key = "String",+ convert = r#"{ format!("{}-{:?}-{}-{}-{}-{:?}", macro_user_id.as_ref(), channel_ids, term, exact_match, limit, cursor.as_ref().and_then(|c| c.as_updated_at()).map(|(id, ts)| format!("{}-{}", id, ts)).unwrap_or_default()) }"#+ )+)]+pub async fn search_channel_names<'a>(+ db: &Pool<Postgres>,+ macro_user_id: &MacroUserId<Lowercase<'a>>,+ channel_ids: &[Uuid],+ term: String,+ exact_match: bool,+ limit: u32,+ cursor: Option<SearchMethodCursor>,+) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {+ search_channel_names_in_batches(+ db,+ macro_user_id,+ channel_ids,+ term,+ exact_match,+ limit,+ cursor,+ CANDIDATE_BATCH_SIZE,+ )+ .await+}++#[allow(clippy::too_many_arguments)]+async fn search_channel_names_in_batches<'a>(+ db: &Pool<Postgres>,+ macro_user_id: &MacroUserId<Lowercase<'a>>,+ channel_ids: &[Uuid],+ term: String,+ exact_match: bool,+ limit: u32,+ cursor: Option<SearchMethodCursor>,+ candidate_batch_size: i64,+) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {+ if term.is_empty() {+ return Err(NameSearchError::EmptySearchTerm);+ }+ if cursor.as_ref().is_some_and(|c| c.as_updated_at().is_none()) {+ return Err(NameSearchError::IncompatibleCursor);+ }+ if channel_ids.is_empty() {+ return Ok(PaginatedResult {+ items: vec![],+ cursor: SearchCursorOption::Done,+ });+ }++ let mut scan_cursor = cursor+ .as_ref()+ .and_then(|c| c.as_updated_at())+ .map(|(id, ts)| (ts, id));+ let viewer_user_id = MacroUserIdStr(macro_user_id.clone());+ let search_pattern = if exact_match {+ format!(r"(^|\W){}($|\W)", escape_regex(&term))+ } else {+ format!(r"(^|\W){}", escape_regex(&term))+ };+ let match_pattern = regex::Regex::new(&format!("(?i){search_pattern}"))+ .expect("escaped search terms always form valid regexes");+ let match_limit = limit as usize + 1;+ let mut results = Vec::with_capacity(match_limit);++ loop {+ let (cursor_updated_at, cursor_entity_id) = scan_cursor+ .map(|(ts, id)| (Some(ts), Some(id)))+ .unwrap_or((None, None));+ let rows = sqlx::query!(+ r#"+ SELECT+ c.id as entity_id,+ c.name,+ c.updated_at+ FROM comms_channels c+ INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id+ WHERE cp.user_id = $1+ AND cp.left_at IS NULL+ AND c.id = ANY($2::uuid[])+ AND (+ $3::timestamptz IS NULL+ OR (c.updated_at, c.id) < ($3, $4)+ )+ AND (+ NULLIF(BTRIM(c.name), '') IS NULL+ OR c.name ~* $5+ )+ ORDER BY c.updated_at DESC, c.id DESC+ LIMIT $6+ "#,+ macro_user_id.as_ref(),+ channel_ids,+ cursor_updated_at,+ cursor_entity_id,+ search_pattern,+ candidate_batch_size,+ )+ .fetch_all(db)+ .await+ .map_err(NameSearchError::DatabaseError)?;++ if rows.is_empty() {+ break;+ }++ let batch_exhausted = rows.len() < candidate_batch_size as usize;+ let last = rows.last().expect("non-empty batch");+ let next_scan_cursor = (last.updated_at, last.entity_id);+ let candidate_ids: Vec<Uuid> = rows+ .iter()+ .filter(|row| row.name.as_ref().is_none_or(|name| name.trim().is_empty()))+ .map(|row| row.entity_id)+ .collect();+ let mut resolved_names =+ batch_resolve_channel_names(db, &candidate_ids, viewer_user_id.clone())+ .await+ .map_err(NameSearchError::DatabaseError)?;++ for row in rows {+ let name = match row.name.filter(|name| !name.trim().is_empty()) {+ Some(name) => name,+ None => {+ let Some(name) = resolved_names.remove(&row.entity_id) else {+ continue;+ };+ name+ }+ };+ if !match_pattern.is_match(&name) {+ continue;+ }+ let Some(name) = highlight_name(&name, &term) else {+ continue;+ };+ results.push(NameSearchResult {+ entity_id: row.entity_id,+ entity_type: SearchEntityType::Channels,+ name,+ updated_at: row.updated_at,+ });+ if results.len() == match_limit {+ break;+ }+ }++ if results.len() == match_limit || batch_exhausted {+ break;+ }+ scan_cursor = Some(next_scan_cursor);+ }++ Ok(SearchCursorOption::paginate(results, limit as usize))+}++#[cfg(test)]+mod test;diff --git a/crates/name_search/src/channel/test.rs b/crates/name_search/src/channel/test.rsnew file mode 100644index 0000000000..e25fdd3a50--- /dev/null+++ b/crates/name_search/src/channel/test.rs@@ -0,0 +1,212 @@+//! Tests for channel name search.++use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};++use super::*;++fn user(id: &str) -> MacroUserId<Lowercase<'_>> {+ MacroUserId::parse_from_str(id).unwrap().lowercase()+}++fn channel_ids() -> Vec<Uuid> {+ [+ "11111111-1111-1111-1111-111111111111",+ "22222222-2222-2222-2222-222222222222",+ "33333333-3333-3333-3333-333333333333",+ "44444444-4444-4444-4444-444444444444",+ "55555555-5555-5555-5555-555555555555",+ "66666666-6666-6666-6666-666666666666",+ ]+ .into_iter()+ .map(|id| id.parse().unwrap())+ .collect()+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn member_sees_matching_channels_but_non_member_does_not(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let member_results = search_channel_names(+ &pool,+ &user("macro|[email protected]"),+ &channel_ids(),+ "Macro".to_string(),+ false,+ 10,+ None,+ )+ .await?;++ assert_eq!(member_results.items.len(), 2);+ assert!(member_results.items.iter().all(|hit| {+ hit.entity_type == SearchEntityType::Channels+ && hit.name.contains("<macro_em>Macro</macro_em>")+ }));++ let non_member_results = search_channel_names(+ &pool,+ &user("macro|[email protected]"),+ &channel_ids(),+ "Macro".to_string(),+ false,+ 10,+ None,+ )+ .await?;++ assert!(non_member_results.items.is_empty());+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn partial_matches_prefix_while_exact_requires_a_complete_token(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let partial = search_channel_names(+ &pool,+ &user("macro|[email protected]"),+ &channel_ids(),+ "Mac".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(partial.items.len(), 3);++ let non_prefix = search_channel_names(+ &pool,+ &user("macro|[email protected]"),+ &channel_ids(),+ "acro".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert!(non_prefix.items.is_empty());++ let exact = search_channel_names(+ &pool,+ &user("macro|[email protected]"),+ &channel_ids(),+ "Mac".to_string(),+ true,+ 10,+ None,+ )+ .await?;+ assert!(exact.items.is_empty());++ let exact_macro = search_channel_names(+ &pool,+ &user("macro|[email protected]"),+ &channel_ids(),+ "Macro".to_string(),+ true,+ 10,+ None,+ )+ .await?;+ assert_eq!(exact_macro.items.len(), 2);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn former_participant_cannot_find_channel(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let results = search_channel_names(+ &pool,+ &user("macro|[email protected]"),+ &channel_ids(),+ "Macro".to_string(),+ false,+ 10,+ None,+ )+ .await?;++ assert!(results.items.is_empty());+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn member_can_find_direct_message_by_resolved_name(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let results = search_channel_names(+ &pool,+ &user("macro|[email protected]"),+ &channel_ids(),+ "Gab".to_string(),+ false,+ 10,+ None,+ )+ .await?;++ assert_eq!(results.items.len(), 1);+ assert_eq!(results.items[0].name, "<macro_em>gab</macro_em>riel");+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn scans_past_non_matching_batches_and_preserves_result_cursor(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let first_page = search_channel_names_in_batches(+ &pool,+ &user("macro|[email protected]"),+ &channel_ids(),+ "Macro".to_string(),+ false,+ 1,+ None,+ 1,+ )+ .await?;++ assert_eq!(first_page.items.len(), 1);+ assert_eq!(+ first_page.items[0].entity_id,+ "22222222-2222-2222-2222-222222222222".parse::<Uuid>()?+ );+ let SearchCursorOption::NotDone(Some(cursor)) = first_page.cursor else {+ anyhow::bail!("expected another page");+ };++ let second_page = search_channel_names_in_batches(+ &pool,+ &user("macro|[email protected]"),+ &channel_ids(),+ "Macro".to_string(),+ false,+ 1,+ Some(cursor),+ 1,+ )+ .await?;++ assert_eq!(second_page.items.len(), 1);+ assert_eq!(+ second_page.items[0].entity_id,+ "11111111-1111-1111-1111-111111111111".parse::<Uuid>()?+ );+ assert!(second_page.cursor.is_done());+ Ok(())+}diff --git a/crates/name_search/src/lib.rs b/crates/name_search/src/lib.rsindex 53dafcdd06..5f1c345e00 100644--- a/crates/name_search/src/lib.rs+++ b/crates/name_search/src/lib.rs@@ -1,9 +1,11 @@#![deny(missing_docs)]//! This crate contains queries to search over macro db entities by their name+mod channel;mod chat;mod highlight;+pub use channel::search_channel_names;pub use chat::search_chat_names;pub use highlight::highlight_name;pub use models_opensearch::SearchEntityType;diff --git a/crates/search_service/src/api/search/channel.rs b/crates/search_service/src/api/search/channel.rsindex eb142c82ee..bfdce01cef 100644--- a/crates/search_service/src/api/search/channel.rs+++ b/crates/search_service/src/api/search/channel.rs@@ -1,4 +1,4 @@-use crate::api::search::simple::SearchError;+use crate::api::search::simple::{SearchError, simple_channel};use crate::api::search::terms::split_search_terms;use chrono::{DateTime, Utc};use indexmap::IndexMap;@@ -17,7 +17,8 @@ use macro_authorization::MacroAuthorizationExtractor;use macro_user_id::user_id::MacroUserId;use models_search::MatchType;use models_search::channel::{- ChannelMessageSearchResponseItem, ChannelSearchRequest, ChannelSearchResponse,+ ChannelMessageSearchResponseItem, ChannelNameSearchRequest, ChannelNameSearchResponse,+ ChannelNameSearchResponseItem, ChannelSearchRequest, ChannelSearchResponse,ChannelSearchResponseItem, ChannelSearchResponseItemWithMetadata, ChannelSearchResult,ChannelSortTimestamp,};@@ -127,6 +128,47 @@ pub(in crate::api::search) async fn enrich_channel_messages())}+/// Enriches channel name hits with channel metadata.+#[tracing::instrument(skip(ctx, results), err)]+pub(in crate::api::search) async fn enrich_channel_names(+ ctx: &SearchHandlerState,+ user_id: &str,+ results: Vec<opensearch_client::search::model::SearchHit>,+) -> Result<Vec<ChannelNameSearchResponseItem>, SearchError> {+ if results.is_empty() {+ return Ok(vec![]);+ }++ let (channel_histories, _) = fetch_channel_enrichment(ctx, user_id, &results).await?;+ Ok(construct_channel_name_items(results, channel_histories))+}++fn construct_channel_name_items(+ search_results: Vec<opensearch_client::search::model::SearchHit>,+ channel_histories: HashMap<Uuid, ChannelHistoryInfo>,+) -> Vec<ChannelNameSearchResponseItem> {+ search_results+ .into_iter()+ .filter_map(|hit| {+ let info = channel_histories.get(&hit.entity_id)?;+ Some(ChannelNameSearchResponseItem {+ metadata: Some(models_search::channel::ChannelMetadata {+ created_at: info.created_at,+ updated_at: info.updated_at,+ viewed_at: info.viewed_at,+ interacted_at: info.interacted_at,+ }),+ id: hit.entity_id,+ owner_id: Some(info.user_id.clone()),+ channel_type: info.channel_type.clone(),+ channel_id: hit.entity_id,+ highlight: hit.highlight.into(),+ score: hit.score,+ })+ })+ .collect()+}+/// Builds one per-message item per content hit. Drops hits whose channel has/// no history info for the caller (no access / channel gone) and hits whose/// message no longer exists in the DB (stale OpenSearch entries); soft-deleted@@ -251,7 +293,68 @@ pub fn construct_search_result(}pub fn router() -> Router<SearchHandlerState> {- Router::new().route("/", post(handler))+ Router::new()+ .route("/", post(handler))+ .route("/name", post(name_handler))+}++/// Internal viewer-aware channel name search used by AI NameSearch.+pub async fn name_handler(+ State(ctx): State<SearchHandlerState>,+ authorization: MacroAuthorizationExtractor<SearchAuthorizationService>,+ extract::Query(query_params): extract::Query<SearchPaginationParams>,+ extract::Json(req): extract::Json<ChannelNameSearchRequest>,+) -> Result<Json<ChannelNameSearchResponse>, SearchError> {+ if !authorization.is_internal_access {+ return Err(SearchError::InternalAccessRequired);+ }++ let query = req.query.trim();+ if query.len() < 3 {+ return Err(SearchError::InvalidQuerySize);+ }+ let page_size = query_params.page_size.unwrap_or(10);+ if !(0..=100).contains(&page_size) {+ return Err(SearchError::InvalidPageSize);+ }++ let user_id = MacroUserId::parse_from_str(&authorization.user_context.user_id)+ .map_err(|_| SearchError::InvalidUserId(authorization.user_context.user_id.clone()))?+ .lowercase();+ let filters = item_filters::ChannelFilters::default();+ let channels = simple_channel::filter_channels(+ &ctx,+ user_id.as_ref(),+ authorization.user_context.organization_id,+ &filters,+ )+ .await?;+ let cursor = query_params+ .cursor+ .as_deref()+ .and_then(SearchMethodCursor::decode)+ .map(|cursor| SearchCursorOption::NotDone(Some(cursor)))+ .unwrap_or_default();+ let (hits, next_cursor) = simple_channel::search_names(+ &ctx.db,+ &user_id,+ &channels,+ query.to_string(),+ req.match_type == MatchType::Exact,+ page_size,+ cursor,+ )+ .await?;+ let results = enrich_channel_names(&ctx, user_id.as_ref(), hits).await?;+ let next_cursor = match next_cursor {+ SearchCursorOption::NotDone(Some(cursor)) => cursor.encode(),+ _ => None,+ };++ Ok(Json(ChannelNameSearchResponse {+ results,+ next_cursor,+ }))}/// Channel content search.diff --git a/crates/search_service/src/api/search/channel/test.rs b/crates/search_service/src/api/search/channel/test.rsindex a76c983084..d47b3aaee8 100644--- a/crates/search_service/src/api/search/channel/test.rs+++ b/crates/search_service/src/api/search/channel/test.rs@@ -32,6 +32,34 @@ fn test_construct_search_result_empty_input() {assert_eq!(result.unwrap().len(), 0);}+#[test]+fn channel_name_hit_has_top_level_highlight() {+ let channel_id: Uuid = "550e8400-e29b-41d4-a716-446655440000".parse().unwrap();+ let hit = opensearch_client::search::model::SearchHit {+ entity_id: channel_id,+ entity_type: SearchEntityType::Channels,+ score: None,+ highlight: Highlight {+ name: Some("<macro_em>acme-h</macro_em>q".to_string()),+ ..Default::default()+ },+ goto: None,+ updated_at: Some(Utc::now()),+ };+ let histories = HashMap::from([(channel_id, create_channel_history(&channel_id.to_string()))]);++ let items = construct_channel_name_items(vec![hit], histories);++ assert_eq!(items.len(), 1);+ assert_eq!(+ items[0].highlight.name.as_deref(),+ Some("<macro_em>acme-h</macro_em>q")+ );+ let json = serde_json::to_value(&items[0]).unwrap();+ assert!(json.get("highlight").is_some());+ assert!(json.get("channel_message_search_results").is_none());+}+#[test]fn test_construct_search_result_single_channel() {let channel_uuid: Uuid = "550e8400-e29b-41d4-a716-446655440000".parse().unwrap();diff --git a/crates/search_service/src/api/search/simple/mod.rs b/crates/search_service/src/api/search/simple/mod.rsindex eb3329a6ce..2d0b4ca2c8 100644--- a/crates/search_service/src/api/search/simple/mod.rs+++ b/crates/search_service/src/api/search/simple/mod.rs@@ -26,6 +26,9 @@ pub enum SearchError {/// No user id found in user context#[error("no user id found in user context")]NoUserId,+ /// The endpoint only accepts internal service authentication.+ #[error("internal access required")]+ InternalAccessRequired,/// Invalid macro user id#[error("invalid macro user id {0}")]InvalidUserId(String),@@ -64,7 +67,9 @@ pub enum SearchError {impl IntoResponse for SearchError {fn into_response(self) -> Response {let status_code = match self {- SearchError::NoUserId | SearchError::InvalidUserId(_) => StatusCode::UNAUTHORIZED,+ SearchError::NoUserId+ | SearchError::InternalAccessRequired+ | SearchError::InvalidUserId(_) => StatusCode::UNAUTHORIZED,SearchError::InvalidPageSize| SearchError::InvalidQuerySize| SearchError::TooManyTermsdiff --git a/crates/search_service/src/api/search/simple/simple_channel.rs b/crates/search_service/src/api/search/simple/simple_channel.rsindex 4275a459fc..3d42e738a4 100644--- a/crates/search_service/src/api/search/simple/simple_channel.rs+++ b/crates/search_service/src/api/search/simple/simple_channel.rs@@ -1,13 +1,66 @@use crate::api::search::simple::SearchError;use item_filters::ChannelFilters;+use macro_user_id::user_id::MacroUserId;+use opensearch_client::search::model::{Highlight, SearchHit};use std::collections::HashSet;use crate::api::context::SearchHandlerState;+#[derive(Debug, Clone)]pub(in crate::api::search) struct FilterChannelResponse {pub channel_ids: Vec<sqlx::types::Uuid>,}+/// Performs the name search over channel names.+#[allow(clippy::too_many_arguments)]+#[tracing::instrument(skip(db), err)]+pub(in crate::api::search) async fn search_names<'a>(+ db: &sqlx::Pool<sqlx::Postgres>,+ user_id: &MacroUserId<macro_user_id::lowercased::Lowercase<'a>>,+ filter_channel_response: &FilterChannelResponse,+ term: String,+ exact_match: bool,+ limit: u32,+ cursor: models_search_cursor::SearchCursorOption,+) -> Result<(Vec<SearchHit>, models_search_cursor::SearchCursorOption), SearchError> {+ let inner_cursor = match cursor {+ models_search_cursor::SearchCursorOption::Done => {+ return Ok((vec![], models_search_cursor::SearchCursorOption::Done));+ }+ models_search_cursor::SearchCursorOption::NotDone(c) => c,+ };++ name_search::search_channel_names(+ db,+ user_id,+ &filter_channel_response.channel_ids,+ term,+ exact_match,+ limit,+ inner_cursor,+ )+ .await+ .map_err(SearchError::NameSearch)+ .map(|response| {+ let hits = response+ .items+ .into_iter()+ .map(|result| SearchHit {+ entity_id: result.entity_id,+ entity_type: result.entity_type,+ score: None,+ highlight: Highlight {+ name: Some(result.name),+ ..Default::default()+ },+ goto: None,+ updated_at: Some(result.updated_at),+ })+ .collect();+ (hits, response.cursor)+ })+}+#[tracing::instrument(skip(ctx, filters), err)]pub(in crate::api::search) async fn filter_channels(ctx: &SearchHandlerState,diff --git a/crates/search_service_client/src/lib.rs b/crates/search_service_client/src/lib.rsindex cea7b375ba..0ea883136f 100644--- a/crates/search_service_client/src/lib.rs+++ b/crates/search_service_client/src/lib.rs@@ -1,5 +1,6 @@use constants::INTERNAL_API_KEY_HEADER;pub(crate) mod constants;+pub mod search_channel_name;pub mod search_unified;#[derive(Clone)]diff --git a/crates/search_service_client/src/search_channel_name.rs b/crates/search_service_client/src/search_channel_name.rsnew file mode 100644index 0000000000..812e753b05--- /dev/null+++ b/crates/search_service_client/src/search_channel_name.rs@@ -0,0 +1,38 @@+use crate::{SearchServiceClient, constants::INTERNAL_MACRO_USER_ID_HEADER};++impl SearchServiceClient {+ pub async fn search_channel_names(+ &self,+ user_id: &str,+ body: models_search::channel::ChannelNameSearchRequest,+ cursor: Option<String>,+ page_size: i64,+ ) -> anyhow::Result<models_search::channel::ChannelNameSearchResponse> {+ let url = format!("{}/internal/search/channel/name", self.url);+ let mut query_params: Vec<(&str, String)> = vec![("page_size", page_size.to_string())];+ if let Some(cursor) = cursor {+ query_params.push(("cursor", cursor));+ }++ let response = self+ .client+ .post(url)+ .query(&query_params)+ .header(INTERNAL_MACRO_USER_ID_HEADER, user_id)+ .json(&body)+ .send()+ .await?;++ match response.status() {+ reqwest::StatusCode::OK => Ok(response.json().await?),+ status_code => {+ let body = response.text().await?;+ anyhow::bail!(+ "unexpected response from search service status code {}: {}",+ status_code,+ body+ )+ }+ }+ }+}diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.tomlindex 92ae1d72a7..128950b25c 100644--- a/crates/workspace-hack/Cargo.toml+++ b/crates/workspace-hack/Cargo.toml@@ -51,7 +51,6 @@ fastrand = { version = "2" }flate2 = { version = "1", features = ["zlib-rs"] }foldhash = { version = "0.2" }form_urlencoded = { version = "1" }-futures = { version = "0.3" }futures-channel = { version = "0.3", features = ["sink"] }futures-core = { version = "0.3" }futures-executor = { version = "0.3" }@@ -175,7 +174,6 @@ fastrand = { version = "2" }flate2 = { version = "1", features = ["zlib-rs"] }foldhash = { version = "0.2" }form_urlencoded = { version = "1" }-futures = { version = "0.3" }futures-channel = { version = "0.3", features = ["sink"] }futures-core = { version = "0.3" }futures-executor = { version = "0.3" }