feat(web): find messages and plans in the current thread #10439
MergedNoojuno(GitHub profile, opens in a new tab)merged 30 commits into
main fromrefs/pull/10439/headmerged by Yash-Singh1(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/web/src/components/chat/ThreadFindBar.tsx line 64OutdatedResolvedby Noojuno(GitHub profile, opens in a new tab)@@ -0,0 +44,21 @@44+45+ if (!props.open) return null;46+47+ const hasQuery = props.query.trim().length > 0;48+ const noResults = hasQuery && props.matchCount === 0;49+ const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {50+ if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return;51+ if (event.key === "Enter") {52+ event.preventDefault();53+ event.stopPropagation();54+ if (event.shiftKey) props.onPrevious();55+ else props.onNext();56+ }57+ };58+59+ return (60+ <InputGroup61+ variant="default"62+ role="search"63+ aria-label="Find in thread"64+ className="absolute top-[calc(100%+0.5rem)] right-0 z-40 h-9 w-[min(24rem,calc(100vw-1.5rem))] bg-popover shadow-sm dark:bg-popover [-webkit-app-region:no-drag]"
- apps/web/src/components/chat/ProposedPlanCard.tsx line 198OutdatedResolvedby Noojuno(GitHub profile, opens in a new tab)@@ -170,5 +173,6 @@170173 </Menu>171174 </div>172175 <div className="mt-4">173- <div className={cn("relative", canCollapse && !expanded && "max-h-104 overflow-hidden")}>174- {canCollapse && !expanded ? (176+ <div177+ className={cn("relative", isCollapsed && "max-h-104 overflow-hidden")}178+ data-thread-find-text="true"apps/web/src/components/chat/ProposedPlanCard.tsx line 198OutdatedResolvedby Noojuno(GitHub profile, opens in a new tab)@@ -170,5 +173,6 @@170173 </Menu>171174 </div>172175 <div className="mt-4">173- <div className={cn("relative", canCollapse && !expanded && "max-h-104 overflow-hidden")}>174- {canCollapse && !expanded ? (176+ <div177+ className={cn("relative", isCollapsed && "max-h-104 overflow-hidden")}178+ data-thread-find-text="true"
- apps/web/src/components/chat/threadFind.ts lines 21 to 35OutdatedResolvedby Noojuno(GitHub profile, opens in a new tab)@@ -0,0 +15,21 @@15+}16+17+/**18+ * Returns the conversation text represented by an entry. Work and lifecycle19+ * rows are intentionally excluded.20+ */21+export function searchableThreadEntryText(entry: TimelineEntry): string | null {22+ if (entry.kind === "proposed-plan") {23+ return stripDisplayedPlanMarkdown(entry.proposedPlan.planMarkdown);24+ }25+ if (entry.kind !== "message") return null;26+ if (entry.message.role === "user") {27+ const displayed = deriveDisplayedUserMessageContent(entry.message.text);28+ return displayed.terminalContexts.reduce(29+ (text, context) => text.replaceAll(formatInlineTerminalContextLabel(context.header), ""),30+ displayed.visibleText,31+ );32+ }33+ if (entry.message.role !== "assistant") return null;34+ return entry.message.text || (entry.message.streaming ? "" : "(empty response)");35+}
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/components/ChatView.tsx line 5932OutdatedResolvedby Noojuno(GitHub profile, opens in a new tab)@@ -5879,0 +5912,21 @@5912+ threadKey: activeThreadKey,5913+ focusRequestId,5914+ };5915+ });5916+ }, [activeThreadKey]);5917+ const closeThreadFind = useCallback(() => setFindState(CLOSED_CHAT_FIND_STATE), []);5918+ const changeThreadFindQuery = useCallback((query: string) => {5919+ setFindState((state) => ({ ...state, query, activeIndex: 0 }));5920+ }, []);5921+ const isThreadFindActive = activeThreadKey !== null && findState.threadKey === activeThreadKey;5922+ const threadFindHistoryState = useThreadFindHistory(5923+ isThreadFindActive && findState.query.trim()5924+ ? `${activeThreadKey}:${findState.focusRequestId}`5925+ : null,5926+ loadEarlierTurns,5927+ );5928+ const threadFindMatches = useMemo(5929+ () =>5930+ buildThreadFindMatches(5931+ timelineEntries,5932+ isThreadFindActive && !threadFindHistoryState ? findState.query : "",
- apps/web/src/components/chat/ThreadFindBar.tsx line 66OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +44,21 @@44+ return () => window.removeEventListener("keydown", closeOnEscape);45+ }, [onClose, open]);46+47+ if (!props.open) return null;48+49+ const hasQuery = props.query.trim().length > 0;50+ const noResults = hasQuery && !props.historyState && props.matchCount === 0;51+ const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {52+ if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return;53+ if (event.key === "Enter") {54+ event.preventDefault();55+ event.stopPropagation();56+ if (event.shiftKey) props.onPrevious();57+ else props.onNext();58+ }59+ };60+61+ return (62+ <InputGroup63+ variant="popover"64+ role="search"
- apps/web/src/components/chat/MessagesTimeline.tsx line 162OutdatedResolvedby Noojuno(GitHub profile, opens in a new tab)@@ -154,15 +154,9 @@154154 } from "./MessagesTimeline.logic";155+import { type ThreadFindMatch } from "./threadFind";156+import { useThreadFindHighlights } from "./threadFindHighlights";155157 import { TerminalContextInlineChip } from "./TerminalContextInlineChip";156158 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";157-import {158- deriveDisplayedUserMessageState,159- type ParsedTerminalContextEntry,160-} from "~/lib/terminalContext";161-import {162- extractTrailingElementContexts,163- type ParsedElementContextEntry,164-} from "~/lib/elementContext";165-import {166- extractTrailingPreviewAnnotation,167- type ParsedPreviewAnnotation,168-} from "~/lib/previewAnnotation";159+import { type ParsedTerminalContextEntry } from "~/lib/terminalContext";160+import { type ParsedElementContextEntry } from "~/lib/elementContext";161+import { type ParsedPreviewAnnotation } from "~/lib/previewAnnotation";162+import { deriveDisplayedUserMessageContent } from "~/lib/visibleMessageText";apps/web/src/components/ChatView.tsx line 6092OutdatedResolvedby Noojuno(GitHub profile, opens in a new tab)@@ -5980,3 +6089,4 @@59806089 return;59816090 }598260916092+ if (command === "chat.find") {
- apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts line 3404OutdatedResolvedby Noojuno(GitHub profile, opens in a new tab)@@ -3396,3 +3398,7 @@33963398 ),33973399 );339834003401+ const searchThread = yield* makeThreadFindQuery(3402+ Effect.fn("ThreadFindQuery.sequence")(function* (threadId) {3403+ const { snapshotSequence } = yield* getSnapshotSequence();3404+ const row = yield* getThreadEventWatermarkRow({apps/web/src/components/chat/threadFind.ts line 56OutdatedResolvedby Noojuno(GitHub profile, opens in a new tab)@@ -0,0 +36,21 @@36+}37+38+function threadEntryTurnId(entry: TimelineEntry): TurnId | null {39+ if (entry.kind === "message") return entry.message.turnId ?? null;40+ if (entry.kind === "proposed-plan") return entry.proposedPlan.turnId;41+ return null;42+}43+44+export function buildThreadFindMatches(45+ entries: ReadonlyArray<TimelineEntry>,46+ query: string,47+): ThreadFindMatch[] {48+ const normalizedQuery = query.trim();49+ if (normalizedQuery.length === 0) return [];50+51+ const matches: ThreadFindMatch[] = [];52+ for (const entry of entries) {53+ const segments = searchableThreadEntrySegments(entry);54+ if (segments === null) continue;55+56+ const total = segments.reduce(apps/web/src/components/CommandPaletteResults.tsx line 21OutdatedResolvedby Noojuno(GitHub profile, opens in a new tab)@@ -38,20 +21 @@38- if (matchIndex === -1) {39- parts.push({ text: props.text.slice(cursor), highlighted: false, start: cursor });40- break;41- }42- if (matchIndex > cursor) {43- parts.push({44- text: props.text.slice(cursor, matchIndex),45- highlighted: false,46- start: cursor,47- });48- }49- parts.push({50- text: props.text.slice(matchIndex, matchIndex + query.length),51- highlighted: true,52- start: matchIndex,53- });54- cursor = matchIndex + query.length;55- }56-57- return parts.map((part) =>21+ return splitThreadSearchText(props.text, props.query).map((part) =>
- packages/shared/src/fileLinks.ts lines 83 to 83OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +63,21 @@63+64+function joinPath(base: string, next: string, separator: "/" | "\\"): string {65+ const cleanBase = base.replace(/[\\/]+$/, "");66+ if (separator === "\\") {67+ return `${cleanBase}\\${next.replaceAll("/", "\\")}`;68+ }69+ return `${cleanBase}/${next.replace(/^\/+/, "")}`;70+}71+72+function inferHomeFromCwd(cwd: string): string | undefined {73+ const posixUser = cwd.match(/^\/Users\/([^/]+)/);74+ if (posixUser?.[1]) {75+ return `/Users/${posixUser[1]}`;76+ }77+78+ const posixHome = cwd.match(/^\/home\/([^/]+)/);79+ if (posixHome?.[1]) {80+ return `/home/${posixHome[1]}`;81+ }82+83+ const windowsUser = cwd.match(/^([A-Za-z]:\\Users\\[^\\]+)/);apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts line 3772OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3757,3 +3759,14 @@37573759 ),37583760 );375937613762+ // Unlike the detail subscription watermark, a search index must include lifecycle3763+ // events: creating a previously deleted ID resets all of its projected messages.3764+ const getThreadSearchSequence = SqlSchema.findOne({3765+ Request: Schema.Struct({ threadId: ThreadId, maxSequence: Schema.Number }),3766+ Result: Schema.Struct({ sequence: Schema.NullOr(Schema.Number) }),3767+ execute: ({ threadId, maxSequence }) => sql`3768+ SELECT MAX(sequence) AS sequence FROM orchestration_events3769+ WHERE aggregate_kind = 'thread' AND stream_id = ${threadId}3770+ AND sequence <= ${maxSequence}`,3771+ });3772+ const searchThread = yield* makeThreadFindQuery(
juliusmarminge closed this
juliusmarminge reopened this
juliusmarminge added labelsaccepted
juliusmarminge added labelstriage:keep-open
- packages/shared/src/threadSearch.ts lines 23 to 23Resolvedby Noojuno(GitHub profile, opens in a new tab)@@ -0,0 +3,21 @@3+ readonly highlighted: boolean;4+ readonly start: number;5+}6+7+function foldThreadSearchCase(text: string): string {8+ const lowered = text.toLowerCase().replace(/ς/g, "σ");9+ if (lowered.length === text.length) return lowered;10+11+ let folded = "";12+ for (const character of text) {13+ const loweredCharacter = character.toLowerCase().replace(/ς/g, "σ");14+ folded += loweredCharacter.length === character.length ? loweredCharacter : character;15+ }16+ return folded;17+}18+19+function scanThreadSearchOccurrences(text: string, query: string, offsets?: number[]): number {20+ if (text.length === 0 || query.length === 0) return 0;21+22+ const foldedText = foldThreadSearchCase(text);23+ const foldedQuery = foldThreadSearchCase(query);apps/web/src/components/ChatMarkdown.tsx line 713Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -901,5 +699,5 @@901699 return (902700 <div className="my-2 border-y border-border/60">903701 <Collapsible904- defaultOpen={open}702+ open={expanded}905703 onOpenChange={setIsOpen}packages/shared/src/threadFindText.ts line 91OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +71,21 @@71+ .use(CHAT_MARKDOWN_REHYPE_PLUGINS);72+const userProcessor = unified()73+ .use(remarkParse)74+ .use(CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS)75+ .use(remarkRehype, { allowDangerousHtml: true });76+77+interface TextTree {78+ readonly type: string;79+ readonly tagName?: string;80+ readonly value?: string;81+ readonly properties?: {82+ readonly href?: unknown;83+ readonly src?: unknown;84+ readonly dataInlineCode?: unknown;85+ };86+ readonly children?: ReadonlyArray<TextTree>;87+}88+89+/** Uses the renderer's Markdown transforms, without mounting folded/virtualized rows. */90+function markdownThreadFindText(markdown: string, userMessage = false, cwd?: string): string[] {91+ const processor = userMessage ? userProcessor : assistantProcessor;apps/server/src/orchestration-v2/ProjectionStore.ts line 6278OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -6257,3 +6270,9 @@62576270 ),62586271 ),62596272 ),6273+ searchThread: (input) =>6274+ service6275+ .getThreadSnapshot(input.threadId)6276+ .pipe(6277+ Effect.map((snapshot) =>6278+ findProjectedThreadItems(apps/server/src/orchestration-v2/ProjectionStore.ts lines 6274 to 6284OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -6257,3 +6270,15 @@62576270 ),62586271 ),62596272 ),6273+ searchThread: (input) =>6274+ service6275+ .getThreadSnapshot(input.threadId)6276+ .pipe(6277+ Effect.map((snapshot) =>6278+ findProjectedThreadItems(6279+ snapshot.projection.visibleTurnItems,6280+ input,6281+ snapshot.snapshotSequence,6282+ ),6283+ ),6284+ ),packages/shared/src/threadFindText.ts line 203Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +129,21 @@129+ }130+ const target = candidate ? resolveMarkdownFileLinkTarget(candidate, cwd) : null;131+ if (target) {132+ const labelText = (node: TextTree): string =>133+ node.value ?? (node.children ?? []).map(labelText).join("");134+ const label = labelText(node);135+ if (node.tagName === "a" && candidate && !isMarkdownFileLinkLabel(label, candidate))136+ text += `${label} `;137+ text += fileLinkLabel(splitFilePathPosition(target), parentSuffixes);138+ return;139+ }140+ }141+ const block = THREAD_FIND_BLOCK_TAGS.has(node.tagName ?? "");142+ if (block) flush();143+ if (node.type === "text" || (userMessage && node.type === "raw")) {144+ text += inPre ? (node.value ?? "") : (node.value ?? "").replace(/\r?\n/g, " ");145+ }146+ for (const child of node.children ?? []) visit(child, inPre || node.tagName === "pre");147+ if (block) flush();148+ };149+ visit(tree);
- apps/web/src/components/chat/useThreadFindNavigation.ts line 254Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +85,21 @@85+ return;86+ }87+ const scroll = listRef.current?.getState?.().scroll;88+ positionedEntriesRef.current = entries;89+ revealedMatchRef.current = matchKey;90+ if (Math.abs(delta) >= 1 && typeof scroll === "number") {91+ listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });92+ }93+ },94+ [95+ container,96+ contentInsetEndAdjustment,97+ entries,98+ listRef,99+ matchKey,100+ positionedMatchKey,101+ rowIndex,102+ ],103+ );104+105+ useThreadFindHighlights({@@ -1888,3 +1890,6 @@18881890 }),18891891 ),18901892 ),1893+ [ORCHESTRATION_V2_WS_METHODS.searchThread]: (input) =>1894+ threadManagement1895+ .searchThread(input)
- apps/web/src/components/chat/useThreadFindNavigation.ts lines 76 to 77OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +57,21 @@57+ setPositionedMatchKey(matchKey);58+ });59+ };60+ if (!range) {61+ if (container) materialize();62+ return;63+ }64+65+ const codeScroller = range.startContainer.parentElement?.closest("pre");66+ if (codeScroller) {67+ const rect = range.getBoundingClientRect();68+ const viewport = codeScroller.getBoundingClientRect();69+ if (rect.left < viewport.left) codeScroller.scrollLeft += rect.left - viewport.left - 16;70+ else if (rect.right > viewport.right)71+ codeScroller.scrollLeft += rect.right - viewport.right + 16;72+ }73+ const rect = range.getBoundingClientRect();74+ const viewport = container?.getBoundingClientRect();75+ if (!viewport || rect.height === 0) return;76+ const top = viewport.top + FIND_MATCH_VIEW_MARGIN;77+ const bottom = viewport.bottom - FIND_MATCH_VIEW_MARGIN - contentInsetEndAdjustment;
- apps/web/src/components/chat/useThreadFind.ts lines 80 to 85OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +65,21 @@65+ isOpen ? thread : null,66+ state.query,67+ state.activeIndex,68+ state.navigationId,69+ state.start,70+ content,71+ skills,72+ );73+ const status: "loading" | "error" | null = remote.error74+ ? "error"75+ : remote.isPending && remote.data === null76+ ? "loading"77+ : null;78+ const count = remote.data?.totalMatches ?? 0;79+ const activeIndex = remote.data?.activeIndex ?? 0;80+ const step = (delta: number) =>81+ setState((previous) => ({82+ ...previous,83+ activeIndex: stepThreadFindIndex(previous.activeIndex ?? activeIndex, count, delta),84+ navigationId: previous.navigationId + 1,85+ }));apps/web/src/components/chat/MessagesTimeline.tsx line 4603OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4450,9 +4594,10 @@44504594 renderContextReference: (reference: ChatMarkdownContextReference) => ReactNode;44514595 skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;44524596 markdownCwd: string | undefined;4597+ expandForFind?: boolean;44534598 footer?: ReactNode;44544599 }) {44554600 const [expanded, setExpanded] = useState(false);44564601 const hasVisibleBody = props.text.trim().length > 0;44574602 const canCollapse = hasVisibleBody && shouldCollapseUserMessage(props.text);4458- const isCollapsed = canCollapse && !expanded;4603+ const isCollapsed = canCollapse && !expanded && !props.expandForFind;
Sign in to join this conversation.
Approvability#
Verdict: Not approved
Macroscope's review found this PR not approvable — This PR adds a substantial cross-layer find-in-thread capability with new server RPCs, projection searches, progressive history loading, virtualized navigation, Markdown indexing, and theme integration. It also changes the default
mod+fproduct behavior, so the scope and customer policy require human review.Not approved because:
- Per-PR cost limit exceeded (workspace setting). Approvability relies on correctness review in order to determine eligibility
Review your spending limits in [Billing settings](https://app.macroscope.com/pingdotgg/settings/billing), or comment `@macroscope-app review this PR` to bypass the limit and review now. You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).