Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(search): make email search response look better (#1647)

gbirman3f0b5ce3ce3b
diff --git a/js/app/packages/app/component/next-soup/search-utils.ts b/js/app/packages/app/component/next-soup/search-utils.ts
index 51fef7fa16..e842a68384 100644
--- a/js/app/packages/app/component/next-soup/search-utils.ts
+++ b/js/app/packages/app/component/next-soup/search-utils.ts
@@ -67,6 +67,7 @@ export const nameFuzzySearchFilter = (
...item,
search: {
nameHighlight: mergeAdjacentMacroEmTags(matchResult.nameHighlight),
+ senderHighlightTerms: null,
contentHitData: null,
source: 'local',
},
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
index 68a4f805a4..20d215a85d 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
@@ -802,10 +802,6 @@ export function StaticMarkdown(props: {
}
});
- const content = createMemo(() => {
- return props.markdown;
- });
-
createEffect(() => {
const editor = currentEditor();
if (!editor) {
@@ -813,7 +809,7 @@ export function StaticMarkdown(props: {
return;
}
- setEditorStateFromMarkdown(editor, content(), props.target);
+ setEditorStateFromMarkdown(editor, props.markdown, props.target);
if (props.singleLine) {
forceSingleLine(editor);
}
@@ -825,7 +821,7 @@ export function StaticMarkdown(props: {
const editor = currentEditor();
// Handle citations without affecting mentions
- replaceCitations(content()).then((content: string) => {
+ replaceCitations(props.markdown).then((content: string) => {
setEditorStateFromMarkdown(editor, content, props.target);
if (props.singleLine) {
forceSingleLine(editor);
diff --git a/js/app/packages/core/component/LexicalMarkdown/theme.ts b/js/app/packages/core/component/LexicalMarkdown/theme.ts
index 4468336157..2d8614bae2 100644
--- a/js/app/packages/core/component/LexicalMarkdown/theme.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/theme.ts
@@ -222,3 +222,8 @@ export const unifiedListMarkdownTheme = createTheme({
// padding right to prevent italics being clipped by overflow properties such as truncation
root: `${theme.root} inline pr-[2px] cursor-default truncate`,
});
+
+export const searchContentHitMarkdownTheme = createTheme({
+ ...unifiedListMarkdownTheme,
+ root: `${theme.root} pr-[2px] cursor-default overflow-x-auto`,
+});
diff --git a/js/app/packages/core/util/searchHighlight.ts b/js/app/packages/core/util/searchHighlight.ts
index 0bd4d40191..c6b534f264 100644
--- a/js/app/packages/core/util/searchHighlight.ts
+++ b/js/app/packages/core/util/searchHighlight.ts
@@ -3,6 +3,25 @@
* that contains <macro_em> tags marking matched terms.
*/
+const INVISIBLE_CHARS_RE =
+ /(?:[\u200B-\u200F\u2028-\u202F\u2060-\u206F\uFEFF\u00AD\u2800-\u28FF]|\u034F)+/g;
+
+/** Collapses newlines, extra whitespace, and invisible Unicode characters into a clean single line. */
+function stripInvisibleChars(text: string): string {
+ return text
+ .replace(/[\r\n]+/g, ' ')
+ .replace(/\s{2,}/g, ' ')
+ .replace(INVISIBLE_CHARS_RE, '')
+ .trim();
+}
+
+/** Returns the visible character count after stripping invisible chars and `<macro_em>` tags. */
+export function visibleLength(content: string): number {
+ return stripInvisibleChars(content)
+ .replace(/<\/?macro_em>/g, '')
+ .trim().length;
+}
+
/**
* Extracts terms from macro_em tags in the highlighted content.
* Returns array of text strings that should be highlighted, preserving order and duplicates.
@@ -63,52 +82,68 @@ export function mergeAdjacentMacroEmTags(highlightedContent: string): string {
return highlightedContent.replace(/<\/macro_em>(\s+)<macro_em>/g, '$1');
}
+/** Wraps each occurrence of the given terms in `<macro_em>` tags (case-insensitive). */
+export function highlightTermsInText(text: string, terms: string[]): string {
+ if (!terms.length) return text;
+ const escaped = terms.map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
+ const pattern = new RegExp(`(${escaped.join('|')})`, 'gi');
+ return text.replace(pattern, '<macro_em>$1</macro_em>');
+}
+
/**
- * Truncate markdown returned from the search service so that the *first*
- * <macro_em> match is visible within a fixed character window.
- *
- * Behavior:
- * - Only the first line containing a <macro_em> tag is considered.
- * - Other <macro_em> tags on the same line are preserved verbatim.
- * - If the match line is not the first line, the result is prefixed with "...".
- * - If the opening <macro_em> tag starts beyond the allowed window,
- * content is trimmed from the front (preferably at a word boundary)
- * until the tag is within the window.
- * - When front-trimming occurs, "..." is prepended.
+ * Creates a single-line window around the first <macro_em> highlight.
+ * - Collapses newlines and invisible chars into a clean single line
+ * - If the highlight is within `chars` of the start, keeps the start
+ * - Otherwise, trims the front to show context before the highlight
+ * - Trims the end to keep total visible length reasonable
*
- * @param text - Markdown source content from search results.
- * @param chars - Maximum visible character window (excluding ellipsis).
- * @returns A truncated string that guarantees visibility of the first match.
+ * @param text - Content with <macro_em> tags
+ * @param chars - Max visible characters to show on each side of the highlight
*/
-export function truncateSearchMatch(text: string, chars: number): string {
- const lines = text.split('\n');
- const macroOpen = '<macro_em>';
-
- const lineIndex = lines.findIndex((l) => l.includes(macroOpen));
- if (lineIndex === -1) {
- return text;
- }
-
- let line = lines[lineIndex];
- let needsEllipsis = lineIndex > 0;
+export function windowSearchMatch(text: string, chars: number = 200): string {
+ let line = stripInvisibleChars(text);
+ const macroOpen = '<macro_em>';
const tagIndex = line.indexOf(macroOpen);
+ if (tagIndex === -1) return line;
- if (tagIndex <= chars) {
- return (needsEllipsis ? '...' : '') + line;
- }
+ const visibleBefore = line
+ .slice(0, tagIndex)
+ .replace(/<\/?macro_em>/g, '').length;
- const targetStart = Math.max(0, tagIndex - chars);
+ // Trim from front if highlight is far from the start
+ if (visibleBefore > chars) {
+ const targetStart = Math.max(0, tagIndex - chars);
+ let cutIndex = targetStart;
+ for (let i = targetStart; i < tagIndex; i++) {
+ if (/\s/.test(line[i])) {
+ cutIndex = i + 1;
+ break;
+ }
+ }
+ line = '...' + line.slice(cutIndex);
+ }
- // prefer trimming at a word boundary
- let cutIndex = targetStart;
- for (let i = targetStart; i < tagIndex; i++) {
- if (/\s/.test(line[i])) {
- cutIndex = i + 1;
- break;
+ // Trim from end to keep total length reasonable
+ const macroClose = '</macro_em>';
+ const lastCloseIndex = line.lastIndexOf(macroClose);
+ if (lastCloseIndex !== -1) {
+ const afterLastTag = lastCloseIndex + macroClose.length;
+ const remainingVisible = line
+ .slice(afterLastTag)
+ .replace(/<\/?macro_em>/g, '')
+ .replace(INVISIBLE_CHARS_RE, '').length;
+ if (remainingVisible > chars) {
+ let endCut = afterLastTag + chars;
+ for (let i = endCut; i < line.length; i++) {
+ if (/\s/.test(line[i])) {
+ endCut = i;
+ break;
+ }
+ }
+ line = line.slice(0, endCut) + '...';
}
}
- line = line.slice(cutIndex);
- return '...' + line;
+ return line;
}
diff --git a/js/app/packages/entity/mocks/mockEntityData.ts b/js/app/packages/entity/mocks/mockEntityData.ts
index 8e8870a13c..d576ac81ac 100644
--- a/js/app/packages/entity/mocks/mockEntityData.ts
+++ b/js/app/packages/entity/mocks/mockEntityData.ts
@@ -505,6 +505,7 @@ export const MOCK_SEARCH_DOCUMENT: WithSearch<DocumentEntity> = {
...MOCK_DOCUMENT_BASIC,
search: {
nameHighlight: 'Meeting **Notes**',
+ senderHighlightTerms: null,
contentHitData: [
{
type: 'md',
@@ -525,6 +526,7 @@ export const MOCK_SEARCH_CHANNEL: WithSearch<ChannelEntity> = {
...MOCK_CHANNEL_PUBLIC,
search: {
nameHighlight: '**general**',
+ senderHighlightTerms: null,
contentHitData: [
{
type: 'channel',
@@ -557,6 +559,7 @@ export const MOCK_SEARCH_EMAIL: WithSearch<EmailEntity> = {
...MOCK_EMAIL_THREAD,
search: {
nameHighlight: '**Design** Review',
+ senderHighlightTerms: null,
contentHitData: [
{
type: 'email',
@@ -589,6 +592,7 @@ export const MOCK_SEARCH_PDF: WithSearch<DocumentEntity> = {
...MOCK_DOCUMENT_PDF,
search: {
nameHighlight: '**Design** Specifications.pdf',
+ senderHighlightTerms: null,
contentHitData: [
{
type: 'pdf',
diff --git a/js/app/packages/entity/src/composed/ListEntity.tsx b/js/app/packages/entity/src/composed/ListEntity.tsx
index cdc42639b1..35891cde88 100644
--- a/js/app/packages/entity/src/composed/ListEntity.tsx
+++ b/js/app/packages/entity/src/composed/ListEntity.tsx
@@ -1,9 +1,12 @@
import type { DateValue } from '@core/util/date';
+import { visibleLength, windowSearchMatch } from '@core/util/searchHighlight';
import { Entity } from '../entity';
import {
isChannelEntity,
isEmailEntity,
isProjectContainedEntity,
+ type ChannelEntity,
+ type EmailEntity,
type ProjectEntity,
type EntityData,
isTaskEntity,
@@ -36,6 +39,24 @@ import { mergeRefs } from '@solid-primitives/refs';
const hasSearchContentHits = (entity: EntityData) =>
isSearchEntity(entity) && !!entity.search.contentHitData?.length;
+const getBestContentHitContent = (entity: EntityData) => {
+ if (!isSearchEntity(entity)) return undefined;
+ const hits = entity.search.contentHitData;
+ if (!hits?.length) return undefined;
+ if (hits.length === 1) return hits[0].content;
+
+ let bestIdx = 0;
+ let bestLen = visibleLength(hits[0].content);
+ for (let i = 1; i < hits.length; i++) {
+ const len = visibleLength(hits[i].content);
+ if (len > bestLen) {
+ bestLen = len;
+ bestIdx = i;
+ }
+ }
+ return hits[bestIdx].content;
+};
+
interface ListEntityProps {
entity: WithNotification<EntityData>;
onClick?: (event: MouseEvent) => void;
@@ -72,6 +93,71 @@ interface LayoutProps {
) => void;
}
+function EmailIdentity(props: { entity: EmailEntity }) {
+ return (
+ <>
+ <Show
+ when={props.entity.isDraft}
+ fallback={
+ <Show when={props.entity.hasIcsAttachment}>
+ <InviteBadge />
+ </Show>
+ }
+ >
+ <DraftBadge />
+ </Show>
+ <span class="truncate">
+ <Entity.EmailParticipants entity={props.entity} />
+ </span>
+ </>
+ );
+}
+
+function EmailSnippet(props: {
+ entity: EmailEntity;
+ showContentHits: boolean;
+}) {
+ return (
+ <Show
+ when={props.showContentHits && getBestContentHitContent(props.entity)}
+ fallback={props.entity.snippet}
+ >
+ {(content) => (
+ <StaticMarkdown
+ markdown={windowSearchMatch(content())}
+ theme={unifiedListMarkdownTheme}
+ singleLine
+ />
+ )}
+ </Show>
+ );
+}
+
+function ChannelMessage(props: {
+ message: NonNullable<ChannelEntity['latestMessage']>;
+}) {
+ const hasContent = () => Boolean(props.message.content?.trim());
+ return (
+ <>
+ <span class="font-semibold truncate min-w-min max-w-1/3">
+ <DisplayName id={props.message.senderId} format="firstName" />
+ </span>
+ <span class="text-ink/50 font-medium truncate inline-flex items-center shrink">
+ <Show
+ when={hasContent()}
+ fallback={<span class="italic">Attached Items</span>}
+ >
+ <StaticMarkdown
+ theme={unifiedListMarkdownTheme}
+ markdown={props.message.content}
+ singleLine
+ />
+ </Show>
+ </span>
+ </>
+ );
+}
+
function NarrowLayout(props: LayoutProps) {
return (
<Entity.Layout
@@ -108,23 +194,7 @@ function NarrowLayout(props: LayoutProps) {
</div>
<Switch>
<Match when={isEmailEntity(props.entity) && props.entity}>
- {(entity) => (
- <>
- <Show
- when={entity().isDraft}
- fallback={
- <Show when={entity().hasIcsAttachment}>
- <InviteBadge />
- </Show>
- }
- >
- <DraftBadge />
- </Show>
- <span class="truncate">
- <Entity.EmailParticipants entity={entity()} />
- </span>
- </>
- )}
+ {(entity) => <EmailIdentity entity={entity()} />}
</Match>
<Match when={props.entity}>
{(entity) => <Entity.Title entity={entity()} />}
@@ -147,8 +217,7 @@ function NarrowLayout(props: LayoutProps) {
<Show
when={
(isEmailEntity(props.entity) || isChannelEntity(props.entity)) &&
- !props.hasNotifications &&
- !props.showContentHits
+ !props.hasNotifications
}
>
<Entity.Slot placement="body" class="flex flex-col gap-1 pb-3 -mt-1">
@@ -161,48 +230,25 @@ function NarrowLayout(props: LayoutProps) {
<Entity.Title entity={entity()} />
</span>
</div>
- <div class="text-ink/50 font-medium w-full truncate">
- <span class="truncate">{entity().snippet}</span>
+ <div class="text-ink/50 font-medium w-full truncate inline-flex items-center">
+ <EmailSnippet
+ entity={entity()}
+ showContentHits={props.showContentHits}
+ />
</div>
</>
)}
</Match>
<Match when={isChannelEntity(props.entity) && props.entity}>
- {(entity) => {
- return (
- <Show when={entity().latestMessage}>
- {(msg) => {
- console.log({ message: msg() });
- const hasContent = () => Boolean(msg().content?.trim());
-
- return (
- <div class="flex items-center gap-2 w-full truncate">
- <span class="font-semibold truncate min-w-min max-w-1/3">
- <DisplayName
- id={msg().senderId}
- format="firstName"
- />
- </span>
- <span class="text-ink/50 font-medium truncate inline-flex items-center shrink">
- <Show
- when={hasContent()}
- fallback={
- <span class="italic">Attached Items</span>
- }
- >
- <StaticMarkdown
- theme={unifiedListMarkdownTheme}
- markdown={msg().content}
- singleLine
- />
- </Show>
- </span>
- </div>
- );
- }}
- </Show>
- );
- }}
+ {(entity) => (
+ <Show when={entity().latestMessage}>
+ {(msg) => (
+ <div class="flex items-center gap-2 w-full truncate">
+ <ChannelMessage message={msg()} />
+ </div>
+ )}
+ </Show>
+ )}
</Match>
</Switch>
</Entity.Slot>
@@ -254,41 +300,18 @@ function WideLayout(props: LayoutProps) {
<Match when={isEmailEntity(props.entity) && props.entity}>
{(entity) => (
<>
- <Show
- when={!props.showContentHits}
- fallback={
- <>
- <span class="truncate">
- <Entity.Title entity={entity()} />
- </span>
- <span class="text-ink/50 font-medium truncate flex-1">
- {entity().snippet}
- </span>
- </>
- }
- >
- <span class="w-(--title-width) truncate shrink-0 flex gap-2">
- <Show
- when={entity().isDraft}
- fallback={
- <Show when={entity().hasIcsAttachment}>
- <InviteBadge />
- </Show>
- }
- >
- <DraftBadge />
- </Show>
- <span class="truncate">
- <Entity.EmailParticipants entity={entity()} />
- </span>
- </span>
- <span class="truncate">
- <Entity.Title entity={entity()} />
- </span>
- <span class="text-ink/50 font-medium truncate flex-1">
- {entity().snippet}
- </span>
- </Show>
+ <span class="w-(--title-width) truncate shrink-0 flex gap-2">
+ <EmailIdentity entity={entity()} />
+ </span>
+ <span class="truncate">
+ <Entity.Title entity={entity()} />
+ </span>
+ <span class="text-ink/50 font-medium truncate flex-1 inline-flex items-center">
+ <EmailSnippet
+ entity={entity()}
+ showContentHits={props.showContentHits}
+ />
+ </span>
</>
)}
</Match>
@@ -299,28 +322,7 @@ function WideLayout(props: LayoutProps) {
<Entity.Title entity={entity()} />
</span>
<Show when={!props.hasNotifications && entity().latestMessage}>
- {(msg) => {
- const hasContent = () => Boolean(msg().content?.trim());
- return (
- <>
- <DisplayName id={msg().senderId} format="firstName" />
- <span class="text-ink/50 font-medium truncate inline-flex shrink items-center">
- <Show
- when={hasContent()}
- fallback={
- <span class="italic">Attached Items</span>
- }
- >
- <StaticMarkdown
- theme={unifiedListMarkdownTheme}
- markdown={msg().content}
- singleLine
- />
- </Show>
- </span>
- </>
- );
- }}
+ {(msg) => <ChannelMessage message={msg()} />}
</Show>
</>
)}
@@ -439,8 +441,10 @@ export function ListEntity(props: ListEntityProps) {
</Show>
<Show when={showContentHits()}>
- <div class="flex gap-2 w-full h-full items-center text-sm px-2 pb-1 -mt-2 min-w-0 overflow-hidden">
- <div class={cn('min-w-0 flex-1 truncate ml-4 @lg/entity:ml-6')}>
+ <div class="flex gap-2 w-full h-full items-center text-sm px-2 pb-1 -mt-2 min-w-0">
+ <div
+ class={cn('min-w-0 flex-1 overflow-hidden ml-4 @lg/entity:ml-6')}
+ >
<Entity.Search.ContentHits
entity={props.entity}
onClick={props.onContentHitClick}
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.tsx
index b627d0c7c1..d43ec29874 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
@@ -29,7 +29,7 @@ export function SearchContentHitRow(props: SearchContentHitRowProps) {
onClick={handleClick}
role="button"
>
- <div class="flex flex-col gap-3">
+ <div class="flex flex-col gap-3 min-w-0">
<Show when={props.hit.type === 'channel' || props.hit.type === 'email'}>
<div class="flex items-center gap-1">
<Show when={senderId()}>
diff --git a/js/app/packages/entity/src/extractors-search/search-content.tsx b/js/app/packages/entity/src/extractors-search/search-content.tsx
index e1e02276f1..314a174908 100644
--- a/js/app/packages/entity/src/extractors-search/search-content.tsx
+++ b/js/app/packages/entity/src/extractors-search/search-content.tsx
@@ -1,6 +1,9 @@
import { Show } from 'solid-js';
import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
-import { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme';
+import {
+ searchContentHitMarkdownTheme,
+ unifiedListMarkdownTheme,
+} from '@core/component/LexicalMarkdown/theme';
import type { ContentHitData } from '../types/search';
interface SearchContentProps {
@@ -24,8 +27,12 @@ export function SearchContent(props: SearchContentProps) {
{(trimmedContent) => (
<StaticMarkdown
markdown={trimmedContent()}
- theme={unifiedListMarkdownTheme}
- singleLine={props.singleLine ?? true}
+ theme={
+ props.singleLine
+ ? unifiedListMarkdownTheme
+ : searchContentHitMarkdownTheme
+ }
+ singleLine={props.singleLine}
/>
)}
</Show>
diff --git a/js/app/packages/entity/src/extractors/entity-email-participants.tsx b/js/app/packages/entity/src/extractors/entity-email-participants.tsx
index 56328ac30c..cf4c5d590a 100644
--- a/js/app/packages/entity/src/extractors/entity-email-participants.tsx
+++ b/js/app/packages/entity/src/extractors/entity-email-participants.tsx
@@ -1,6 +1,14 @@
import { useEmail } from '@core/context/user';
import { emailToMacroId, useDisplayName } from '@core/user';
+import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme';
+import {
+ mergeAdjacentMacroEmTags,
+ highlightTermsInText,
+} from '@core/util/searchHighlight';
import type { EmailEntity, EmailThreadParticipants } from '../types/entity';
+import { isSearchEntity } from '../types/search';
+import { Show } from 'solid-js';
/** Checks if a value is likely an email address */
export function isLikelyEmail(value?: string): boolean {
@@ -88,11 +96,7 @@ export function formatDisplayNames(names: string[]): string | undefined {
return `${firstNames[0]} .. ${firstNames[firstNames.length - 2]}, ${firstNames[firstNames.length - 1]}`;
}
-/**
- * Get a nicely formatted list of participants from an email entity.
- * @param props
- * @returns
- */
+/** Get a nicely formatted list of participants from an email entity. */
export function EntityEmailParticipants(props: { entity: EmailEntity }) {
const userEmail = useEmail();
const fetchDisplayName = (email: string) =>
@@ -108,5 +112,25 @@ export function EntityEmailParticipants(props: { entity: EmailEntity }) {
);
};
- return <>{displayNames()}</>;
+ const highlighted = () => {
+ if (!isSearchEntity(props.entity)) return undefined;
+ const terms = props.entity.search.senderHighlightTerms;
+ if (!terms?.length) return undefined;
+ const names = displayNames();
+ if (!names) return undefined;
+ const result = mergeAdjacentMacroEmTags(highlightTermsInText(names, terms));
+ return result !== names ? result : undefined;
+ };
+
+ return (
+ <Show when={highlighted()} fallback={displayNames()}>
+ {(md) => (
+ <StaticMarkdown
+ markdown={md()}
+ theme={unifiedListMarkdownTheme}
+ singleLine
+ />
+ )}
+ </Show>
+ );
}
diff --git a/js/app/packages/entity/src/types/search.ts b/js/app/packages/entity/src/types/search.ts
index c8cd08bf82..d1024cd9c9 100644
--- a/js/app/packages/entity/src/types/search.ts
+++ b/js/app/packages/entity/src/types/search.ts
@@ -80,6 +80,7 @@ export type ContentHitData =
export type SearchData = {
nameHighlight: string | null;
+ senderHighlightTerms: string[] | null;
contentHitData: ContentHitData[] | null;
source: 'local' | 'service';
};
diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.ts
index 8845741dc1..0647fcc981 100644
--- a/js/app/packages/queries/soup/transform-utils.ts
+++ b/js/app/packages/queries/soup/transform-utils.ts
@@ -5,7 +5,6 @@ import {
import { useChannelsContext } from '@core/context/channels';
import { emailToId } from '@core/user';
import {
- truncateSearchMatch,
mergeAdjacentMacroEmTags,
extractSearchSnippet,
extractSearchTerms,
@@ -37,8 +36,6 @@ import type {
} from '@service-storage/generated/schemas';
import type { UseQueryResult } from '@tanstack/solid-query';
-const SEARCH_MATCH_LENGTH = 60;
-
type InnerSearchResult =
| DocumentSearchResult
| EmailSearchResult
@@ -66,10 +63,7 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {
return contents.map((content) => ({
type: 'channel' as const,
id: r.message_id!,
- content: truncateSearchMatch(
- mergeAdjacentMacroEmTags(content),
- SEARCH_MATCH_LENGTH
- ),
+ content: mergeAdjacentMacroEmTags(content),
senderId: r.sender_id!,
sentAt: r.created_at!,
location: {
@@ -88,10 +82,7 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {
const mergedContent = mergeAdjacentMacroEmTags(content);
return {
type: 'pdf' as const,
- content: truncateSearchMatch(
- mergeAdjacentMacroEmTags(content),
- SEARCH_MATCH_LENGTH
- ),
+ content: mergeAdjacentMacroEmTags(content),
location: {
type: 'pdf' as const,
searchPage: Number(r.node_id),
@@ -112,10 +103,7 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {
const contents = r.highlight.content ?? [];
return contents.map((content) => ({
type: 'md' as const,
- content: truncateSearchMatch(
- mergeAdjacentMacroEmTags(content),
- SEARCH_MATCH_LENGTH
- ),
+ content: mergeAdjacentMacroEmTags(content),
location: { type: 'md' as const, nodeId: r.node_id! },
}));
});
@@ -126,10 +114,7 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {
const contents = r.highlight.content ?? [];
return contents.map((content) => ({
type: 'email' as const,
- content: truncateSearchMatch(
- mergeAdjacentMacroEmTags(content),
- SEARCH_MATCH_LENGTH
- ),
+ content: mergeAdjacentMacroEmTags(content),
sender: r.pretty_sender!,
senderId: emailToId(r.sender),
sentAt: r.sent_at!,
@@ -145,10 +130,7 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {
contentHitData = data.results.flatMap((r) => {
const contents = r.highlight.content ?? [];
return contents.map((content) => ({
- content: truncateSearchMatch(
- mergeAdjacentMacroEmTags(content),
- SEARCH_MATCH_LENGTH
- ),
+ content: mergeAdjacentMacroEmTags(content),
location: undefined,
}));
});
@@ -157,10 +139,23 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {
const nameHighlight = data.results.at(0)?.highlight.name ?? null;
+ let senderHighlightTerms: string[] | null = null;
+ if (data.type === 'email') {
+ const terms = [
+ ...new Set(
+ data.results
+ .flatMap((r) => (r.highlight.sender ?? '').toLowerCase().split(/\s+/))
+ .filter(Boolean)
+ ),
+ ];
+ senderHighlightTerms = terms.length > 0 ? terms : null;
+ }
+
return {
nameHighlight: nameHighlight
? mergeAdjacentMacroEmTags(nameHighlight)
: null,
+ senderHighlightTerms,
contentHitData: contentHitData.length > 0 ? contentHitData : null,
source: 'service' as const,
};
diff --git a/rust/cloud-storage/opensearch_client/src/search/builder.rs b/rust/cloud-storage/opensearch_client/src/search/builder.rs
index 9cb3ddbd5d..cb29f3b29e 100644
--- a/rust/cloud-storage/opensearch_client/src/search/builder.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/builder.rs
@@ -336,7 +336,7 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {
.highlight_type("plain")
.pre_tags(vec![MacroEm::Open.to_string()])
.post_tags(vec![MacroEm::Close.to_string()])
- .number_of_fragments(1),
+ .number_of_fragments(0),
),
};
diff --git a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs b/rust/cloud-storage/opensearch_client/src/search/builder/test.rs
index cae80e2714..a4a8279a4a 100644
--- a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/builder/test.rs
@@ -144,7 +144,7 @@ fn test_build_search_request() -> anyhow::Result<()> {
"fields": {
"content": {
"type": "plain",
- "number_of_fragments": 1,
+ "number_of_fragments": 0,
"pre_tags": ["<macro_em>"],
"post_tags": ["</macro_em>"],
},
@@ -212,7 +212,7 @@ fn test_build_search_request() -> anyhow::Result<()> {
"fields": {
"content": {
"type": "plain",
- "number_of_fragments": 1,
+ "number_of_fragments": 0,
"pre_tags": ["<macro_em>"],
"post_tags": ["</macro_em>"],
},
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rs
index b0b6fd5a97..922ed01634 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs
@@ -411,14 +411,13 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchReques
search_request_builder.add_sort(sort);
}
- // Build highlight
let highlight = Highlight::new().require_field_match(true).field(
"content",
HighlightField::new()
.highlight_type("plain")
.pre_tags(vec![MacroEm::Open.to_string()])
.post_tags(vec![MacroEm::Close.to_string()])
- .number_of_fragments(500),
+ .number_of_fragments(0),
);
search_request_builder.highlight(highlight);
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
index 7a48d48a6e..f77f94a639 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
@@ -473,7 +473,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
"highlight": {
"fields": {
"content": {
- "number_of_fragments": 500,
+ "number_of_fragments": 0,
"post_tags": ["</macro_em>"],
"pre_tags": ["<macro_em>"],
"type": "plain"
@@ -875,7 +875,7 @@ fn test_build_unified_search_request_single_index() -> anyhow::Result<()> {
"highlight": {
"fields": {
"content": {
- "number_of_fragments": 500,
+ "number_of_fragments": 0,
"post_tags": ["</macro_em>"],
"pre_tags": ["<macro_em>"],
"type": "plain"