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
perf(channel): make search in channel gooder (#3305)
gbirmancbde8f169139
diff --git a/js/app/packages/channel/Channel/Channel.tsx b/js/app/packages/channel/Channel/Channel.tsxindex 9e3e86b38e..0125624614 100644--- a/js/app/packages/channel/Channel/Channel.tsx+++ b/js/app/packages/channel/Channel/Channel.tsx@@ -316,6 +316,7 @@ export function Channel(props: ChannelProps) {channelId: () => props.channelId,goToMessage,clearSelection,+ isMessageLoaded: (id) => messageIndex.keys.includes(id),});const { messageListScopeId, attachMessageListRef, attachInputRef } =@@ -450,6 +451,7 @@ export function Channel(props: ChannelProps) {channelId={() => props.channelId}isNewestThread={isNewestThread()}getMessageActions={getMessageActions}+ targetThreadId={targetMessageController.activeTargetMessageId()}targetReplyId={targetMessageController.pendingTargetReplyId()}selectedReplyId={targetMessageController.activeTargetMessageReplyId()}onTargetReplyScrolled={(replyId) => {diff --git a/js/app/packages/channel/Channel/create-channel-find-bar.ts b/js/app/packages/channel/Channel/create-channel-find-bar.tsindex bee75f280f..e948bde0f0 100644--- a/js/app/packages/channel/Channel/create-channel-find-bar.ts+++ b/js/app/packages/channel/Channel/create-channel-find-bar.ts@@ -8,6 +8,9 @@ import {isChannelMessageEntity,type WithSearch,} from '@entity';+import { channelMessagesQueryOptions } from '@queries/channel/channel-messages';+import { threadRepliesQueryOptions } from '@queries/channel/thread-replies';+import { queryClient } from '@queries/client';import {useSearchChannelQuery,validateSearchServiceText,@@ -23,11 +26,14 @@ import type { SearchHighlightTermsLookup } from '../Message/context';const FIND_BAR_PAGE_SIZE = 50;const FIND_BAR_PREFETCH_THRESHOLD = 10;+const FIND_BAR_REPLY_PREFETCH_LOOKAHEAD = 2;+const FIND_BAR_MESSAGES_PREFETCH_LOOKAHEAD = 2;type CreateChannelFindBarOptions = {channelId: Accessor<string>;goToMessage: (messageId: string, replyId?: string) => void;clearSelection: () => void;+ isMessageLoaded: (messageId: string) => boolean;};export type ChannelFindBar = FindBarController & {@@ -111,6 +117,61 @@ export function createChannelFindBar(}});+ // Prefetch /replies for the next few reply hits ahead of the cursor.+ // ChannelThread fires the replies query only on mount with `targetReplyId`+ // set, so the very first reply-nav into each thread always pays a round-trip.+ // Warming the cache in advance hides that latency on rapid next/prev.+ // `prefetchQuery` is a no-op when the cached entry is fresh (staleTime is+ // Infinity for replies), so re-runs are cheap.+ createEffect(() => {+ const rs = results();+ const idx = activeIndex();+ if (idx === 0 || rs.length === 0) return;++ const channelId = options.channelId();+ const end = Math.min(+ idx + FIND_BAR_REPLY_PREFETCH_LOOKAHEAD,+ rs.length+ );+ for (let i = idx; i < end; i++) {+ const threadId = rs[i].threadId;+ if (!threadId) continue;+ queryClient.prefetchQuery(+ threadRepliesQueryOptions(channelId, threadId)+ );+ }+ });++ // Prefetch the load-around channel-messages window for the next few hits.+ // When the user navigates to a result that's outside the current message+ // window, tmc switches `loadAroundMessageId` to that id and `/messages?+ // load_around_message_id=…` fetches a 50-row window centered on it. That+ // round-trip is the dominant delay on rapid find-bar navigation through+ // older messages. Skip hits that are already in the loaded window (we'd+ // never actually fire an around-fetch for them) and dedupe so multiple+ // replies to the same parent thread share one prefetch.+ createEffect(() => {+ const rs = results();+ const idx = activeIndex();+ if (idx === 0 || rs.length === 0) return;++ const channelId = options.channelId();+ const end = Math.min(+ idx + FIND_BAR_MESSAGES_PREFETCH_LOOKAHEAD,+ rs.length+ );+ const seen = new Set<string>();+ for (let i = idx; i < end; i++) {+ const aroundId = rs[i].threadId ?? rs[i].messageId;+ if (seen.has(aroundId)) continue;+ seen.add(aroundId);+ if (options.isMessageLoaded(aroundId)) continue;+ queryClient.prefetchInfiniteQuery(+ channelMessagesQueryOptions(channelId, aroundId)+ );+ }+ });+return {results,totalCount,diff --git a/js/app/packages/channel/Message/Content.tsx b/js/app/packages/channel/Message/Content.tsxindex 0d7e2b87f9..cf8af7d50d 100644--- a/js/app/packages/channel/Message/Content.tsx+++ b/js/app/packages/channel/Message/Content.tsx@@ -1,14 +1,11 @@import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { channelTheme } from '@core/component/LexicalMarkdown/theme';-import {- highlightTermsInText,- mergeAdjacentMacroEmTags,-} from '@core/util/searchHighlight';import { isEmojiOnly } from '@core/util/string';import { cn } from '@ui';-import { createMemo, Show } from 'solid-js';+import { createMemo, createSignal, Show } from 'solid-js';import { useMessage, useSearchHighlightTermsLookup } from './context';+import { createSearchHighlightOverlay } from './highlightOverlay';type ContentProps = {class?: string;@@ -19,12 +16,12 @@ export function Content(props: ContentProps) {const bigEmoji = createMemo(() => isEmojiOnly(message().content ?? ''));const termsLookup = useSearchHighlightTermsLookup();- const renderedMarkdown = createMemo(() => {- const raw = message().content ?? '';- const terms = termsLookup?.(message().id);- if (!terms?.length) return raw;- return mergeAdjacentMacroEmTags(highlightTermsInText(raw, [...terms]));- });+ const content = createMemo(() => message().content ?? '');+ const terms = createMemo(() => termsLookup?.(message().id));++ const [markdownRoot, setMarkdownRoot] = createSignal<HTMLDivElement>();++ createSearchHighlightOverlay({ root: markdownRoot, content, terms });return (<Show when={message().content}>@@ -36,9 +33,10 @@ export function Content(props: ContentProps) {)}><StaticMarkdown- markdown={renderedMarkdown()}+ markdown={content()}theme={channelTheme}target="internal"+ rootRef={setMarkdownRoot}/></div></Show>diff --git a/js/app/packages/channel/Message/highlightOverlay.ts b/js/app/packages/channel/Message/highlightOverlay.tsnew file mode 100644index 0000000000..fc4dc27859--- /dev/null+++ b/js/app/packages/channel/Message/highlightOverlay.ts@@ -0,0 +1,35 @@+import {+ applyDomHighlights,+ unwrapDomHighlights,+} from '@core/util/searchHighlight';+import { type Accessor, createEffect, on, onCleanup } from 'solid-js';++/**+ * Mutates the rendered DOM under `root` to wrap term matches in highlight+ * spans. Kept outside any reactive component subtree (e.g. Lexical's+ * StaticMarkdown) so expensive decorator components don't re-mount when+ * the active search term changes.+ *+ * Re-applies when the root remounts (e.g. async citation replacement+ * recreates the markdown div), the source content changes (Solid wipes+ * the wrappers), or terms change.+ */+export function createSearchHighlightOverlay(args: {+ root: Accessor<HTMLElement | undefined>;+ content: Accessor<string>;+ terms: Accessor<readonly string[] | undefined>;+}): void {+ createEffect(+ on([args.root, args.content, args.terms], ([root, _content, terms]) => {+ if (!root) return;+ unwrapDomHighlights(root);+ if (!terms?.length) return;+ applyDomHighlights(root, terms);+ })+ );++ onCleanup(() => {+ const root = args.root();+ if (root) unwrapDomHighlights(root);+ });+}diff --git a/js/app/packages/channel/Thread/ChannelThread.tsx b/js/app/packages/channel/Thread/ChannelThread.tsxindex f4abc6817b..7a69958d3b 100644--- a/js/app/packages/channel/Thread/ChannelThread.tsx+++ b/js/app/packages/channel/Thread/ChannelThread.tsx@@ -1,7 +1,6 @@import { DebugSuspense } from '@channel/DebugSuspense';import { useUserId } from '@core/context/user';import { tryMacroId, useDisplayName } from '@core/user';-import { deferredGate } from '@core/util/debounce';import { MarkMessageNotifications } from '@notifications/components/MarkMessageNotifications';import { useThreadRepliesQuery } from '@queries/channel/thread-replies';import type { ApiThreadReply } from '@service-comms/client';@@ -27,11 +26,10 @@ export function ChannelThread(props: ThreadProps) {const [displayName] = useDisplayName(macroId());const thread = () => props.data().thread;const hasReplies = () => thread().reply_count > 0;- const debouncedFetchRepliesEnabled = deferredGate(hasReplies, 300);- // Targeted reply navigation needs the full reply list immediately so the- // thread can resolve the reply index and complete the scroll.const fetchRepliesEnabled = () =>- !!props.targetReplyId || debouncedFetchRepliesEnabled();+ (!!props.targetReplyId && props.targetThreadId === props.data().id) ||+ props.isExpanded() ||+ (hasReplies() && thread().reply_count > DEFAULT_VISIBLE_REPLY_COUNT);const isSelected = () => props.selectedMessageId?.() === props.data().id;diff --git a/js/app/packages/channel/Thread/types.ts b/js/app/packages/channel/Thread/types.tsindex 3cad6c9427..07f5d202ff 100644--- a/js/app/packages/channel/Thread/types.ts+++ b/js/app/packages/channel/Thread/types.ts@@ -36,6 +36,7 @@ export type ThreadProps = {listMeta?: ChannelMessageListMeta;threadActions?: ThreadActions;messageEditor?: MessageEditor;+ targetThreadId?: string;/** One-shot scroll target. Caller must clear via `onTargetReplyScrolled`. */targetReplyId?: string;onTargetReplyScrolled?: (replyId: string) => void;diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsxindex 45e0461400..8da07794e9 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx@@ -74,6 +74,7 @@ import { DocumentCard as DocumentCardDecorator } from '../decorator/DocumentCardimport { DocumentMention as DocumentMentionDecorator } from '../decorator/DocumentMention';import { Equation as EquationDecorator } from '../decorator/Equation';import { GroupMention as GroupMentionDecorator } from '../decorator/GroupMention';+import { LazyDecorator } from '../decorator/LazyDecorator';import { MarkdownImage as ImageDecorator } from '../decorator/MarkdownImage';import { MarkdownVideo as VideoDecorator } from '../decorator/MarkdownVideo';import { Snapshot as SnapshotDecorator } from '../decorator/Snapshot';@@ -267,18 +268,34 @@ const UserMention: RenderableEntity<UserMentionNode> = {),};+const MentionPlaceholder = () => (+ <span class="pointer-events-none inline-block align-baseline opacity-60">+ <span class="relative top-[0.125em] size-[1em] inline-block mx-1 bg-current/15 rounded-xs" />+ <span class="inline-block w-12 h-[0.9em] align-baseline bg-current/10 rounded-sm" />+ </span>+);+const DocumentMention: RenderableEntity<DocumentMentionNode> = {guard: (node: LexicalNode): node is DocumentMentionNode =>node.__type === 'document-mention',- render: (props) => (- <span class={getTextClassName(props.node, props.theme)}>- {DocumentMentionDecorator({- ...props.node.exportComponentProps(),- key: props.node.getKey(),- theme: props.theme,- })}- </span>- ),+ render: (props) => {+ const componentProps = props.node.exportComponentProps();+ const key = props.node.getKey();+ return (+ <span class={getTextClassName(props.node, props.theme)}>+ <LazyDecorator+ placeholder={<MentionPlaceholder />}+ render={() =>+ DocumentMentionDecorator({+ ...componentProps,+ key,+ theme: props.theme,+ })+ }+ />+ </span>+ );+ },};const ThemeMention: RenderableEntity<ThemeMentionNode> = {@@ -840,6 +857,7 @@ export function StaticMarkdown(props: {return Document({rootNode: $getRoot(),theme: mergedTheme(),+ rootRef: props.rootRef,});});});diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/LazyDecorator.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/LazyDecorator.tsxnew file mode 100644index 0000000000..a865fbc792--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/LazyDecorator.tsx@@ -0,0 +1,78 @@+import {+ createMemo,+ createSignal,+ type JSX,+ onCleanup,+ onMount,+} from 'solid-js';++/**+ * Wraps an expensive decorator in a viewport-gated placeholder. Renders the+ * cheap `placeholder` slot synchronously; calls `render` (instantiating the+ * heavy component) only once the wrapper intersects the viewport, then keeps+ * the upgraded content mounted to avoid flicker on small scrolls.+ * One shared `IntersectionObserver` services all instances in the document.+ */++const OBSERVER_OPTS: IntersectionObserverInit = {+ // Upgrade slightly before scrolling into view so users don't see a flash+ // of placeholder content.+ rootMargin: '400px 0px',+ threshold: 0,+};++const upgradeCallbacks = new WeakMap<Element, () => void>();+let sharedObserver: IntersectionObserver | undefined;++function getSharedObserver(): IntersectionObserver {+ if (sharedObserver) return sharedObserver;+ sharedObserver = new IntersectionObserver((entries) => {+ for (const entry of entries) {+ if (!entry.isIntersecting) continue;+ const cb = upgradeCallbacks.get(entry.target);+ if (cb) cb();+ }+ }, OBSERVER_OPTS);+ return sharedObserver;+}++export function LazyDecorator(props: {+ placeholder: JSX.Element;+ render: () => JSX.Element;+}): JSX.Element {+ const [upgraded, setUpgraded] = createSignal(false);+ let el: HTMLSpanElement | undefined;++ onMount(() => {+ if (!el) return;+ const observer = getSharedObserver();+ const upgrade = () => {+ observer.unobserve(el!);+ upgradeCallbacks.delete(el!);+ setUpgraded(true);+ };+ upgradeCallbacks.set(el, upgrade);+ observer.observe(el);+ });++ onCleanup(() => {+ if (!el) return;+ upgradeCallbacks.delete(el);+ sharedObserver?.unobserve(el);+ });++ const content = createMemo(() =>+ upgraded() ? props.render() : props.placeholder+ );++ return (+ <span+ ref={(r) => {+ el = r;+ }}+ class="inline"+ >+ {content()}+ </span>+ );+}diff --git a/js/app/packages/core/util/searchHighlight.tsx b/js/app/packages/core/util/searchHighlight.tsxindex e097196865..f3d4f627c2 100644--- a/js/app/packages/core/util/searchHighlight.tsx+++ b/js/app/packages/core/util/searchHighlight.tsx@@ -85,14 +85,129 @@ export function mergeAdjacentMacroEmTags(highlightedContent: string): string {return highlightedContent.replace(/<\/macro_em>(\s+)<macro_em>/g, '$1');}+/** Escapes regex special characters in a string. */+export function escapeRegex(s: string): string {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++/**+ * Builds a case-insensitive global RegExp that matches any of the given+ * terms as a single capture group. Returns `undefined` if `terms` is empty.+ */+export function buildTermsPattern(+ terms: readonly string[]+): RegExp | undefined {+ if (terms.length === 0) return undefined;+ return new RegExp(`(${terms.map(escapeRegex).join('|')})`, 'gi');+}+/** 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');+ const pattern = buildTermsPattern(terms);+ if (!pattern) return text;return text.replace(pattern, '<macro_em>$1</macro_em>');}+/**+ * Default attribute used to mark DOM highlight wrappers. The DOM helpers+ * below use this to find and unwrap their own injected spans on the next+ * pass without disturbing other spans in the subtree.+ */+const DOM_HIGHLIGHT_MARKER_ATTR = 'data-search-highlight';+const DOM_HIGHLIGHT_DEFAULT_CLASS = 'md-mark search-match inline';++type DomHighlightOptions = {+ /** CSS classes applied to the injected `<span>` wrapper. */+ className?: string;+ /** Marker attribute name (used to find wrappers on cleanup). */+ markerAttr?: string;+};++/**+ * Removes previously-injected highlight spans from `root` (those carrying+ * the marker attribute). Adjacent text nodes are merged via `normalize()`.+ */+export function unwrapDomHighlights(+ root: HTMLElement,+ options: DomHighlightOptions = {}+): void {+ const markerAttr = options.markerAttr ?? DOM_HIGHLIGHT_MARKER_ATTR;+ const spans = root.querySelectorAll<HTMLElement>(`span[${markerAttr}]`);+ if (spans.length === 0) return;+ spans.forEach((s) => {+ const text = s.ownerDocument.createTextNode(s.textContent ?? '');+ s.parentNode?.replaceChild(text, s);+ });+ root.normalize();+}++/**+ * Walks text nodes under `root` and wraps occurrences of `terms` (case-+ * insensitive) in `<span>` elements carrying the marker attribute and CSS+ * classes. Pure DOM mutation — does not touch any component tree, so it's+ * safe to use when the rendered subtree is expensive to rebuild.+ *+ * Text nodes inside existing highlight wrappers are skipped so re-applying+ * is idempotent when paired with {@link unwrapDomHighlights}.+ */+export function applyDomHighlights(+ root: HTMLElement,+ terms: readonly string[],+ options: DomHighlightOptions = {}+): void {+ const pattern = buildTermsPattern(terms);+ if (!pattern) return;++ const markerAttr = options.markerAttr ?? DOM_HIGHLIGHT_MARKER_ATTR;+ const className = options.className ?? DOM_HIGHLIGHT_DEFAULT_CLASS;++ const targets: Text[] = [];+ const walker = root.ownerDocument.createTreeWalker(+ root,+ NodeFilter.SHOW_TEXT,+ {+ acceptNode(node) {+ const parent = node.parentElement;+ if (parent?.hasAttribute(markerAttr)) {+ return NodeFilter.FILTER_REJECT;+ }+ return NodeFilter.FILTER_ACCEPT;+ },+ }+ );+ while (true) {+ const n = walker.nextNode();+ if (!n) break;+ targets.push(n as Text);+ }++ for (const tn of targets) {+ const text = tn.nodeValue ?? '';+ pattern.lastIndex = 0;+ if (!pattern.test(text)) continue;+ pattern.lastIndex = 0;++ const doc = tn.ownerDocument;+ const frag = doc.createDocumentFragment();+ let lastIdx = 0;+ for (const m of text.matchAll(pattern)) {+ if (m.index > lastIdx) {+ frag.appendChild(doc.createTextNode(text.slice(lastIdx, m.index)));+ }+ const span = doc.createElement('span');+ span.className = className;+ span.setAttribute(markerAttr, '1');+ span.textContent = m[0];+ frag.appendChild(span);+ lastIdx = m.index + m[0].length;+ }+ if (lastIdx < text.length) {+ frag.appendChild(doc.createTextNode(text.slice(lastIdx)));+ }+ tn.parentNode?.replaceChild(frag, tn);+ }+}+/*** Creates a single-line window around the first <macro_em> highlight.* - Collapses newlines and invisible chars into a clean single line