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): support call records in search (#2816)
gbirman637805872e03
diff --git a/infra/stacks/opensearch/helpers/constants.ts b/infra/stacks/opensearch/helpers/constants.tsindex 71ed5aab43..5c26fed0fa 100644--- a/infra/stacks/opensearch/helpers/constants.ts+++ b/infra/stacks/opensearch/helpers/constants.ts@@ -2,8 +2,17 @@ const CHAT_INDEX = 'chats';const DOCUMENT_INDEX = 'documents';const EMAIL_INDEX = 'emails';const CHANNEL_INDEX = 'channels';+const CALL_RECORDS_INDEX = 'call_records';+const CALL_RECORDS_ALIAS = 'call_records_alias';-export { CHAT_INDEX, DOCUMENT_INDEX, EMAIL_INDEX, CHANNEL_INDEX };+export {+ CHAT_INDEX,+ DOCUMENT_INDEX,+ EMAIL_INDEX,+ CHANNEL_INDEX,+ CALL_RECORDS_INDEX,+ CALL_RECORDS_ALIAS,+};export const SHARD_SETTINGS =process.env.ENVIRONMENT === 'prod'diff --git a/infra/stacks/opensearch/helpers/scripts/create_indices.ts b/infra/stacks/opensearch/helpers/scripts/create_indices.tsindex 1f9bf9be6d..5908903055 100644--- a/infra/stacks/opensearch/helpers/scripts/create_indices.ts+++ b/infra/stacks/opensearch/helpers/scripts/create_indices.ts@@ -1,6 +1,8 @@import type { Client } from '@opensearch-project/opensearch';import { client } from '../client';import {+ CALL_RECORDS_ALIAS,+ CALL_RECORDS_INDEX,CHANNEL_INDEX,CHAT_INDEX,DOCUMENT_INDEX,@@ -17,7 +19,7 @@ async function createChannelIndex(opensearchClient: Client) {if (!channelIndexExists) {console.log(`${CHANNEL_INDEX} index does not exist, creating...`);- opensearchClient.indices.create({+ await opensearchClient.indices.create({index: CHANNEL_INDEX,body: {settings: {@@ -89,7 +91,7 @@ async function createDocumentIndex(opensearchClient: Client) {if (!documentIndexExists) {console.log(`${DOCUMENT_INDEX} index does not exist, creating...`);- opensearchClient.indices.create({+ await opensearchClient.indices.create({index: DOCUMENT_INDEX,body: {settings: {@@ -166,7 +168,7 @@ async function createChatIndex(opensearchClient: Client) {if (!chatIndexExists) {console.log(`${CHAT_INDEX} index does not exist, creating...`);- opensearchClient.indices.create({+ await opensearchClient.indices.create({index: CHAT_INDEX,body: {settings: {@@ -234,7 +236,7 @@ async function createEmailIndex(opensearchClient: Client) {if (!emailIndexExists) {console.log(`${EMAIL_INDEX} index does not exist, creating...`);- opensearchClient.indices.create({+ await opensearchClient.indices.create({index: EMAIL_INDEX,body: {settings: {@@ -345,6 +347,100 @@ async function createEmailIndex(opensearchClient: Client) {}}+async function createCallRecordsIndex(opensearchClient: Client) {+ const callRecordsIndexExists = (+ await opensearchClient.indices.exists({+ index: CALL_RECORDS_INDEX,+ })+ ).body;+ if (!callRecordsIndexExists) {+ console.log(`${CALL_RECORDS_INDEX} index does not exist, creating...`);++ await opensearchClient.indices.create({+ index: CALL_RECORDS_INDEX,+ body: {+ settings: {+ ...SHARD_SETTINGS,+ refresh_interval: '2s',+ },+ aliases: {+ [CALL_RECORDS_ALIAS]: {},+ },+ // One doc per transcript segment; `_id` is the `transcript_id`.+ mappings: {+ dynamic: 'false',+ properties: {+ entity_id: {+ type: 'keyword',+ },+ transcript_id: {+ type: 'keyword',+ index: false,+ doc_values: true,+ },+ channel_id: {+ type: 'keyword',+ index: true,+ doc_values: true,+ },+ participant_ids: {+ type: 'keyword',+ index: true,+ doc_values: true,+ },+ channel_name: {+ type: 'text',+ fields: {+ keyword: {+ type: 'keyword',+ ignore_above: 128,+ },+ },+ },+ speaker_id: {+ type: 'keyword',+ index: true,+ doc_values: true,+ },+ sequence_num: {+ type: 'integer',+ index: false,+ doc_values: true,+ },+ content: {+ type: 'text',+ analyzer: 'standard',+ },+ started_at_seconds: {+ type: 'date',+ format: 'epoch_second',+ index: false,+ doc_values: true,+ },+ ended_at_seconds: {+ type: 'date',+ format: 'epoch_second',+ index: false,+ doc_values: true,+ },+ // Aliases for the shared `updated_at_sort` script.+ created_at_seconds: {+ type: 'alias',+ path: 'started_at_seconds',+ },+ updated_at_seconds: {+ type: 'alias',+ path: 'started_at_seconds',+ },+ },+ },+ },+ });+ } else {+ console.log(`${CALL_RECORDS_INDEX} index already exists`);+ }+}+async function createIndices() {const opensearchClient = client();console.log('Creating indices...');@@ -354,6 +450,7 @@ async function createIndices() {await createChatIndex(opensearchClient);await createEmailIndex(opensearchClient);await createChannelIndex(opensearchClient);+ await createCallRecordsIndex(opensearchClient);console.log('done');} catch (error) {console.error('Error', error);diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/active-filter-chips.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/active-filter-chips.tsxindex 7d75f82b40..544fed4ecd 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/active-filter-chips.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/active-filter-chips.tsx@@ -62,6 +62,8 @@ export type ActiveFilter = {*/isPopupOpen?: Accessor<boolean>;setPopupOpen?: (v: boolean) => void;+ /** Per-chip override for the container-level `hideCategoryLabel`. */+ hideCategoryLabel?: boolean;};interface ActiveFilterChipsProps {@@ -128,7 +130,11 @@ const SearchableFilterChip = (props: {)}</Show><span class="font-medium">- <Show when={!props.hideCategoryLabel}>+ <Show+ when={+ !(props.filter.hideCategoryLabel ?? props.hideCategoryLabel)+ }+ >{props.filter.categoryLabel}:{' '}</Show>{props.filter.optionLabel()}@@ -188,7 +194,11 @@ const FilterChip = (props: {)}</Show><span class="font-medium">- <Show when={!props.hideCategoryLabel}>+ <Show+ when={+ !(props.filter.hideCategoryLabel ?? props.hideCategoryLabel)+ }+ >{props.filter.categoryLabel}:{' '}</Show>{props.filter.optionLabel()}@@ -211,7 +221,11 @@ const FilterChip = (props: {)}</Show><span class="font-medium">- <Show when={!props.hideCategoryLabel}>+ <Show+ when={+ !(props.filter.hideCategoryLabel ?? props.hideCategoryLabel)+ }+ >{props.filter.categoryLabel}:{' '}</Show>{props.filter.optionLabel()}diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/search-filter-controls.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/search-filter-controls.tsxindex a8805f453e..d036999049 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/search-filter-controls.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/search-filter-controls.tsx@@ -12,7 +12,13 @@ import {} from '@app/component/next-soup/soup-view/soup-view-cache-key';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';import type { SoupBody } from '@queries/soup/items';-import { batch, createMemo, type JSX } from 'solid-js';+import {+ type Accessor,+ batch,+ createEffect,+ createMemo,+ type JSX,+} from 'solid-js';import type { Option } from './filter-primitives';import type {ChannelFilters,@@ -26,16 +32,14 @@ export type SearchableOption = {};/**- * Shared option accessors for search view's In/From pickers. Used both by the- * Filter menu submenus and by the active-filter chips.+ * Picker for the "In" chip (channels + DMs). Used by channel-message and+ * call-record search.*/-export function useSearchFilterOptions() {+function useChannelPicker() {const { useList } = useQuickAccess();- const currentUserId = useUserId();const channels = useList('channel', 'dm');- const senders = useList('person');- const channelOptions = createMemo((): SearchableOption[] =>+ const options = createMemo((): SearchableOption[] =>channels().filter((ch) => ch.data.name).map((ch) => ({@@ -53,11 +57,29 @@ export function useSearchFilterOptions() {})));- const senderOptions = createMemo((): SearchableOption[] => {+ const labelMap = createMemo(() => {+ const map = new Map<string, string>();+ for (const opt of options()) map.set(opt.id, opt.label);+ return map;+ });++ return { options, labelMap };+}++/**+ * Picker for the "From" chip (people). Used by channel-message sender+ * filter and call-record speaker filter.+ */+function usePersonPicker() {+ const { useList } = useQuickAccess();+ const currentUserId = useUserId();+ const people = useList('person');++ const options = createMemo((): SearchableOption[] => {const uid = currentUserId();let me: SearchableOption | undefined;const others: SearchableOption[] = [];- for (const s of senders()) {+ for (const s of people()) {const opt: SearchableOption = {id: s.id,label:@@ -72,7 +94,30 @@ export function useSearchFilterOptions() {return [...(me ? [me] : []), ...others];});- return { channelOptions, senderOptions };+ const labelMap = createMemo(() => {+ const map = new Map<string, string>();+ for (const opt of options()) map.set(opt.id, opt.label);+ return map;+ });++ return { options, labelMap };+}++/**+ * Shared options + label maps for the In (channel) and From (person)+ * search-filter chips. Both are reused across channel-message and+ * call-record search.+ */+export function useSearchFilterOptions() {+ const channel = useChannelPicker();+ const person = usePersonPicker();++ return {+ channelOptions: channel.options,+ channelLabelMap: channel.labelMap,+ senderOptions: person.options,+ senderLabelMap: person.labelMap,+ };}export type ChannelSubFilters = Pick<@@ -80,6 +125,11 @@ export type ChannelSubFilters = Pick<'channel_ids' | 'sender_ids'>;export type EmailSubFilters = Pick<EmailFilters, 'importance'>;+export type CallSubFilters = {+ channel_ids?: string[];+ speaker_ids?: string[];+ attended?: boolean | null;+};export function getCachedChannelSubFilters(contentId: string@@ -137,6 +187,162 @@ export function cacheEmailSubFilters(}}+export function getCachedCallSubFilters(contentId: string): CallSubFilters {+ if ((activeSoupViewCounts.get(contentId) ?? 0) > 1) return {};+ try {+ const raw = localStorage.getItem(+ soupViewCacheKey(contentId, 'call-sub-filters')+ );+ return raw ? JSON.parse(raw) : {};+ } catch {+ return {};+ }+}++export function cacheCallSubFilters(+ contentId: string,+ filters: CallSubFilters+) {+ if ((activeSoupViewCounts.get(contentId) ?? 0) > 1) return;+ try {+ localStorage.setItem(+ soupViewCacheKey(contentId, 'call-sub-filters'),+ JSON.stringify(filters)+ );+ } catch {+ // best-effort+ }+}++type SearchFilterHookOpts = {+ contentId: string;+ isSearchView: Accessor<boolean>;+};++/** Channel-message search filters (in:, from:). */+export function useChannelSearchFilter(opts: SearchFilterHookOpts) {+ const { soup, queryFilters, setQueryFilters } = useSoupView();+ const { changeIndex } = useSearchIndexController();++ const isActive = () => soup.filters.isActive('channels');+ const mutate = <K extends keyof ChannelFilters>(+ field: K,+ value: ChannelFilters[K]+ ) =>+ batch(() => {+ if (!isActive()) changeIndex('channels');+ setQueryFilters((prev) => ({+ ...prev,+ channel_filters: { ...prev.channel_filters, [field]: value },+ }));+ });++ const channelIds = createMemo(+ () => queryFilters().channel_filters?.channel_ids ?? []+ );+ const senderIds = createMemo(+ () => queryFilters().channel_filters?.sender_ids ?? []+ );++ createEffect(() => {+ if (!opts.isSearchView() || !isActive()) return;+ const sub: ChannelSubFilters = {};+ if (channelIds().length) sub.channel_ids = channelIds();+ if (senderIds().length) sub.sender_ids = senderIds();+ cacheChannelSubFilters(opts.contentId, sub);+ });++ return {+ isActive,+ channelIds,+ setChannelIds: (ids: string[]) =>+ mutate('channel_ids', ids.length ? ids : undefined),+ senderIds,+ setSenderIds: (ids: string[]) =>+ mutate('sender_ids', ids.length ? ids : undefined),+ };+}++/** Email search filters (importance). */+export function useEmailSearchFilter(opts: SearchFilterHookOpts) {+ const { soup, queryFilters, setQueryFilters } = useSoupView();+ const { changeIndex } = useSearchIndexController();++ const isActive = () => soup.filters.isActive('email');+ const importance = createMemo(() => queryFilters().email_filters?.importance);++ const setImportance = (val: boolean | undefined) =>+ batch(() => {+ if (!isActive()) changeIndex('email');+ setQueryFilters((prev) => ({+ ...prev,+ email_filters: { ...prev.email_filters, importance: val },+ }));+ });++ createEffect(() => {+ if (!opts.isSearchView() || !isActive()) return;+ cacheEmailSubFilters(opts.contentId, { importance: importance() ?? null });+ });++ return { isActive, importance, setImportance };+}++type CallFieldMap = {+ channel_ids: string[] | undefined;+ speaker_ids: string[] | undefined;+ attended: boolean | undefined;+};++/** Call-record search filters (in:, from:, attended). */+export function useCallSearchFilter(opts: SearchFilterHookOpts) {+ const { soup, queryFilters, setQueryFilters } = useSoupView();+ const { changeIndex } = useSearchIndexController();++ const isActive = () => soup.filters.isActive('calls');+ const mutate = <K extends keyof CallFieldMap>(+ field: K,+ value: CallFieldMap[K]+ ) =>+ batch(() => {+ if (!isActive()) changeIndex('calls');+ setQueryFilters((prev) => ({+ ...prev,+ call_filters: { ...prev.call_filters, [field]: value },+ }));+ });++ const channelIds = createMemo(+ () => queryFilters().call_filters?.channel_ids ?? []+ );+ const speakerIds = createMemo(+ () => queryFilters().call_filters?.speaker_ids ?? []+ );+ const attended = createMemo(() => queryFilters().call_filters?.attended);++ createEffect(() => {+ if (!opts.isSearchView() || !isActive()) return;+ const sub: CallSubFilters = {};+ if (channelIds().length) sub.channel_ids = channelIds();+ if (speakerIds().length) sub.speaker_ids = speakerIds();+ if (attended() !== undefined && attended() !== null)+ sub.attended = attended();+ cacheCallSubFilters(opts.contentId, sub);+ });++ return {+ isActive,+ channelIds,+ setChannelIds: (ids: string[]) =>+ mutate('channel_ids', ids.length ? ids : undefined),+ speakerIds,+ setSpeakerIds: (ids: string[]) =>+ mutate('speaker_ids', ids.length ? ids : undefined),+ attended,+ setAttended: (val: boolean | undefined) => mutate('attended', val),+ };+}+export function useSearchIndexController() {const { soup, setQueryFilters } = useSoupView();const panel = useSplitPanelOrThrow();@@ -185,6 +391,21 @@ export function useSearchIndexController() {importance,},});+ } else if (opt.value === 'calls') {+ const cached = getCachedCallSubFilters(contentId);+ const attended =+ 'attended' in cached+ ? (cached.attended ?? undefined)+ : opt.queryFilters.call_filters?.attended;+ setQueryFilters({+ ...opt.queryFilters,+ call_filters: {+ ...opt.queryFilters.call_filters,+ channel_ids: cached.channel_ids,+ speaker_ids: cached.speaker_ids,+ attended,+ },+ });} else {setQueryFilters({ ...opt.queryFilters });}@@ -221,6 +442,12 @@ export const INDEX_OPTIONS: (Option & { queryFilters: SoupBody })[] = [icon: () => <EntityIcon targetType="email" size="xs" theme="monochrome" />,queryFilters: QUERY_FILTERS.email,},+ {+ value: 'calls',+ label: 'Calls',+ icon: () => <EntityIcon targetType="call" size="xs" theme="monochrome" />,+ queryFilters: QUERY_FILTERS.calls,+ },{value: 'folders',label: 'Folders',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 2bf6135cea..c58f477a34 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@@ -1,4 +1,5 @@import { DropdownMenu } from '@kobalte/core/dropdown-menu';+import { match } from 'ts-pattern';import { cn } from '@ui/utils/classname';import { Button } from '@app/component/next-soup/soup-view/filters-bar/button';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';@@ -7,7 +8,6 @@ import { isListViewID } from '@app/constants/list-views';import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-context';import {type Accessor,- batch,createEffect,createMemo,createSignal,@@ -34,11 +34,11 @@ import { registerHotkey } from '@core/hotkey/hotkeys';import { LabelAndHotKey, Tooltip } from '@core/component/Tooltip';import {INDEX_OPTIONS,- cacheChannelSubFilters,- cacheEmailSubFilters,+ useCallSearchFilter,+ useChannelSearchFilter,+ useEmailSearchFilter,useSearchFilterOptions,useSearchIndexController,- type ChannelSubFilters,type SearchableOption,} from './search-filter-controls';@@ -419,16 +419,228 @@ const SearchableFilterSubmenu = (props: {);};+/** Single-value sub-menu (e.g. Importance, Attended). */+function SingleValueSubmenu<T>(props: {+ label: string;+ options: { label: string; value: T }[];+ current: Accessor<T>;+ onSelect: (value: T) => void;+}) {+ return (+ <DropdownMenu.Sub gutter={4}>+ <DropdownMenu.SubTrigger class="w-full flex items-center justify-between gap-2 px-3 py-1.5 rounded-xs text-left text-xs transition-colors hover:bg-hover outline-none data-highlighted:bg-hover">+ <span class="text-ink">{props.label}</span>+ <CaretRightIcon class="size-3 text-ink-muted" />+ </DropdownMenu.SubTrigger>+ <DropdownMenu.Portal>+ <DropdownMenu.SubContent class="z-action-menu bg-menu border border-edge-muted rounded-sm shadow-xl min-w-[160px] p-1">+ <For each={props.options}>+ {(option) => {+ const active = () => props.current() === option.value;+ return (+ <DropdownMenu.Item+ class="w-full flex items-center gap-2.5 px-3 py-1.5 rounded-xs text-left text-xs transition-colors hover:bg-hover outline-none data-highlighted:bg-hover"+ onSelect={() => props.onSelect(option.value)}+ closeOnSelect+ >+ <TypeIndicator active={active()} />+ <span+ class={cn(+ 'flex-1 truncate',+ active() ? 'text-ink' : 'text-ink-muted'+ )}+ >+ {option.label}+ </span>+ </DropdownMenu.Item>+ );+ }}+ </For>+ </DropdownMenu.SubContent>+ </DropdownMenu.Portal>+ </DropdownMenu.Sub>+ );+}++type InFromOpen = 'in' | 'from' | null;++/** In + From (channel messages). */+const ChannelSearchSubContent = (props: {+ channel: ReturnType<typeof useChannelSearchFilter>;+ channelOptions: Accessor<SearchableOption[]>;+ senderOptions: Accessor<SearchableOption[]>;+}) => {+ const [openSub, setOpenSub] = createSignal<InFromOpen>(null);+ return (+ <>+ <SearchableFilterSubmenu+ label="In"+ options={props.channelOptions}+ activeIds={props.channel.channelIds}+ onChange={props.channel.setChannelIds}+ placeholder="Search channels..."+ open={() => openSub() === 'in'}+ onOpenChange={(v) => setOpenSub(v ? 'in' : null)}+ />+ <SearchableFilterSubmenu+ label="From"+ options={props.senderOptions}+ activeIds={props.channel.senderIds}+ onChange={props.channel.setSenderIds}+ placeholder="Search senders..."+ open={() => openSub() === 'from'}+ onOpenChange={(v) => setOpenSub(v ? 'from' : null)}+ />+ </>+ );+};++const IMPORTANCE_OPTIONS: {+ label: string;+ value: boolean | undefined;+}[] = [+ { label: 'Signal', value: true },+ { label: 'Noise', value: false },+ { label: 'All', value: undefined },+];++/** Importance (emails). */+const EmailSearchSubContent = (props: {+ email: ReturnType<typeof useEmailSearchFilter>;+}) => (+ <SingleValueSubmenu+ label="Importance"+ options={IMPORTANCE_OPTIONS}+ current={props.email.importance}+ onSelect={props.email.setImportance}+ />+);++const ATTENDED_OPTIONS: {+ label: string;+ value: boolean | undefined;+}[] = [+ { label: 'Attended', value: true },+ { label: 'Unattended', value: false },+ { label: 'All', value: undefined },+];++/** In + From + Attended (calls). */+const CallSearchSubContent = (props: {+ call: ReturnType<typeof useCallSearchFilter>;+ channelOptions: Accessor<SearchableOption[]>;+ senderOptions: Accessor<SearchableOption[]>;+}) => {+ const [openSub, setOpenSub] = createSignal<InFromOpen>(null);+ return (+ <>+ <SearchableFilterSubmenu+ label="In"+ options={props.channelOptions}+ activeIds={props.call.channelIds}+ onChange={props.call.setChannelIds}+ placeholder="Search channels..."+ open={() => openSub() === 'in'}+ onOpenChange={(v) => setOpenSub(v ? 'in' : null)}+ />+ <SearchableFilterSubmenu+ label="From"+ options={props.senderOptions}+ activeIds={props.call.speakerIds}+ onChange={props.call.setSpeakerIds}+ placeholder="Search speakers..."+ open={() => openSub() === 'from'}+ onOpenChange={(v) => setOpenSub(v ? 'from' : null)}+ />+ <SingleValueSubmenu+ label="Attended"+ options={ATTENDED_OPTIONS}+ current={() => props.call.attended() ?? undefined}+ onSelect={props.call.setAttended}+ />+ </>+ );+};++/** One row in the Type picker — a flat item, or a Sub with nested filters. */+const SearchIndexRow = (props: {+ option: (typeof INDEX_OPTIONS)[number];+ active: Accessor<boolean>;+ onSelect: () => void;+ closeRoot: () => void;+ subContent?: JSX.Element;+}) => (+ <Show+ when={props.subContent !== undefined}+ fallback={+ <DropdownMenu.Item+ class="w-full flex items-center gap-2.5 px-3 py-1.5 rounded-xs text-left text-xs transition-colors hover:bg-hover outline-none data-highlighted:bg-hover"+ onSelect={props.onSelect}+ closeOnSelect+ >+ <TypeIndicator active={props.active()} />+ <Show when={props.option.icon}>+ {(icon) => (+ <span class="size-4 flex items-center justify-center shrink-0">+ {icon()()}+ </span>+ )}+ </Show>+ <span+ class={cn(+ 'flex-1 truncate',+ props.active() ? 'text-ink' : 'text-ink-muted'+ )}+ >+ {props.option.label}+ </span>+ </DropdownMenu.Item>+ }+ >+ <DropdownMenu.Sub gutter={4}>+ <DropdownMenu.SubTrigger+ class="w-full flex items-center gap-2.5 px-3 py-1.5 rounded-xs text-left text-xs transition-colors hover:bg-hover outline-none data-highlighted:bg-hover"+ onPointerDown={props.onSelect}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ e.stopPropagation();+ props.onSelect();+ props.closeRoot();+ }+ }}+ >+ <TypeIndicator active={props.active()} />+ <Show when={props.option.icon}>+ {(icon) => (+ <span class="size-4 flex items-center justify-center shrink-0">+ {icon()()}+ </span>+ )}+ </Show>+ <span+ class={cn(+ 'flex-1 truncate',+ props.active() ? 'text-ink' : 'text-ink-muted'+ )}+ >+ {props.option.label}+ </span>+ <CaretRightIcon class="size-3 text-ink-muted" />+ </DropdownMenu.SubTrigger>+ <DropdownMenu.Portal>+ <DropdownMenu.SubContent class="z-action-menu bg-menu border border-edge-muted rounded-sm shadow-xl min-w-[180px] p-1">+ {props.subContent}+ </DropdownMenu.SubContent>+ </DropdownMenu.Portal>+ </DropdownMenu.Sub>+ </Show>+);+export const UnifiedFilterDropdown = () => {const [open, setOpen] = createSignal(false);const panel = useSplitPanelOrThrow();- const {- soup,- queryFilters,- setQueryFilters,- assigneeFilter,- setAssigneeFilter,- } = useSoupView();+ const { soup, assigneeFilter, setAssigneeFilter } = useSoupView();const contacts = useContacts();const userId = useUserId();const contentId = panel.handle.content().id;@@ -491,82 +703,19 @@ export const UnifiedFilterDropdown = () => {});const isTasksView = () => currentView() === 'tasks';- const isSearchView = () => currentView() === 'search';- const isChannelsIndexActive = () => soup.filters.isActive('channels');- const isEmailIndexActive = () => soup.filters.isActive('email');+ const isSearchView = createMemo(() => currentView() === 'search');const hasActiveIndex = () =>INDEX_OPTIONS.some((opt) => soup.filters.isActive(opt.value));const { changeIndex: handleIndexChange } = useSearchIndexController();- createEffect(() => {- if (!isSearchView() || !isChannelsIndexActive()) return;- const cf = queryFilters().channel_filters;- const sub: ChannelSubFilters = {};- if (cf?.channel_ids?.length) sub.channel_ids = cf.channel_ids;- if (cf?.sender_ids?.length) sub.sender_ids = cf.sender_ids;- cacheChannelSubFilters(contentId, sub);- });-- createEffect(() => {- if (!isSearchView() || !isEmailIndexActive()) return;- const ef = queryFilters().email_filters;- cacheEmailSubFilters(contentId, { importance: ef?.importance ?? null });- });+ const channel = useChannelSearchFilter({ contentId, isSearchView });+ const email = useEmailSearchFilter({ contentId, isSearchView });+ const call = useCallSearchFilter({ contentId, isSearchView });const { channelOptions: inChannelOptions, senderOptions: fromSenderOptions } =useSearchFilterOptions();- const activeChannelIds: Accessor<string[]> = createMemo(- () => queryFilters().channel_filters?.channel_ids ?? []- );-- const setChannelIds = (ids: string[]) => {- batch(() => {- if (!isChannelsIndexActive()) handleIndexChange('channels');- setQueryFilters((prev) => ({- ...prev,- channel_filters: {- ...prev.channel_filters,- channel_ids: ids.length > 0 ? ids : undefined,- },- }));- });- };-- const activeSenderIds: Accessor<string[]> = createMemo(- () => queryFilters().channel_filters?.sender_ids ?? []- );-- const setSenderIds = (ids: string[]) => {- batch(() => {- if (!isChannelsIndexActive()) handleIndexChange('channels');- setQueryFilters((prev) => ({- ...prev,- channel_filters: {- ...prev.channel_filters,- sender_ids: ids.length > 0 ? ids : undefined,- },- }));- });- };-- const setImportance = (val: boolean | undefined) => {- batch(() => {- if (!isEmailIndexActive()) handleIndexChange('email');- setQueryFilters((prev) => ({- ...prev,- email_filters: { ...prev.email_filters, importance: val },- }));- });- };-- const importance = createMemo(() => queryFilters().email_filters?.importance);-- const [openChannelSub, setOpenChannelSub] = createSignal<- 'in' | 'from' | null- >(null);-registerHotkey({hotkey: 'f',scopeId: panel.splitHotkeyScope,@@ -673,167 +822,33 @@ export const UnifiedFilterDropdown = () => {<Show when={isSearchView()}><For each={INDEX_OPTIONS}>{(option) => {- const active = () =>- soup.filters.isActive(option.value);- const hasSub =- option.value === 'channels' ||- option.value === 'email';+ const subContent = match(option.value)+ .with('channels', () => (+ <ChannelSearchSubContent+ channel={channel}+ channelOptions={inChannelOptions}+ senderOptions={fromSenderOptions}+ />+ ))+ .with('email', () => (+ <EmailSearchSubContent email={email} />+ ))+ .with('calls', () => (+ <CallSearchSubContent+ call={call}+ channelOptions={inChannelOptions}+ senderOptions={fromSenderOptions}+ />+ ))+ .otherwise(() => undefined);return (- <Show- when={hasSub}- fallback={- <DropdownMenu.Item- class="w-full flex items-center gap-2.5 px-3 py-1.5 rounded-xs text-left text-xs transition-colors hover:bg-hover outline-none data-highlighted:bg-hover"- onSelect={() => handleIndexChange(option.value)}- closeOnSelect- >- <TypeIndicator active={active()} />- <Show when={option.icon}>- {(icon) => (- <span class="size-4 flex items-center justify-center shrink-0">- {icon()()}- </span>- )}- </Show>- <span- class={cn(- 'flex-1 truncate',- active() ? 'text-ink' : 'text-ink-muted'- )}- >- {option.label}- </span>- </DropdownMenu.Item>- }- >- <DropdownMenu.Sub gutter={4}>- <DropdownMenu.SubTrigger- class="w-full flex items-center gap-2.5 px-3 py-1.5 rounded-xs text-left text-xs transition-colors hover:bg-hover outline-none data-highlighted:bg-hover"- onPointerDown={() =>- handleIndexChange(option.value)- }- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- e.stopPropagation();- handleIndexChange(option.value);- setOpen(false);- }- }}- >- <TypeIndicator active={active()} />- <Show when={option.icon}>- {(icon) => (- <span class="size-4 flex items-center justify-center shrink-0">- {icon()()}- </span>- )}- </Show>- <span- class={cn(- 'flex-1 truncate',- active() ? 'text-ink' : 'text-ink-muted'- )}- >- {option.label}- </span>- <CaretRightIcon class="size-3 text-ink-muted" />- </DropdownMenu.SubTrigger>- <DropdownMenu.Portal>- <DropdownMenu.SubContent class="z-action-menu bg-menu border border-edge-muted rounded-sm shadow-xl min-w-[180px] p-1">- <Show when={option.value === 'channels'}>- <SearchableFilterSubmenu- label="In"- options={inChannelOptions}- activeIds={activeChannelIds}- onChange={setChannelIds}- placeholder="Search channels..."- open={() => openChannelSub() === 'in'}- onOpenChange={(v) =>- setOpenChannelSub(v ? 'in' : null)- }- />- <SearchableFilterSubmenu- label="From"- options={fromSenderOptions}- activeIds={activeSenderIds}- onChange={setSenderIds}- placeholder="Search senders..."- open={() => openChannelSub() === 'from'}- onOpenChange={(v) =>- setOpenChannelSub(v ? 'from' : null)- }- />- </Show>- <Show when={option.value === 'email'}>- <DropdownMenu.Sub gutter={4}>- <DropdownMenu.SubTrigger class="w-full flex items-center justify-between gap-2 px-3 py-1.5 rounded-xs text-left text-xs transition-colors hover:bg-hover outline-none data-highlighted:bg-hover">- <span class="text-ink">Importance</span>- <CaretRightIcon class="size-3 text-ink-muted" />- </DropdownMenu.SubTrigger>- <DropdownMenu.Portal>- <DropdownMenu.SubContent class="z-action-menu bg-menu border border-edge-muted rounded-sm shadow-xl min-w-[160px] p-1">- <For- each={[- {- label: 'Signal',- value: true as- | boolean- | undefined,- },- {- label: 'Noise',- value: false as- | boolean- | undefined,- },- {- label: 'All',- value: undefined as- | boolean- | undefined,- },- ]}- >- {(importanceOption) => {- const importanceActive = () =>- importance() ===- importanceOption.value;- return (- <DropdownMenu.Item- class="w-full flex items-center gap-2.5 px-3 py-1.5 rounded-xs text-left text-xs transition-colors hover:bg-hover outline-none data-highlighted:bg-hover"- onSelect={() =>- setImportance(- importanceOption.value- )- }- closeOnSelect- >- <TypeIndicator- active={importanceActive()}- />- <span- class={cn(- 'flex-1 truncate',- importanceActive()- ? 'text-ink'- : 'text-ink-muted'- )}- >- {importanceOption.label}- </span>- </DropdownMenu.Item>- );- }}- </For>- </DropdownMenu.SubContent>- </DropdownMenu.Portal>- </DropdownMenu.Sub>- </Show>- </DropdownMenu.SubContent>- </DropdownMenu.Portal>- </DropdownMenu.Sub>- </Show>+ <SearchIndexRow+ option={option}+ active={() => soup.filters.isActive(option.value)}+ onSelect={() => handleIndexChange(option.value)}+ closeRoot={() => setOpen(false)}+ subContent={subContent}+ />);}}</For>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 12a3969457..28d94989d7 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@@ -12,10 +12,11 @@ import { isListViewID } from '@app/constants/list-views';import { useUserContext, useUserId } from '@core/context/user';import { deepEqual } from '@core/util/compareUtils';import { useContacts } from '@queries/contacts/contacts';-import { batch, createMemo, createSignal } from 'solid-js';+import { type Accessor, batch, createMemo, createSignal } from 'solid-js';import type { ActiveFilter } from './active-filter-chips';import { INDEX_OPTIONS } from './search-operator-autocomplete';import {+ type SearchableOption,useSearchFilterOptions,useSearchIndexController,} from './search-filter-controls';@@ -56,7 +57,8 @@ export function useFilterRefinements() {const user = useUserContext();const contacts = useContacts();const currentUserId = useUserId();- const { channelOptions, senderOptions } = useSearchFilterOptions();+ const { channelOptions, channelLabelMap, senderOptions, senderLabelMap } =+ useSearchFilterOptions();const { changeIndex } = useSearchIndexController();const getPresetContext = (): PresetContext => ({@@ -131,21 +133,6 @@ export function useFilterRefinements() {return VIEW_FILTER_CATEGORIES[view as ListView] ?? [];});- // Reactive id → label maps derived from the chip's option sources.- // Using quickAccess.getById here would read a plain Map that isn't a signal,- // so on page reload the chip label shows the raw uuid until the first- // rerender that happens to read live data.- const channelLabelMap = createMemo(() => {- const map = new Map<string, string>();- for (const opt of channelOptions()) map.set(opt.id, opt.label);- return map;- });- const senderLabelMap = createMemo(() => {- const map = new Map<string, string>();- for (const opt of senderOptions()) map.set(opt.id, opt.label);- return map;- });-const labelForIds = (ids: string[],labelMap: Map<string, string>@@ -157,23 +144,16 @@ export function useFilterRefinements() {return `${firstLabel} and ${rest.length} ${rest.length === 1 ? 'other' : 'others'}`;};- const setChannelIds = (ids: string[]) =>- setQueryFilters((prev) => ({- ...prev,- channel_filters: {- ...prev.channel_filters,- channel_ids: ids.length > 0 ? ids : undefined,- },- }));-- const setSenderIds = (ids: string[]) =>- setQueryFilters((prev) => ({- ...prev,- channel_filters: {- ...prev.channel_filters,- sender_ids: ids.length > 0 ? ids : undefined,- },- }));+ const setFilterIds =+ (filterKey: 'channel_filters' | 'call_filters', field: string) =>+ (ids: string[]) =>+ setQueryFilters((prev) => ({+ ...prev,+ [filterKey]: {+ ...(prev[filterKey] ?? {}),+ [field]: ids.length > 0 ? ids : undefined,+ },+ }));/*** Cache of chip objects keyed by a stable id derived from the chip's category@@ -261,8 +241,40 @@ export function useFilterRefinements() {);}- // Sub-filters: assignee- const _optionsMap = assigneeOptionsMap();+ // Keep a chip alive while its popup is still open, even if the user+ // toggled every option off — closing the menu mid-swap is jarring.+ const pushSearchableChip = (args: {+ key: string;+ categoryLabel: 'In' | 'From';+ optionIdPrefix: string;+ getIds: () => string[];+ searchableOptions: Accessor<SearchableOption[]>;+ labelMap: Accessor<Map<string, string>>;+ onChange: (ids: string[]) => void;+ searchPlaceholder: string;+ }) => {+ const popupOpen = chipCache.get(args.key)?.isPopupOpen?.() ?? false;+ if (args.getIds().length === 0 && !popupOpen) return;+ seenKeys.add(args.key);+ filters.push(+ getOrCreateChip(args.key, () => {+ const [isPopupOpen, setPopupOpen] = createSignal(false);+ return {+ categoryLabel: args.categoryLabel,+ optionId: () => `${args.optionIdPrefix}:${args.getIds().join(',')}`,+ optionLabel: () => labelForIds(args.getIds(), args.labelMap()),+ searchableOptions: args.searchableOptions,+ activeSearchableIds: args.getIds,+ onSearchableChange: args.onChange,+ searchPlaceholder: args.searchPlaceholder,+ onRemove: () => args.onChange([]),+ isPopupOpen,+ setPopupOpen,+ };+ })+ );+ };+for (const id of assigneeFilter()) {const key = `Assignee|${id}`;seenKeys.add(key);@@ -277,86 +289,112 @@ export function useFilterRefinements() {);}- // Search operator filters: in: (channel_ids)- const channelIds = (- queryFilters().channel_filters?.channel_ids ?? []- ).filter((id) => id !== NIL_UUID);- // Keep the chip alive while its popup is still open, even if the user- // toggled every option off — they may be mid-way through swapping A→B- // and closing the menu on them would be jarring.- const inChipOpen = chipCache.get('In')?.isPopupOpen?.() ?? false;- if (channelIds.length > 0 || inChipOpen) {- const key = 'In';- seenKeys.add(key);- filters.push(- getOrCreateChip(key, () => {- const [isPopupOpen, setPopupOpen] = createSignal(false);- return {- categoryLabel: 'In',- optionId: () => {- const ids = (- queryFilters().channel_filters?.channel_ids ?? []- ).filter((id) => id !== NIL_UUID);- return `in:${ids.join(',')}`;- },- optionLabel: () => {- const ids = (- queryFilters().channel_filters?.channel_ids ?? []- ).filter((id) => id !== NIL_UUID);- return labelForIds(ids, channelLabelMap());- },- searchableOptions: channelOptions,- activeSearchableIds: () =>- (queryFilters().channel_filters?.channel_ids ?? []).filter(- (id) => id !== NIL_UUID- ),- onSearchableChange: setChannelIds,- searchPlaceholder: 'Search channels...',- onRemove: () => setChannelIds([]),- isPopupOpen,- setPopupOpen,- };- })- );- }+ pushSearchableChip({+ key: 'ChannelIn',+ categoryLabel: 'In',+ optionIdPrefix: 'channel-in',+ getIds: () =>+ (queryFilters().channel_filters?.channel_ids ?? []).filter(+ (id) => id !== NIL_UUID+ ),+ searchableOptions: channelOptions,+ labelMap: channelLabelMap,+ onChange: setFilterIds('channel_filters', 'channel_ids'),+ searchPlaceholder: 'Search channels...',+ });- // Search operator filters: from: (sender_ids)- const senderIds = queryFilters().channel_filters?.sender_ids ?? [];- const fromChipOpen = chipCache.get('From')?.isPopupOpen?.() ?? false;- if (senderIds.length > 0 || fromChipOpen) {- const key = 'From';- seenKeys.add(key);- filters.push(- getOrCreateChip(key, () => {- const [isPopupOpen, setPopupOpen] = createSignal(false);- return {- categoryLabel: 'From',- optionId: () => {- const ids = queryFilters().channel_filters?.sender_ids ?? [];- return `from:${ids.join(',')}`;- },- optionLabel: () => {- const ids = queryFilters().channel_filters?.sender_ids ?? [];- return labelForIds(ids, senderLabelMap());- },- searchableOptions: senderOptions,- activeSearchableIds: () =>- queryFilters().channel_filters?.sender_ids ?? [],- onSearchableChange: setSenderIds,- searchPlaceholder: 'Search senders...',- onRemove: () => setSenderIds([]),- isPopupOpen,- setPopupOpen,- };- })- );- }+ pushSearchableChip({+ key: 'ChannelFrom',+ categoryLabel: 'From',+ optionIdPrefix: 'channel-from',+ getIds: () => queryFilters().channel_filters?.sender_ids ?? [],+ searchableOptions: senderOptions,+ labelMap: senderLabelMap,+ onChange: setFilterIds('channel_filters', 'sender_ids'),+ searchPlaceholder: 'Search senders...',+ });- // Email importance (only when the email index is active in the search view- // and the user has explicitly set a value — undefined means "All", no chip)- if (currentView() === 'search' && soup.filters.isActive('email')) {- const importance = queryFilters().email_filters?.importance;- if (importance !== undefined) {+ if (currentView() === 'search') {+ if (soup.filters.isActive('calls')) {+ pushSearchableChip({+ key: 'CallIn',+ categoryLabel: 'In',+ optionIdPrefix: 'call-in',+ getIds: () =>+ (queryFilters().call_filters?.channel_ids ?? []).filter(+ (id) => id !== NIL_UUID+ ),+ searchableOptions: channelOptions,+ labelMap: channelLabelMap,+ onChange: setFilterIds('call_filters', 'channel_ids'),+ searchPlaceholder: 'Search channels...',+ });++ pushSearchableChip({+ key: 'CallFrom',+ categoryLabel: 'From',+ optionIdPrefix: 'call-from',+ getIds: () => queryFilters().call_filters?.speaker_ids ?? [],+ searchableOptions: senderOptions,+ labelMap: senderLabelMap,+ onChange: setFilterIds('call_filters', 'speaker_ids'),+ searchPlaceholder: 'Search speakers...',+ });++ const callAttended = queryFilters().call_filters?.attended;+ if (callAttended !== undefined && callAttended !== null) {+ const ATTENDED_YES = 'attended:yes';+ const ATTENDED_NO = 'attended:no';+ const key = 'CallAttended';+ seenKeys.add(key);+ filters.push(+ getOrCreateChip(key, () => ({+ categoryLabel: 'Attended',+ hideCategoryLabel: true,+ optionId: () =>+ queryFilters().call_filters?.attended+ ? ATTENDED_YES+ : ATTENDED_NO,+ optionLabel: () =>+ queryFilters().call_filters?.attended+ ? 'Attended'+ : 'Unattended',+ categoryOptions: [+ { id: ATTENDED_YES, label: 'Attended' },+ { id: ATTENDED_NO, label: 'Unattended' },+ ] as unknown as ActiveFilter['categoryOptions'],+ multiple: false,+ isOptionActive: (optionId) =>+ optionId ===+ (queryFilters().call_filters?.attended+ ? ATTENDED_YES+ : ATTENDED_NO),+ onRemove: () =>+ setQueryFilters((prev) => ({+ ...prev,+ call_filters: {+ ...prev.call_filters,+ attended: undefined,+ },+ })),+ onReplace: (newOptionId) =>+ setQueryFilters((prev) => ({+ ...prev,+ call_filters: {+ ...prev.call_filters,+ attended: newOptionId === ATTENDED_YES,+ },+ })),+ }))+ );+ }+ }++ // undefined importance means "All" — no chip.+ if (+ soup.filters.isActive('email') &&+ queryFilters().email_filters?.importance !== undefined+ ) {const IMPORTANCE_SIGNAL = 'importance:signal';const IMPORTANCE_NOISE = 'importance:noise';const key = 'Importance';diff --git a/js/app/packages/block-automation/component/Automation.tsx b/js/app/packages/block-automation/component/Automation.tsxindex 5cb1f99d12..d1b1d0f987 100644--- a/js/app/packages/block-automation/component/Automation.tsx+++ b/js/app/packages/block-automation/component/Automation.tsx@@ -33,6 +33,7 @@ import {WEEKDAY_OPTIONS,} from './automationUtils';import type { ScheduleDraft } from './types';+import { blockNameToDefaultFile } from '@core/constant/allBlocks';type HistoryRecord = {id?: string | null;@@ -242,7 +243,7 @@ export function Automation() {setRenameOpen(true);}}>- {d().name || 'Untitled automation'}+ {d().name || blockNameToDefaultFile('automation')}</span></div></SplitHeaderLeft>diff --git a/js/app/packages/block-automation/component/automationUtils.ts b/js/app/packages/block-automation/component/automationUtils.tsindex 708e6cf017..44a9a7bfa1 100644--- a/js/app/packages/block-automation/component/automationUtils.ts+++ b/js/app/packages/block-automation/component/automationUtils.ts@@ -8,6 +8,7 @@ import type {UpdateScheduledAction,} from '@service-scheduled-action/generated/schemas';import type { ScheduleDraft, ScheduleFrequency } from './types';+import { blockNameToDefaultFile } from '@core/constant/allBlocks';export const INPUT_CLASS ='w-full border border-edge-muted rounded-sm bg-input px-2 py-1.5 text-sm text-ink outline-none placeholder:text-ink/30 focus:border-accent/20 cursor-default';@@ -51,7 +52,7 @@ function normalizePrompt(value: string) {function deriveScheduleName(prompt: string) {const summary = normalizePrompt(prompt);- if (!summary) return 'Untitled automation';+ if (!summary) return blockNameToDefaultFile('automation');return summary.length > 72 ? `${summary.slice(0, 71)}…` : summary;}diff --git a/js/app/packages/block-automation/definition.ts b/js/app/packages/block-automation/definition.tsindex 6f53b1e130..4bc069cf8b 100644--- a/js/app/packages/block-automation/definition.ts+++ b/js/app/packages/block-automation/definition.ts@@ -5,7 +5,7 @@ import { Automation } from './component/Automation';export const definition = defineBlock({name: 'automation',description: 'view and edit a single automation',- defaultFilename: 'Automation',+ defaultFilename: 'Untitled automation',component: Automation,accepted: {},async load(source, intent) {diff --git a/js/app/packages/block-call/definition.ts b/js/app/packages/block-call/definition.tsindex 08408d33ba..5e85b04bb8 100644--- a/js/app/packages/block-call/definition.ts+++ b/js/app/packages/block-call/definition.ts@@ -6,6 +6,7 @@ import { CallBlockAdapter } from './component/CallBlockAdapter';export const definition = defineBlock({name: 'call',description: '',+ defaultFilename: 'Call',component: CallBlockAdapter,async load(source, _intent) {if (!ENABLE_CALLS()) return LoadErrors.MISSING;diff --git a/js/app/packages/entity/src/components/CallChannelName.tsx b/js/app/packages/entity/src/components/CallChannelName.tsxnew file mode 100644index 0000000000..372bdcec14--- /dev/null+++ b/js/app/packages/entity/src/components/CallChannelName.tsx@@ -0,0 +1,60 @@+import { blockNameToDefaultFile } from '@core/constant/allBlocks';+import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme';+import { isChannelPreviewItem, useItemPreview } from '@queries/preview';+import { Show } from 'solid-js';+import type { CallEntity } from '../types/entity';+import { isSearchEntity } from '../types/search';++/** Channel name for a call row — falls back to the preview endpoint when+ * transform-utils couldn't resolve it locally. */+export function CallChannelName(props: { entity: CallEntity }) {+ const highlight = () =>+ isSearchEntity(props.entity)+ ? (props.entity.search.nameHighlight ?? undefined)+ : undefined;++ return (+ <Show+ when={highlight()}+ fallback={<CallChannelNameText entity={props.entity} />}+ >+ {(h) => (+ <StaticMarkdown+ markdown={h()}+ theme={unifiedListMarkdownTheme}+ singleLine={true}+ />+ )}+ </Show>+ );+}++function CallChannelNameText(props: { entity: CallEntity }) {+ return (+ <Show+ when={props.entity.name}+ fallback={+ <CallChannelNameFromPreview channelId={props.entity.channelId} />+ }+ >+ {props.entity.name}+ </Show>+ );+}++// TODO: once we have call record rename/preview, we should use that instead of the channel name+function CallChannelNameFromPreview(props: { channelId: string }) {+ const [preview] = useItemPreview(() => ({+ id: props.channelId,+ type: 'channel' as const,+ }));++ const name = () => {+ const p = preview();+ if (isChannelPreviewItem(p)) return p.name;+ return blockNameToDefaultFile('call');+ };++ return <>{name()}</>;+}diff --git a/js/app/packages/entity/src/composed/ListEntity.tsx b/js/app/packages/entity/src/composed/ListEntity.tsxindex c010245426..ffce756819 100644--- a/js/app/packages/entity/src/composed/ListEntity.tsx+++ b/js/app/packages/entity/src/composed/ListEntity.tsx@@ -42,6 +42,7 @@ import {useContext,} from 'solid-js';import { AttendanceBadge, DraftBadge, SharedBadge } from '../components/Badges';+import { CallChannelName } from '../components/CallChannelName';import { MultiSelectCheckbox } from '../components/MultiSelectCheckbox';import { ProjectBreadCrumb } from '../components/ProjectBreadCrumb';import { UnreadIndicator } from '../components/UnreadIndicator';@@ -51,7 +52,9 @@ import { getActionVerb } from '../extractors-notification/notification-descriptiimport { SearchContent } from '../extractors-search/search-content';import { SearchSender } from '../extractors-search/search-sender';import {+ type CallEntity,type ChannelEntity,+ type ChannelMessageEntity,type EmailEntity,type EntityData,isCallEntity,@@ -66,10 +69,12 @@ import {} from '../types/entity';import {isWithNotification,+ type Notification,type WithNotification,} from '../types/notification';-import type { SearchLocation } from '../types/search';-import { isSearchEntity } from '../types/search';+import type { ContentHitData, SearchLocation } from '../types/search';+import { isCallRecordHit, isSearchEntity } from '../types/search';+import { matches } from '@core/util/match';import { createEntityDraggable } from '../utils/draggable';import { unreadFilterFn } from '../utils/filter';import {@@ -272,6 +277,299 @@ function ChannelMessage(props: {);}+function firstContentHit(entity: EntityData): ContentHitData | undefined {+ return isSearchEntity(entity) ? entity.search.contentHitData?.[0] : undefined;+}++// Narrow inbox body slots (one per entity type)++function ChannelMessageNarrowBody(props: { entity: ChannelMessageEntity }) {+ const hit = () => firstContentHit(props.entity);+ return (+ <Entity.Slot placement="body" class="flex flex-col pb-2 min-h-[2lh] pr-4">+ <Show when={hit()}>+ {(h) => (+ <>+ <span class="text-ink-muted text-xs flex items-center gap-1">+ <Show when={props.entity.senderId}>+ {(id) => <UserIcon id={id()} size="xs" />}+ </Show>+ <SearchSender hit={h()} />+ </span>+ <span class="text-ink-extra-muted truncate">+ <SearchContent hit={h()} />+ </span>+ </>+ )}+ </Show>+ </Entity.Slot>+ );+}++function ChannelLatestMessageNarrowBody(props: {+ message: NonNullable<ChannelEntity['latestMessage']>;+ senderFirstName?: string;+}) {+ return (+ <Entity.Slot+ placement="body"+ class="text-ink-extra-muted line-clamp-2 pb-2 min-h-[2lh] pr-4"+ >+ <Show+ when={props.message.content?.trim()}+ fallback={<span class="italic">Attached Items</span>}+ >+ <StaticMarkdown+ theme={twoLineClampMarkdownTheme}+ markdown={+ (props.senderFirstName ? `**${props.senderFirstName}:** ` : '') ++ props.message.content.trim()+ }+ singleLine+ />+ </Show>+ </Entity.Slot>+ );+}++function EmailNarrowBody(props: {+ entity: EmailEntity;+ chars: number;+ showContentHits: boolean;+ setContainerRef: (el: HTMLElement) => void;+}) {+ return (+ <Entity.Slot placement="body" class="flex flex-col pb-2 min-h-[2lh] pr-4">+ <Entity.Title entity={props.entity} />+ <span+ ref={props.setContainerRef}+ class="text-ink/50 font-medium truncate"+ >+ <EmailSnippet+ entity={props.entity}+ showContentHits={props.showContentHits}+ chars={props.chars}+ />+ </span>+ </Entity.Slot>+ );+}++function TaskNarrowBody(props: {+ entity: EntityData;+ notification?: Notification;+}) {+ return (+ <Entity.Slot placement="body" class="flex flex-col pb-2 min-h-[2lh] pr-4 ">+ <Entity.Properties entity={props.entity} />+ <Show when={props.notification}>+ {(notif) => (+ <span class="text-ink-extra-muted font-normal truncate">+ <Show when={notif().sender_id}>+ {(senderId) => (+ <>+ <DisplayName id={senderId()} format="firstName" />{' '}+ </>+ )}+ </Show>+ {getActionVerb(notif().notification_event_type as NotificationType)}+ </span>+ )}+ </Show>+ </Entity.Slot>+ );+}++function CallNarrowBody(props: {+ entity: CallEntity;+ showAttendanceBadge: boolean;+}) {+ const hit = () => firstContentHit(props.entity);+ return (+ <Entity.Slot placement="body" class="flex flex-col pb-2 min-h-[2lh] pr-4">+ <Show+ when={hit()}+ fallback={+ <span class="text-ink-muted text-xs truncate">+ <CallChannelName entity={props.entity} />+ </span>+ }+ >+ {(h) => (+ <span class="flex items-center gap-1 min-w-0 truncate">+ <Show when={matches(h(), isCallRecordHit)}>+ {(callHit) => (+ <Show when={callHit().senderId}>+ {(id) => <UserIcon id={id()} size="xs" />}+ </Show>+ )}+ </Show>+ <span class="shrink-0 text-ink-extra-muted text-xs whitespace-nowrap">+ <SearchSender hit={h()} />+ </span>+ <span class="text-ink/50 font-normal truncate min-w-0 text-xs">+ <SearchContent hit={h()} singleLine />+ </span>+ </span>+ )}+ </Show>+ <span class="text-ink-extra-muted text-xs flex items-center gap-2">+ <Show+ when={props.entity.durationMs}+ fallback={props.entity.isActive ? 'In progress' : 'No duration'}+ >+ {(ms) => formatCallDuration(ms())}+ </Show>+ <Show when={props.showAttendanceBadge}>+ <AttendanceBadge attended={props.entity.attended} />+ </Show>+ </span>+ </Entity.Slot>+ );+}++// Wide layout content slots (one per entity type)++function EmailWideContent(props: {+ entity: EmailEntity;+ chars: number;+ showContentHits: boolean;+ setContainerRef: (el: HTMLElement) => void;+}) {+ return (+ <>+ <span class="w-(--title-width) shrink-0">+ <span class="truncate max-w-32 flex gap-2 items-center">+ <EmailIdentity entity={props.entity} />+ </span>+ </span>+ <span class="truncate">+ <Entity.Title entity={props.entity} />+ </span>+ <span+ ref={props.setContainerRef}+ class="text-ink/50 font-medium truncate flex-1 inline-flex items-center"+ >+ <EmailSnippet+ entity={props.entity}+ showContentHits={props.showContentHits}+ chars={props.chars}+ />+ </span>+ </>+ );+}++function ChannelMessageWideContent(props: { entity: ChannelMessageEntity }) {+ const hit = () => firstContentHit(props.entity);+ return (+ <>+ <span class="shrink-0 flex gap-1.5 items-center">+ <span class="text-ink-muted whitespace-nowrap">+ {props.entity.channelName}+ </span>+ <Show when={props.entity.senderId}>+ {(id) => <UserIcon id={id()} size="xs" />}+ </Show>+ <Show when={hit()}>+ {(h) => (+ <span class="text-ink-extra-muted text-xs whitespace-nowrap">+ <SearchSender hit={h()} />+ </span>+ )}+ </Show>+ </span>+ <div class="text-ink/50 font-medium flex-1 min-w-0 overflow-hidden">+ <Show when={hit()} fallback={props.entity.content}>+ {(h) => <SearchContent hit={h()} singleLine />}+ </Show>+ </div>+ </>+ );+}++function ChannelWideContent(props: {+ entity: ChannelEntity;+ showLatestMessage: boolean;+}) {+ return (+ <Show+ when={props.showLatestMessage && props.entity.latestMessage}+ fallback={+ <span class="truncate flex gap-2">+ <Entity.Title entity={props.entity} />+ </span>+ }+ >+ {(msg) => (+ <>+ <span class="w-(--title-width) shrink-0 truncate flex gap-2">+ <Entity.Title entity={props.entity} />+ </span>+ <ChannelMessage message={msg()} />+ </>+ )}+ </Show>+ );+}++function CallWideContent(props: { entity: CallEntity }) {+ const hit = () => firstContentHit(props.entity);+ return (+ <>+ <span class="truncate">+ <CallChannelName entity={props.entity} />+ </span>+ <Show+ when={hit()}+ fallback={+ <span class="text-ink-extra-muted font-medium truncate">+ <Show+ when={props.entity.durationMs}+ fallback={props.entity.isActive ? 'In progress' : ''}+ >+ {(ms) => formatCallDuration(ms())}+ </Show>+ </span>+ }+ >+ {(h) => (+ <>+ <span class="shrink-0 flex gap-1.5 items-center">+ <Show when={matches(h(), isCallRecordHit)}>+ {(callHit) => (+ <Show when={callHit().senderId}>+ {(id) => <UserIcon id={id()} size="xs" />}+ </Show>+ )}+ </Show>+ <span class="text-ink-extra-muted text-xs whitespace-nowrap">+ <SearchSender hit={h()} />+ </span>+ </span>+ <div class="text-ink/50 font-medium flex-1 min-w-0 overflow-hidden">+ <SearchContent hit={h()} singleLine />+ </div>+ </>+ )}+ </Show>+ </>+ );+}++function AutomationWideContent(props: { entity: AutomationEntity }) {+ return (+ <>+ <span class="w-(--title-width) shrink-0 truncate">+ <Entity.Title entity={props.entity} />+ </span>+ <span class="">+ <AutomationSubtitle entity={props.entity} />+ </span>+ </>+ );+}+function NarrowLayout(props: LayoutProps) {return (<Entity.Layout@@ -311,7 +609,7 @@ function NarrowLayout(props: LayoutProps) {>{(entity) => {const hit = () => {- const e = entity() as EntityData;+ const e = entity();return isSearchEntity(e)? e.search.contentHitData?.[0]: undefined;@@ -474,126 +772,40 @@ function NarrowInboxLayout(props: LayoutProps) {<Switch><Match when={isChannelMessageEntity(props.entity) && props.entity}>- {(entity) => {- const hit = () => {- const e = entity() as EntityData;- return isSearchEntity(e)- ? e.search.contentHitData?.[0]- : undefined;- };- return (- <Entity.Slot- placement="body"- class="flex flex-col pb-2 min-h-[2lh] pr-4"- >- <Show when={hit()}>- {(h) => (- <>- <span class="text-ink-muted text-xs flex items-center gap-1">- <Show when={entity().senderId}>- {(id) => <UserIcon id={id()} size="xs" />}- </Show>- <SearchSender hit={h()} />- </span>- <span class="text-ink-extra-muted truncate">- <SearchContent hit={h()} />- </span>- </>- )}- </Show>- </Entity.Slot>- );- }}+ {(entity) => <ChannelMessageNarrowBody entity={entity()} />}</Match><Matchwhen={isChannelEntity(props.entity) && props.entity.latestMessage}>{(msg) => (- <Entity.Slot- placement="body"- class="text-ink-extra-muted line-clamp-2 pb-2 min-h-[2lh] pr-4"- >- <Show- when={msg().content?.trim()}- fallback={<span class="italic">Attached Items</span>}- >- <StaticMarkdown- theme={twoLineClampMarkdownTheme}- markdown={(() => {- const name = mostRecentMessageSenderName?.firstName();- return (name ? `**${name}:** ` : '') + msg().content.trim();- })()}- singleLine- />- </Show>- </Entity.Slot>+ <ChannelLatestMessageNarrowBody+ message={msg()}+ senderFirstName={mostRecentMessageSenderName?.firstName()}+ />)}</Match><Match when={isEmailEntity(props.entity) && props.entity}>{(entity) => (- <Entity.Slot- placement="body"- class="flex flex-col pb-2 min-h-[2lh] pr-4"- >- <Entity.Title entity={props.entity} />- <span- ref={setEmailSnippetContainerRef}- class="text-ink/50 font-medium truncate"- >- <EmailSnippet- entity={entity()}- showContentHits={props.showContentHits}- chars={chars()}- />- </span>- </Entity.Slot>+ <EmailNarrowBody+ entity={entity()}+ chars={chars()}+ showContentHits={props.showContentHits}+ setContainerRef={setEmailSnippetContainerRef}+ />)}</Match><Match when={isTaskEntity(props.entity)}>- <Entity.Slot- placement="body"- class="flex flex-col pb-2 min-h-[2lh] pr-4 "- >- <Entity.Properties entity={props.entity} />- <Show when={firstNotification()}>- {(notif) => (- <span class="text-ink-extra-muted font-normal truncate">- <Show when={notif().sender_id}>- {(senderId) => (- <>- <DisplayName id={senderId()} format="firstName" />{' '}- </>- )}- </Show>- {getActionVerb(- notif().notification_event_type as NotificationType- )}- </span>- )}- </Show>- </Entity.Slot>+ <TaskNarrowBody+ entity={props.entity}+ notification={firstNotification()}+ /></Match><Match when={isCallEntity(props.entity) && props.entity}>{(entity) => (- <Entity.Slot- placement="body"- class="flex flex-col pb-2 min-h-[2lh] pr-4"- >- <span class="text-ink-muted text-xs truncate">- {entity().channelName ?? 'Call'}- </span>- <span class="text-ink-extra-muted text-xs flex items-center gap-2">- <Show- when={entity().durationMs}- fallback={entity().isActive ? 'In progress' : 'No duration'}- >- {(ms) => formatCallDuration(ms())}- </Show>- <Show when={(soupView?.activeTab() ?? 'all') === 'all'}>- <AttendanceBadge attended={entity().attended} />- </Show>- </span>- </Entity.Slot>+ <CallNarrowBody+ entity={entity()}+ showAttendanceBadge={(soupView?.activeTab() ?? 'all') === 'all'}+ />)}</Match><Match when={true}>@@ -651,109 +863,30 @@ function WideLayout(props: LayoutProps) {<Switch><Match when={isEmailEntity(props.entity) && props.entity}>{(entity) => (- <>- <span class="w-(--title-width) shrink-0">- <span class="truncate max-w-32 flex gap-2 items-center">- <EmailIdentity entity={entity()} />- </span>- </span>- <span class="truncate">- <Entity.Title entity={entity()} />- </span>- <span- ref={setEmailSnippetContainerRef}- class="text-ink/50 font-medium truncate flex-1 inline-flex items-center"- >- <EmailSnippet- entity={entity()}- showContentHits={props.showContentHits}- chars={chars()}- />- </span>- </>+ <EmailWideContent+ entity={entity()}+ chars={chars()}+ showContentHits={props.showContentHits}+ setContainerRef={setEmailSnippetContainerRef}+ />)}</Match><Match when={isChannelMessageEntity(props.entity) && props.entity}>- {(entity) => {- const hit = () => {- const e = entity() as EntityData;- return isSearchEntity(e)- ? e.search.contentHitData?.[0]- : undefined;- };- return (- <>- <span class="shrink-0 flex gap-1.5 items-center">- <span class="text-ink-muted whitespace-nowrap">- {entity().channelName}- </span>- <Show when={entity().senderId}>- {(id) => <UserIcon id={id()} size="xs" />}- </Show>- <Show when={hit()}>- {(h) => (- <span class="text-ink-extra-muted text-xs whitespace-nowrap">- <SearchSender hit={h()} />- </span>- )}- </Show>- </span>- <div class="text-ink/50 font-medium flex-1 min-w-0 overflow-hidden">- <Show when={hit()} fallback={entity().content}>- {(h) => <SearchContent hit={h()} singleLine />}- </Show>- </div>- </>- );- }}+ {(entity) => <ChannelMessageWideContent entity={entity()} />}</Match><Match when={isChannelEntity(props.entity) && props.entity}>{(entity) => (- <Show- when={!props.hasNotifications && entity().latestMessage}- fallback={- <span class="truncate flex gap-2">- <Entity.Title entity={entity()} />- </span>- }- >- {(msg) => (- <>- <span class="w-(--title-width) shrink-0 truncate flex gap-2">- <Entity.Title entity={entity()} />- </span>- <ChannelMessage message={msg()} />- </>- )}- </Show>+ <ChannelWideContent+ entity={entity()}+ showLatestMessage={!props.hasNotifications}+ />)}</Match><Match when={isCallEntity(props.entity) && props.entity}>- {(entity) => (- <>- <Entity.Title entity={entity()} />- <span class="text-ink-extra-muted font-medium truncate">- <Show- when={entity().durationMs}- fallback={entity().isActive ? 'In progress' : ''}- >- {(ms) => formatCallDuration(ms())}- </Show>- </span>- </>- )}+ {(entity) => <CallWideContent entity={entity()} />}</Match><Match when={isAutomationEntity(props.entity) && props.entity}>- {(entity) => (- <>- <span class="w-(--title-width) shrink-0 truncate">- <Entity.Title entity={entity()} />- </span>- <span class="">- <AutomationSubtitle entity={entity()} />- </span>- </>- )}+ {(entity) => <AutomationWideContent entity={entity()} />}</Match><Match when={props.entity}>{(entity) => <Entity.Title entity={entity()} />}diff --git a/js/app/packages/entity/src/extractors-search/search-content-hit-row.tsx b/js/app/packages/entity/src/extractors-search/search-content-hit-row.tsxindex aeba1c0f32..573341ecda 100644--- a/js/app/packages/entity/src/extractors-search/search-content-hit-row.tsx+++ b/js/app/packages/entity/src/extractors-search/search-content-hit-row.tsx@@ -1,5 +1,9 @@import { Show } from 'solid-js';-import type { ContentHitData, SearchLocation } from '../types/search';+import {+ type ContentHitData,+ hitHasSender,+ type SearchLocation,+} from '../types/search';import { SearchContent } from './search-content';import { SearchSender } from './search-sender';import { SearchTimestamp } from './search-timestamp';@@ -30,7 +34,7 @@ export function SearchContentHitRow(props: SearchContentHitRowProps) {role="button"><div class="flex flex-col gap-3 min-w-0">- <Show when={props.hit.type === 'channel' || props.hit.type === 'email'}>+ <Show when={hitHasSender(props.hit)}><div class="flex items-center gap-1"><Show when={senderId()}>{(id) => <UserIcon id={id()} size="xs" />}diff --git a/js/app/packages/entity/src/extractors-search/search-helpers.ts b/js/app/packages/entity/src/extractors-search/search-helpers.tsindex 64d6d11c82..2c9a8b91f0 100644--- a/js/app/packages/entity/src/extractors-search/search-helpers.ts+++ b/js/app/packages/entity/src/extractors-search/search-helpers.ts@@ -1,18 +1,17 @@import { match } from 'ts-pattern';-import type { ContentHitData } from '../types/search';+import { type ContentHitData, hitHasSender } from '../types/search';import FileTextIcon from '@icon/regular/file-text.svg';import FilePdfIcon from '@icon/regular/file-pdf.svg';import HashIcon from '@icon/regular/hash.svg';import EnvelopeIcon from '@icon/regular/envelope.svg';+import PhoneCallIcon from '@macro-icons/wide/call.svg';/*** Gets the sender ID from a content hit, if applicable* @internal*/export function getSenderId(hit: ContentHitData): string | undefined {- if (hit.type === 'channel' || hit.type === 'email') {- return hit.senderId;- }+ return hitHasSender(hit) ? hit.senderId : undefined;}/**@@ -25,5 +24,6 @@ export function getSearchIcon(hit: ContentHitData) {.with({ type: 'pdf' }, () => FilePdfIcon).with({ type: 'channel' }, () => HashIcon).with({ type: 'email' }, () => EnvelopeIcon)+ .with({ type: 'call_record' }, () => PhoneCallIcon).otherwise(() => FileTextIcon);}diff --git a/js/app/packages/entity/src/extractors-search/search-sender.tsx b/js/app/packages/entity/src/extractors-search/search-sender.tsxindex 0f35beb040..7793ba04fa 100644--- a/js/app/packages/entity/src/extractors-search/search-sender.tsx+++ b/js/app/packages/entity/src/extractors-search/search-sender.tsx@@ -1,30 +1,14 @@import { Show } from 'solid-js';-import type {- ContentHitData,- ChannelContentHitData,- EmailContentHitData,-} from '../types/search';+import type { ContentHitData } from '../types/search';import { DisplayName } from '../components/DisplayName';+import { getSenderId } from './search-helpers';interface SearchSenderProps {hit?: ContentHitData;}/**- * Gets sender ID from content hit if available- */-function getSenderId(hit: ContentHitData): string | undefined {- if (hit.type === 'channel') {- return (hit as ChannelContentHitData).senderId;- }- if (hit.type === 'email') {- return (hit as EmailContentHitData).senderId;- }- return undefined;-}--/**- * Displays the sender of a search hit (for channel/email)+ * Displays the sender of a search hit (for channel/email/call_record)*/export function SearchSender(props: SearchSenderProps) {const senderId = () => (props.hit ? getSenderId(props.hit) : undefined);diff --git a/js/app/packages/entity/src/extractors-search/search-timestamp.tsx b/js/app/packages/entity/src/extractors-search/search-timestamp.tsxindex 1a99642d5d..1290786463 100644--- a/js/app/packages/entity/src/extractors-search/search-timestamp.tsx+++ b/js/app/packages/entity/src/extractors-search/search-timestamp.tsx@@ -1,21 +1,13 @@import type { DateValue } from '@core/util/date';-import type { ContentHitData } from '../types/search';+import { type ContentHitData, hitHasSender } from '../types/search';import { formatRelativeTimestamp } from '../utils/timestamp';interface SearchTimestampProps {hit?: ContentHitData;}-/**- * Gets timestamp from content hit if available- */function getTimestamp(hit: ContentHitData): DateValue | undefined {- switch (hit.type) {- case 'email':- case 'channel':- return hit.sentAt;- }- return undefined;+ return hitHasSender(hit) ? hit.sentAt : undefined;}/**diff --git a/js/app/packages/entity/src/extractors/entity-title.tsx b/js/app/packages/entity/src/extractors/entity-title.tsxindex 4fbe4aa7ac..0642db17f3 100644--- a/js/app/packages/entity/src/extractors/entity-title.tsx+++ b/js/app/packages/entity/src/extractors/entity-title.tsx@@ -5,6 +5,7 @@ import { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme'import { Show } from 'solid-js';import type { EntityData } from '../types/entity';import { isSearchEntity } from '../types/search';+import { blockNameToDefaultFile } from '@core/constant/allBlocks';function extractRawTitle(entity: EntityData): string {return match(entity)@@ -18,8 +19,11 @@ function extractRawTitle(entity: EntityData): string {.with({ type: 'channel_message' }, (e) => e.channelName).with({ type: 'email' }, (e) => e.name || '(No Subject)').with({ type: 'chat' }, (e) => e.name)- .with({ type: 'call' }, (e) => e.name)- .with({ type: 'automation' }, (e) => e.name || 'Untitled automation')+ .with({ type: 'call' }, (e) => e.name || blockNameToDefaultFile('call'))+ .with(+ { type: 'automation' },+ (e) => e.name || blockNameToDefaultFile('automation')+ ).otherwise(() => 'Unknown');}diff --git a/js/app/packages/entity/src/types/search.ts b/js/app/packages/entity/src/types/search.tsindex d1024cd9c9..6ff2b6f6c6 100644--- a/js/app/packages/entity/src/types/search.ts+++ b/js/app/packages/entity/src/types/search.ts@@ -1,4 +1,5 @@import type { DateValue } from '@core/util/date';+import { isMatching, P } from 'ts-pattern';import type { EntityData } from './entity';type MarkdownHighlightLocation = {@@ -25,11 +26,18 @@ type EmailMessageHighlightLocation = {messageId: string;};+type CallRecordSegmentHighlightLocation = {+ type: 'call_record';+ callId: string;+ transcriptId: string;+};+export type SearchLocation =| MarkdownHighlightLocation| PdfHighlightLocation| ChannelMessageHighlightLocation- | EmailMessageHighlightLocation;+ | EmailMessageHighlightLocation+ | CallRecordSegmentHighlightLocation;export type ChannelContentHitData = {type: 'channel';@@ -67,6 +75,15 @@ export type EmailContentHitData = {location: EmailMessageHighlightLocation;};+export type CallRecordContentHitData = {+ type: 'call_record';+ id: string;+ content: string;+ senderId: string;+ sentAt: DateValue;+ location: CallRecordSegmentHighlightLocation;+};+export type DocumentContentHitData =| MdContentHitData| PdfContentHitData@@ -76,6 +93,7 @@ export type ContentHitData =| DocumentContentHitData| ChannelContentHitData| EmailContentHitData+ | CallRecordContentHitData| GenericContentHitData;export type SearchData = {@@ -92,3 +110,17 @@ export type WithSearch<T extends EntityData> = T & {export const isSearchEntity = <T extends EntityData>(entity: T): entity is WithSearch<T> => 'search' in entity;++export const isCallRecordHit = (+ hit: ContentHitData+): hit is CallRecordContentHitData => hit.type === 'call_record';++/** Content hits that carry sender + sent_at (channel / email / call_record). */+export type HitWithSender =+ | ChannelContentHitData+ | EmailContentHitData+ | CallRecordContentHitData;++export const hitHasSender = isMatching({+ type: P.union('channel', 'email', 'call_record'),+}) as (hit: ContentHitData) => hit is HitWithSender;diff --git a/js/app/packages/queries/soup/normalized-cache/operations.ts b/js/app/packages/queries/soup/normalized-cache/operations.tsindex 46082e748e..90590c2f4f 100644--- a/js/app/packages/queries/soup/normalized-cache/operations.ts+++ b/js/app/packages/queries/soup/normalized-cache/operations.ts@@ -376,6 +376,7 @@ function getSearchResultId(result: UnifiedSearchResponseItem): string {.with({ type: 'channel' }, (r) => r.channel_id).with({ type: 'email' }, (r) => r.thread_id).with({ type: 'project' }, (r) => r.id)+ .with({ type: 'callRecord' }, (r) => r.call_id).exhaustive();}diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.tsindex 86df4639c2..a69d271150 100644--- a/js/app/packages/queries/soup/transform-utils.ts+++ b/js/app/packages/queries/soup/transform-utils.ts@@ -29,6 +29,7 @@ import type {ChatMessageSearchResult,ChannelSearchResult,ProjectSearchResult,+ CallRecordSearchResult,UnifiedSearchResponseItem,} from '@service-search/generated/models';import type {@@ -42,14 +43,20 @@ type InnerSearchResult =| EmailSearchResult| ChatMessageSearchResult| ChannelSearchResult- | ProjectSearchResult;+ | ProjectSearchResult+ | CallRecordSearchResult;type TypedInnerSearchResult =| { results: InnerSearchResult[]; type?: undefined }| { results: DocumentSearchResult[]; type: 'pdf'; searchQuery: string }| { results: DocumentSearchResult[]; type: 'md' }| { results: ChannelSearchResult[]; type: 'channel' }- | { results: EmailSearchResult[]; type: 'email'; searchQuery?: string };+ | { results: EmailSearchResult[]; type: 'email'; searchQuery?: string }+ | {+ results: CallRecordSearchResult[];+ type: 'call_record';+ callId: string;+ };const getSearchData = (data: TypedInnerSearchResult): SearchData => {let contentHitData: ContentHitData[] = [];@@ -127,6 +134,28 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {});break;}+ case 'call_record': {+ contentHitData = data.results.flatMap((r) => {+ // TODO: support name only hits for call records when we support rename+ const isContentHit = !!r.transcript_id;+ if (!isContentHit) return [];++ const contents = r.highlight.content ?? [];+ return contents.map((content) => ({+ type: 'call_record' as const,+ id: r.transcript_id!,+ content: mergeAdjacentMacroEmTags(content),+ senderId: r.speaker_id!,+ sentAt: r.started_at!,+ location: {+ type: 'call_record' as const,+ callId: data.callId,+ transcriptId: r.transcript_id!,+ },+ }));+ });+ break;+ }default: {contentHitData = data.results.flatMap((r) => {const contents = r.highlight.content ?? [];@@ -328,6 +357,39 @@ export const useSearchResponseItemMapper = () => {},];}++ case 'callRecord': {+ if (!result.metadata) return [];+ const search = getSearchData({+ type: 'call_record',+ results: result.call_search_results,+ callId: result.call_id,+ });++ const channelName: string | undefined =+ result.metadata.channel_name ??+ channels().find((c) => c.id === result.channel_id)?.name ??+ undefined;++ return [+ {+ type: 'call',+ id: result.call_id,+ // NOTE: leave empty, the CallChannelName will fall back to the preview endpoint.+ name: result.name ?? channelName ?? '',+ channelId: result.channel_id,+ channelName,+ ownerId: result.owner_id,+ createdAt: result.metadata.started_at,+ updatedAt: result.metadata.updated_at,+ isActive: false,+ attended: result.metadata.attended,+ durationMs: result.metadata.duration_ms,+ participantIds: result.participant_ids,+ search,+ },+ ];+ }}};};@@ -449,7 +511,7 @@ export const mapSoupPageToEntityList: (return {type: 'call',id: item.data.callId,- name: item.data.channelName ?? 'Call',+ name: item.data.channelName ?? blockNameToDefaultFile('call'),channelId: item.data.channelId,channelName: item.data.channelName ?? undefined,ownerId: item.data.createdBy,diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex e109bece30..279dd403b2 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -75,7 +75,16 @@ export const BashCodeExecutionResponse = z.object({export const ContentSearch = z.object({entityTypes: z- .array(z.enum(['documents', 'chats', 'emails', 'channels', 'projects']))+ .array(+ z.enum([+ 'documents',+ 'chats',+ 'emails',+ 'channels',+ 'projects',+ 'call_records',+ ])+ ).default([]),query: z.string(),})@@ -301,6 +310,52 @@ export const SearchToolResponse = z.object({type: z.literal('project'),updated_at: z.string().datetime({ offset: true }),}),+ z.object({+ call_id: z.string().uuid(),+ call_search_results: z.array(+ z.object({+ ended_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ 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(),+ }),+ score: z.union([z.number(), z.null()]).optional(),+ sequence_num: z.union([z.number().int(), z.null()]).optional(),+ speaker_id: z.union([z.string(), z.null()]).optional(),+ started_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ transcript_id: z.union([z.string().uuid(), z.null()]).optional(),+ })+ ),+ channel_id: z.string().uuid(),+ id: z.string().uuid(),+ metadata: z+ .union([+ z.object({+ attended: z.boolean(),+ channel_name: z.union([z.string(), z.null()]).optional(),+ created_by: z.string(),+ duration_ms: z.number().int(),+ ended_at: z.string().datetime({ offset: true }),+ started_at: z.string().datetime({ offset: true }),+ updated_at: z.string().datetime({ offset: true }),+ }),+ z.null(),+ ])+ .optional(),+ name: z.union([z.string(), z.null()]).optional(),+ owner_id: z.string(),+ participant_ids: z.array(z.string()),+ type: z.literal('callRecord'),+ }),];const errors = schemas.reduce<z.ZodError[]>((errors, schema) =>@@ -514,7 +569,16 @@ export const ListEntitiesResponse = z.object({export const NameSearch = z.object({entityTypes: z- .array(z.enum(['documents', 'chats', 'emails', 'channels', 'projects']))+ .array(+ z.enum([+ 'documents',+ 'chats',+ 'emails',+ 'channels',+ 'projects',+ 'call_records',+ ])+ ).default([]),name: z.string(),})diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex cb83c7c768..a902a7048b 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -106,7 +106,14 @@ export interface ContentSearch {/*** Which types of items to search. Leave empty to search all types. Examples: ['documents'], ['emails', 'documents'], ['channels']*/- entityTypes: ('documents' | 'chats' | 'emails' | 'channels' | 'projects')[];+ entityTypes: (+ | 'documents'+ | 'chats'+ | 'emails'+ | 'channels'+ | 'projects'+ | 'call_records'+ )[];/*** The text content to search for. This searches within the body of documents, emails, and messages.*/@@ -573,6 +580,65 @@ export interface SearchToolResponse {type: 'project';updated_at: string;}+ | {+ call_id: string;+ call_search_results: {+ ended_at?: string | null;+ highlight: {+ /**+ * The highlight match on the bcc (email only)+ */+ bcc?: string[];+ /**+ * The highlight match on the cc (email only)+ */+ cc?: string[];+ /**+ * The highlight match on the content field+ */+ content?: string[];+ /**+ * The highlight match on the name field+ */+ name?: string | null;+ /**+ * The highlight match on the recipients (email only)+ */+ recipients?: string[];+ /**+ * The highlight match on the sender (email only)+ */+ sender?: string | null;+ /**+ * The highlight match on the user (owner) of the entity+ */+ user_id?: string | null;+ };+ score?: number | null;+ sequence_num?: number | null;+ speaker_id?: string | null;+ started_at?: string | null;+ transcript_id?: string | null;+ }[];+ channel_id: string;+ id: string;+ /**+ * `None` if the call has been deleted.+ */+ metadata?: {+ attended: boolean;+ channel_name?: string | null;+ created_by: string;+ duration_ms: number;+ ended_at: string;+ started_at: string;+ updated_at: string;+ } | null;+ name?: string | null;+ owner_id: string;+ participant_ids: string[];+ type: 'callRecord';+ })[];}@@ -983,7 +1049,14 @@ export interface NameSearch {/*** Which types of items to search. Leave empty to search all types. Examples: ['documents'], ['emails', 'documents'], ['channels']*/- entityTypes: ('documents' | 'chats' | 'emails' | 'channels' | 'projects')[];+ entityTypes: (+ | 'documents'+ | 'chats'+ | 'emails'+ | 'channels'+ | 'projects'+ | 'call_records'+ )[];/*** The name or title to search for. For emails, this is the subject line. For channels, this can be the channel name or participant names.*/diff --git a/js/app/packages/service-clients/service-search/generated/models/callFilters.ts b/js/app/packages/service-clients/service-search/generated/models/callFilters.tsindex 2d60295462..048d996ace 100644--- a/js/app/packages/service-clients/service-search/generated/models/callFilters.ts+++ b/js/app/packages/service-clients/service-search/generated/models/callFilters.ts@@ -16,4 +16,6 @@ export interface CallFilters {attended?: CallFiltersAttended;/** Channel IDs to filter calls by. Empty to include all calls. */channel_ids?: string[];+ /** Speaker macro user ids. Empty to include all. */+ speaker_ids?: string[];}diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordMetadata.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordMetadata.tsnew file mode 100644index 0000000000..8d7b7859af--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordMetadata.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { CallRecordMetadataChannelName } from './callRecordMetadataChannelName';++export interface CallRecordMetadata {+ attended: boolean;+ channel_name?: CallRecordMetadataChannelName;+ created_by: string;+ duration_ms: number;+ ended_at: string;+ started_at: string;+ updated_at: string;+}diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordMetadataChannelName.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordMetadataChannelName.tsnew file mode 100644index 0000000000..385615388a--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordMetadataChannelName.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++export type CallRecordMetadataChannelName = string | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItem.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItem.tsnew file mode 100644index 0000000000..02e8e1b394--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItem.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++import type { CallRecordSearchResponseItemName } from './callRecordSearchResponseItemName';+import type { CallRecordSearchResult } from './callRecordSearchResult';++export interface CallRecordSearchResponseItem {+ call_id: string;+ call_search_results: CallRecordSearchResult[];+ channel_id: string;+ id: string;+ name?: CallRecordSearchResponseItemName;+ owner_id: string;+ participant_ids: string[];+}diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItemName.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItemName.tsnew file mode 100644index 0000000000..250be8263e--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItemName.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++export type CallRecordSearchResponseItemName = string | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItemWithMetadata.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItemWithMetadata.tsnew file mode 100644index 0000000000..12519e8418--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItemWithMetadata.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 { CallRecordSearchResponseItem } from './callRecordSearchResponseItem';+import type { CallRecordSearchResponseItemWithMetadataAllOf } from './callRecordSearchResponseItemWithMetadataAllOf';++export type CallRecordSearchResponseItemWithMetadata =+ CallRecordSearchResponseItem & CallRecordSearchResponseItemWithMetadataAllOf;diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItemWithMetadataAllOf.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItemWithMetadataAllOf.tsnew file mode 100644index 0000000000..d49ec3f66b--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItemWithMetadataAllOf.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 { CallRecordSearchResponseItemWithMetadataAllOfMetadata } from './callRecordSearchResponseItemWithMetadataAllOfMetadata';++export type CallRecordSearchResponseItemWithMetadataAllOf = {+ metadata?: CallRecordSearchResponseItemWithMetadataAllOfMetadata;+};diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItemWithMetadataAllOfMetadata.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItemWithMetadataAllOfMetadata.tsnew file mode 100644index 0000000000..98c4ab1f2c--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResponseItemWithMetadataAllOfMetadata.ts@@ -0,0 +1,10 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { CallRecordMetadata } from './callRecordMetadata';++export type CallRecordSearchResponseItemWithMetadataAllOfMetadata =+ null | CallRecordMetadata;diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResult.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResult.tsnew file mode 100644index 0000000000..704db6074f--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResult.ts@@ -0,0 +1,23 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { CallRecordSearchResultEndedAt } from './callRecordSearchResultEndedAt';+import type { CallRecordSearchResultScore } from './callRecordSearchResultScore';+import type { CallRecordSearchResultSequenceNum } from './callRecordSearchResultSequenceNum';+import type { CallRecordSearchResultSpeakerId } from './callRecordSearchResultSpeakerId';+import type { CallRecordSearchResultStartedAt } from './callRecordSearchResultStartedAt';+import type { CallRecordSearchResultTranscriptId } from './callRecordSearchResultTranscriptId';+import type { SearchHighlight } from './searchHighlight';++export interface CallRecordSearchResult {+ ended_at?: CallRecordSearchResultEndedAt;+ highlight: SearchHighlight;+ score?: CallRecordSearchResultScore;+ sequence_num?: CallRecordSearchResultSequenceNum;+ speaker_id?: CallRecordSearchResultSpeakerId;+ started_at?: CallRecordSearchResultStartedAt;+ transcript_id?: CallRecordSearchResultTranscriptId;+}diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultEndedAt.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultEndedAt.tsnew file mode 100644index 0000000000..2813bd647d--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultEndedAt.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++export type CallRecordSearchResultEndedAt = string | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultScore.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultScore.tsnew file mode 100644index 0000000000..ba073497df--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultScore.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++export type CallRecordSearchResultScore = number | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultSequenceNum.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultSequenceNum.tsnew file mode 100644index 0000000000..0907939cf7--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultSequenceNum.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++export type CallRecordSearchResultSequenceNum = number | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultSpeakerId.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultSpeakerId.tsnew file mode 100644index 0000000000..2fe4f009c5--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultSpeakerId.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++export type CallRecordSearchResultSpeakerId = string | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultStartedAt.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultStartedAt.tsnew file mode 100644index 0000000000..950382b0d9--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultStartedAt.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++export type CallRecordSearchResultStartedAt = string | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultTranscriptId.ts b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultTranscriptId.tsnew file mode 100644index 0000000000..8e07721e69--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/callRecordSearchResultTranscriptId.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++export type CallRecordSearchResultTranscriptId = string | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/index.ts b/js/app/packages/service-clients/service-search/generated/models/index.tsindex ea3d48a6f5..db298f93de 100644--- a/js/app/packages/service-clients/service-search/generated/models/index.ts+++ b/js/app/packages/service-clients/service-search/generated/models/index.ts@@ -7,6 +7,20 @@export * from './callFilters';export * from './callFiltersAttended';+export * from './callRecordMetadata';+export * from './callRecordMetadataChannelName';+export * from './callRecordSearchResponseItem';+export * from './callRecordSearchResponseItemName';+export * from './callRecordSearchResponseItemWithMetadata';+export * from './callRecordSearchResponseItemWithMetadataAllOf';+export * from './callRecordSearchResponseItemWithMetadataAllOfMetadata';+export * from './callRecordSearchResult';+export * from './callRecordSearchResultEndedAt';+export * from './callRecordSearchResultScore';+export * from './callRecordSearchResultSequenceNum';+export * from './callRecordSearchResultSpeakerId';+export * from './callRecordSearchResultStartedAt';+export * from './callRecordSearchResultTranscriptId';export * from './channelFilters';export * from './channelFiltersImportance';export * from './channelFiltersOrgId';@@ -169,6 +183,8 @@ export * from './searchHighlightUserId';export * from './searchOn';export * from './searchResponse';export * from './sharedEmailFilter';+export * from './simpleCallRecordSearchResponseBaseItemHumanReadableTimestamp';+export * from './simpleCallRecordSearchResponseBaseItemHumanReadableTimestampChannelName';export * from './simpleChannelSearchReponseBaseItem';export * from './simpleChannelSearchReponseBaseItemHumanReadableTimestamp';export * from './simpleChannelSearchReponseBaseItemHumanReadableTimestampOrgId';@@ -204,6 +220,9 @@ export * from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfAexport * from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfFour';export * from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfFourAllOf';export * from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfFourAllOfType';+export * from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesix';+export * from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOf';+export * from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOfType';export * from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnethree';export * from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnethreeAllOf';export * from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnethreeAllOfType';@@ -219,6 +238,9 @@ export * from './simpleUnifiedSearchResponseBaseItemOneOfAllOfType';export * from './simpleUnifiedSearchResponseBaseItemOneOfFour';export * from './simpleUnifiedSearchResponseBaseItemOneOfFourAllOf';export * from './simpleUnifiedSearchResponseBaseItemOneOfFourAllOfType';+export * from './simpleUnifiedSearchResponseBaseItemOneOfOnesix';+export * from './simpleUnifiedSearchResponseBaseItemOneOfOnesixAllOf';+export * from './simpleUnifiedSearchResponseBaseItemOneOfOnesixAllOfType';export * from './simpleUnifiedSearchResponseBaseItemOneOfOnethree';export * from './simpleUnifiedSearchResponseBaseItemOneOfOnethreeAllOf';export * from './simpleUnifiedSearchResponseBaseItemOneOfOnethreeAllOfType';@@ -243,6 +265,9 @@ export * from './unifiedSearchResponseItemOneOfAllOfType';export * from './unifiedSearchResponseItemOneOfFour';export * from './unifiedSearchResponseItemOneOfFourAllOf';export * from './unifiedSearchResponseItemOneOfFourAllOfType';+export * from './unifiedSearchResponseItemOneOfOnesix';+export * from './unifiedSearchResponseItemOneOfOnesixAllOf';+export * from './unifiedSearchResponseItemOneOfOnesixAllOfType';export * from './unifiedSearchResponseItemOneOfOnethree';export * from './unifiedSearchResponseItemOneOfOnethreeAllOf';export * from './unifiedSearchResponseItemOneOfOnethreeAllOfType';diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleCallRecordSearchResponseBaseItemHumanReadableTimestamp.ts b/js/app/packages/service-clients/service-search/generated/models/simpleCallRecordSearchResponseBaseItemHumanReadableTimestamp.tsnew file mode 100644index 0000000000..692da99161--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/simpleCallRecordSearchResponseBaseItemHumanReadableTimestamp.ts@@ -0,0 +1,23 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++import type { SearchHighlight } from './searchHighlight';+import type { SimpleCallRecordSearchResponseBaseItemHumanReadableTimestampChannelName } from './simpleCallRecordSearchResponseBaseItemHumanReadableTimestampChannelName';++export interface SimpleCallRecordSearchResponseBaseItemHumanReadableTimestamp {+ call_id: string;+ channel_id: string;+ channel_name?: SimpleCallRecordSearchResponseBaseItemHumanReadableTimestampChannelName;+ duration_ms: number;+ /** DateTime<Utc> ts_seconds deserialization + RFC3339 serialization */+ ended_at: string;+ highlight: SearchHighlight;+ participant_ids: string[];+ /** DateTime<Utc> ts_seconds deserialization + RFC3339 serialization */+ started_at: string;+ user_id: string;+}diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleCallRecordSearchResponseBaseItemHumanReadableTimestampChannelName.ts b/js/app/packages/service-clients/service-search/generated/models/simpleCallRecordSearchResponseBaseItemHumanReadableTimestampChannelName.tsnew file mode 100644index 0000000000..ed7765b745--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/simpleCallRecordSearchResponseBaseItemHumanReadableTimestampChannelName.ts@@ -0,0 +1,10 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++export type SimpleCallRecordSearchResponseBaseItemHumanReadableTimestampChannelName =+ | string+ | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItem.ts b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItem.tsindex b95afbb98a..f43ce6ce19 100644--- a/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItem.ts+++ b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItem.ts@@ -6,6 +6,7 @@*/import type { SimpleUnifiedSearchResponseBaseItemOneOf } from './simpleUnifiedSearchResponseBaseItemOneOf';import type { SimpleUnifiedSearchResponseBaseItemOneOfFour } from './simpleUnifiedSearchResponseBaseItemOneOfFour';+import type { SimpleUnifiedSearchResponseBaseItemOneOfOnesix } from './simpleUnifiedSearchResponseBaseItemOneOfOnesix';import type { SimpleUnifiedSearchResponseBaseItemOneOfOnethree } from './simpleUnifiedSearchResponseBaseItemOneOfOnethree';import type { SimpleUnifiedSearchResponseBaseItemOneOfOnezero } from './simpleUnifiedSearchResponseBaseItemOneOfOnezero';import type { SimpleUnifiedSearchResponseBaseItemOneOfSeven } from './simpleUnifiedSearchResponseBaseItemOneOfSeven';@@ -15,4 +16,5 @@ export type SimpleUnifiedSearchResponseBaseItem =| SimpleUnifiedSearchResponseBaseItemOneOfFour| SimpleUnifiedSearchResponseBaseItemOneOfSeven| SimpleUnifiedSearchResponseBaseItemOneOfOnezero- | SimpleUnifiedSearchResponseBaseItemOneOfOnethree;+ | SimpleUnifiedSearchResponseBaseItemOneOfOnethree+ | SimpleUnifiedSearchResponseBaseItemOneOfOnesix;diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemHumanReadableTimestamp.ts b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemHumanReadableTimestamp.tsindex 28b8f925f4..19dd22194e 100644--- a/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemHumanReadableTimestamp.ts+++ b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemHumanReadableTimestamp.ts@@ -6,6 +6,7 @@*/import type { SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOf } from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOf';import type { SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfFour } from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfFour';+import type { SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesix } from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesix';import type { SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnethree } from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnethree';import type { SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnezero } from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnezero';import type { SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfSeven } from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfSeven';@@ -15,4 +16,5 @@ export type SimpleUnifiedSearchResponseBaseItemHumanReadableTimestamp =| SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfFour| SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfSeven| SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnezero- | SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnethree;+ | SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnethree+ | SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesix;diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesix.ts b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesix.tsnew file mode 100644index 0000000000..d32dba79ff--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesix.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { SimpleCallRecordSearchResponseBaseItemHumanReadableTimestamp } from './simpleCallRecordSearchResponseBaseItemHumanReadableTimestamp';+import type { SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOf } from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOf';++export type SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesix =+ SimpleCallRecordSearchResponseBaseItemHumanReadableTimestamp &+ SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOf;diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOf.ts b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOf.tsnew file mode 100644index 0000000000..bd397cedc4--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOf.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOfType } from './simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOfType';++export type SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOf =+ {+ type: SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOfType;+ };diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOfType.ts b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOfType.tsnew file mode 100644index 0000000000..0e1dbc35a7--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOfType.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++export type SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOfType =+ (typeof SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOfType)[keyof typeof SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const SimpleUnifiedSearchResponseBaseItemHumanReadableTimestampOneOfOnesixAllOfType =+ {+ callRecord: 'callRecord',+ } as const;diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemOneOfOnesix.ts b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemOneOfOnesix.tsnew file mode 100644index 0000000000..f23368a972--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemOneOfOnesix.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { SimpleCallRecordSearchResponseBaseItemHumanReadableTimestamp } from './simpleCallRecordSearchResponseBaseItemHumanReadableTimestamp';+import type { SimpleUnifiedSearchResponseBaseItemOneOfOnesixAllOf } from './simpleUnifiedSearchResponseBaseItemOneOfOnesixAllOf';++export type SimpleUnifiedSearchResponseBaseItemOneOfOnesix =+ SimpleCallRecordSearchResponseBaseItemHumanReadableTimestamp &+ SimpleUnifiedSearchResponseBaseItemOneOfOnesixAllOf;diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemOneOfOnesixAllOf.ts b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemOneOfOnesixAllOf.tsnew file mode 100644index 0000000000..05e2579481--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemOneOfOnesixAllOf.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 { SimpleUnifiedSearchResponseBaseItemOneOfOnesixAllOfType } from './simpleUnifiedSearchResponseBaseItemOneOfOnesixAllOfType';++export type SimpleUnifiedSearchResponseBaseItemOneOfOnesixAllOf = {+ type: SimpleUnifiedSearchResponseBaseItemOneOfOnesixAllOfType;+};diff --git a/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemOneOfOnesixAllOfType.ts b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemOneOfOnesixAllOfType.tsnew file mode 100644index 0000000000..3454e85b18--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/simpleUnifiedSearchResponseBaseItemOneOfOnesixAllOfType.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 SimpleUnifiedSearchResponseBaseItemOneOfOnesixAllOfType =+ (typeof SimpleUnifiedSearchResponseBaseItemOneOfOnesixAllOfType)[keyof typeof SimpleUnifiedSearchResponseBaseItemOneOfOnesixAllOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const SimpleUnifiedSearchResponseBaseItemOneOfOnesixAllOfType = {+ callRecord: 'callRecord',+} as const;diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItem.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItem.tsindex f6e342caad..9c7c1c9695 100644--- a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItem.ts+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItem.ts@@ -6,6 +6,7 @@*/import type { UnifiedSearchResponseItemOneOf } from './unifiedSearchResponseItemOneOf';import type { UnifiedSearchResponseItemOneOfFour } from './unifiedSearchResponseItemOneOfFour';+import type { UnifiedSearchResponseItemOneOfOnesix } from './unifiedSearchResponseItemOneOfOnesix';import type { UnifiedSearchResponseItemOneOfOnethree } from './unifiedSearchResponseItemOneOfOnethree';import type { UnifiedSearchResponseItemOneOfOnezero } from './unifiedSearchResponseItemOneOfOnezero';import type { UnifiedSearchResponseItemOneOfSeven } from './unifiedSearchResponseItemOneOfSeven';@@ -15,4 +16,5 @@ export type UnifiedSearchResponseItem =| UnifiedSearchResponseItemOneOfFour| UnifiedSearchResponseItemOneOfSeven| UnifiedSearchResponseItemOneOfOnezero- | UnifiedSearchResponseItemOneOfOnethree;+ | UnifiedSearchResponseItemOneOfOnethree+ | UnifiedSearchResponseItemOneOfOnesix;diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesix.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesix.tsnew file mode 100644index 0000000000..d74d0cb189--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesix.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { CallRecordSearchResponseItemWithMetadata } from './callRecordSearchResponseItemWithMetadata';+import type { UnifiedSearchResponseItemOneOfOnesixAllOf } from './unifiedSearchResponseItemOneOfOnesixAllOf';++export type UnifiedSearchResponseItemOneOfOnesix =+ CallRecordSearchResponseItemWithMetadata &+ UnifiedSearchResponseItemOneOfOnesixAllOf;diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesixAllOf.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesixAllOf.tsnew file mode 100644index 0000000000..b4ba1d8dee--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesixAllOf.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 { UnifiedSearchResponseItemOneOfOnesixAllOfType } from './unifiedSearchResponseItemOneOfOnesixAllOfType';++export type UnifiedSearchResponseItemOneOfOnesixAllOf = {+ type: UnifiedSearchResponseItemOneOfOnesixAllOfType;+};diff --git a/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesixAllOfType.ts b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesixAllOfType.tsnew file mode 100644index 0000000000..3c6c44a574--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfOnesixAllOfType.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 UnifiedSearchResponseItemOneOfOnesixAllOfType =+ (typeof UnifiedSearchResponseItemOneOfOnesixAllOfType)[keyof typeof UnifiedSearchResponseItemOneOfOnesixAllOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const UnifiedSearchResponseItemOneOfOnesixAllOfType = {+ callRecord: 'callRecord',+} as const;diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex 36103a4f88..45d3ccdf7f 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -187,6 +187,149 @@"type": "string"},"description": "Channel IDs to filter calls by. Empty to include all calls."+ },+ "speaker_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Speaker macro user ids. Empty to include all."+ }+ }+ },+ "CallRecordMetadata": {+ "type": "object",+ "required": [+ "created_by",+ "started_at",+ "ended_at",+ "duration_ms",+ "updated_at",+ "attended"+ ],+ "properties": {+ "attended": {+ "type": "boolean"+ },+ "channel_name": {+ "type": ["string", "null"]+ },+ "created_by": {+ "type": "string"+ },+ "duration_ms": {+ "type": "integer",+ "format": "int64"+ },+ "ended_at": {+ "type": "string",+ "format": "date-time"+ },+ "started_at": {+ "type": "string",+ "format": "date-time"+ },+ "updated_at": {+ "type": "string",+ "format": "date-time"+ }+ }+ },+ "CallRecordSearchResponseItem": {+ "type": "object",+ "required": [+ "id",+ "owner_id",+ "call_id",+ "channel_id",+ "participant_ids",+ "call_search_results"+ ],+ "properties": {+ "call_id": {+ "type": "string",+ "format": "uuid"+ },+ "call_search_results": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CallRecordSearchResult"+ }+ },+ "channel_id": {+ "type": "string",+ "format": "uuid"+ },+ "id": {+ "type": "string",+ "format": "uuid"+ },+ "name": {+ "type": ["string", "null"]+ },+ "owner_id": {+ "type": "string"+ },+ "participant_ids": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "CallRecordSearchResponseItemWithMetadata": {+ "allOf": [+ {+ "$ref": "#/components/schemas/CallRecordSearchResponseItem"+ },+ {+ "type": "object",+ "properties": {+ "metadata": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/CallRecordMetadata",+ "description": "`None` if the call has been deleted."+ }+ ]+ }+ }+ }+ ]+ },+ "CallRecordSearchResult": {+ "type": "object",+ "required": ["highlight"],+ "properties": {+ "ended_at": {+ "type": ["string", "null"],+ "format": "date-time"+ },+ "highlight": {+ "$ref": "#/components/schemas/SearchHighlight"+ },+ "score": {+ "type": ["number", "null"],+ "format": "double"+ },+ "sequence_num": {+ "type": ["integer", "null"],+ "format": "int32"+ },+ "speaker_id": {+ "type": ["string", "null"]+ },+ "started_at": {+ "type": ["string", "null"],+ "format": "date-time"+ },+ "transcript_id": {+ "type": ["string", "null"],+ "format": "uuid"}}},@@ -2313,6 +2456,56 @@"description": "Controls whether shared email threads are included in results.","enum": ["exclude", "include", "only"]},+ "SimpleCallRecordSearchResponseBaseItem_HumanReadableTimestamp": {+ "type": "object",+ "required": [+ "call_id",+ "channel_id",+ "user_id",+ "participant_ids",+ "started_at",+ "ended_at",+ "duration_ms",+ "highlight"+ ],+ "properties": {+ "call_id": {+ "type": "string"+ },+ "channel_id": {+ "type": "string"+ },+ "channel_name": {+ "type": ["string", "null"]+ },+ "duration_ms": {+ "type": "integer",+ "format": "int64"+ },+ "ended_at": {+ "type": "string",+ "format": "date-time",+ "description": "DateTime<Utc> ts_seconds deserialization + RFC3339 serialization"+ },+ "highlight": {+ "$ref": "#/components/schemas/SearchHighlight"+ },+ "participant_ids": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "started_at": {+ "type": "string",+ "format": "date-time",+ "description": "DateTime<Utc> ts_seconds deserialization + RFC3339 serialization"+ },+ "user_id": {+ "type": "string"+ }+ }+ },"SimpleChannelSearchReponseBaseItem": {"type": "object","required": [@@ -3110,6 +3303,23 @@}}]+ },+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/SimpleCallRecordSearchResponseBaseItem_HumanReadableTimestamp"+ },+ {+ "type": "object",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["callRecord"]+ }+ }+ }+ ]}]},@@ -3199,6 +3409,23 @@}}]+ },+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/SimpleCallRecordSearchResponseBaseItem_HumanReadableTimestamp"+ },+ {+ "type": "object",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["callRecord"]+ }+ }+ }+ ]}]},@@ -3362,6 +3589,23 @@}}]+ },+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/CallRecordSearchResponseItemWithMetadata"+ },+ {+ "type": "object",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["callRecord"]+ }+ }+ }+ ]}]}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/callFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/callFilters.tsindex 9424602a8c..5e4ca07a2a 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/callFilters.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/callFilters.ts@@ -16,4 +16,6 @@ export interface CallFilters {attended?: CallFiltersAttended;/** Channel IDs to filter calls by. Empty to include all calls. */channel_ids?: string[];+ /** Speaker macro user ids. Empty to include all. */+ speaker_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 165867d5d9..7a046746a9 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -5197,6 +5197,10 @@ export const postItemsSoupBody = zod.describe('Channel IDs to filter calls by. Empty to include all calls.'),+ speaker_ids: zod+ .array(zod.string())+ .optional()+ .describe('Speaker macro user ids. Empty to include all.'),}).optional().describe('Filters for call records.'),diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 3b680478a6..debede067f 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -6214,6 +6214,13 @@"type": "string"},"description": "Channel IDs to filter calls by. Empty to include all calls."+ },+ "speaker_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Speaker macro user ids. Empty to include all."}}},diff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rsindex 38ca76845a..c1b74bcae6 100644--- a/rust/cloud-storage/call/src/domain/ports.rs+++ b/rust/cloud-storage/call/src/domain/ports.rs@@ -468,3 +468,29 @@ impl CallRecordQueryService for NoOpCallRecordQueryService {Ok(Vec::new())}}++/// Propagates call record lifecycle events to the search index.+pub trait CallSearchIndexer: Send + Sync + 'static {+ /// Enqueue an upsert.+ fn enqueue_upsert(&self, call_id: &Uuid) -> impl Future<Output = anyhow::Result<()>> + Send;++ /// Enqueue a removal.+ fn enqueue_remove(+ &self,+ channel_id: &Uuid,+ call_id: &Uuid,+ ) -> impl Future<Output = anyhow::Result<()>> + Send;+}++/// No-op for services without search.+pub struct NoOpCallSearchIndexer;++impl CallSearchIndexer for NoOpCallSearchIndexer {+ async fn enqueue_upsert(&self, _call_id: &Uuid) -> anyhow::Result<()> {+ Ok(())+ }++ async fn enqueue_remove(&self, _channel_id: &Uuid, _call_id: &Uuid) -> anyhow::Result<()> {+ Ok(())+ }+}diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rsindex daa5e53d58..9b6ee31f7b 100644--- a/rust/cloud-storage/call/src/domain/service.rs+++ b/rust/cloud-storage/call/src/domain/service.rs@@ -30,8 +30,8 @@ use super::models::{TranscriptSegmentRequest,};use super::ports::{- CallRecordQueryService, CallRepository, CallRtcClient, CallService, CallSummarizer,- RecordingStorage,+ CallRecordQueryService, CallRepository, CallRtcClient, CallSearchIndexer, CallService,+ CallSummarizer, NoOpCallSearchIndexer, RecordingStorage,};/// The concrete call service implementation.@@ -43,6 +43,7 @@ pub struct CallServiceImpl<N: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer = NoopCallSummarizer,+ I: CallSearchIndexer = NoOpCallSearchIndexer,> {repo: R,rtc_client: C,@@ -50,6 +51,7 @@ pub struct CallServiceImpl<entity_access_service: E,notification_ingress: N,recording_storage: S,+ search_indexer: I,server_url: String,egress_s3_config: Option<EgressS3Config>,internal_call_secret: Option<String>,@@ -64,7 +66,7 @@ impl<N: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer,-> CallServiceImpl<R, C, Cn, E, N, S, Sm>+> CallServiceImpl<R, C, Cn, E, N, S, Sm, NoOpCallSearchIndexer>{/// Create a new call service.pub fn new(@@ -83,13 +85,26 @@ impl<entity_access_service,notification_ingress,recording_storage,+ search_indexer: NoOpCallSearchIndexer,server_url: server_url.into(),egress_s3_config: None,internal_call_secret: None,summarizer: None,}}+}+impl<+ R: CallRepository,+ C: CallRtcClient,+ Cn: ConnectionService,+ E: EntityAccessService,+ N: NotificationIngress,+ S: RecordingStorage,+ Sm: CallSummarizer,+ I: CallSearchIndexer,+> CallServiceImpl<R, C, Cn, E, N, S, Sm, I>+{/// Enable auto-recording with the given S3 configuration.pub fn with_egress(mut self, s3_config: EgressS3Config) -> Self {self.egress_s3_config = Some(s3_config);@@ -109,6 +124,26 @@ impl<self}+ /// Swap the search indexer.+ pub fn with_search_indexer<I2: CallSearchIndexer>(+ self,+ indexer: I2,+ ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I2> {+ CallServiceImpl {+ repo: self.repo,+ rtc_client: self.rtc_client,+ connection_service: self.connection_service,+ entity_access_service: self.entity_access_service,+ notification_ingress: self.notification_ingress,+ recording_storage: self.recording_storage,+ search_indexer: indexer,+ server_url: self.server_url,+ egress_s3_config: self.egress_s3_config,+ internal_call_secret: self.internal_call_secret,+ summarizer: self.summarizer,+ }+ }+/// Send a call event to all channel members (best-effort).async fn send_call_event(&self,@@ -244,7 +279,8 @@ impl<N: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer + Clone,-> CallService for CallServiceImpl<R, C, Cn, E, N, S, Sm>+ I: CallSearchIndexer,+> CallService for CallServiceImpl<R, C, Cn, E, N, S, Sm, I>{fn validate_internal_call(&self, token: &str) -> bool {self.internal_call_secret@@ -530,6 +566,10 @@ impl<// `call_records` row is persisted.self.spawn_summarize_call(call.id);+ if let Err(e) = self.search_indexer.enqueue_upsert(&call.id).await {+ tracing::error!(error=?e, call_id=%call.id, "failed to enqueue call record for search indexing");+ }+self.send_call_event(&channel_id,"call_ended",@@ -635,6 +675,10 @@ impl<// `call_records` row is persisted.self.spawn_summarize_call(call.id);+ if let Err(e) = self.search_indexer.enqueue_upsert(&call.id).await {+ tracing::error!(error=?e, call_id=%call.id, "failed to enqueue call record for search indexing");+ }+// Stop egress explicitly before deleting the room. DeleteRoom// is expected to cascade-stop egress, but a failed or slow// DeleteRoom can leave egress running and billing. Doing it@@ -778,12 +822,29 @@ impl<let call_id = Uuid::parse_str(&entity.entity_id).map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call_id in receipt")))?;+ // Look up channel_id before deletion to keep the search-remove message id unique.+ let channel_id = self+ .repo+ .get_call_record_by_call_id(&call_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?+ .map(|r| r.channel_id);+let recording_key = self.repo.delete_call_record(&call_id).await.map_err(|e| CallError::Internal(e.into()))?;+ if let Some(channel_id) = channel_id+ && let Err(e) = self+ .search_indexer+ .enqueue_remove(&channel_id, &call_id)+ .await+ {+ tracing::error!(error=?e, call_id=%call_id, "failed to enqueue call record removal from search");+ }+if let Some(key) = recording_key {self.recording_storage.delete_recording(&key)@@ -945,7 +1006,8 @@ impl<N: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer + Clone,-> CallServiceImpl<R, C, Cn, E, N, S, Sm>+ I: CallSearchIndexer,+> CallServiceImpl<R, C, Cn, E, N, S, Sm, I>{/// Fire-and-forget spawn of [`CallService::summarize_call`] for `call_id`.///diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rsindex c79600f932..1382465453 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs@@ -54,6 +54,8 @@ fn collect_channel_ids(expr: &Expr<CallLiteral>, ids: &mut Vec<Uuid>) {match expr {Expr::Literal(CallLiteral::ChannelId(id)) => ids.push(*id),Expr::Literal(CallLiteral::Attended(_)) => {}+ // Speaker is transcript-segment-only; soup's call list ignores it.+ Expr::Literal(CallLiteral::Speaker(_)) => {}Expr::And(a, b) | Expr::Or(a, b) => {collect_channel_ids(a, ids);collect_channel_ids(b, ids);@@ -75,6 +77,7 @@ fn find_attended(expr: &Expr<CallLiteral>) -> Option<bool> {match expr {Expr::Literal(CallLiteral::Attended(b)) => Some(*b),Expr::Literal(CallLiteral::ChannelId(_)) => None,+ Expr::Literal(CallLiteral::Speaker(_)) => None,Expr::And(a, b) | Expr::Or(a, b) => find_attended(a).or_else(|| find_attended(b)),Expr::Not(inner) => find_attended(inner).map(|b| !b),}diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 08b4e91390..4f1a12a38e 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -196,6 +196,7 @@ pub(crate) type DssCallService = CallServiceImpl<NotificationIngressType,Option<call::outbound::s3_recording_storage::S3RecordingStorage>,call::outbound::ai_call_summarizer::AiCallSummarizer,+ crate::service::call_search_indexer::SqsCallSearchIndexer,>;/// Type alias for the call router state.diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 94b6674037..4e14c790be 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -456,7 +456,10 @@ async fn main() -> anyhow::Result<()> {call_service_builder = call_service_builder.with_egress(config);}- let call_service = Arc::new(call_service_builder);+ let call_search_indexer = crate::service::call_search_indexer::SqsCallSearchIndexer::new(+ Arc::new(sqs_client.clone()),+ );+ let call_service = Arc::new(call_service_builder.with_search_indexer(call_search_indexer));let call_state = CallRouterState::new(call_service.clone(), entity_access_service.clone());let call_webhook_state = WebhookRouterState::new(call_service.clone());diff --git a/rust/cloud-storage/document_storage_service/src/service/call_search_indexer.rs b/rust/cloud-storage/document_storage_service/src/service/call_search_indexer.rsnew file mode 100644index 0000000000..7215d35721--- /dev/null+++ b/rust/cloud-storage/document_storage_service/src/service/call_search_indexer.rs@@ -0,0 +1,45 @@+use std::sync::Arc;++use call::domain::ports::CallSearchIndexer;+use sqs_client::{+ SQS,+ search::{+ SearchQueueMessage,+ call::{CallRecordMessage, RemoveCallRecord},+ },+};+use uuid::Uuid;++#[derive(Clone)]+pub struct SqsCallSearchIndexer {+ sqs: Arc<SQS>,+}++impl SqsCallSearchIndexer {+ pub fn new(sqs: Arc<SQS>) -> Self {+ Self { sqs }+ }+}++impl CallSearchIndexer for SqsCallSearchIndexer {+ async fn enqueue_upsert(&self, call_id: &Uuid) -> anyhow::Result<()> {+ self.sqs+ .send_message_to_search_event_queue(SearchQueueMessage::CallRecord(CallRecordMessage {+ call_id: call_id.to_string(),+ }))+ .await?;+ Ok(())+ }++ async fn enqueue_remove(&self, channel_id: &Uuid, call_id: &Uuid) -> anyhow::Result<()> {+ self.sqs+ .send_message_to_search_event_queue(SearchQueueMessage::RemoveCallRecord(+ RemoveCallRecord {+ channel_id: channel_id.to_string(),+ call_id: Some(call_id.to_string()),+ },+ ))+ .await?;+ Ok(())+ }+}diff --git a/rust/cloud-storage/document_storage_service/src/service/mod.rs b/rust/cloud-storage/document_storage_service/src/service/mod.rsindex 6d635845c7..d27eca2441 100644--- a/rust/cloud-storage/document_storage_service/src/service/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/service/mod.rs@@ -1,3 +1,4 @@+pub mod call_search_indexer;pub mod conn_gateway;pub mod delete_document_worker;pub mod s3;diff --git a/rust/cloud-storage/item_filters/src/ast/call.rs b/rust/cloud-storage/item_filters/src/ast/call.rsindex e0ec9fa3ae..dce4a3d6c3 100644--- a/rust/cloud-storage/item_filters/src/ast/call.rs+++ b/rust/cloud-storage/item_filters/src/ast/call.rs@@ -1,4 +1,5 @@use filter_ast::{ExpandFrame, Expr, FoldTree, TryExpandNode};+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use serde::{Deserialize, Serialize};use uuid::Uuid;@@ -9,6 +10,8 @@ use crate::{CallFilters, ast::ExpandErr};pub enum CallLiteral {/// filter by the channel a call belongs toChannelId(Uuid),+ /// filter by the speaker of a transcript segment+ Speaker(MacroUserIdStr<'static>),/// whether the requesting user attended the callAttended(bool),}@@ -19,6 +22,7 @@ impl ExpandFrame<CallLiteral> for CallFilters {fn expand_ast(filter_request: CallFilters) -> Result<Option<Expr<CallLiteral>>, Self::Err> {let CallFilters {channel_ids,+ speaker_ids,attended,} = filter_request;@@ -27,8 +31,15 @@ impl ExpandFrame<CallLiteral> for CallFilters {.map(|s| Uuid::parse_str(s)).try_expand(|r| r.map(CallLiteral::ChannelId), Expr::or)?;+ let speaker_ids = speaker_ids+ .iter()+ .map(|s| MacroUserIdStr::parse_from_str(s).map(CowLike::into_owned))+ .try_expand(|r| r.map(CallLiteral::Speaker), Expr::or)?;+let attended = attended.map(|b| Expr::Literal(CallLiteral::Attended(b)));- Ok([channel_ids, attended].into_iter().fold_with(Expr::and))+ Ok([channel_ids, speaker_ids, attended]+ .into_iter()+ .fold_with(Expr::and))}}diff --git a/rust/cloud-storage/item_filters/src/ast/tests.rs b/rust/cloud-storage/item_filters/src/ast/tests.rsindex f6fdbfdfad..e7f12a5224 100644--- a/rust/cloud-storage/item_filters/src/ast/tests.rs+++ b/rust/cloud-storage/item_filters/src/ast/tests.rs@@ -803,6 +803,7 @@ fn entity_type_ast_deserialization_rejects_invalid() {fn it_expands_call_filter_with_attended_only() {let f = CallFilters {channel_ids: vec![],+ speaker_ids: vec![],attended: Some(true),};let ast = CallFilters::expand_ast(f)@@ -817,6 +818,7 @@ fn it_expands_call_filter_with_attended_only() {fn it_expands_call_filter_with_attended_false() {let f = CallFilters {channel_ids: vec![],+ speaker_ids: vec![],attended: Some(false),};let ast = CallFilters::expand_ast(f).unwrap().unwrap();@@ -830,6 +832,7 @@ fn it_expands_call_filter_with_channel_and_attended_as_and() {let channel_id = Uuid::new_v4();let f = CallFilters {channel_ids: vec![channel_id.to_string()],+ speaker_ids: vec![],attended: Some(true),};let ast = CallFilters::expand_ast(f).unwrap().unwrap();diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rsindex 6d75967348..dfe1eef9a5 100644--- a/rust/cloud-storage/item_filters/src/lib.rs+++ b/rust/cloud-storage/item_filters/src/lib.rs@@ -292,6 +292,9 @@ pub struct CallFilters {/// Channel IDs to filter calls by. Empty to include all calls.#[serde(default, skip_serializing_if = "Vec::is_empty")]pub channel_ids: Vec<String>,+ /// Speaker macro user ids. Empty to include all.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub speaker_ids: Vec<String>,/// Filter by whether the requesting user attended the call./// `None` = no filter, `Some(true)` = only calls the user joined,/// `Some(false)` = only calls the user did not join.@@ -303,9 +306,10 @@ impl IsEmpty for CallFilters {fn is_empty(&self) -> bool {let CallFilters {channel_ids,+ speaker_ids,attended,} = self;- channel_ids.is_empty() && attended.is_none()+ channel_ids.is_empty() && speaker_ids.is_empty() && attended.is_none()}}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-3907578083a1a10d49eab63c85fd92d078cbce9ef2e968480ea475623ec76f63.json b/rust/cloud-storage/macro_db_client/.sqlx/query-3907578083a1a10d49eab63c85fd92d078cbce9ef2e968480ea475623ec76f63.jsonnew file mode 100644index 0000000000..43ea9df225--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-3907578083a1a10d49eab63c85fd92d078cbce9ef2e968480ea475623ec76f63.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n cr.id AS \"call_id!\",\n cr.channel_id AS \"channel_id!\",\n cr.created_by AS \"created_by!\",\n cc.name AS \"channel_name?\"\n FROM call_records cr\n LEFT JOIN comms_channels cc ON cc.id = cr.channel_id\n WHERE cr.id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "call_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "channel_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "created_by!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "channel_name?",+ "type_info": "Varchar"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true+ ]+ },+ "hash": "3907578083a1a10d49eab63c85fd92d078cbce9ef2e968480ea475623ec76f63"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-4335b5e8988b8d37dba886ecb9a1c06701a3d1f26a605fae745a70c264a9971a.json b/rust/cloud-storage/macro_db_client/.sqlx/query-4335b5e8988b8d37dba886ecb9a1c06701a3d1f26a605fae745a70c264a9971a.jsonnew file mode 100644index 0000000000..c6ed4c4137--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-4335b5e8988b8d37dba886ecb9a1c06701a3d1f26a605fae745a70c264a9971a.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH user_source_ids AS (\n SELECT cp.channel_id::text AS source_id\n FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text\n FROM team_user t\n WHERE t.user_id = $1\n UNION ALL\n SELECT $1\n )\n SELECT DISTINCT cr.id AS \"id!\"\n FROM call_records cr\n WHERE (\n EXISTS (\n SELECT 1 FROM entity_access ea\n WHERE ea.entity_id = cr.id\n AND ea.entity_type = 'call'\n AND ea.source_id IN (SELECT source_id FROM user_source_ids)\n ) OR EXISTS (\n SELECT 1 FROM \"SharePermission\" sp\n WHERE sp.id = cr.share_permission_id\n AND sp.\"isPublic\" = true\n AND sp.\"publicAccessLevel\" IS NOT NULL\n )\n )\n AND ($2::bool IS NULL OR EXISTS (\n SELECT 1 FROM call_record_participants crp\n WHERE crp.call_record_id = cr.id AND crp.user_id = $1\n ) = $2)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Bool"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "4335b5e8988b8d37dba886ecb9a1c06701a3d1f26a605fae745a70c264a9971a"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-74e76c125eb6beb0ade0d0aa8882199445908c8a1990d01d5526a2717a33d39f.json b/rust/cloud-storage/macro_db_client/.sqlx/query-74e76c125eb6beb0ade0d0aa8882199445908c8a1990d01d5526a2717a33d39f.jsonnew file mode 100644index 0000000000..453c91ef24--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-74e76c125eb6beb0ade0d0aa8882199445908c8a1990d01d5526a2717a33d39f.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id AS \"call_id!\" FROM call_records ORDER BY started_at DESC LIMIT $1 OFFSET $2",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "call_id!",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Int8",+ "Int8"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "74e76c125eb6beb0ade0d0aa8882199445908c8a1990d01d5526a2717a33d39f"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-b658079195dd801dac88ad00ecc09a42de5ded7acd840a8f9a3e065bcf7bcc0c.json b/rust/cloud-storage/macro_db_client/.sqlx/query-b658079195dd801dac88ad00ecc09a42de5ded7acd840a8f9a3e065bcf7bcc0c.jsonnew file mode 100644index 0000000000..32eb477e8c--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-b658079195dd801dac88ad00ecc09a42de5ded7acd840a8f9a3e065bcf7bcc0c.json@@ -0,0 +1,52 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id AS \"transcript_id!\",\n speaker_id AS \"speaker_id!\",\n sequence_num AS \"sequence_num!\",\n content AS \"content!\",\n started_at AS \"started_at!\",\n ended_at\n FROM call_record_transcripts\n WHERE call_record_id = $1\n ORDER BY sequence_num ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "transcript_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "speaker_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "sequence_num!",+ "type_info": "Int4"+ },+ {+ "ordinal": 3,+ "name": "content!",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "started_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "ended_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ true+ ]+ },+ "hash": "b658079195dd801dac88ad00ecc09a42de5ded7acd840a8f9a3e065bcf7bcc0c"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-c35b200b4901483cf44b5c34cb7711954310f6eedb582fcc4aa3ecebcb1bd79b.json b/rust/cloud-storage/macro_db_client/.sqlx/query-c35b200b4901483cf44b5c34cb7711954310f6eedb582fcc4aa3ecebcb1bd79b.jsonnew file mode 100644index 0000000000..a16c429dfe--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-c35b200b4901483cf44b5c34cb7711954310f6eedb582fcc4aa3ecebcb1bd79b.json@@ -0,0 +1,59 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n cr.id AS \"call_id!\",\n cr.created_by AS \"created_by!\",\n cr.started_at AS \"started_at!\",\n cr.ended_at AS \"ended_at!\",\n cr.duration_ms AS \"duration_ms!\",\n cc.name AS \"channel_name?\",\n EXISTS (\n SELECT 1 FROM call_record_participants crp\n WHERE crp.call_record_id = cr.id AND crp.user_id = $2\n ) AS \"attended!\"\n FROM call_records cr\n LEFT JOIN comms_channels cc ON cc.id = cr.channel_id\n WHERE cr.id = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "call_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "created_by!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "started_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 3,+ "name": "ended_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 4,+ "name": "duration_ms!",+ "type_info": "Int8"+ },+ {+ "ordinal": 5,+ "name": "channel_name?",+ "type_info": "Varchar"+ },+ {+ "ordinal": 6,+ "name": "attended!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ true,+ null+ ]+ },+ "hash": "c35b200b4901483cf44b5c34cb7711954310f6eedb582fcc4aa3ecebcb1bd79b"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-f5fff13701e91118a77c814a3c1b31f3c3202031f51868b9af724e701248079f.json b/rust/cloud-storage/macro_db_client/.sqlx/query-f5fff13701e91118a77c814a3c1b31f3c3202031f51868b9af724e701248079f.jsonnew file mode 100644index 0000000000..6e3ae4d785--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-f5fff13701e91118a77c814a3c1b31f3c3202031f51868b9af724e701248079f.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT user_id AS \"user_id!\"\n FROM call_record_participants\n WHERE call_record_id = $1\n ORDER BY joined_at ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "f5fff13701e91118a77c814a3c1b31f3c3202031f51868b9af724e701248079f"+}diff --git a/rust/cloud-storage/macro_db_client/src/call_record/get.rs b/rust/cloud-storage/macro_db_client/src/call_record/get.rsnew file mode 100644index 0000000000..4edf6e48b4--- /dev/null+++ b/rust/cloud-storage/macro_db_client/src/call_record/get.rs@@ -0,0 +1,207 @@+use chrono::{DateTime, Utc};+use uuid::Uuid;++#[derive(Debug, Clone)]+pub struct CallRecordSearchBackfill {+ pub call_id: Uuid,+}++#[derive(Debug, Clone)]+pub struct CallRecordMetadataRow {+ pub call_id: Uuid,+ pub created_by: String,+ pub started_at: DateTime<Utc>,+ pub ended_at: DateTime<Utc>,+ pub duration_ms: i64,+ pub channel_name: Option<String>,+ /// Whether the requesting user was a participant on the call.+ pub attended: bool,+}++#[derive(Debug, Clone)]+pub struct CallRecordTranscriptSegment {+ pub transcript_id: Uuid,+ pub speaker_id: String,+ pub sequence_num: i32,+ pub content: String,+ pub started_at: DateTime<Utc>,+ pub ended_at: Option<DateTime<Utc>>,+}++#[derive(Debug, Clone)]+pub struct CallRecordSearchPayload {+ pub call_id: Uuid,+ pub channel_id: Uuid,+ pub created_by: String,+ pub channel_name: Option<String>,+ pub participant_ids: Vec<String>,+ pub segments: Vec<CallRecordTranscriptSegment>,+}++/// `attended` optionally narrows by participation.+#[tracing::instrument(skip(db))]+pub async fn get_accessible_call_ids(+ db: &sqlx::Pool<sqlx::Postgres>,+ user_id: &str,+ attended: Option<bool>,+) -> anyhow::Result<Vec<Uuid>> {+ sqlx::query_scalar!(+ r#"+ WITH user_source_ids AS (+ SELECT cp.channel_id::text AS source_id+ FROM comms_channel_participants cp+ WHERE cp.user_id = $1 AND cp.left_at IS NULL+ UNION ALL+ SELECT t.team_id::text+ FROM team_user t+ WHERE t.user_id = $1+ UNION ALL+ SELECT $1+ )+ SELECT DISTINCT cr.id AS "id!"+ FROM call_records cr+ WHERE (+ EXISTS (+ SELECT 1 FROM entity_access ea+ WHERE ea.entity_id = cr.id+ AND ea.entity_type = 'call'+ AND ea.source_id IN (SELECT source_id FROM user_source_ids)+ ) OR EXISTS (+ SELECT 1 FROM "SharePermission" sp+ WHERE sp.id = cr.share_permission_id+ AND sp."isPublic" = true+ AND sp."publicAccessLevel" IS NOT NULL+ )+ )+ AND ($2::bool IS NULL OR EXISTS (+ SELECT 1 FROM call_record_participants crp+ WHERE crp.call_record_id = cr.id AND crp.user_id = $1+ ) = $2)+ "#,+ user_id,+ attended,+ )+ .fetch_all(db)+ .await+ .map_err(Into::into)+}++#[tracing::instrument(skip(db))]+pub async fn get_call_records_for_search_backfill(+ db: &sqlx::Pool<sqlx::Postgres>,+ limit: i64,+ offset: i64,+) -> anyhow::Result<Vec<CallRecordSearchBackfill>> {+ sqlx::query_as!(+ CallRecordSearchBackfill,+ r#"SELECT id AS "call_id!" FROM call_records ORDER BY started_at DESC LIMIT $1 OFFSET $2"#,+ limit,+ offset,+ )+ .fetch_all(db)+ .await+ .map_err(Into::into)+}++/// Returns `None` if the call has been deleted.+#[tracing::instrument(skip(db))]+pub async fn get_call_record_search_payload(+ db: &sqlx::Pool<sqlx::Postgres>,+ call_id: &Uuid,+) -> anyhow::Result<Option<CallRecordSearchPayload>> {+ let Some(header) = sqlx::query!(+ r#"+ SELECT+ cr.id AS "call_id!",+ cr.channel_id AS "channel_id!",+ cr.created_by AS "created_by!",+ cc.name AS "channel_name?"+ FROM call_records cr+ LEFT JOIN comms_channels cc ON cc.id = cr.channel_id+ WHERE cr.id = $1+ "#,+ call_id,+ )+ .fetch_optional(db)+ .await?+ else {+ return Ok(None);+ };++ let participant_ids = sqlx::query_scalar!(+ r#"+ SELECT user_id AS "user_id!"+ FROM call_record_participants+ WHERE call_record_id = $1+ ORDER BY joined_at ASC+ "#,+ call_id,+ )+ .fetch_all(db)+ .await?;++ let segments = sqlx::query_as!(+ CallRecordTranscriptSegment,+ r#"+ SELECT+ id AS "transcript_id!",+ speaker_id AS "speaker_id!",+ sequence_num AS "sequence_num!",+ content AS "content!",+ started_at AS "started_at!",+ ended_at+ FROM call_record_transcripts+ WHERE call_record_id = $1+ ORDER BY sequence_num ASC+ "#,+ call_id,+ )+ .fetch_all(db)+ .await?;++ Ok(Some(CallRecordSearchPayload {+ call_id: header.call_id,+ channel_id: header.channel_id,+ created_by: header.created_by,+ channel_name: header.channel_name,+ participant_ids,+ segments,+ }))+}++/// `user_id` drives the per-row `attended` flag.+#[tracing::instrument(skip(db))]+pub async fn get_call_records_metadata(+ db: &sqlx::Pool<sqlx::Postgres>,+ user_id: &str,+ call_ids: &[Uuid],+) -> anyhow::Result<Vec<CallRecordMetadataRow>> {+ if call_ids.is_empty() {+ return Ok(Vec::new());+ }++ sqlx::query_as!(+ CallRecordMetadataRow,+ r#"+ SELECT+ cr.id AS "call_id!",+ cr.created_by AS "created_by!",+ cr.started_at AS "started_at!",+ cr.ended_at AS "ended_at!",+ cr.duration_ms AS "duration_ms!",+ cc.name AS "channel_name?",+ EXISTS (+ SELECT 1 FROM call_record_participants crp+ WHERE crp.call_record_id = cr.id AND crp.user_id = $2+ ) AS "attended!"+ FROM call_records cr+ LEFT JOIN comms_channels cc ON cc.id = cr.channel_id+ WHERE cr.id = ANY($1)+ "#,+ call_ids,+ user_id,+ )+ .fetch_all(db)+ .await+ .map_err(Into::into)+}diff --git a/rust/cloud-storage/macro_db_client/src/call_record/mod.rs b/rust/cloud-storage/macro_db_client/src/call_record/mod.rsnew file mode 100644index 0000000000..125ca70d5d--- /dev/null+++ b/rust/cloud-storage/macro_db_client/src/call_record/mod.rs@@ -0,0 +1 @@+pub mod get;diff --git a/rust/cloud-storage/macro_db_client/src/entity_name.rs b/rust/cloud-storage/macro_db_client/src/entity_name.rsindex f57568d77b..1b6f86ecf8 100644--- a/rust/cloud-storage/macro_db_client/src/entity_name.rs+++ b/rust/cloud-storage/macro_db_client/src/entity_name.rs@@ -82,6 +82,9 @@ pub async fn get_entity_name_and_owner(SearchEntityType::Projects => {anyhow::bail!("entity type not supported");}+ SearchEntityType::CallRecords => {+ anyhow::bail!("entity type not supported");+ }};Ok(result)diff --git a/rust/cloud-storage/macro_db_client/src/lib.rs b/rust/cloud-storage/macro_db_client/src/lib.rsindex 1cfa88dda4..59a538d47f 100644--- a/rust/cloud-storage/macro_db_client/src/lib.rs+++ b/rust/cloud-storage/macro_db_client/src/lib.rs@@ -4,6 +4,7 @@ pub mod activity;pub mod advisory_lock;pub mod annotations;pub mod blocked_email;+pub mod call_record;pub mod chat;pub mod chat_history;pub mod convert;diff --git a/rust/cloud-storage/models_opensearch/src/lib.rs b/rust/cloud-storage/models_opensearch/src/lib.rsindex 3fb023b907..21033eeb7b 100644--- a/rust/cloud-storage/models_opensearch/src/lib.rs+++ b/rust/cloud-storage/models_opensearch/src/lib.rs@@ -13,14 +13,15 @@ pub enum SearchIndex {Chats,/// The document indexDocuments,- /// The email index+ /// aliased email index#[strum(serialize = "emails_alias")]Emails,+ /// aliased call records index+ #[strum(serialize = "call_records_alias")]+ CallRecords,}-/// All searchable entity types across the system.-/// Not all variants have a corresponding OpenSearch index — Projects-/// are searched via Postgres only.+/// All searchable entity types. Projects are Postgres-only.#[derive(Debug,Clone,@@ -44,12 +45,15 @@ pub enum SearchEntityType {Documents,/// The email entity type (has OpenSearch index)Emails,- /// The project entity type (Postgres-only, no OpenSearch index)+ /// The project entity type (Postgres-only)Projects,+ /// The call records entity type (has OpenSearch index)+ #[strum(serialize = "call_records")]+ #[serde(rename = "call_records")]+ CallRecords,}-/// The subset of [`SearchEntityType`] that have a corresponding OpenSearch index.-/// Projects are intentionally excluded — they are searched via Postgres only.+/// `SearchEntityType` variants that have an OpenSearch index.#[derive(Debug,Clone,@@ -73,6 +77,10 @@ pub enum OpenSearchEntityType {Documents,/// The email indexEmails,+ /// The call records index+ #[strum(serialize = "call_records")]+ #[serde(rename = "call_records")]+ CallRecords,}impl OpenSearchEntityType {@@ -83,6 +91,7 @@ impl OpenSearchEntityType {Self::Chats => "chats",Self::Documents => "documents",Self::Emails => "emails_alias",+ Self::CallRecords => "call_records_alias",}}}@@ -94,6 +103,7 @@ impl From<OpenSearchEntityType> for SearchEntityType {OpenSearchEntityType::Chats => SearchEntityType::Chats,OpenSearchEntityType::Documents => SearchEntityType::Documents,OpenSearchEntityType::Emails => SearchEntityType::Emails,+ OpenSearchEntityType::CallRecords => SearchEntityType::CallRecords,}}}@@ -105,6 +115,7 @@ impl From<OpenSearchEntityType> for SearchIndex {OpenSearchEntityType::Chats => SearchIndex::Chats,OpenSearchEntityType::Documents => SearchIndex::Documents,OpenSearchEntityType::Emails => SearchIndex::Emails,+ OpenSearchEntityType::CallRecords => SearchIndex::CallRecords,}}}@@ -120,6 +131,7 @@ mod test {OpenSearchEntityType::Chats,OpenSearchEntityType::Documents,OpenSearchEntityType::Emails,+ OpenSearchEntityType::CallRecords,] {let from_index: SearchIndex = variant.clone().into();assert_eq!(variant.index_name(), from_index.as_ref());diff --git a/rust/cloud-storage/models_search/src/call_record.rs b/rust/cloud-storage/models_search/src/call_record.rsnew file mode 100644index 0000000000..06b9311fc2--- /dev/null+++ b/rust/cloud-storage/models_search/src/call_record.rs@@ -0,0 +1,90 @@+use chrono::{DateTime, Utc};+use item_filters::CallFilters;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;++use crate::{MatchType, SearchHighlight, SearchOn};++#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]+pub struct CallRecordSearchResult {+ pub transcript_id: Option<uuid::Uuid>,+ pub speaker_id: Option<String>,+ pub sequence_num: Option<i32>,+ pub started_at: Option<DateTime<Utc>>,+ pub ended_at: Option<DateTime<Utc>>,+ pub highlight: SearchHighlight,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub score: Option<f64>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]+pub struct CallRecordSearchResponseItem {+ pub id: uuid::Uuid,+ pub name: Option<String>,+ pub owner_id: String,+ pub call_id: uuid::Uuid,+ pub channel_id: uuid::Uuid,+ pub participant_ids: Vec<String>,+ pub call_search_results: Vec<CallRecordSearchResult>,+}++#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]+pub struct CallRecordMetadata {+ pub created_by: String,+ pub started_at: DateTime<Utc>,+ pub ended_at: DateTime<Utc>,+ pub duration_ms: i64,+ pub updated_at: DateTime<Utc>,+ pub channel_name: Option<String>,+ pub attended: bool,+}++#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]+pub struct CallRecordSearchResponseItemWithMetadata {+ /// `None` if the call has been deleted.+ pub metadata: Option<CallRecordMetadata>,+ #[serde(flatten)]+ pub extra: CallRecordSearchResponseItem,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct CallRecordSearchResponse {+ pub results: Vec<CallRecordSearchResponseItemWithMetadata>,+}++#[derive(Serialize, Deserialize, Debug, ToSchema, JsonSchema)]+pub struct CallRecordSearchRequest {+ pub query: Option<String>,+ pub terms: Option<Vec<String>>,+ pub match_type: MatchType,+ #[serde(flatten)]+ pub filters: Option<CallFilters>,+ #[serde(default)]+ pub search_on: SearchOn,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub collapse: Option<bool>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]+pub struct SimpleCallRecordSearchResponseBaseItem<T> {+ pub call_id: String,+ pub channel_id: String,+ pub user_id: String,+ pub participant_ids: Vec<String>,+ #[schema(inline)]+ pub started_at: T,+ #[schema(inline)]+ pub ended_at: T,+ pub duration_ms: i64,+ pub channel_name: Option<String>,+ pub highlight: SearchHighlight,+}++pub type SimpleCallRecordSearchResponseItem =+ SimpleCallRecordSearchResponseBaseItem<crate::HumanReadableTimestamp>;++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct SimpleCallRecordSearchResponse {+ pub results: Vec<SimpleCallRecordSearchResponseItem>,+}diff --git a/rust/cloud-storage/models_search/src/lib.rs b/rust/cloud-storage/models_search/src/lib.rsindex 260e48c859..6ca0e8fbd2 100644--- a/rust/cloud-storage/models_search/src/lib.rs+++ b/rust/cloud-storage/models_search/src/lib.rs@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};use strum::{Display, EnumString};use utoipa::ToSchema;+pub mod call_record;pub mod channel;pub mod chat;pub mod document;diff --git a/rust/cloud-storage/models_search/src/simple.rs b/rust/cloud-storage/models_search/src/simple.rsindex 02cf6f9a9a..5b6bd55f6f 100644--- a/rust/cloud-storage/models_search/src/simple.rs+++ b/rust/cloud-storage/models_search/src/simple.rs@@ -50,6 +50,17 @@ pub struct SearchGotoChannel {pub channel_message_id: uuid::Uuid,}+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, JsonSchema)]+pub struct SearchGotoCallRecord {+ pub channel_id: uuid::Uuid,+ pub transcript_id: uuid::Uuid,+ pub speaker_id: String,+ pub sequence_num: i32,+ pub started_at: DateTime<Utc>,+ pub ended_at: Option<DateTime<Utc>>,+ pub participant_ids: Vec<String>,+}+/// The search service version of a goto#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema, JsonSchema)]#[serde(untagged)]@@ -58,6 +69,7 @@ pub enum SearchGotoContent {Chats(SearchGotoChat),Emails(SearchGotoEmail),Channels(SearchGotoChannel),+ CallRecords(SearchGotoCallRecord),}impl From<opensearch_client::search::model::SearchGotoContent> for SearchGotoContent {@@ -91,6 +103,17 @@ impl From<opensearch_client::search::model::SearchGotoContent> for SearchGotoConchannel_message_id: a.channel_message_id,})}+ opensearch_client::search::model::SearchGotoContent::CallRecords(a) => {+ SearchGotoContent::CallRecords(SearchGotoCallRecord {+ channel_id: a.channel_id,+ transcript_id: a.transcript_id,+ speaker_id: a.speaker_id,+ sequence_num: a.sequence_num,+ started_at: a.started_at,+ ended_at: a.ended_at,+ participant_ids: a.participant_ids,+ })+ }}}}diff --git a/rust/cloud-storage/models_search/src/unified.rs b/rust/cloud-storage/models_search/src/unified.rsindex 59c199be20..03c968cb40 100644--- a/rust/cloud-storage/models_search/src/unified.rs+++ b/rust/cloud-storage/models_search/src/unified.rs@@ -1,19 +1,21 @@use chrono::{DateTime, Utc};use uuid::Uuid;+use crate::call_record::CallRecordSearchResponseItemWithMetadata;use crate::channel::ChannelSearchResponseItemWithMetadata;use crate::chat::ChatSearchResponseItemWithMetadata;use crate::document::DocumentSearchResponseItemWithMetadata;use crate::email::EmailSearchResponseItemWithMetadata;use crate::project::ProjectSearchResponseItemWithMetadata;use crate::{- MatchType, SearchOn, channel::SimpleChannelSearchReponseBaseItem,- chat::SimpleChatSearchResponseBaseItem, document::SimpleDocumentSearchResponseBaseItem,- email::SimpleEmailSearchResponseBaseItem, project::SimpleProjectSearchResponseBaseItem,+ MatchType, SearchOn, call_record::SimpleCallRecordSearchResponseBaseItem,+ channel::SimpleChannelSearchReponseBaseItem, chat::SimpleChatSearchResponseBaseItem,+ document::SimpleDocumentSearchResponseBaseItem, email::SimpleEmailSearchResponseBaseItem,+ project::SimpleProjectSearchResponseBaseItem,};use item_filters::{- ChannelFilters, ChatFilters, DocumentFilters, EmailFilters, EntityFilters, ProjectFilters,- ast::document::resolve_file_types,+ CallFilters, ChannelFilters, ChatFilters, DocumentFilters, EmailFilters, EntityFilters,+ ProjectFilters, ast::document::resolve_file_types,};use model_file_type::FileAssociation;use schemars::JsonSchema;@@ -28,6 +30,8 @@ pub enum UnifiedSearchIndex {Emails,Channels,Projects,+ #[serde(rename = "call_records")]+ CallRecords,}const NIL_UUID: &str = "00000000-0000-0000-0000-000000000000";@@ -57,7 +61,10 @@ pub fn entity_filters_from_include(filters.channel_filters.channel_ids = exclude.clone();}if !include.contains(&UnifiedSearchIndex::Projects) {- filters.project_filters.project_ids = exclude;+ filters.project_filters.project_ids = exclude.clone();+ }+ if !include.contains(&UnifiedSearchIndex::CallRecords) {+ filters.call_filters.channel_ids = exclude;}filters}@@ -110,6 +117,8 @@ pub struct SearchEntityFilters {pub should_include_channels: bool,/// Whether to include projects in search resultspub should_include_projects: bool,+ /// Whether to include call records in search results+ pub should_include_call_records: bool,/// Document filters with file associations expandedpub document_filters: DocumentFilters,/// Chat filters@@ -120,6 +129,8 @@ pub struct SearchEntityFilters {pub channel_filters: ChannelFilters,/// Project filterspub project_filters: ProjectFilters,+ /// Call filters+ pub call_filters: CallFilters,}fn contains_nil_uuid(ids: &[String]) -> bool {@@ -149,12 +160,14 @@ impl From<EntityFilters> for SearchEntityFilters {let mut email_filters = filters.email_filters;let mut channel_filters = filters.channel_filters;let mut project_filters = filters.project_filters;+ let mut call_filters = filters.call_filters;let should_include_documents = !contains_nil_uuid(&document_filters.document_ids);let should_include_chats = !contains_nil_uuid(&chat_filters.chat_ids);let should_include_emails = !contains_nil_uuid(&email_filters.email_thread_ids);let should_include_channels = !contains_nil_uuid(&channel_filters.channel_ids);let should_include_projects = !contains_nil_uuid(&project_filters.project_ids);+ let should_include_call_records = !contains_nil_uuid(&call_filters.channel_ids);strip_nil_uuids(&mut document_filters.document_ids);strip_nil_uuids(&mut chat_filters.chat_ids);@@ -162,6 +175,7 @@ impl From<EntityFilters> for SearchEntityFilters {strip_nil_uuids(&mut email_filters.recipients);strip_nil_uuids(&mut channel_filters.channel_ids);strip_nil_uuids(&mut project_filters.project_ids);+ strip_nil_uuids(&mut call_filters.channel_ids);document_filters.file_types = expand_file_types_for_search(document_filters.file_types);@@ -171,11 +185,13 @@ impl From<EntityFilters> for SearchEntityFilters {should_include_emails,should_include_channels,should_include_projects,+ should_include_call_records,document_filters,chat_filters,email_filters,channel_filters,project_filters,+ call_filters,}}}@@ -188,6 +204,7 @@ pub enum UnifiedSearchResponseItem {Email(EmailSearchResponseItemWithMetadata),Channel(ChannelSearchResponseItemWithMetadata),Project(ProjectSearchResponseItemWithMetadata),+ CallRecord(CallRecordSearchResponseItemWithMetadata),}impl UnifiedSearchResponseItem {@@ -198,6 +215,7 @@ impl UnifiedSearchResponseItem {Self::Email(item) => item.extra.id,Self::Channel(item) => item.extra.id,Self::Project(item) => item.extra.id,+ Self::CallRecord(item) => item.extra.id,}}/// Get the updated_at timestamp for each item@@ -219,6 +237,7 @@ impl UnifiedSearchResponseItem {max_result_updated_at.or_else(|| item.metadata.as_ref().map(|m| m.updated_at))}Self::Project(item) => item.metadata.as_ref().map(|m| m.updated_at),+ Self::CallRecord(item) => item.metadata.as_ref().map(|m| m.updated_at),}}}@@ -239,6 +258,7 @@ pub enum SimpleUnifiedSearchResponseBaseItem<T> {Email(SimpleEmailSearchResponseBaseItem<T>),Channel(SimpleChannelSearchReponseBaseItem<T>),Project(SimpleProjectSearchResponseBaseItem<T>),+ CallRecord(SimpleCallRecordSearchResponseBaseItem<T>),}pub type SimpleUnifiedSearchResponseItem =diff --git a/rust/cloud-storage/opensearch_client/src/call_record.rs b/rust/cloud-storage/opensearch_client/src/call_record.rsnew file mode 100644index 0000000000..e23c402d3b--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/call_record.rs@@ -0,0 +1,35 @@+use crate::{+ OpensearchClient, Result, delete,+ upsert::{+ self, BulkUpsertResult,+ call_record::{UpsertCallRecordSegmentArgs, bulk_upsert_call_record_segments},+ },+};++impl OpensearchClient {+ #[tracing::instrument(skip(self))]+ pub async fn upsert_call_record_segment(+ &self,+ args: &UpsertCallRecordSegmentArgs,+ ) -> Result<()> {+ upsert::call_record::upsert_call_record_segment(&self.inner, args).await+ }++ #[tracing::instrument(skip(self, segments))]+ pub async fn bulk_upsert_call_record_segments(+ &self,+ segments: &[UpsertCallRecordSegmentArgs],+ ) -> Result<BulkUpsertResult> {+ bulk_upsert_call_record_segments(&self.inner, segments).await+ }++ #[tracing::instrument(skip(self))]+ pub async fn delete_call_record(&self, call_id: &str) -> Result<()> {+ delete::call_record::delete_call_record_by_id(&self.inner, call_id).await+ }++ #[tracing::instrument(skip(self))]+ pub async fn delete_call_records_by_channel(&self, channel_id: &str) -> Result<()> {+ delete::call_record::delete_call_records_by_channel_id(&self.inner, channel_id).await+ }+}diff --git a/rust/cloud-storage/opensearch_client/src/delete/call_record.rs b/rust/cloud-storage/opensearch_client/src/delete/call_record.rsnew file mode 100644index 0000000000..0d9a533a41--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/delete/call_record.rs@@ -0,0 +1,66 @@+use models_opensearch::SearchIndex;++use crate::{Result, error::OpensearchClientError};++#[tracing::instrument(skip(client))]+pub async fn delete_call_record_by_id(+ client: &opensearch::OpenSearch,+ call_id: &str,+) -> Result<()> {+ delete_by_term(client, "entity_id", call_id, "delete_call_record_by_id").await+}++#[tracing::instrument(skip(client))]+pub async fn delete_call_records_by_channel_id(+ client: &opensearch::OpenSearch,+ channel_id: &str,+) -> Result<()> {+ delete_by_term(+ client,+ "channel_id",+ channel_id,+ "delete_call_records_by_channel_id",+ )+ .await+}++async fn delete_by_term(+ client: &opensearch::OpenSearch,+ field: &str,+ value: &str,+ method: &str,+) -> Result<()> {+ let query = serde_json::json!({ "query": { "term": { field: value } } });++ let response = client+ .delete_by_query(opensearch::DeleteByQueryParts::Index(&[+ SearchIndex::CallRecords.as_ref(),+ ]))+ .body(query)+ .refresh(true)+ .send()+ .await+ .map_err(|err| OpensearchClientError::Unknown {+ details: err.to_string(),+ method: Some(method.to_string()),+ })?;++ let status = response.status_code();+ if !status.is_success() {+ let body =+ response+ .text()+ .await+ .map_err(|err| OpensearchClientError::DeserializationFailed {+ details: err.to_string(),+ method: Some(method.to_string()),+ })?;+ tracing::error!(status_code = ?status, body = ?body, "error deleting call records");+ return Err(OpensearchClientError::Unknown {+ details: body,+ method: Some(method.to_string()),+ });+ }++ Ok(())+}diff --git a/rust/cloud-storage/opensearch_client/src/delete/mod.rs b/rust/cloud-storage/opensearch_client/src/delete/mod.rsindex 0f40840c1b..ee9171dd5a 100644--- a/rust/cloud-storage/opensearch_client/src/delete/mod.rs+++ b/rust/cloud-storage/opensearch_client/src/delete/mod.rs@@ -1,3 +1,4 @@+pub mod call_record;pub mod channel;pub mod chat;pub mod document;diff --git a/rust/cloud-storage/opensearch_client/src/error.rs b/rust/cloud-storage/opensearch_client/src/error.rsindex c043834458..f1123bef36 100644--- a/rust/cloud-storage/opensearch_client/src/error.rs+++ b/rust/cloud-storage/opensearch_client/src/error.rs@@ -52,6 +52,9 @@ pub enum OpensearchClientError {#[error("empty ids with ids only for {0}")]EmptyIdsWithIdsOnly(OpenSearchEntityType),+ #[error("USER_ID_KEY is required for ids_only=false search on {0}")]+ UserIdKeyRequired(OpenSearchEntityType),+#[error("searching with exhausted cursor")]SearchWithExhaustedCursor,}diff --git a/rust/cloud-storage/opensearch_client/src/lib.rs b/rust/cloud-storage/opensearch_client/src/lib.rsindex 9ce9123b30..516617dc29 100644--- a/rust/cloud-storage/opensearch_client/src/lib.rs+++ b/rust/cloud-storage/opensearch_client/src/lib.rs@@ -5,6 +5,7 @@ pub mod search;pub mod unified;pub mod upsert;+pub mod call_record;pub mod channel_message;pub mod chat;pub mod document;diff --git a/rust/cloud-storage/opensearch_client/src/search/builder.rs b/rust/cloud-storage/opensearch_client/src/search/builder.rsindex 40ef97375b..c50b016039 100644--- a/rust/cloud-storage/opensearch_client/src/search/builder.rs+++ b/rust/cloud-storage/opensearch_client/src/search/builder.rs@@ -76,8 +76,10 @@ pub(crate) fn search_after(cursor: SearchMethodCursor) -> Vec<serde_json::Value>pub trait SearchQueryConfig {/// Key for item idconst ID_KEY: &'static str = "entity_id";- /// Key for user id- const USER_ID_KEY: &'static str;+ /// Key for user id. Required for `ids_only = false`; leave `None` for+ /// indices that only support `ids_only = true` (access comes from the+ /// caller-supplied id allowlist).+ const USER_ID_KEY: Option<&'static str> = None;/// Key for titleconst TITLE_KEY: &'static str;/// Content field@@ -166,7 +168,7 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {/// access to/has requested./// This could either be a single term/terms query for ids_only or just user_id/// Or a bool query that contains both of these items- fn build_filter_query<'a>(&'a self, user_id_key: &str) -> Result<QueryType<'a>> {+ fn build_filter_query<'a>(&'a self, user_id_key: Option<&str>) -> Result<QueryType<'a>> {if self.ids_only {// We only need to search over the entity ids providedif self.ids.is_empty() {@@ -176,6 +178,8 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {// Return just the id query to filter overOk(QueryType::terms(T::ID_KEY.to_string(), self.ids.to_vec()))} else {+ let user_id_key =+ user_id_key.ok_or(OpensearchClientError::UserIdKeyRequired(T::ENTITY_INDEX))?;let user_id_query = QueryType::term(user_id_key.to_string(), self.user_id.clone());// If there are no ids provided we can return only the user id query to filter overdiff --git a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs b/rust/cloud-storage/opensearch_client/src/search/builder/test.rsindex 9089cc7f38..584d35beb8 100644--- a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/builder/test.rs@@ -5,7 +5,7 @@ use opensearch_query_builder::ToOpenSearchJson;struct TestSearchConfig;impl SearchQueryConfig for TestSearchConfig {- const USER_ID_KEY: &'static str = "test_user_id";+ const USER_ID_KEY: Option<&'static str> = Some("test_user_id");const TITLE_KEY: &'static str = "test_title";const ENTITY_INDEX: OpenSearchEntityType = OpenSearchEntityType::Documents;}diff --git a/rust/cloud-storage/opensearch_client/src/search/call_records.rs b/rust/cloud-storage/opensearch_client/src/search/call_records.rsnew file mode 100644index 0000000000..4efa91c469--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/search/call_records.rs@@ -0,0 +1,110 @@+use crate::{+ Result, delegate_methods,+ search::builder::{SearchQueryBuilder, SearchQueryConfig},+};++use models_opensearch::OpenSearchEntityType;+use opensearch_query_builder::{BoolQueryBuilder, QueryType};++#[derive(Debug, serde::Serialize, serde::Deserialize)]+pub(crate) struct CallRecordIndex {+ pub entity_id: uuid::Uuid,+ pub channel_id: uuid::Uuid,+ pub transcript_id: uuid::Uuid,+ #[serde(default)]+ pub participant_ids: Vec<String>,+ #[serde(default)]+ pub channel_name: Option<String>,+ pub speaker_id: String,+ pub sequence_num: i32,+ pub started_at_seconds: i64,+ #[serde(default)]+ pub ended_at_seconds: Option<i64>,+}++pub(crate) struct CallRecordSearchConfig;++impl SearchQueryConfig for CallRecordSearchConfig {+ const TITLE_KEY: &'static str = "channel_name";+ const ENTITY_INDEX: OpenSearchEntityType = OpenSearchEntityType::CallRecords;+}++pub(crate) struct CallRecordQueryBuilder {+ inner: SearchQueryBuilder<CallRecordSearchConfig>,+ channel_ids: Vec<String>,+ speaker_ids: Vec<String>,+}++impl CallRecordQueryBuilder {+ pub fn new(terms: Vec<String>) -> Self {+ Self {+ inner: SearchQueryBuilder::new(terms),+ channel_ids: Vec::new(),+ speaker_ids: Vec::new(),+ }+ }++ delegate_methods! {+ fn match_type(match_type: &str) -> Self;+ fn page(page: u32) -> Self;+ fn page_size(page_size: u32) -> Self;+ fn user_id(user_id: &str) -> Self;+ fn collapse(collapse: bool) -> Self;+ fn ids(ids: Vec<String>) -> Self;+ fn ids_only(ids_only: bool) -> Self;+ }++ pub fn channel_ids(mut self, channel_ids: Vec<String>) -> Self {+ self.channel_ids = channel_ids;+ self+ }++ pub fn speaker_ids(mut self, speaker_ids: Vec<String>) -> Self {+ self.speaker_ids = speaker_ids;+ self+ }++ pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {+ // Access comes from `ids_only` + accessible call_ids; these just narrow.+ let mut content_bool_query = self.inner.build_content_bool_query()?;++ if !self.channel_ids.is_empty() {+ content_bool_query.filter(QueryType::terms("channel_id", self.channel_ids.clone()));+ }++ if !self.speaker_ids.is_empty() {+ content_bool_query.filter(QueryType::terms("speaker_id", self.speaker_ids.clone()));+ }++ Ok(content_bool_query)+ }+}++#[derive(Debug, Default)]+pub struct CallRecordSearchArgs {+ pub terms: Vec<String>,+ pub user_id: String,+ pub call_ids: Vec<String>,+ pub channel_ids: Vec<String>,+ pub speaker_ids: Vec<String>,+ pub page: u32,+ pub page_size: u32,+ pub match_type: String,+ pub collapse: bool,+ pub ids_only: bool,+}++impl From<CallRecordSearchArgs> for CallRecordQueryBuilder {+ fn from(args: CallRecordSearchArgs) -> Self {+ CallRecordQueryBuilder::new(args.terms)+ .match_type(&args.match_type)+ .page_size(args.page_size)+ .page(args.page)+ .user_id(&args.user_id)+ .ids(args.call_ids)+ .channel_ids(args.channel_ids)+ .speaker_ids(args.speaker_ids)+ .collapse(args.collapse)+ .ids_only(args.ids_only)+ }+}diff --git a/rust/cloud-storage/opensearch_client/src/search/channels.rs b/rust/cloud-storage/opensearch_client/src/search/channels.rsindex 7b86cac6d0..b2397192c1 100644--- a/rust/cloud-storage/opensearch_client/src/search/channels.rs+++ b/rust/cloud-storage/opensearch_client/src/search/channels.rs@@ -23,7 +23,7 @@ pub(crate) struct ChannelMessageIndex {pub(crate) struct ChannelMessageSearchConfig;impl SearchQueryConfig for ChannelMessageSearchConfig {- const USER_ID_KEY: &'static str = "sender_id";+ const USER_ID_KEY: Option<&'static str> = Some("sender_id");const TITLE_KEY: &'static str = "name";const ENTITY_INDEX: OpenSearchEntityType = OpenSearchEntityType::Channels;}diff --git a/rust/cloud-storage/opensearch_client/src/search/chats.rs b/rust/cloud-storage/opensearch_client/src/search/chats.rsindex 64280ac983..3b4954c8e7 100644--- a/rust/cloud-storage/opensearch_client/src/search/chats.rs+++ b/rust/cloud-storage/opensearch_client/src/search/chats.rs@@ -22,7 +22,7 @@ pub(crate) struct ChatIndex {pub(crate) struct ChatSearchConfig;impl SearchQueryConfig for ChatSearchConfig {- const USER_ID_KEY: &'static str = "user_id";+ const USER_ID_KEY: Option<&'static str> = Some("user_id");const TITLE_KEY: &'static str = "name";const ENTITY_INDEX: OpenSearchEntityType = OpenSearchEntityType::Chats;}diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rsindex 370bac7ae5..3cb9d49ff4 100644--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs@@ -10,7 +10,7 @@ use opensearch_query_builder::{BoolQueryBuilder, QueryType};pub(crate) struct DocumentSearchConfig;impl SearchQueryConfig for DocumentSearchConfig {- const USER_ID_KEY: &'static str = "owner_id";+ const USER_ID_KEY: Option<&'static str> = Some("owner_id");const TITLE_KEY: &'static str = "name";const ENTITY_INDEX: OpenSearchEntityType = OpenSearchEntityType::Documents;}diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rsindex 1391e78225..fe427ee2ad 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs@@ -12,7 +12,7 @@ use opensearch_query_builder::{BoolQuery, BoolQueryBuilder, QueryType, SimpleQuepub(crate) struct EmailSearchConfig;impl SearchQueryConfig for EmailSearchConfig {- const USER_ID_KEY: &'static str = "user_id";+ const USER_ID_KEY: Option<&'static str> = Some("user_id");const TITLE_KEY: &'static str = "subject";const ENTITY_INDEX: OpenSearchEntityType = OpenSearchEntityType::Emails;}diff --git a/rust/cloud-storage/opensearch_client/src/search/mod.rs b/rust/cloud-storage/opensearch_client/src/search/mod.rsindex 8cbcb574ab..9a6220d929 100644--- a/rust/cloud-storage/opensearch_client/src/search/mod.rs+++ b/rust/cloud-storage/opensearch_client/src/search/mod.rs@@ -1,4 +1,5 @@mod builder;+pub mod call_records;pub mod channels;pub mod chats;pub mod documents;diff --git a/rust/cloud-storage/opensearch_client/src/search/model/mod.rs b/rust/cloud-storage/opensearch_client/src/search/model/mod.rsindex 8b3877e2ac..a0f2867b1e 100644--- a/rust/cloud-storage/opensearch_client/src/search/model/mod.rs+++ b/rust/cloud-storage/opensearch_client/src/search/model/mod.rs@@ -388,6 +388,17 @@ pub struct SearchGotoChannel {pub updated_at: chrono::DateTime<chrono::Utc>,}+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]+pub struct SearchGotoCallRecord {+ pub channel_id: uuid::Uuid,+ pub transcript_id: uuid::Uuid,+ pub speaker_id: String,+ pub sequence_num: i32,+ pub started_at: chrono::DateTime<chrono::Utc>,+ pub ended_at: Option<chrono::DateTime<chrono::Utc>>,+ pub participant_ids: Vec<String>,+}+/// Enum containing structs for all data needed to handle search "goto" in the frontend#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]#[serde(untagged)]@@ -396,6 +407,7 @@ pub enum SearchGotoContent {Chats(SearchGotoChat),Emails(SearchGotoEmail),Channels(SearchGotoChannel),+ CallRecords(SearchGotoCallRecord),// there is no goto needed for projects}diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rsindex 9254489f24..60c424d953 100644--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs@@ -5,6 +5,9 @@ use crate::{error::{OpensearchClientError, ResponseExt},search::{builder::{SearchQueryConfig, search_after, updated_at_sort},+ call_records::{+ CallRecordIndex, CallRecordQueryBuilder, CallRecordSearchArgs, CallRecordSearchConfig,+ },channels::{ChannelMessageIndex, ChannelMessageQueryBuilder, ChannelMessageSearchArgs,ChannelMessageSearchConfig,@@ -15,8 +18,8 @@ use crate::{},emails::{EmailIndex, EmailQueryBuilder, EmailSearchArgs, EmailSearchConfig},model::{- DefaultSearchResponse, Hit, MacroEm, SearchGotoChannel, SearchGotoChat,- SearchGotoContent, SearchGotoDocument, SearchGotoEmail, SearchHit,+ DefaultSearchResponse, Hit, MacroEm, SearchGotoCallRecord, SearchGotoChannel,+ SearchGotoChat, SearchGotoContent, SearchGotoDocument, SearchGotoEmail, SearchHit,exclude_source_content, inject_fragment_size, parse_highlight_hit,},query::Keys,@@ -58,6 +61,8 @@ pub struct UnifiedSearchArgs {pub channel_message_search_args: UnifiedChannelMessageSearchArgs,/// The chat search args. If None, we do not search chatspub chat_search_args: UnifiedChatSearchArgs,+ /// The call record search args. If None, we do not search call records+ pub call_record_search_args: UnifiedCallRecordSearchArgs,}impl From<UnifiedSearchArgs> for DocumentSearchArgs {@@ -134,6 +139,23 @@ impl From<UnifiedSearchArgs> for ChatSearchArgs {}}+impl From<UnifiedSearchArgs> for CallRecordSearchArgs {+ fn from(args: UnifiedSearchArgs) -> Self {+ CallRecordSearchArgs {+ terms: args.call_record_search_args.terms,+ user_id: args.user_id,+ page: args.page,+ page_size: args.page_size,+ match_type: args.match_type,+ collapse: args.collapse,+ ids_only: args.call_record_search_args.ids_only,+ call_ids: args.call_record_search_args.call_ids,+ channel_ids: args.call_record_search_args.channel_ids,+ speaker_ids: args.call_record_search_args.speaker_ids,+ }+ }+}+#[derive(Debug, Default, Clone)]pub struct UnifiedChatSearchArgs {pub terms: Vec<String>,@@ -174,6 +196,15 @@ pub struct UnifiedChannelMessageSearchArgs {pub sender_ids: Vec<String>,}+#[derive(Debug, Default, Clone)]+pub struct UnifiedCallRecordSearchArgs {+ pub terms: Vec<String>,+ pub call_ids: Vec<String>,+ pub channel_ids: Vec<String>,+ pub speaker_ids: Vec<String>,+ pub ids_only: bool,+}+/// Possible search result indices for unified search#[derive(Debug, serde::Serialize, serde::Deserialize)]#[serde(untagged)]@@ -182,6 +213,7 @@ pub(crate) enum UnifiedSearchIndex {Document(DocumentIndex),Chat(ChatIndex),Email(EmailIndex),+ CallRecord(CallRecordIndex),}pub struct SplitUnifiedSearchResponseValues {@@ -190,6 +222,7 @@ pub struct SplitUnifiedSearchResponseValues {pub document: Vec<SearchHit>,pub email: Vec<SearchHit>,pub project: Vec<SearchHit>,+ pub call_record: Vec<SearchHit>,}pub trait SplitUnifiedSearchResponse: Iterator<Item = SearchHit> {@@ -201,9 +234,17 @@ whereT: Iterator<Item = SearchHit>,{fn split_search_response(self) -> SplitUnifiedSearchResponseValues {- let (channel_message, chat, document, email, project) = self.into_iter().fold(- (vec![], vec![], vec![], vec![], vec![]),- |(mut channel_message, mut chat, mut document, mut email, mut project), item| {+ let (channel_message, chat, document, email, project, call_record) = self.into_iter().fold(+ (vec![], vec![], vec![], vec![], vec![], vec![]),+ |(+ mut channel_message,+ mut chat,+ mut document,+ mut email,+ mut project,+ mut call_record,+ ),+ item| {match item.entity_type {SearchEntityType::Channels => {channel_message.push(item);@@ -220,8 +261,11 @@ whereSearchEntityType::Projects => {project.push(item);}+ SearchEntityType::CallRecords => {+ call_record.push(item);+ }}- (channel_message, chat, document, email, project)+ (channel_message, chat, document, email, project, call_record)},);@@ -231,6 +275,7 @@ wheredocument,email,project,+ call_record,}}}@@ -344,6 +389,36 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {.updated_at_seconds.and_then(|s| DateTime::from_timestamp(s, 0)),},+ UnifiedSearchIndex::CallRecord(a) => SearchHit {+ entity_id: a.entity_id,+ entity_type: SearchEntityType::CallRecords,+ score: index.score,+ highlight: index+ .highlight+ .map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: CallRecordSearchConfig::TITLE_KEY,+ content_key: CallRecordSearchConfig::CONTENT_KEY,+ },+ )+ })+ .unwrap_or_default(),+ goto: Some(SearchGotoContent::CallRecords(SearchGotoCallRecord {+ channel_id: a.channel_id,+ transcript_id: a.transcript_id,+ speaker_id: a.speaker_id,+ sequence_num: a.sequence_num,+ started_at: DateTime::from_timestamp(a.started_at_seconds, 0)+ .unwrap_or_default(),+ ended_at: a+ .ended_at_seconds+ .and_then(|s| DateTime::from_timestamp(s, 0)),+ participant_ids: a.participant_ids,+ })),+ updated_at: DateTime::from_timestamp(a.started_at_seconds, 0),+ },}}}@@ -404,6 +479,17 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchRequesbool_query.should(query_type.to_owned());}+ if args+ .search_indices+ .contains(&OpenSearchEntityType::CallRecords)+ {+ let call_record_search_args: CallRecordSearchArgs = args.clone().into();+ let call_record_query_builder: CallRecordQueryBuilder = call_record_search_args.into();+ let call_record_bool_query = call_record_query_builder.build_bool_query()?;+ let query_type: QueryType = call_record_bool_query.build().into();+ bool_query.should(query_type.to_owned());+ }+// create the search requestlet mut search_request_builder = SearchRequestBuilder::new();diff --git a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs b/rust/cloud-storage/opensearch_client/src/search/unified/test.rsindex 3daf4a290a..2811f4ffd2 100644--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs@@ -449,6 +449,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {role: vec!["id1".to_string(), "id2".to_string()],ids_only: false,},+ call_record_search_args: UnifiedCallRecordSearchArgs::default(),cursor: SearchCursorOption::NotDone(Some(SearchMethodCursor {entity_id,updated_at: time,@@ -834,6 +835,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {role: vec!["id1".to_string(), "id2".to_string()],ids_only: false,},+ call_record_search_args: UnifiedCallRecordSearchArgs::default(),cursor: SearchCursorOption::NotDone(Some(SearchMethodCursor {entity_id,updated_at: time,diff --git a/rust/cloud-storage/opensearch_client/src/upsert/call_record.rs b/rust/cloud-storage/opensearch_client/src/upsert/call_record.rsnew file mode 100644index 0000000000..970a3a84e5--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/upsert/call_record.rs@@ -0,0 +1,94 @@+use models_opensearch::SearchIndex;++use super::BulkUpsertResult;+use crate::{Result, date_format::EpochSeconds, error::OpensearchClientError};++#[derive(Debug, serde::Serialize)]+pub struct UpsertCallRecordSegmentArgs {+ #[serde(rename = "entity_id")]+ pub call_id: String,+ pub transcript_id: String,+ pub channel_id: String,+ pub participant_ids: Vec<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub channel_name: Option<String>,+ pub speaker_id: String,+ pub sequence_num: i32,+ pub content: String,+ pub started_at_seconds: EpochSeconds,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub ended_at_seconds: Option<EpochSeconds>,+}++#[tracing::instrument(skip(client), err)]+pub(crate) async fn upsert_call_record_segment(+ client: &opensearch::OpenSearch,+ args: &UpsertCallRecordSegmentArgs,+) -> Result<()> {+ let id = &args.transcript_id;+ let response = client+ .index(opensearch::IndexParts::IndexId(+ SearchIndex::CallRecords.as_ref(),+ id,+ ))+ .body(args)+ .send()+ .await+ .map_err(|err| OpensearchClientError::DeserializationFailed {+ details: err.to_string(),+ method: Some("upsert_call_record_segment".to_string()),+ })?;++ let status_code = response.status_code();+ if status_code.is_success() {+ tracing::trace!(id=%id, "call record segment upserted");+ } else {+ let body =+ response+ .text()+ .await+ .map_err(|err| OpensearchClientError::DeserializationFailed {+ details: err.to_string(),+ method: Some("upsert_call_record_segment".to_string()),+ })?;++ tracing::error!(status_code=%status_code, body=%body, "error upserting call record segment");++ return Err(OpensearchClientError::Unknown {+ details: body,+ method: Some("upsert_call_record_segment".to_string()),+ });+ }+ Ok(())+}++#[tracing::instrument(skip(client, segments), err)]+pub(crate) async fn bulk_upsert_call_record_segments(+ client: &opensearch::OpenSearch,+ segments: &[UpsertCallRecordSegmentArgs],+) -> Result<BulkUpsertResult> {+ if segments.is_empty() {+ return Ok(BulkUpsertResult::default());+ }++ let mut bulk_body = Vec::with_capacity(segments.len() * 2);++ for seg in segments {+ let action = serde_json::json!({ "index": { "_id": seg.transcript_id } });+ bulk_body.push(action.to_string());+ bulk_body.push(serde_json::to_string(seg).map_err(|e| {+ OpensearchClientError::DeserializationFailed {+ details: e.to_string(),+ method: Some("bulk_upsert_call_record_segments".to_string()),+ }+ })?);+ }++ super::bulk_upsert_to_index(+ client,+ SearchIndex::CallRecords.as_ref(),+ bulk_body,+ "bulk_upsert_call_record_segments",+ )+ .await+}diff --git a/rust/cloud-storage/opensearch_client/src/upsert/mod.rs b/rust/cloud-storage/opensearch_client/src/upsert/mod.rsindex a21975c497..bfef2f9cbd 100644--- a/rust/cloud-storage/opensearch_client/src/upsert/mod.rs+++ b/rust/cloud-storage/opensearch_client/src/upsert/mod.rs@@ -1,3 +1,4 @@+pub mod call_record;pub mod channel_message;pub mod chat_message;pub mod document;diff --git a/rust/cloud-storage/search_processing_service/Cargo.toml b/rust/cloud-storage/search_processing_service/Cargo.tomlindex 7a92413764..2b24382fc9 100644--- a/rust/cloud-storage/search_processing_service/Cargo.toml+++ b/rust/cloud-storage/search_processing_service/Cargo.toml@@ -15,6 +15,11 @@ name = "backfill_chat"path = "src/bin/backfill_chat.rs"required-features = ["service"]+[[bin]]+name = "backfill_call"+path = "src/bin/backfill_call.rs"+required-features = ["service"]+[[bin]]name = "search_processing_service"path = "src/main.rs"diff --git a/rust/cloud-storage/search_processing_service/README.md b/rust/cloud-storage/search_processing_service/README.mdindex 12f98b9594..08707b768a 100644--- a/rust/cloud-storage/search_processing_service/README.md+++ b/rust/cloud-storage/search_processing_service/README.md@@ -4,17 +4,23 @@ This service is responsible for processing search text extraction messages and u## Running Locally-To run the service locally, you need to have aws cli setup with valid credentials for Macro.+The `localdev` sops bundle already carries every env var this service needs (dev `DATABASE_URL`, dev OpenSearch creds, `ENVIRONMENT=local`, dummy `SYNC_SERVICE_AUTH_KEY` / `LEXICAL_SERVICE_URL` that are unused by most processors). Requires valid AWS credentials for secrets manager + SQS.-Copy the `.env.sample` file to `.env` and fill in the values for the environment variables.--Run the following command to start the service:+From the repo root:```bash+just get_environment localdev # writes .env at repo root+cd rust/cloud-storage/search_processing_servicecargo run```-To run without processing queue messages, you can run the following command:+Override `SEARCH_EVENT_QUEUE` on a per-run basis (e.g. backfills onto a scratch queue) so you don't consume the shared dev queue:++```bash+SEARCH_EVENT_QUEUE=search-event-queue-<scope>-<you> cargo run+```++To run the API surface without the worker loop:```bashcargo run --features disable_processingdiff --git a/rust/cloud-storage/search_processing_service/src/api/context.rs b/rust/cloud-storage/search_processing_service/src/api/context.rsindex db5f4e580a..4a0ffdf3c0 100644--- a/rust/cloud-storage/search_processing_service/src/api/context.rs+++ b/rust/cloud-storage/search_processing_service/src/api/context.rs@@ -7,6 +7,7 @@ use crate::config::Config;#[derive(Clone, FromRef)]pub(crate) struct ApiContext {+ pub db: sqlx::Pool<sqlx::Postgres>,pub sqs_client: Arc<sqs_client::SQS>,pub opensearch_client: Arc<opensearch_client::OpensearchClient>,pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,diff --git a/rust/cloud-storage/search_processing_service/src/api/internal/backfill_calls.rs b/rust/cloud-storage/search_processing_service/src/api/internal/backfill_calls.rsnew file mode 100644index 0000000000..95f2270ab1--- /dev/null+++ b/rust/cloud-storage/search_processing_service/src/api/internal/backfill_calls.rs@@ -0,0 +1,99 @@+use axum::{+ extract::{self, State},+ http::StatusCode,+ response::{IntoResponse, Response},+};+use sqs_client::search::{SearchQueueMessage, call::CallRecordMessage};++use crate::api::context::ApiContext;++#[derive(serde::Deserialize, Default)]+#[serde(default)]+pub struct BackfillCallsRequest {+ /// Empty = every archived call.+ pub call_ids: Vec<String>,+}++#[derive(serde::Serialize)]+pub struct BackfillCallsResponse {+ pub enqueued: usize,+}++const BACKFILL_PAGE: i64 = 2000;++#[tracing::instrument(err(Debug), skip(ctx, req))]+pub async fn handler(+ State(ctx): State<ApiContext>,+ extract::Json(req): extract::Json<BackfillCallsRequest>,+) -> Result<Response, Response> {+ if !req.call_ids.is_empty() {+ let messages: Vec<SearchQueueMessage> = req+ .call_ids+ .iter()+ .map(|id| {+ SearchQueueMessage::CallRecord(CallRecordMessage {+ call_id: id.clone(),+ })+ })+ .collect();++ let count = messages.len();+ ctx.sqs_client+ .bulk_send_message_to_search_event_queue(messages)+ .await+ .map_err(internal_error)?;++ return Ok(axum::Json(BackfillCallsResponse { enqueued: count }).into_response());+ }++ let mut offset = 0i64;+ let mut enqueued = 0usize;++ loop {+ let batch = macro_db_client::call_record::get::get_call_records_for_search_backfill(+ &ctx.db,+ BACKFILL_PAGE,+ offset,+ )+ .await+ .map_err(internal_error)?;++ if batch.is_empty() {+ break;+ }++ let batch_len = batch.len();+ let messages: Vec<SearchQueueMessage> = batch+ .into_iter()+ .map(|r| {+ SearchQueueMessage::CallRecord(CallRecordMessage {+ call_id: r.call_id.to_string(),+ })+ })+ .collect();++ enqueued += messages.len();++ ctx.sqs_client+ .bulk_send_message_to_search_event_queue(messages)+ .await+ .map_err(internal_error)?;++ if (batch_len as i64) < BACKFILL_PAGE {+ break;+ }++ offset += BACKFILL_PAGE;+ }++ Ok(axum::Json(BackfillCallsResponse { enqueued }).into_response())+}++fn internal_error(e: impl std::fmt::Debug) -> Response {+ tracing::error!(error=?e, "call records backfill failed");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ "failed to enqueue call records",+ )+ .into_response()+}diff --git a/rust/cloud-storage/search_processing_service/src/api/internal/mod.rs b/rust/cloud-storage/search_processing_service/src/api/internal/mod.rsindex 8112edf7e6..e93090fd8b 100644--- a/rust/cloud-storage/search_processing_service/src/api/internal/mod.rs+++ b/rust/cloud-storage/search_processing_service/src/api/internal/mod.rs@@ -4,6 +4,7 @@ use axum::{routing::{delete, post},};+pub(in crate::api) mod backfill_calls;pub(in crate::api) mod delete_document;pub(in crate::api) mod extract_sync;@@ -11,4 +12,5 @@ pub fn router() -> Router<ApiContext> {Router::new().route("/delete/{document_id}", delete(delete_document::handler)).route("/extract_sync", post(extract_sync::handler))+ .route("/backfill/calls", post(backfill_calls::handler))}diff --git a/rust/cloud-storage/search_processing_service/src/bin/backfill_call.rs b/rust/cloud-storage/search_processing_service/src/bin/backfill_call.rsnew file mode 100644index 0000000000..f1fd2e1096--- /dev/null+++ b/rust/cloud-storage/search_processing_service/src/bin/backfill_call.rs@@ -0,0 +1,65 @@+use anyhow::Context;+use macro_entrypoint::MacroEntrypoint;+use sqlx::postgres::PgPoolOptions;+use sqs_client::search::call::CallRecordMessage;++#[tokio::main]+async fn main() -> anyhow::Result<()> {+ MacroEntrypoint::default().init();++ let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL not set")?;+ let db = PgPoolOptions::new()+ .min_connections(5)+ .max_connections(30)+ .connect(&database_url)+ .await+ .context("could not connect to db")?;++ let search_event_queue =+ std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE not set")?;++ let queue_aws_config = macro_aws_config::get_macro_aws_config().await;++ let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&queue_aws_config))+ .search_event_queue(&search_event_queue);++ let limit = 2000;+ let mut offset = 0;+ let mut count = 0;+ loop {+ tracing::info!(limit = %limit, offset = %offset, "getting call records");++ let records = macro_db_client::call_record::get::get_call_records_for_search_backfill(+ &db, limit, offset,+ )+ .await?;+ tracing::info!(%offset, fetched = records.len(), "fetched batch");++ if records.is_empty() {+ tracing::info!("no more call records found");+ break;+ }++ count += records.len();++ sqs_client+ .bulk_send_message_to_search_event_queue(+ records+ .iter()+ .map(|r| {+ sqs_client::search::SearchQueueMessage::CallRecord(CallRecordMessage {+ call_id: r.call_id.to_string(),+ })+ })+ .collect(),+ )+ .await?;+ tracing::info!(%offset, "queued batch");++ offset += limit;+ }++ tracing::info!(total = count, "completed call record backfill");++ Ok(())+}diff --git a/rust/cloud-storage/search_processing_service/src/main.rs b/rust/cloud-storage/search_processing_service/src/main.rsindex db779e720f..787859cda7 100644--- a/rust/cloud-storage/search_processing_service/src/main.rs+++ b/rust/cloud-storage/search_processing_service/src/main.rs@@ -138,6 +138,7 @@ async fn main() -> anyhow::Result<()> {}api::setup_and_serve(ApiContext {+ db,sqs_client: Arc::new(sqs_client),opensearch_client: Arc::new(opensearch_client),internal_auth_key,diff --git a/rust/cloud-storage/search_processing_service/src/process/call.rs b/rust/cloud-storage/search_processing_service/src/process/call.rsnew file mode 100644index 0000000000..a7ec5904d1--- /dev/null+++ b/rust/cloud-storage/search_processing_service/src/process/call.rs@@ -0,0 +1,88 @@+use anyhow::Context;+use opensearch_client::{+ OpensearchClient, date_format::EpochSeconds, upsert::call_record::UpsertCallRecordSegmentArgs,+};+use sqlx::PgPool;+use sqs_client::search::call::{CallRecordMessage, RemoveCallRecord};+use uuid::Uuid;++#[tracing::instrument(skip(opensearch_client, db), err)]+pub async fn process_call_record(+ opensearch_client: &OpensearchClient,+ db: &PgPool,+ message: &CallRecordMessage,+) -> anyhow::Result<()> {+ let call_id: Uuid = message+ .call_id+ .parse()+ .context("failed to parse call_id as UUID")?;++ let Some(payload) =+ macro_db_client::call_record::get::get_call_record_search_payload(db, &call_id).await?+ else {+ tracing::debug!(call_id = %call_id, "call record no longer exists; skipping");+ return Ok(());+ };++ if payload.segments.is_empty() {+ tracing::debug!(call_id = %call_id, "call has no transcript segments to index");+ return Ok(());+ }++ let call_id_s = payload.call_id.to_string();+ let channel_id_s = payload.channel_id.to_string();++ let segments: Vec<UpsertCallRecordSegmentArgs> = payload+ .segments+ .into_iter()+ .map(|seg| {+ let ended_at_seconds = seg+ .ended_at+ .map(|dt| EpochSeconds::new(dt.timestamp()))+ .transpose()?;+ Ok::<_, anyhow::Error>(UpsertCallRecordSegmentArgs {+ call_id: call_id_s.clone(),+ transcript_id: seg.transcript_id.to_string(),+ channel_id: channel_id_s.clone(),+ participant_ids: payload.participant_ids.clone(),+ channel_name: payload.channel_name.clone(),+ speaker_id: seg.speaker_id,+ sequence_num: seg.sequence_num,+ content: seg.content,+ started_at_seconds: EpochSeconds::new(seg.started_at.timestamp())?,+ ended_at_seconds,+ })+ })+ .collect::<Result<Vec<_>, _>>()?;++ let result = opensearch_client+ .bulk_upsert_call_record_segments(&segments)+ .await+ .context("failed to bulk upsert call record segments")?;++ if result.failed > 0 {+ tracing::warn!(+ failed = result.failed,+ errors = ?result.errors,+ call_id = %call_id,+ "some call-record segments failed to upsert"+ );+ }++ Ok(())+}++#[tracing::instrument(skip(opensearch_client), err)]+pub async fn process_remove_call_record(+ opensearch_client: &OpensearchClient,+ message: &RemoveCallRecord,+) -> anyhow::Result<()> {+ if let Some(call_id) = &message.call_id {+ opensearch_client.delete_call_record(call_id).await?;+ } else {+ opensearch_client+ .delete_call_records_by_channel(&message.channel_id)+ .await?;+ }+ Ok(())+}diff --git a/rust/cloud-storage/search_processing_service/src/process/mod.rs b/rust/cloud-storage/search_processing_service/src/process/mod.rsindex 8ffba222a9..d8169cbf5d 100644--- a/rust/cloud-storage/search_processing_service/src/process/mod.rs+++ b/rust/cloud-storage/search_processing_service/src/process/mod.rs@@ -1,3 +1,4 @@+mod call;mod channel;mod chat;pub mod context;@@ -95,6 +96,12 @@ pub async fn process_message(SearchQueueMessage::RemoveChatMessage(message) => {chat::remove_chat_message(&ctx.opensearch_client, &message).await?;}+ SearchQueueMessage::CallRecord(message) => {+ call::process_call_record(&ctx.opensearch_client, &ctx.db, &message).await?;+ }+ SearchQueueMessage::RemoveCallRecord(message) => {+ call::process_remove_call_record(&ctx.opensearch_client, &message).await?;+ }}ctx.worker.cleanup_message(message).await?;diff --git a/rust/cloud-storage/search_service/src/api/search/call_record.rs b/rust/cloud-storage/search_service/src/api/search/call_record.rsnew file mode 100644index 0000000000..6533f41e70--- /dev/null+++ b/rust/cloud-storage/search_service/src/api/search/call_record.rs@@ -0,0 +1,115 @@+use indexmap::IndexMap;+use models_search::call_record::{+ CallRecordMetadata, CallRecordSearchResponseItem, CallRecordSearchResponseItemWithMetadata,+ CallRecordSearchResult,+};+use opensearch_client::search::model::{SearchGotoContent, SearchHit};+use sqlx::types::Uuid;++use crate::api::context::SearchHandlerState;+use crate::api::search::simple::SearchError;++#[tracing::instrument(skip(ctx, results), err)]+pub(in crate::api::search) async fn enrich_call_records(+ ctx: &SearchHandlerState,+ user_id: &str,+ results: Vec<SearchHit>,+) -> Result<Vec<CallRecordSearchResponseItemWithMetadata>, SearchError> {+ let results: Vec<SearchHit> = results+ .into_iter()+ .filter(|r| r.entity_type == models_opensearch::SearchEntityType::CallRecords)+ .collect();++ if results.is_empty() {+ return Ok(vec![]);+ }++ // Dedup — many segments map to the same call.+ let mut seen: std::collections::HashSet<Uuid> = std::collections::HashSet::new();+ let call_ids: Vec<Uuid> = results+ .iter()+ .filter_map(|r| seen.insert(r.entity_id).then_some(r.entity_id))+ .collect();++ let metadata_rows =+ macro_db_client::call_record::get::get_call_records_metadata(&ctx.db, user_id, &call_ids)+ .await+ .map_err(SearchError::InternalError)?;++ let metadata_by_id: std::collections::HashMap<Uuid, CallRecordMetadata> = metadata_rows+ .into_iter()+ .map(|row| {+ (+ row.call_id,+ CallRecordMetadata {+ created_by: row.created_by,+ started_at: row.started_at,+ ended_at: row.ended_at,+ duration_ms: row.duration_ms,+ updated_at: row.ended_at,+ channel_name: row.channel_name,+ attended: row.attended,+ },+ )+ })+ .collect();++ let mut hits_by_call_id: IndexMap<Uuid, Vec<CallRecordSearchResult>> = IndexMap::new();+ let mut call_context: std::collections::HashMap<Uuid, (Uuid, Vec<String>)> =+ std::collections::HashMap::new();++ for hit in results {+ let goto = match hit.goto.clone() {+ Some(SearchGotoContent::CallRecords(goto)) => Some(goto),+ _ => None,+ };++ if let Some(g) = &goto {+ call_context+ .entry(hit.entity_id)+ .or_insert_with(|| (g.channel_id, g.participant_ids.clone()));+ }++ hits_by_call_id+ .entry(hit.entity_id)+ .or_default()+ .push(CallRecordSearchResult {+ transcript_id: goto.as_ref().map(|g| g.transcript_id),+ speaker_id: goto.as_ref().map(|g| g.speaker_id.clone()),+ sequence_num: goto.as_ref().map(|g| g.sequence_num),+ started_at: goto.as_ref().map(|g| g.started_at),+ ended_at: goto.as_ref().and_then(|g| g.ended_at),+ highlight: hit.highlight.into(),+ score: hit.score,+ });+ }++ let result = hits_by_call_id+ .into_iter()+ .map(|(call_id, hits)| {+ let (channel_id, participant_ids) = call_context+ .get(&call_id)+ .cloned()+ .expect("CallRecords hit missing SearchGotoCallRecord");+ let metadata = metadata_by_id.get(&call_id).cloned();++ CallRecordSearchResponseItemWithMetadata {+ extra: CallRecordSearchResponseItem {+ id: call_id,+ name: metadata.as_ref().and_then(|m| m.channel_name.clone()),+ owner_id: metadata+ .as_ref()+ .map(|m| m.created_by.clone())+ .unwrap_or_default(),+ call_id,+ channel_id,+ participant_ids,+ call_search_results: hits,+ },+ metadata,+ }+ })+ .collect();++ Ok(result)+}diff --git a/rust/cloud-storage/search_service/src/api/search/enrich.rs b/rust/cloud-storage/search_service/src/api/search/enrich.rsindex bc2a02b3ee..6ce608c814 100644--- a/rust/cloud-storage/search_service/src/api/search/enrich.rs+++ b/rust/cloud-storage/search_service/src/api/search/enrich.rs@@ -7,8 +7,9 @@ use opensearch_client::search::model::SearchHit;use crate::api::{context::SearchHandlerState,search::{- channel::enrich_channels, chat::enrich_chats, document::enrich_documents,- email::enrich_emails, project::enrich_projects, simple::SearchError,+ call_record::enrich_call_records, channel::enrich_channels, chat::enrich_chats,+ document::enrich_documents, email::enrich_emails, project::enrich_projects,+ simple::SearchError,},};@@ -57,5 +58,12 @@ pub async fn enrich_search_response(.map(UnifiedSearchResponseItem::Project).collect())}+ SearchEntityType::CallRecords => {+ let response = enrich_call_records(ctx, user_id, results).await?;+ Ok(response+ .into_iter()+ .map(UnifiedSearchResponseItem::CallRecord)+ .collect())+ }}}diff --git a/rust/cloud-storage/search_service/src/api/search/mod.rs b/rust/cloud-storage/search_service/src/api/search/mod.rsindex 5c8ad94658..475a08713c 100644--- a/rust/cloud-storage/search_service/src/api/search/mod.rs+++ b/rust/cloud-storage/search_service/src/api/search/mod.rs@@ -2,6 +2,7 @@ use axum::{Router, routing::post};use crate::api::context::SearchHandlerState;+pub(in crate::api) mod call_record;pub(in crate::api) mod channel;pub(in crate::api) mod chat;pub(in crate::api) mod document;diff --git a/rust/cloud-storage/search_service/src/api/search/simple/filter.rs b/rust/cloud-storage/search_service/src/api/search/simple/filter.rsindex 89a6298dce..48ba29b6de 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/filter.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/filter.rs@@ -3,15 +3,16 @@use comms_db_client::model::SimpleMention;use opensearch_client::search::unified::{- UnifiedChannelMessageSearchArgs, UnifiedChatSearchArgs, UnifiedDocumentSearchArgs,- UnifiedEmailSearchArgs,+ UnifiedCallRecordSearchArgs, UnifiedChannelMessageSearchArgs, UnifiedChatSearchArgs,+ UnifiedDocumentSearchArgs, UnifiedEmailSearchArgs,};use crate::api::{context::SearchHandlerState,search::simple::{- SearchError, simple_channel::filter_channels, simple_chat::filter_chats,- simple_document::filter_documents, simple_project::filter_projects,+ SearchError, simple_call_record::filter_calls, simple_channel::filter_channels,+ simple_chat::filter_chats, simple_document::filter_documents,+ simple_project::filter_projects,},};@@ -174,3 +175,29 @@ impl FilterVariantToSearchArgs for item_filters::EmailFilters {}}}++impl FilterVariantToSearchArgs for item_filters::CallFilters {+ type Output = UnifiedCallRecordSearchArgs;++ async fn filter_to_search_args(+ &self,+ ctx: &SearchHandlerState,+ user_id: &str,+ _user_organization_id: Option<i32>,+ should_include: bool,+ ) -> Result<Self::Output, SearchError> {+ if !should_include {+ return Ok(UnifiedCallRecordSearchArgs::default());+ }++ let response = filter_calls(ctx, user_id, self).await?;++ Ok(UnifiedCallRecordSearchArgs {+ call_ids: response.call_ids,+ channel_ids: response.channel_ids,+ speaker_ids: self.speaker_ids.clone(),+ ids_only: true,+ ..Default::default()+ })+ }+}diff --git a/rust/cloud-storage/search_service/src/api/search/simple/mod.rs b/rust/cloud-storage/search_service/src/api/search/simple/mod.rsindex cf3e72fc2f..7b6aec929e 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/mod.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/mod.rs@@ -10,6 +10,7 @@ use name_search::NameSearchError;use opensearch_client::error::OpensearchClientError;pub(in crate::api) mod filter;+pub(in crate::api) mod simple_call_record;pub(in crate::api) mod simple_channel;pub(in crate::api) mod simple_chat;pub(in crate::api) mod simple_document;diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_call_record.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_call_record.rsnew file mode 100644index 0000000000..01d1c90192--- /dev/null+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_call_record.rs@@ -0,0 +1,32 @@+use item_filters::CallFilters;++use crate::api::context::SearchHandlerState;+use crate::api::search::simple::SearchError;++#[derive(Debug)]+pub(in crate::api::search) struct FilterCallResponse {+ pub call_ids: Vec<String>,+ pub channel_ids: Vec<String>,+}++#[tracing::instrument(skip(ctx, filters), err)]+pub(in crate::api::search) async fn filter_calls(+ ctx: &SearchHandlerState,+ user_id: &str,+ filters: &CallFilters,+) -> Result<FilterCallResponse, SearchError> {+ let accessible = macro_db_client::call_record::get::get_accessible_call_ids(+ &ctx.db,+ user_id,+ filters.attended,+ )+ .await+ .map_err(SearchError::InternalError)?;++ let call_ids = accessible.into_iter().map(|id| id.to_string()).collect();++ Ok(FilterCallResponse {+ call_ids,+ channel_ids: filters.channel_ids.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 85a0b75f75..ea2447bf18 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@@ -168,12 +168,14 @@ pub(in crate::api::search) async fn perform_unified_search(let chat_filters = search_filters.chat_filters;let doc_filters = search_filters.document_filters;let project_filters = search_filters.project_filters;+ let call_filters = search_filters.call_filters;let should_include_documents = search_filters.should_include_documents;let should_include_channels = search_filters.should_include_channels;let should_include_chats = search_filters.should_include_chats;let should_include_projects = search_filters.should_include_projects;let should_include_emails = search_filters.should_include_emails;+ let should_include_call_records = search_filters.should_include_call_records;let email_terms = split_search_terms(&terms);// Await all tasks in parallel@@ -183,6 +185,7 @@ pub(in crate::api::search) async fn perform_unified_search(mut filter_chat_response,mut filter_email_response,filter_project_response,+ mut filter_call_record_response,) = tokio::try_join!(doc_filters.filter_to_search_args(ctx,@@ -213,6 +216,12 @@ pub(in crate::api::search) async fn perform_unified_search(user_id.as_ref(),user_organization_id,should_include_projects+ ),+ call_filters.filter_to_search_args(+ ctx,+ user_id.as_ref(),+ user_organization_id,+ should_include_call_records,)).map_err(|e| SearchError::InternalError(anyhow::anyhow!("tokio error: {:?}", e)))?;@@ -223,6 +232,7 @@ pub(in crate::api::search) async fn perform_unified_search(filter_channel_response.terms = terms.clone();filter_chat_response.terms = terms.clone();filter_email_response.terms = email_terms.clone();+ filter_call_record_response.terms = terms.clone();// Clone terms for use in name searcheslet name_search_term = terms[0].clone();@@ -279,12 +289,16 @@ pub(in crate::api::search) async fn perform_unified_search(if should_include_channels && !filter_channel_response.channel_ids.is_empty() {indices.insert(models_opensearch::OpenSearchEntityType::Channels);}+ if should_include_call_records && !filter_call_record_response.call_ids.is_empty() {+ indices.insert(models_opensearch::OpenSearchEntityType::CallRecords);+ }indices},document_search_args: filter_document_response.clone(),email_search_args: filter_email_response.clone(),channel_message_search_args: filter_channel_response,chat_search_args: filter_chat_response.clone(),+ call_record_search_args: filter_call_record_response.clone(),};// Call search functions in parallel for included entity typesdiff --git a/rust/cloud-storage/search_service/src/api/search/unified.rs b/rust/cloud-storage/search_service/src/api/search/unified.rsindex 56871bb562..e6b76fa265 100644--- a/rust/cloud-storage/search_service/src/api/search/unified.rs+++ b/rust/cloud-storage/search_service/src/api/search/unified.rs@@ -67,6 +67,7 @@ pub async fn handler(document,email,project,+ call_record,} = {let _span = tracing::info_span!("split_search_response_by_type").entered();results.into_iter().split_search_response()@@ -78,6 +79,7 @@ pub async fn handler(enriched_channel_results,enriched_project_results,enriched_email_results,+ enriched_call_record_results,) = tokio::try_join!(enrich_search_response(&ctx,@@ -114,6 +116,13 @@ pub async fn handler(models_opensearch::SearchEntityType::Emails,None,),+ enrich_search_response(+ &ctx,+ &user_context.user_id,+ call_record,+ models_opensearch::SearchEntityType::CallRecords,+ None,+ ),).map_err(|e| SearchError::InternalError(anyhow::anyhow!("tokio error: {:?}", e)))?;@@ -127,6 +136,7 @@ pub async fn handler(results.extend(enriched_channel_results);results.extend(enriched_project_results);results.extend(enriched_email_results);+ results.extend(enriched_call_record_results);sort_unified_search_results(results)};diff --git a/rust/cloud-storage/sqs_client/src/search/call.rs b/rust/cloud-storage/sqs_client/src/search/call.rsnew file mode 100644index 0000000000..babce0f8db--- /dev/null+++ b/rust/cloud-storage/sqs_client/src/search/call.rs@@ -0,0 +1,11 @@+#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Debug)]+pub struct CallRecordMessage {+ pub call_id: String,+}++#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Debug)]+pub struct RemoveCallRecord {+ pub channel_id: String,+ /// `None` removes every call record for `channel_id`.+ pub call_id: Option<String>,+}diff --git a/rust/cloud-storage/sqs_client/src/search/mod.rs b/rust/cloud-storage/sqs_client/src/search/mod.rsindex ba3473240d..4a261fbf41 100644--- a/rust/cloud-storage/sqs_client/src/search/mod.rs+++ b/rust/cloud-storage/sqs_client/src/search/mod.rs@@ -1,6 +1,7 @@use crate::{SQS,search::{+ call::{CallRecordMessage, RemoveCallRecord},channel::{ChannelMessageUpdate, RemoveChannelMessage},chat::{ChatMessage, RemoveChatMessage},document::{DocumentId, SearchExtractorMessage},@@ -12,6 +13,7 @@ use aws_sdk_sqs::{self as sqs, types::SendMessageBatchRequestEntry};use futures::StreamExt;use strum::Display;+pub mod call;pub mod channel;pub mod chat;pub mod document;@@ -80,6 +82,9 @@ pub enum SearchQueueMessage {// ChannelChannelMessageUpdate(ChannelMessageUpdate),RemoveChannelMessage(RemoveChannelMessage),+ // Call+ CallRecord(CallRecordMessage),+ RemoveCallRecord(RemoveCallRecord),// UserRemoveUserProfile(String),@@ -109,6 +114,12 @@ impl PrimaryId for SearchQueueMessage {message.message_id.clone().unwrap_or_default())}+ SearchQueueMessage::CallRecord(message) => message.call_id.clone(),+ SearchQueueMessage::RemoveCallRecord(message) => format!(+ "{}{}",+ message.channel_id,+ message.call_id.clone().unwrap_or_default()+ ),SearchQueueMessage::RemoveUserProfile(message) => message.clone(),}@@ -134,6 +145,9 @@ impl SearchQueueMessage {// ChannelsSearchQueueMessage::ChannelMessageUpdate(_) => Operation::ExtractText,SearchQueueMessage::RemoveChannelMessage(_) => Operation::Remove,+ // Calls+ SearchQueueMessage::CallRecord(_) => Operation::ExtractText,+ SearchQueueMessage::RemoveCallRecord(_) => Operation::Remove,// UsersSearchQueueMessage::RemoveUserProfile(_) => Operation::Remove,}