Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadFindText.ts

241 lines8.4 KB

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 extractMarkdownLinkHrefs,
18 extractInlineCodeSpans,
19 inlineCodeFilePathCandidate,
20 resolveMarkdownFileLink,
21 shouldRenderMarkdownImageAsFileLink,
22} from "./markdownLinks.ts";
23import { mediaKindFromPath } from "./mediaPreview.ts";
24import { upgradeLegacyContextMessage } from "./composerContextLegacy.ts";
25import {
26 isAttachmentOnlyBootstrapPrompt,
27 parseComposerContextHref,
28} from "./composerContextReferences.ts";
29import { parseAssistantCitationHref } from "./assistantCitations.ts";
30import type { OrchestrationV2ConversationMessage } from "@t3tools/contracts";
31import { proposedPlanTitle, stripDisplayedPlanMarkdown } from "./proposedPlanText.ts";
32import { unified } from "unified";
33import remarkParse from "remark-parse";
34import remarkRehype from "remark-rehype";
35import {
36 remarkAssistantInsights,
37 CHAT_MARKDOWN_REHYPE_PLUGINS,
38 CHAT_MARKDOWN_REMARK_PLUGINS,
39 CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
40 CHAT_USER_MARKDOWN_REMARK_PLUGINS,
41 chatMarkdownImageSource,
42 decodeMarkdownLinkEscapes,
43 type ChatMarkdownImageProperties,
44} from "./markdownPipeline.ts";
45​
46// Inline wrappers (including Shiki token spans) must not split a search phrase.
47​
48function assistantTextProcessor(lineBreaks = false, renderInsights = false) {
49 return unified()
50 .use(remarkParse)
51 .use(renderInsights ? [remarkAssistantInsights] : [])
52 .use(lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS)
53 .use(remarkRehype, { allowDangerousHtml: true })
54 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
56const assistantProcessor = assistantTextProcessor();
57const assistantBreaksProcessor = assistantTextProcessor(true);
58const insightProcessor = assistantTextProcessor(false, true);
59const insightBreaksProcessor = assistantTextProcessor(true, true);
60const userProcessor = unified()
61 .use(remarkParse)
62 .use(CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS)
63 .use(CHAT_USER_MARKDOWN_REMARK_PLUGINS)
64 .use(remarkRehype, { allowDangerousHtml: true });
65​
66interface TextTree {
67 readonly type: string;
68 readonly tagName?: string;
69 readonly value?: string;
70 readonly properties?: ChatMarkdownImageProperties & {
71 readonly href?: unknown;
72 readonly dataInlineCode?: unknown;
73 };
74 readonly children?: ReadonlyArray<TextTree>;
76​
77function markdownThreadFindText(
78 markdown: string,
79 {
80 userMessage = false,
81 cwd,
82 skills = [],
83 lineBreaks = false,
84 renderInsights = false,
85 theme,
86 }: {
87 userMessage?: boolean;
88 cwd: string | undefined;
89 skills?: readonly InlineSkill[];
90 lineBreaks?: boolean;
91 renderInsights?: boolean;
92 theme: "dark" | "light" | undefined;
93 },
94): string[] {
95 const processor = userMessage
96 ? userProcessor
97 : lineBreaks
98 ? assistantBreaksProcessor
99 : assistantProcessor;
100 const renderer = renderInsights
101 ? lineBreaks
102 ? insightBreaksProcessor
103 : insightProcessor
104 : processor;
105 const tree = renderer.runSync(renderer.parse(markdown), markdown);
106 const paths = [
107 ...extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(markdown)).map(
108 decodeMarkdownLinkEscapes,
109 ),
110 ...extractInlineCodeSpans(markdown).flatMap((span) => inlineCodeFilePathCandidate(span) ?? []),
111 ].flatMap((href) => {
112 const resolved = resolveMarkdownFileLink(href, cwd);
113 return resolved ? [resolved.position.path] : [];
114 });
115 const parentSuffixes = buildFileLinkParentSuffixByPath(paths);
116 const segments: string[] = [];
117 let text = "";
118 const flush = () => {
119 if (text.trim()) segments.push(text);
120 text = "";
121 };
122 const visit = (node: TextTree, inPre = false, inlineSkills = false) => {
123 const href = node.properties?.href ?? node.properties?.src;
124 if (userMessage && typeof href === "string" && parseComposerContextHref(href)) {
125 flush();
126 return;
127 }
128 const citation =
129 node.tagName === "a" && typeof href === "string" ? parseAssistantCitationHref(href) : null;
130 if (citation) {
131 // The quote card is not searched, and it splits the text before it from its comment.
132 flush();
133 text += (citation.comment ?? "").replace(/\r?\n/g, " ");
134 return;
135 }
136 {
137 let candidate: string | null = null;
138 if (node.tagName === "a" && typeof href === "string") {
139 candidate = href;
140 } else if (node.tagName === "img") {
141 const source = chatMarkdownImageSource(node.properties, theme);
142 if (source) {
143 const { authoredSrc, classifiedSrc } = source;
144 if (
145 shouldRenderMarkdownImageAsFileLink(
146 classifyMarkdownImageSource(classifiedSrc, cwd),
147 mediaKindFromPath(classifiedSrc),
148 )
149 ) {
150 candidate = authoredSrc;
151 }
152 }
153 } else if (
154 node.tagName === "code" &&
155 !inPre &&
156 node.properties?.dataInlineCode !== undefined
157 ) {
158 candidate = inlineCodeFilePathCandidate(
159 (node.children ?? []).map((child) => child.value ?? "").join(""),
160 );
161 }
162 const resolved = candidate ? resolveMarkdownFileLink(candidate, cwd) : null;
163 if (candidate && resolved) {
164 const labelText = (node: TextTree): string =>
165 node.value ?? (node.children ?? []).map(labelText).join("");
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/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);
202 if (block) flush();
203 };
204 visit(tree);
205 flush();
206 return segments;
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 ];
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 return markdownThreadFindText(message.text || (message.streaming ? "" : "(empty response)"), {
235 cwd,
236 skills,
237 lineBreaks: shouldPreserveAssistantLineBreaks(message.text),
238 renderInsights: true,
239 theme,
240 });