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 visit = (node: TextTree, inPre = false, inlineSkills = false) => {
124 const href = node.properties?.href ?? node.properties?.src;
125 if (userMessage && typeof href === "string" && parseComposerContextHref(href)) {
126 flush();
127 return;
128 }
129 const citation =
130 node.tagName === "a" && typeof href === "string" ? parseAssistantCitationHref(href) : null;
131 if (citation) {
132 // The quote card is not searched, and it splits the text before it from its comment.
133 flush();
134 text += (citation.comment ?? "").replace(/\r?\n/g, " ");
135 return;
136 }
137 {
138 let candidate: string | null = null;
139 if (node.tagName === "a" && typeof href === "string") {
140 candidate = href;
141 } else if (node.tagName === "img") {
142 const source = chatMarkdownImageSource(node.properties, theme);
143 if (source) {
144 const { authoredSrc, classifiedSrc } = source;
145 if (
146 shouldRenderMarkdownImageAsFileLink(
147 classifyMarkdownImageSource(classifiedSrc, cwd),
148 mediaKindFromPath(classifiedSrc),
149 )
150 ) {
151 candidate = authoredSrc;
152 }
153 }
154 } else if (
155 node.tagName === "code" &&
156 !inPre &&
157 node.properties?.dataInlineCode !== undefined
158 ) {
159 candidate = inlineCodeFilePathCandidate(
160 (node.children ?? []).map((child) => child.value ?? "").join(""),
161 );
162 }
163 const resolved = candidate ? resolveMarkdownFileLink(candidate, cwd) : null;
164 if (candidate && resolved) {
165 const labelText = (node: TextTree): string =>
166 node.value ?? (node.children ?? []).map(labelText).join("");
167 const label = labelText(node);
168 if (node.tagName === "a" && !isMarkdownFileLinkLabel(label, candidate)) text += `${label} `;
169 text += fileLinkLabel(resolved.position, parentSuffixes);
170 return;
171 }
172 }
173 const template = artifactTemplateFromHastProperties(node.properties);
174 if (template) {
175 flush();
176 segments.push(
177 template.displayName,
178 codexArtifactTemplatePresentationLabel(template.artifactKind),
179 );
180 return;
181 }
182 const block = THREAD_FIND_BLOCK_TAGS.has(node.tagName ?? "");
183 if (block) flush();
184 if (node.type === "text" || (userMessage && node.type === "raw")) {
185 let value = node.value ?? "";
186 if (inlineSkills) {
187 let cursor = 0;
188 let rendered = "";
189 for (const { start, end, skill } of matchInlineSkills(value, skills)) {
190 rendered += value.slice(cursor, start) + formatProviderSkillDisplayName(skill);
191 cursor = end;
192 }
193 value = rendered + value.slice(cursor);
194 }
195 text += inPre ? value : value.replace(/\r\n|\r|\n/g, " ");
196 }
197 const renderSkills =
198 node.tagName === "code" || node.tagName === "a"
199 ? false
200 : inlineSkills || node.tagName === "p" || node.tagName === "li";
201 for (const child of node.children ?? [])
202 visit(child, inPre || node.tagName === "pre", renderSkills);
203 if (block) flush();
204 };
205 visit(tree);
206 flush();
207 return segments;
208}
209
210/** Plans render `$skill` tokens literally (no skill chips), so they are indexed as written. */
211export function searchablePlanSegments(
212 markdown: string,
213 cwd?: string,
214 theme?: "dark" | "light",
215): readonly string[] {
216 return [
217 proposedPlanTitle(markdown) ?? "Proposed plan",
218 ...markdownThreadFindText(stripDisplayedPlanMarkdown(markdown), { cwd, theme }),
219 ];
220}
221
222export function searchableMessageSegments(
223 message: Pick<OrchestrationV2ConversationMessage, "role" | "text" | "streaming" | "context">,
224 cwd?: string,
225 skills: readonly InlineSkill[] = [],
226 theme?: "dark" | "light",
227): readonly string[] | null {
228 if (message.role === "user") {
229 // Clients hide this prompt, so find must not match text nobody can see.
230 if (isAttachmentOnlyBootstrapPrompt(message.text)) return [];
231 const text = message.context ? message.text : upgradeLegacyContextMessage(message.text).text;
232 return markdownThreadFindText(text, { userMessage: true, cwd, skills, theme });
233 }
234 if (message.role !== "assistant") return null;
235 const text =
236 !message.streaming && message.text.trim().length === 0 ? "(empty response)" : message.text;
237 return markdownThreadFindText(text, {
238 cwd,
239 skills,
240 lineBreaks: shouldPreserveAssistantLineBreaks(message.text),
241 renderInsights: true,
242 theme,
243 });
244}