@devries-cameron20 / t3code-1 / commits / 3b199e77fb
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix: index displayed file line ranges in thread search (#39308)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 19, 2026 at 21:29 UTC 3b199e77fb42556852648b50b545eebaec8c9430
13 files changed +374 -154
apps/server/src/orchestration-v2/ThreadFind.test.ts
+31
@@ -463,6 +463,37 @@ describe("V2 thread find", () => {
463 }).pipe(Effect.provide(layerTest)),
464 );
465
466 + it.effect("searches only the picture file chips visible in the viewer's theme", () =>
467 + Effect.gen(function* () {
468 + const projection = yield* setup;
469 + yield* putItems([
470 + item(
471 + "picture",
472 + 1,
473 + '<picture><source media="(prefers-color-scheme: dark)" srcset="/workspace/repo/notes.ts#L42-L64"><img src="/workspace/repo/screenshot.png" alt="notes"></picture>',
474 + ),
475 + item(
476 + "fallback",
477 + 2,
478 + '<picture><source media="(prefers-color-scheme: dark)" srcset="/workspace/repo/dark.png"><img src="/workspace/repo/fallback.ts#L42-L64" alt="notes"></picture>',
479 + ),
480 + ]);
481 + const dark = { threadId, query: "L42–64", theme: "dark" } as const;
482 + const light = { ...dark, theme: "light" } as const;
483 + const darkResult = yield* projection.searchThread(dark);
484 + assert.equal(darkResult.totalMatches, 1);
485 + assert.equal(darkResult.match?.entryId, "picture");
486 + assert.equal(
487 + (yield* projection.searchThread({ ...light, query: "notes.ts" })).totalMatches,
488 + 0,
489 + );
490 + const lightResult = yield* projection.searchThread(light);
491 + assert.equal(lightResult.totalMatches, 1);
492 + assert.equal(lightResult.match?.entryId, "fallback");
493 + assert.equal((yield* projection.searchThread(dark)).match?.entryId, "picture");
494 + }).pipe(Effect.provide(layerTest)),
495 + );
496 +
497 it.effect("refreshes file labels when the project cwd changes without a thread event", () =>
498 Effect.gen(function* () {
499 const projection = yield* setup;
apps/server/src/orchestration-v2/ThreadFind.ts
+10 -3
@@ -72,12 +72,14 @@ class TextKey extends Data.Class<{
72 hasContext: boolean;
73 cwd: string | undefined;
74 skills: NonNullable<OrchestrationV2SearchThreadInput["skills"]>;
75 + theme: OrchestrationV2SearchThreadInput["theme"];
76 }> {}
77
78 function textKey(
79 item: OrchestrationV2TurnItem,
80 cwd: string | undefined,
81 skills: TextKey["skills"],
82 + theme: TextKey["theme"],
83 ) {
84 return new TextKey({
85 text:
@@ -92,12 +94,13 @@ function textKey(
94 hasContext: item.type === "user_message" && item.context !== undefined,
95 cwd,
96 skills,
97 + theme,
98 });
99 }
100
101 function parseText(key: TextKey): readonly string[] {
102 return key.role === "plan"
100 - ? searchablePlanSegments(key.text, key.cwd)
103 + ? searchablePlanSegments(key.text, key.cwd, key.theme)
104 : (searchableMessageSegments(
105 {
106 role: key.role,
@@ -107,6 +110,7 @@ function parseText(key: TextKey): readonly string[] {
110 },
111 key.cwd,
112 key.skills,
113 + key.theme,
114 ) ?? []);
115 }
116
@@ -207,6 +211,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
211 cwd: Schema.optional(Schema.String),
212 query: Schema.optional(Schema.String),
213 skills: OrchestrationV2SearchThreadInput.fields.skills,
214 + theme: OrchestrationV2SearchThreadInput.fields.theme,
215 }),
216 ),
217 );
@@ -309,7 +314,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
314 scans: CompletedScans,
315 renderedSnapshot: RenderedSnapshot,
316 ) {
312 - const { threadId } = input;
317 + const { threadId, theme } = input;
318 const active = yield* sql<{ cwd: string | null }>`
319 SELECT COALESCE(json_extract(t.payload_json, '$.worktreePath'), p.workspace_root) AS cwd
320 FROM orchestration_v2_projection_threads t JOIN projection_projects p ON p.project_id = t.project_id
@@ -322,6 +327,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
327 cwd,
328 query: input.query,
329 skills: input.skills ?? [],
330 + ...(theme === undefined ? {} : { theme }),
331 });
332 const cached = scans.get(cacheKey);
333 if (cached && cached.sequence === (yield* readRevision(cached.sourceThreadIds))) {
@@ -334,6 +340,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
340 threadId,
341 cwd,
342 skills: input.skills ?? [],
343 + ...(theme === undefined ? {} : { theme }),
344 });
345 const rendered = renderedSnapshot.current;
346 if (
@@ -449,7 +456,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
456 rendered = row;
457 } else {
458 const decoded = yield* decode(row);
452 - const key = textKey(decoded.item, cwd, input.skills ?? []);
459 + const key = textKey(decoded.item, cwd, input.skills ?? [], input.theme);
460 const segments =
461 decoded.item.type === "assistant_message" &&
462 decoded.item.text === "" &&
apps/web/src/components/ChatMarkdown.tsx
+6 -11
@@ -5,7 +5,9 @@ import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
5 import { clientHostEnvironmentAtom } from "../state/clientHostEnvironment";
6 import { buildFileLinkParentSuffixByPath, fileLinkLabel } from "@t3tools/shared/fileLinks";
7 import {
8 + isMarkdownFileLinkLabel,
9 isWindowsDrivePathHref,
10 + shouldRenderMarkdownImageAsFileLink,
11 normalizeMarkdownLinkDestination,
12 extractInlineCodeSpans,
13 extractMarkdownLinkHrefs,
@@ -23,6 +25,7 @@ import {
25 CHAT_MARKDOWN_REMARK_PLUGINS,
26 CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
27 CHAT_MARKDOWN_REHYPE_PLUGINS,
28 + chatMarkdownImageSource,
29 decodeMarkdownLinkEscapes,
30 remarkAssistantInsights,
31 } from "@t3tools/shared/markdownPipeline";
@@ -156,7 +159,6 @@ import {
159 markdownFileEditorTarget,
160 resolveMarkdownFileHostPath,
161 } from "../markdownFileHostPath";
159 -import { isMarkdownFileLinkLabel } from "@t3tools/shared/markdownLinks";
162 import { isElectron } from "../env";
163 import { readLocalApi } from "../localApi";
164 import { appAtomRegistry } from "../rpc/atomRegistry";
@@ -1586,18 +1588,11 @@ const CHAT_MARKDOWN_COMPONENTS = {
1588 <span>{label}</span>
1589 );
1590 }
1589 - // A `<picture>`'s source for this theme, resolved like any other image.
1590 - const themeSrc = node?.properties?.[resolvedTheme === "dark" ? "dataDarkSrc" : "dataLightSrc"];
1591 - const localSrc = typeof themeSrc === "string" ? undefined : node?.properties?.dataLocalSrc;
1591 + const { authoredSrc: srcString = "", classifiedSrc = "" } =
1592 + chatMarkdownImageSource(node?.properties ?? { src }, resolvedTheme) ?? {};
1593 const markdownTitle = node?.properties?.dataMarkdownTitle;
1594 const standalone = node?.properties?.dataStandalone === true;
1594 - const authoredSrc =
1595 - typeof themeSrc === "string" ? themeSrc : typeof localSrc === "string" ? localSrc : src;
1595 const authoredTitle = typeof markdownTitle === "string" ? markdownTitle : title;
1597 - const srcString =
1598 - typeof authoredSrc === "string" ? normalizeMarkdownLinkDestination(authoredSrc) : "";
1599 - const classifiedSrc =
1600 - typeof localSrc === "string" ? srcString.replaceAll("\\", "/") : srcString;
1596 const altText = alt ?? "";
1597 const copyMarkdown = markdownImageCopy(altText, srcString, authoredTitle);
1598 const { className, style: _style, width, height, ...imageProps } = props;
@@ -1634,7 +1629,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
1629 />
1630 );
1631 }
1637 - if (mediaKind === null && imageSource._tag === "WorkspaceFile") {
1632 + if (shouldRenderMarkdownImageAsFileLink(imageSource, mediaKind)) {
1633 const fileLinkMeta = resolveMarkdownFileLinkMeta(srcString, cwd, imageBaseDir ?? cwd);
1634 if (fileLinkMeta) return fileLinkChip(fileLinkMeta, copyMarkdown, srcString);
1635 }
apps/web/src/components/chat/threadFindStore.ts
+2
@@ -10,9 +10,11 @@ import {
10 messageSearchTokens,
11 } from "@t3tools/shared/paletteSearch";
12 import { create } from "zustand";
13 +import type { ThemeAppearance } from "~/themePalette";
14 import type { ThreadFindPositionReader, ThreadFindStart } from "./threadFind";
15
16 export interface ThreadFindLocalSelection {
17 + readonly theme: ThemeAppearance;
18 readonly base: OrchestrationV2SearchThreadResult;
19 readonly baseNavigationId: number;
20 readonly activeIndex: number;
apps/web/src/components/chat/useThreadFind.ts
+22 -4
@@ -3,9 +3,11 @@ import type { OrchestrationV2SearchThreadResult, ScopedThreadRef } from "@t3tool
3 import { scopedThreadKey } from "@t3tools/client-runtime/environment";
4 import { useEffect, useEffectEvent, useRef, useState } from "react";
5 import { orchestrationEnvironment } from "~/state/orchestration";
6 +import { useRenderedAppearance } from "~/hooks/useTheme";
7 import { useThreadProjection } from "~/state/entities";
8 import { useEnvironmentQuery } from "~/state/query";
9 import { useDebouncedValue } from "~/state/queries";
10 +import type { ThemeAppearance } from "~/themePalette";
11 import { type ThreadFindMatch, type ThreadFindStart, stepThreadFindIndex } from "./threadFind";
12 import {
13 CLOSED_THREAD_FIND,
@@ -40,6 +42,11 @@ export function useThreadFind({
42 const isOpen = useThreadFindOpen(thread, enabled);
43 const stored = useThreadFindStore();
44 const state = isOpen ? stored : CLOSED_THREAD_FIND;
45 + const theme = useRenderedAppearance();
46 + const requestId =
47 + state.localSelection && state.localSelection.theme !== theme
48 + ? state.navigationId
49 + : state.requestId;
50 const setState = (update: (previous: ThreadFindState) => Partial<ThreadFindState>) =>
51 useThreadFindStore.setState((previous) =>
52 previous.threadKey === threadKey ? update(previous) : previous,
@@ -49,10 +56,11 @@ export function useThreadFind({
56 isOpen ? thread : null,
57 state.query,
58 state.offset,
52 - state.requestId,
59 + requestId,
60 state.start,
61 skills,
62 progressive,
63 + theme,
64 );
65 const status: "loading" | "error" | null = remote.error
66 ? "error"
@@ -63,6 +71,7 @@ export function useThreadFind({
71 state.localSelection,
72 remote.data,
73 remote.navigationId,
74 + theme,
75 );
76 const count = remote.data?.totalMatches ?? 0;
77 const activeIndex = localSelection?.activeIndex ?? remote.data?.activeIndex ?? 0;
@@ -95,7 +104,12 @@ export function useThreadFind({
104 const step = (delta: number) => {
105 if (count === 0 || counting) return;
106 setState((previous) => {
98 - const local = rebaseLocalSelection(previous.localSelection, remote.data, remote.navigationId);
107 + const local = rebaseLocalSelection(
108 + previous.localSelection,
109 + remote.data,
110 + remote.navigationId,
111 + theme,
112 + );
113 const pending = previous.navigationId !== (local?.navigationId ?? remote.navigationId);
114 const selected = local?.match ?? remote.data?.match;
115 const nextIndex = stepThreadFindIndex(
@@ -125,6 +139,7 @@ export function useThreadFind({
139 ...previous,
140 navigationId: nextNavigationId,
141 localSelection: {
142 + theme,
143 base: remote.data,
144 baseNavigationId: remote.navigationId,
145 activeIndex: nextIndex,
@@ -258,8 +273,9 @@ function rebaseLocalSelection(
273 selection: ThreadFindLocalSelection | null,
274 data: OrchestrationV2SearchThreadResult | null,
275 navigationId: number,
276 + theme: ThemeAppearance,
277 ) {
262 - if (!selection || !data) return null;
278 + if (!selection || !data || selection.theme !== theme) return null;
279 if (selection.base === data && selection.baseNavigationId === navigationId) return selection;
280 if (navigationId >= selection.navigationId) return null;
281 const entry = data.navigation?.find((entry) => entry.entryId === selection.match.entryId);
@@ -276,6 +292,7 @@ function useServerResults(
292 start: ThreadFindStart | undefined,
293 skills: readonly InlineSkill[],
294 progressive: boolean,
295 + theme: ThemeAppearance,
296 ) {
297 const skillLabels = skills.map(({ name, displayName }) => ({ name, displayName }));
298 const normalizedQuery = query.trim();
@@ -289,6 +306,7 @@ function useServerResults(
306 input: {
307 threadId,
308 query: debouncedQuery,
309 + theme,
310 ...(start ? { start } : {}),
311 ...(offset !== 0 ? { offset } : {}),
312 skills: skillLabels,
@@ -307,7 +325,7 @@ function useServerResults(
325 }
326 const result = useEnvironmentQuery(atom);
327 const key = thread
310 - ? JSON.stringify([thread.environmentId, thread.threadId, normalizedQuery, skillLabels])
328 + ? JSON.stringify([thread.environmentId, thread.threadId, normalizedQuery, skillLabels, theme])
329 : null;
330 const [previous, setPrevious] = useState({
331 key,
apps/web/src/markdown-links.ts
+15 -22
@@ -4,8 +4,7 @@ import {
4 inlineCodeFilePathCandidate,
5 isRelativeFilePath,
6 normalizeMarkdownLinkDestination,
7 - parseMarkdownFileLink,
8 - resolveMarkdownFileLinkTarget,
7 + resolveMarkdownFileLink,
8 } from "@t3tools/shared/markdownLinks";
9 import { parseFileUrlHref, splitFilePathPosition } from "@t3tools/shared/fileLinks";
10
@@ -76,31 +75,25 @@ export function resolveMarkdownFileLinkMeta(
75 cwd?: string,
76 baseDir: string | undefined = cwd,
77 ): MarkdownFileLinkMeta | null {
79 - const targetPath = resolveMarkdownFileLinkTarget(href, cwd, baseDir);
80 - if (!targetPath) return null;
81 - const source = href ? parseMarkdownFileLink(href) : null;
82 - return {
83 - ...buildFileLinkMetaFromTarget(targetPath, cwd),
84 - ...(source?.endLine !== undefined ? { endLine: source.endLine } : {}),
85 - workspaceLookupPath:
86 - source !== null &&
87 - !isAbsolutePath(source.path) &&
88 - baseDir !== undefined &&
89 - workspaceRelativeFilePath(baseDir, cwd) === "."
90 - ? source.path
91 - : null,
92 - };
93 -}
94 -
95 -function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string) {
96 - const { path, line, column } = splitFilePathPosition(targetPath);
78 + const resolved = resolveMarkdownFileLink(href, cwd, baseDir);
79 + if (!resolved) return null;
80 + const {
81 + sourcePath,
82 + targetPath,
83 + position: { path, ...lines },
84 + } = resolved;
85 return {
86 filePath: path,
87 targetPath,
88 displayPath: formatWorkspaceRelativePath(targetPath, cwd),
89 workspaceRelativePath: workspaceRelativeFilePath(path, cwd),
90 basename: fileBasename(path),
103 - ...(line !== undefined ? { line } : {}),
104 - ...(column !== undefined ? { column } : {}),
91 + ...lines,
92 + workspaceLookupPath:
93 + !isAbsolutePath(sourcePath) &&
94 + baseDir !== undefined &&
95 + workspaceRelativeFilePath(baseDir, cwd) === "."
96 + ? sourcePath
97 + : null,
98 };
99 }
packages/client-runtime/src/markdownImages.ts
+4 -64
@@ -1,73 +1,13 @@
1 import {
2 - isNetworkPath,
3 - isWindowsAbsolutePath,
4 - workspaceRelativeFilePath,
5 -} from "@t3tools/shared/path";
6 -
7 -import {
8 - markdownDestinationHostPath,
2 normalizeMarkdownLinkDestination,
3 splitMarkdownLinkSearchAndHash,
4 } from "@t3tools/shared/markdownLinks";
5
13 -const DIRECT_IMAGE_SOURCE_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i;
14 -const URI_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/;
15 -
16 -export type MarkdownImageSource =
17 - | { readonly _tag: "Direct"; readonly uri: string }
18 - | { readonly _tag: "WorkspaceFile"; readonly path: string; readonly relative?: true }
19 - | { readonly _tag: "Blocked" };
6 +export {
7 + classifyMarkdownImageSource,
8 + type MarkdownImageSource,
9 +} from "@t3tools/shared/markdownLinks";
10
11 export function markdownImageSourceFragment(source: string): string {
12 return splitMarkdownLinkSearchAndHash(normalizeMarkdownLinkDestination(source)).hash;
13 }
24 -
25 -function joinWorkspacePath(workspaceRoot: string, relativePath: string): string {
26 - const separator = isWindowsAbsolutePath(workspaceRoot) ? "\\" : "/";
27 - const root = workspaceRoot.replace(/[\\/]+$/, "");
28 - const path = relativePath.replace(/[\\/]/g, separator).replace(/^[\\/]+/, "");
29 - return `${root}${separator}${path}`;
30 -}
31 -
32 -/** Rendering is not a click, so a network path loads only from the project's own share. */
33 -function hostFileSource(
34 - path: string,
35 - workspaceRoot: string | null | undefined,
36 -): MarkdownImageSource {
37 - return isNetworkPath(path) && workspaceRelativeFilePath(path, workspaceRoot) === null
38 - ? { _tag: "Blocked" }
39 - : { _tag: "WorkspaceFile", path };
40 -}
41 -
42 -/**
43 - * Filesystem paths belong to the environment host and must never reach a
44 - * browser or native image component without first becoming a signed asset URL.
45 - */
46 -export function classifyMarkdownImageSource(
47 - value: string | null | undefined,
48 - workspaceRoot?: string | null,
49 -): MarkdownImageSource {
50 - if (value === null || value === undefined) return { _tag: "Blocked" };
51 -
52 - const source = normalizeMarkdownLinkDestination(value);
53 - if (source.length === 0 || source.startsWith("#") || source.startsWith("?")) {
54 - return { _tag: "Blocked" };
55 - }
56 - if (DIRECT_IMAGE_SOURCE_PATTERN.test(source)) {
57 - return { _tag: "Direct", uri: source };
58 - }
59 -
60 - const path = markdownDestinationHostPath(source);
61 - if (path === null) return { _tag: "Blocked" };
62 - if (/^file:/i.test(source)) return hostFileSource(path, workspaceRoot);
63 - if (path.length === 0) return { _tag: "Blocked" };
64 - if (path.startsWith("/") || isWindowsAbsolutePath(path)) {
65 - return hostFileSource(path, workspaceRoot);
66 - }
67 - if (URI_SCHEME_PATTERN.test(path) || path.startsWith("~/") || path.startsWith("~\\")) {
68 - return { _tag: "Blocked" };
69 - }
70 - if (!workspaceRoot) return { _tag: "Blocked" };
71 -
72 - return { _tag: "WorkspaceFile", path: joinWorkspacePath(workspaceRoot, path), relative: true };
73 -}
packages/contracts/src/orchestrationV2.ts
+1
@@ -4473,6 +4473,7 @@ export class OrchestrationGetWorkflowScriptError extends Schema.TaggedError<Orch
4473
4474 export const OrchestrationV2SearchThreadInput = Schema.Struct({
4475 threadId: ThreadId,
4476 + theme: Schema.optionalKey(Schema.Literals(["dark", "light"])),
4477 skills: Schema.optionalKey(
4478 Schema.Array(
4479 Schema.Struct({
packages/shared/src/markdownLinks.ts
+94 -3
@@ -1,3 +1,4 @@
1 +import type { mediaKindFromPath } from "./mediaPreview.ts";
2 import {
3 isNetworkPath,
4 isWindowsAbsolutePath,
@@ -285,6 +286,71 @@ export function markdownDestinationHostPath(source: string): string | null {
286 );
287 }
288
289 +const DIRECT_IMAGE_SOURCE_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i;
290 +const URI_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/;
291 +
292 +export type MarkdownImageSource =
293 + | { readonly _tag: "Direct"; readonly uri: string }
294 + | { readonly _tag: "WorkspaceFile"; readonly path: string; readonly relative?: true }
295 + | { readonly _tag: "Blocked" };
296 +
297 +function joinWorkspacePath(workspaceRoot: string, relativePath: string): string {
298 + const separator = isWindowsAbsolutePath(workspaceRoot) ? "\\" : "/";
299 + const root = workspaceRoot.replace(/[\\/]+$/, "");
300 + const path = relativePath.replace(/[\\/]/g, separator).replace(/^[\\/]+/, "");
301 + return `${root}${separator}${path}`;
302 +}
303 +
304 +/** Rendering is not a click, so a network path loads only from the project's own share. */
305 +function hostFileSource(
306 + path: string,
307 + workspaceRoot: string | null | undefined,
308 +): MarkdownImageSource {
309 + return isNetworkPath(path) && workspaceRelativeFilePath(path, workspaceRoot) === null
310 + ? { _tag: "Blocked" }
311 + : { _tag: "WorkspaceFile", path };
312 +}
313 +
314 +/**
315 + * Filesystem paths belong to the environment host and must never reach a
316 + * browser or native image component without first becoming a signed asset URL.
317 + */
318 +export function classifyMarkdownImageSource(
319 + value: string | null | undefined,
320 + workspaceRoot?: string | null,
321 +): MarkdownImageSource {
322 + if (value === null || value === undefined) return { _tag: "Blocked" };
323 +
324 + const source = normalizeMarkdownLinkDestination(value);
325 + if (source.length === 0 || source.startsWith("#") || source.startsWith("?")) {
326 + return { _tag: "Blocked" };
327 + }
328 + if (DIRECT_IMAGE_SOURCE_PATTERN.test(source)) {
329 + return { _tag: "Direct", uri: source };
330 + }
331 +
332 + const path = markdownDestinationHostPath(source);
333 + if (path === null) return { _tag: "Blocked" };
334 + if (/^file:/i.test(source)) return hostFileSource(path, workspaceRoot);
335 + if (path.length === 0) return { _tag: "Blocked" };
336 + if (path.startsWith("/") || isWindowsAbsolutePath(path)) {
337 + return hostFileSource(path, workspaceRoot);
338 + }
339 + if (URI_SCHEME_PATTERN.test(path) || path.startsWith("~/") || path.startsWith("~\\")) {
340 + return { _tag: "Blocked" };
341 + }
342 + if (!workspaceRoot) return { _tag: "Blocked" };
343 +
344 + return { _tag: "WorkspaceFile", path: joinWorkspacePath(workspaceRoot, path), relative: true };
345 +}
346 +
347 +export function shouldRenderMarkdownImageAsFileLink(
348 + source: MarkdownImageSource,
349 + mediaKind: ReturnType<typeof mediaKindFromPath>,
350 +): boolean {
351 + return source._tag === "WorkspaceFile" && mediaKind === null;
352 +}
353 +
354 export function isMarkdownFileLinkLabel(label: string, href: string): boolean {
355 const destination = parseMarkdownFileLink(href);
356 if (!destination) return false;
@@ -494,10 +560,35 @@ export function resolveMarkdownFileLinkTarget(
560 cwd?: string,
561 baseDir: string | undefined = cwd,
562 ): string | null {
497 - if (!href) return null;
498 - const target = parseMarkdownFileLink(href);
499 - if (!target) return null;
563 + return resolveMarkdownFileLink(href, cwd, baseDir)?.targetPath ?? null;
564 +}
565 +
566 +/** Resolves the displayed position and the editor target, which opens at the start line. */
567 +export function resolveMarkdownFileLink(
568 + href: string | undefined,
569 + cwd?: string,
570 + baseDir: string | undefined = cwd,
571 +): { sourcePath: string; targetPath: string; position: FilePathPosition } | null {
572 + const source = href ? parseMarkdownFileLink(href) : null;
573 + if (!source) return null;
574
575 + const targetPath = resolveParsedFileLinkTarget(source, cwd, baseDir);
576 + if (!targetPath) return null;
577 + return {
578 + sourcePath: source.path,
579 + targetPath,
580 + position: {
581 + ...splitFilePathPosition(targetPath),
582 + ...(source.endLine !== undefined ? { endLine: source.endLine } : {}),
583 + },
584 + };
585 +}
586 +
587 +function resolveParsedFileLinkTarget(
588 + target: FilePathPosition,
589 + cwd: string | undefined,
590 + baseDir: string | undefined,
591 +): string | null {
592 const pathWithPosition = formatFilePathPosition(target);
593 if (!isRelativeFilePath(pathWithPosition)) {
594 // Opening a network path makes Windows sign in to its host with the user's
packages/shared/src/markdownPipeline.ts
+43 -18
@@ -840,36 +840,61 @@ const imageSourceProcessor = unified()
840 .use(remarkRehype, { allowDangerousHtml: true })
841 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
842
843 +export type ChatMarkdownImageProperties = {
844 + readonly src?: unknown;
845 + readonly dataLocalSrc?: unknown;
846 + readonly dataDarkSrc?: unknown;
847 + readonly dataLightSrc?: unknown;
848 +};
849 +
850 +/** Keep the authored path for file links and normalize Windows separators for classification. */
851 +export function chatMarkdownImageSource(
852 + properties?: ChatMarkdownImageProperties,
853 + theme?: "dark" | "light",
854 +) {
855 + const themeSrc =
856 + theme === undefined
857 + ? undefined
858 + : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"];
859 + const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc;
860 + const source =
861 + typeof themeSrc === "string"
862 + ? themeSrc
863 + : typeof localSrc === "string"
864 + ? localSrc
865 + : properties?.src;
866 + if (typeof source !== "string") return null;
867 + const authoredSrc = normalizeMarkdownLinkDestination(source);
868 + return {
869 + authoredSrc,
870 + classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc,
871 + };
872 +}
873 +
874 interface ImageSourceNode {
875 readonly type: string;
876 readonly tagName?: string;
846 - readonly properties?: {
847 - readonly src?: unknown;
848 - readonly dataLocalSrc?: unknown;
849 - readonly dataDarkSrc?: unknown;
850 - readonly dataLightSrc?: unknown;
851 - };
877 + readonly properties?: ChatMarkdownImageProperties;
878 readonly children?: ReadonlyArray<ImageSourceNode>;
879 }
880
881 /**
856 - * The sources of the images chat markdown shows, read as ChatMarkdown's `img` renderer reads
857 - * them. Code, comments, and plain links show no image, so they add none.
882 + * Collect the fallback and every theme variant so images are available to all viewers.
883 */
884 export function chatMarkdownImageSources(markdown: string): Array<string> {
885 const sources: Array<string> = [];
886 const visit = (node: ImageSourceNode) => {
887 if (node.type === "element" && node.tagName === "img") {
863 - const { src, dataLocalSrc, dataDarkSrc, dataLightSrc } = node.properties ?? {};
864 - // The sanitizer drops a Windows drive path from `src`; the renderer reads it from here.
865 - if (typeof dataLocalSrc === "string") {
866 - sources.push(normalizeMarkdownLinkDestination(dataLocalSrc).replaceAll("\\", "/"));
867 - } else if (typeof src === "string") {
868 - sources.push(normalizeMarkdownLinkDestination(src));
869 - }
870 - // A `<picture>` shows one of these instead, by the viewer's theme.
871 - for (const variant of [dataDarkSrc, dataLightSrc]) {
872 - if (typeof variant === "string") sources.push(normalizeMarkdownLinkDestination(variant));
888 + const properties = node.properties;
889 + const fallback = chatMarkdownImageSource(properties);
890 + if (fallback) sources.push(fallback.classifiedSrc);
891 + for (const [theme, variant] of [
892 + ["dark", properties?.dataDarkSrc],
893 + ["light", properties?.dataLightSrc],
894 + ] as const) {
895 + if (typeof variant !== "string") continue;
896 + const source = chatMarkdownImageSource(properties, theme);
897 + if (source) sources.push(source.classifiedSrc);
898 }
899 }
900 node.children?.forEach(visit);
packages/shared/src/threadFindText.test.ts
+53
@@ -148,6 +148,50 @@ it("keeps fence paths literal and indexes file-chip labels in user messages", ()
148 ).toEqual(["file.ts · L42"]);
149 });
150
151 +it.each([
152 + {
153 + source: "user",
154 + cwd: "/workspace/repo",
155 + text: "See [src/notes.ts](src/notes.ts#L42-L64) and [src/notes.ts](src/notes.ts#L42-L70)",
156 + expected: ["See notes.ts · L42–64 and notes.ts · L42–70"],
157 + },
158 + {
159 + source: "assistant",
160 + cwd: "/workspace/repo",
161 + text: "[Read notes](src/notes.ts:42-64) and `test/notes.ts:42-64`",
162 + expected: ["Read notes notes.ts · repo/src · L42–64 and notes.ts · repo/test · L42–64"],
163 + },
164 + {
165 + source: "assistant",
166 + cwd: undefined,
167 + text: [
168 + "[notes.ts](file:///tmp/notes.ts#L42-64) [relative](src/notes.ts#L42-L64)",
169 + "[web](https://example.com/notes.ts#L42-L64) [reverse](/tmp/notes.ts#L64-L42)",
170 + "`port:42-64`",
171 + "\n```text\n/tmp/notes.ts:42-64\n```",
172 + ].join(" "),
173 + expected: [
174 + "notes.ts · L42–64 relative web reverse notes.ts · L64 port:42-64",
175 + "/tmp/notes.ts:42-64\n",
176 + ],
177 + },
178 + {
179 + source: "plan",
180 + cwd: String.raw`\\server\share\repo`,
181 + text: "[notes.ts](file://server/share/repo/notes.ts#L42-L64) [other](file://other/share/notes.ts#L42-L64)",
182 + expected: ["Proposed plan", "notes.ts · L42–64 other"],
183 + },
184 +] as const)(
185 + "indexes the displayed file range in $source text",
186 + ({ source, cwd, text, expected }) => {
187 + const segments =
188 + source === "plan"
189 + ? searchablePlanSegments(text, cwd)
190 + : searchableMessageSegments({ role: source, text, streaming: false }, cwd);
191 + expect(segments).toEqual(expected);
192 + },
193 +);
194 +
195 it("indexes nested disclosure summaries and bodies in rendered order", () => {
196 expect(
197 assistantSegments(
@@ -188,3 +232,12 @@ it("indexes insight bodies without hidden fences and keeps user and plan text li
232 expect(searchablePlanSegments(text).join("\n")).toContain("★ Insight");
233 expect(assistantSegments(`\`\`\`text\n${text}\n\`\`\``)?.join("\n")).toContain("★ Insight");
234 });
235 +
236 +it("indexes image destinations rendered as file chips", () => {
237 + expect(
238 + assistantSegments(
239 + "![note](src/notes.ts#L42-L64) ![screenshot](src/screenshot.png#L42-L64)",
240 + "/workspace/repo",
241 + ),
242 + ).toEqual(["notes.ts · L42–64 "]);
243 +});
packages/shared/src/threadFindText.ts
+55 -29
@@ -8,18 +8,17 @@ import {
8 renderCodexInlineDirectivesAsMarkdown,
9 } from "./codexMarkdownDirectives.ts";
10 import { codexArtifactTemplatePresentationLabel } from "./codexArtifactTemplates.ts";
11 +import { buildFileLinkParentSuffixByPath, fileLinkLabel } from "./fileLinks.ts";
12 import {
12 - buildFileLinkParentSuffixByPath,
13 - splitFilePathPosition,
14 - fileLinkLabel,
15 -} from "./fileLinks.ts";
16 -import {
13 + classifyMarkdownImageSource,
14 isMarkdownFileLinkLabel,
15 extractMarkdownLinkHrefs,
16 extractInlineCodeSpans,
17 inlineCodeFilePathCandidate,
21 - resolveMarkdownFileLinkTarget,
18 + resolveMarkdownFileLink,
19 + shouldRenderMarkdownImageAsFileLink,
20 } from "./markdownLinks.ts";
21 +import { mediaKindFromPath } from "./mediaPreview.ts";
22 import { upgradeLegacyContextMessage } from "./composerContextLegacy.ts";
23 import {
24 isAttachmentOnlyBootstrapPrompt,
@@ -38,7 +37,9 @@ import {
37 CHAT_MARKDOWN_REMARK_PLUGINS,
38 CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
39 CHAT_USER_MARKDOWN_REMARK_PLUGINS,
40 + chatMarkdownImageSource,
41 decodeMarkdownLinkEscapes,
42 + type ChatMarkdownImageProperties,
43 } from "./markdownPipeline.ts";
44
45 // Inline wrappers (including Shiki token spans) must not split a search phrase.
@@ -103,9 +104,8 @@ interface TextTree {
104 readonly type: string;
105 readonly tagName?: string;
106 readonly value?: string;
106 - readonly properties?: {
107 + readonly properties?: ChatMarkdownImageProperties & {
108 readonly href?: unknown;
108 - readonly src?: unknown;
109 readonly dataInlineCode?: unknown;
110 };
111 readonly children?: ReadonlyArray<TextTree>;
@@ -113,11 +113,21 @@ interface TextTree {
113
114 function markdownThreadFindText(
115 markdown: string,
116 - userMessage = false,
117 - cwd?: string,
118 - skills: readonly InlineSkill[] = [],
119 - lineBreaks = false,
120 - renderInsights = false,
116 + {
117 + userMessage = false,
118 + cwd,
119 + skills = [],
120 + lineBreaks = false,
121 + renderInsights = false,
122 + theme,
123 + }: {
124 + userMessage?: boolean;
125 + cwd: string | undefined;
126 + skills?: readonly InlineSkill[];
127 + lineBreaks?: boolean;
128 + renderInsights?: boolean;
129 + theme: "dark" | "light" | undefined;
130 + },
131 ): string[] {
132 const processor = userMessage
133 ? userProcessor
@@ -136,8 +146,8 @@ function markdownThreadFindText(
146 ),
147 ...extractInlineCodeSpans(markdown).flatMap((span) => inlineCodeFilePathCandidate(span) ?? []),
148 ].flatMap((href) => {
139 - const target = resolveMarkdownFileLinkTarget(href, cwd);
140 - return target ? [splitFilePathPosition(target).path] : [];
149 + const resolved = resolveMarkdownFileLink(href, cwd);
150 + return resolved ? [resolved.position.path] : [];
151 });
152 const parentSuffixes = buildFileLinkParentSuffixByPath(paths);
153 const segments: string[] = [];
@@ -164,6 +174,19 @@ function markdownThreadFindText(
174 let candidate: string | null = null;
175 if (node.tagName === "a" && typeof href === "string") {
176 candidate = href;
177 + } else if (node.tagName === "img") {
178 + const source = chatMarkdownImageSource(node.properties, theme);
179 + if (source) {
180 + const { authoredSrc, classifiedSrc } = source;
181 + if (
182 + shouldRenderMarkdownImageAsFileLink(
183 + classifyMarkdownImageSource(classifiedSrc, cwd),
184 + mediaKindFromPath(classifiedSrc),
185 + )
186 + ) {
187 + candidate = authoredSrc;
188 + }
189 + }
190 } else if (
191 node.tagName === "code" &&
192 !inPre &&
@@ -173,14 +196,13 @@ function markdownThreadFindText(
196 (node.children ?? []).map((child) => child.value ?? "").join(""),
197 );
198 }
176 - const target = candidate ? resolveMarkdownFileLinkTarget(candidate, cwd) : null;
177 - if (target) {
199 + const resolved = candidate ? resolveMarkdownFileLink(candidate, cwd) : null;
200 + if (candidate && resolved) {
201 const labelText = (node: TextTree): string =>
202 node.value ?? (node.children ?? []).map(labelText).join("");
203 const label = labelText(node);
181 - if (node.tagName === "a" && candidate && !isMarkdownFileLinkLabel(label, candidate))
182 - text += `${label} `;
183 - text += fileLinkLabel(splitFilePathPosition(target), parentSuffixes);
204 + if (node.tagName === "a" && !isMarkdownFileLinkLabel(label, candidate)) text += `${label} `;
205 + text += fileLinkLabel(resolved.position, parentSuffixes);
206 return;
207 }
208 }
@@ -222,10 +244,14 @@ function markdownThreadFindText(
244 }
245
246 /** Plans render `$skill` tokens literally (no skill chips), so they are indexed as written. */
225 -export function searchablePlanSegments(markdown: string, cwd?: string): readonly string[] {
247 +export function searchablePlanSegments(
248 + markdown: string,
249 + cwd?: string,
250 + theme?: "dark" | "light",
251 +): readonly string[] {
252 return [
253 proposedPlanTitle(markdown) ?? "Proposed plan",
228 - ...markdownThreadFindText(stripDisplayedPlanMarkdown(markdown), false, cwd, []),
254 + ...markdownThreadFindText(stripDisplayedPlanMarkdown(markdown), { cwd, theme }),
255 ];
256 }
257
@@ -233,20 +259,20 @@ export function searchableMessageSegments(
259 message: Pick<OrchestrationV2ConversationMessage, "role" | "text" | "streaming" | "context">,
260 cwd?: string,
261 skills: readonly InlineSkill[] = [],
262 + theme?: "dark" | "light",
263 ): readonly string[] | null {
264 if (message.role === "user") {
265 // Clients hide this prompt, so find must not match text nobody can see.
266 if (isAttachmentOnlyBootstrapPrompt(message.text)) return [];
267 const text = message.context ? message.text : upgradeLegacyContextMessage(message.text).text;
241 - return markdownThreadFindText(text, true, cwd, skills);
268 + return markdownThreadFindText(text, { userMessage: true, cwd, skills, theme });
269 }
270 if (message.role !== "assistant") return null;
244 - return markdownThreadFindText(
245 - message.text || (message.streaming ? "" : "(empty response)"),
246 - false,
271 + return markdownThreadFindText(message.text || (message.streaming ? "" : "(empty response)"), {
272 cwd,
273 skills,
249 - shouldPreserveAssistantLineBreaks(message.text),
250 - true,
251 - );
274 + lineBreaks: shouldPreserveAssistantLineBreaks(message.text),
275 + renderInsights: true,
276 + theme,
277 + });
278 }
scripts/scenarios/thread-find-matches-file-line-range.e2e.ts new
+38
@@ -0,0 +1,38 @@
1 +import { expect } from "e2e";
2 +
3 +import { test, WEB } from "./t3.ts";
4 +
5 +test(
6 + "Find in thread matches the displayed line range of a file link",
7 + WEB,
8 + async ({ t3, app, screen, browser }) => {
9 + const project = await t3.project("demo", { "src/notes.ts": "// Notes\n".repeat(64) });
10 + const thread = await t3.thread({
11 + project,
12 + title: "File review",
13 + messages: ["See [src/notes.ts](src/notes.ts#L42-L64)"],
14 + });
15 + await t3.open(thread);
16 + await screen.getByRole("button", /^Agent See/).tap();
17 + await browser
18 + .locator("[data-user-message-body]")
19 + .getByText("notes.ts · L42–64", { exact: true })
20 + .waitFor();
21 +
22 + await browser.keyboard.press("Control+f");
23 + await screen.getByRole("searchbox", "Find in thread").fill("L42–64");
24 + try {
25 + await expect
26 + .poll(
27 + () =>
28 + browser.evaluate<string>(
29 + 'document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""',
30 + ),
31 + { message: "Find in thread counts the displayed line range as a match" },
32 + )
33 + .toBe("1/1");
34 + } finally {
35 + await app.screenshot("file-range-find-result");
36 + }
37 + },
38 +);