Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(desktop): render chat search highlights (R1-M2)

Josué33c074a6ce43
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index bcd0e9ab4..b221f82a2 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -24,6 +24,7 @@ import { DESKTOP_ROUTES, SIDEBAR_COLLAPSED_KEY } from '@constants/navigation'
import { THEME_STORAGE_KEY } from '@constants/theme'
import { useAgentChatActionsValue } from '@hooks/useAgentChatActionsValue'
import { useAppController } from '@hooks/useAppController'
+import type { ChatLocalMatch } from '@lib/chatLocalSearch'
import {
activeChatViewTab,
addBlankChatViewTab,
@@ -268,6 +269,10 @@ export function App() {
const [composerFocusRequestId, setComposerFocusRequestId] = React.useState(0)
const [globalSearchFocusRequestId, setGlobalSearchFocusRequestId] = React.useState(0)
const [chatLocalSearchOpen, setChatLocalSearchOpen] = React.useState(false)
+ const [chatLocalSearchState, setChatLocalSearchState] = React.useState<{
+ query: string
+ currentMatch: ChatLocalMatch | null
+ }>({ query: '', currentMatch: null })
const [sandboxLocalSearchRequestId, setSandboxLocalSearchRequestId] = React.useState(0)
const [commandPaletteOpen, setCommandPaletteOpen] = React.useState(false)
const [commandPaletteReturnToSandbox, setCommandPaletteReturnToSandbox] = React.useState(false)
@@ -340,6 +345,7 @@ export function App() {
const closeChatLocalSearch = React.useCallback((restoreFocus = true) => {
setChatLocalSearchOpen(false)
+ setChatLocalSearchState({ query: '', currentMatch: null })
if (!restoreFocus) return
const previous = chatLocalSearchPreviousFocusRef.current
requestAnimationFrame(() => {
@@ -347,6 +353,19 @@ export function App() {
})
}, [])
+ const handleChatLocalSearchStateChange = React.useCallback(
+ (query: string, currentMatch: ChatLocalMatch | null) => {
+ setChatLocalSearchState(previous =>
+ previous.query === query &&
+ previous.currentMatch?.messageId === currentMatch?.messageId &&
+ previous.currentMatch?.occurrence === currentMatch?.occurrence
+ ? previous
+ : { query, currentMatch }
+ )
+ },
+ []
+ )
+
const handleSelectChatAgentWithTabs = React.useCallback(
(
agentName: string,
@@ -1525,6 +1544,8 @@ export function App() {
handleLoadOlderMessages: vm.handleLoadOlderMessages,
activityByMessageId: vm.activityByMessageId,
progressByMessageId: vm.progressByMessageId,
+ localSearchQuery: chatLocalSearchOpen ? chatLocalSearchState.query : '',
+ localSearchCurrentMatch: chatLocalSearchOpen ? chatLocalSearchState.currentMatch : null,
}),
[
vm.activeChatId,
@@ -1536,6 +1557,8 @@ export function App() {
vm.handleLoadOlderMessages,
vm.activityByMessageId,
vm.progressByMessageId,
+ chatLocalSearchOpen,
+ chatLocalSearchState,
]
)
@@ -1700,6 +1723,7 @@ export function App() {
<ChatLocalSearch
messages={vm.activeMessages}
onClose={closeChatLocalSearch}
+ onSearchStateChange={handleChatLocalSearchStateChange}
/>
) : null}
<ChatPage scrollContainerRef={contentPanelRef} />
diff --git a/desktop-app/ui/src/components/ChatLocalSearch/ChatLocalSearch.test.tsx b/desktop-app/ui/src/components/ChatLocalSearch/ChatLocalSearch.test.tsx
index cc3b5936a..47cb9bc47 100644
--- a/desktop-app/ui/src/components/ChatLocalSearch/ChatLocalSearch.test.tsx
+++ b/desktop-app/ui/src/components/ChatLocalSearch/ChatLocalSearch.test.tsx
@@ -30,6 +30,7 @@ describe('ChatLocalSearch', () => {
second.id = chatMessageDomId('two')
document.body.append(second)
const onClose = vi.fn()
+ const onSearchStateChange = vi.fn()
render(
<ChatLocalSearch
messages={[
@@ -37,17 +38,30 @@ describe('ChatLocalSearch', () => {
{ id: 'two', role: 'assistant', content: 'needle twice needle', timestamp: 2 },
]}
onClose={onClose}
+ onSearchStateChange={onSearchStateChange}
/>
)
const input = screen.getByRole('textbox', { name: 'Find in current chat' })
fireEvent.change(input, { target: { value: 'NEEDLE' } })
expect(screen.getByRole('status').textContent).toBe('1/3')
+ expect(onSearchStateChange).toHaveBeenLastCalledWith('NEEDLE', {
+ messageId: 'one',
+ occurrence: 0,
+ })
fireEvent.keyDown(input, { key: 'Enter' })
expect(screen.getByRole('status').textContent).toBe('2/3')
+ expect(onSearchStateChange).toHaveBeenLastCalledWith('NEEDLE', {
+ messageId: 'two',
+ occurrence: 0,
+ })
fireEvent.keyDown(input, { key: 'Enter', shiftKey: true })
expect(screen.getByRole('status').textContent).toBe('1/3')
fireEvent.keyDown(input, { key: 'Enter', shiftKey: true })
expect(screen.getByRole('status').textContent).toBe('3/3')
+ expect(onSearchStateChange).toHaveBeenLastCalledWith('NEEDLE', {
+ messageId: 'two',
+ occurrence: 1,
+ })
fireEvent.keyDown(input, { key: 'Escape' })
expect(onClose).toHaveBeenCalledOnce()
expect(loadSessionMessages).not.toHaveBeenCalled()
diff --git a/desktop-app/ui/src/components/ChatLocalSearch/index.tsx b/desktop-app/ui/src/components/ChatLocalSearch/index.tsx
index 68f34f7c7..b7320da95 100644
--- a/desktop-app/ui/src/components/ChatLocalSearch/index.tsx
+++ b/desktop-app/ui/src/components/ChatLocalSearch/index.tsx
@@ -1,13 +1,9 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { Button, TextInput } from '@components/Common'
-import {
- chatMessageDomId,
- findLoadedChatMessageMatches,
- wrapMatchIndex,
-} from '@lib/chatLocalSearch'
+import { findLoadedChatMessageMatches, wrapMatchIndex } from '@lib/chatLocalSearch'
import type { ChatLocalSearchProps } from './types'
-export function ChatLocalSearch({ messages, onClose }: ChatLocalSearchProps) {
+export function ChatLocalSearch({ messages, onClose, onSearchStateChange }: ChatLocalSearchProps) {
const [query, setQuery] = useState('')
const [currentIndex, setCurrentIndex] = useState(0)
const inputRef = useRef<HTMLInputElement | null>(null)
@@ -23,14 +19,13 @@ export function ChatLocalSearch({ messages, onClose }: ChatLocalSearchProps) {
}, [matches.length])
useEffect(() => {
- const previous = document.querySelector<HTMLElement>('[data-current-search-match="true"]')
- previous?.removeAttribute('data-current-search-match')
- if (!currentMatch) return undefined
- const target = document.getElementById(chatMessageDomId(currentMatch.messageId))
- target?.setAttribute('data-current-search-match', 'true')
- target?.scrollIntoView?.({ block: 'center' })
- return () => target?.removeAttribute('data-current-search-match')
- }, [currentMatch])
+ onSearchStateChange(query, currentMatch)
+ if (!currentMatch) return
+ requestAnimationFrame(() => {
+ const target = document.querySelector<HTMLElement>('[data-current-search-match="true"]')
+ target?.scrollIntoView?.({ block: 'center' })
+ })
+ }, [currentMatch, onSearchStateChange, query])
const move = (delta: 1 | -1) => {
setCurrentIndex(index => wrapMatchIndex(index, matches.length, delta))
diff --git a/desktop-app/ui/src/components/ChatLocalSearch/types.ts b/desktop-app/ui/src/components/ChatLocalSearch/types.ts
index 449d9527b..7d9d72285 100644
--- a/desktop-app/ui/src/components/ChatLocalSearch/types.ts
+++ b/desktop-app/ui/src/components/ChatLocalSearch/types.ts
@@ -1,6 +1,8 @@
+import type { ChatLocalMatch } from '@lib/chatLocalSearch'
import type { AgentChatMessage } from '@/uiTypes'
export type ChatLocalSearchProps = {
messages: AgentChatMessage[]
onClose: () => void
+ onSearchStateChange: (query: string, currentMatch: ChatLocalMatch | null) => void
}
diff --git a/desktop-app/ui/src/components/agents/ChatThread.tsx b/desktop-app/ui/src/components/agents/ChatThread.tsx
index e1061da4d..a82a08016 100644
--- a/desktop-app/ui/src/components/agents/ChatThread.tsx
+++ b/desktop-app/ui/src/components/agents/ChatThread.tsx
@@ -33,7 +33,11 @@ import {
} from '@constants/agents'
import { HTML_PREVIEW_INLINE_MAX_BYTES } from '@constants/htmlPreview'
import type { ChatMessageAttachment } from '../../../../src/types'
-import { chatMessageDomId } from '../../lib/chatLocalSearch'
+import {
+ chatMessageDomId,
+ createChatSearchRehypePlugin,
+ highlightChatText,
+} from '../../lib/chatLocalSearch'
import {
getChatMessageAttachmentTypeLabel,
parseChatMessageDisplay,
@@ -229,6 +233,8 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C
activeChatId,
activityByMessageId,
progressByMessageId,
+ localSearchQuery,
+ localSearchCurrentMatch,
} = useChatThreadStateContext()
const {
chatList,
@@ -568,6 +574,10 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C
const parsedUserMessage =
message.role === 'user' ? parseChatMessageDisplay(message.content) : null
const displayContent = parsedUserMessage?.content ?? message.content
+ const activeSearchOccurrence =
+ localSearchCurrentMatch?.messageId === message.id
+ ? localSearchCurrentMatch.occurrence
+ : null
const displayAttachments =
message.role === 'user'
? message.attachments && message.attachments.length
@@ -629,9 +639,13 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C
: ''}
</div>
<div className="error-bubble-message">
- {message.content.length > 180
- ? `${message.content.slice(0, 177)}...`
- : message.content}
+ {highlightChatText(
+ localSearchQuery || message.content.length <= 180
+ ? message.content
+ : `${message.content.slice(0, 177)}...`,
+ localSearchQuery,
+ activeSearchOccurrence
+ )}
</div>
<details className="error-bubble-details">
<summary>Details</summary>
@@ -650,10 +664,24 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C
/>
)}
{isJson ? (
- <pre className="message-block json-content">{displayContent}</pre>
+ <pre className="message-block json-content">
+ {highlightChatText(
+ displayContent,
+ localSearchQuery,
+ activeSearchOccurrence
+ )}
+ </pre>
) : message.role === 'assistant' ? (
<div className="message-block markdown-content">
- <ReactMarkdown remarkPlugins={[remarkGfm]}>
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm]}
+ rehypePlugins={[
+ createChatSearchRehypePlugin(
+ localSearchQuery,
+ activeSearchOccurrence
+ ),
+ ]}
+ >
{displayContent}
</ReactMarkdown>
{selectedAgent && !hasResponseFileAttachment && (
@@ -669,7 +697,13 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C
) : null}
</div>
) : displayContent ? (
- <p className="message-block">{displayContent}</p>
+ <p className="message-block">
+ {highlightChatText(
+ displayContent,
+ localSearchQuery,
+ activeSearchOccurrence
+ )}
+ </p>
) : null}
<MessageAttachmentList attachments={displayAttachments} />
</>
diff --git a/desktop-app/ui/src/components/agents/__tests__/AgentWorkspace.chatScroll.test.tsx b/desktop-app/ui/src/components/agents/__tests__/AgentWorkspace.chatScroll.test.tsx
index bc3ca335d..da2a75717 100644
--- a/desktop-app/ui/src/components/agents/__tests__/AgentWorkspace.chatScroll.test.tsx
+++ b/desktop-app/ui/src/components/agents/__tests__/AgentWorkspace.chatScroll.test.tsx
@@ -183,6 +183,8 @@ function WorkspaceHarness({
handleLoadOlderMessages: vi.fn(),
activityByMessageId: {},
progressByMessageId: {},
+ localSearchQuery: '',
+ localSearchCurrentMatch: null,
}}
>
<ChatActionsProvider
diff --git a/desktop-app/ui/src/components/agents/__tests__/chatThread.toolSteps.test.tsx b/desktop-app/ui/src/components/agents/__tests__/chatThread.toolSteps.test.tsx
index f1b7619c3..e01d14dac 100644
--- a/desktop-app/ui/src/components/agents/__tests__/chatThread.toolSteps.test.tsx
+++ b/desktop-app/ui/src/components/agents/__tests__/chatThread.toolSteps.test.tsx
@@ -8,7 +8,6 @@
* - live progress absent → render from `message.toolSteps`
* - neither → render nothing
*/
-import type { ReactNode } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
@@ -38,6 +37,8 @@ let threadStateValue: {
hasOlderMessages: boolean
olderMessagesLoading: boolean
handleLoadOlderMessages: ReturnType<typeof vi.fn>
+ localSearchQuery: string
+ localSearchCurrentMatch: { messageId: string; occurrence: number } | null
}
vi.mock('@contexts/NavigationContext', () => ({ useNavigationContext: () => navValue }))
@@ -58,10 +59,6 @@ vi.mock('../InFlightAssistantPlaceholder', () => ({ InFlightAssistantPlaceholder
vi.mock('../NudgeArea', () => ({ NudgeArea: () => null }))
vi.mock('../ChatStateBadge', () => ({ ChatStateBadge: () => null }))
vi.mock('@components/MessageArtifactActions', () => ({ MessageArtifactActions: () => null }))
-vi.mock('react-markdown', () => ({
- default: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
-}))
-vi.mock('remark-gfm', () => ({ default: () => undefined }))
const actEnvGlobal = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
actEnvGlobal.IS_REACT_ACT_ENVIRONMENT = true
@@ -103,9 +100,54 @@ function setThreadState(
hasOlderMessages: options.hasOlderMessages ?? false,
olderMessagesLoading: options.olderMessagesLoading ?? false,
handleLoadOlderMessages: vi.fn().mockResolvedValue(undefined),
+ localSearchQuery: '',
+ localSearchCurrentMatch: null,
}
}
+describe('ChatThread local-search highlighting', () => {
+ it('renders every plain and Markdown match and distinguishes the selected occurrence', () => {
+ setThreadState([
+ {
+ role: 'user',
+ items: [{ ...userMsg, content: 'Needle then needle' }],
+ },
+ {
+ role: 'assistant',
+ items: [
+ {
+ id: 'turn-1-assistant',
+ role: 'assistant',
+ content: 'A **needle** in a [needle link](https://example.com).',
+ timestamp: 2,
+ },
+ ],
+ },
+ ])
+ threadStateValue.localSearchQuery = 'needle'
+ threadStateValue.localSearchCurrentMatch = {
+ messageId: 'turn-1-assistant',
+ occurrence: 1,
+ }
+
+ const { rerender } = render(<ChatThread />)
+
+ expect(document.querySelectorAll('.chat-search-match')).toHaveLength(4)
+ const active = screen.getByTestId('chat-search-current-match')
+ expect(active.textContent).toBe('needle')
+ expect(active.closest('a')?.getAttribute('href')).toBe('https://example.com')
+
+ threadStateValue.localSearchCurrentMatch = { messageId: 'turn-1-user', occurrence: 1 }
+ rerender(<ChatThread />)
+ expect(screen.getByTestId('chat-search-current-match').textContent).toBe('needle')
+
+ threadStateValue.localSearchQuery = 'missing'
+ threadStateValue.localSearchCurrentMatch = null
+ rerender(<ChatThread />)
+ expect(document.querySelector('.chat-search-match')).toBeNull()
+ })
+})
+
describe('ChatThread tool-steps fallback (#582)', () => {
it('renders assistant response-file attachments with a direct download action', () => {
const assistant: AgentChatMessage = {
diff --git a/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts b/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts
index 13be252eb..bedb85d5e 100644
--- a/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts
+++ b/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts
@@ -1,4 +1,5 @@
import type { ReactNode } from 'react'
+import type { ChatLocalMatch } from '../../lib/chatLocalSearch'
import type { AgentChatMessage, AgentMessageActivity, TaskProgress } from '../../uiTypes'
/**
@@ -17,6 +18,8 @@ export interface ChatThreadStateContextValue {
handleLoadOlderMessages: () => Promise<void>
activityByMessageId: Record<string, AgentMessageActivity>
progressByMessageId: Record<string, TaskProgress>
+ localSearchQuery: string
+ localSearchCurrentMatch: ChatLocalMatch | null
}
export interface ChatThreadStateProviderProps {
diff --git a/desktop-app/ui/src/lib/chatLocalSearch.ts b/desktop-app/ui/src/lib/chatLocalSearch.ts
index d92374ac3..02be16fee 100644
--- a/desktop-app/ui/src/lib/chatLocalSearch.ts
+++ b/desktop-app/ui/src/lib/chatLocalSearch.ts
@@ -1,3 +1,4 @@
+import { type ReactNode, createElement } from 'react'
import type { AgentChatMessage } from '../uiTypes'
import { parseChatMessageDisplay } from './chatMessageAttachments'
@@ -40,3 +41,94 @@ export function wrapMatchIndex(index: number, total: number, delta: 1 | -1): num
if (total <= 0) return 0
return (index + delta + total) % total
}
+
+type SearchTextPart = { text: string; occurrence: number | null }
+
+function splitSearchText(value: string, query: string, occurrenceStart = 0): SearchTextPart[] {
+ const needle = query.trim().toLocaleLowerCase()
+ if (!needle) return [{ text: value, occurrence: null }]
+ const lowerValue = value.toLocaleLowerCase()
+ const parts: SearchTextPart[] = []
+ let offset = 0
+ let occurrence = occurrenceStart
+ while (offset <= lowerValue.length - needle.length) {
+ const index = lowerValue.indexOf(needle, offset)
+ if (index < 0) break
+ if (index > offset) parts.push({ text: value.slice(offset, index), occurrence: null })
+ parts.push({ text: value.slice(index, index + needle.length), occurrence })
+ occurrence += 1
+ offset = index + needle.length
+ }
+ if (offset < value.length) parts.push({ text: value.slice(offset), occurrence: null })
+ return parts.length ? parts : [{ text: value, occurrence: null }]
+}
+
+function searchMarkProperties(occurrence: number, activeOccurrence: number | null) {
+ const active = occurrence === activeOccurrence
+ return {
+ className: active ? 'chat-search-match chat-search-match--active' : 'chat-search-match',
+ 'data-testid': active ? 'chat-search-current-match' : 'chat-search-match',
+ ...(active ? { 'data-current-search-match': 'true' } : {}),
+ }
+}
+
+export function highlightChatText(
+ value: string,
+ query: string,
+ activeOccurrence: number | null
+): ReactNode {
+ return splitSearchText(value, query).map((part, index) =>
+ part.occurrence === null
+ ? part.text
+ : createElement(
+ 'mark',
+ {
+ key: `${part.occurrence}-${index}`,
+ ...searchMarkProperties(part.occurrence, activeOccurrence),
+ },
+ part.text
+ )
+ )
+}
+
+type HastNode = {
+ type: string
+ value?: string
+ tagName?: string
+ properties?: Record<string, unknown>
+ children?: HastNode[]
+}
+
+/** Declaratively marks rendered Markdown text nodes without parsing or injecting raw HTML. */
+export function createChatSearchRehypePlugin(query: string, activeOccurrence: number | null) {
+ return () => (tree: HastNode) => {
+ let occurrence = 0
+ const visit = (node: HastNode) => {
+ if (!node.children) return
+ const nextChildren: HastNode[] = []
+ for (const child of node.children) {
+ if (child.type !== 'text' || typeof child.value !== 'string') {
+ visit(child)
+ nextChildren.push(child)
+ continue
+ }
+ const parts = splitSearchText(child.value, query, occurrence)
+ for (const part of parts) {
+ if (part.occurrence === null) {
+ if (part.text) nextChildren.push({ type: 'text', value: part.text })
+ continue
+ }
+ occurrence = part.occurrence + 1
+ nextChildren.push({
+ type: 'element',
+ tagName: 'mark',
+ properties: searchMarkProperties(part.occurrence, activeOccurrence),
+ children: [{ type: 'text', value: part.text }],
+ })
+ }
+ }
+ node.children = nextChildren
+ }
+ visit(tree)
+ }
+}
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index b14336b72..852cec55c 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -14967,6 +14967,14 @@ pre {
text-align: center;
}
-.chat-bubble[data-current-search-match='true'] {
+.chat-search-match {
+ background: rgba(var(--warning-rgb), 0.3);
+ border-radius: 2px;
+ color: inherit;
+ padding: 0 1px;
+}
+
+.chat-search-match--active {
+ background: rgba(var(--warning-rgb), 0.62);
box-shadow: 0 0 0 2px rgba(var(--focus-rgb), 0.9);
}