Skip to content

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

TypeScript

fix(desktop): r1-m8 derive chat search from Markdown semantics

Josué20c0a8fcdadd
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 5ea20ca63..0e9303446 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -11,12 +11,16 @@
"dependencies": {
"@clerum/desktop-app-links": "file:../packages/desktop-app-links",
"@tanstack/react-query": "5.100.10",
+ "hast-util-to-jsx-runtime": "^2.3.6",
"js-yaml": "^4.1.1",
"keytar": "^7.9.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-markdown": "^10.1.0",
- "remark-gfm": "^4.0.1"
+ "remark-gfm": "^4.0.1",
+ "remark-parse": "^11.0.0",
+ "remark-rehype": "^11.1.2",
+ "unified": "^11.0.5"
},
"devDependencies": {
"@electron-forge/cli": "^7.11.1",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index aeb68307b..4b32ae2c9 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -45,12 +45,16 @@
"dependencies": {
"@clerum/desktop-app-links": "file:../packages/desktop-app-links",
"@tanstack/react-query": "5.100.10",
+ "hast-util-to-jsx-runtime": "^2.3.6",
"js-yaml": "^4.1.1",
"keytar": "^7.9.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-markdown": "^10.1.0",
- "remark-gfm": "^4.0.1"
+ "remark-gfm": "^4.0.1",
+ "remark-parse": "^11.0.0",
+ "remark-rehype": "^11.1.2",
+ "unified": "^11.0.5"
},
"devDependencies": {
"@electron-forge/cli": "^7.11.1",
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index b221f82a2..28391ff8f 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -25,6 +25,7 @@ import { THEME_STORAGE_KEY } from '@constants/theme'
import { useAgentChatActionsValue } from '@hooks/useAgentChatActionsValue'
import { useAppController } from '@hooks/useAppController'
import type { ChatLocalMatch } from '@lib/chatLocalSearch'
+import { buildLoadedChatSemanticModels } from '@lib/chatMessageSemantics'
import {
activeChatViewTab,
addBlankChatViewTab,
@@ -1533,6 +1534,11 @@ export function App() {
]
)
+ const chatSemanticModels = React.useMemo(
+ () => buildLoadedChatSemanticModels(vm.activeMessages),
+ [vm.activeMessages]
+ )
+
const chatThreadStateValue = React.useMemo(
() => ({
activeChatId: vm.activeChatId,
@@ -1546,6 +1552,9 @@ export function App() {
progressByMessageId: vm.progressByMessageId,
localSearchQuery: chatLocalSearchOpen ? chatLocalSearchState.query : '',
localSearchCurrentMatch: chatLocalSearchOpen ? chatLocalSearchState.currentMatch : null,
+ semanticModelsByMessageId: new Map(
+ chatSemanticModels.map(model => [model.messageId, model] as const)
+ ),
}),
[
vm.activeChatId,
@@ -1559,6 +1568,7 @@ export function App() {
vm.progressByMessageId,
chatLocalSearchOpen,
chatLocalSearchState,
+ chatSemanticModels,
]
)
@@ -1721,7 +1731,7 @@ export function App() {
/>
{chatLocalSearchOpen ? (
<ChatLocalSearch
- messages={vm.activeMessages}
+ models={chatSemanticModels}
onClose={closeChatLocalSearch}
onSearchStateChange={handleChatLocalSearchStateChange}
/>
diff --git a/desktop-app/ui/src/components/ChatLocalSearch/ChatLocalSearch.test.tsx b/desktop-app/ui/src/components/ChatLocalSearch/ChatLocalSearch.test.tsx
index 47cb9bc47..c820d92e6 100644
--- a/desktop-app/ui/src/components/ChatLocalSearch/ChatLocalSearch.test.tsx
+++ b/desktop-app/ui/src/components/ChatLocalSearch/ChatLocalSearch.test.tsx
@@ -2,6 +2,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { chatMessageDomId } from '@lib/chatLocalSearch'
+import { buildLoadedChatSemanticModels } from '@lib/chatMessageSemantics'
import { ChatLocalSearch } from '.'
describe('ChatLocalSearch', () => {
@@ -33,10 +34,10 @@ describe('ChatLocalSearch', () => {
const onSearchStateChange = vi.fn()
render(
<ChatLocalSearch
- messages={[
+ models={buildLoadedChatSemanticModels([
{ id: 'one', role: 'user', content: 'Needle once', timestamp: 1 },
{ id: 'two', role: 'assistant', content: 'needle twice needle', timestamp: 2 },
- ]}
+ ])}
onClose={onClose}
onSearchStateChange={onSearchStateChange}
/>
diff --git a/desktop-app/ui/src/components/ChatLocalSearch/index.tsx b/desktop-app/ui/src/components/ChatLocalSearch/index.tsx
index b7320da95..3e0dc6ad4 100644
--- a/desktop-app/ui/src/components/ChatLocalSearch/index.tsx
+++ b/desktop-app/ui/src/components/ChatLocalSearch/index.tsx
@@ -3,11 +3,11 @@ import { Button, TextInput } from '@components/Common'
import { findLoadedChatMessageMatches, wrapMatchIndex } from '@lib/chatLocalSearch'
import type { ChatLocalSearchProps } from './types'
-export function ChatLocalSearch({ messages, onClose, onSearchStateChange }: ChatLocalSearchProps) {
+export function ChatLocalSearch({ models, onClose, onSearchStateChange }: ChatLocalSearchProps) {
const [query, setQuery] = useState('')
const [currentIndex, setCurrentIndex] = useState(0)
const inputRef = useRef<HTMLInputElement | null>(null)
- const matches = useMemo(() => findLoadedChatMessageMatches(messages, query), [messages, query])
+ const matches = useMemo(() => findLoadedChatMessageMatches(models, query), [models, query])
const currentMatch = matches[currentIndex] ?? null
useEffect(() => {
diff --git a/desktop-app/ui/src/components/ChatLocalSearch/types.ts b/desktop-app/ui/src/components/ChatLocalSearch/types.ts
index 7d9d72285..2b6be19ce 100644
--- a/desktop-app/ui/src/components/ChatLocalSearch/types.ts
+++ b/desktop-app/ui/src/components/ChatLocalSearch/types.ts
@@ -1,8 +1,8 @@
import type { ChatLocalMatch } from '@lib/chatLocalSearch'
-import type { AgentChatMessage } from '@/uiTypes'
+import type { ChatMessageSemanticModel } from '@lib/chatMessageSemantics'
export type ChatLocalSearchProps = {
- messages: AgentChatMessage[]
+ models: readonly ChatMessageSemanticModel[]
onClose: () => void
onSearchStateChange: (query: string, currentMatch: ChatLocalMatch | null) => void
}
diff --git a/desktop-app/ui/src/components/Common/EditableInputContracts.test.tsx b/desktop-app/ui/src/components/Common/EditableInputContracts.test.tsx
index 27fee3a99..d56802a85 100644
--- a/desktop-app/ui/src/components/Common/EditableInputContracts.test.tsx
+++ b/desktop-app/ui/src/components/Common/EditableInputContracts.test.tsx
@@ -26,7 +26,7 @@ describe('Desktop editable input contracts', () => {
})
it('does not cancel editing commands in current-chat search', () => {
- render(<ChatLocalSearch messages={[]} onClose={vi.fn()} onSearchStateChange={vi.fn()} />)
+ render(<ChatLocalSearch models={[]} onClose={vi.fn()} onSearchStateChange={vi.fn()} />)
expectEditingEventsRemainNative(screen.getByRole('textbox', { name: 'Find in current chat' }))
})
diff --git a/desktop-app/ui/src/components/agents/ChatMarkdownContent.tsx b/desktop-app/ui/src/components/agents/ChatMarkdownContent.tsx
new file mode 100644
index 000000000..f332308b4
--- /dev/null
+++ b/desktop-app/ui/src/components/agents/ChatMarkdownContent.tsx
@@ -0,0 +1,29 @@
+import { Fragment, useMemo } from 'react'
+import { toJsxRuntime } from 'hast-util-to-jsx-runtime'
+import { jsx, jsxs } from 'react/jsx-runtime'
+import {
+ type ChatMessageSemanticModel,
+ annotateChatSemanticTree,
+} from '../../lib/chatMessageSemantics'
+
+export function ChatMarkdownContent({
+ model,
+ query,
+ activeOccurrence,
+}: {
+ model: ChatMessageSemanticModel
+ query: string
+ activeOccurrence: number | null
+}) {
+ const tree = useMemo(
+ () => annotateChatSemanticTree(model, query, activeOccurrence),
+ [activeOccurrence, model, query]
+ )
+ return toJsxRuntime(tree, {
+ Fragment,
+ ignoreInvalidStyle: true,
+ jsx,
+ jsxs,
+ passKeys: true,
+ })
+}
diff --git a/desktop-app/ui/src/components/agents/ChatThread.tsx b/desktop-app/ui/src/components/agents/ChatThread.tsx
index a82a08016..130aaffbd 100644
--- a/desktop-app/ui/src/components/agents/ChatThread.tsx
+++ b/desktop-app/ui/src/components/agents/ChatThread.tsx
@@ -13,8 +13,6 @@ import { useChatThreadStateContext } from '@contexts/ChatThreadStateContext'
import { useMcpRuntimeContext } from '@contexts/McpRuntimeContext'
import { useNavigationContext } from '@contexts/NavigationContext'
import { useNotificationsContext } from '@contexts/NotificationsContext'
-import ReactMarkdown from 'react-markdown'
-import remarkGfm from 'remark-gfm'
import { Button, IconButton, MenuItem } from '@components/Common'
import { ConfirmDialog } from '@components/ConfirmDialog'
import { MessageArtifactActions } from '@components/MessageArtifactActions'
@@ -33,11 +31,7 @@ import {
} from '@constants/agents'
import { HTML_PREVIEW_INLINE_MAX_BYTES } from '@constants/htmlPreview'
import type { ChatMessageAttachment } from '../../../../src/types'
-import {
- chatMessageDomId,
- createChatSearchRehypePlugin,
- highlightChatText,
-} from '../../lib/chatLocalSearch'
+import { chatMessageDomId } from '../../lib/chatLocalSearch'
import {
getChatMessageAttachmentTypeLabel,
parseChatMessageDisplay,
@@ -51,6 +45,7 @@ import {
import { resolveTaskActionState } from '../../pages/AgentsPage.helpers'
import type { AgentChatMessage, ProgressStep, TaskProgress } from '../../uiTypes'
import { ProgressStepper } from '../ProgressStepper'
+import { ChatMarkdownContent } from './ChatMarkdownContent'
import { ChatStateBadge } from './ChatStateBadge'
import { InFlightAssistantPlaceholder } from './InFlightAssistantPlaceholder'
import { MessageTokens } from './MessageTokens'
@@ -235,6 +230,7 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C
progressByMessageId,
localSearchQuery,
localSearchCurrentMatch,
+ semanticModelsByMessageId,
} = useChatThreadStateContext()
const {
chatList,
@@ -574,6 +570,8 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C
const parsedUserMessage =
message.role === 'user' ? parseChatMessageDisplay(message.content) : null
const displayContent = parsedUserMessage?.content ?? message.content
+ const semanticModel = semanticModelsByMessageId.get(message.id)
+ if (!semanticModel) return null
const activeSearchOccurrence =
localSearchCurrentMatch?.messageId === message.id
? localSearchCurrentMatch.occurrence
@@ -639,13 +637,11 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C
: ''}
</div>
<div className="error-bubble-message">
- {highlightChatText(
- localSearchQuery || message.content.length <= 180
- ? message.content
- : `${message.content.slice(0, 177)}...`,
- localSearchQuery,
- activeSearchOccurrence
- )}
+ <ChatMarkdownContent
+ model={semanticModel}
+ query={localSearchQuery}
+ activeOccurrence={activeSearchOccurrence}
+ />
</div>
<details className="error-bubble-details">
<summary>Details</summary>
@@ -665,25 +661,19 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C
)}
{isJson ? (
<pre className="message-block json-content">
- {highlightChatText(
- displayContent,
- localSearchQuery,
- activeSearchOccurrence
- )}
+ <ChatMarkdownContent
+ model={semanticModel}
+ query={localSearchQuery}
+ activeOccurrence={activeSearchOccurrence}
+ />
</pre>
) : message.role === 'assistant' ? (
<div className="message-block markdown-content">
- <ReactMarkdown
- remarkPlugins={[remarkGfm]}
- rehypePlugins={[
- createChatSearchRehypePlugin(
- localSearchQuery,
- activeSearchOccurrence
- ),
- ]}
- >
- {displayContent}
- </ReactMarkdown>
+ <ChatMarkdownContent
+ model={semanticModel}
+ query={localSearchQuery}
+ activeOccurrence={activeSearchOccurrence}
+ />
{selectedAgent && !hasResponseFileAttachment && (
<MessageArtifactActions
hostRef={selectedAgent}
@@ -698,11 +688,11 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: C
</div>
) : displayContent ? (
<p className="message-block">
- {highlightChatText(
- displayContent,
- localSearchQuery,
- activeSearchOccurrence
- )}
+ <ChatMarkdownContent
+ model={semanticModel}
+ query={localSearchQuery}
+ activeOccurrence={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 da2a75717..4e33d9af5 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
@@ -11,6 +11,7 @@ import { NotificationsContext } from '@contexts/NotificationsContext'
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
import { createRoot } from 'react-dom/client'
import { useChatScroll } from '@hooks/domain/useChatScroll'
+import { buildLoadedChatSemanticModels } from '@lib/chatMessageSemantics'
import type { AgentChatMessage } from '../../../uiTypes'
import { AgentWorkspace } from '../AgentWorkspace'
@@ -185,6 +186,9 @@ function WorkspaceHarness({
progressByMessageId: {},
localSearchQuery: '',
localSearchCurrentMatch: null,
+ semanticModelsByMessageId: new Map(
+ buildLoadedChatSemanticModels(messages).map(model => [model.messageId, model])
+ ),
}}
>
<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 e275c70a7..569adc9b3 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
@@ -13,6 +13,7 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { MessageToolStep } from '../../../../../src/types'
import { findLoadedChatMessageMatches } from '../../../lib/chatLocalSearch'
+import { buildLoadedChatSemanticModels } from '../../../lib/chatMessageSemantics'
import type { AgentChatMessage, TaskProgress } from '../../../uiTypes'
// vi.mock calls are hoisted above this import, so ChatThread binds the mocks.
import { ChatThread } from '../ChatThread'
@@ -40,6 +41,10 @@ let threadStateValue: {
handleLoadOlderMessages: ReturnType<typeof vi.fn>
localSearchQuery: string
localSearchCurrentMatch: { messageId: string; occurrence: number } | null
+ semanticModelsByMessageId: ReadonlyMap<
+ string,
+ ReturnType<typeof buildLoadedChatSemanticModels>[number]
+ >
}
vi.mock('@contexts/NavigationContext', () => ({ useNavigationContext: () => navValue }))
@@ -103,6 +108,9 @@ function setThreadState(
handleLoadOlderMessages: vi.fn().mockResolvedValue(undefined),
localSearchQuery: '',
localSearchCurrentMatch: null,
+ semanticModelsByMessageId: new Map(
+ buildLoadedChatSemanticModels(activeMessages).map(model => [model.messageId, model])
+ ),
}
}
@@ -125,7 +133,9 @@ describe('ChatThread local-search highlighting', () => {
const renderedMatches = document.querySelectorAll('.chat-search-match')
expect(renderedMatches).toHaveLength(2)
- expect(findLoadedChatMessageMatches([assistant], 'needle')).toHaveLength(renderedMatches.length)
+ expect(
+ findLoadedChatMessageMatches(buildLoadedChatSemanticModels([assistant]), 'needle')
+ ).toHaveLength(renderedMatches.length)
})
it('renders every plain and Markdown match and distinguishes the selected occurrence', () => {
@@ -158,7 +168,9 @@ describe('ChatThread local-search highlighting', () => {
const renderedMatches = document.querySelectorAll('.chat-search-match')
expect(renderedMatches).toHaveLength(4)
- expect(findLoadedChatMessageMatches(messages, 'needle')).toHaveLength(renderedMatches.length)
+ expect(
+ findLoadedChatMessageMatches(buildLoadedChatSemanticModels(messages), 'needle')
+ ).toHaveLength(renderedMatches.length)
const active = screen.getByTestId('chat-search-current-match')
expect(active.textContent).toBe('needle')
expect(active.closest('a')?.getAttribute('href')).toBe('https://needle.example/needle')
@@ -172,6 +184,46 @@ describe('ChatThread local-search highlighting', () => {
rerender(<ChatThread />)
expect(document.querySelector('.chat-search-match')).toBeNull()
})
+
+ it('renders one logical match across inline nodes with shared mark identity', () => {
+ const assistant: AgentChatMessage = {
+ id: 'cross-inline',
+ role: 'assistant',
+ content: 'A cross **node** remains one result.',
+ timestamp: 2,
+ }
+ setThreadState([{ role: 'assistant', items: [assistant] }])
+ threadStateValue.localSearchQuery = 'cross node'
+ threadStateValue.localSearchCurrentMatch = { messageId: assistant.id, occurrence: 0 }
+
+ render(<ChatThread />)
+
+ const marks = [...document.querySelectorAll<HTMLElement>('.chat-search-match')]
+ expect(
+ findLoadedChatMessageMatches(
+ [...threadStateValue.semanticModelsByMessageId.values()],
+ 'cross node'
+ )
+ ).toHaveLength(1)
+ expect(marks).toHaveLength(2)
+ expect(new Set(marks.map(mark => mark.dataset.chatSearchMatchId))).toHaveProperty('size', 1)
+ })
+
+ it('keeps raw HTML inert and unsafe Markdown URLs sanitized', () => {
+ const assistant: AgentChatMessage = {
+ id: 'safe-markdown',
+ role: 'assistant',
+ content: '[unsafe](javascript:alert(1)) <button onclick="evil()">literal</button>',
+ timestamp: 2,
+ }
+ setThreadState([{ role: 'assistant', items: [assistant] }])
+
+ render(<ChatThread />)
+
+ expect(document.querySelector('a')?.getAttribute('href')).toBe('')
+ expect(document.querySelector('button[onclick]')).toBeNull()
+ expect(screen.getByText(/<button onclick="evil\(\)">literal<\/button>/)).toBeTruthy()
+ })
})
describe('ChatThread tool-steps fallback (#582)', () => {
diff --git a/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts b/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts
index bedb85d5e..1619dce60 100644
--- a/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts
+++ b/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts
@@ -1,5 +1,6 @@
import type { ReactNode } from 'react'
import type { ChatLocalMatch } from '../../lib/chatLocalSearch'
+import type { ChatMessageSemanticModel } from '../../lib/chatMessageSemantics'
import type { AgentChatMessage, AgentMessageActivity, TaskProgress } from '../../uiTypes'
/**
@@ -20,6 +21,7 @@ export interface ChatThreadStateContextValue {
progressByMessageId: Record<string, TaskProgress>
localSearchQuery: string
localSearchCurrentMatch: ChatLocalMatch | null
+ semanticModelsByMessageId: ReadonlyMap<string, ChatMessageSemanticModel>
}
export interface ChatThreadStateProviderProps {
diff --git a/desktop-app/ui/src/lib/__tests__/chatLocalSearch.test.ts b/desktop-app/ui/src/lib/__tests__/chatLocalSearch.test.ts
index 3dd95df1f..ab4084148 100644
--- a/desktop-app/ui/src/lib/__tests__/chatLocalSearch.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/chatLocalSearch.test.ts
@@ -1,10 +1,7 @@
import { describe, expect, it } from 'vitest'
import type { AgentChatMessage } from '../../uiTypes'
-import {
- findLoadedChatMessageMatches,
- markdownSearchableText,
- wrapMatchIndex,
-} from '../chatLocalSearch'
+import { findLoadedChatMessageMatches, wrapMatchIndex } from '../chatLocalSearch'
+import { buildLoadedChatSemanticModels } from '../chatMessageSemantics'
function message(id: string, content: string, role: AgentChatMessage['role'] = 'assistant') {
return { id, content, role, timestamp: 1 } satisfies AgentChatMessage
@@ -14,7 +11,10 @@ describe('loaded chat local search', () => {
it('matches case-insensitively across renderer-owned loaded message data', () => {
expect(
findLoadedChatMessageMatches(
- [message('one', 'Alpha alpha'), message('two', 'BETA Alpha')],
+ buildLoadedChatSemanticModels([
+ message('one', 'Alpha alpha'),
+ message('two', 'BETA Alpha'),
+ ]),
'ALPHA'
)
).toEqual([
@@ -28,10 +28,16 @@ describe('loaded chat local search', () => {
const content =
'Visible question\n\nUSER-ATTACHED CONTEXT: The user selected these capabilities/files for this message.\nPlugins: hidden-search-plugin.'
expect(
- findLoadedChatMessageMatches([message('user', content, 'user')], 'visible')
+ findLoadedChatMessageMatches(
+ buildLoadedChatSemanticModels([message('user', content, 'user')]),
+ 'visible'
+ )
).toHaveLength(1)
expect(
- findLoadedChatMessageMatches([message('user', content, 'user')], 'hidden-search')
+ findLoadedChatMessageMatches(
+ buildLoadedChatSemanticModels([message('user', content, 'user')]),
+ 'hidden-search'
+ )
).toEqual([])
})
@@ -45,8 +51,12 @@ describe('loaded chat local search', () => {
'[hidden-ref]: https://example.test/needle "needle title"',
].join('\n')
- expect(markdownSearchableText(content)).not.toContain('needle.example')
- expect(findLoadedChatMessageMatches([message('assistant', content)], 'needle')).toEqual([
+ expect(
+ findLoadedChatMessageMatches(
+ buildLoadedChatSemanticModels([message('assistant', content)]),
+ 'needle'
+ )
+ ).toEqual([
{ messageId: 'assistant', occurrence: 0 },
{ messageId: 'assistant', occurrence: 1 },
{ messageId: 'assistant', occurrence: 2 },
@@ -55,7 +65,12 @@ describe('loaded chat local search', () => {
it('keeps code lines that are not valid closers for a longer fence', () => {
const content = ['````typescript', '```needle', 'visible needle', '````'].join('\n')
- expect(findLoadedChatMessageMatches([message('assistant', content)], 'needle')).toEqual([
+ expect(
+ findLoadedChatMessageMatches(
+ buildLoadedChatSemanticModels([message('assistant', content)]),
+ 'needle'
+ )
+ ).toEqual([
{ messageId: 'assistant', occurrence: 0 },
{ messageId: 'assistant', occurrence: 1 },
])
diff --git a/desktop-app/ui/src/lib/__tests__/chatMessageSemantics.test.ts b/desktop-app/ui/src/lib/__tests__/chatMessageSemantics.test.ts
new file mode 100644
index 000000000..5015afc91
--- /dev/null
+++ b/desktop-app/ui/src/lib/__tests__/chatMessageSemantics.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from 'vitest'
+import type { AgentChatMessage } from '../../uiTypes'
+import {
+ annotateChatSemanticTree,
+ buildChatMessageSemanticModel,
+ findChatSemanticMatches,
+} from '../chatMessageSemantics'
+
+function assistant(content: string): AgentChatMessage {
+ return { id: 'assistant-1', role: 'assistant', content, timestamp: 1 }
+}
+
+function textValues(node: unknown): string {
+ if (!node || typeof node !== 'object') return ''
+ const value = node as { type?: string; value?: string; children?: unknown[] }
+ if (value.type === 'text') return value.value ?? ''
+ return value.children?.map(textValues).join('') ?? ''
+}
+
+function markCount(node: unknown): number {
+ if (!node || typeof node !== 'object') return 0
+ const value = node as { tagName?: string; children?: unknown[] }
+ return (
+ (value.tagName === 'mark' ? 1 : 0) +
+ (value.children?.map(markCount).reduce((total, count) => total + count, 0) ?? 0)
+ )
+}
+
+describe('chat message Markdown semantic model', () => {
+ it('derives visible text and logical highlights from the same immutable tree', () => {
+ const model = buildChatMessageSemanticModel(
+ assistant('# Heading\n\nA cross **node** and [visible link](https://example.test/hidden).')
+ )
+ const matches = findChatSemanticMatches(model, 'cross node')
+ const annotated = annotateChatSemanticTree(model, 'cross node', 0)
+
+ expect(matches).toHaveLength(1)
+ expect(matches[0]?.ranges).toHaveLength(2)
+ expect(markCount(annotated)).toBe(2)
+ expect(textValues(annotated)).toContain('A cross node and visible link.')
+ expect(model.searchText).not.toContain('example.test')
+ expect(Object.isFrozen(model.renderTree)).toBe(true)
+ })
+
+ it('preserves code, entities, raw HTML text, and excludes invisible Markdown metadata', () => {
+ const model = buildChatMessageSemanticModel(
+ assistant(
+ [
+ '&amp; escaped',
+ '`inline code`',
+ '````js',
+ '```needle',
+ 'fenced needle',
+ '````',
+ '<button onclick="evil()">literal</button>',
+ '[ref label][target]',
+ '[target]: javascript:alert(1) "hidden title"',
+ '![hidden image metadata](https://example.test/image.png)',
+ ].join('\n\n')
+ )
+ )
+
+ expect(model.searchText).toContain('& escaped')
+ expect(model.searchText).toContain('inline code')
+ expect(model.searchText).toContain('```needle')
+ expect(model.searchText).toContain('fenced needle')
+ expect(model.searchText).toContain('<button onclick="evil()">literal</button>')
+ expect(model.searchText).toContain('ref label')
+ expect(model.searchText).not.toContain('hidden title')
+ expect(model.searchText).not.toContain('hidden image metadata')
+ expect(findChatSemanticMatches(model, 'needle')).toHaveLength(2)
+ })
+
+ it('prevents logical matches from crossing blocks and GFM table cells', () => {
+ const blocks = buildChatMessageSemanticModel(assistant('alpha\n\nbeta'))
+ const table = buildChatMessageSemanticModel(assistant('| alpha | beta |\n| --- | --- |'))
+ const inline = buildChatMessageSemanticModel(assistant('alpha **beta**'))
+
+ expect(findChatSemanticMatches(blocks, 'alpha beta')).toEqual([])
+ expect(findChatSemanticMatches(table, 'alpha beta')).toEqual([])
+ expect(findChatSemanticMatches(inline, 'alpha beta')).toHaveLength(1)
+ })
+
+ it('maps Unicode case-fold expansions back to valid original UTF-16 slices', () => {
+ const model = buildChatMessageSemanticModel(assistant('İstanbul 😀 STRASSE'))
+ const dotted = findChatSemanticMatches(model, 'i̇stanbul')
+ const emoji = findChatSemanticMatches(model, '😀')
+
+ expect(dotted).toHaveLength(1)
+ expect(dotted[0]?.ranges[0]).toMatchObject({ start: 0, end: 8 })
+ expect(emoji).toHaveLength(1)
+ expect(emoji[0]?.ranges[0]).toMatchObject({ start: 9, end: 11 })
+ })
+
+ it('handles adversarial destination-like input without a projection regex', () => {
+ const hostile = `[label](${String.raw`\(`.repeat(20_000)}destination)`
+ const started = performance.now()
+ const model = buildChatMessageSemanticModel(assistant(hostile))
+ expect(findChatSemanticMatches(model, 'label')).toHaveLength(1)
+ expect(performance.now() - started).toBeLessThan(2_000)
+ })
+})
diff --git a/desktop-app/ui/src/lib/chatLocalSearch.ts b/desktop-app/ui/src/lib/chatLocalSearch.ts
index 8198dec18..f74b440df 100644
--- a/desktop-app/ui/src/lib/chatLocalSearch.ts
+++ b/desktop-app/ui/src/lib/chatLocalSearch.ts
@@ -1,6 +1,5 @@
-import { type ReactNode, createElement } from 'react'
-import type { AgentChatMessage } from '../uiTypes'
-import { parseChatMessageDisplay } from './chatMessageAttachments'
+import type { ChatMessageSemanticModel } from './chatMessageSemantics'
+import { findChatSemanticMatches } from './chatMessageSemantics'
export type ChatLocalMatch = {
messageId: string
@@ -11,160 +10,19 @@ export function chatMessageDomId(messageId: string): string {
return `chat-message-${encodeURIComponent(messageId)}`
}
-/**
- * Project Markdown source to the text ReactMarkdown makes searchable. This
- * intentionally keeps labels and code contents while masking metadata that is
- * not rendered as message text (destinations, reference definitions, tags,
- * and fenced-code language identifiers).
- */
-export function markdownSearchableText(source: string): string {
- let fence: { marker: '`' | '~'; length: number } | null = null
- return source
- .split(/(\r?\n)/)
- .map(part => {
- if (part === '\n' || part === '\r\n') return part
- const fenceMatch = part.match(/^\s{0,3}(`{3,}|~{3,})(.*)$/)
- if (fence === null && fenceMatch) {
- const run = fenceMatch[1]!
- fence = { marker: run[0] as '`' | '~', length: run.length }
- return ' '.repeat(part.length)
- }
- if (fence !== null) {
- const run = fenceMatch?.[1] ?? ''
- const trailing = fenceMatch?.[2] ?? ''
- if (run[0] === fence.marker && run.length >= fence.length && trailing.trim().length === 0) {
- fence = null
- return ' '.repeat(part.length)
- }
- return part
- }
- if (/^\s{0,3}\[[^\]]+\]:\s*/.test(part)) return ' '.repeat(part.length)
- return part
- .replace(/\]\((?:\\.|[^)])*\)/g, match => `]${' '.repeat(match.length - 1)}`)
- .replace(/\]\[[^\]]+\]/g, match => `]${' '.repeat(match.length - 1)}`)
- .replace(/<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^>]*)?\/?>/g, match => ' '.repeat(match.length))
- })
- .join('')
-}
-
export function findLoadedChatMessageMatches(
- messages: AgentChatMessage[],
+ models: readonly ChatMessageSemanticModel[],
query: string
): ChatLocalMatch[] {
- const needle = query.trim().toLocaleLowerCase()
- if (!needle) return []
- const matches: ChatLocalMatch[] = []
- for (const message of messages) {
- const displayed =
- message.role === 'user'
- ? (parseChatMessageDisplay(message.content)?.content ?? message.content)
- : markdownSearchableText(message.content)
- const haystack = displayed.toLocaleLowerCase()
- let offset = 0
- let occurrence = 0
- while (offset <= haystack.length - needle.length) {
- const index = haystack.indexOf(needle, offset)
- if (index < 0) break
- matches.push({ messageId: message.id, occurrence })
- occurrence += 1
- offset = index + Math.max(1, needle.length)
- }
- }
- return matches
+ return models.flatMap(model =>
+ findChatSemanticMatches(model, query).map(match => ({
+ messageId: match.messageId,
+ occurrence: match.occurrence,
+ }))
+ )
}
export function wrapMatchIndex(index: number, total: number, delta: 1 | -1): number {
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/lib/chatMessageSemantics.ts b/desktop-app/ui/src/lib/chatMessageSemantics.ts
new file mode 100644
index 000000000..e12d64da8
--- /dev/null
+++ b/desktop-app/ui/src/lib/chatMessageSemantics.ts
@@ -0,0 +1,282 @@
+import type { Element, Root, RootContent, Text } from 'hast'
+import { defaultUrlTransform } from 'react-markdown'
+import remarkGfm from 'remark-gfm'
+import remarkParse from 'remark-parse'
+import remarkRehype from 'remark-rehype'
+import { unified } from 'unified'
+import type { AgentChatMessage } from '../uiTypes'
+import { parseChatMessageDisplay } from './chatMessageAttachments'
+
+type SemanticText = Text & { searchFragmentId?: string }
+
+export type ChatSemanticFragment = Readonly<{
+ id: string
+ flowId: number
+ start: number
+ end: number
+ text: string
+}>
+
+export type ChatMessageSemanticModel = Readonly<{
+ messageId: string
+ contentRevision: string
+ representation: 'markdown' | 'plain'
+ renderTree: Root
+ searchText: string
+ fragments: readonly ChatSemanticFragment[]
+ flows: readonly Readonly<{ id: number; text: string }>[]
+}>
+
+export type ChatSemanticMatch = Readonly<{
+ id: string
+ messageId: string
+ occurrence: number
+ ranges: readonly Readonly<{ fragmentId: string; start: number; end: number }>[]
+}>
+
+const FLOW_BOUNDARIES = new Set([
+ 'blockquote',
+ 'h1',
+ 'h2',
+ 'h3',
+ 'h4',
+ 'h5',
+ 'h6',
+ 'li',
+ 'p',
+ 'pre',
+ 'td',
+ 'th',
+])
+const URL_PROPERTIES = new Set(['href', 'src'])
+
+function normalizeTree(node: RootContent | Root): void {
+ if ('children' in node) {
+ node.children = node.children.map(child => {
+ if (child.type === 'raw') return { type: 'text', value: child.value }
+ normalizeTree(child)
+ return child
+ }) as typeof node.children
+ }
+ if (node.type === 'element') {
+ for (const property of URL_PROPERTIES) {
+ if (Object.hasOwn(node.properties, property)) {
+ node.properties[property] = defaultUrlTransform(String(node.properties[property] || ''))
+ }
+ }
+ }
+}
+
+function freezeTree(node: RootContent | Root): void {
+ if ('children' in node) {
+ node.children.forEach(freezeTree)
+ Object.freeze(node.children)
+ }
+ if (node.type === 'element') Object.freeze(node.properties)
+ Object.freeze(node)
+}
+
+function indexTree(tree: Root): {
+ fragments: ChatSemanticFragment[]
+ flows: Array<{ id: number; text: string }>
+} {
+ const fragments: ChatSemanticFragment[] = []
+ const flows: Array<{ id: number; text: string }> = []
+ let currentFlow: { id: number; text: string } | null = null
+ let nextFlowId = 0
+ const ensureFlow = () => {
+ if (!currentFlow) {
+ currentFlow = { id: nextFlowId++, text: '' }
+ flows.push(currentFlow)
+ }
+ return currentFlow
+ }
+ const visit = (node: RootContent | Root, startsFlow: boolean) => {
+ if (node.type === 'element' && (FLOW_BOUNDARIES.has(node.tagName) || node.tagName === 'br')) {
+ currentFlow = null
+ startsFlow = true
+ }
+ if (node.type === 'text' && node.value) {
+ const flow = ensureFlow()
+ const id = `${flow.id}:${fragments.length}`
+ const start = flow.text.length
+ flow.text += node.value
+ ;(node as SemanticText).searchFragmentId = id
+ fragments.push({ id, flowId: flow.id, start, end: flow.text.length, text: node.value })
+ } else if ('children' in node) {
+ node.children.forEach(child => visit(child, false))
+ }
+ if (startsFlow) currentFlow = null
+ }
+ tree.children.forEach(child => visit(child, true))
+ return { fragments, flows }
+}
+
+function plainTree(value: string): Root {
+ return { type: 'root', children: [{ type: 'text', value }] }
+}
+
+export function buildChatMessageSemanticModel(message: AgentChatMessage): ChatMessageSemanticModel {
+ let parsesAsJson = false
+ if (message.role === 'assistant') {
+ try {
+ JSON.parse(message.content)
+ parsesAsJson = true
+ } catch {
+ // Normal assistant prose is Markdown.
+ }
+ }
+ const representation =
+ message.role === 'assistant' && !message.isError && !parsesAsJson ? 'markdown' : 'plain'
+ const displayed =
+ representation === 'plain'
+ ? (parseChatMessageDisplay(message.content)?.content ?? message.content)
+ : message.content
+ const processor = unified()
+ .use(remarkParse)
+ .use(remarkGfm)
+ .use(remarkRehype, { allowDangerousHtml: true })
+ const tree =
+ representation === 'markdown'
+ ? (processor.runSync(processor.parse(displayed)) as Root)
+ : plainTree(displayed)
+ normalizeTree(tree)
+ const { fragments, flows } = indexTree(tree)
+ freezeTree(tree)
+ return Object.freeze({
+ messageId: message.id,
+ contentRevision: displayed,
+ representation,
+ renderTree: tree,
+ searchText: flows.map(flow => flow.text).join('\u0000'),
+ fragments: Object.freeze(fragments.map(fragment => Object.freeze(fragment))),
+ flows: Object.freeze(flows.map(flow => Object.freeze(flow))),
+ })
+}
+
+export function buildLoadedChatSemanticModels(
+ messages: readonly AgentChatMessage[]
+): readonly ChatMessageSemanticModel[] {
+ return messages.map(buildChatMessageSemanticModel)
+}
+
+function foldWithOffsets(value: string): { folded: string; starts: number[]; ends: number[] } {
+ let folded = ''
+ const starts: number[] = []
+ const ends: number[] = []
+ let offset = 0
+ for (const character of value) {
+ const end = offset + character.length
+ const lower = character.toLocaleLowerCase()
+ folded += lower
+ for (let index = 0; index < lower.length; index += 1) {
+ starts.push(offset)
+ ends.push(end)
+ }
+ offset = end
+ }
+ return { folded, starts, ends }
+}
+
+export function findChatSemanticMatches(
+ model: ChatMessageSemanticModel,
+ query: string
+): readonly ChatSemanticMatch[] {
+ const needle = foldWithOffsets(query.trim()).folded
+ if (!needle) return []
+ const matches: ChatSemanticMatch[] = []
+ let occurrence = 0
+ for (const flow of model.flows) {
+ const folded = foldWithOffsets(flow.text)
+ let offset = 0
+ while (offset <= folded.folded.length - needle.length) {
+ const index = folded.folded.indexOf(needle, offset)
+ if (index < 0) break
+ const start = folded.starts[index]!
+ const end = folded.ends[index + needle.length - 1]!
+ const ranges = model.fragments
+ .filter(
+ fragment => fragment.flowId === flow.id && fragment.start < end && fragment.end > start
+ )
+ .map(fragment => ({
+ fragmentId: fragment.id,
+ start: Math.max(0, start - fragment.start),
+ end: Math.min(fragment.text.length, end - fragment.start),
+ }))
+ .filter(range => range.end > range.start)
+ if (ranges.length) {
+ matches.push(
+ Object.freeze({
+ id: `${model.messageId}:${flow.id}:${start}:${end}`,
+ messageId: model.messageId,
+ occurrence,
+ ranges: Object.freeze(ranges.map(range => Object.freeze(range))),
+ })
+ )
+ occurrence += 1
+ }
+ offset = index + Math.max(1, needle.length)
+ }
+ }
+ return Object.freeze(matches)
+}
+
+function markProperties(match: ChatSemanticMatch, activeOccurrence: number | null) {
+ const active = match.occurrence === activeOccurrence
+ return {
+ className: active ? ['chat-search-match', 'chat-search-match--active'] : ['chat-search-match'],
+ 'data-chat-search-match-id': match.id,
+ 'data-testid': active ? 'chat-search-current-match' : 'chat-search-match',
+ ...(active ? { 'data-current-search-match': 'true' } : {}),
+ }
+}
+
+export function annotateChatSemanticTree(
+ model: ChatMessageSemanticModel,
+ query: string,
+ activeOccurrence: number | null
+): Root {
+ const rangesByFragment = new Map<
+ string,
+ Array<{ match: ChatSemanticMatch; start: number; end: number }>
+ >()
+ for (const match of findChatSemanticMatches(model, query)) {
+ for (const range of match.ranges) {
+ const ranges = rangesByFragment.get(range.fragmentId) ?? []
+ ranges.push({ match, start: range.start, end: range.end })
+ rangesByFragment.set(range.fragmentId, ranges)
+ }
+ }
+ const clone = (node: RootContent | Root): RootContent | Root => {
+ if (node.type === 'text') {
+ const fragmentId = (node as SemanticText).searchFragmentId
+ const ranges = fragmentId ? rangesByFragment.get(fragmentId) : undefined
+ if (!ranges?.length) return { type: 'text', value: node.value }
+ const children: RootContent[] = []
+ let offset = 0
+ ranges.forEach(range => {
+ if (range.start > offset)
+ children.push({ type: 'text', value: node.value.slice(offset, range.start) })
+ children.push({
+ type: 'element',
+ tagName: 'mark',
+ properties: markProperties(range.match, activeOccurrence),
+ children: [{ type: 'text', value: node.value.slice(range.start, range.end) }],
+ })
+ offset = range.end
+ })
+ if (offset < node.value.length)
+ children.push({ type: 'text', value: node.value.slice(offset) })
+ return { type: 'element', tagName: 'span', properties: {}, children } as Element
+ }
+ if ('children' in node) {
+ return {
+ ...node,
+ ...(node.type === 'element' ? { properties: { ...node.properties } } : {}),
+ children: node.children.map(clone),
+ } as RootContent | Root
+ }
+ return { ...node }
+ }
+ return clone(model.renderTree) as Root
+}