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): improve keyword windowing (#1977)
gbirmanba0717d11b19
diff --git a/js/app/packages/core/util/searchHighlight.test.ts b/js/app/packages/core/util/searchHighlight.test.tsnew file mode 100644index 0000000000..0327193717--- /dev/null+++ b/js/app/packages/core/util/searchHighlight.test.ts@@ -0,0 +1,192 @@+import { describe, expect, it } from 'vitest';+import {+ visibleLength,+ extractSearchTerms,+ extractSearchSnippet,+ mergeAdjacentMacroEmTags,+ highlightTermsInText,+ windowSearchMatch,+ parseSearchHighlightSegments,+} from './searchHighlight';++describe('visibleLength', () => {+ it('counts visible characters excluding macro_em tags', () => {+ expect(visibleLength('hello')).toBe(5);+ expect(visibleLength('<macro_em>hello</macro_em>')).toBe(5);+ expect(visibleLength('the <macro_em>quick</macro_em> brown')).toBe(15);+ });++ it('strips invisible unicode characters', () => {+ expect(visibleLength('hello\u200Bworld')).toBe(10);+ expect(visibleLength('\u200B\u200F')).toBe(0);+ });++ it('collapses whitespace and newlines', () => {+ expect(visibleLength('hello\n\n world')).toBe(11);+ });+});++describe('extractSearchTerms', () => {+ it('extracts terms from macro_em tags', () => {+ expect(+ extractSearchTerms(+ 'The <macro_em>quick</macro_em> brown <macro_em>fox</macro_em>'+ )+ ).toEqual(['quick', 'fox']);+ });++ it('returns empty array when no tags', () => {+ expect(extractSearchTerms('no highlights here')).toEqual([]);+ });++ it('handles adjacent tags', () => {+ expect(+ extractSearchTerms(+ '<macro_em>hello</macro_em> <macro_em>world</macro_em>'+ )+ ).toEqual(['hello', 'world']);+ });++ it('trims whitespace inside tags', () => {+ expect(extractSearchTerms('<macro_em> padded </macro_em>')).toEqual([+ 'padded',+ ]);+ });+});++describe('extractSearchSnippet', () => {+ it('removes macro_em tags and normalizes whitespace', () => {+ expect(+ extractSearchSnippet('The <macro_em>quick</macro_em>\n brown fox')+ ).toBe('The quick brown fox');+ });++ it('returns plain text unchanged', () => {+ expect(extractSearchSnippet('hello world')).toBe('hello world');+ });++ it('handles empty string', () => {+ expect(extractSearchSnippet('')).toBe('');+ });+});++describe('mergeAdjacentMacroEmTags', () => {+ it('merges adjacent tags separated by whitespace', () => {+ expect(+ mergeAdjacentMacroEmTags(+ 'The <macro_em>quick</macro_em> <macro_em>brown</macro_em> fox'+ )+ ).toBe('The <macro_em>quick brown</macro_em> fox');+ });++ it('does not merge tags separated by non-whitespace', () => {+ expect(+ mergeAdjacentMacroEmTags(+ '<macro_em>Hello</macro_em>, <macro_em>world</macro_em>'+ )+ ).toBe('<macro_em>Hello</macro_em>, <macro_em>world</macro_em>');+ });++ it('merges multiple adjacent tags', () => {+ expect(+ mergeAdjacentMacroEmTags(+ '<macro_em>a</macro_em> <macro_em>b</macro_em> <macro_em>c</macro_em>'+ )+ ).toBe('<macro_em>a b c</macro_em>');+ });++ it('returns text without tags unchanged', () => {+ expect(mergeAdjacentMacroEmTags('no tags here')).toBe('no tags here');+ });+});++describe('highlightTermsInText', () => {+ it('wraps matching terms in macro_em tags', () => {+ expect(highlightTermsInText('hello world', ['hello'])).toBe(+ '<macro_em>hello</macro_em> world'+ );+ });++ it('is case-insensitive', () => {+ expect(highlightTermsInText('Hello World', ['hello'])).toBe(+ '<macro_em>Hello</macro_em> World'+ );+ });++ it('highlights multiple terms', () => {+ expect(highlightTermsInText('the quick brown fox', ['quick', 'fox'])).toBe(+ 'the <macro_em>quick</macro_em> brown <macro_em>fox</macro_em>'+ );+ });++ it('returns text unchanged when no terms', () => {+ expect(highlightTermsInText('hello', [])).toBe('hello');+ });++ it('escapes regex special characters in terms', () => {+ expect(highlightTermsInText('price is $10.00', ['$10.00'])).toBe(+ 'price is <macro_em>$10.00</macro_em>'+ );+ });+});++describe('windowSearchMatch', () => {+ it('returns full text when highlight is near the start', () => {+ expect(windowSearchMatch('<macro_em>hello</macro_em> world', 50)).toBe(+ '<macro_em>hello</macro_em> world'+ );+ });++ it('trims front when highlight is far from start', () => {+ const longPrefix = 'a '.repeat(50);+ const text = `${longPrefix}<macro_em>match</macro_em> end`;+ const result = windowSearchMatch(text, 10);+ expect(result.length).toBeLessThan(text.length);+ expect(result).toContain('<macro_em>match</macro_em>');+ });++ it('trims end when text after highlight is long', () => {+ const longSuffix = ' b'.repeat(50);+ const text = `<macro_em>match</macro_em>${longSuffix}`;+ const result = windowSearchMatch(text, 10);+ expect(result.length).toBeLessThan(text.length);+ expect(result).toContain('<macro_em>match</macro_em>');+ });++ it('returns text as-is when no macro_em tag present', () => {+ expect(windowSearchMatch('no highlight here', 20)).toBe(+ 'no highlight here'+ );+ });+});++describe('parseSearchHighlightSegments', () => {+ it('parses mixed content into segments', () => {+ expect(+ parseSearchHighlightSegments(+ 'The <macro_em>quick</macro_em> brown <macro_em>fox</macro_em>'+ )+ ).toEqual([+ { text: 'The ', highlight: false },+ { text: 'quick', highlight: true },+ { text: ' brown ', highlight: false },+ { text: 'fox', highlight: true },+ ]);+ });++ it('handles text with no highlights', () => {+ expect(parseSearchHighlightSegments('plain text')).toEqual([+ { text: 'plain text', highlight: false },+ ]);+ });++ it('handles fully highlighted text', () => {+ expect(parseSearchHighlightSegments('<macro_em>all</macro_em>')).toEqual([+ { text: 'all', highlight: true },+ ]);+ });++ it('handles empty string', () => {+ expect(parseSearchHighlightSegments('')).toEqual([]);+ });+});diff --git a/js/app/packages/core/util/searchHighlight.tsx b/js/app/packages/core/util/searchHighlight.tsxindex 4a1f06dd9d..3a1a7251bb 100644--- a/js/app/packages/core/util/searchHighlight.tsx+++ b/js/app/packages/core/util/searchHighlight.tsx@@ -2,7 +2,7 @@* Utilities for extracting information from search highlight content* that contains <macro_em> tags marking matched terms.*/-import { Index } from 'solid-js';+import { For } from 'solid-js';const INVISIBLE_CHARS_RE =/(?:[\u200B-\u200F\u2028-\u202F\u2060-\u206F\uFEFF\u00AD\u2800-\u28FF]|\u034F)+/g;@@ -103,7 +103,7 @@ export function highlightTermsInText(text: string, terms: string[]): string {* @param text - Content with <macro_em> tags* @param chars - Max visible characters to show on each side of the highlight*/-export function windowSearchMatch(text: string, chars: number = 200): string {+export function windowSearchMatch(text: string, chars: number): string {let line = stripInvisibleChars(text);const macroOpen = '<macro_em>';@@ -124,7 +124,7 @@ export function windowSearchMatch(text: string, chars: number = 200): string {break;}}- line = '...' + line.slice(cutIndex);+ line = line.slice(cutIndex);}// Trim from end to keep total length reasonable@@ -144,7 +144,7 @@ export function windowSearchMatch(text: string, chars: number = 200): string {break;}}- line = line.slice(0, endCut) + '...';+ line = line.slice(0, endCut);}}@@ -175,15 +175,15 @@ export function parseSearchHighlightSegments(export function HighlightRender(props: { text: string }) {return (<span>- <Index each={parseSearchHighlightSegments(props.text)}>+ <For each={parseSearchHighlightSegments(props.text)}>{(segment) =>- segment().highlight ? (- <span class="md-mark search-match">{segment().text}</span>+ segment.highlight ? (+ <span class="md-mark search-match">{segment.text}</span>) : (- segment().text+ segment.text)}- </Index>+ </For></span>);}diff --git a/js/app/packages/entity/src/composed/ListEntity.tsx b/js/app/packages/entity/src/composed/ListEntity.tsxindex 047f891191..f71fde7897 100644--- a/js/app/packages/entity/src/composed/ListEntity.tsx+++ b/js/app/packages/entity/src/composed/ListEntity.tsx@@ -56,6 +56,7 @@ import {} from '../utils/notification';import { useSplitPanel } from '@app/component/split-layout/layoutUtils';import { mergeRefs } from '@solid-primitives/refs';+import { createElementSize } from '@solid-primitives/resize-observer';const WIDE_BREAKPOINT = 512; // @lg container query = 32rem@@ -111,6 +112,20 @@ const getBestContentHitContent = (entity: EntityData) => {return hits[bestIdx].content;};+function useCharacterCount(ref: Accessor<HTMLElement | undefined>) {+ const size = createElementSize(ref);+ const [chars, setChars] = createSignal(200);+ const CHAR_WIDTH_PX = 6; // this is an approximation for text-sm++ createEffect(() => {+ if (!size.width) return;+ const charCount = Math.round(size.width / CHAR_WIDTH_PX / 2);+ setChars(charCount);+ });++ return chars;+}+interface ListEntityProps {entity: WithNotification<EntityData>;onClick?: (event: MouseEvent) => void;@@ -171,13 +186,16 @@ function EmailIdentity(props: { entity: EmailEntity }) {function EmailSnippet(props: {entity: EmailEntity;showContentHits: boolean;+ chars: number;}) {return (<Showwhen={props.showContentHits && getBestContentHitContent(props.entity)}fallback={props.entity.snippet}>- {(content) => <HighlightRender text={windowSearchMatch(content())} />}+ {(content) => (+ <HighlightRender text={windowSearchMatch(content(), props.chars)} />+ )}</Show>);}@@ -208,6 +226,11 @@ function ChannelMessage(props: {}function NarrowLayout(props: LayoutProps) {+ const [emailSnippetContainerRef, setEmailSnippetContainerRef] = createSignal<+ HTMLElement | undefined+ >();+ const chars = useCharacterCount(emailSnippetContainerRef);+return (<Entity.Layoutclass="w-full gap-x-2 items-center text-sm pl-0 px-2 grid"@@ -279,10 +302,14 @@ function NarrowLayout(props: LayoutProps) {<Entity.Title entity={entity()} /></span></div>- <div class="text-ink/50 font-medium w-full truncate inline-flex items-center">+ <div+ ref={setEmailSnippetContainerRef}+ class="text-ink/50 font-medium w-full truncate inline-flex items-center"+ ><EmailSnippetentity={entity()}showContentHits={props.showContentHits}+ chars={chars()}/></div></>@@ -307,6 +334,11 @@ function NarrowLayout(props: LayoutProps) {}function WideLayout(props: LayoutProps) {+ const [emailSnippetContainerRef, setEmailSnippetContainerRef] = createSignal<+ HTMLElement | undefined+ >();+ const chars = useCharacterCount(emailSnippetContainerRef);+return (<Entity.Layoutclass={cn(@@ -354,10 +386,14 @@ function WideLayout(props: LayoutProps) {<span class="truncate"><Entity.Title entity={entity()} /></span>- <span class="text-ink/50 font-medium truncate flex-1 inline-flex items-center">+ <span+ ref={setEmailSnippetContainerRef}+ class="text-ink/50 font-medium truncate flex-1 inline-flex items-center"+ ><EmailSnippetentity={entity()}showContentHits={props.showContentHits}+ chars={chars()}/></span></>diff --git a/rust/cloud-storage/opensearch_client/src/search/model.rs b/rust/cloud-storage/opensearch_client/src/search/model/mod.rssimilarity index 80%rename from rust/cloud-storage/opensearch_client/src/search/model.rsrename to rust/cloud-storage/opensearch_client/src/search/model/mod.rsindex bb3ed36c0a..18d01dc879 100644--- a/rust/cloud-storage/opensearch_client/src/search/model.rs+++ b/rust/cloud-storage/opensearch_client/src/search/model/mod.rs@@ -1,3 +1,6 @@+#[cfg(test)]+mod test;+use std::{collections::HashMap, fmt::Display};use chrono::{DateTime, Utc};@@ -36,9 +39,10 @@ pub(crate) fn exclude_source_content(query: &mut serde_json::Value) {}}-const MAX_VISIBLE_FRAGMENT_CHARS: usize = 500;+const MAX_VISIBLE_FRAGMENT_CHARS: usize = 1000;const OPEN_TAG: &str = "<macro_em>";const CLOSE_TAG: &str = "</macro_em>";+const CHARS_BEFORE_HIGHLIGHT: usize = 200;fn normalize_highlight_fragment(fragment: &str) -> String {let stripped: String = fragment@@ -70,7 +74,74 @@ fn normalize_highlight_fragment(fragment: &str) -> String {.collect();let trimmed = normalized.trim();- truncate_preserving_tags(trimmed, MAX_VISIBLE_FRAGMENT_CHARS)+ window_around_highlight(trimmed, MAX_VISIBLE_FRAGMENT_CHARS)+}++/// Returns a window of `max_chars` visible characters around the first+/// `<macro_em>` highlight tag. If the highlight is near the start, the window+/// starts from the beginning. Otherwise, the front is trimmed (on a word+/// boundary) to keep the highlight visible. If no highlight tag is found,+/// truncates from the start.+fn window_around_highlight(s: &str, max_chars: usize) -> String {+ let tag_byte_pos = match s.find(OPEN_TAG) {+ Some(pos) => pos,+ None => return truncate_preserving_tags(s, max_chars),+ };++ let visible_before_tag = s[..tag_byte_pos]+ .replace(CLOSE_TAG, "")+ .replace(OPEN_TAG, "")+ .chars()+ .count();++ if visible_before_tag <= CHARS_BEFORE_HIGHLIGHT {+ return truncate_preserving_tags(s, max_chars);+ }++ let target_visible_skip = visible_before_tag.saturating_sub(CHARS_BEFORE_HIGHLIGHT);+ let prefix = &s[..tag_byte_pos];+ let no_tags = prefix.replace(OPEN_TAG, "").replace(CLOSE_TAG, "");+ let skip_byte_len: usize = no_tags+ .chars()+ .take(target_visible_skip)+ .map(|c| c.len_utf8())+ .sum();++ let cut_point = find_tag_aware_byte_offset(prefix, skip_byte_len);++ let after_cut = &s[cut_point..];+ let word_break = after_cut+ .find(|c: char| c.is_whitespace())+ .map(|i| i + 1)+ .unwrap_or(0);++ let windowed = &after_cut[word_break..];+ let truncated = truncate_preserving_tags(windowed, max_chars);+ format!("...{truncated}")+}++/// Maps a visible-char byte length to the actual byte offset in text that may+/// contain `<macro_em>` / `</macro_em>` tags (skipping tag bytes).+fn find_tag_aware_byte_offset(s: &str, visible_byte_len: usize) -> usize {+ let mut visible_bytes = 0;+ let mut byte_offset = 0;+ while byte_offset < s.len() {+ if s[byte_offset..].starts_with(OPEN_TAG) {+ byte_offset += OPEN_TAG.len();+ continue;+ }+ if s[byte_offset..].starts_with(CLOSE_TAG) {+ byte_offset += CLOSE_TAG.len();+ continue;+ }+ if visible_bytes >= visible_byte_len {+ break;+ }+ let c = s[byte_offset..].chars().next().unwrap();+ visible_bytes += c.len_utf8();+ byte_offset += c.len_utf8();+ }+ byte_offset}/// Truncates a highlight fragment to `max_chars` visible characters (excludingdiff --git a/rust/cloud-storage/opensearch_client/src/search/model/test.rs b/rust/cloud-storage/opensearch_client/src/search/model/test.rsnew file mode 100644index 0000000000..fb664f1912--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/search/model/test.rs@@ -0,0 +1,150 @@+use super::*;++#[test]+fn truncate_preserving_tags_no_tags() {+ let result = truncate_preserving_tags("hello world", 5);+ assert_eq!(result, "hello...");+}++#[test]+fn truncate_preserving_tags_within_limit() {+ let result = truncate_preserving_tags("hello", 10);+ assert_eq!(result, "hello");+}++#[test]+fn truncate_preserving_tags_with_highlight() {+ let result = truncate_preserving_tags("say <macro_em>hello</macro_em> world", 20);+ assert_eq!(result, "say <macro_em>hello</macro_em> world");+}++#[test]+fn truncate_preserving_tags_cuts_after_highlight() {+ let result = truncate_preserving_tags("say <macro_em>hello</macro_em> world foo bar", 12);+ assert_eq!(result, "say <macro_em>hello</macro_em> wo...");+}++#[test]+fn truncate_preserving_tags_closes_open_tag() {+ let result = truncate_preserving_tags("<macro_em>hello world</macro_em>", 7);+ assert_eq!(result, "<macro_em>hello w</macro_em>...");+}++#[test]+fn truncate_preserving_tags_excludes_tags_from_count() {+ let input = "a<macro_em>b</macro_em>c";+ let result = truncate_preserving_tags(input, 3);+ assert_eq!(result, "a<macro_em>b</macro_em>c");+}++#[test]+fn window_highlight_near_start() {+ let input = "say <macro_em>hello</macro_em> world";+ let result = window_around_highlight(input, 300);+ assert_eq!(result, "say <macro_em>hello</macro_em> world");+}++#[test]+fn window_highlight_far_from_start() {+ let padding = "x".repeat(300);+ let input = format!("{padding} say <macro_em>hello</macro_em> world end");+ let result = window_around_highlight(&input, 1000);+ assert!(result.starts_with("..."));+ assert!(result.contains("<macro_em>hello</macro_em>"));+ let before_tag = result.find("<macro_em>").unwrap();+ let visible_before: usize = result[..before_tag]+ .replace(OPEN_TAG, "")+ .replace(CLOSE_TAG, "")+ .chars()+ .count();+ assert!(+ visible_before <= CHARS_BEFORE_HIGHLIGHT + 10,+ "expected <= {} chars before highlight, got {}",+ CHARS_BEFORE_HIGHLIGHT + 10,+ visible_before+ );+}++#[test]+fn window_no_highlight_tag() {+ let input = "just some text without any highlight tags at all";+ let result = window_around_highlight(input, 20);+ assert_eq!(result, "just some text witho...");+}++#[test]+fn window_trims_on_word_boundary() {+ let padding = "word ".repeat(100);+ let input = format!("{padding}<macro_em>match</macro_em> end");+ let result = window_around_highlight(&input, 1000);+ assert!(result.starts_with("..."));+ let after_ellipsis = &result[3..];+ assert!(+ !after_ellipsis.starts_with(' '),+ "should trim to word boundary, got: {after_ellipsis}"+ );+}++#[test]+fn normalize_strips_invisible_and_collapses_whitespace() {+ let input = "hello\n\n world\u{200B}foo";+ let result = normalize_highlight_fragment(input);+ assert_eq!(result, "hello worldfoo");+}++#[test]+fn normalize_preserves_highlight_tags() {+ let input = "say <macro_em>hello</macro_em> world";+ let result = normalize_highlight_fragment(input);+ assert_eq!(result, "say <macro_em>hello</macro_em> world");+}++#[test]+fn normalize_windows_when_highlight_is_far() {+ let padding = "a ".repeat(200);+ let input = format!("{padding}<macro_em>match</macro_em> end");+ let result = normalize_highlight_fragment(&input);+ assert!(result.contains("<macro_em>match</macro_em>"));+ assert!(result.starts_with("..."));+}++#[test]+fn find_tag_aware_byte_offset_skips_tags() {+ let s = "ab<macro_em>cd</macro_em>ef";+ let offset = find_tag_aware_byte_offset(s, 4);+ let remaining = &s[offset..];+ assert_eq!(remaining.replace(OPEN_TAG, "").replace(CLOSE_TAG, ""), "ef");+}++#[test]+fn find_tag_aware_byte_offset_handles_no_tags() {+ let s = "abcdef";+ let offset = find_tag_aware_byte_offset(s, 3);+ assert_eq!(&s[offset..], "def");+}++#[test]+fn find_tag_aware_byte_offset_handles_utf8() {+ let s = "café";+ let offset = find_tag_aware_byte_offset(s, "caf".len());+ assert_eq!(&s[offset..], "é");+}++#[test]+fn window_real_world_email_fragment() {+ let input = "Hi Gabriel, We often need to copy email to other tools — our notes, todo list, or Slack. In Gmail and Outlook, this is error prone and tedious. In Superhuman Mail, it is accurate and instantaneous: Hit Cmd+C (Mac) or Ctrl+C (Windows) to copy the current message. Hit it again to copy the conversation. Hit Cmd+V (Mac) or Ctrl+V (Windows) to paste wherever you want. You can even paste straight into Superhuman Mail! No selecting, no dragging, no fuss. I'd love to hear what you think: please reply and say <macro_em>hello</macro_em> :) Speak soon, Rahul";+ let result = window_around_highlight(input, MAX_VISIBLE_FRAGMENT_CHARS);+ assert!(result.contains("<macro_em>hello</macro_em>"));+ let tag_pos = result.find("<macro_em>").unwrap();+ let visible_before: usize = result[..tag_pos]+ .replace(OPEN_TAG, "")+ .replace(CLOSE_TAG, "")+ .chars()+ .count();+ assert!(+ visible_before <= CHARS_BEFORE_HIGHLIGHT + 10,+ "highlight should be within first ~{} chars, but was at {}",+ CHARS_BEFORE_HIGHLIGHT,+ visible_before+ );+}