Open History to see the last commit
1import { shouldPreserveAssistantLineBreaks } from "./assistantInsights.ts";
2import { THREAD_FIND_BLOCK_TAGS } from "./threadFindBlockTags.ts";
3import {
4 matchInlineSkills,
5 formatProviderSkillDisplayName,
6 type InlineSkill,
7} from "./inlineSkills.ts";
8import { renderCodexInlineDirectivesAsMarkdown } from "./codexMarkdownDirectives.ts";
9import {
10 artifactTemplateFromHastProperties,
11 codexArtifactTemplatePresentationLabel,
12} from "./codexArtifactTemplates.ts";
13import { buildFileLinkParentSuffixByPath, fileLinkLabel } from "./fileLinks.ts";
14import {
15 classifyMarkdownImageSource,
16 isMarkdownFileLinkLabel,
17 encodeMarkdownLinkBoundaryWhitespace,
18 extractMarkdownLinkHrefs,
19 extractInlineCodeSpans,
20 inlineCodeFilePathCandidate,
21 resolveMarkdownFileLink,
22 shouldRenderMarkdownImageAsFileLink,
23} from "./markdownLinks.ts";
24import { mediaKindFromPath } from "./mediaPreview.ts";
25import { upgradeLegacyContextMessage } from "./composerContextLegacy.ts";
26import {
27 isAttachmentOnlyBootstrapPrompt,
28 parseComposerContextHref,
29} from "./composerContextReferences.ts";
30import { parseAssistantCitationHref } from "./assistantCitations.ts";
31import type { OrchestrationV2ConversationMessage } from "@t3tools/contracts";
32import { proposedPlanTitle, stripDisplayedPlanMarkdown } from "./proposedPlanText.ts";
33import { unified } from "unified";
34import remarkParse from "remark-parse";
35import remarkRehype from "remark-rehype";
36import {
37 remarkAssistantInsights,
38 CHAT_MARKDOWN_REHYPE_PLUGINS,
39 CHAT_MARKDOWN_REMARK_PLUGINS,
40 CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
41 CHAT_USER_MARKDOWN_REMARK_PLUGINS,
42 chatMarkdownImageSource,
43 decodeMarkdownLinkEscapes,
44 type ChatMarkdownImageProperties,
45} from "./markdownPipeline.ts";
46
47// Inline wrappers (including Shiki token spans) must not split a search phrase.
48
49function assistantTextProcessor(lineBreaks = false, renderInsights = false) {
50 return unified()
51 .use(remarkParse)
52 .use(renderInsights ? [remarkAssistantInsights] : [])
53 .use(lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS)
54 .use(remarkRehype, { allowDangerousHtml: true })
55 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
56}
57const assistantProcessor = assistantTextProcessor();
58const assistantBreaksProcessor = assistantTextProcessor(true);
59const insightProcessor = assistantTextProcessor(false, true);
60const insightBreaksProcessor = assistantTextProcessor(true, true);
61const userProcessor = unified()
62 .use(remarkParse)
63 .use(CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS)
64 .use(CHAT_USER_MARKDOWN_REMARK_PLUGINS)
65 .use(remarkRehype, { allowDangerousHtml: true });
66
67interface TextTree {
68 readonly type: string;
69 readonly tagName?: string;
70 readonly value?: string;
71 readonly properties?: ChatMarkdownImageProperties & {
72 readonly href?: unknown;
73 readonly dataInlineCode?: unknown;
74 };
75 readonly children?: ReadonlyArray<TextTree>;
76}
77
78function markdownThreadFindText(
79 markdown: string,
80 {
81 userMessage = false,
82 cwd,
83 skills = [],
84 lineBreaks = false,
85 renderInsights = false,
86 theme,
87 }: {
88 userMessage?: boolean;
89 cwd: string | undefined;
90 skills?: readonly InlineSkill[];
91 lineBreaks?: boolean;
92 renderInsights?: boolean;
93 theme: "dark" | "light" | undefined;
94 },
95): string[] {
96 const processor = userMessage
97 ? userProcessor
98 : lineBreaks
99 ? assistantBreaksProcessor
100 : assistantProcessor;
101 const renderer = renderInsights
102 ? lineBreaks
103 ? insightBreaksProcessor
104 : insightProcessor
105 : processor;
106 const tree = renderer.runSync(renderer.parse(markdown), markdown);
107 const paths = [
108 ...extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(markdown)).map((href) =>
109 encodeMarkdownLinkBoundaryWhitespace(decodeMarkdownLinkEscapes(href), true),
110 ),
111 ...extractInlineCodeSpans(markdown).flatMap((span) => inlineCodeFilePathCandidate(span) ?? []),
112 ].flatMap((href) => {
113 const resolved = resolveMarkdownFileLink(href, cwd);
114 return resolved ? [resolved.position.path] : [];
115 });
116 const parentSuffixes = buildFileLinkParentSuffixByPath(paths);
117 const segments: string[] = [];
118 let text = "";
119 const flush = () => {
120 if (text.trim()) segments.push(text);
121 text = "";
122 };
123 const labelText = (node: TextTree): string =>
124 node.value ?? (node.children ?? []).map(labelText).join("");
125 const visit = (node: TextTree, inPre = false, inlineSkills = false, inAnchor = false) => {
126 const href = node.properties?.href ?? node.properties?.src;
127 if (userMessage && typeof href === "string" && parseComposerContextHref(href)) {
128 flush();
129 return;
130 }
131 const citation =
132 node.tagName === "a" && typeof href === "string" ? parseAssistantCitationHref(href) : null;
133 if (citation) {
134 // The quote card is not searched, and it splits the text before it from its comment.
135 flush();
136 text += (citation.comment ?? "").replace(/\r?\n/g, " ");
137 return;
138 }
139 {
140 let candidate: string | null = null;
141 if (node.tagName === "a" && typeof href === "string") {
142 candidate = href;
143 } else if (node.tagName === "img") {
144 const source = chatMarkdownImageSource(node.properties, theme);
145 if (source) {
146 const { authoredSrc, classifiedSrc } = source;
147 if (
148 shouldRenderMarkdownImageAsFileLink(
149 classifyMarkdownImageSource(classifiedSrc, cwd),
150 mediaKindFromPath(classifiedSrc),
151 )
152 ) {
153 candidate = authoredSrc;
154 }
155 }
156 } else if (
157 node.tagName === "code" &&
158 !inPre &&
159 !inAnchor &&
160 (!userMessage || node.properties?.dataInlineCode !== undefined)
161 ) {
162 candidate = inlineCodeFilePathCandidate(labelText(node));
163 }
164 const resolved = candidate ? resolveMarkdownFileLink(candidate, cwd) : null;
165 if (candidate && resolved) {
166 const label = labelText(node);
167 if (node.tagName === "a" && !isMarkdownFileLinkLabel(label, candidate)) text += `${label} `;
168 text += fileLinkLabel(resolved.position, parentSuffixes);
169 return;
170 }
171 }
172 const template = artifactTemplateFromHastProperties(node.properties);
173 if (template) {
174 flush();
175 segments.push(
176 template.displayName,
177 codexArtifactTemplatePresentationLabel(template.artifactKind),
178 );
179 return;
180 }
181 const block = THREAD_FIND_BLOCK_TAGS.has(node.tagName ?? "");
182 if (block) flush();
183 if (node.type === "text" || (userMessage && node.type === "raw")) {
184 let value = node.value ?? "";
185 if (inlineSkills) {
186 let cursor = 0;
187 let rendered = "";
188 for (const { start, end, skill } of matchInlineSkills(value, skills)) {
189 rendered += value.slice(cursor, start) + formatProviderSkillDisplayName(skill);
190 cursor = end;
191 }
192 value = rendered + value.slice(cursor);
193 }
194 text += inPre ? value : value.replace(/\r\n|\r|\n/g, " ");
195 }
196 const renderSkills =
197 node.tagName === "code" || node.tagName === "a"
198 ? false
199 : inlineSkills || node.tagName === "p" || node.tagName === "li";
200 for (const child of node.children ?? [])
201 visit(child, inPre || node.tagName === "pre", renderSkills, inAnchor || node.tagName === "a");
202 if (block) flush();
203 };
204 visit(tree);
205 flush();
206 return segments;
207}
208
209/** Plans render `$skill` tokens literally (no skill chips), so they are indexed as written. */
210export function searchablePlanSegments(
211 markdown: string,
212 cwd?: string,
213 theme?: "dark" | "light",
214): readonly string[] {
215 return [
216 proposedPlanTitle(markdown) ?? "Proposed plan",
217 ...markdownThreadFindText(stripDisplayedPlanMarkdown(markdown), { cwd, theme }),
218 ];
219}
220
221export function searchableMessageSegments(
222 message: Pick<OrchestrationV2ConversationMessage, "role" | "text" | "streaming" | "context">,
223 cwd?: string,
224 skills: readonly InlineSkill[] = [],
225 theme?: "dark" | "light",
226): readonly string[] | null {
227 if (message.role === "user") {
228 // Clients hide this prompt, so find must not match text nobody can see.
229 if (isAttachmentOnlyBootstrapPrompt(message.text)) return [];
230 const text = message.context ? message.text : upgradeLegacyContextMessage(message.text).text;
231 return markdownThreadFindText(text, { userMessage: true, cwd, skills, theme });
232 }
233 if (message.role !== "assistant") return null;
234 const text =
235 !message.streaming && message.text.trim().length === 0 ? "(empty response)" : message.text;
236 return markdownThreadFindText(text, {
237 cwd,
238 skills,
239 lineBreaks: shouldPreserveAssistantLineBreaks(message.text),
240 renderInsights: true,
241 theme,
242 });
243}