TypeScript
feat(web): find messages and plans in the current thread (#10439)
Jono Kemball12069eefd707
diff --git a/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts b/apps/mobile/modules/t3-markdown-text/src/markdownLinks.tsindex 8b491c0c77c..913f7cb3716 100644--- a/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts+++ b/apps/mobile/modules/t3-markdown-text/src/markdownLinks.ts@@ -1,10 +1,10 @@+import { fileBasename } from "@t3tools/shared/path";+import { formatFilePathPosition } from "@t3tools/shared/fileLinks";import {- fileBasename,- formatFilePathPosition,inlineCodeFilePathCandidate,normalizeMarkdownLinkDestination,parseMarkdownFileLink,-} from "@t3tools/client-runtime/markdown-links";+} from "@t3tools/shared/markdownLinks";import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";import { videoMimeType } from "@t3tools/shared/video";diff --git a/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts b/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.tsindex 6ae50075093..58df022faf1 100644--- a/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts+++ b/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts@@ -1,5 +1,5 @@import type { MarkdownNode } from "react-native-nitro-markdown/headless";-import { isMarkdownFileLinkLabel } from "@t3tools/client-runtime/markdown-links";+import { isMarkdownFileLinkLabel } from "@t3tools/shared/markdownLinks";import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";import { imageMimeType } from "@t3tools/shared/image";import { isWindowsAbsolutePath } from "@t3tools/shared/path";diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex 79990884085..b6930deb5e8 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -29,7 +29,7 @@ import type {import {appendCodexArtifactTemplateUsePrompt,type CodexArtifactTemplate,-} from "@t3tools/client-runtime/codex-artifact-templates";+} from "@t3tools/shared/codexArtifactTemplates";import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";import {presentPendingBackgroundWork,diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex 4cfa8f2676b..44673dcf275 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -36,9 +36,9 @@ import { writeComposerContextClipboard } from "../../lib/composerContextClipboarimport {codexArtifactTemplatePresentationLabel,type CodexArtifactTemplate,-} from "@t3tools/client-runtime/codex-artifact-templates";+} from "@t3tools/shared/codexArtifactTemplates";import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";-import { isMarkdownFileLinkLabel } from "@t3tools/client-runtime/markdown-links";+import { isMarkdownFileLinkLabel } from "@t3tools/shared/markdownLinks";import { getTextContent, type MarkdownNode } from "react-native-nitro-markdown/headless";import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";@@ -50,7 +50,7 @@ import { resolveViewedImageAsset } from "@t3tools/client-runtime/work-log/presenimport {renderCodexFileCitationsAsMarkdown,splitCodexArtifactTemplateMarkdown,-} from "@t3tools/client-runtime/codex-markdown-directives";+} from "@t3tools/shared/codexMarkdownDirectives";import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";import { imageMimeType } from "@t3tools/shared/image";import { videoMimeType } from "@t3tools/shared/video";diff --git a/apps/mobile/src/features/threads/fileChipMenu.ts b/apps/mobile/src/features/threads/fileChipMenu.tsindex 9f82e089444..9835c0c37cc 100644--- a/apps/mobile/src/features/threads/fileChipMenu.ts+++ b/apps/mobile/src/features/threads/fileChipMenu.ts@@ -1,4 +1,4 @@-import { fileBasename } from "@t3tools/client-runtime/markdown-links";+import { fileBasename } from "@t3tools/shared/path";import type { ThreadId } from "@t3tools/contracts";import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";import type { MarkdownFileContextMenu } from "@t3tools/mobile-markdown-text/types";diff --git a/apps/mobile/src/features/threads/thread-search-match.tsx b/apps/mobile/src/features/threads/thread-search-match.tsxindex 553160dbdd8..1f03e2c2adf 100644--- a/apps/mobile/src/features/threads/thread-search-match.tsx+++ b/apps/mobile/src/features/threads/thread-search-match.tsx@@ -1,48 +1,9 @@+import { splitThreadSearchText } from "@t3tools/shared/threadSearch";import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";import { AppText as Text } from "../../components/AppText";import { cn } from "../../lib/cn";-function foldAsciiCase(value: string): string {- return value.replace(/[A-Z]/g, (character) => character.toLowerCase());-}--function splitHighlightParts(text: string, query: string) {- const normalizedText = foldAsciiCase(text);- const normalizedQuery = foldAsciiCase(query.trim());- if (normalizedQuery.length === 0) {- return [{ text, highlighted: false, start: 0 }];- }-- const parts: Array<{- readonly text: string;- readonly highlighted: boolean;- readonly start: number;- }> = [];- let cursor = 0;- while (cursor < text.length) {- const matchIndex = normalizedText.indexOf(normalizedQuery, cursor);- if (matchIndex === -1) {- parts.push({ text: text.slice(cursor), highlighted: false, start: cursor });- break;- }- if (matchIndex > cursor) {- parts.push({- text: text.slice(cursor, matchIndex),- highlighted: false,- start: cursor,- });- }- parts.push({- text: text.slice(matchIndex, matchIndex + normalizedQuery.length),- highlighted: true,- start: matchIndex,- });- cursor = matchIndex + normalizedQuery.length;- }- return parts;-}-export function ThreadSearchMatchExcerpt(props: {readonly match: EnvironmentThreadSearchMatch;readonly query: string;@@ -51,7 +12,7 @@ export function ThreadSearchMatchExcerpt(props: {readonly sidebar?: boolean;}) {const isUser = props.match.source === "user";- const parts = splitHighlightParts(props.match.snippet, props.query);+ const parts = splitThreadSearchText(props.match.snippet, props.query);return (<TextclassName={cn(diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex d434ca86a3a..5f242c43992 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -47,6 +47,8 @@ export const RPC_REQUIRED_SCOPES = {[ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,+ [ORCHESTRATION_V2_WS_METHODS.searchThread]: AuthOrchestrationReadScope,+ [ORCHESTRATION_V2_WS_METHODS.searchThreadStream]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.getTurnItem]: AuthOrchestrationReadScope,diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.tsindex d01c7812bc1..9aac9be1a56 100644--- a/apps/server/src/observability/RpcInstrumentation.ts+++ b/apps/server/src/observability/RpcInstrumentation.ts@@ -21,6 +21,8 @@ const RPC_AGGREGATES = {[ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.searchThreads]: "orchestration",+ [ORCHESTRATION_V2_WS_METHODS.searchThread]: "orchestration",+ [ORCHESTRATION_V2_WS_METHODS.searchThreadStream]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: "orchestrationV2",[ORCHESTRATION_V2_WS_METHODS.launchThread]: "orchestration",diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex d35426eb2cb..1d7f907a519 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -1,3 +1,8 @@+import type {+ OrchestrationV2SearchThreadInput,+ OrchestrationV2SearchThreadResult,+ OrchestrationV2ThreadHistoryPage,+} from "@t3tools/contracts";import {latestExecutedRun,latestRootProviderFailure,@@ -281,6 +286,18 @@ export interface OrchestratorV2Shape {readonly dispatch: (command: OrchestrationV2ServerCommand,) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;+ readonly searchThreadStream: (+ input: OrchestrationV2SearchThreadInput,+ ) => Stream.Stream<OrchestrationV2SearchThreadResult, OrchestratorV2Error>;+ readonly searchThread: (+ input: OrchestrationV2SearchThreadInput,+ ) => Effect.Effect<OrchestrationV2SearchThreadResult, OrchestratorV2Error>;+ readonly getThreadHistoryPage: (+ threadId: ThreadId,+ cursor: string,+ throughEntryId?: string,+ conversationOnly?: boolean,+ ) => Effect.Effect<OrchestrationV2ThreadHistoryPage, OrchestratorV2Error>;readonly getTimelinePage: (threadId: ThreadId,options: ProjectionTimelinePageOptions,@@ -10817,6 +10834,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiorecoverDelegatedTask,delegatedTaskResultPending,dispatch: dispatchWithReceipt,+ searchThreadStream: (input) =>+ projectionStore+ .searchThreadStream(input)+ .pipe(+ Stream.mapError(+ (cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }),+ ),+ ),+ searchThread: (input) =>+ projectionStore+ .searchThread(input)+ .pipe(+ Effect.mapError(+ (cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }),+ ),+ ),+ getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>+ projectionStore+ .getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly)+ .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),getTimelinePage: (threadId, options) =>projectionStore.getTimelinePage(threadId, options)@@ -10951,6 +10988,11 @@ const layerUnavailable: Layer.Layer<OrchestratorV2> = Layer.succeed(cause: "Orchestration V2 live runtime is not configured.",}),),+ searchThreadStream: (input) =>+ Stream.fail(new OrchestratorProjectionError({ threadId: input.threadId })),+ searchThread: (input) =>+ Effect.fail(new OrchestratorProjectionError({ threadId: input.threadId })),+ getThreadHistoryPage: (threadId) => Effect.fail(new OrchestratorProjectionError({ threadId })),getTimelinePage: (threadId) => Effect.fail(new OrchestratorProjectionError({ threadId })),getMessageCount: (threadId) => Effect.fail(new OrchestratorProjectionError({ threadId })),getTurnItem: ({ threadId }) => Effect.fail(new OrchestratorProjectionError({ threadId })),diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.tsindex df123755cfc..86b2d503c6b 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -1,3 +1,11 @@+import { projectTurnItemForWire } from "./WireProjection.ts";+import * as Stream from "effect/Stream";+import { makeThreadFind, findProjectedThreadItems } from "./ThreadFind.ts";+import type {+ OrchestrationV2SearchThreadInput,+ OrchestrationV2SearchThreadResult,+ OrchestrationV2ThreadHistoryPage,+} from "@t3tools/contracts";import {latestRootProviderFailure,latestUnheldRun,@@ -28,7 +36,6 @@ import type {ProviderThreadId,ProviderTurnId,RunAttemptId,- MessageId,} from "@t3tools/contracts";import {OrchestrationV2AppThreadJson as OrchestrationV2AppThreadJsonSchema,@@ -49,6 +56,7 @@ import {OrchestrationV2TurnItemJson as OrchestrationV2TurnItemJsonSchema,orchestrationV2RunWorkStartedAt,RunId,+ MessageId,RuntimeRequestId,CheckpointScopeId,ThreadId,@@ -74,8 +82,13 @@ import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp";import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts";import {isThreadHistoryUserTurn,+ isConversationHistoryItem,isThreadHistoryTurnStart,THREAD_HISTORY_MAX_RAW_TURNS,+ selectHistoryPageFromCursor,+ selectRecentTimelineWindow,+ THREAD_HISTORY_PAGE_POLICY,+ OLDER_THREAD_USER_TURN_LIMIT,} from "./threadHistoryPaging.ts";export class ProjectionStoreApplyEventError extends Schema.TaggedError<ProjectionStoreApplyEventError>()(@@ -318,9 +331,21 @@ export interface ShellSnapshotOptions {}export interface ProjectionStoreV2Shape {+ readonly searchThreadStream: (+ input: OrchestrationV2SearchThreadInput,+ ) => Stream.Stream<OrchestrationV2SearchThreadResult, ProjectionStoreV2Error>;+ readonly searchThread: (+ input: OrchestrationV2SearchThreadInput,+ ) => Effect.Effect<OrchestrationV2SearchThreadResult, ProjectionStoreV2Error>;readonly getThreadAttachmentIds: (threadId: ThreadId,) => Effect.Effect<ReadonlyArray<string>, ProjectionStoreV2Error>;+ readonly getThreadHistoryPage: (+ threadId: ThreadId,+ cursor: string,+ throughEntryId?: string,+ conversationOnly?: boolean,+ ) => Effect.Effect<OrchestrationV2ThreadHistoryPage, ProjectionStoreV2Error>;readonly getTimelinePage: (threadId: ThreadId,options: ProjectionTimelinePageOptions,@@ -969,6 +994,11 @@ type ShellRunItemCountRow = {readonly item_count: number;};+const encodeTimelineSources = Schema.encodeEffect(+ Schema.fromJsonString(+ Schema.Array(Schema.Struct({ threadId: Schema.String, id: Schema.String })),+ ),+);const encodeIdList = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));const encodeThreadPayload = Schema.encodeEffect(@@ -4706,12 +4736,17 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =);// Only the timeline index is assembled across fork ancestry. Payloads are read- // after page selection, so a small MCP page never hydrates all tool output.+ // after page selection, so history and MCP pages hydrate only the requested rows.type TimelineIndexItem = Pick<OrchestrationV2TurnItem,"id" | "threadId" | "runId" | "nodeId" | "type"> & {- readonly inputIntent?: "queued_turn";+ readonly inputIntent?: Extract<+ OrchestrationV2TurnItem,+ { type: "user_message" }+ >["inputIntent"];+ readonly createdBy?: "user" | "agent" | "system";+ readonly messageId?: MessageId;};type TimelineIndexRow = {readonly sourceThreadId: ThreadId;@@ -4738,9 +4773,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =run_id: string | null;node_id: string | null;type: OrchestrationV2TurnItem["type"];- input_intent: string | null;+ input_intent: NonNullable<TimelineIndexItem["inputIntent"]> | null;+ created_by: "user" | "agent" | "system" | null;+ message_id: string | null;}>`SELECT turn_item_id, run_id, node_id, type,- CASE WHEN type = 'user_message' THEN json_extract(payload_json, '$.inputIntent') END AS input_intent+ CASE WHEN type = 'user_message' THEN json_extract(payload_json, '$.inputIntent') END AS input_intent,+ CASE WHEN type = 'user_message' THEN json_extract(payload_json, '$.createdBy') END AS created_by,+ CASE WHEN type IN ('user_message', 'assistant_message') THEN json_extract(payload_json, '$.messageId') END AS message_idFROM orchestration_v2_projection_turn_items WHERE thread_id = ${threadId}ORDER BY ordinal ASC, turn_item_id ASC`;const items: Array<TimelineIndexItem> = rows.map((row) => ({@@ -4749,7 +4788,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =runId: row.run_id === null ? null : RunId.make(row.run_id),nodeId: row.node_id === null ? null : NodeId.make(row.node_id),type: row.type,- ...(row.input_intent === "queued_turn" ? { inputIntent: "queued_turn" as const } : {}),+ ...(row.input_intent === null ? {} : { inputIntent: row.input_intent }),+ ...(row.created_by === null ? {} : { createdBy: row.created_by }),+ ...(row.message_id === null ? {} : { messageId: MessageId.make(row.message_id) }),}));const local: Array<TimelineIndexRow> = items.map((item) => ({sourceThreadId: threadId,@@ -4819,6 +4860,116 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =),);+ const { searchThread, searchThreadStream } = yield* makeThreadFind((threadId) =>+ readTimelineIndex(threadId, new Set()).pipe(Effect.map((index) => index.visible)),+ );++ const getThreadHistoryPage: ProjectionStoreV2Shape["getThreadHistoryPage"] = (+ threadId,+ cursor,+ throughEntryId,+ conversationOnly,+ ) =>+ sql+ .withTransaction(+ Effect.gen(function* () {+ const index = yield* readTimelineIndex(threadId, new Set());+ if (index.records.thread.deletedAt !== null)+ return yield* new ProjectionStoreThreadNotFoundError({ threadId });+ const revisions = yield* sql<{+ sequence: number;+ }>`SELECT COALESCE(MAX(sequence), 0) AS sequence+ FROM orchestration_events WHERE application_event_version = 2+ AND aggregate_kind = 'thread' AND stream_id = ${threadId}`;+ const snapshotSequence = revisions[0]?.sequence ?? 0;+ // Choose complete turns from the light index before loading any bodies.+ // A history page does not need nodes, provider turns, or other control state.+ const page = yield* Effect.try({+ try: () =>+ selectHistoryPageFromCursor({+ items: index.visible.map((row, position) => ({+ ...row,+ position,+ canonicalPosition: position,+ })),+ cursor,+ snapshotSequence,+ rowEncodedBytes: () => 0,+ throughEntryId,+ }),+ catch: (cause) => new ProjectionStoreReadError({ threadId, cause }),+ });+ const end = (page.items.at(-1)?.canonicalPosition ?? -1) + 1;+ const hasUserTurns = index.visible+ .slice(0, end)+ .some((row) => isThreadHistoryUserTurn(row.item));+ const materialized =+ conversationOnly && hasUserTurns+ ? page.items.filter((row) => isConversationHistoryItem(row.item))+ : page.items;+ const sources = yield* encodeTimelineSources(+ materialized+ .filter((row) => !row.synthetic)+ .map((row) => ({ threadId: row.sourceThreadId, id: row.sourceItemId })),+ );+ const payloads = yield* sql<{+ thread_id: string;+ turn_item_id: string;+ payload_json: string;+ }>`+ SELECT item.thread_id, item.turn_item_id, item.payload_json+ FROM orchestration_v2_projection_turn_items item JOIN json_each(${sources}) wanted+ ON item.thread_id = json_extract(wanted.value, '$.threadId')+ AND item.turn_item_id = json_extract(wanted.value, '$.id')`;+ const byIdentity = new Map(+ payloads.map((row) => [`${row.thread_id}:${row.turn_item_id}`, row.payload_json]),+ );+ const items = yield* Effect.forEach(materialized, (row) =>+ Effect.gen(function* () {+ const payload = byIdentity.get(`${row.sourceThreadId}:${row.sourceItemId}`);+ const item =+ row.synthetic ??+ (payload === undefined+ ? yield* new ProjectionStoreReadError({ threadId })+ : yield* decodeTurnItemPayload(payload));+ return {+ position: row.canonicalPosition,+ visibility: row.visibility,+ sourceThreadId: row.sourceThreadId,+ sourceItemId: row.sourceItemId,+ item: projectTurnItemForWire(item),+ };+ }),+ );+ if (hasUserTurns)+ return {+ ...page,+ snapshotSequence,+ items: items.map((row, position) => ({ ...row, position })),+ };+ // The no-turn fallback also respects the encoded byte budget after projection.+ const bounded = selectRecentTimelineWindow({+ items,+ snapshotSequence,+ policy: {+ ...THREAD_HISTORY_PAGE_POLICY,+ maxUserTurns: OLDER_THREAD_USER_TURN_LIMIT,+ maxItems:+ THREAD_HISTORY_PAGE_POLICY.maxItems * (throughEntryId === undefined ? 1 : 2),+ },+ });+ return {+ snapshotSequence,+ items: conversationOnly+ ? bounded.items.filter((row) => isConversationHistoryItem(row.item))+ : bounded.items,+ nextCursor: bounded.hasMoreHistory ? bounded.nextCursor : page.nextCursor,+ hasMoreHistory: bounded.hasMoreHistory || page.hasMoreHistory,+ };+ }),+ )+ .pipe(Effect.mapError(controlReadError(threadId)));+const getTimelinePage: ProjectionStoreV2Shape["getTimelinePage"] = (threadId, options) =>sql.withTransaction(@@ -5756,6 +5907,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =getThreadSnapshot,getThreadSnapshotWindow,getTimelinePage,+ getThreadHistoryPage,+ searchThread,+ searchThreadStream,getThreadAttachmentIds,} satisfies ProjectionStoreV2Shape;}),@@ -6314,6 +6468,53 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(),),),+ searchThreadStream: (input) => Stream.fromEffect(service.searchThread(input)),+ searchThread: (input) =>+ service.getThreadSnapshot(input.threadId).pipe(+ Effect.flatMap(({ projection, snapshotSequence }) =>+ projection.thread.deletedAt !== null+ ? Effect.fail(new ProjectionStoreThreadNotFoundError({ threadId: input.threadId }))+ : Effect.succeed(+ // This store has no project records, so only worktree paths resolve labels.+ findProjectedThreadItems(+ projection.visibleTurnItems,+ input,+ snapshotSequence,+ projection.thread.worktreePath ?? undefined,+ ),+ ),+ ),+ ),+ getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>+ service.getThreadSnapshot(threadId).pipe(+ Effect.flatMap(({ projection, snapshotSequence }) =>+ Effect.gen(function* () {+ if (projection.thread.deletedAt !== null)+ return yield* new ProjectionStoreThreadNotFoundError({ threadId });+ return yield* Effect.try({+ try: () => {+ const page = selectHistoryPageFromCursor({+ items: projection.visibleTurnItems.map((row) => ({+ ...row,+ item: projectTurnItemForWire(row.item),+ })),+ cursor,+ throughEntryId,+ snapshotSequence,+ });+ return {+ ...page,+ snapshotSequence,+ items: conversationOnly+ ? page.items.filter((row) => isConversationHistoryItem(row.item))+ : page.items,+ };+ },+ catch: (cause) => new ProjectionStoreReadError({ threadId, cause }),+ });+ }),+ ),+ ),getTimelinePage: (threadId, options) =>service.getThreadProjection(threadId).pipe(Effect.map((projection) => {diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.tsindex 09c80f66fa2..0808386da53 100644--- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts+++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts@@ -225,6 +225,9 @@ it.effect(getPlan: () => Effect.die("unused"),hasUnpairedRunInterruptRequest: () => Effect.die("unused interrupt read"),getThreadAttachmentIds: () => Effect.die("Unused attachment lookup"),+ searchThread: () => Effect.die("unused"),+ searchThreadStream: () => Stream.empty,+ getThreadHistoryPage: () => Effect.die("unused"),getTimelinePage: () => Effect.die("Unused timeline read"),getMessageCount: () => Effect.die("unused message count"),getNextTurnItemOrdinal: () => Effect.die("unused ordinal read"),diff --git a/apps/server/src/orchestration-v2/ThreadFind.test.ts b/apps/server/src/orchestration-v2/ThreadFind.test.tsnew file mode 100644index 00000000000..d5ec86dad6c--- /dev/null+++ b/apps/server/src/orchestration-v2/ThreadFind.test.ts@@ -0,0 +1,1012 @@+import { assert, it, describe } from "@effect/vitest";+import {+ EventId,+ MessageId,+ PlanId,+ RunId,+ RuntimeRequestId,+ TurnItemId,+ type OrchestrationV2TurnItem,+ type OrchestrationV2Run,+ type OrchestrationV2SearchThreadResult,+ type OrchestrationV2ThreadHistoryPage,+ ProjectId,+ ProviderInstanceId,+ ThreadId,+ type OrchestrationV2DomainEvent,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as SqlClient from "effect/sql/SqlClient";+import * as Stream from "effect/Stream";+import { vi } from "vite-plus/test";+import * as ThreadFindText from "@t3tools/shared/threadFindText";++import * as SqlitePersistence from "../persistence/Sqlite.ts";+import * as ProjectionStore from "./ProjectionStore.ts";+import * as ProjectStore from "./ProjectStore.ts";+import * as EventStore from "./EventStore.ts";+import { encodeThreadHistoryCursor, selectHistoryPageFromCursor } from "./threadHistoryPaging.ts";+import { projectTurnItemForWire } from "./WireProjection.ts";++const layerTest = Layer.mergeAll(EventStore.layer, ProjectionStore.layer, ProjectStore.layer).pipe(+ Layer.provideMerge(SqlitePersistence.layerMemory),+);++const providerInstanceId = ProviderInstanceId.make("codex");+const at = (minute: number) => DateTime.makeUnsafe(Date.UTC(2026, 8, 27, 0, minute));++const createProject = (projectId: ProjectId) =>+ Effect.flatMap(ProjectStore.ProjectStoreV2, (projects) =>+ projects.apply({+ sequence: 0,+ eventId: EventId.make(`created:${projectId}`),+ aggregateKind: "project",+ aggregateId: projectId,+ occurredAt: DateTime.formatIso(at(0)),+ commandId: null,+ causationEventId: null,+ correlationId: null,+ metadata: {},+ type: "project.created",+ payload: {+ projectId,+ title: projectId,+ workspaceRoot: `/work/${projectId}`,+ defaultModelSelection: null,+ scripts: [],+ createdAt: DateTime.formatIso(at(0)),+ updatedAt: DateTime.formatIso(at(0)),+ },+ }),+ );++const thread = (+ threadId: ThreadId,+ projectId: ProjectId,+ overrides: { readonly archivedAt?: DateTime.Utc; readonly deletedAt?: DateTime.Utc } = {},+): OrchestrationV2DomainEvent => ({+ id: EventId.make(`created:${threadId}`),+ type: "thread.created",+ threadId,+ providerInstanceId,+ occurredAt: at(0),+ payload: {+ createdBy: "user",+ creationSource: "web",+ id: threadId,+ projectId,+ title: threadId,+ providerInstanceId,+ modelSelection: { instanceId: providerInstanceId, model: "gpt-5" },+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ activeProviderThreadId: null,+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },+ forkedFrom: null,+ createdAt: at(0),+ updatedAt: at(0),+ archivedAt: overrides.archivedAt ?? null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: null,+ deletedAt: overrides.deletedAt ?? null,+ },+});++const threadId = ThreadId.make("thread:find");+const projectId = ProjectId.make("project:find");+const runId = RunId.make("run:find");++function item(+ id: string,+ ordinal: number,+ text: string,+ kind: "user_message" | "assistant_message" | "proposed_plan" = "assistant_message",+ owner = threadId,+): Extract<+ OrchestrationV2TurnItem,+ { type: "user_message" | "assistant_message" | "proposed_plan" }+> {+ const base = {+ id: TurnItemId.make(id),+ threadId: owner,+ runId,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal,+ status: "completed" as const,+ title: null,+ // Creation time deliberately opposes the canonical item order.+ startedAt: at(100 - ordinal),+ completedAt: at(100 - ordinal),+ updatedAt: at(1),+ };+ if (kind === "proposed_plan")+ return { ...base, type: kind, planId: PlanId.make(id), markdown: text, streaming: false };+ if (kind === "user_message")+ return {+ ...base,+ type: kind,+ messageId: MessageId.make(id),+ text,+ inputIntent: "turn_start",+ attachments: [],+ createdBy: "user",+ creationSource: "web",+ };+ return { ...base, type: kind, messageId: MessageId.make(id), text, streaming: false };+}++function run(+ owner = threadId,+ id = runId,+ ordinal = 1,+ status: OrchestrationV2Run["status"] = "completed",+): Extract<OrchestrationV2DomainEvent, { type: "run.created" }> {+ return {+ id: EventId.make(`run:${owner}:${id}:${status}`),+ threadId: owner,+ occurredAt: at(1),+ type: "run.created",+ payload: {+ id,+ threadId: owner,+ ordinal,+ providerInstanceId,+ modelSelection: { instanceId: providerInstanceId, model: "gpt-6" },+ providerThreadId: null,+ userMessageId: MessageId.make("prompt"),+ rootNodeId: null,+ activeAttemptId: null,+ status,+ requestedAt: at(1),+ startedAt: at(1),+ completedAt: at(2),+ checkpointId: null,+ contextHandoffId: null,+ },+ };+}++const commit = Effect.fn("ThreadFindTest.commit")(function* (+ events: readonly OrchestrationV2DomainEvent[],+) {+ const store = yield* EventStore.EventStoreV2;+ const projection = yield* ProjectionStore.ProjectionStoreV2;+ yield* store.append({ events });+ yield* Effect.forEach(events, projection.apply, { discard: true });+});+const putItems = (items: readonly OrchestrationV2TurnItem[], version = "initial") =>+ commit(+ items.map((payload) => ({+ id: EventId.make(`${payload.threadId}:${payload.id}:${version}`),+ threadId: payload.threadId,+ occurredAt: at(1),+ type: "turn-item.updated" as const,+ payload,+ })),+ );+const setup = Effect.gen(function* () {+ yield* createProject(projectId);+ yield* commit([thread(threadId, projectId), run()]);+ return yield* ProjectionStore.ProjectionStoreV2;+});++describe("V2 thread find", () => {+ it.effect("delivers the reading-position match before parsing the remaining history", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ yield* putItems([+ item("before", 0, "before progressive needle needle"),+ item("reading", 1, "reading progressive needle needle"),+ item("after", 2, "after progressive needle"),+ ]);+ const parse = vi.spyOn(ThreadFindText, "searchableMessageSegments");+ const frames: OrchestrationV2SearchThreadResult[] = [];+ try {+ yield* projection+ .searchThreadStream({+ threadId,+ query: "needle",+ start: { entryId: "reading", occurrence: 1 },+ })+ .pipe(+ Stream.runForEach((frame) =>+ Effect.sync(() => {+ frames.push(frame);+ if (frame.complete === false) {+ assert.deepEqual(frame.match, { entryId: "reading", runId, occurrence: 1 });+ assert.equal(parse.mock.calls.length, 1);+ assert.equal(parse.mock.calls[0]![0].text, "reading progressive needle needle");+ }+ }),+ ),+ );+ assert.equal(frames.length, 2);+ assert.notEqual(frames[1]!.complete, false);+ assert.deepEqual(frames[1]!.match, frames[0]!.match);+ assert.equal(frames[1]!.totalMatches, 5);+ assert.equal(frames[1]!.activeIndex, 3);+ const cached = yield* projection+ .searchThreadStream({ threadId, query: "needle" })+ .pipe(Stream.runCollect);+ assert.equal(cached.length, 1);+ assert.notEqual(cached[0]!.complete, false);+ } finally {+ parse.mockRestore();+ }+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("wraps from an exhausted bottom anchor and cancels without counting the rest", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ yield* putItems([+ item("first", 0, "cancel progressive needle"),+ item("later", 1, "cancel later needle needle"),+ item("bottom", 2, "cancel bottom needle"),+ ]);+ const parse = vi.spyOn(ThreadFindText, "searchableMessageSegments");+ try {+ const frames = yield* projection+ .searchThreadStream({+ threadId,+ query: "needle",+ start: { entryId: "bottom", occurrence: 1 },+ })+ .pipe(Stream.take(1), Stream.runCollect);+ assert.equal(frames[0]!.complete, false);+ assert.equal(frames[0]!.match?.entryId, "first");+ assert.deepEqual(+ parse.mock.calls.map(([message]) => message.text),+ ["cancel bottom needle", "cancel progressive needle"],+ );+ const complete = yield* projection.searchThread({ threadId, query: "needle" });+ assert.equal(complete.totalMatches, 4);+ assert.equal(parse.mock.calls.length, 3);+ } finally {+ parse.mockRestore();+ }+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("finishes one snapshot while later searches include newly inserted matches", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ yield* putItems([+ item("selected", 1, "snapshot needle"),+ item("last", 2, "snapshot last needle"),+ ]);+ const frames = yield* projection.searchThreadStream({ threadId, query: "needle" }).pipe(+ Stream.tap((frame) =>+ frame.complete === false+ ? putItems([item("inserted", 0, "snapshot inserted needle")], "during-search")+ : Effect.void,+ ),+ Stream.runCollect,+ );+ assert.equal(frames.length, 2);+ assert.equal(frames[1]!.totalMatches, 2);+ assert.deepEqual(frames[1]!.match, frames[0]!.match);+ const updated = yield* projection.searchThread({+ threadId,+ query: "needle",+ start: { entryId: "selected", occurrence: 0 },+ });+ assert.equal(updated.totalMatches, 3);+ assert.equal(updated.activeIndex, 1);+ assert.equal(updated.match?.entryId, "selected");+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("returns only a final frame for empty searches and relative navigation", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ yield* putItems([item("only", 0, "needle needle")]);+ const empty = yield* projection+ .searchThreadStream({ threadId, query: "missing" })+ .pipe(Stream.runCollect);+ assert.equal(empty.length, 1);+ assert.equal(empty[0]!.totalMatches, 0);+ assert.notEqual(empty[0]!.complete, false);+ const relative = yield* projection+ .searchThreadStream({ threadId, query: "needle", offset: 1 })+ .pipe(Stream.runCollect);+ assert.equal(relative.length, 1);+ assert.equal(relative[0]!.match?.occurrence, 1);+ assert.notEqual(relative[0]!.complete, false);+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("returns bounded navigation counts around the selection, including wraparound", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ yield* putItems(+ Array.from({ length: 30 }, (_, i) =>+ item(`message:${i}`, i, "needle ".repeat((i % 3) + 1)),+ ),+ );+ const current = yield* projection.searchThread({+ threadId,+ query: "needle",+ start: { entryId: "message:14", occurrence: 1 },+ });+ assert.equal(current.totalMatches, 60);+ assert.equal(current.activeIndex, 28);+ assert.equal(current.navigation?.length, 17);+ assert.deepEqual(+ current.navigation?.map((entry) => entry.entryId),+ Array.from({ length: 17 }, (_, i) => `message:${i + 6}`),+ );+ assert.deepEqual(+ current.navigation?.find((entry) => entry.entryId === "message:14"),+ {+ entryId: "message:14",+ runId,+ startIndex: 27,+ count: 3,+ },+ );+ const first = yield* projection.searchThread({ threadId, query: "needle" });+ assert.equal(first.navigation?.length, 17);+ assert.include(first.navigation?.map((entry) => entry.entryId) ?? [], "message:29");+ const empty = yield* projection.searchThread({ threadId, query: "absent" });+ assert.deepEqual(empty.navigation, []);+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("keeps navigation compact for a message with thousands of occurrences", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ yield* putItems([item("many", 1, "needle ".repeat(5000))]);+ const result = yield* projection.searchThread({ threadId, query: "needle", index: 2000 });+ assert.equal(result.totalMatches, 5000);+ assert.equal(result.match?.occurrence, 2000);+ assert.deepEqual(result.navigation, [{ entryId: "many", runId, startIndex: 0, count: 5000 }]);+ assert.isBelow(JSON.stringify(result).length, 500);+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("cycles relative to the current match when new matches are inserted", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ yield* putItems([+ item("first", 10, "needle"),+ item("current", 20, "needle"),+ item("last", 30, "needle"),+ ]);+ const initial = yield* projection.searchThread({ threadId, query: "needle", index: 1 });+ assert.equal(initial.match?.entryId, "current");+ yield* putItems([+ item("new-before", 15, "needle"),+ item("new-after", 25, "needle"),+ item("new-last", 40, "needle"),+ ]);+ const start = { entryId: "current", occurrence: 0 };+ const refreshed = yield* projection.searchThread({ threadId, query: "needle", start });+ assert.equal(refreshed.totalMatches, 6);+ assert.equal(refreshed.activeIndex, 2);+ assert.equal(refreshed.match?.entryId, "current");+ const next = yield* projection.searchThread({ threadId, query: "needle", start, offset: 1 });+ assert.equal(next.match?.entryId, "new-after");+ const previous = yield* projection.searchThread({+ threadId,+ query: "needle",+ start,+ offset: -1,+ });+ assert.equal(previous.match?.entryId, "new-before");+ const end = yield* projection.searchThread({+ threadId,+ query: "needle",+ start: { entryId: "last", occurrence: 0 },+ offset: 1,+ });+ assert.equal(end.match?.entryId, "new-last");+ const wrapped = yield* projection.searchThread({+ threadId,+ query: "needle",+ start: { entryId: "new-last", occurrence: 0 },+ offset: 1,+ });+ assert.equal(wrapped.match?.entryId, "first");+ const backwards = yield* projection.searchThread({+ threadId,+ query: "needle",+ start: { entryId: "first", occurrence: 0 },+ offset: -1,+ });+ assert.equal(backwards.match?.entryId, "new-last");+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("reuses parses of large messages across navigation, edits, and new queries", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ const text = `${"large message ".repeat(2600)}needle`;+ yield* putItems(Array.from({ length: 8 }, (_, i) => item(`large:${i}`, i + 1, text)));+ const parse = vi.spyOn(ThreadFindText, "searchableMessageSegments");+ try {+ const first = yield* projection.searchThread({ threadId, query: "needle" });+ assert.equal(first.totalMatches, 8);+ // Identical bodies share one parse.+ assert.equal(parse.mock.calls.length, 1);+ parse.mockClear();+ const next = yield* projection.searchThread({ threadId, query: "needle", index: 4 });+ assert.equal(next.match?.entryId, "large:4");+ assert.equal(next.snapshotSequence, first.snapshotSequence);+ assert.equal(parse.mock.calls.length, 0);+ yield* putItems([item("large:4", 5, `${text} needle`)], "changed");+ const changed = yield* projection.searchThread({ threadId, query: "needle", index: 5 });+ assert.equal(changed.totalMatches, 9);+ assert.deepEqual(changed.match, { entryId: "large:4", runId, occurrence: 1 });+ // Only the edited message is parsed again.+ assert.equal(parse.mock.calls.length, 1);+ parse.mockClear();+ const retyped = yield* projection.searchThread({ threadId, query: "large message" });+ assert.equal(retyped.totalMatches, 8 * 2600);+ assert.equal(parse.mock.calls.length, 0);+ } finally {+ parse.mockRestore();+ }+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("searches visible rendered messages and plans in canonical item order", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ yield* putItems([+ item("user", 1, "Check **the build**", "user_message"),+ item("assistant", 2, "check the build twice: check the build"),+ item("plan-item", 3, "# Check the build\nShip it", "proposed_plan"),+ item("url", 4, "[documentation](https://hidden.example/needle)"),+ ]);+ const matches = [];+ for (let index = 0; index < 4; index++) {+ const result = yield* projection.searchThread({+ threadId,+ query: "CHECK THE BUILD",+ index,+ });+ assert.equal(result.totalMatches, 4);+ matches.push(result.match);+ }+ assert.deepEqual(matches, [+ { entryId: "user", runId, occurrence: 0 },+ { entryId: "assistant", runId, occurrence: 0 },+ { entryId: "assistant", runId, occurrence: 1 },+ { entryId: "plan-item", runId, occurrence: 0 },+ ]);+ assert.equal(+ (yield* projection.searchThread({ threadId, query: "hidden.example" })).totalMatches,+ 0,+ );+ assert.equal(+ (yield* projection.searchThread({ threadId, query: "check", index: 99 })).activeIndex,+ 3,+ );+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("keeps a search snapshot consistent while another thread commits", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ const other = ThreadId.make("thread:busy");+ yield* commit([thread(other, projectId), run(other, RunId.make("run:busy"))]);+ yield* putItems(Array.from({ length: 260 }, (_, i) => item(`message:${i}`, i, "needle")));+ const before = yield* projection.searchThread({ threadId, query: "needle" });+ const [during] = yield* Effect.all(+ [+ projection.searchThread({ threadId, query: "needle", index: 259 }),+ putItems([item("busy", 1, "busy", "assistant_message", other)]),+ ],+ { concurrency: "unbounded" },+ );+ assert.equal(during.totalMatches, 260);+ assert.equal(during.match?.entryId, "message:259");+ assert.equal(during.snapshotSequence, before.snapshotSequence);+ assert.equal(+ (yield* projection.searchThread({ threadId, query: "needle" })).snapshotSequence,+ before.snapshotSequence,+ );+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("searches displayed skill labels and invalidates parsed text when labels change", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ yield* putItems([item("skill", 1, "Use $test-t3-app now")]);+ const input = {+ threadId,+ query: "T3 App Testing",+ skills: [{ name: "test-t3-app", displayName: "T3 App Testing" }],+ };+ assert.equal((yield* projection.searchThread(input)).totalMatches, 1);+ assert.equal((yield* projection.searchThread({ ...input, skills: [] })).totalMatches, 0);+ // Plans render `$skill` tokens literally, so they match as written, not by label.+ yield* putItems(+ [item("skill-plan", 2, "# Verify\nUse $test-t3-app now", "proposed_plan")],+ "plan",+ );+ assert.equal((yield* projection.searchThread(input)).totalMatches, 1);+ assert.equal(+ (yield* projection.searchThread({ ...input, query: "$test-t3-app" })).totalMatches,+ 1,+ );+ // The message label "T3 App Testing" plus the plan's literal "$test-t3-app".+ assert.equal((yield* projection.searchThread({ ...input, query: "App" })).totalMatches, 2);+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("never mixes message versions when the searched thread changes during a scan", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ const sql = yield* SqlClient.SqlClient;+ const items = Array.from({ length: 260 }, (_, i) => item(`message:${i}`, i, "needle"));+ yield* putItems(items);+ const updated = items.map((item) =>+ item.type === "assistant_message" ? { ...item, text: "needle needle" } : item,+ );+ const [during] = yield* Effect.all(+ [+ projection.searchThread({ threadId, query: "needle" }),+ sql.withTransaction(putItems(updated, "concurrent")),+ ],+ { concurrency: "unbounded" },+ );+ assert.include([260, 520], during.totalMatches);+ assert.equal(+ (yield* projection.searchThread({ threadId, query: "needle" })).totalMatches,+ 520,+ );+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("starts at the reading position and wraps when no later match exists", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ yield* putItems([+ item("first", 1, "needle"),+ item("reading", 2, "needle above, needle below"),+ item("between", 3, "nothing"),+ item("last", 4, "needle"),+ item("end", 5, "nothing"),+ ]);+ const from = (entryId: string, occurrence = 0) =>+ projection.searchThread({ threadId, query: "needle", start: { entryId, occurrence } });+ assert.equal((yield* from("reading")).activeIndex, 1);+ const below = yield* from("reading", 1);+ assert.equal(below.activeIndex, 2);+ assert.equal(below.match?.occurrence, 1);+ assert.equal((yield* from("between")).match?.entryId, "last");+ assert.equal((yield* from("reading", 2)).activeIndex, 3);+ assert.equal((yield* from("end")).match?.entryId, "first");+ assert.equal((yield* from("missing")).activeIndex, 0);+ const explicit = yield* projection.searchThread({+ threadId,+ query: "needle",+ start: { entryId: "last", occurrence: 0 },+ index: 1,+ });+ assert.equal(explicit.match?.entryId, "reading");+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("finds matches beyond the recent history window", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ const items = Array.from({ length: 520 }, (_, i) =>+ item(`message:${i}`, i + 1, i === 8 || i === 510 ? "sentinel" : "other message"),+ );+ yield* putItems(items);+ const first = yield* projection.searchThread({ threadId, query: "sentinel" });+ const last = yield* projection.searchThread({ threadId, query: "sentinel", index: 1 });+ assert.equal(first.totalMatches, 2);+ assert.equal(first.match?.entryId, "message:8");+ assert.equal(last.match?.entryId, "message:510");+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("invalidates cached counts when streamed text changes or a run rolls back", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ const original = item("streaming", 1, "needle");+ yield* putItems([original]);+ assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 1);+ if (original.type !== "assistant_message") return;+ yield* putItems([{ ...original, text: "needle needle", streaming: true }], "streaming");+ assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 2);+ const updated = run(threadId, runId, 1, "rolled_back");+ yield* commit([{ ...updated, type: "run.updated" }]);+ assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 0);+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect(+ "does not search undispatched inputs, cancelled queue rows, or folded question answers",+ () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ const queuedRunId = RunId.make("queued:cancelled");+ yield* commit([run(threadId, queuedRunId, 2, "cancelled")]);+ const queued = item("cancelled", 1, "needle", "user_message");+ if (queued.type !== "user_message") return;+ const answer = item("async-answer:question", 2, "needle", "user_message");+ const question: OrchestrationV2TurnItem = {+ ...item("question", 3, ""),+ type: "user_input_request",+ requestId: RuntimeRequestId.make("question"),+ questions: [],+ questionAnswer: { requestId: "question", answers: {}, attachmentsByQuestionId: {} },+ };+ yield* putItems([+ { ...queued, runId: queuedRunId, inputIntent: "queued_turn" },+ answer,+ question,+ ]);+ const event: OrchestrationV2DomainEvent = {+ id: EventId.make("undispatched"),+ threadId,+ occurredAt: at(2),+ type: "message.updated",+ payload: {+ id: MessageId.make("undispatched"),+ threadId,+ runId: null,+ nodeId: null,+ role: "user",+ text: "needle",+ attachments: [],+ streaming: false,+ createdBy: "user",+ creationSource: "web",+ createdAt: at(2),+ updatedAt: at(2),+ },+ };+ yield* commit([event]);+ const result = yield* projection.searchThread({ threadId, query: "needle" });+ assert.equal(result.totalMatches, 0);+ assert.isNull(result.match);+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect(+ "searches inherited fork history through the fork boundary, using source item identities",+ () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ const parent = ThreadId.make("thread:parent");+ const laterRun = RunId.make("run:later");+ const parentRun = RunId.make("run:parent");+ yield* commit([+ thread(parent, projectId),+ run(parent, parentRun),+ run(parent, laterRun, 2),+ ]);+ yield* putItems([+ { ...item("inherited", 1, "needle", "assistant_message", parent), runId: parentRun },+ { ...item("after-fork", 2, "needle", "assistant_message", parent), runId: laterRun },+ ]);+ const child = thread(threadId, projectId);+ if (child.type !== "thread.created") return;+ yield* commit([+ {+ ...child,+ id: EventId.make("child:fork"),+ type: "thread.metadata-updated",+ payload: {+ ...child.payload,+ forkedFrom: { type: "run", threadId: parent, runId: parentRun },+ },+ },+ ]);+ yield* putItems([item("local", 1, "needle")]);+ const inherited = yield* projection.searchThread({ threadId, query: "needle" });+ assert.equal(inherited.totalMatches, 2);+ assert.equal(inherited.match?.entryId, "inherited");+ assert.equal(+ (yield* projection.searchThread({ threadId, query: "needle", index: 1 })).match?.entryId,+ "local",+ );+ const snapshot = yield* projection.getThreadSnapshot(threadId);+ const history = yield* projection.getThreadHistoryPage(+ threadId,+ encodeThreadHistoryCursor({+ snapshotSequence: snapshot.snapshotSequence,+ sourceThreadId: threadId,+ sourceItemId: "local",+ position: 2,+ }),+ );+ assert.deepEqual(+ history.items,+ snapshot.projection.visibleTurnItems+ .slice(0, -1)+ .map((row) => ({ ...row, item: projectTurnItemForWire(row.item) })),+ );+ assert.equal(history.items[0]?.sourceThreadId, parent);+ assert.equal(history.items.at(-1)?.item.type, "fork");+ // Parent updates invalidate a child's cached inherited result too.+ yield* putItems(+ [{ ...item("inherited", 1, "gone", "assistant_message", parent), runId: parentRun }],+ "parent-update",+ );+ assert.equal(+ (yield* projection.searchThread({ threadId, query: "needle" })).totalMatches,+ 1,+ );+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("rejects deleted threads and keeps results scoped to their thread", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ const other = ThreadId.make("thread:other");+ yield* commit([thread(other, projectId), run(other, RunId.make("run:other"))]);+ yield* putItems([+ item("shared-id", 1, "needle"),+ item("other-id", 1, "other text", "assistant_message", other),+ ]);+ assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 1);+ assert.equal(+ (yield* projection.searchThread({ threadId: other, query: "needle" })).totalMatches,+ 0,+ );+ const deleted = thread(threadId, projectId, { deletedAt: at(3) });+ if (deleted.type !== "thread.created") return;+ yield* commit([{ ...deleted, id: EventId.make("deleted"), type: "thread.deleted" }]);+ const error = yield* Effect.flip(projection.searchThread({ threadId, query: "needle" }));+ assert.equal(error._tag, "ProjectionStoreThreadNotFoundError");+ const historyError = yield* Effect.flip(+ projection.getThreadHistoryPage(+ threadId,+ encodeThreadHistoryCursor({+ snapshotSequence: 0,+ sourceThreadId: threadId,+ sourceItemId: "shared-id",+ position: 0,+ }),+ ),+ );+ assert.equal(historyError._tag, "ProjectionStoreThreadNotFoundError");+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("invalidates a cached fork search when its empty source gains its first message", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ const parent = ThreadId.make("thread:empty-parent");+ const parentRun = RunId.make("run:empty-parent");+ yield* commit([thread(parent, projectId), run(parent, parentRun)]);+ const child = thread(threadId, projectId);+ if (child.type !== "thread.created") return;+ yield* commit([+ {+ ...child,+ id: EventId.make("child:empty-fork"),+ type: "thread.metadata-updated",+ payload: {+ ...child.payload,+ forkedFrom: { type: "run", threadId: parent, runId: parentRun },+ },+ },+ ]);+ yield* putItems([item("local", 1, "needle")]);+ assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 1);+ yield* putItems([+ { ...item("inherited", 1, "needle", "assistant_message", parent), runId: parentRun },+ ]);+ const updated = yield* projection.searchThread({ threadId, query: "needle" });+ assert.equal(updated.totalMatches, 2);+ assert.equal(updated.match?.entryId, "inherited");+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("memory store resolves worktree file labels and rejects deleted threads", () =>+ Effect.gen(function* () {+ const projection = yield* ProjectionStore.ProjectionStoreV2;+ const created = thread(threadId, projectId);+ if (created.type !== "thread.created") return;+ const withWorktree = {+ ...created,+ payload: { ...created.payload, worktreePath: "/work/tree" },+ };+ const message = item("file", 1, "See `docs/notes.md:12`.");+ yield* Effect.forEach(+ [+ withWorktree,+ run(),+ {+ id: EventId.make("file"),+ threadId,+ occurredAt: at(1),+ type: "turn-item.updated",+ payload: message,+ },+ ] satisfies OrchestrationV2DomainEvent[],+ projection.apply,+ { discard: true },+ );+ assert.equal(+ (yield* projection.searchThread({ threadId, query: "notes.md · L12" })).totalMatches,+ 1,+ );+ const deleted = thread(threadId, projectId, { deletedAt: at(3) });+ if (deleted.type !== "thread.created") return;+ yield* projection.apply({ ...deleted, id: EventId.make("deleted"), type: "thread.deleted" });+ const error = yield* Effect.flip(projection.searchThread({ threadId, query: "notes" }));+ assert.equal(error._tag, "ProjectionStoreThreadNotFoundError");+ }).pipe(Effect.provide(ProjectionStore.layerMemory)),+ );+});++describe("V2 history materialization", () => {+ it.effect(+ "combines history pages through a match's message identity without skipping intervening turns",+ () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ const items = Array.from({ length: 45 }, (_, turn) => [+ item(`user:${turn}`, turn * 3, `turn ${turn}`, "user_message"),+ {+ ...item(`answer:${turn}`, turn * 3 + 1, `answer ${turn}`),+ messageId: MessageId.make(`message:${turn}`),+ },+ {+ ...item(`tool:${turn}`, turn * 3 + 2, ""),+ type: "command_execution" as const,+ input: "pwd",+ output: "huge output".repeat(1000),+ exitCode: 0,+ },+ ]).flat();+ yield* putItems(items);+ const snapshot = yield* projection.getThreadSnapshot(threadId);+ const cursor = encodeThreadHistoryCursor({+ snapshotSequence: snapshot.snapshotSequence,+ sourceThreadId: threadId,+ sourceItemId: "absent",+ position: items.length,+ });+ const ordinary = yield* projection.getThreadHistoryPage(threadId, cursor);+ assert.equal(ordinary.items[0]?.sourceItemId, "user:25");+ const targeted = yield* projection.getThreadHistoryPage(threadId, cursor, "message:10");+ assert.equal(targeted.items[0]?.sourceItemId, "user:10");+ assert.deepEqual(+ targeted.items.map((row) => row.sourceItemId),+ items.slice(30).map((entry) => entry.id),+ );+ const conversation = yield* projection.getThreadHistoryPage(+ threadId,+ cursor,+ "message:10",+ true,+ );+ assert.equal(conversation.nextCursor, targeted.nextCursor);+ assert.equal(conversation.hasMoreHistory, targeted.hasMoreHistory);+ assert.deepEqual(+ conversation.items.map((row) => row.sourceItemId),+ targeted.items+ .filter((row) => row.item.type !== "command_execution")+ .map((row) => row.sourceItemId),+ );+ assert.equal(conversation.items.length, 70);+ assert.equal(targeted.items.length, 105);+ assert.isTrue(targeted.hasMoreHistory);+ const earlier = yield* projection.getThreadHistoryPage(threadId, targeted.nextCursor!);+ assert.deepEqual(+ earlier.items.map((row) => row.sourceItemId),+ items.slice(0, 30).map((entry) => entry.id),+ );+ assert.isFalse(earlier.hasMoreHistory);+ const capped = yield* projection.getThreadHistoryPage(threadId, cursor, "message:0");+ assert.equal(capped.items[0]?.sourceItemId, "user:5");+ const absent = yield* projection.getThreadHistoryPage(+ threadId,+ cursor,+ "another-thread-message",+ );+ assert.deepEqual(absent, ordinary);+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("pages complete turns without duplicating or skipping messages", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ const items = Array.from({ length: 45 }, (_, turn) => [+ item(`user:${turn}`, turn * 3, `turn ${turn}`, "user_message"),+ {+ ...item(`steer:${turn}`, turn * 3 + 1, "steer", "user_message"),+ inputIntent: "steer" as const,+ },+ item(+ `answer:${turn}`,+ turn * 3 + 2,+ turn === 40 ? "large ".repeat(200_000) : `answer ${turn}`,+ ),+ ]).flat();+ yield* putItems(items);+ const snapshot = yield* projection.getThreadSnapshot(threadId);+ const rows = snapshot.projection.visibleTurnItems.map((row) => ({+ ...row,+ item: projectTurnItemForWire(row.item),+ }));+ let cursor: string | null = encodeThreadHistoryCursor({+ snapshotSequence: snapshot.snapshotSequence,+ sourceThreadId: threadId,+ sourceItemId: "absent",+ position: rows.length,+ });+ const collected: string[] = [];+ while (cursor !== null) {+ const page: OrchestrationV2ThreadHistoryPage = yield* projection.getThreadHistoryPage(+ threadId,+ cursor,+ );+ assert.deepEqual(page, {+ snapshotSequence: snapshot.snapshotSequence,+ ...selectHistoryPageFromCursor({+ items: rows,+ cursor,+ snapshotSequence: snapshot.snapshotSequence,+ }),+ });+ assert.equal(page.items[0]?.item.type, "user_message");+ collected.unshift(...page.items.map((row) => String(row.sourceItemId)));+ cursor = page.nextCursor;+ }+ assert.deepEqual(+ collected,+ items.map((entry) => String(entry.id)),+ );+ }).pipe(Effect.provide(layerTest)),+ );++ it.effect("enforces fallback item and byte limits and always admits an oversized row", () =>+ Effect.gen(function* () {+ const projection = yield* setup;+ yield* putItems(+ Array.from({ length: 80 }, (_, ordinal) =>+ item(`row:${ordinal}`, ordinal, ordinal < 78 ? "small" : "large ".repeat(200_000)),+ ),+ );+ const snapshot = yield* projection.getThreadSnapshot(threadId);+ const rows = snapshot.projection.visibleTurnItems.map((row) => ({+ ...row,+ item: projectTurnItemForWire(row.item),+ }));+ let cursor: string | null = encodeThreadHistoryCursor({+ snapshotSequence: snapshot.snapshotSequence,+ sourceThreadId: threadId,+ sourceItemId: "absent",+ position: rows.length,+ });+ const sizes: number[] = [];+ while (cursor !== null) {+ const page: OrchestrationV2ThreadHistoryPage = yield* projection.getThreadHistoryPage(+ threadId,+ cursor,+ );+ assert.deepEqual(page, {+ snapshotSequence: snapshot.snapshotSequence,+ ...selectHistoryPageFromCursor({+ items: rows,+ cursor,+ snapshotSequence: snapshot.snapshotSequence,+ }),+ });+ sizes.push(page.items.length);+ cursor = page.nextCursor;+ }+ assert.deepEqual(sizes, [1, 1, 75, 3]);+ }).pipe(Effect.provide(layerTest)),+ );+});diff --git a/apps/server/src/orchestration-v2/ThreadFind.ts b/apps/server/src/orchestration-v2/ThreadFind.tsnew file mode 100644index 00000000000..a764da8dd5f--- /dev/null+++ b/apps/server/src/orchestration-v2/ThreadFind.ts@@ -0,0 +1,449 @@+import {+ OrchestrationV2TurnItemJson,+ type OrchestrationV2ProjectedTurnItem,+ OrchestrationV2SearchThreadInput,+ type OrchestrationV2SearchThreadResult,+ type OrchestrationV2TurnItem,+ ThreadId,+ TurnItemId,+} from "@t3tools/contracts";+import { searchableMessageSegments, searchablePlanSegments } from "@t3tools/shared/threadFindText";+import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";+import * as Cache from "effect/Cache";+import * as Data from "effect/Data";+import * as Effect from "effect/Effect";+import * as Schema from "effect/Schema";+import * as Stream from "effect/Stream";+import * as SqlClient from "effect/sql/SqlClient";+import {+ ProjectionStoreReadError,+ ProjectionStoreThreadNotFoundError,+ type ProjectionStoreV2Error,+} from "./ProjectionStore.ts";++interface FindRow {+ readonly position: number;+ readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];+ readonly sourceThreadId: ThreadId;+ readonly sourceItemId: TurnItemId;+}+interface FindPayload extends FindRow {+ readonly payload: string;+ readonly entryId: string;+ readonly type: OrchestrationV2TurnItem["type"];+}+interface FindDocument extends FindRow {+ readonly entryId: string;+ readonly runId: OrchestrationV2TurnItem["runId"];+ readonly count: number;+}+class TextKey extends Data.Class<{+ text: string;+ role: "user" | "assistant" | "plan";+ streaming: boolean;+ hasContext: boolean;+ cwd: string | undefined;+ skills: NonNullable<OrchestrationV2SearchThreadInput["skills"]>;+}> {}++function textKey(+ item: OrchestrationV2TurnItem,+ cwd: string | undefined,+ skills: TextKey["skills"],+) {+ return new TextKey({+ text:+ item.type === "proposed_plan"+ ? item.markdown+ : item.type === "user_message" || item.type === "assistant_message"+ ? item.text+ : "",+ role:+ item.type === "proposed_plan" ? "plan" : item.type === "user_message" ? "user" : "assistant",+ streaming: item.type === "assistant_message" && item.streaming,+ hasContext: item.type === "user_message" && item.context !== undefined,+ cwd,+ skills,+ });+}++function parseText(key: TextKey): readonly string[] {+ return key.role === "plan"+ ? searchablePlanSegments(key.text, key.cwd)+ : (searchableMessageSegments(+ {+ role: key.role,+ text: key.text,+ streaming: key.streaming,+ context: key.hasContext ? { version: 1, records: [] } : undefined,+ },+ key.cwd,+ key.skills,+ ) ?? []);+}++function searchableRows(items: readonly OrchestrationV2ProjectedTurnItem[]) {+ const foldedAnswers = new Set(+ items.flatMap(({ item }) =>+ item.type === "user_input_request" && item.questionAnswer+ ? [`async-answer:${item.questionAnswer.requestId}`]+ : [],+ ),+ );+ return items.filter(+ ({ item }) =>+ ["user_message", "assistant_message", "proposed_plan"].includes(item.type) &&+ !(item.type === "user_message" && foldedAnswers.has(item.messageId)),+ );+}++function documentFor(row: OrchestrationV2ProjectedTurnItem, count: number): FindDocument {+ return {+ position: row.position,+ visibility: row.visibility,+ sourceThreadId: row.sourceThreadId,+ sourceItemId: row.sourceItemId,+ entryId:+ row.item.type === "user_message" || row.item.type === "assistant_message"+ ? row.item.messageId+ : row.item.id,+ runId: row.item.runId,+ count,+ };+}++function countSegments(segments: readonly string[], query: string) {+ return segments.reduce((sum, text) => sum + countThreadSearchOccurrences(text, query), 0);+}++function selectMatch(+ documents: readonly FindDocument[],+ input: Pick<OrchestrationV2SearchThreadInput, "index" | "start" | "offset">,+) {+ const totalMatches = documents.reduce((sum, doc) => sum + doc.count, 0);+ let requestedIndex = input.index ?? 0;+ if (input.index === undefined && input.start) {+ const startIndex = documents.findIndex((doc) => doc.entryId === input.start?.entryId);+ if (startIndex >= 0) {+ requestedIndex =+ documents.slice(0, startIndex).reduce((sum, doc) => sum + doc.count, 0) ++ Math.min(input.start.occurrence, documents[startIndex]!.count);+ if (requestedIndex >= totalMatches) requestedIndex = 0;+ }+ }+ const activeIndex =+ input.index === undefined && totalMatches > 0+ ? (((requestedIndex + (input.offset ?? 0)) % totalMatches) + totalMatches) % totalMatches+ : Math.min(requestedIndex, Math.max(0, totalMatches - 1));+ let occurrence = activeIndex;+ for (const document of documents) {+ if (occurrence < document.count) return { totalMatches, activeIndex, document, occurrence };+ occurrence -= document.count;+ }+ return { totalMatches, activeIndex, document: null, occurrence: 0 };+}++/** The memory projection uses the same match ordering as SQLite. */+export function findProjectedThreadItems(+ items: readonly OrchestrationV2ProjectedTurnItem[],+ input: OrchestrationV2SearchThreadInput,+ snapshotSequence: number,+ cwd?: string,+): OrchestrationV2SearchThreadResult {+ const rows = searchableRows(items);+ const docs = rows.map((row) =>+ documentFor(+ row,+ countSegments(parseText(textKey(row.item, cwd, input.skills ?? [])), input.query),+ ),+ );+ return resultForSelection(selectMatch(docs, input), docs, snapshotSequence);+}++function resultForSelection(+ selected: ReturnType<typeof selectMatch>,+ documents: readonly FindDocument[],+ snapshotSequence: number,+): OrchestrationV2SearchThreadResult {+ let startIndex = 0;+ const entries = documents.flatMap(({ entryId, runId, count }) => {+ const entry = { entryId, runId, count, startIndex };+ startIndex += count;+ return count > 0 ? [entry] : [];+ });+ const selectedEntry = entries.findIndex((entry) => entry.entryId === selected.document?.entryId);+ const navigation =+ entries.length <= 17+ ? entries+ : Array.from(+ { length: 17 },+ (_, i) => entries[(selectedEntry + i - 8 + entries.length) % entries.length]!,+ );+ return {+ snapshotSequence,+ totalMatches: selected.totalMatches,+ activeIndex: selected.activeIndex,+ navigation,+ match:+ selected.document === null+ ? null+ : {+ entryId: selected.document.entryId,+ runId: selected.document.runId,+ occurrence: selected.occurrence,+ },+ };+}++/** Read the canonical index once per scan, including inherited fork rows, without tool bodies. */+export const makeThreadFind = Effect.fn("makeThreadFind")(function* (+ readIndex: (threadId: ThreadId) => Effect.Effect<+ readonly (Omit<FindRow, "position"> & {+ readonly item: Pick<OrchestrationV2TurnItem, "type">;+ })[],+ ProjectionStoreV2Error+ >,+) {+ const sql = yield* SqlClient.SqlClient;+ const encodeCacheKey = Schema.encodeEffect(+ Schema.fromJsonString(+ Schema.Struct({+ threadId: ThreadId,+ cwd: Schema.optional(Schema.String),+ query: Schema.String,+ skills: OrchestrationV2SearchThreadInput.fields.skills,+ }),+ ),+ );+ const encodeThreadIds = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(ThreadId)));+ const encodeSources = Schema.encodeEffect(+ Schema.fromJsonString(Schema.Array(Schema.Struct({ threadId: ThreadId, id: TurnItemId }))),+ );+ const decodeItem = Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2TurnItemJson));+ const isSnapshotError = Schema.is(+ Schema.Union([ProjectionStoreReadError, ProjectionStoreThreadNotFoundError]),+ );+ const load = Effect.fn("ThreadFind.load")(function* (+ threadId: ThreadId,+ rows: readonly FindRow[],+ ) {+ if (rows.length === 0) return [];+ const sources = yield* encodeSources(+ rows.map((row) => ({ threadId: row.sourceThreadId, id: row.sourceItemId })),+ ).pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })));+ const payloads = yield* sql<{+ thread_id: string;+ turn_item_id: string;+ payload_json: string;+ entry_id: string;+ item_type: OrchestrationV2TurnItem["type"];+ }>`+ SELECT item.thread_id, item.turn_item_id, item.payload_json,+ COALESCE(json_extract(item.payload_json, '$.messageId'), item.turn_item_id) AS entry_id,+ json_extract(item.payload_json, '$.type') AS item_type+ FROM orchestration_v2_projection_turn_items AS item+ JOIN json_each(${sources}) AS wanted+ ON item.thread_id = json_extract(wanted.value, '$.threadId')+ AND item.turn_item_id = json_extract(wanted.value, '$.id')+ `.pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })));+ const byThread = new Map<string, Map<string, (typeof payloads)[number]>>();+ for (const row of payloads) {+ let items = byThread.get(row.thread_id);+ if (!items) byThread.set(row.thread_id, (items = new Map()));+ items.set(row.turn_item_id, row);+ }+ return yield* Effect.forEach(rows, (row) => {+ const payload = byThread.get(row.sourceThreadId)?.get(row.sourceItemId);+ return payload === undefined+ ? Effect.fail(new ProjectionStoreReadError({ threadId }))+ : Effect.succeed({+ ...row,+ payload: payload.payload_json,+ entryId: payload.entry_id,+ type: payload.item_type,+ });+ });+ });+ // Cache rendered segments, not queries; typing and navigation reuse Markdown parsing.+ const textCache = yield* Cache.make({+ capacity: 512,+ timeToLive: "1 minute",+ lookup: (key: TextKey) => Effect.sync(() => parseText(key)),+ });+ // Bounded separately because each entry can hold a large body; typing reuses the parse.+ const largeTextCache = yield* Cache.make({+ capacity: 32,+ timeToLive: "1 minute",+ lookup: (key: TextKey) => Effect.sync(() => parseText(key)),+ });+ // Scans retain counts and item references, never message bodies. Navigation checks+ // the current revision in its transaction without reloading message payloads.+ const scans = new Map<+ string,+ {+ sequence: number;+ documents: readonly FindDocument[];+ sourceThreadIds: readonly ThreadId[];+ }+ >();+ const readRevision = Effect.fn("ThreadFind.readRevision")(function* (+ threadIds: readonly ThreadId[],+ ) {+ const sources = yield* encodeThreadIds(threadIds);+ const revision = yield* sql<{ sequence: number }>`+ WITH RECURSIVE source_threads(thread_id) AS (+ SELECT value FROM json_each(${sources})+ UNION+ SELECT json_extract(t.payload_json, '$.forkedFrom.threadId')+ FROM orchestration_v2_projection_threads t+ JOIN source_threads s ON s.thread_id = t.thread_id+ WHERE json_extract(t.payload_json, '$.forkedFrom.type') = 'run'+ )+ SELECT COALESCE(MAX(sequence), 0) AS sequence FROM orchestration_events+ WHERE application_event_version = 2 AND aggregate_kind = 'thread'+ AND stream_id IN (SELECT thread_id FROM source_threads)+ `;+ return revision[0]?.sequence ?? 0;+ });+ const snapshot = Effect.fn("ThreadFind.snapshot")(+ function* (input: OrchestrationV2SearchThreadInput) {+ const { threadId } = input;+ const active = yield* sql<{ cwd: string | null }>`+ SELECT COALESCE(json_extract(t.payload_json, '$.worktreePath'), p.workspace_root) AS cwd+ FROM orchestration_v2_projection_threads t JOIN projection_projects p ON p.project_id = t.project_id+ WHERE t.thread_id = ${threadId} AND t.deleted_at IS NULL AND p.deleted_at IS NULL+ `;+ if (!active[0]) return yield* new ProjectionStoreThreadNotFoundError({ threadId });+ const cwd = active[0].cwd ?? undefined;+ const cacheKey = yield* encodeCacheKey({+ threadId,+ cwd,+ query: input.query,+ skills: input.skills ?? [],+ });+ const cached = scans.get(cacheKey);+ if (cached && cached.sequence === (yield* readRevision(cached.sourceThreadIds))) {+ const selected = selectMatch(cached.documents, input);+ scans.delete(cacheKey);+ scans.set(cacheKey, cached);+ return { result: resultForSelection(selected, cached.documents, cached.sequence) };+ }+ const index = yield* readIndex(threadId);+ const sourceThreadIds = [...new Set([threadId, ...index.map((row) => row.sourceThreadId)])];+ const sequence = yield* readRevision(sourceThreadIds);+ const candidates = index+ .map((row, position) => ({ ...row, position }))+ .filter((row) =>+ ["user_message", "assistant_message", "proposed_plan", "user_input_request"].includes(+ row.item.type,+ ),+ );+ const payloads: FindPayload[] = [];+ for (let start = 0; start < candidates.length; start += 128) {+ payloads.push(...(yield* load(threadId, candidates.slice(start, start + 128))));+ }+ return { payloads, cwd, sequence, cacheKey, sourceThreadIds };+ },+ sql.withTransaction,+ (effect, input) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isSnapshotError(cause)+ ? cause+ : new ProjectionStoreReadError({ threadId: input.threadId, cause }),+ ),+ ),+ );+ const searchThreadStream = (input: OrchestrationV2SearchThreadInput) =>+ Stream.unwrap(+ Effect.gen(function* () {+ // Release SQLite before decoding and parsing. Both frames describe one snapshot.+ const data = yield* snapshot(input);+ if (data.result) return Stream.succeed(data.result);+ const { payloads, cwd, sequence, cacheKey, sourceThreadIds } = data;+ const decode = (row: FindPayload) =>+ decodeItem(row.payload).pipe(+ Effect.map((item) => ({ ...row, item })),+ Effect.mapError(+ (cause) => new ProjectionStoreReadError({ threadId: input.threadId, cause }),+ ),+ );+ // Answers rendered inside question cards must not appear as separate matches.+ const foldedAnswers = new Set<string>();+ for (const payload of payloads) {+ if (payload.type !== "user_input_request") continue;+ const { item } = yield* decode(payload);+ if (item.type === "user_input_request" && item.questionAnswer)+ foldedAnswers.add(`async-answer:${item.questionAnswer.requestId}`);+ }+ const rows = payloads.filter(+ (row) =>+ row.type !== "user_input_request" &&+ !(row.type === "user_message" && foldedAnswers.has(row.entryId)),+ );+ const documents = new Map<number, FindDocument>();+ const count = Effect.fnUntraced(function* (row: FindPayload) {+ const cached = documents.get(row.position);+ if (cached) return cached;+ const decoded = yield* decode(row);+ const key = textKey(decoded.item, cwd, input.skills ?? []);+ const segments = yield* Cache.get(+ key.text.length <= 32_768 ? textCache : largeTextCache,+ key,+ );+ const document = documentFor(decoded, countSegments(segments, input.query));+ documents.set(row.position, document);+ yield* Effect.yieldNow;+ return document;+ });+ const finish = Effect.gen(function* () {+ for (const row of rows) yield* count(row);+ const ordered = rows.map((row) => documents.get(row.position)!);+ scans.delete(cacheKey);+ scans.set(cacheKey, { sequence, documents: ordered, sourceThreadIds });+ if (scans.size > 8) {+ const oldest = scans.keys().next().value;+ if (oldest !== undefined) scans.delete(oldest);+ }+ return resultForSelection(selectMatch(ordered, input), ordered, sequence);+ });+ // Relative navigation needs the final counts. Initial searches can reveal an+ // identity immediately, scanning at/below the reading anchor before wrapping.+ if (input.index !== undefined || (input.offset ?? 0) !== 0)+ return Stream.fromEffect(finish);+ const anchor = Math.max(+ 0,+ rows.findIndex((row) => row.entryId === input.start?.entryId),+ );+ for (let step = 0; step <= rows.length; step++) {+ const index = (anchor + step) % rows.length;+ const row = rows[index];+ if (!row) break;+ const document = yield* count(row);+ const occurrence =+ step === 0 && row.entryId === input.start?.entryId+ ? Math.min(input.start.occurrence, document.count)+ : 0;+ if (occurrence >= document.count) continue;+ const first: OrchestrationV2SearchThreadResult = {+ complete: false,+ snapshotSequence: sequence,+ totalMatches: 1,+ activeIndex: 0,+ match: { entryId: document.entryId, runId: document.runId, occurrence },+ };+ // The remainder is pulled only after the first frame has been delivered.+ return Stream.concat(Stream.succeed(first), Stream.fromEffect(finish));+ }+ return Stream.fromEffect(finish);+ }),+ );+ return {+ searchThreadStream,+ searchThread: (input: OrchestrationV2SearchThreadInput) =>+ searchThreadStream(input).pipe(+ Stream.runCollect,+ Effect.map((results) => results[results.length - 1]!),+ ),+ };+});diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.tsindex e59fce35bcb..a12e6680ca7 100644--- a/apps/server/src/orchestration-v2/ThreadManagementService.ts+++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts@@ -1,3 +1,7 @@+import type {+ OrchestrationV2SearchThreadInput,+ OrchestrationV2SearchThreadResult,+} from "@t3tools/contracts";import type {ProjectionRecordField,ProjectionRecordFilter,@@ -271,12 +275,19 @@ export type ThreadManagementError = typeof ThreadManagementError.Type;type ThreadManagementFailure = ThreadManagementError | Orchestrator.OrchestratorV2Error;export interface ThreadManagementServiceShape {+ readonly searchThreadStream: (+ input: OrchestrationV2SearchThreadInput,+ ) => Stream.Stream<OrchestrationV2SearchThreadResult, Orchestrator.OrchestratorV2Error>;+ readonly searchThread: (+ input: OrchestrationV2SearchThreadInput,+ ) => Effect.Effect<OrchestrationV2SearchThreadResult, Orchestrator.OrchestratorV2Error>;readonly ensureLegacyTranscript: (threadId: ThreadId,) => Effect.Effect<void, LegacyV1ThreadImporter.LegacyV1ThreadImportError>;readonly dispatch: (command: OrchestrationV2ServerCommand,) => Effect.Effect<Orchestrator.OrchestratorV2DispatchResult, Orchestrator.OrchestratorV2Error>;+ readonly getThreadHistoryPage: Orchestrator.OrchestratorV2["Service"]["getThreadHistoryPage"];readonly getTimelinePage: Orchestrator.OrchestratorV2["Service"]["getTimelinePage"];readonly getMessageCount: Orchestrator.OrchestratorV2["Service"]["getMessageCount"];/**@@ -859,7 +870,23 @@ const make = Effect.gen(function* () {return ThreadManagementService.of({ensureLegacyTranscript,+ searchThreadStream: (input) =>+ Stream.unwrap(+ ensureProjectionTranscript(input.threadId).pipe(+ Effect.as(orchestrator.searchThreadStream(input)),+ ),+ ),+ searchThread: (input) =>+ ensureProjectionTranscript(input.threadId).pipe(+ Effect.andThen(orchestrator.searchThread(input)),+ ),dispatch,+ getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>+ ensureProjectionTranscript(threadId).pipe(+ Effect.andThen(+ orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly),+ ),+ ),getTimelinePage: (threadId, options) =>ensureProjectionTranscript(threadId).pipe(Effect.andThen(orchestrator.getTimelinePage(threadId, options)),diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.tsindex 8f8c30034c4..8f67002333b 100644--- a/apps/server/src/orchestration-v2/http.ts+++ b/apps/server/src/orchestration-v2/http.ts@@ -1,8 +1,6 @@import {AuthOrchestrationReadScope,EnvironmentHttpApi,- ThreadId,- TurnItemId,type OrchestrationProjectShell,} from "@t3tools/contracts";import * as Effect from "effect/Effect";@@ -24,7 +22,6 @@ import {buildBoundedThreadProjection,decodeThreadHistoryCursor,InvalidThreadHistoryCursorError,- selectHistoryPageFromCursor,THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,THREAD_HISTORY_PAGE_POLICY,OLDER_THREAD_USER_TURN_LIMIT,@@ -43,22 +40,6 @@ function isThreadNotFound(error: unknown): boolean {);}-function selectHistoryPageFromCursorOrError(- input: Parameters<typeof selectHistoryPageFromCursor>[0],-):- | { readonly _tag: "ok"; readonly page: ReturnType<typeof selectHistoryPageFromCursor> }- | { readonly _tag: "invalid_cursor" }- | { readonly _tag: "error"; readonly cause: unknown } {- try {- return { _tag: "ok", page: selectHistoryPageFromCursor(input) };- } catch (cause) {- if (cause instanceof InvalidThreadHistoryCursorError) {- return { _tag: "invalid_cursor" };- }- return { _tag: "error", cause };- }-}-/*** Serves orchestration V2 snapshots over HTTP so clients can load the* (potentially large) shell and thread projections off the socket; gzip@@ -222,41 +203,33 @@ export const layer = HttpApiBuilder.group(Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) {yield* annotateEnvironmentRequest(args.endpoint.name);yield* requireEnvironmentScope(AuthOrchestrationReadScope);- let anchorItemId;try {- anchorItemId = TurnItemId.make(decodeThreadHistoryCursor(args.query.cursor).si);+ decodeThreadHistoryCursor(args.query.cursor);} catch (cause) {- if (cause instanceof InvalidThreadHistoryCursorError) {+ if (cause instanceof InvalidThreadHistoryCursorError)return yield* failEnvironmentInvalidRequest("invalid_history_cursor");- }return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause);}- const decodedCursor = decodeThreadHistoryCursor(args.query.cursor);- const snapshot = yield* loadThreadSnapshotWindow(- args.params.threadId,- anchorItemId,- ThreadId.make(decodedCursor.st),- ).pipe(traceLocalHandlerWork);- const pageOrError = selectHistoryPageFromCursorOrError({- items: snapshot.projection.visibleTurnItems,- cursor: args.query.cursor,- snapshotSequence: snapshot.snapshotSequence,- });- if (pageOrError._tag === "invalid_cursor") {- return yield* failEnvironmentInvalidRequest("invalid_history_cursor");- }- if (pageOrError._tag === "error") {- return yield* failEnvironmentInternal(- "orchestration_thread_history_failed",- pageOrError.cause,+ return yield* threadManagement+ .getThreadHistoryPage(+ args.params.threadId,+ args.query.cursor,+ args.query.throughEntryId,+ args.query.view === "conversation",+ )+ .pipe(+ traceLocalHandlerWork,+ Effect.catch(+ Effect.fnUntraced(function* (cause) {+ if (isThreadNotFound(cause))+ return yield* failEnvironmentNotFound("thread_not_found");+ return yield* failEnvironmentInternal(+ "orchestration_thread_history_failed",+ cause,+ );+ }),+ ),);- }- return {- snapshotSequence: snapshot.snapshotSequence,- items: pageOrError.page.items,- nextCursor: pageOrError.page.nextCursor,- hasMoreHistory: pageOrError.page.hasMoreHistory,- };}),);}),diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.tsindex a2e6c87e20d..8ee7c2641bd 100644--- a/apps/server/src/orchestration-v2/threadHistoryPaging.ts+++ b/apps/server/src/orchestration-v2/threadHistoryPaging.ts@@ -17,6 +17,11 @@ export const THREAD_HISTORY_PAGE_POLICY = {} as const;export const OLDER_THREAD_USER_TURN_LIMIT = 20;++/** Load conversation rows before the bulk of a turn's folded tool activity. */+export function isConversationHistoryItem(item: Pick<OrchestrationV2TurnItem, "type">): boolean {+ return !["command_execution", "reasoning", "file_change", "dynamic_tool"].includes(item.type);+}export const THREAD_HISTORY_MAX_RAW_TURNS = 150;/** Extra rows let the projection query retain an inclusive cursor and prove another page exists. */@@ -39,8 +44,19 @@ export type ThreadHistoryCursorPayload = {readonly p: number;};-export type SelectTimelinePageResult = {- readonly items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;+type HistoryRow = Pick<+ OrchestrationV2ProjectedTurnItem,+ "position" | "visibility" | "sourceThreadId" | "sourceItemId"+> & {+ readonly item: Pick<OrchestrationV2TurnItem, "type"> & {+ readonly id?: string;+ readonly messageId?: string;+ readonly inputIntent?: string;+ readonly createdBy?: string;+ };+};+export type SelectTimelinePageResult<Row extends HistoryRow = OrchestrationV2ProjectedTurnItem> = {+ readonly items: ReadonlyArray<Row>;readonly nextCursor: string | null;readonly hasMoreHistory: boolean;};@@ -67,7 +83,7 @@ function bytesOfJson(value: unknown): number {}/** Ordinary history-page cost: one projected row (item is nested once). */-export function projectedRowEncodedBytes(row: OrchestrationV2ProjectedTurnItem): number {+export function projectedRowEncodedBytes(row: HistoryRow): number {return bytesOfJson(row);}@@ -87,9 +103,7 @@ export function projectedRowBoundedSnapshotEncodedBytes(return rowBytes;}-function renumberPositions(- items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,-): OrchestrationV2ProjectedTurnItem[] {+function renumberPositions<Row extends HistoryRow>(items: ReadonlyArray<Row>): Row[] {return items.map((row, position) => (row.position === position ? row : { ...row, position }));}@@ -148,7 +162,7 @@ export function decodeThreadHistoryCursor(cursor: string): ThreadHistoryCursorPareturn parsed as ThreadHistoryCursorPayload;}-export function isThreadHistoryTurnStart(item: OrchestrationV2TurnItem): boolean {+export function isThreadHistoryTurnStart(item: HistoryRow["item"]): boolean {return (item.type === "user_message" &&(item.inputIntent === "turn_start" || item.inputIntent === "queued_turn")@@ -156,7 +170,7 @@ export function isThreadHistoryTurnStart(item: OrchestrationV2TurnItem): boolean}/** Steering belongs to its existing turn and must not consume another page slot. */-export function isThreadHistoryUserTurn(item: OrchestrationV2TurnItem): boolean {+export function isThreadHistoryUserTurn(item: HistoryRow["item"]): boolean {return (isThreadHistoryTurnStart(item) && item.type === "user_message" && item.createdBy === "user");@@ -167,13 +181,13 @@ export function isThreadHistoryUserTurn(item: OrchestrationV2TurnItem): boolean* through complete user turns. Histories without turn starts use row budgets* and always admit at least one row so oversized items cannot deadlock paging.*/-function selectOlderTimelinePage(input: {- readonly items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;+function selectOlderTimelinePage<Row extends HistoryRow>(input: {+ readonly items: ReadonlyArray<Row>;readonly exclusiveEndIndex: number;readonly snapshotSequence: number;readonly policy?: ThreadHistoryPagePolicy | undefined;- readonly rowEncodedBytes?: ((row: OrchestrationV2ProjectedTurnItem) => number) | undefined;-}): SelectTimelinePageResult {+ readonly rowEncodedBytes?: ((row: Row) => number) | undefined;+}): SelectTimelinePageResult<Row> {const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY;const rowCost = input.rowEncodedBytes ?? projectedRowEncodedBytes;const end = Math.min(Math.max(input.exclusiveEndIndex, 0), input.items.length);@@ -181,7 +195,7 @@ function selectOlderTimelinePage(input: {return { items: [], nextCursor: null, hasMoreHistory: false };}- const selected: OrchestrationV2ProjectedTurnItem[] = [];+ const selected: Row[] = [];let encodedBytes = 0;let userTurns = 0;let rawTurns = 0;@@ -247,7 +261,7 @@ export function selectRecentTimelineWindow(input: {}function findCursorIndex(- items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,+ items: ReadonlyArray<Pick<HistoryRow, "sourceThreadId" | "sourceItemId">>,cursor: ThreadHistoryCursorPayload,): number {const byIdentity = items.findIndex(@@ -264,22 +278,48 @@ function findCursorIndex(return Math.min(cursor.p, items.length);}-export function selectHistoryPageFromCursor(input: {- readonly items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;+export function selectHistoryPageFromCursor<Row extends HistoryRow>(input: {+ readonly items: ReadonlyArray<Row>;readonly cursor: string;readonly snapshotSequence: number;readonly policy?: ThreadHistoryPagePolicy | undefined;-}): SelectTimelinePageResult {+ readonly rowEncodedBytes?: ((row: Row) => number) | undefined;+ readonly throughEntryId?: string | undefined;+}): SelectTimelinePageResult<Row> {const decoded = decodeThreadHistoryCursor(input.cursor);const anchorIndex = findCursorIndex(input.items, decoded);+ let policy = input.policy ?? {+ ...THREAD_HISTORY_PAGE_POLICY,+ maxUserTurns: OLDER_THREAD_USER_TURN_LIMIT,+ };+ if (input.throughEntryId !== undefined) {+ const targetIndex = input.items.findIndex(+ (row) => (row.item.messageId ?? row.item.id) === input.throughEntryId,+ );+ if (targetIndex >= 0 && targetIndex < anchorIndex) {+ // A search jump can combine two pages, but never grow into an unbounded read.+ const turns = input.items+ .slice(targetIndex, anchorIndex)+ .filter((row) => isThreadHistoryUserTurn(row.item)).length;+ policy = {+ ...policy,+ maxUserTurns: Math.min(+ OLDER_THREAD_USER_TURN_LIMIT * 2,+ Math.max(+ OLDER_THREAD_USER_TURN_LIMIT,+ turns + (isThreadHistoryUserTurn(input.items[targetIndex]!.item) ? 0 : 1),+ ),+ ),+ maxItems: policy.maxItems * 2,+ };+ }+ }return selectOlderTimelinePage({items: input.items,exclusiveEndIndex: anchorIndex,snapshotSequence: input.snapshotSequence,- policy: input.policy ?? {- ...THREAD_HISTORY_PAGE_POLICY,- maxUserTurns: OLDER_THREAD_USER_TURN_LIMIT,- },+ ...(input.rowEncodedBytes === undefined ? {} : { rowEncodedBytes: input.rowEncodedBytes }),+ policy,});}diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.tsindex aa64f048ad8..f10af26391c 100644--- a/apps/server/src/relay/AgentAwarenessRelay.test.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts@@ -193,6 +193,9 @@ const makeTestRelay = Effect.fnUntraced(function* (readShellSnapshot: unused,ensureLegacyTranscript: unused,dispatch: unused,+ searchThread: () => Effect.die("unused"),+ searchThreadStream: () => Stream.empty,+ getThreadHistoryPage: () => Effect.die("unused"),getTimelinePage: () => Effect.die("Unused timeline read"),getMessageCount: () => Effect.die("unused message count"),getTurnItem: () => Effect.die("unused turn item read"),diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 70238f10a88..2a11852ecbc 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -52,6 +52,7 @@ import {type AcpRegistrySetProviderInput,OrchestrationGetFullThreadDiffError,OrchestrationSearchThreadsError,+ OrchestrationV2SearchThreadError,OrchestrationGetTurnDiffError,ORCHESTRATION_V2_WS_METHODS,ORCHESTRATION_PROTOCOL_QUERY_PARAM,@@ -1727,6 +1728,8 @@ const layerWsRpc = (shellResumeCompletionMarker: true,threadResumeCompletionMarker: true,threadSnapshotPagination: true,+ threadFind: true,+ threadFindProgressive: true,...Option.match(scratchWorkspaceRoot, {onNone: () => ({}),onSome: (root) => ({ scratchWorkspaceRoot: root }),@@ -1894,6 +1897,14 @@ const layerWsRpc = (}),),),+ [ORCHESTRATION_V2_WS_METHODS.searchThread]: (input) =>+ threadManagement+ .searchThread(input)+ .pipe(Effect.mapError((cause) => new OrchestrationV2SearchThreadError({ cause }))),+ [ORCHESTRATION_V2_WS_METHODS.searchThreadStream]: (input) =>+ threadManagement+ .searchThreadStream(input)+ .pipe(Stream.mapError((cause) => new OrchestrationV2SearchThreadError({ cause }))),[ORCHESTRATION_V2_WS_METHODS.searchThreads]: (input) =>threadSearch.search(input).pipe(Effect.mapError(diff --git a/apps/web/package.json b/apps/web/package.jsonindex 915466100bc..20e180aad46 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -60,10 +60,7 @@"react": "19.2.6","react-dom": "19.2.6","react-markdown": "^10.1.0",- "rehype-raw": "^7.0.0",- "rehype-sanitize": "^6.0.0",- "remark-breaks": "^4.0.0",- "remark-gfm": "^4.0.1",+ "remark-gfm": "catalog:","tailwind-merge": "^3.4.0","unbash": "^5.0.0","zustand": "^5.0.11"@@ -88,7 +85,7 @@"jsdom": "^30.0.1","react-test-renderer": "19.2.6","tailwindcss": "^4.0.0",- "unified": "^11.0.5",+ "unified": "catalog:","vite": "catalog:","vite-plus": "catalog:"}diff --git a/apps/web/src/components/ChatMarkdown.test.tsx b/apps/web/src/components/ChatMarkdown.test.tsxindex b1ceb33062c..08fb61eac0b 100644--- a/apps/web/src/components/ChatMarkdown.test.tsx+++ b/apps/web/src/components/ChatMarkdown.test.tsx@@ -1,6 +1,12 @@// @vitest-environment jsdomimport { EnvironmentId, type AuthEnvironmentScope } from "@t3tools/contracts";+import { createRoot } from "react-dom/client";+import { useThreadFindHighlights } from "./chat/threadFindHighlights";+import { searchableMessageSegments } from "@t3tools/shared/threadFindText";+import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";++import { MarkdownFindContext } from "./chat/markdownFindContext";import { act, type ComponentProps, type ReactNode } from "react";import { renderToStaticMarkup } from "react-dom/server";import { create, type ReactTestRenderer } from "react-test-renderer";@@ -12,6 +18,10 @@ import { Button } from "./ui/button";import { setMarkdownTaskChecked } from "./files/filePreviewMode";vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));+vi.mock("./chat/MermaidDiagram", () => ({+ // Real Mermaid needs layout APIs jsdom lacks; a rendered diagram is an SVG.+ MermaidDiagram: () => <svg aria-label="Diagram" />,+}));vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));vi.mock("../hooks/useSettings", async (importOriginal) => {const actual = await importOriginal<typeof import("../hooks/useSettings")>();@@ -1034,3 +1044,231 @@ describe("ChatMarkdown Windows file links", () => {expect(html).not.toContain("chat-markdown-file-link");});});++it("opens a disclosure only when find selects a match inside it", async () => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.stubGlobal(+ "Highlight",+ class extends Set<Range> {+ constructor(...ranges: Range[]) {+ super(ranges);+ }+ },+ );+ const highlights = new Map<string, Set<Range>>();+ vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ const openStates = () =>+ [...container.querySelectorAll("[data-markdown-details-open]")].map((node) =>+ node.getAttribute("data-markdown-details-open"),+ );+ function Probe({+ activeOccurrence,+ searching = true,+ }: {+ activeOccurrence: number;+ searching?: boolean;+ }) {+ useThreadFindHighlights({+ container,+ query: searching ? "needle" : "",+ activeRowId: "row",+ activeOccurrence,+ onActiveRange: () => {},+ });+ return (+ <div data-timeline-row-id="row">+ <div data-thread-find-text>+ <MarkdownFindContext value={searching}>+ <ChatMarkdown+ cwd={undefined}+ text={[+ "Visible needle.",+ "<details><summary>Unrelated</summary><p>nothing here</p></details>",+ "<details><summary>Outer</summary><details><summary>Inner</summary><p>needle</p></details></details>",+ ].join("\n\n")}+ />+ </MarkdownFindContext>+ </div>+ </div>+ );+ }+ const frame = () =>+ act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));+ try {+ // Closed panels are unmounted until find starts, as in the app.+ await act(() => root.render(<Probe activeOccurrence={0} searching={false} />));+ expect(container.textContent).not.toContain("nothing here");+ await act(() => root.render(<Probe activeOccurrence={0} />));+ await frame();+ // Selecting the visible match opens nothing; the folded one is counted but not painted.+ expect(openStates()).toEqual(["false", "false", "false"]);+ expect(container.textContent).toContain("nothing here");+ expect(+ [...(highlights.get("t3-thread-find-active") ?? [])].map((range) => range.toString()),+ ).toEqual(["needle"]);+ expect(highlights.get("t3-thread-find")?.size).toBe(0);++ await act(() => root.render(<Probe activeOccurrence={1} />));+ await frame();+ await frame();+ // Stepping to the folded match opens its two ancestors, not the unrelated one.+ expect(openStates()).toEqual(["false", "true", "true"]);+ expect(highlights.get("t3-thread-find-active")?.size).toBe(1);+ } finally {+ await act(() => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+ }+});++it("keeps Mermaid diagrams rendered until find selects a match in their source", async () => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.stubGlobal(+ "Highlight",+ class extends Set<Range> {+ constructor(...ranges: Range[]) {+ super(ranges);+ }+ },+ );+ const highlights = new Map<string, Set<Range>>();+ vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ const diagram = "```mermaid\ngraph TD; Alpha-->Beta\n```";+ function Probe({ query }: { query: string }) {+ useThreadFindHighlights({+ container,+ query,+ activeRowId: "row",+ activeOccurrence: 0,+ onActiveRange: () => {},+ });+ return (+ <div data-timeline-row-id="row">+ <div data-thread-find-text>+ <MarkdownFindContext value={true}>+ <ChatMarkdown cwd={undefined} text={`Needle first.\n\n${diagram}\n\n${diagram}`} />+ </MarkdownFindContext>+ </div>+ </div>+ );+ }+ const frame = () =>+ act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));+ const diagrams = () => container.querySelectorAll('svg[aria-label="Diagram"]').length;+ try {+ await act(() => root.render(<Probe query="Needle" />));+ await frame();+ expect(diagrams()).toBe(2);+ await act(() => root.render(<Probe query="Alpha" />));+ await frame();+ await frame();+ // Only the diagram holding the selected match switches to source.+ expect(diagrams()).toBe(1);+ expect(+ [...(highlights.get("t3-thread-find-active") ?? [])].map((range) => range.toString()),+ ).toEqual(["Alpha"]);+ } finally {+ await act(() => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+ }+});++it.each([+ {+ text: "```mermaid\ngraph TD; SearchSourceAlpha-->B\n```",+ query: "SearchSourceAlpha",+ count: 1,+ },+ {+ text: "★ Insight ─────\nfirst line\nsecond line",+ query: "first line second",+ count: 0,+ lineBreaks: true,+ },+ { text: '```ts title="src/needle.ts"\nconst a = 1;\n```', query: "needle", count: 0 },+ { text: "```weirdlang\nconst a = 1;\n```", query: "weirdlang", count: 0 },+ { text: "Use $test-t3-app now", query: "T3 App Testing", count: 1 },+ { text: "`/tmp/file.ts:42`", query: "file.ts · L42", count: 1, user: true, lineBreaks: true },+ { text: "> [!NOTE]\n> Searchable alert", query: "Searchable alert", count: 1 },+ {+ text: "<details><summary>Folded</summary><p>Hidden needle</p></details>",+ query: "Hidden needle",+ count: 1,+ },+ { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Hello World", count: 1, useTemplate: true },+ { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Document template", count: 1, useTemplate: true },+ { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "World Document", count: 0, useTemplate: true },+ { text: ARTIFACT_TEMPLATE_DIRECTIVE, query: "Use template", count: 0, useTemplate: true },+])(+ "highlights the indexed occurrences of $query in $text",+ async ({ text, query, count, lineBreaks, user, useTemplate }) => {+ const skills = [{ name: "test-t3-app", displayName: "T3 App Testing" }];+ const highlights = new Map<string, Set<Range>>();+ vi.stubGlobal(+ "Highlight",+ class extends Set<Range> {+ constructor(...ranges: Range[]) {+ super(ranges);+ }+ },+ );+ vi.stubGlobal("CSS", { highlights, escape: (value: string) => value });+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ function Probe() {+ useThreadFindHighlights({+ container,+ query,+ activeRowId: "row",+ activeOccurrence: 0,+ onActiveRange: () => {},+ });+ return (+ <div data-timeline-row-id="row">+ <div data-thread-find-text>+ <MarkdownFindContext value={true}>+ <ChatMarkdown+ text={text}+ cwd={undefined}+ skills={skills}+ lineBreaks={lineBreaks ?? false}+ parseRawHtml={!user}+ onUseArtifactTemplate={useTemplate ? () => undefined : undefined}+ />+ </MarkdownFindContext>+ </div>+ </div>+ );+ }+ try {+ await act(() => root.render(<Probe />));+ await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));+ const ranges = [...highlights.values()].flatMap((value) => [...value]);+ expect(ranges.map((range) => range.toString())).toEqual(+ Array.from({ length: count }, () => query),+ );+ const segments =+ searchableMessageSegments(+ { role: user ? "user" : "assistant", text, streaming: false },+ undefined,+ skills,+ ) ?? [];+ expect(+ segments.reduce((sum, segment) => sum + countThreadSearchOccurrences(segment, query), 0),+ ).toBe(count);+ } finally {+ await act(() => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+ }+ },+);diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex d926f5aaf41..42b4a0618b6 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -1,5 +1,24 @@+import { MarkdownFindContext, useFindRevealRef } from "./chat/markdownFindContext";+import {+ buildFileLinkParentSuffixByPath,+ fileLinkLabel,+ resolvePathLinkTarget,+} from "@t3tools/shared/fileLinks";+import {+ isWindowsDrivePathHref,+ normalizeMarkdownLinkDestination,+ extractInlineCodeSpans,+ extractMarkdownLinkHrefs,+ inlineCodeFilePathCandidate,+} from "@t3tools/shared/markdownLinks";+import { isAbsolutePath } from "@t3tools/shared/path";import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";import { AuthFilesystemReadScope, AuthOrchestrationOperateScope } from "@t3tools/contracts";+import {+ CHAT_MARKDOWN_REMARK_PLUGINS,+ CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,+ CHAT_MARKDOWN_REHYPE_PLUGINS,+} from "@t3tools/shared/markdownPipeline";import { useAtomValue } from "@effect/atom-react";import {COMPOSER_CONTEXT_CLIPBOARD_MIME,@@ -46,12 +65,11 @@ import {codexArtifactTemplatePresentationLabel,type CodexArtifactTemplate,type CodexArtifactTemplateKind,-} from "@t3tools/client-runtime/codex-artifact-templates";+} from "@t3tools/shared/codexArtifactTemplates";import {classifyMarkdownImageSource,markdownImageSourceFragment,} from "@t3tools/client-runtime/markdown-images";-import { inlineCodeFilePathCandidate } from "@t3tools/client-runtime/markdown-links";import { mediaFileReference, mediaUrlReference } from "@t3tools/client-runtime/media-reference";import { mediaKindFromPath, mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";import * as Cause from "effect/Cause";@@ -83,24 +101,16 @@ import ReactMarkdown from "react-markdown";import { toHtml } from "hast-util-to-html";import { createIncrementalMarkdownPlugin } from "../markdown-incremental";import { defaultUrlTransform } from "react-markdown";-import rehypeRaw from "rehype-raw";-import rehypeSanitize, { defaultSchema } from "rehype-sanitize";-import remarkBreaks from "remark-breaks";import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations";import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences";-import { parseThreadLinkHref, THREAD_LINK_PROTOCOL } from "@t3tools/shared/threadLinks";+import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";import { AssistantCitationChip } from "./chat/AssistantCitationChip";import { MarkdownThreadLink } from "./chat/MarkdownThreadLink";-import remarkGfm from "remark-gfm";-import type { Processor } from "unified";import { isWindowsAbsolutePath } from "@t3tools/shared/path";-import { remarkGithubAlerts } from "../markdown-github-alerts";import {artifactTemplateFromHastProperties,- CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,- remarkCodexDirectives,renderCodexFileCitationsAsMarkdown,-} from "@t3tools/client-runtime/codex-markdown-directives";+} from "@t3tools/shared/codexMarkdownDirectives";import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";import {resolveMarkdownMediaPreview,@@ -153,11 +163,7 @@ import {serializeTableElementToCsv,serializeTableElementToMarkdown,} from "../markdown-clipboard";-import { remarkNormalizeListItemIndentation } from "../markdown-list-indentation";import {- extractMarkdownLinkHrefs,- isWindowsDrivePathHref,- normalizeMarkdownLinkDestination,resolveInlineCodeFileLinkMeta,resolveMarkdownFileLinkMeta,rewriteMarkdownFileUriHref,@@ -165,7 +171,7 @@ import {shouldOpenMarkdownFileLinkInEditor,type MarkdownFileLinkMeta,} from "../markdown-links";-import { isMarkdownFileLinkLabel } from "@t3tools/client-runtime/markdown-links";+import { isMarkdownFileLinkLabel } from "@t3tools/shared/markdownLinks";import { readLocalApi } from "../localApi";import { useAssetUrlRefresh, useAssetUrlState } from "../assets/assetUrls";import { cn } from "../lib/utils";@@ -195,7 +201,6 @@ import {import { useOpenLink } from "../browser/useOpenLink";import { writeTextToClipboard } from "../hooks/useCopyToClipboard";import { isPreviewAvailableFor } from "../browser/previewRuntime";-import { isAbsolutePath, resolvePathLinkTarget } from "../terminal-links";import {isBrowserPreviewFile,openFileInPreview,@@ -322,15 +327,17 @@ function CodexArtifactTemplateCard(props: {<SparklesIcon aria-hidden className="size-2.5" /></span></span>- <span className="min-w-0">- <span className="block truncate text-sm font-medium text-foreground">+ {/* Block elements keep the name and label separate thread-find segments. */}+ <div className="min-w-0">+ <div className="truncate text-sm font-medium text-foreground">{props.template.displayName}- </span>- <span className="block text-xs text-muted-foreground">{presentationLabel}</span>- </span>+ </div>+ <div className="text-xs text-muted-foreground">{presentationLabel}</div>+ </div></div>{props.onUse ? (<Button+ data-thread-find-ignoretype="button"size="sm"variant="outline"@@ -396,190 +403,6 @@ function orderedListGutterStyle(return { "--list-gutter": `${markerWidth + 2}ch` };}-type MarkdownImageHastNode = {- type?: string;- value?: string;- tagName?: string;- properties?: Record<string, unknown>;- children?: MarkdownImageHastNode[];-};--function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {- return (node.children ?? []).filter(- (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),- );-}--/**- * An image that is the only content of its block (optionally wrapped in a- * link) is almost always a screenshot or figure, so it gets a reserved slot- * while it loads. Images mixed with text or other images — badge rows, icons- * in a sentence — stay inline at their natural size, since a placeholder taller- * than the image would move the page more than the image itself does.- */-/** Containers whose sole child image reads as a figure rather than part of a sentence. */-const STANDALONE_IMAGE_BLOCKS = new Set([- "p",- "div",- "li",- "td",- "th",- "figure",- "center",- "blockquote",-]);--function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {- const children = meaningfulHastChildren(node);- if (children.length !== 1) return undefined;- const only = children[0];- if (only?.type !== "element") return undefined;- if (only.tagName === "img") return only;- // A link, emphasis, or similar inline wrapper around the image still counts- // as long as nothing else shares the block.- return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"- ? soleImageDescendant(only)- : undefined;-}--function markStandaloneImages(node: MarkdownImageHastNode) {- // A raw `<img>` on its own line reaches the root without a paragraph.- if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {- const image = soleImageDescendant(node);- if (image) image.properties = { ...image.properties, dataStandalone: true };- }- node.children?.forEach((child) => {- if (child.type === "element") markStandaloneImages(child);- });-}--/** Keep unmatched inline `<A>` placeholders from opening an HTML link over later blocks. */-function rehypePreserveBareAnchorPlaceholders() {- return (tree: MarkdownImageHastNode) => {- const anchors: Array<MarkdownImageHastNode | null> = [];- let rawTextTag: string | undefined;- const visit = (node: MarkdownImageHastNode) => {- if (node.type === "raw" && typeof node.value === "string") {- // Raw blocks can contain several tags. Consume whole tags, quoted attributes,- // and comments so text resembling a closing anchor cannot pair a placeholder.- const tags = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;- let offset = 0;- while (rawTextTag !== "plaintext") {- // Raw text ends at its closing tag even inside comment-looking text.- const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;- matcher.lastIndex = offset;- const match = matcher.exec(node.value);- if (!match) break;- const [tag] = match;- offset = matcher.lastIndex;- if (rawTextTag) {- rawTextTag = undefined;- continue;- }- if (tag.startsWith("<!--")) continue;- const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();- const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();- if (- opening &&- /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)- ) {- rawTextTag = opening;- } else if (opening === "a") {- anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);- } else if (closing === "a") {- anchors.pop();- }- }- }- node.children?.forEach(visit);- };-- visit(tree);- for (const anchor of anchors) {- if (anchor) anchor.type = "text";- }- };-}--/** Carries authored image source metadata through the sanitizer to the image renderer. */-function rehypePreserveImageSourceMeta() {- return (tree: MarkdownImageHastNode) => {- const visit = (node: MarkdownImageHastNode) => {- const src = node.properties?.src;- const title = node.properties?.title;- if (node.type === "element" && node.tagName === "img") {- node.properties = {- ...node.properties,- ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),- ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),- };- }- node.children?.forEach(visit);- };-- visit(tree);- markStandaloneImages(tree);- };-}--const CHAT_MARKDOWN_SANITIZE_SCHEMA = {- ...defaultSchema,- attributes: {- ...defaultSchema.attributes,- "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),- code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],- blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],- div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],- a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],- img: [- ...(defaultSchema.attributes?.img ?? []),- "dataLocalSrc",- "dataMarkdownTitle",- "dataStandalone",- ],- },- protocols: {- ...defaultSchema.protocols,- href: [- ...(defaultSchema.protocols?.href ?? []),- "file",- "t3-citation",- "t3-context",- THREAD_LINK_PROTOCOL,- ],- src: [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"],- },-} satisfies Parameters<typeof rehypeSanitize>[0];--const CHAT_MARKDOWN_REMARK_PLUGINS = [- remarkGfm,- remarkKeepWindowsPathDestinations,- remarkGithubAlerts,- remarkNormalizeListItemIndentation,- remarkCodexDirectives,- remarkPreserveCodeMeta,- remarkNormalizeLinksAndTagInlineCode,-] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;--const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [- remarkGfm,- remarkKeepWindowsPathDestinations,- remarkGithubAlerts,- remarkNormalizeListItemIndentation,- remarkCodexDirectives,- remarkBreaks,- remarkPreserveCodeMeta,- remarkNormalizeLinksAndTagInlineCode,-] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;--const CHAT_MARKDOWN_REHYPE_PLUGINS = [- rehypePreserveBareAnchorPlaceholders,- rehypeRaw,- rehypePreserveImageSourceMeta,- [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],-] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;--/** GitHub's own five alert kinds, in its colors: the glyph names the urgency, the title says it. */const GITHUB_ALERT_PRESENTATIONS: Record<string,{ label: string; Icon: typeof InfoIcon; borderClassName: string; titleClassName: string }@@ -680,87 +503,6 @@ type MarkdownAstNode = {children?: MarkdownAstNode[];};-function remarkPreserveCodeMeta() {- return (tree: MarkdownAstNode) => {- const visit = (node: MarkdownAstNode) => {- if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {- node.data = {- ...node.data,- hProperties: {- ...node.data?.hProperties,- dataCodeMeta: node.meta.trim(),- },- };- }- node.children?.forEach(visit);- };-- visit(tree);- };-}--interface DestinationCompileContext {- readonly stack: ReadonlyArray<{ readonly type: string; url?: string }>;- resume(): string;- sliceSerialize(token: unknown): string;-}--function keepWindowsPathDestination(this: DestinationCompileContext, token: unknown) {- const decoded = this.resume();- const authored = this.sliceSerialize(token);- const node = this.stack.at(-1);- // Character references still need decoding, so those destinations keep the parsed URL.- if (node)- node.url = isWindowsAbsolutePath(authored) && !authored.includes("&") ? authored : decoded;-}--/**- * CommonMark reads the `\.` in `C:\me\.t3\shot.png` as an escape, even in a link- * destination. Every backslash in a Windows path is a separator, so link, image, and- * definition destinations that are Windows paths keep the text as written.- */-function remarkKeepWindowsPathDestinations(this: Processor) {- const data = this.data();- (data.fromMarkdownExtensions ??= []).push({- exit: {- resourceDestinationString: keepWindowsPathDestination,- definitionDestinationString: keepWindowsPathDestination,- },- });-}--/**- * Preserve Windows drive links as allowed `file:` URLs before sanitization.- * The same traversal tags inline code while it can still be distinguished- * from fenced code. Code inside links stays untagged to avoid nested anchors.- */-function remarkNormalizeLinksAndTagInlineCode() {- return (tree: MarkdownAstNode) => {- const visit = (node: MarkdownAstNode, insideLink: boolean) => {- if (- (node.type === "link" || node.type === "definition") &&- typeof node.url === "string" &&- WINDOWS_DRIVE_PATH_REGEX.test(node.url)- ) {- node.url = `file:///${node.url.replaceAll("\\", "/")}`;- }- if (node.type === "inlineCode" && !insideLink) {- node.data = {- ...node.data,- hProperties: {- ...node.data?.hProperties,- dataInlineCode: "",- },- };- }- const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";- node.children?.forEach((child) => visit(child, childInsideLink));- };-- visit(tree, false);- };-}-function nodeToPlainText(node: ReactNode): string {if (typeof node === "string" || typeof node === "number") {return String(node);@@ -947,6 +689,12 @@ function MarkdownDetails({open = false,}: Pick<React.ComponentProps<"details">, "children" | "open">) {const [isOpen, setIsOpen] = useState(open);+ const searching = use(MarkdownFindContext);+ const expanded = isOpen;+ const revealForFind = useCallback(() => setIsOpen(true), []);+ // Base UI only listens for `beforematch` on a panel mounted at its first+ // render; a closed panel mounts later, when find starts, so listen here.+ const findRevealRef = useFindRevealRef(revealForFind);const childNodes = Children.toArray(children);const summaryIndex = childNodes.findIndex((child) => isValidElement(child) && child.type === "summary",@@ -961,10 +709,10 @@ function MarkdownDetails({return (<div className="my-2 border-y border-border/60"><Collapsible- defaultOpen={open}+ open={expanded}onOpenChange={setIsOpen}data-markdown-details=""- data-markdown-details-open={isOpen ? "true" : "false"}+ data-markdown-details-open={expanded ? "true" : "false"}><CollapsibleTriggerclassName="flex w-full items-center gap-2 py-2 text-left text-sm font-medium text-foreground data-panel-open:[&_svg]:rotate-90"@@ -976,7 +724,7 @@ function MarkdownDetails({/><span>{summary}</span></CollapsibleTrigger>- <CollapsiblePanel>+ <CollapsiblePanel ref={findRevealRef} hiddenUntilFound={searching}><divclassName="pb-3 ps-6 text-foreground/[calc(80%+var(--appearance-contrast-boost)/5)]"data-markdown-details-content=""@@ -995,6 +743,10 @@ function MarkdownDetails({* language title, an optional actions slot, and the body as children. The* composer passes Tiptap's node view wrapper as the outer element.*/+const THREAD_FIND_IGNORE_PROPS = {+ "data-thread-find-ignore": "",+} as React.HTMLAttributes<HTMLDivElement>;+export function MarkdownCodeBlockFrame({as: Wrapper = "div",language,@@ -1203,6 +955,8 @@ function MarkdownCodeBlock({fenceTitle={fenceTitle}theme={theme}wrapped={wrapped}+ // Find does not count the header, so it must not highlight it either.+ headerProps={THREAD_FIND_IGNORE_PROPS}actions={<span className="flex items-center gap-0.5" role="toolbar" aria-label="Code block actions">{leadingActions}@@ -1272,6 +1026,9 @@ function MarkdownMermaidCodeBlock({children: ReactNode;}) {const [showCode, setShowCode] = useState(false);+ const searching = use(MarkdownFindContext);+ const revealSource = useCallback(() => setShowCode(true), []);+ const sourceRevealRef = useFindRevealRef(revealSource);const showDiagram = !showCode && !isStreaming && code.trim().length > 0;const toggleLabel = showCode ? "Show diagram" : "Show code";return (@@ -1315,6 +1072,12 @@ function MarkdownMermaidCodeBlock({><MermaidDiagram source={code} theme={theme} onExpand={onExpand} /></Suspense>+ {/* Find counts the source; a selected match here switches to it. */}+ {searching ? (+ <pre ref={sourceRevealRef} hidden>+ {code}+ </pre>+ ) : null}</RenderErrorBoundary>) : (children@@ -1454,79 +1217,6 @@ interface MarkdownFileLinkProps {const MARKDOWN_FILE_LINK_CLASS_NAME = "chat-markdown-file-link";-function pathParentSegments(path: string): string[] {- const normalized = path.replaceAll("\\", "/");- const segments = normalized.split("/").filter((segment) => segment.length > 0);- return segments.slice(0, -1);-}--function buildFileLinkParentSuffixByPath(filePaths: ReadonlyArray<string>): Map<string, string> {- const groups = new Map<string, Set<string>>();- for (const filePath of filePaths) {- const normalizedPath = filePath.replaceAll("\\", "/");- const pathSegments = normalizedPath.split("/").filter((segment) => segment.length > 0);- const basename = pathSegments[pathSegments.length - 1];- if (!basename) continue;- const group = groups.get(basename) ?? new Set<string>();- group.add(normalizedPath);- groups.set(basename, group);- }-- const suffixByPath = new Map<string, string>();- for (const group of groups.values()) {- const uniquePaths = [...group];- if (uniquePaths.length < 2) continue;-- const parentSegmentsByPath = new Map(- uniquePaths.map((filePath) => [filePath, pathParentSegments(filePath)]),- );- const minUniqueDepthByPath = new Map<string, number>();-- for (const filePath of uniquePaths) {- const segments = parentSegmentsByPath.get(filePath) ?? [];- let resolvedDepth = segments.length;- for (let depth = 1; depth <= segments.length; depth += 1) {- const candidate = segments.slice(-depth).join("/");- const collision = uniquePaths.some((otherPath) => {- if (otherPath === filePath) return false;- const otherSegments = parentSegmentsByPath.get(otherPath) ?? [];- return otherSegments.slice(-depth).join("/") === candidate;- });- if (!collision) {- resolvedDepth = depth;- break;- }- }- minUniqueDepthByPath.set(filePath, resolvedDepth);- }-- for (const filePath of uniquePaths) {- const segments = parentSegmentsByPath.get(filePath) ?? [];- if (segments.length === 0) continue;- const minUniqueDepth = minUniqueDepthByPath.get(filePath) ?? 1;- const suffixDepth = Math.min(segments.length, Math.max(minUniqueDepth, 2));- suffixByPath.set(filePath, segments.slice(-suffixDepth).join("/"));- }- }-- return suffixByPath;-}--const FENCED_CODE_SEGMENT_PATTERN = /(```[\s\S]*?(?:```|$))/;-const INLINE_CODE_SPAN_PATTERN = /`([^`\n]+)`/g;--function extractInlineCodeSpans(text: string): string[] {- const spans: string[] = [];- const segments = text.split(FENCED_CODE_SEGMENT_PATTERN);- for (let index = 0; index < segments.length; index += 2) {- for (const match of (segments[index] ?? "").matchAll(INLINE_CODE_SPAN_PATTERN)) {- const span = match[1]?.trim();- if (span) spans.push(span);- }- }- return spans;-}-function normalizeMarkdownLinkHrefKey(href: string): string {const normalizedHref = normalizeMarkdownLinkDestination(href);const rewrittenHref = rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref;@@ -1659,7 +1349,8 @@ function ChatMarkdownMediaUnavailableLabel(props: {}) {const label = props.kind === "video" ? "Video unavailable" : "Image unavailable";return (- <span className="inline-flex items-center gap-1.5">+ // Find indexes no image text, so this fallback must not highlight either.+ <span data-thread-find-ignore className="inline-flex items-center gap-1.5"><TriangleAlertIcon aria-hidden className="size-3.5 shrink-0" />{props.alt.length > 0 ? `${label} · ${props.alt}` : label}</span>@@ -2877,18 +2568,6 @@ function useChatMarkdownState({);const fileLinkChip = useCallback((fileLinkMeta: MarkdownFileLinkMeta, copyMarkdown: string, mediaSource?: string) => {- const parentSuffix = fileLinkParentSuffixByPath.get(- fileLinkMeta.filePath.replaceAll("\\", "/"),- );- const labelParts = [fileLinkMeta.basename];- if (typeof parentSuffix === "string" && parentSuffix.length > 0) {- labelParts.push(parentSuffix);- }- if (fileLinkMeta.line) {- labelParts.push(- `L${fileLinkMeta.line}${fileLinkMeta.column ? `:C${fileLinkMeta.column}` : ""}`,- );- }const mediaPath = mediaSource ?? fileLinkMeta.filePath;const canPreviewMedia =mediaMimeTypeFromExtension(@@ -2908,7 +2587,14 @@ function useChatMarkdownState({displayPath={fileLinkMeta.displayPath}panelPath={panelPath}line={fileLinkMeta.line}- label={labelParts.join(" · ")}+ label={fileLinkLabel(+ {+ path: fileLinkMeta.filePath,+ ...(fileLinkMeta.line !== undefined ? { line: fileLinkMeta.line } : {}),+ ...(fileLinkMeta.column !== undefined ? { column: fileLinkMeta.column } : {}),+ },+ fileLinkParentSuffixByPath,+ )}copyMarkdown={copyMarkdown}theme={resolvedTheme}threadRef={threadRef}@@ -3086,7 +2772,10 @@ const CHAT_MARKDOWN_COMPONENTS = {// text under a colored title — which is how the host renders it.return (<div role="note" className={cn("my-1 border-l-2 pl-3", alert.borderClassName)}>- <p className={cn("flex items-center gap-1.5 font-medium", alert.titleClassName)}>+ <p+ data-thread-find-ignore="true"+ className={cn("flex items-center gap-1.5 font-medium", alert.titleClassName)}+ ><alert.Icon aria-hidden className="size-3.5 shrink-0" />{alert.label}</p>diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.tsindex bf8d32f1daf..f870182b1b2 100644--- a/apps/web/src/components/ChatView.logic.test.ts+++ b/apps/web/src/components/ChatView.logic.test.ts@@ -24,7 +24,7 @@ import {type OrchestrationV2ProjectedTurnItem,type WorktreeSetupSnapshot,} from "@t3tools/contracts";-import type { CodexArtifactTemplate } from "@t3tools/client-runtime/codex-artifact-templates";+import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";import * as DateTime from "effect/DateTime";import * as Option from "effect/Option";import { afterEach, describe, expect, it, vi } from "vite-plus/test";diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex f36e54d334f..1e79964caa0 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -38,7 +38,7 @@ import {appendCodexArtifactTemplateUsePrompt,codexArtifactTemplateUsePrompt,type CodexArtifactTemplate,-} from "@t3tools/client-runtime/codex-artifact-templates";+} from "@t3tools/shared/codexArtifactTemplates";import { presentThreadShell } from "@t3tools/client-runtime/state/shell";import {type ChatMessage,diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 792fbacb619..5b70ffb1757 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -1,4 +1,5 @@-import { ChatCanvas } from "./chat/ChatCanvas";+import { ThreadFind, ThreadFindCanvas, type ThreadFindControls } from "./chat/ThreadFindProvider";+import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar";import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner";import {resolveBackgroundDraftWorkspaceOptions,@@ -608,7 +609,7 @@ import {const EMPTY_PROVIDERS: ServerProvider[] = [];const EMPTY_PROVIDER_MODELS: ServerProvider["models"] = [];const EMPTY_USAGE_LIMIT_SOURCES: UsageLimitSourceSnapshots = [];-import type { CodexArtifactTemplate } from "@t3tools/client-runtime/codex-artifact-templates";+import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";const TIMELINE_SCROLL_CANCEL_SENTINEL = Object.freeze({});const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray<CodexFeedbackSubmission> = [];@@ -1735,10 +1736,13 @@ export default function ChatView(props: ChatViewProps) {hasMoreHistory: serverThreadHistory.hasMoreHistory,loading: serverThreadHistory.loading,error: serverThreadHistory.error,- onLoadEarlier: () => {+ onLoadEarlier: (throughEntryId) => {void loadEarlierThreadHistory({environmentId: routeThreadDetailRef.environmentId,- input: { threadId: routeThreadDetailRef.threadId },+ input: {+ threadId: routeThreadDetailRef.threadId,+ ...(throughEntryId === undefined ? {} : { throughEntryId }),+ },});},};@@ -7931,6 +7935,18 @@ export default function ChatView(props: ChatViewProps) {}),[composerRef, previewPanelOpen, terminalUiState.terminalOpen, routeKind, phase],);+ const timelineSkills = activeProviderStatus+ ? resolveProviderSkillsForCwd(activeProviderStatus, gitCwd)+ : EMPTY_PROVIDER_SKILLS;+ const threadFindControlsRef = useRef<ThreadFindControls | null>(null);+ const [isThreadFindActive, setIsThreadFindActive] = useState(false);+ const openThreadFind = useCallback(() => threadFindControlsRef.current?.open(), []);+ const closeThreadFind = useCallback(() => threadFindControlsRef.current?.close(), []);+ // The details popover hangs off the header over the find bar; opening find dismisses it.+ useEffect(() => {+ if (!isThreadFindActive || threadPanelPresentation !== "popover" || !activeThreadRef) return;+ useRightPanelStore.getState().setThreadPanelOpen(activeThreadRef, "popover", false);+ }, [activeThreadRef, isThreadFindActive, threadPanelPresentation]);useEffect(() => {const handler = (event: globalThis.KeyboardEvent) => {@@ -7938,6 +7954,8 @@ export default function ChatView(props: ChatViewProps) {event.stopPropagation();return;}+ // Let contextual controls claim Escape before the bubbling find handler.+ if (isThreadFindActive && event.key === "Escape") return;if (isTerminalCloseConfirmPending() && preventTerminalCloseShortcut(event, keybindings)) {event.stopPropagation();return;@@ -8029,6 +8047,14 @@ export default function ChatView(props: ChatViewProps) {return;}+ // Drafts and servers without thread search leave Mod+F to the browser.+ if (command === "chat.find" && isServerThread && serverConfig?.threadFind === true) {+ event.preventDefault();+ event.stopPropagation();+ openThreadFind();+ return;+ }+if (command === "rightPanel.toggle") {event.preventDefault();event.stopPropagation();@@ -8211,8 +8237,28 @@ export default function ChatView(props: ChatViewProps) {event.stopPropagation();void runProjectScript(script);};+ const dismissFind = (event: KeyboardEvent) => {+ if (+ event.key !== "Escape" ||+ !isThreadFindActive ||+ event.defaultPrevented ||+ event.isComposing ||+ event.keyCode === 229 ||+ isCommandPaletteOpen()+ )+ return;+ const context = getShortcutContext(event.target);+ if (context.terminalFocus || context.previewFocus || context.modelPickerOpen) return;+ event.preventDefault();+ closeThreadFind();+ focusComposer();+ };window.addEventListener("keydown", handler, true);- return () => window.removeEventListener("keydown", handler, true);+ window.addEventListener("keydown", dismissFind);+ return () => {+ window.removeEventListener("keydown", handler, true);+ window.removeEventListener("keydown", dismissFind);+ };}, [activeProject,activeRightPanelSurface,@@ -8239,6 +8285,7 @@ export default function ChatView(props: ChatViewProps) {scriptKeybindings,handleUnsettleActiveThread,isServerThread,+ serverConfig?.threadFind,onInterrupt,onToggleDiff,pinThread,@@ -8248,6 +8295,9 @@ export default function ChatView(props: ChatViewProps) {confirmAndUnpinThread,copyActiveThreadReference,getShortcutContext,+ openThreadFind,+ closeThreadFind,+ isThreadFindActive,toggleRightPanel,toggleThreadPanel,toggleTerminalVisibility,@@ -11237,7 +11287,18 @@ export default function ChatView(props: ChatViewProps) {{/* Main content area with optional plan sidebar */}<div className="relative flex min-h-0 min-w-0 flex-1">{/* Chat column */}- <ChatCanvas+ <ThreadFindCanvas+ findOptions={{+ skills: timelineSkills,+ progressive: serverConfig?.threadFindProgressive === true,+ thread: activeThreadRef,+ enabled:+ isServerThread && serverConfig?.threadFind === true && !paintOnlyDisplayedTimeline,+ content: serverProjection ?? undefined,+ }}+ controlsRef={threadFindControlsRef}+ onOpenChange={setIsThreadFindActive}+ detailsCardTopInset={isThreadFindActive ? THREAD_FIND_BAR_RESERVED_HEIGHT : 0}composerOverlayElement={isDraftHeroState ? null : composerOverlayElement}data-chat-workspace-drop-target="true"onDragEnter={workspaceFileDropHandlers.onDragEnter}@@ -11245,6 +11306,7 @@ export default function ChatView(props: ChatViewProps) {onDragLeave={workspaceFileDropHandlers.onDragLeave}onDrop={workspaceFileDropHandlers.onDrop}>+ <ThreadFind onClose={focusComposer} />{isWorkspaceFileDragActive ? (<divclassName="pointer-events-none absolute inset-2 z-40 flex items-center justify-center rounded-2xl border-2 border-dashed border-primary/60 bg-primary/[0.035]"@@ -11367,11 +11429,7 @@ export default function ChatView(props: ChatViewProps) {? (heldPaintContext?.workspaceRoot ?? undefined): activeWorkspaceRoot}- skills={- activeProviderStatus- ? resolveProviderSkillsForCwd(activeProviderStatus, gitCwd)- : EMPTY_PROVIDER_SKILLS- }+ skills={timelineSkills}anchorMessageId={paintOnlyDisplayedTimeline ? null : timelineAnchorMessageId}onAnchorReady={onTimelineAnchorReady}onAnchorSizeChanged={onTimelineAnchorSizeChanged}@@ -11390,7 +11448,7 @@ export default function ChatView(props: ChatViewProps) {/>{/* scroll to end pill — shown when user has scrolled away from the live edge */}- {showScrollToBottom && (+ {showScrollToBottom && !isThreadFindActive && (<divclassName="chat-scroll-to-bottom pointer-events-none absolute z-30 flex justify-center py-1.5"style={{ bottom: scrollToEndClearance + 4 }}@@ -11809,7 +11867,7 @@ export default function ChatView(props: ChatViewProps) {onPrepared={handlePreparedPullRequestThread}/>) : null}- </ChatCanvas>+ </ThreadFindCanvas>{/* end chat column */}</div>{/* end horizontal flex container */}diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsxindex 023eafa9397..80aedc344fb 100644--- a/apps/web/src/components/CommandPalette.tsx+++ b/apps/web/src/components/CommandPalette.tsx@@ -68,6 +68,7 @@ import {SunIcon,TextSearchIcon,} from "lucide-react";+import { requestThreadFindOpen } from "./chat/threadFindActionBus";import {useCallback,useDeferredValue,@@ -1139,6 +1140,9 @@ function OpenCommandPaletteDialog(props: {);const activeThreadId = activeThread?.id;+ const supportsThreadFind =+ environments.find((environment) => environment.environmentId === activeThread?.environmentId)+ ?.serverConfig?.threadFind === true;const currentProjectEnvironmentId =activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null;const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null;@@ -1929,6 +1933,20 @@ function OpenCommandPaletteDialog(props: {});}+ if (activeThreadId && supportsThreadFind) {+ actionItems.push({+ kind: "action",+ value: "find-current-thread",+ title: "Find in current thread",+ searchTerms: ["find", "search", "messages", "plans"],+ icon: <TextSearchIcon className={ITEM_ICON_CLASS} />,+ shortcutCommand: "chat.find",+ run: async () => {+ requestThreadFindOpen();+ },+ });+ }+if (activeThreadReferenceCopyTarget !== null) {actionItems.push({kind: "action",@@ -3093,6 +3111,15 @@ function OpenCommandPaletteDialog(props: {void copyActiveThreadReference();return;}+ // ChatView ignores shortcuts while the palette is open, so handle find here+ // instead of letting the browser's own Find open.+ if (command === "chat.find" && activeThreadId && !event.nativeEvent.isComposing) {+ event.preventDefault();+ event.stopPropagation();+ setOpen(false);+ requestThreadFindOpen();+ return;+ }if (addProjectCloneFlow?.step === "repository" && event.key === "Enter") {event.preventDefault();diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsxindex ae2c6e460f2..babdfc4a1f4 100644--- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx+++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx@@ -1,3 +1,4 @@+import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";import { Extension, InputRule, Node, wrappingInputRule, type JSONContent } from "@tiptap/core";import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react";import StarterKit from "@tiptap/starter-kit";@@ -102,7 +103,6 @@ import {ComposerContextRecordsContext,} from "./composerContextPresentation";import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";-import { formatProviderSkillDisplayName } from "@t3tools/client-runtime/providerSkills";import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";import { ComposerCodeBlockNodeView } from "./chat/ComposerCodeBlockNodeView";import { composerCodeBlockHighlight } from "./composerCodeBlockHighlight";diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsxindex 23cb11ea9c5..6e3aff08484 100644--- a/apps/web/src/components/GitActionsControl.tsx+++ b/apps/web/src/components/GitActionsControl.tsx@@ -121,7 +121,7 @@ import { threadEnvironment } from "~/state/threads";import { useAtomCommand } from "~/state/use-atom-command";import { vcsActionManager, vcsEnvironment } from "~/state/vcs";import { randomUUID } from "~/lib/utils";-import { resolvePathLinkTarget } from "~/terminal-links";+import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";import {THREAD_DETAILS_PANEL_CHEVRON_CLASS,diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsxindex bd40a441795..5e0f1e4a489 100644--- a/apps/web/src/components/ThreadTerminalDrawer.tsx+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx@@ -60,7 +60,8 @@ import {} from "~/terminal/ghostty/surface";import { type GhosttyColor, type GhosttyTheme } from "~/terminal/ghostty/core";import { useOpenInPreferredEditor } from "../editorPreferences";-import { isTerminalUrl, resolvePathLinkTarget } from "../terminal-links";+import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";+import { isTerminalUrl } from "../terminal-links";import {isDiffToggleShortcut,isTerminalClearShortcut,diff --git a/apps/web/src/components/chat/ChatCanvas.tsx b/apps/web/src/components/chat/ChatCanvas.tsxindex 504db173048..3606f6db970 100644--- a/apps/web/src/components/chat/ChatCanvas.tsx+++ b/apps/web/src/components/chat/ChatCanvas.tsx@@ -17,10 +17,12 @@ import type { PreviewMiniPlayerObstacles } from "../preview/previewMiniPlayerLay*/export function ChatCanvas({composerOverlayElement,+ detailsCardTopInset = 0,children,...props}: Omit<ComponentProps<"div">, "className" | "style" | "ref"> & {composerOverlayElement: HTMLElement | null;+ detailsCardTopInset?: number;}) {const elementRef = useRef<HTMLDivElement | null>(null);const widthProbeRef = useRef<HTMLDivElement | null>(null);@@ -106,8 +108,17 @@ export function ChatCanvas({clearPreview,registerTimeline,reportDetailsCard,+ detailsCardTopInset,};- }, [measurements, preview, detailsCard, reportPreview, clearPreview, reportDetailsCard]);+ }, [+ measurements,+ preview,+ detailsCard,+ reportPreview,+ clearPreview,+ reportDetailsCard,+ detailsCardTopInset,+ ]);const { layout } = context;return (<ChatCanvasContext value={context}>diff --git a/apps/web/src/components/chat/ChatCanvasContext.ts b/apps/web/src/components/chat/ChatCanvasContext.tsindex 44b91f82632..f5fc19d6a7f 100644--- a/apps/web/src/components/chat/ChatCanvasContext.ts+++ b/apps/web/src/components/chat/ChatCanvasContext.ts@@ -11,6 +11,8 @@ export const ChatCanvasContext = createContext<{clearPreview: (key: string) => void;registerTimeline: (element: HTMLElement | null) => void;reportDetailsCard: (card: PreviewMiniPlayerObstacles["detailsCard"]) => void;+ /** Height reserved above the details card, such as the open find bar. */+ detailsCardTopInset: number;} | null>(null);export const useChatCanvas = () => useContext(ChatCanvasContext);diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex 0f84927b591..858f9a77850 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -1,3 +1,4 @@+import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText";import { runtimeModeConfig, runtimeModeOptions as runtimeModes } from "./runtimeModeConfig";import { isLocalEnvironmentDisabled } from "../../localEnvironment";@@ -1088,7 +1089,7 @@ import {ShieldIcon,XIcon,} from "lucide-react";-import { proposedPlanTitle } from "../../proposedPlan";+import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText";import { hasProviderSetup } from "./ProviderStatusBanner";import {applyProviderInstanceSettings,@@ -1124,7 +1125,6 @@ import {} from "@t3tools/client-runtime/state/composer-dispatch";import type { ContextWindowSnapshot } from "../../lib/contextWindow";import {- formatProviderSkillDisplayName,getProviderSlashCommandsForSlashMenu,getProviderSkillsForSlashMenu,hasCompleteProviderWorkspaceSnapshot,diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsxindex 4c13641dd1b..edd28efe1d7 100644--- a/apps/web/src/components/chat/ComposerCommandMenu.tsx+++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx@@ -1,5 +1,5 @@+import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";import {- formatProviderSkillDisplayName,resolveProviderSkillSourceKind,type ProviderSkillSourceKind,} from "@t3tools/client-runtime/providerSkills";diff --git a/apps/web/src/components/chat/MermaidDiagram.tsx b/apps/web/src/components/chat/MermaidDiagram.tsxindex 30c98791884..dd03bdc4ea1 100644--- a/apps/web/src/components/chat/MermaidDiagram.tsx+++ b/apps/web/src/components/chat/MermaidDiagram.tsx@@ -192,7 +192,11 @@ export function MermaidDiagram({</Button>) : null}</div>- <pre className="mt-2 mb-0 overflow-auto font-mono text-xs whitespace-pre-wrap">+ {/* Find matches the source through the hidden copy beside the diagram. */}+ <pre+ data-thread-find-ignore+ className="mt-2 mb-0 overflow-auto font-mono text-xs whitespace-pre-wrap"+ >{source}</pre></div>diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.tsindex 93fc89598be..8ba1552452a 100644--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts@@ -1,3 +1,4 @@+import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";import { ThreadId, type WorktreeSetupSnapshot } from "@t3tools/contracts";import {CheckpointRef,@@ -27,6 +28,7 @@ import {computeStableMessagesTimelineRows,computeMessageDurationStart,deriveMessagesTimelineRows,+ timelineEntryTurnFoldRunId,deriveMessagesTimelineRowsWithState,shouldCollapseUserMessage,liveWorkEntryLabel,@@ -34,7 +36,6 @@ import {resolveAssistantMessageCopyState,resolveWorkGroupScrollIndex,shouldFollowWorkGroupAppend,- shouldPreserveAssistantLineBreaks,threadReadLabelPrefix,threadReadTargetId,threadReadTargetTitle,@@ -2404,6 +2405,33 @@ describe("deriveMessagesTimelineRows", () => {const withoutPrompt = rows([]);expect(withoutPrompt).toContain("turn-fold");expect(withoutPrompt).not.toContain("assistant:imported-update");++ // Find must open the fold holding a folded imported message by its synthetic key.+ const timelineEntries = [+ message("imported-prompt", "user", 0),+ message("imported-update", "assistant", 4),+ message("imported-answer", "assistant", 8),+ ];+ const foldInput = { timelineEntries, latestRun: null, isWorking: false };+ const foldRunId = timelineEntryTurnFoldRunId(foldInput, "imported-update");+ expect(foldRunId).not.toBeNull();+ // The rendered turn-fold row carries the same key, so find can map it back.+ const foldRow = deriveMessagesTimelineRows({+ ...foldInput,+ turnDiffSummaries: [],+ supportsConversationRollback: false,+ }).find((row) => row.kind === "turn-fold");+ expect(foldRow?.kind === "turn-fold" ? foldRow.runId : null).toBe(foldRunId);+ expect(timelineEntryTurnFoldRunId(foldInput, "imported-answer")).toBeNull();+ const expanded = deriveMessagesTimelineRows({+ ...foldInput,+ expandedRunIds: new Set([foldRunId!]),+ turnDiffSummaries: [],+ supportsConversationRollback: false,+ });+ expect(+ expanded.some((row) => row.kind === "message" && row.message.id === "imported-update"),+ ).toBe(true);});it("shows a provider-native subagent's runless tools as live work while it works", () => {diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.tsindex 4a81905eaa2..b4f879e9a99 100644--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts@@ -7,7 +7,7 @@ import {collectAssistantCitations,} from "@t3tools/shared/assistantCitations";import { shallow } from "zustand/vanilla/shallow";-import { renderCodexDirectivesForCopy } from "@t3tools/client-runtime/codex-markdown-directives";+import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives";import {commandDisplayText,commandProgramName,@@ -351,10 +351,6 @@ export function resolveTimelineIsAtEnd(state: TimelineEndState | undefined): booreturn contentLength - scroll - scrollLength <= TIMELINE_FOLLOW_REARM_THRESHOLD_PX;}-export function shouldPreserveAssistantLineBreaks(text: string): boolean {- return /^★ Insight(?:\s|─)/mu.test(text);-}-export function resolveTimelineMinimapHeightStyle(itemCount: number): string {const naturalHeight = Math.max(1, (itemCount - 1) * TIMELINE_MINIMAP_ITEM_SPACING);return `min(${naturalHeight}px, ${TIMELINE_MINIMAP_MAX_HEIGHT_CSS})`;@@ -1298,6 +1294,35 @@ function settleSupersededReasoning(entries: ReadonlyArray<TimelineEntry>) {});}+function timelineRowEntries(entries: ReadonlyArray<TimelineEntry>) {+ return withoutSubagentDelegationRows(settleSupersededReasoning(entries));+}++/** The turn folds the timeline would draw, before applying expansion state. */+function deriveTimelineTurnFolds(+ input: Pick<+ MessagesTimelineRowsInput,+ "timelineEntries" | "latestRun" | "isWorking" | "runlessWorkActive" | "runningRunId"+ >,+) {+ const timelineEntries = timelineRowEntries(input.timelineEntries);+ const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null, input.runningRunId ?? null);+ const failedRunIds = failedTimelineRunIds(timelineEntries, input.latestRun ?? null);+ const activeVisualResponseRunIds = deriveActiveVisualResponseRunIds({+ timelineEntries,+ unsettledRunId,+ isWorking: input.isWorking,+ });+ return deriveTurnFolds({+ timelineEntries,+ terminalAssistantMessageIds: deriveTerminalAssistantMessageIds(timelineEntries),+ latestRun: input.latestRun ?? null,+ unfoldedRunIds: new Set([...activeVisualResponseRunIds, ...failedRunIds]),+ runlessWorkActive: input.isWorking && input.runlessWorkActive === true,+ liveSubagentEntryIds: liveSubagentCardEntryIds(timelineEntries),+ });+}+export function deriveMessagesTimelineRows(input: {timelineEntries: ReadonlyArray<TimelineEntry>;latestRun?: TimelineLatestRun | null;@@ -1319,9 +1344,7 @@ export function deriveMessagesTimelineRows(input: {/** Live bootstrap progress. Renders a stage card under the first user message. */worktreeSetup?: WorktreeSetupSnapshot | null;}): MessagesTimelineRow[] {- const timelineEntries = withoutSubagentDelegationRows(- settleSupersededReasoning(input.timelineEntries),- );+ const timelineEntries = timelineRowEntries(input.timelineEntries);const turnDiffSummaryByAssistantMessageId = new Map<MessageId, TurnDiffSummary>();for (const summary of input.turnDiffSummaries) {if (summary.assistantMessageId) {@@ -1989,6 +2012,35 @@ export interface MessagesTimelineRowsProjection {readonly rows: MessagesTimelineRow[];}+/**+ * The turn fold that holds an entry, keyed as `expandedRunIds` expects. Runless+ * (imported V1) turns fold under a synthetic key, so the entry's own run id is+ * not enough to open them.+ */+export function timelineEntryTurnFoldRunId(+ input: Pick<+ MessagesTimelineRowsInput,+ "timelineEntries" | "latestRun" | "isWorking" | "runlessWorkActive" | "runningRunId"+ >,+ entryId: string,+): RunId | null {+ return timelineTurnFoldRunIdsByEntryId(input).get(entryId) ?? null;+}++/** Every folded entry's fold key, computed once for callers that check many entries. */+export function timelineTurnFoldRunIdsByEntryId(+ input: Pick<+ MessagesTimelineRowsInput,+ "timelineEntries" | "latestRun" | "isWorking" | "runlessWorkActive" | "runningRunId"+ >,+): ReadonlyMap<string, RunId> {+ const byEntryId = new Map<string, RunId>();+ for (const fold of deriveTimelineTurnFolds(input).values()) {+ for (const entryId of fold.hiddenEntryIds) byEntryId.set(entryId, fold.runId);+ }+ return byEntryId;+}+function sameCheckpointSummaries(previous: MessagesTimelineRowsInput["turnDiffSummaries"],next: MessagesTimelineRowsInput["turnDiffSummaries"],diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex ab6b1e87b09..8d2b445a22c 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -1,3 +1,6 @@+import { ThreadFindTimelineContext } from "./ThreadFindProvider";+import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";+import { MarkdownFindContext, useFindRevealRef } from "./markdownFindContext";import { ComputerUseAppIcon } from "~/components/Icons";import { useChatCanvas } from "./ChatCanvasContext";import { WorkLogBlock, WorkLogButton, WorkLogDetails, WorkLogList, WorkLogRow } from "./WorkLog";@@ -70,6 +73,7 @@ import {memo,use,useCallback,+ useContext,useEffect,useLayoutEffect,useMemo,@@ -95,7 +99,7 @@ import {workEntrySignalsSevereFailure,workLogEntryIsToolLike,} from "../../session-logic";-import type { CodexArtifactTemplate } from "@t3tools/client-runtime/codex-artifact-templates";+import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";import {type ChatMessage,type ChatFileAttachment,@@ -209,7 +213,7 @@ import {resolveWorkGroupScrollIndex,shouldCollapseUserMessage,shouldFollowWorkGroupAppend,- shouldPreserveAssistantLineBreaks,+ timelineTurnFoldRunIdsByEntryId,threadReadLabelPrefix,threadReadTargetId,threadReadTargetTitle,@@ -224,6 +228,10 @@ import {type TimelineLatestRun,type WorkGroupScrollAnchor,} from "./MessagesTimeline.logic";+import { type ThreadFindMatch } from "./threadFind";+import { useThreadFindNavigation } from "./useThreadFindNavigation";+import { readThreadFindPosition } from "./threadFindPosition";+import type { ThreadFindPositionReader } from "./threadFind";import { TerminalContextInlineChip } from "./TerminalContextInlineChip";import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";import { Spinner } from "../ui/spinner";@@ -327,6 +335,7 @@ interface TimelineRowSharedState {*/onAppFullscreenChange: (rowId: string, fullscreen: boolean) => void;onRunShellCommand: ((command: string) => void) | undefined;+ findActive: boolean;onImageExpand: (preview: ExpandedImagePreview) => void;displayThreadKey?: string;onOpenTurnDiff: (runId: RunId, filePath?: string) => void;@@ -402,6 +411,7 @@ function TimelineListFooter({</div>);}+const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];const TIMELINE_MAINTAIN_SCROLL_AT_END = {animated: false,@@ -433,7 +443,7 @@ export interface MessagesTimelineHistoryControls {readonly hasMoreHistory: boolean;readonly loading: boolean;readonly error: string | null;- readonly onLoadEarlier: () => void;+ readonly onLoadEarlier: (throughEntryId?: string) => void;}interface MessagesTimelineProps {@@ -519,19 +529,41 @@ interface MessagesTimelineProps {onContentOverflowChange?: (overflows: boolean) => void;onToolOutputCollapsedAtEnd?: () => void;onManualNavigation: () => void;- cancelPositionRestoreRef?: React.RefObject<(() => void) | null>;+ findOpen?: boolean;+ cancelPositionRestoreRef?: React.RefObject<(() => void) | null> | undefined;hideEmptyPlaceholder?: boolean;topFadeEnabled?: boolean;- historyControls?: MessagesTimelineHistoryControls;+ historyControls?: MessagesTimelineHistoryControls | undefined;/** Non-null when older turns exist beyond the loaded window. */loadEarlier?: CitationHistoryPage | null;+ findPositionReaderRef?: React.RefObject<ThreadFindPositionReader | null>;+ findExpanded?: boolean;+ findQuery?: string;+ activeFindMatch?: ThreadFindMatch | null;+ findNavigationId?: number;}// ---------------------------------------------------------------------------// MessagesTimeline — list owner// ----------------------------------------------------------------------------export const MessagesTimeline = memo(function MessagesTimeline({+export function MessagesTimeline(props: MessagesTimelineProps) {+ const find = useContext(ThreadFindTimelineContext);+ const findOpen = find?.findOpen ?? props.findOpen;+ const { onManualNavigation } = props;+ useEffect(() => {+ if (findOpen) onManualNavigation();+ }, [findOpen, onManualNavigation]);+ return (+ <ConversationTimeline+ {...props}+ {...find}+ liveFollowEnabled={!findOpen && props.liveFollowEnabled}+ />+ );+}++const ConversationTimeline = memo(function ConversationTimeline({citationRequest = null,citationHistoryLoading = false,onCiteAssistantText,@@ -551,6 +583,11 @@ export const MessagesTimeline = memo(function MessagesTimeline({awaitingUser = false,listRef,timelineEntries,+ findExpanded = false,+ findQuery = "",+ activeFindMatch = null,+ findNavigationId = 0,+ findPositionReaderRef,latestRun,runningRunId = null,turnDiffSummaries,@@ -651,6 +688,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({const disclosureAnchorKeyRef = useRef<string | null>(null);const disclosureSettleFrameRef = useRef<number | null>(null);const disclosureSettleSecondFrameRef = useRef<number | null>(null);+ const normalizedFindQuery = findQuery.trim();+ const findActive = findExpanded;+useEffect(() => {return () => {if (disclosureSettleFrameRef.current !== null) {@@ -784,6 +824,54 @@ export const MessagesTimeline = memo(function MessagesTimeline({});}, [latestRun]);+ // Find the fold that hides the match: imported turns have no run id but still+ // fold under a synthetic key, so the match's own run id cannot open them.+ const findFoldRunIds = useMemo(+ () =>+ findActive+ ? timelineTurnFoldRunIdsByEntryId({+ timelineEntries,+ latestRun,+ runningRunId,+ isWorking,+ runlessWorkActive,+ })+ : null,+ [findActive, timelineEntries, latestRun, runningRunId, isWorking, runlessWorkActive],+ );+ const activeFindRunId = activeFindMatch+ ? findFoldRunIds?.get(activeFindMatch.entryId)+ : undefined;+ useEffect(() => {+ if (!activeFindRunId) return;+ setExpandedRunIds((previous) =>+ previous.has(activeFindRunId) ? previous : new Set(previous).add(activeFindRunId),+ );+ }, [activeFindRunId]);+ const visibleExpandedRunIds = useMemo(() => {+ if (!activeFindRunId || paintedExpandedRunIds.has(activeFindRunId)) {+ return paintedExpandedRunIds;+ }+ return new Set(paintedExpandedRunIds).add(activeFindRunId);+ }, [activeFindRunId, paintedExpandedRunIds]);++ const activeFindAttemptId = activeFindMatch+ ? timelineEntries.find((entry) => entry.id === activeFindMatch.entryId)?.attempt?.id+ : undefined;+ useEffect(() => {+ if (!activeFindAttemptId) return;+ setExpandedAttemptIds((previous) =>+ previous.has(activeFindAttemptId) ? previous : new Set(previous).add(activeFindAttemptId),+ );+ }, [activeFindAttemptId]);+ const visibleExpandedAttemptIds = useMemo(+ () =>+ activeFindAttemptId && !paintedExpandedAttemptIds.has(activeFindAttemptId)+ ? new Set(paintedExpandedAttemptIds).add(activeFindAttemptId)+ : paintedExpandedAttemptIds,+ [activeFindAttemptId, paintedExpandedAttemptIds],+ );+const rowsProjectionRef = useRef<{readonly threadKey: string;readonly workspaceRoot: string | undefined;@@ -796,8 +884,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({timelineEntries,latestRun,runningRunId,- expandedRunIds,- expandedAttemptIds,+ expandedRunIds: visibleExpandedRunIds,+ expandedAttemptIds: visibleExpandedAttemptIds,expandedWorkGroupIds,isWorking,runlessWorkActive,@@ -819,8 +907,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({timelineEntries,latestRun,runningRunId,- expandedRunIds,- expandedAttemptIds,+ visibleExpandedRunIds,+ visibleExpandedAttemptIds,expandedWorkGroupIds,isWorking,runlessWorkActive,@@ -979,6 +1067,11 @@ export const MessagesTimeline = memo(function MessagesTimeline({onExpandTurn: expandCitedRun,onManualNavigation,});+ const [findListReady, setFindListReady] = useState(false);+ const handleListLoad = useCallback(() => {+ onCitationListLoad();+ setFindListReady(true);+ }, [onCitationListLoad]);const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);const [fullscreenAppRowId, setFullscreenAppRowId] = useState<string | null>(null);// Only the row that holds the pin can release it.@@ -1220,6 +1313,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({activeThreadEnvironmentId,onRevertToTurnCount,onRunShellCommand,+ findActive,onImageExpand,onFileOpen,onUseArtifactTemplate,@@ -1257,6 +1351,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({activeThreadEnvironmentId,onRevertToTurnCount,onRunShellCommand,+ findActive,onImageExpand,onFileOpen,onUseArtifactTemplate,@@ -1351,6 +1446,86 @@ export const MessagesTimeline = memo(function MessagesTimeline({[listRef, registerTimeline],);+ useLayoutEffect(() => {+ if (!findPositionReaderRef || !timelineViewportElement) return;+ const read: ThreadFindPositionReader = (query) => {+ // Imported turns fold under a synthetic key, so match folds by key, not run id.+ const foldRunIds =+ findFoldRunIds ??+ timelineTurnFoldRunIdsByEntryId({+ timelineEntries,+ latestRun,+ runningRunId,+ isWorking,+ runlessWorkActive,+ });+ const entryById = new Map(timelineEntries.map((entry) => [entry.id, entry]));+ return readThreadFindPosition(+ timelineViewportElement,+ query,+ (rowId) => {+ const rowIndex = rows.findIndex((row) => row.id === rowId);+ for (const row of rows.slice(Math.max(0, rowIndex))) {+ // Ordinary rows map to one entry by id; only folds need a scan.+ if (row.kind !== "turn-fold" && row.kind !== "attempt-fold") {+ const entry = entryById.get(row.kind === "assistant-meta" ? row.message.id : row.id);+ if (entry && (entry.kind === "message" || entry.kind === "proposed-plan"))+ return entry.id;+ continue;+ }+ const entry = timelineEntries.find((entry) => {+ const runId =+ row.kind === "turn-fold"+ ? foldRunIds.get(entry.id)+ : entry.kind === "message"+ ? entry.message.runId+ : entry.kind === "proposed-plan"+ ? entry.proposedPlan.runId+ : null;+ return (+ runId === row.runId &&+ (entry.kind !== "message" || entry.message.role === "assistant") &&+ (row.kind !== "attempt-fold" || entry.attempt?.id === row.attemptId)+ );+ });+ if (entry && (entry.kind === "message" || entry.kind === "proposed-plan"))+ return entry.id;+ }+ return undefined;+ },+ contentInsetEndAdjustment,+ );+ };+ findPositionReaderRef.current = read;+ return () => {+ if (findPositionReaderRef.current === read) findPositionReaderRef.current = null;+ };+ }, [+ contentInsetEndAdjustment,+ findFoldRunIds,+ findPositionReaderRef,+ isWorking,+ latestRun,+ rows,+ runlessWorkActive,+ runningRunId,+ timelineEntries,+ timelineViewportElement,+ ]);++ useThreadFindNavigation({+ listReady: findListReady,+ historyControls,+ entries: timelineEntries,+ container: timelineViewportElement,+ query: normalizedFindQuery,+ match: activeFindMatch,+ navigationId: findNavigationId,+ rowIndex: activeFindMatch ? rows.findIndex((row) => row.id === activeFindMatch.entryId) : -1,+ listRef,+ contentInsetEndAdjustment,+ });+// Stable renderItem — no closure deps. Row components read shared state// from TimelineRowCtx, which propagates through LegendList's memo.const renderItem = useCallback(@@ -1387,81 +1562,86 @@ export const MessagesTimeline = memo(function MessagesTimeline({}return (- <TimelineRowCtx value={sharedState}>- <TimelineRowActivityCtx value={activityState}>- <TooltipScrollDismissArea- ref={setTimelineViewportElement}- className="relative h-full min-h-0"- data-assistant-citation-viewport="true"- >- {onCiteAssistantText && citationThreadRef ? (- <AssistantSelectionToolbar- viewport={timelineViewportElement}- threadRef={citationThreadRef}- onCite={onCiteAssistantText}+ <MarkdownFindContext value={findActive}>+ <TimelineRowCtx value={sharedState}>+ <TimelineRowActivityCtx value={activityState}>+ <TooltipScrollDismissArea+ ref={setTimelineViewportElement}+ className="relative h-full min-h-0"+ data-assistant-citation-viewport="true"+ >+ {onCiteAssistantText && citationThreadRef ? (+ <AssistantSelectionToolbar+ viewport={timelineViewportElement}+ threadRef={citationThreadRef}+ onCite={onCiteAssistantText}+ />+ ) : null}+ <LegendList<MessagesTimelineRow>+ ref={setTimelineList}+ data={rows}+ extraData={`${listIdentityKey}:${rows.length}`}+ keyExtractor={keyExtractor}+ getItemType={getItemType}+ renderItem={renderItem}+ estimatedItemSize={90}+ initialScrollAtEnd={+ !findActive && citationRequest === null && rememberedPosition?.atEnd !== false+ }+ // Legend needs a data refresh to mount new pins without a scroll event.+ dataVersion={readyCitationRequest?.key ?? listIdentityKey}+ {...(alwaysRender ? { alwaysRender } : {})}+ onLoad={handleListLoad}+ {...(anchoredEndSpace ? { anchoredEndSpace } : {})}+ contentInsetEndAdjustment={anchoredEndSpace ? contentInsetEndAdjustment : 0}+ maintainScrollAtEnd={+ citationPositioning ||+ (restoringThreadPosition && rememberedPosition?.atEnd === false) ||+ anchoredEndSpace ||+ !liveFollowEnabled ||+ fullscreenAppRowId !== null ||+ disclosureToggleSettling+ ? false+ : isWorking && !prefersReducedMotion && settlingListIdentity === null+ ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH+ : TIMELINE_MAINTAIN_SCROLL_AT_END+ }+ maintainVisibleContentPosition={+ findActive ||+ citationPositioning ||+ (restoringThreadPosition && rememberedPosition?.atEnd === false)+ ? false+ : maintainVisibleContentPosition+ }+ maintainScrollAtEndThreshold={1}+ onScroll={handleScroll}+ onItemSizeChanged={reportContentOverflow}+ className={cn(+ "messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]",+ topFadeEnabled && "topbar-scroll-fade",+ )}+ ListHeaderComponent={listHeader}+ ListFooterComponent={timelineListFooter}/>- ) : null}- <LegendList<MessagesTimelineRow>- ref={setTimelineList}- data={rows}- extraData={`${listIdentityKey}:${rows.length}`}- keyExtractor={keyExtractor}- getItemType={getItemType}- renderItem={renderItem}- estimatedItemSize={90}- initialScrollAtEnd={citationRequest === null && rememberedPosition?.atEnd !== false}- // Legend needs a data refresh to mount new pins without a scroll event.- dataVersion={readyCitationRequest?.key ?? listIdentityKey}- {...(alwaysRender ? { alwaysRender } : {})}- onLoad={onCitationListLoad}- {...(anchoredEndSpace ? { anchoredEndSpace } : {})}- contentInsetEndAdjustment={anchoredEndSpace ? contentInsetEndAdjustment : 0}- maintainScrollAtEnd={- citationPositioning ||- (restoringThreadPosition && rememberedPosition?.atEnd === false) ||- anchoredEndSpace ||- !liveFollowEnabled ||- fullscreenAppRowId !== null ||- disclosureToggleSettling- ? false- : isWorking && !prefersReducedMotion && settlingListIdentity === null- ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH- : TIMELINE_MAINTAIN_SCROLL_AT_END- }- maintainVisibleContentPosition={- citationPositioning ||- (restoringThreadPosition && rememberedPosition?.atEnd === false)- ? false- : maintainVisibleContentPosition- }- maintainScrollAtEndThreshold={1}- onScroll={handleScroll}- onItemSizeChanged={reportContentOverflow}- className={cn(- "messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]",- topFadeEnabled && "topbar-scroll-fade",- )}- ListHeaderComponent={listHeader}- ListFooterComponent={timelineListFooter}- />- <TimelineMinimap- items={minimapItems}- hasPersistentGutter={minimapHasPersistentGutter}- hitStripWidth={minimapHitStripWidth}- currentIndex={minimapCurrentIndex}- stripMap={minimapStripMap}- onSelect={(item) => {- onManualNavigation();- void listRef.current?.scrollToIndex({- index: item.rowIndex,- animated: true,- viewOffset: 24,- });- }}- />- </TooltipScrollDismissArea>- </TimelineRowActivityCtx>- </TimelineRowCtx>+ <TimelineMinimap+ items={minimapItems}+ hasPersistentGutter={minimapHasPersistentGutter}+ hitStripWidth={minimapHitStripWidth}+ currentIndex={minimapCurrentIndex}+ stripMap={minimapStripMap}+ onSelect={(item) => {+ onManualNavigation();+ void listRef.current?.scrollToIndex({+ index: item.rowIndex,+ animated: true,+ viewOffset: 24,+ });+ }}+ />+ </TooltipScrollDismissArea>+ </TimelineRowActivityCtx>+ </TimelineRowCtx>+ </MarkdownFindContext>);});@@ -1477,7 +1657,7 @@ function TimelineHistoryControl(props: MessagesTimelineHistoryControls) {type="button"disabled={props.loading}aria-label="Load earlier turns"- onClick={props.onLoadEarlier}+ onClick={() => props.onLoadEarlier()}className="w-full py-1.5 text-xs text-muted-foreground/60 hover:text-foreground disabled:cursor-default">{props.loading ? "Loading earlier turns…" : "Load earlier turns"}@@ -2144,21 +2324,23 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"? (userFiles.find((file) => file.id === record.attachmentId) ?? null): null;return (- <UserMessageContextReferenceChip- reference={reference}- record={record}- annotationImage={annotationImage}- attachment={attachment}- onExpandImage={(image) => {- const preview = buildExpandedImagePreview(userImages, image.id);- if (preview) onImageExpand(preview);- }}- onOpenFile={onFileOpen}- onExpandVideo={(file) => {- const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);- if (preview) onImageExpand(preview);- }}- />+ <span data-thread-find-ignore>+ <UserMessageContextReferenceChip+ reference={reference}+ record={record}+ annotationImage={annotationImage}+ attachment={attachment}+ onExpandImage={(image) => {+ const preview = buildExpandedImagePreview(userImages, image.id);+ if (preview) onImageExpand(preview);+ }}+ onOpenFile={onFileOpen}+ onExpandVideo={(file) => {+ const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);+ if (preview) onImageExpand(preview);+ }}+ />+ </span>);},[@@ -2568,26 +2750,28 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess<><div className="relative min-w-0 px-1 py-0.5"><MessageAuthorHeading>T3 Code</MessageAuthorHeading>- <AssistantCitationSource- messageId={row.message.id}- {...(ctx.threadRef ? { threadRef: ctx.threadRef } : {})}- itemKey={row.id}- request={ctx.citationRequest}- listRef={ctx.listRef}- >- <ChatMarkdown- text={messageText}- cwd={ctx.markdownCwd}- threadRef={ctx.threadRef ?? undefined}- isStreaming={Boolean(row.message.streaming)}- lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}- skills={ctx.skills}- headingLevelOffset={MESSAGE_HEADING_LEVEL}- onUseArtifactTemplate={ctx.onUseArtifactTemplate}- onRunShellCommand={ctx.onRunShellCommand}- onImageExpand={ctx.onImageExpand}- />- </AssistantCitationSource>+ <div data-thread-find-text="true">+ <AssistantCitationSource+ messageId={row.message.id}+ {...(ctx.threadRef ? { threadRef: ctx.threadRef } : {})}+ itemKey={row.id}+ request={ctx.citationRequest}+ listRef={ctx.listRef}+ >+ <ChatMarkdown+ text={messageText}+ cwd={ctx.markdownCwd}+ threadRef={ctx.threadRef ?? undefined}+ isStreaming={Boolean(row.message.streaming)}+ lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}+ skills={ctx.skills}+ headingLevelOffset={MESSAGE_HEADING_LEVEL}+ onUseArtifactTemplate={ctx.onUseArtifactTemplate}+ onRunShellCommand={ctx.onRunShellCommand}+ onImageExpand={ctx.onImageExpand}+ />+ </AssistantCitationSource>+ </div><AssistantChangedFilesSectionturnSummary={row.assistantTurnDiffSummary}routeThreadKey={ctx.routeThreadKey}@@ -2764,6 +2948,7 @@ function ProposedPlanTimelineRow({threadRef={ctx.threadRef ?? undefined}cwd={ctx.markdownCwd}workspaceRoot={ctx.workspaceRoot}+ findActive={ctx.findActive}/></div>);@@ -4534,16 +4719,23 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(propfooter?: ReactNode;}) {const [expanded, setExpanded] = useState(false);+ // Find opens the body only when it selects a match in the clipped part.+ const revealForFind = useCallback(() => setExpanded(true), []);+ const findRevealRef = useFindRevealRef(revealForFind);const hasVisibleBody = props.text.trim().length > 0;const canCollapse = hasVisibleBody && shouldCollapseUserMessage(props.text);const isCollapsed = canCollapse && !expanded;+ const showCollapseControl = canCollapse;return (<div>{hasVisibleBody ? (<div+ ref={findRevealRef}className={cn("relative", isCollapsed && "max-h-44 overflow-hidden")}data-user-message-body="true"+ data-thread-find-text="true"+ data-thread-find-fold={isCollapsed ? "" : undefined}data-user-message-collapsed={isCollapsed ? "true" : "false"}data-user-message-collapsible={canCollapse ? "true" : "false"}data-user-message-fade={isCollapsed ? "true" : "false"}@@ -4564,15 +4756,15 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop/></div>) : null}- {canCollapse || props.footer ? (+ {showCollapseControl || props.footer ? (<divclassName={cn("mt-1.5 flex items-center gap-2",- canCollapse && props.footer ? "justify-between" : "justify-end",+ showCollapseControl && props.footer ? "justify-between" : "justify-end",)}data-user-message-footer="true">- {canCollapse ? (+ {showCollapseControl ? (<Buttontype="button"size="xs"diff --git a/apps/web/src/components/chat/ProposedPlanCard.tsx b/apps/web/src/components/chat/ProposedPlanCard.tsxindex 856d50a10a6..de082c3d356 100644--- a/apps/web/src/components/chat/ProposedPlanCard.tsx+++ b/apps/web/src/components/chat/ProposedPlanCard.tsx@@ -1,4 +1,6 @@-import { memo, useState, useId } from "react";+import { proposedPlanTitle, stripDisplayedPlanMarkdown } from "@t3tools/shared/proposedPlanText";+import { memo, useCallback, useState, useId } from "react";+import { useFindRevealRef } from "./markdownFindContext";import {isAtomCommandInterrupted,squashAtomCommandFailure,@@ -13,8 +15,6 @@ import {buildProposedPlanMarkdownFilename,downloadPlanAsTextFile,normalizePlanMarkdownForExport,- proposedPlanTitle,- stripDisplayedPlanMarkdown,} from "../../proposedPlan";import ChatMarkdown from "../ChatMarkdown";import { EllipsisIcon } from "lucide-react";@@ -44,12 +44,14 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({threadRef,cwd,workspaceRoot,+ findActive = false,}: {planMarkdown: string;environmentId: EnvironmentId;threadRef?: ScopedThreadRef | undefined;cwd: string | undefined;workspaceRoot: string | undefined;+ findActive?: boolean;}) {const [expanded, setExpanded] = useState(false);const canWriteFiles = useEnvironmentScope(environmentId, AuthFilesystemWriteScope);@@ -79,6 +81,12 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({const collapsedPreview = canCollapse? buildCollapsedProposedPlanPreviewMarkdown(planMarkdown, { maxLines: 10 }): null;+ const isCollapsed = canCollapse && !expanded;+ // While finding, the full plan stays mounted but clipped, so a match past the+ // preview can be counted and then opened only once it is selected.+ const showPreview = isCollapsed && !findActive;+ const revealForFind = useCallback(() => setExpanded(true), []);+ const findRevealRef = useFindRevealRef(revealForFind);const downloadFilename = buildProposedPlanMarkdownFilename(planMarkdown);const saveContents = normalizePlanMarkdownForExport(planMarkdown);@@ -159,7 +167,9 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({<Badge variant="secondary">Plan</Badge>{/* Same heading level as the message author headings in the timeline,so a plan's own headings nest beneath it in the outline. */}- <h3 className="truncate text-sm font-medium text-foreground">{title}</h3>+ <h3 data-thread-find-text="true" className="truncate text-sm font-medium text-foreground">+ {title}+ </h3></div><Menu><MenuTrigger@@ -182,8 +192,13 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({</Menu></div><div className="mt-4">- <div className={cn("relative", canCollapse && !expanded && "max-h-104 overflow-hidden")}>- {canCollapse && !expanded ? (+ <div+ ref={findRevealRef}+ className={cn("relative", isCollapsed && "max-h-104 overflow-hidden")}+ data-thread-find-text="true"+ data-thread-find-fold={isCollapsed ? "" : undefined}+ >+ {showPreview ? (<ChatMarkdowntext={collapsedPreview ?? ""}cwd={cwd}@@ -202,7 +217,7 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({headingLevelOffset={3}/>)}- {canCollapse && !expanded ? (+ {isCollapsed ? (<div className="pointer-events-none absolute inset-x-0 bottom-0 h-24 bg-linear-to-t from-card/95 via-card/80 to-transparent" />) : null}</div>diff --git a/apps/web/src/components/chat/SkillInlineText.tsx b/apps/web/src/components/chat/SkillInlineText.tsxindex 2327577b3a8..5832f8904a5 100644--- a/apps/web/src/components/chat/SkillInlineText.tsx+++ b/apps/web/src/components/chat/SkillInlineText.tsx@@ -1,34 +1,20 @@+import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";import { Children, cloneElement, isValidElement, type ReactNode } from "react";-import type { ServerProviderSkill } from "@t3tools/contracts";-import { formatProviderSkillDisplayName } from "@t3tools/client-runtime/providerSkills";+import { matchInlineSkills, type InlineSkill } from "@t3tools/shared/inlineSkills";import { SKILL_CHIP_ICON_SVG } from "../composerInlineChip";import { ContextChip, ContextChipLabel } from "../ContextChip";-const SKILL_TOKEN_REGEX =- /(^|\s)\p{Sc}(?![0-9][0-9_]*(?:[kKmMbBtT]|[eE][0-9]+)?(?:\s|$))(?=[a-zA-Z0-9:_-]*[a-zA-Z])([a-zA-Z0-9][a-zA-Z0-9:_-]*)(?=\s|$)/gu;--type InlineSkill = Pick<ServerProviderSkill, "name" | "displayName">;-export function SkillInlineText(props: { text: string; skills: ReadonlyArray<InlineSkill> }) {const nodes: ReactNode[] = [];let cursor = 0;- for (const match of props.text.matchAll(SKILL_TOKEN_REGEX)) {- const prefix = match[1] ?? "";- const name = match[2] ?? "";- const start = (match.index ?? 0) + prefix.length;- const rawText = `$${name}`;- const skill = props.skills.find((candidate) => candidate.name === name);- if (!skill) {- continue;- }-+ for (const { start, end, skill, rawText } of matchInlineSkills(props.text, props.skills)) {if (start > cursor) {nodes.push(props.text.slice(cursor, start));}- nodes.push(<SkillChip key={`${start}:${name}`} skill={skill} rawText={rawText} />);- cursor = (match.index ?? 0) + match[0].length;+ nodes.push(<SkillChip key={`${start}:${skill.name}`} skill={skill} rawText={rawText} />);+ cursor = end;}if (cursor === 0) {diff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsxindex 74cbf60cc9e..040c7ec81f1 100644--- a/apps/web/src/components/chat/ThreadDetailsCard.tsx+++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx@@ -31,6 +31,7 @@ export function ThreadDetailsCard({container: canvas.container,lane: canvas.lane,frame: null,+ topInset: canvas.detailsCardTopInset,}): null;const placement = canvas@@ -39,6 +40,7 @@ export function ThreadDetailsCard({lane: canvas.lane,frame: canvas.layout.frame,overlapsDetailsCard: canvas.layout.overlapsDetailsCard,+ topInset: canvas.detailsCardTopInset,}): null;const mode = placement ? "inline" : "popover";diff --git a/apps/web/src/components/chat/ThreadFindBar.tsx b/apps/web/src/components/chat/ThreadFindBar.tsxnew file mode 100644index 00000000000..21e3eeee2d6--- /dev/null+++ b/apps/web/src/components/chat/ThreadFindBar.tsx@@ -0,0 +1,123 @@+import { useEffect, useRef, type KeyboardEvent } from "react";+import { ChevronDownIcon, ChevronUpIcon, XIcon } from "lucide-react";+import { Button } from "../ui/button";+import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";+import { cn } from "~/lib/utils";+import { formatThreadFindCount } from "./threadFind";+import { THREAD_DETAILS_CARD_GAP } from "./threadDetailsCardLayout";++interface ThreadFindBarProps {+ readonly open: boolean;+ readonly query: string;+ readonly matchCount: number;+ readonly counting?: boolean;+ readonly status: "loading" | "error" | null;+ readonly onRetry: () => void;+ readonly activeIndex: number;+ readonly focusRequestId: number;+ readonly onQueryChange: (query: string) => void;+ readonly onNext: () => void;+ readonly onPrevious: () => void;+ readonly onClose: () => void;+}++/**+ * Room the open bar takes at the top of the chat canvas: its `h-9` height plus+ * the shared 12px gap below it, so the details card starts on the same rhythm.+ */+export const THREAD_FIND_BAR_RESERVED_HEIGHT = 36 + THREAD_DETAILS_CARD_GAP;++export function ThreadFindBar(props: ThreadFindBarProps) {+ const inputRef = useRef<HTMLInputElement | null>(null);++ useEffect(() => {+ if (!props.open) return;+ inputRef.current?.focus();+ inputRef.current?.select();+ }, [props.focusRequestId, props.open]);++ if (!props.open) return null;++ const hasQuery = props.query.trim().length > 0;+ const noResults = hasQuery && !props.status && props.matchCount === 0;+ let label = "";+ if (hasQuery) {+ label = props.counting ? "1/…" : formatThreadFindCount(props.activeIndex, props.matchCount);+ }+ if (props.status === "loading") label = "Searching…";+ if (props.status === "error") label = "Search failed";+ const navigationDisabled =+ props.matchCount === 0 || props.status === "loading" || props.counting === true;+ const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {+ if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return;+ if (event.key === "Enter") {+ event.preventDefault();+ event.stopPropagation();+ if (event.shiftKey) props.onPrevious();+ else props.onNext();+ }+ };++ return (+ <InputGroup+ variant="popover"+ size="lg"+ onContextMenu={(event) => event.stopPropagation()}+ role="search"+ aria-label="Find in thread"+ aria-busy={props.status === "loading" || props.counting === true}+ className="absolute top-3 right-3 z-40 w-[min(24rem,calc(100%-1.5rem))]"+ >+ <InputGroupInput+ ref={inputRef}+ type="search"+ size="sm"+ value={props.query}+ aria-label="Find in thread"+ placeholder="Find in thread"+ maxLength={200}+ spellCheck={false}+ autoComplete="off"+ onChange={(event) => props.onQueryChange(event.target.value)}+ onKeyDown={handleKeyDown}+ />+ <InputGroupAddon align="inline-end" inset="pill">+ <span+ aria-live="polite"+ className={cn(+ "min-w-10 text-center text-xs tabular-nums",+ noResults ? "text-destructive" : "text-muted-foreground",+ )}+ >+ {label}+ </span>+ {props.status === "error" ? (+ <Button size="xs" variant="ghost" onClick={props.onRetry}>+ Retry+ </Button>+ ) : null}+ <Button+ size="icon-xs"+ variant="ghost"+ aria-label="Previous match"+ disabled={navigationDisabled}+ onClick={props.onPrevious}+ >+ <ChevronUpIcon />+ </Button>+ <Button+ size="icon-xs"+ variant="ghost"+ aria-label="Next match"+ disabled={navigationDisabled}+ onClick={props.onNext}+ >+ <ChevronDownIcon />+ </Button>+ <Button size="icon-xs" variant="ghost" aria-label="Close find" onClick={props.onClose}>+ <XIcon />+ </Button>+ </InputGroupAddon>+ </InputGroup>+ );+}diff --git a/apps/web/src/components/chat/ThreadFindProvider.test.tsx b/apps/web/src/components/chat/ThreadFindProvider.test.tsxnew file mode 100644index 00000000000..b2830fd7440--- /dev/null+++ b/apps/web/src/components/chat/ThreadFindProvider.test.tsx@@ -0,0 +1,127 @@+import { act, createRef, useContext, useState } from "react";+import { create, type ReactTestRenderer } from "react-test-renderer";+import { afterEach, expect, it, vi } from "vite-plus/test";+import {+ EnvironmentId,+ ThreadId,+ type OrchestrationV2SearchThreadResult,+} from "@t3tools/contracts";+import {+ ThreadFind,+ ThreadFindProvider,+ ThreadFindTimelineContext,+ type ThreadFindControls,+} from "./ThreadFindProvider";+import type { ThreadFindBar } from "./ThreadFindBar";++const query = vi.hoisted(() => ({+ value: {+ data: null as OrchestrationV2SearchThreadResult | null,+ isPending: false,+ error: null,+ refresh: vi.fn(),+ },+ listeners: new Set<() => void>(),+}));+let bar: Parameters<typeof ThreadFindBar>[0];+vi.mock("./ThreadFindBar", () => ({+ ThreadFindBar: (props: typeof bar) => {+ bar = props;+ return null;+ },+}));+vi.mock("~/state/orchestration", () => ({+ orchestrationEnvironment: { threadFind: (target: unknown) => target },+}));+vi.mock("~/state/queries", () => ({ useDebouncedValue: <T,>(value: T) => value }));+vi.mock("~/state/query", async () => {+ const { useSyncExternalStore } = await import("react");+ return {+ useEnvironmentQuery: (atom: unknown) => {+ const value = useSyncExternalStore(+ (listener) => {+ query.listeners.add(listener);+ return () => query.listeners.delete(listener);+ },+ () => query.value,+ );+ return { ...value, data: atom ? value.data : null };+ },+ };+});+vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));++let renderer: ReactTestRenderer | undefined;+afterEach(async () => {+ if (renderer) await act(async () => renderer?.unmount());+ renderer = undefined;+ query.listeners.clear();+ vi.unstubAllGlobals();+});++it("keeps navigation and pending responses out of the surrounding chat and unrelated children", async () => {+ vi.stubGlobal("window", new EventTarget());+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ const controls = createRef<ThreadFindControls>();+ const parentRender = vi.fn();+ const composerRender = vi.fn();+ const timelineRender = vi.fn();+ function Composer() {+ composerRender();+ return null;+ }+ function Timeline() {+ timelineRender(useContext(ThreadFindTimelineContext));+ return null;+ }+ function Chat() {+ parentRender();+ const [, setOpen] = useState(false);+ return (+ <ThreadFindProvider+ thread={{ environmentId: EnvironmentId.make("dev"), threadId: ThreadId.make("thread") }}+ enabled+ content={undefined}+ controlsRef={controls}+ onOpenChange={setOpen}+ >+ <ThreadFind onClose={() => {}} />+ <Timeline />+ <Composer />+ </ThreadFindProvider>+ );+ }+ const response = (index: number): OrchestrationV2SearchThreadResult => ({+ totalMatches: 3,+ activeIndex: index,+ snapshotSequence: 1,+ match: { entryId: "message", runId: null, occurrence: index },+ });+ query.value = { ...query.value, data: response(0), isPending: false };+ await act(async () => {+ renderer = create(<Chat />);+ });+ await act(async () => controls.current?.open());+ await act(async () => bar.onQueryChange("COD4"));+ const parentCount = parentRender.mock.calls.length;+ const composerCount = composerRender.mock.calls.length;+ const timelineCount = timelineRender.mock.calls.length;+ await act(async () => {+ query.value = { ...query.value, data: null, isPending: true };+ for (const listener of query.listeners) listener();+ bar.onNext();+ });+ expect(parentRender).toHaveBeenCalledTimes(parentCount);+ expect(composerRender).toHaveBeenCalledTimes(composerCount);+ expect(timelineRender).toHaveBeenCalledTimes(timelineCount);+ await act(async () => {+ query.value = { ...query.value, data: response(1), isPending: false };+ for (const listener of query.listeners) listener();+ });+ expect(parentRender).toHaveBeenCalledTimes(parentCount);+ expect(composerRender).toHaveBeenCalledTimes(composerCount);+ expect(timelineRender).toHaveBeenCalledTimes(timelineCount + 1);+ expect(timelineRender.mock.lastCall?.[0]?.activeFindMatch?.occurrence).toBe(1);+ await act(async () => controls.current?.close());+ expect(parentRender.mock.calls.length).toBeGreaterThan(parentCount);+});diff --git a/apps/web/src/components/chat/ThreadFindProvider.tsx b/apps/web/src/components/chat/ThreadFindProvider.tsxnew file mode 100644index 00000000000..f35fcea8f92--- /dev/null+++ b/apps/web/src/components/chat/ThreadFindProvider.tsx@@ -0,0 +1,72 @@+import {+ createContext,+ use,+ useEffect,+ useImperativeHandle,+ type ReactNode,+ type ComponentProps,+ type Ref,+} from "react";+import { useThreadFind } from "./useThreadFind";+import { ThreadFindBar } from "./ThreadFindBar";+import { ChatCanvas } from "./ChatCanvas";++type Find = ReturnType<typeof useThreadFind>;+export type ThreadFindControls = Pick<Find, "open" | "close">;+export const ThreadFindTimelineContext = createContext<Find["timelineProps"] | null>(null);+const ThreadFindBarContext = createContext<Find["barProps"] | null>(null);++export function ThreadFindCanvas({+ findOptions,+ controlsRef,+ onOpenChange,+ ...canvasProps+}: ComponentProps<typeof ChatCanvas> & {+ findOptions: Parameters<typeof useThreadFind>[0];+ controlsRef: Ref<ThreadFindControls>;+ onOpenChange: (open: boolean) => void;+}) {+ return (+ <ThreadFindProvider {...findOptions} controlsRef={controlsRef} onOpenChange={onOpenChange}>+ <ChatCanvas {...canvasProps} />+ </ThreadFindProvider>+ );+}++/** Owns search updates below the chat view so cycling does not rerender the composer and panels. */+export function ThreadFindProvider({+ controlsRef,+ onOpenChange,+ children,+ ...options+}: Parameters<typeof useThreadFind>[0] & {+ controlsRef: Ref<ThreadFindControls>;+ onOpenChange: (open: boolean) => void;+ children: ReactNode;+}) {+ const find = useThreadFind(options);+ useImperativeHandle(controlsRef, () => ({ open: find.open, close: find.close }), [+ find.open,+ find.close,+ ]);+ useEffect(() => onOpenChange(find.isOpen), [find.isOpen, onOpenChange]);+ return (+ <ThreadFindBarContext value={find.barProps}>+ <ThreadFindTimelineContext value={find.timelineProps}>{children}</ThreadFindTimelineContext>+ </ThreadFindBarContext>+ );+}++export function ThreadFind({ onClose }: { onClose: () => void }) {+ const bar = use(ThreadFindBarContext);+ if (!bar) return null;+ return (+ <ThreadFindBar+ {...bar}+ onClose={() => {+ bar.onClose();+ onClose();+ }}+ />+ );+}diff --git a/apps/web/src/components/chat/markdownFindContext.ts b/apps/web/src/components/chat/markdownFindContext.tsnew file mode 100644index 00000000000..64754cc6b3c--- /dev/null+++ b/apps/web/src/components/chat/markdownFindContext.ts@@ -0,0 +1,20 @@+import { createContext, useCallback } from "react";++// While find is active, folded content stays mounted (hidden) so its text can be+// matched. Nothing opens until the selected match lies inside it.+export const MarkdownFindContext = createContext(false);++/**+ * Find dispatches `beforematch` on hidden or clipped ancestors of the selected+ * match, like the browser's own find-in-page. `onReveal` must be stable.+ */+export function useFindRevealRef(onReveal: () => void) {+ return useCallback(+ (element: HTMLElement | null) => {+ if (!element) return;+ element.addEventListener("beforematch", onReveal);+ return () => element.removeEventListener("beforematch", onReveal);+ },+ [onReveal],+ );+}diff --git a/apps/web/src/components/chat/threadDetailsCardLayout.test.ts b/apps/web/src/components/chat/threadDetailsCardLayout.test.tsindex 165985245cd..e7d961bc811 100644--- a/apps/web/src/components/chat/threadDetailsCardLayout.test.ts+++ b/apps/web/src/components/chat/threadDetailsCardLayout.test.ts@@ -22,6 +22,16 @@ describe("workspace card", () => {});expect(resolve(1344, 900)).toMatchObject({ x: 1052, width: 280 });});+ it("starts below the open find bar, keeping the bottom inset", () => {+ expect(+ resolveThreadDetailsCardLayout({+ container: { width: 1600, height: 900 },+ lane,+ frame: null,+ topInset: 48,+ }),+ ).toEqual({ x: 1308, y: 60, width: 280, height: 828 });+ });it("hides when a readable chat lane cannot fit beside it", () => {expect(resolve(984, 900)).toMatchObject({ x: 692 });expect(resolve(983, 900)).toBeNull();diff --git a/apps/web/src/components/chat/threadDetailsCardLayout.ts b/apps/web/src/components/chat/threadDetailsCardLayout.tsindex 655aaa48706..8353a3883ba 100644--- a/apps/web/src/components/chat/threadDetailsCardLayout.ts+++ b/apps/web/src/components/chat/threadDetailsCardLayout.ts@@ -1,6 +1,9 @@import type { PreviewMiniPlayerFrame } from "../preview/previewMiniPlayerLayout";import { DETAILS_CARD_CLEARANCE } from "./chatCanvasLayout";+/** Inset of the card from the canvas edges; the find bar shares it to line up. */+export const THREAD_DETAILS_CARD_GAP = 12;+export function resolveThreadDetailsCardDensity(height: number,content: { full: number; compact: number },@@ -19,28 +22,32 @@ export function resolveThreadDetailsCardLayout({lane,frame,overlapsDetailsCard = false,+ topInset = 0,}: {container: { width: number; height: number };lane: { padding: number; minChatWidth: number };frame: PreviewMiniPlayerFrame | null;overlapsDetailsCard?: boolean;+ /** Space taken above the card, such as the open find bar. */+ topInset?: number;}) {- const gap = 12;+ const gap = THREAD_DETAILS_CARD_GAP;// Keep in sync with --thread-details-panel-width, which sizes the popover.const width = 280;const x = container.width - width - gap;if (x - DETAILS_CARD_CLEARANCE - lane.padding < lane.minChatWidth) return null;+ const y = gap + topInset;// Resizing consumes the height above the player. Dragging first tries to// clear the full card and folds it only when there is no readable placement.const height =overlapsDetailsCard && frame && frame.x + frame.width > x - gap && frame.x < x + width + gap- ? Math.min(container.height - gap * 2, frame.y - gap * 2)- : container.height - gap * 2;+ ? Math.min(container.height - y - gap, frame.y - y - gap)+ : container.height - y - gap;if (height < 160) return null;return {x,width,- y: gap,+ y,height,} as const;}diff --git a/apps/web/src/components/chat/threadFind.test.ts b/apps/web/src/components/chat/threadFind.test.tsnew file mode 100644index 00000000000..10511f4a260--- /dev/null+++ b/apps/web/src/components/chat/threadFind.test.ts@@ -0,0 +1,11 @@+import { describe, expect, it } from "vite-plus/test";+import { formatThreadFindCount, stepThreadFindIndex } from "./threadFind";++describe("thread find navigation", () => {+ it("clamps, wraps, and formats positions", () => {+ expect(stepThreadFindIndex(2, 3, 1)).toBe(0);+ expect(stepThreadFindIndex(0, 3, -1)).toBe(2);+ expect(formatThreadFindCount(4, 2)).toBe("2/2");+ expect(formatThreadFindCount(0, 0)).toBe("0/0");+ });+});diff --git a/apps/web/src/components/chat/threadFind.ts b/apps/web/src/components/chat/threadFind.tsnew file mode 100644index 00000000000..dbb49848465--- /dev/null+++ b/apps/web/src/components/chat/threadFind.ts@@ -0,0 +1,28 @@+import type { OrchestrationV2SearchThreadInput, RunId } from "@t3tools/contracts";++export type ThreadFindStart = NonNullable<OrchestrationV2SearchThreadInput["start"]>;+export type ThreadFindPositionReader = (query: string) => ThreadFindStart | undefined;++/** One occurrence of the query inside a searchable timeline entry. */+export interface ThreadFindMatch {+ readonly entryId: string;+ /** The turn to expand when the matching entry is folded. */+ readonly runId: RunId | null;+ /** Zero-based occurrence within this timeline entry. */+ readonly occurrence: number;+}++function clampThreadFindIndex(index: number, total: number): number {+ if (total <= 0 || !Number.isFinite(index) || index < 0) return 0;+ return Math.min(Math.trunc(index), total - 1);+}++export function stepThreadFindIndex(index: number, total: number, delta: number): number {+ if (total <= 0) return 0;+ const clamped = clampThreadFindIndex(index, total);+ return (((clamped + delta) % total) + total) % total;+}++export function formatThreadFindCount(index: number, total: number): string {+ return total <= 0 ? "0/0" : `${clampThreadFindIndex(index, total) + 1}/${total}`;+}diff --git a/apps/web/src/components/chat/threadFindActionBus.ts b/apps/web/src/components/chat/threadFindActionBus.tsnew file mode 100644index 00000000000..375610fbc07--- /dev/null+++ b/apps/web/src/components/chat/threadFindActionBus.ts@@ -0,0 +1,10 @@+const THREAD_FIND_OPEN_EVENT = "t3:thread-find-open";++export function requestThreadFindOpen(): void {+ window.dispatchEvent(new Event(THREAD_FIND_OPEN_EVENT));+}++export function subscribeThreadFindOpen(listener: () => void): () => void {+ window.addEventListener(THREAD_FIND_OPEN_EVENT, listener);+ return () => window.removeEventListener(THREAD_FIND_OPEN_EVENT, listener);+}diff --git a/apps/web/src/components/chat/threadFindHighlights.test.tsx b/apps/web/src/components/chat/threadFindHighlights.test.tsxnew file mode 100644index 00000000000..631510f35b8--- /dev/null+++ b/apps/web/src/components/chat/threadFindHighlights.test.tsx@@ -0,0 +1,276 @@+// @vitest-environment jsdom++import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { collectThreadFindRanges, useThreadFindHighlights } from "./threadFindHighlights";++function Probe(props: Parameters<typeof useThreadFindHighlights>[0]) {+ useThreadFindHighlights(props);+ return null;+}++let root: Root;+let host: HTMLElement;+let container: HTMLElement;+const onActiveRange = vi.fn();+const activeRanges = () => [+ ...(CSS.highlights.get("t3-thread-find-active") as unknown as Set<Range>),+];++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.stubGlobal("CSS", { highlights: new Map() });+ vi.stubGlobal(+ "Highlight",+ class extends Set<Range> {+ constructor(...ranges: Range[]) {+ super(ranges);+ }+ },+ );+ host = document.createElement("div");+ container = document.createElement("div");+ container.innerHTML =+ '<div data-timeline-row-id="first"><p data-thread-find-text>COD4 and COD4</p></div>' ++ '<div data-timeline-row-id="second"><p data-thread-find-text>COD4</p></div>';+ document.body.append(host, container);+ root = createRoot(host);+});+afterEach(async () => {+ await act(async () => root.unmount());+ host.remove();+ container.remove();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ vi.unstubAllGlobals();+});++describe("find highlight caching", () => {+ it("checks only the old and new occurrence when cycling a message with many clipped matches", async () => {+ container.innerHTML =+ '<div data-timeline-row-id="first"><div data-thread-find-fold><p data-thread-find-text>' ++ "COD4 ".repeat(1500) ++ "</p></div></div>";+ const bounds = vi.fn(() => new DOMRect(0, 0, 40, 20));+ Object.defineProperty(Range.prototype, "getBoundingClientRect", {+ configurable: true,+ value: bounds,+ });+ container.querySelector<HTMLElement>("[data-thread-find-fold]")!.getBoundingClientRect = () =>+ new DOMRect(0, 0, 800, 100);+ const props = {+ container,+ query: "COD4",+ activeRowId: "first",+ activeOccurrence: 0,+ onActiveRange,+ };+ try {+ await act(async () => root.render(<Probe {...props} />));+ const inactive = CSS.highlights.get("t3-thread-find");+ const first = activeRanges()[0];+ bounds.mockClear();+ await act(async () => root.render(<Probe {...props} activeOccurrence={1} />));+ expect(bounds).toHaveBeenCalledTimes(2);+ expect(CSS.highlights.get("t3-thread-find")).toBe(inactive);+ expect(inactive?.size).toBe(1499);+ expect(inactive?.has(first!)).toBe(true);+ expect(activeRanges()[0]?.startOffset).toBe(5);+ expect(inactive?.has(activeRanges()[0]!)).toBe(false);+ } finally {+ Reflect.deleteProperty(Range.prototype, "getBoundingClientRect");+ }+ });++ it("repaints for searchable text changes but not for timers outside it", async () => {+ const timer = document.createElement("span");+ container.firstElementChild!.append(timer);+ await act(async () =>+ root.render(+ <Probe+ container={container}+ query="COD4"+ activeRowId="first"+ activeOccurrence={0}+ onActiveRange={onActiveRange}+ />,+ ),+ );+ onActiveRange.mockClear();+ await act(async () => {+ timer.textContent = "0:01";+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ expect(onActiveRange).not.toHaveBeenCalled();+ await act(async () => {+ container.querySelector("p")!.append(" COD4");+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ expect(onActiveRange).toHaveBeenCalled();+ });++ it("opens only the selected fold while reusing its cached text", async () => {+ container.innerHTML =+ '<div data-timeline-row-id="first"><div hidden><p data-thread-find-text>COD4 COD4</p></div></div>' ++ '<div data-timeline-row-id="second"><div hidden><p data-thread-find-text>COD4</p></div></div>';+ const folds = [...container.querySelectorAll<HTMLElement>("[hidden]")];+ for (const fold of folds)+ fold.addEventListener("beforematch", () => fold.removeAttribute("hidden"));+ const createRange = vi.spyOn(document, "createRange");+ await act(async () =>+ root.render(+ <Probe+ container={container}+ query="COD4"+ activeRowId="first"+ activeOccurrence={0}+ onActiveRange={onActiveRange}+ />,+ ),+ );+ await act(async () => {+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ expect(folds[0]?.hasAttribute("hidden")).toBe(false);+ expect(folds[1]?.hasAttribute("hidden")).toBe(true);+ expect(activeRanges()[0]?.toString()).toBe("COD4");+ expect(CSS.highlights.get("t3-thread-find")?.size).toBe(1);+ const scanned = createRange.mock.calls.length;+ await act(async () =>+ root.render(+ <Probe+ container={container}+ query="COD4"+ activeRowId="first"+ activeOccurrence={1}+ onActiveRange={onActiveRange}+ />,+ ),+ );+ expect(createRange).toHaveBeenCalledTimes(scanned);+ expect(activeRanges()[0]?.startOffset).toBe(5);+ });++ it("observes rows mounted synchronously while revealing the first match", async () => {+ container.replaceChildren();+ onActiveRange.mockImplementationOnce(() => {+ container.innerHTML =+ '<div data-timeline-row-id="first"><p data-thread-find-text>COD4</p></div>';+ });+ await act(async () => {+ root.render(+ <Probe+ container={container}+ query="COD4"+ activeRowId="first"+ activeOccurrence={0}+ onActiveRange={onActiveRange}+ />,+ );+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ await act(async () => {+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ expect(activeRanges()[0]?.toString()).toBe("COD4");+ });++ it("rebuilds ranges when the list moves or recycles an existing row", async () => {+ const props = {+ container,+ query: "COD4",+ activeRowId: "first",+ activeOccurrence: 0,+ onActiveRange,+ };+ await act(async () => root.render(<Probe {...props} />));+ const initial = activeRanges()[0];+ const row = container.querySelector<HTMLElement>('[data-timeline-row-id="first"]')!;+ await act(async () => {+ row.remove();+ container.append(row);+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ expect(activeRanges()[0]).not.toBe(initial);+ expect(activeRanges()[0]?.toString()).toBe("COD4");+ await act(async () => {+ row.dataset.timelineRowId = "recycled";+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ expect(activeRanges()).toHaveLength(0);+ await act(async () => root.render(<Probe {...props} activeRowId="recycled" />));+ expect(activeRanges()[0]?.toString()).toBe("COD4");+ });++ it("reuses unchanged text ranges on navigation and scans only the streaming row", async () => {+ const createRange = vi.spyOn(document, "createRange");+ const props = {+ container,+ query: "COD4",+ activeRowId: "first",+ activeOccurrence: 0,+ onActiveRange,+ };+ await act(async () => root.render(<Probe {...props} />));+ expect(createRange).toHaveBeenCalledTimes(3);+ const initial = activeRanges()[0];+ await act(async () => root.render(<Probe {...props} activeOccurrence={1} />));+ expect(createRange).toHaveBeenCalledTimes(3);+ expect(activeRanges()[0]?.startOffset).toBe(9);+ await act(async () => root.render(<Probe {...props} />));+ expect(activeRanges()[0]).toBe(initial);+ await act(async () => {+ container.querySelector('[data-timeline-row-id="second"] p')!.firstChild!.nodeValue =+ "COD4 COD4";+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ expect(createRange).toHaveBeenCalledTimes(5);+ expect(activeRanges()[0]).toBe(initial);+ await act(async () =>+ root.render(<Probe {...props} activeRowId="second" activeOccurrence={1} />),+ );+ expect(createRange).toHaveBeenCalledTimes(5);+ expect(activeRanges()[0]?.toString()).toBe("COD4");+ expect(activeRanges()[0]?.startOffset).toBe(5);+ await act(async () => {+ container.querySelector('[data-timeline-row-id="second"]')!.remove();+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ expect(activeRanges()).toHaveLength(0);+ expect(onActiveRange).toHaveBeenLastCalledWith(null);+ expect(CSS.highlights.get("t3-thread-find")?.size).toBe(2);+ await act(async () => root.render(<Probe {...props} query="missing" />));+ expect(CSS.highlights.get("t3-thread-find")?.size).toBe(0);+ });+});++function row(html: string) {+ const container = document.createElement("div");+ container.innerHTML = `<div data-timeline-row-id="row"><div data-thread-find-text>${html}</div></div>`;+ return container;+}++describe("collectThreadFindRanges", () => {+ it("finds matches split across inline token spans, in order", () => {+ // Shiki-style tokens split one identifier over several text nodes.+ const container = row(+ "<pre><code><span>con</span><span>st</span> a = <span>c</span>onst; const</code></pre>",+ );+ const ranges = collectThreadFindRanges(container, "const");+ expect(ranges.map((match) => [match.occurrence, match.range.toString()])).toEqual([+ [0, "const"],+ [1, "const"],+ [2, "const"],+ ]);+ });++ it("finds every match across thousands of token nodes", () => {+ const tokens = Array.from({ length: 4000 }, (_, i) => `<span>id</span><span>${i} </span>`);+ const container = row(`<pre><code>${tokens.join("")}</code></pre>`);+ const ranges = collectThreadFindRanges(container, "id");+ expect(ranges).toHaveLength(4000);+ expect(ranges.map((match) => match.occurrence)).toEqual([...ranges.keys()]);+ expect(ranges.every((match) => match.range.toString() === "id")).toBe(true);+ });+});diff --git a/apps/web/src/components/chat/threadFindHighlights.ts b/apps/web/src/components/chat/threadFindHighlights.tsnew file mode 100644index 00000000000..6a505de65fe--- /dev/null+++ b/apps/web/src/components/chat/threadFindHighlights.ts@@ -0,0 +1,269 @@+import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";+import { useEffect, useLayoutEffect, useRef } from "react";+import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText";++const THREAD_FIND_HIGHLIGHT_NAME = "t3-thread-find";+const THREAD_FIND_ACTIVE_HIGHLIGHT_NAME = "t3-thread-find-active";++const THREAD_FIND_TEXT_SELECTOR = "[data-thread-find-text]";+const THREAD_FIND_IGNORE_SELECTOR = "[data-thread-find-ignore]";++interface ThreadFindRange {+ readonly rowId: string;+ readonly occurrence: number;+ readonly range: Range;+}++/** Collects visible occurrences without modifying rendered markdown. */+export function collectThreadFindRanges(container: HTMLElement, query: string): ThreadFindRange[] {+ if (query.length === 0) return [];++ const ranges: ThreadFindRange[] = [];+ const occurrenceByRowId = new Map<string, number>();++ for (const scope of container.querySelectorAll(THREAD_FIND_TEXT_SELECTOR)) {+ if (scope.parentElement?.closest(THREAD_FIND_TEXT_SELECTOR)) continue;+ const rowId = scope.closest("[data-timeline-row-id]")?.getAttribute("data-timeline-row-id");+ if (!rowId) continue;++ let text = "";+ let nodes: { node: Node; start: number; end: number }[] = [];+ const flush = () => {+ // Offsets ascend, so both node cursors only move forward: linear in text nodes.+ let startIndex = 0;+ let endIndex = 0;+ for (const offset of findThreadSearchOccurrences(text, query)) {+ while (startIndex < nodes.length && nodes[startIndex]!.end <= offset) startIndex++;+ if (endIndex < startIndex) endIndex = startIndex;+ while (endIndex < nodes.length && nodes[endIndex]!.end < offset + query.length) endIndex++;+ const start = nodes[startIndex];+ const end = nodes[endIndex];+ if (!start || !end) continue;+ const range = container.ownerDocument.createRange();+ range.setStart(start.node, offset - start.start);+ range.setEnd(end.node, offset + query.length - end.start);+ const occurrence = occurrenceByRowId.get(rowId) ?? 0;+ ranges.push({ rowId, occurrence, range });+ occurrenceByRowId.set(rowId, occurrence + 1);+ }+ text = "";+ nodes = [];+ };+ const visit = (node: Node, inPre = false) => {+ const element = node.nodeType === 1 ? (node as Element) : null;+ if (element?.matches("svg")) return;+ if (element?.matches(`${THREAD_FIND_IGNORE_SELECTOR}, [role="toolbar"]`)) {+ flush();+ return;+ }+ const tag = element?.tagName.toLowerCase() ?? "";+ const block = THREAD_FIND_BLOCK_TAGS.has(tag);+ if (block) flush();+ if (node.nodeType === 3) {+ const value = node.nodeValue ?? "";+ const start = text.length;+ text += inPre ? value : value.replace(/\r?\n/g, " ");+ nodes.push({ node, start, end: text.length });+ }+ for (const child of node.childNodes) visit(child, inPre || tag === "pre");+ if (block) flush();+ };+ visit(scope);+ flush();+ }+ return ranges;+}++/** Ancestors that hide (`hidden`) or clip (`data-thread-find-fold`) text until find opens them. */+const FOLD_SELECTOR = "[hidden], [data-thread-find-fold]";++/** Folds around the range that currently keep it out of sight, innermost first. */+function foldsHiding(range: Range, container: HTMLElement): Element[] {+ const folds: Element[] = [];+ for (+ let fold = range.startContainer.parentElement?.closest(FOLD_SELECTOR);+ fold && container.contains(fold);+ fold = fold.parentElement?.closest(FOLD_SELECTOR)+ ) {+ // A clipped body still shows its first lines; only text past the cutoff is folded.+ if (+ fold.hasAttribute("hidden") ||+ range.getBoundingClientRect().bottom > fold.getBoundingClientRect().bottom+ )+ folds.push(fold);+ }+ return folds;+}++/** Dispatches `beforematch` on each fold hiding the range; returns whether any existed. */+function revealFolded(range: Range, container: HTMLElement): boolean {+ const folds = foldsHiding(range, container);+ for (const fold of folds) fold.dispatchEvent(new Event("beforematch"));+ return folds.length > 0;+}++function affectsSearchableText(record: MutationRecord): boolean {+ if (record.type === "attributes") return true;+ const target =+ record.target.nodeType === 1 ? (record.target as Element) : record.target.parentElement;+ if (target?.closest(THREAD_FIND_TEXT_SELECTOR)) return true;+ // Rows mounting or unmounting add or remove whole searchable scopes.+ const touchesScope = (node: Node) =>+ node.nodeType === 1 &&+ ((node as Element).matches(THREAD_FIND_TEXT_SELECTOR) ||+ (node as Element).querySelector(THREAD_FIND_TEXT_SELECTOR) !== null);+ return [...record.addedNodes, ...record.removedNodes].some(touchesScope);+}++export function useThreadFindHighlights(input: {+ readonly container: HTMLElement | null;+ readonly query: string;+ readonly activeRowId: string | null;+ readonly activeOccurrence: number;+ readonly onActiveRange: (range: Range | null) => void;+}): void {+ const { container, query, activeRowId, activeOccurrence, onActiveRange } = input;++ const rangesRef = useRef<readonly ThreadFindRange[]>([]);+ const paintRef = useRef<ReturnType<typeof makeThreadFindHighlightPainter> | null>(null);+ const selectionRef = useRef({ activeRowId, activeOccurrence, onActiveRange });+ useLayoutEffect(() => {+ selectionRef.current = { activeRowId, activeOccurrence, onActiveRange };+ }, [activeRowId, activeOccurrence, onActiveRange]);++ useEffect(() => {+ if (typeof CSS === "undefined" || !CSS.highlights || typeof Highlight === "undefined") {+ selectionRef.current.onActiveRange(null);+ return;+ }+ const clearHighlights = () => {+ CSS.highlights.delete(THREAD_FIND_HIGHLIGHT_NAME);+ CSS.highlights.delete(THREAD_FIND_ACTIVE_HIGHLIGHT_NAME);+ };+ rangesRef.current = [];+ if (!container || query.length === 0) {+ selectionRef.current.onActiveRange(null);+ clearHighlights();+ return;+ }++ // Selection changes reuse ranges. Only changed or newly mounted rows+ // need their text walked again; removed rows release their DOM references.+ const cache = new Map<Element, readonly ThreadFindRange[]>();+ const paint = makeThreadFindHighlightPainter(container);+ paintRef.current = paint;+ const repaint = () => {+ const rows = new Set(container.querySelectorAll("[data-timeline-row-id]"));+ const ranges: ThreadFindRange[] = [];+ for (const row of rows) {+ let matches = cache.get(row);+ if (+ !matches ||+ matches.some(+ ({ range }) => !row.contains(range.startContainer) || !row.contains(range.endContainer),+ )+ ) {+ matches = collectThreadFindRanges(row as HTMLElement, query);+ cache.set(row, matches);+ }+ ranges.push(...matches);+ }+ for (const row of cache.keys()) if (!rows.has(row)) cache.delete(row);+ rangesRef.current = ranges;+ paint(ranges, selectionRef.current);+ };+ let frame: number | null = null;+ const observer = new MutationObserver((mutations) => {+ // Timers and status chrome tick every second; only searchable text and folds matter.+ const relevant = mutations.filter(affectsSearchableText);+ if (relevant.length === 0) return;+ for (const mutation of relevant) {+ const target =+ mutation.target.nodeType === 1+ ? (mutation.target as Element)+ : mutation.target.parentElement;+ const row = target?.closest("[data-timeline-row-id]");+ if (row) cache.delete(row);+ }+ if (frame !== null) return;+ frame = requestAnimationFrame(() => {+ frame = null;+ repaint();+ });+ });+ observer.observe(container, {+ subtree: true,+ childList: true,+ characterData: true,+ attributes: true,+ attributeFilter: [+ "data-wrap",+ "hidden",+ "data-thread-find-fold",+ "data-timeline-row-id",+ "data-thread-find-text",+ "data-thread-find-ignore",+ ],+ });+ // Revealing the first match can synchronously mount or recycle list rows.+ repaint();+ return () => {+ observer.disconnect();+ if (frame !== null) cancelAnimationFrame(frame);+ cache.clear();+ paintRef.current = null;+ rangesRef.current = [];+ clearHighlights();+ };+ }, [container, query]);++ useEffect(() => {+ paintRef.current?.(rangesRef.current, { activeRowId, activeOccurrence, onActiveRange });+ }, [activeOccurrence, activeRowId, onActiveRange]);+}++/** Selection changes touch only the old and new match; layout checks run once per DOM scan. */+function makeThreadFindHighlightPainter(container: HTMLElement) {+ let previousRanges: readonly ThreadFindRange[] | null = null;+ const rangesByRow = new Map<string, Range[]>();+ const inactive = new Highlight();+ const active = new Highlight();+ let previousActive: Range | null = null;+ CSS.highlights.set(THREAD_FIND_HIGHLIGHT_NAME, inactive);+ CSS.highlights.set(THREAD_FIND_ACTIVE_HIGHLIGHT_NAME, active);+ return (+ ranges: readonly ThreadFindRange[],+ selection: Pick<+ Parameters<typeof useThreadFindHighlights>[0],+ "activeRowId" | "activeOccurrence" | "onActiveRange"+ >,+ ) => {+ if (previousRanges !== ranges) {+ previousRanges = ranges;+ previousActive = null;+ rangesByRow.clear();+ inactive.clear();+ for (const match of ranges) {+ const row = rangesByRow.get(match.rowId) ?? [];+ row[match.occurrence] = match.range;+ rangesByRow.set(match.rowId, row);+ if (foldsHiding(match.range, container).length === 0) inactive.add(match.range);+ }+ }+ if (previousActive && foldsHiding(previousActive, container).length === 0)+ inactive.add(previousActive);+ const selected =+ selection.activeRowId === null+ ? null+ : (rangesByRow.get(selection.activeRowId)?.[selection.activeOccurrence] ?? null);+ active.clear();+ if (selected) inactive.delete(selected);+ previousActive = selected;+ if (selected && revealFolded(selected, container)) {+ selection.onActiveRange(null);+ } else {+ if (selected) active.add(selected);+ selection.onActiveRange(selected);+ }+ };+}diff --git a/apps/web/src/components/chat/threadFindPosition.test.ts b/apps/web/src/components/chat/threadFindPosition.test.tsnew file mode 100644index 00000000000..a1867e547a6--- /dev/null+++ b/apps/web/src/components/chat/threadFindPosition.test.ts@@ -0,0 +1,60 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { readThreadFindPosition } from "./threadFindPosition";++afterEach(() => vi.restoreAllMocks());+beforeEach(() => {+ Object.defineProperty(Range.prototype, "getBoundingClientRect", {+ configurable: true,+ writable: true,+ value: () => new DOMRect(),+ });+});++function viewport(text = "COD4 COD4") {+ const container = document.createElement("div");+ container.innerHTML = `<div data-timeline-row-id="above"><div data-thread-find-text>COD4</div></div>+ <div data-timeline-row-id="reading"><div data-thread-find-text>${text}</div></div>`;+ vi.spyOn(container, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 100, 500, 400));+ vi.spyOn(container.children[0]!, "getBoundingClientRect").mockReturnValue(+ new DOMRect(0, 0, 500, 80),+ );+ vi.spyOn(container.children[1]!, "getBoundingClientRect").mockReturnValue(+ new DOMRect(0, 50, 500, 300),+ );+ return container;+}++describe("reading position for find", () => {+ it("skips earlier rows and occurrences above the viewport within the current message", () => {+ const container = viewport();+ vi.spyOn(Range.prototype, "getBoundingClientRect").mockImplementation(function (this: Range) {+ return new DOMRect(0, this.startOffset === 0 ? 60 : 160, 40, 20);+ });+ expect(readThreadFindPosition(container, "COD4", (id) => id, 100)).toEqual({+ entryId: "reading",+ occurrence: 1,+ });+ });++ it("starts after the current message when all its occurrences are above the viewport", () => {+ const container = viewport();+ vi.spyOn(Range.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 60, 40, 20));+ expect(readThreadFindPosition(container, "COD4", (id) => id, 100)).toEqual({+ entryId: "reading",+ occurrence: 2,+ });+ });++ it("anchors unmatched or folded content and excludes rows hidden behind the composer", () => {+ const container = viewport("nothing");+ expect(readThreadFindPosition(container, "COD4", () => "folded-message", 100)).toEqual({+ entryId: "folded-message",+ occurrence: 0,+ });+ vi.spyOn(container.children[1]!, "getBoundingClientRect").mockReturnValue(+ new DOMRect(0, 420, 500, 300),+ );+ expect(readThreadFindPosition(container, "COD4", (id) => id, 100)).toBeUndefined();+ });+});diff --git a/apps/web/src/components/chat/threadFindPosition.ts b/apps/web/src/components/chat/threadFindPosition.tsnew file mode 100644index 00000000000..d67f3604921--- /dev/null+++ b/apps/web/src/components/chat/threadFindPosition.ts@@ -0,0 +1,24 @@+import type { ThreadFindStart } from "./threadFind";+import { collectThreadFindRanges } from "./threadFindHighlights";++/** Anchor to the first row being read, skipping occurrences above its viewport. */+export function readThreadFindPosition(+ container: HTMLElement,+ query: string,+ resolveEntry: (rowId: string) => string | undefined,+ contentInsetEndAdjustment: number,+): ThreadFindStart | undefined {+ const viewport = container.getBoundingClientRect();+ for (const row of container.querySelectorAll<HTMLElement>("[data-timeline-row-id]")) {+ const rect = row.getBoundingClientRect();+ if (rect.bottom <= viewport.top || rect.top >= viewport.bottom - contentInsetEndAdjustment)+ continue;+ const rowId = row.dataset.timelineRowId;+ const entryId = rowId ? resolveEntry(rowId) : undefined;+ if (!entryId) continue;+ const matches = collectThreadFindRanges(row, query);+ const next = matches.find((match) => match.range.getBoundingClientRect().bottom > viewport.top);+ return { entryId, occurrence: next?.occurrence ?? matches.length };+ }+ return undefined;+}diff --git a/apps/web/src/components/chat/useThreadFind.test.tsx b/apps/web/src/components/chat/useThreadFind.test.tsxnew file mode 100644index 00000000000..2c87b9ebf3f--- /dev/null+++ b/apps/web/src/components/chat/useThreadFind.test.tsx@@ -0,0 +1,720 @@+import { act, useLayoutEffect } from "react";+import { create, type ReactTestRenderer } from "react-test-renderer";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import {+ EnvironmentId,+ RunId,+ ThreadId,+ type OrchestrationV2SearchThreadInput,+ type OrchestrationV2SearchThreadResult,+} from "@t3tools/contracts";+import { useThreadFind } from "./useThreadFind";+import { orchestrationEnvironment } from "~/state/orchestration";+import { requestThreadFindOpen } from "./threadFindActionBus";++const queries = vi.hoisted(() => ({+ results: new Map<string, OrchestrationV2SearchThreadResult>(),+ pending: false,+ refresh: vi.fn(),+}));+vi.mock("~/state/orchestration", () => ({+ orchestrationEnvironment: {+ threadFindProgressive: vi.fn(+ (input: { environmentId: EnvironmentId; input: OrchestrationV2SearchThreadInput }) => input,+ ),+ threadFind: vi.fn(+ (input: { environmentId: EnvironmentId; input: OrchestrationV2SearchThreadInput }) => input,+ ),+ },+}));+vi.mock("~/state/queries", () => ({ useDebouncedValue: <T,>(value: T) => value }));+vi.mock("~/state/query", () => ({+ useEnvironmentQuery: (atom: { environmentId: EnvironmentId } | null) => ({+ data: atom === null ? null : (queries.results.get(atom.environmentId) ?? null),+ isPending: queries.pending,+ error: null,+ refresh: queries.refresh,+ }),+}));++vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));++let renderer: ReactTestRenderer | undefined;+let find: ReturnType<typeof useThreadFind>;+const a = EnvironmentId.make("environment:a");+const b = EnvironmentId.make("environment:b");+const threadId = ThreadId.make("shared-thread");+const runId = RunId.make("run:plan");+function Probe({+ environmentId,+ enabled = true,+ progressive = false,+ content,+}: {+ environmentId: EnvironmentId;+ enabled?: boolean;+ progressive?: boolean;+ content?: Parameters<typeof useThreadFind>[0]["content"];+}) {+ const state = useThreadFind({+ thread: { environmentId, threadId },+ enabled,+ progressive,+ content,+ });+ useLayoutEffect(() => {+ find = state;+ });+ return null;+}+beforeEach(() => {+ vi.stubGlobal("window", new EventTarget());+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+});+afterEach(async () => {+ if (renderer) await act(async () => renderer?.unmount());+ renderer = undefined;+ queries.results.clear();+ queries.pending = false;+ vi.clearAllMocks();+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe("V2 find state", () => {+ function messageResult(index: number, snapshotSequence = 9): OrchestrationV2SearchThreadResult {+ return {+ snapshotSequence,+ totalMatches: 10,+ activeIndex: index,+ match: { entryId: `message:${index + 2}`, runId, occurrence: 0 },+ };+ }++ it("reveals an early match and updates its count without requesting another jump", async () => {+ await act(async () => {+ renderer = create(<Probe environmentId={a} progressive />);+ });+ await act(async () => find.open());+ await act(async () => find.barProps.onQueryChange("needle"));+ const partial: OrchestrationV2SearchThreadResult = {+ complete: false,+ snapshotSequence: 9,+ totalMatches: 1,+ activeIndex: 0,+ match: { entryId: "early", runId, occurrence: 2 },+ };+ queries.pending = true;+ queries.results.set(a, partial);+ await act(async () => renderer?.update(<Probe environmentId={a} progressive />));+ expect(find.barProps.counting).toBe(true);+ expect(find.barProps.status).toBeNull();+ expect(find.timelineProps.activeFindMatch).toEqual(partial.match);+ const match = find.timelineProps.activeFindMatch;+ const navigationId = find.timelineProps.findNavigationId;+ const requests = vi.mocked(orchestrationEnvironment.threadFindProgressive).mock.calls.length;+ await act(async () => {+ find.barProps.onNext();+ find.barProps.onPrevious();+ });+ expect(orchestrationEnvironment.threadFindProgressive).toHaveBeenCalledTimes(requests);+ queries.results.set(a, { ...partial, complete: true, totalMatches: 123, activeIndex: 42 });+ await act(async () => renderer?.update(<Probe environmentId={a} progressive />));+ expect(find.barProps.counting).toBe(false);+ expect(find.barProps.matchCount).toBe(123);+ expect(find.barProps.activeIndex).toBe(42);+ expect(find.timelineProps.activeFindMatch).toBe(match);+ expect(find.timelineProps.findNavigationId).toBe(navigationId);+ expect(orchestrationEnvironment.threadFind).not.toHaveBeenCalled();+ queries.pending = false;+ await act(async () => renderer?.update(<Probe environmentId={a} progressive />));+ await act(async () => find.barProps.onNext());+ expect(orchestrationEnvironment.threadFindProgressive).toHaveBeenCalledTimes(requests + 1);+ });++ it("coalesces incoming pages until the progressive scan finishes", async () => {+ vi.useFakeTimers();+ queries.pending = true;+ await act(async () => {+ renderer = create(<Probe environmentId={a} progressive />);+ });+ await act(async () => find.open());+ await act(async () => find.barProps.onQueryChange("needle"));+ queries.results.set(a, { ...messageResult(0), complete: false, totalMatches: 1 });+ const content = { visibleTurnItems: [], runs: [] };+ await act(async () =>+ renderer?.update(<Probe environmentId={a} progressive content={content} />),+ );+ const requests = vi.mocked(orchestrationEnvironment.threadFindProgressive).mock.calls.length;+ await act(async () => vi.advanceTimersByTime(300));+ expect(orchestrationEnvironment.threadFindProgressive).toHaveBeenCalledTimes(requests);+ expect(queries.refresh).not.toHaveBeenCalled();+ queries.results.set(a, messageResult(0));+ queries.pending = false;+ await act(async () =>+ renderer?.update(<Probe environmentId={a} progressive content={content} />),+ );+ expect(orchestrationEnvironment.threadFindProgressive).toHaveBeenCalledTimes(requests + 1);+ expect(orchestrationEnvironment.threadFindProgressive).toHaveBeenLastCalledWith({+ environmentId: a,+ input: {+ threadId,+ query: "needle",+ skills: [],+ start: { entryId: "message:2", occurrence: 0 },+ },+ });+ expect(find.timelineProps.activeFindMatch?.entryId).toBe("message:2");+ });++ it("requests a fresh jump when the same search wraps to the same match from a new position", async () => {+ queries.results.set(a, messageResult(0));+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ find.timelineProps.findPositionReaderRef.current = () => ({+ entryId: "reading",+ occurrence: 0,+ });+ await act(async () => find.barProps.onQueryChange("COD4"));+ const firstNavigationId = find.timelineProps.findNavigationId;+ const firstMatch = find.timelineProps.activeFindMatch;+ find.timelineProps.findPositionReaderRef.current = () => ({ entryId: "bottom", occurrence: 0 });+ await act(async () => find.barProps.onQueryChange("COD4"));+ expect(find.timelineProps.findNavigationId).toBeGreaterThan(firstNavigationId);+ expect(find.timelineProps.activeFindMatch).toEqual(firstMatch);+ expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({+ environmentId: a,+ input: { threadId, query: "COD4", skills: [], start: { entryId: "bottom", occurrence: 0 } },+ });+ const repeatedNavigationId = find.timelineProps.findNavigationId;+ find.timelineProps.findPositionReaderRef.current = () => ({+ entryId: "new-bottom",+ occurrence: 0,+ });+ await act(async () => requestThreadFindOpen());+ expect(find.timelineProps.findNavigationId).toBeGreaterThan(repeatedNavigationId);+ expect(find.timelineProps.activeFindMatch).toEqual(firstMatch);+ expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({+ environmentId: a,+ input: {+ threadId,+ query: "COD4",+ skills: [],+ start: { entryId: "new-bottom", occurrence: 0 },+ },+ });+ });++ it("cycles cached entries immediately, wraps, and accumulates clicks in one event", async () => {+ const initial = {+ ...messageResult(0),+ totalMatches: 5,+ match: { entryId: "first", runId, occurrence: 0 },+ navigation: [+ { entryId: "first", runId, startIndex: 0, count: 3 },+ { entryId: "second", runId, startIndex: 3, count: 2 },+ ],+ };+ queries.results.set(a, initial);+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ await act(async () => find.barProps.onQueryChange("COD4"));+ const requests = vi.mocked(orchestrationEnvironment.threadFind).mock.calls.length;+ await act(async () => {+ find.barProps.onNext();+ find.barProps.onNext();+ });+ expect(find.barProps.activeIndex).toBe(2);+ expect(find.timelineProps.activeFindMatch).toEqual({ entryId: "first", runId, occurrence: 2 });+ expect(find.timelineProps.findNavigationId).toBe(3);+ await act(async () => find.barProps.onNext());+ expect(find.timelineProps.activeFindMatch).toEqual({ entryId: "second", runId, occurrence: 0 });+ await act(async () => {+ find.barProps.onNext();+ find.barProps.onNext();+ });+ expect(find.barProps.activeIndex).toBe(0);+ await act(async () => find.barProps.onPrevious());+ expect(find.barProps.activeIndex).toBe(4);+ expect(find.timelineProps.activeFindMatch).toEqual({ entryId: "second", runId, occurrence: 1 });+ expect(orchestrationEnvironment.threadFind).toHaveBeenCalledTimes(requests);+ expect(queries.refresh).not.toHaveBeenCalled();+ });++ it("does not let an older background response undo a cached step", async () => {+ const initial = {+ ...messageResult(0),+ match: { entryId: "first", runId, occurrence: 0 },+ navigation: [{ entryId: "first", runId, startIndex: 0, count: 3 }],+ };+ queries.results.set(a, initial);+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ await act(async () => find.barProps.onQueryChange("COD4"));+ const requests = vi.mocked(orchestrationEnvironment.threadFind).mock.calls.length;+ await act(async () => find.barProps.onNext());+ queries.results.set(a, {+ ...initial,+ snapshotSequence: 10,+ totalMatches: 11,+ activeIndex: 1,+ navigation: [{ entryId: "first", runId, startIndex: 1, count: 3 }],+ });+ await act(async () => renderer?.update(<Probe environmentId={a} />));+ expect(find.timelineProps.activeFindMatch).toEqual({ entryId: "first", runId, occurrence: 1 });+ expect(find.barProps.activeIndex).toBe(2);+ expect(find.barProps.matchCount).toBe(11);+ expect(find.timelineProps.findNavigationId).toBe(2);+ await act(async () => find.barProps.onNext());+ expect(find.timelineProps.activeFindMatch?.occurrence).toBe(2);+ expect(find.barProps.activeIndex).toBe(3);+ expect(orchestrationEnvironment.threadFind).toHaveBeenCalledTimes(requests);+ });++ it("fetches the next window from the locally selected match and retains it while pending", async () => {+ const initial = {+ ...messageResult(0),+ match: { entryId: "first", runId, occurrence: 0 },+ navigation: [{ entryId: "first", runId, startIndex: 0, count: 2 }],+ };+ queries.results.set(a, initial);+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ await act(async () => find.barProps.onQueryChange("COD4"));+ await act(async () => find.barProps.onNext());+ expect(find.timelineProps.activeFindMatch?.occurrence).toBe(1);+ queries.pending = true;+ queries.results.delete(a);+ await act(async () => {+ find.barProps.onNext();+ find.barProps.onNext();+ });+ expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({+ environmentId: a,+ input: {+ threadId,+ query: "COD4",+ skills: [],+ start: { entryId: "first", occurrence: 1 },+ offset: 2,+ },+ });+ expect(find.barProps.activeIndex).toBe(1);+ expect(find.timelineProps.findNavigationId).toBe(2);+ queries.pending = false;+ queries.results.set(a, messageResult(3));+ await act(async () => renderer?.update(<Probe environmentId={a} />));+ expect(find.barProps.activeIndex).toBe(3);+ expect(find.timelineProps.findNavigationId).toBe(4);+ });++ it("refreshes around the cached selection when live matches are inserted before it", async () => {+ vi.useFakeTimers();+ const initial = {+ ...messageResult(0),+ match: { entryId: "first", runId, occurrence: 0 },+ navigation: [+ { entryId: "first", runId, startIndex: 0, count: 1 },+ { entryId: "second", runId, startIndex: 1, count: 1 },+ ],+ };+ queries.results.set(a, initial);+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ await act(async () => find.barProps.onQueryChange("COD4"));+ await act(async () => find.barProps.onNext());+ expect(find.timelineProps.activeFindMatch?.entryId).toBe("second");+ const content = { runs: [], visibleTurnItems: [] };+ await act(async () => renderer?.update(<Probe environmentId={a} content={content} />));+ await act(async () => vi.advanceTimersByTime(300));+ expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({+ environmentId: a,+ input: { threadId, query: "COD4", skills: [], start: { entryId: "second", occurrence: 0 } },+ });+ queries.results.set(a, {+ ...initial,+ snapshotSequence: 10,+ totalMatches: 11,+ activeIndex: 2,+ match: { entryId: "second", runId, occurrence: 0 },+ navigation: [+ { entryId: "inserted", runId, startIndex: 1, count: 1 },+ { entryId: "second", runId, startIndex: 2, count: 1 },+ ],+ });+ await act(async () => renderer?.update(<Probe environmentId={a} content={content} />));+ expect(find.barProps.matchCount).toBe(11);+ expect(find.barProps.activeIndex).toBe(2);+ expect(find.timelineProps.activeFindMatch?.entryId).toBe("second");+ expect(find.timelineProps.findNavigationId).toBe(2);+ await act(async () => find.barProps.onPrevious());+ expect(find.timelineProps.activeFindMatch?.entryId).toBe("inserted");+ });++ it("asks the server rather than using stale navigation counts during live updates", async () => {+ const initial = {+ ...messageResult(0),+ navigation: [{ entryId: "message:2", runId, startIndex: 0, count: 10 }],+ };+ queries.results.set(a, initial);+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ await act(async () => find.barProps.onQueryChange("COD4"));+ await act(async () =>+ renderer?.update(<Probe environmentId={a} content={{ runs: [], visibleTurnItems: [] }} />),+ );+ await act(async () => find.barProps.onNext());+ expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({+ environmentId: a,+ input: {+ threadId,+ query: "COD4",+ skills: [],+ start: { entryId: "message:2", occurrence: 0 },+ offset: 1,+ },+ });+ });++ it("starts from the viewport and steps from the server-selected match", async () => {+ queries.results.set(a, messageResult(4));+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ find.timelineProps.findPositionReaderRef.current = () => ({+ entryId: "message:6",+ occurrence: 1,+ });+ await act(async () => find.barProps.onQueryChange("COD4"));+ expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({+ environmentId: a,+ input: {+ threadId,+ query: "COD4",+ skills: [],+ start: { entryId: "message:6", occurrence: 1 },+ },+ });+ expect(find.barProps.activeIndex).toBe(4);+ queries.results.set(a, messageResult(5));+ await act(async () => find.barProps.onNext());+ expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({+ environmentId: a,+ input: {+ threadId,+ query: "COD4",+ skills: [],+ start: { entryId: "message:6", occurrence: 0 },+ offset: 1,+ },+ });+ expect(find.timelineProps.activeFindMatch?.entryId).toBe("message:7");+ queries.results.set(a, messageResult(4));+ await act(async () => find.barProps.onPrevious());+ expect(find.barProps.activeIndex).toBe(4);+ expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({+ environmentId: a,+ input: {+ threadId,+ query: "COD4",+ skills: [],+ start: { entryId: "message:7", occurrence: 0 },+ offset: -1,+ },+ });+ });++ it("accumulates rapid navigation against the same match until the response arrives", async () => {+ queries.results.set(a, messageResult(4));+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ await act(async () => find.barProps.onQueryChange("COD4"));+ queries.pending = true;+ queries.results.delete(a);+ await act(async () => find.barProps.onNext());+ await act(async () => find.barProps.onNext());+ expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({+ environmentId: a,+ input: {+ threadId,+ query: "COD4",+ skills: [],+ start: { entryId: "message:6", occurrence: 0 },+ offset: 2,+ },+ });+ expect(find.timelineProps.findNavigationId).toBe(1);+ queries.pending = false;+ queries.results.set(a, messageResult(6));+ await act(async () => renderer?.update(<Probe environmentId={a} />));+ expect(find.timelineProps.findNavigationId).toBe(3);+ expect(find.barProps.activeIndex).toBe(6);+ });++ it("refreshes continuous updates without shifting the current match or showing Searching", async () => {+ vi.useFakeTimers();+ queries.results.set(a, messageResult(4));+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ await act(async () => find.barProps.onQueryChange("COD4"));+ for (let i = 0; i < 3; i++) {+ await act(async () =>+ renderer?.update(<Probe environmentId={a} content={{ visibleTurnItems: [], runs: [] }} />),+ );+ await act(async () => vi.advanceTimersByTime(100));+ }+ expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({+ environmentId: a,+ input: {+ threadId,+ query: "COD4",+ skills: [],+ start: { entryId: "message:6", occurrence: 0 },+ },+ });+ const updated = { ...messageResult(5, 10), totalMatches: 11, match: messageResult(4).match };+ queries.results.set(a, updated);+ await act(async () => renderer?.update(<Probe environmentId={a} />));+ expect(find.barProps.matchCount).toBe(11);+ expect(find.barProps.activeIndex).toBe(5);+ expect(find.timelineProps.activeFindMatch?.entryId).toBe("message:6");+ expect(find.timelineProps.findNavigationId).toBe(1);+ expect(find.barProps.status).toBeNull();+ await act(async () => find.barProps.onNext());+ expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({+ environmentId: a,+ input: {+ threadId,+ query: "COD4",+ skills: [],+ start: { entryId: "message:6", occurrence: 0 },+ offset: 1,+ },+ });+ });++ it("keeps pending navigation when incoming content triggers a refresh", async () => {+ vi.useFakeTimers();+ queries.results.set(a, messageResult(4));+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ await act(async () => find.barProps.onQueryChange("COD4"));+ queries.pending = true;+ queries.results.delete(a);+ await act(async () => find.barProps.onNext());+ await act(async () =>+ renderer?.update(<Probe environmentId={a} content={{ visibleTurnItems: [], runs: [] }} />),+ );+ await act(async () => vi.advanceTimersByTime(300));+ expect(queries.refresh).toHaveBeenCalledTimes(1);+ expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({+ environmentId: a,+ input: {+ threadId,+ query: "COD4",+ skills: [],+ start: { entryId: "message:6", occurrence: 0 },+ offset: 1,+ },+ });+ queries.pending = false;+ queries.results.set(a, { ...messageResult(6, 10), totalMatches: 11 });+ await act(async () => renderer?.update(<Probe environmentId={a} />));+ expect(find.timelineProps.activeFindMatch?.entryId).toBe("message:8");+ expect(find.timelineProps.findNavigationId).toBe(2);+ expect(find.barProps.matchCount).toBe(11);+ });++ it("does not navigate the previous result while a new match is loading", async () => {+ queries.results.set(a, messageResult(0));+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ await act(async () => find.barProps.onQueryChange("COD4"));+ queries.pending = true;+ queries.results.delete(a);+ await act(async () => find.barProps.onNext());+ expect(find.timelineProps.activeFindMatch?.entryId).toBe("message:2");+ expect(find.timelineProps.findNavigationId).toBe(1);+ expect(find.barProps.status).toBeNull();+ expect(find.barProps.activeIndex).toBe(0);+ expect(find.barProps.matchCount).toBe(10);+ queries.pending = false;+ queries.results.set(a, messageResult(1));+ await act(async () => renderer?.update(<Probe environmentId={a} />));+ expect(find.timelineProps.activeFindMatch?.entryId).toBe("message:3");+ expect(find.timelineProps.findNavigationId).toBe(2);+ });++ it("keeps the reading-position start when Enter is pressed before results arrive", async () => {+ queries.pending = true;+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ find.timelineProps.findPositionReaderRef.current = () => ({+ entryId: "message:6",+ occurrence: 1,+ });+ await act(async () => find.barProps.onQueryChange("COD4"));+ await act(async () => find.barProps.onNext());+ expect(orchestrationEnvironment.threadFind).toHaveBeenLastCalledWith({+ environmentId: a,+ input: {+ threadId,+ query: "COD4",+ skills: [],+ start: { entryId: "message:6", occurrence: 1 },+ },+ });+ });++ it("shows Searching only when the query has no result yet", async () => {+ queries.pending = true;+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ await act(async () => find.barProps.onQueryChange("COD4"));+ expect(find.barProps.status).toBe("loading");+ queries.pending = false;+ queries.results.set(a, messageResult(0));+ await act(async () => renderer?.update(<Probe environmentId={a} />));+ expect(find.barProps.status).toBeNull();+ queries.pending = true;+ queries.results.delete(a);+ await act(async () => find.barProps.onQueryChange("different query"));+ expect(find.barProps.status).toBe("loading");+ expect(find.barProps.matchCount).toBe(0);+ // Folded content stays expanded while the new query loads.+ expect(find.timelineProps.findQuery).toBe("");+ expect(find.timelineProps.findExpanded).toBe(true);+ await act(async () => find.barProps.onQueryChange(""));+ expect(find.timelineProps.findExpanded).toBe(false);+ });++ it("keeps search unavailable when the server does not support it", async () => {+ await act(async () => {+ renderer = create(<Probe environmentId={a} enabled={false} />);+ });+ await act(async () => {+ find.open();+ requestThreadFindOpen();+ });+ expect(find.isOpen).toBe(false);+ expect(find.timelineProps.activeFindMatch).toBeNull();+ expect(orchestrationEnvironment.threadFind).not.toHaveBeenCalled();+ });++ it("closes search when support disappears without restoring stale queries", async () => {+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => find.open());+ await act(async () => find.barProps.onQueryChange("needle"));+ expect(find.isOpen).toBe(true);+ vi.mocked(orchestrationEnvironment.threadFind).mockClear();+ await act(async () => {+ renderer?.update(<Probe environmentId={a} enabled={false} />);+ });+ expect(find.isOpen).toBe(false);+ expect(find.timelineProps.activeFindMatch).toBeNull();+ expect(find.timelineProps.findQuery).toBe("");+ expect(orchestrationEnvironment.threadFind).not.toHaveBeenCalled();+ await act(async () => {+ renderer?.update(<Probe environmentId={a} />);+ });+ expect(find.isOpen).toBe(false);+ await act(async () => find.open());+ expect(find.barProps.query).toBe("");+ });++ it("preserves plan item ID and run ownership for navigation", async () => {+ queries.results.set(a, {+ snapshotSequence: 9,+ totalMatches: 1,+ activeIndex: 0,+ match: { entryId: "plan-item", runId, occurrence: 0 },+ });+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => {+ find.open();+ });+ await act(async () => {+ find.barProps.onQueryChange("needle");+ });+ expect(find.timelineProps.activeFindMatch).toEqual({+ entryId: "plan-item",+ runId,+ occurrence: 0,+ });+ await act(async () => {+ find.close();+ });+ expect(find.timelineProps.activeFindMatch).toBeNull();+ expect(find.timelineProps.findQuery).toBe("");+ });++ it("drops results on environment changes even when the thread IDs are identical", async () => {+ queries.results.set(a, {+ snapshotSequence: 1,+ totalMatches: 3,+ activeIndex: 0,+ match: null,+ });+ queries.results.set(b, {+ snapshotSequence: 2,+ totalMatches: 0,+ activeIndex: 0,+ match: null,+ });+ await act(async () => {+ renderer = create(<Probe environmentId={a} />);+ });+ await act(async () => {+ find.open();+ });+ await act(async () => {+ find.barProps.onQueryChange("needle");+ });+ expect(find.barProps.matchCount).toBe(3);+ await act(async () => {+ renderer?.update(<Probe environmentId={b} />);+ });+ expect(find.isOpen).toBe(false);+ expect(find.timelineProps.activeFindMatch).toBeNull();+ await act(async () => {+ find.open();+ });+ await act(async () => {+ find.barProps.onQueryChange("needle");+ });+ expect(find.barProps.matchCount).toBe(0);+ await act(async () => {+ renderer?.update(<Probe environmentId={a} />);+ });+ expect(find.isOpen).toBe(false);+ });+});diff --git a/apps/web/src/components/chat/useThreadFind.ts b/apps/web/src/components/chat/useThreadFind.tsnew file mode 100644index 00000000000..08be0f16b24--- /dev/null+++ b/apps/web/src/components/chat/useThreadFind.ts@@ -0,0 +1,386 @@+import type { InlineSkill } from "@t3tools/shared/inlineSkills";+import type {+ OrchestrationV2ThreadProjection,+ OrchestrationV2SearchThreadResult,+ ScopedThreadRef,+} from "@t3tools/contracts";+import { scopedThreadKey } from "@t3tools/client-runtime/environment";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { orchestrationEnvironment } from "~/state/orchestration";+import { useEnvironmentQuery } from "~/state/query";+import { useDebouncedValue } from "~/state/queries";+import {+ type ThreadFindPositionReader,+ type ThreadFindStart,+ stepThreadFindIndex,+} from "./threadFind";+import { subscribeThreadFindOpen } from "./threadFindActionBus";+import { toastManager } from "../ui/toast";++const EMPTY_SKILLS: readonly InlineSkill[] = [];++const CLOSED_FIND = {+ threadKey: null as string | null,+ query: "",+ offset: 0,+ start: undefined as ThreadFindStart | undefined,+ focusRequestId: 0,+ navigationId: 0,+ requestId: 0,+ localSelection: null as {+ base: OrchestrationV2SearchThreadResult;+ baseNavigationId: number;+ activeIndex: number;+ match: NonNullable<OrchestrationV2SearchThreadResult["match"]>;+ navigationId: number;+ } | null,+};++/** Owns find state for the active thread and its environment. */+export function useThreadFind({+ thread,+ enabled,+ progressive = false,+ skills = EMPTY_SKILLS,+ content,+}: {+ thread: ScopedThreadRef | null;+ enabled: boolean;+ progressive?: boolean;+ skills?: readonly InlineSkill[];+ content: Pick<OrchestrationV2ThreadProjection, "visibleTurnItems" | "runs"> | undefined;+}) {+ const findPositionReaderRef = useRef<ThreadFindPositionReader | null>(null);+ const lastContentRef = useRef(content);+ const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const refreshAfterSearchRef = useRef(false);+ const threadKey = thread ? scopedThreadKey(thread) : null;+ const [state, setState] = useState(CLOSED_FIND);+ if (state.threadKey !== null && (!enabled || state.threadKey !== threadKey))+ setState(CLOSED_FIND);+ const isOpen = enabled && threadKey !== null && state.threadKey === threadKey;+ const open = useCallback(() => {+ if (threadKey === null) return;+ if (!enabled) {+ toastManager.add({+ id: "thread-find-unavailable",+ title: "Thread search is unavailable on this server.",+ description: "Update the server to enable it.",+ });+ return;+ }+ const start =+ state.threadKey === threadKey && state.query.trim()+ ? findPositionReaderRef.current?.(state.query.trim())+ : undefined;+ setState((previous) => {+ const current = previous.threadKey === threadKey ? previous : CLOSED_FIND;+ return {+ ...current,+ threadKey,+ focusRequestId: previous.focusRequestId + 1,+ ...(current.query.trim()+ ? {+ start,+ offset: 0,+ localSelection: null,+ navigationId: current.navigationId + 1,+ requestId: current.navigationId + 1,+ }+ : {}),+ };+ });+ }, [enabled, state.query, state.threadKey, threadKey]);+ const close = useCallback(() => setState(CLOSED_FIND), []);+ useEffect(() => subscribeThreadFindOpen(open), [open]);++ const remote = useServerResults(+ isOpen ? thread : null,+ state.query,+ state.offset,+ state.requestId,+ state.start,+ skills,+ progressive,+ );+ const status: "loading" | "error" | null = remote.error+ ? "error"+ : remote.isPending && remote.data === null+ ? "loading"+ : null;+ const localSelection = rebaseLocalSelection(+ state.localSelection,+ remote.data,+ remote.navigationId,+ );+ const count = remote.data?.totalMatches ?? 0;+ const activeIndex = localSelection?.activeIndex ?? remote.data?.activeIndex ?? 0;+ const selectedMatch = localSelection?.match ?? remote.data?.match;+ const entryId = selectedMatch?.entryId;+ const runId = selectedMatch?.runId;+ const occurrence = selectedMatch?.occurrence;+ // Finishing the count must not rerender the timeline or request another jump.+ const match = useMemo(+ () =>+ entryId !== undefined && occurrence !== undefined+ ? { entryId, runId: runId ?? null, occurrence }+ : null,+ [entryId, runId, occurrence],+ );+ const counting = remote.data?.complete === false;+ const navigationId = localSelection?.navigationId ?? remote.navigationId;+ const step = (delta: number) => {+ if (count === 0 || counting) return;+ setState((previous) => {+ const local = rebaseLocalSelection(previous.localSelection, remote.data, remote.navigationId);+ const pending = previous.navigationId !== (local?.navigationId ?? remote.navigationId);+ const selected = local?.match ?? remote.data?.match;+ const nextIndex = stepThreadFindIndex(+ local?.activeIndex ?? remote.data?.activeIndex ?? 0,+ count,+ delta,+ );+ const entry = remote.data?.navigation?.find(+ (entry) => nextIndex >= entry.startIndex && nextIndex < entry.startIndex + entry.count,+ );+ const nextNavigationId = previous.navigationId + 1;+ if (+ !pending &&+ !remote.isPending &&+ entry &&+ remote.data &&+ (!local ||+ local.base === remote.data ||+ remote.data.navigation?.some(+ (entry) =>+ entry.entryId === local.match.entryId && local.match.occurrence < entry.count,+ )) &&+ refreshTimerRef.current === null &&+ lastContentRef.current === content+ ) {+ return {+ ...previous,+ navigationId: nextNavigationId,+ localSelection: {+ base: remote.data,+ baseNavigationId: remote.navigationId,+ activeIndex: nextIndex,+ match: {+ entryId: entry.entryId,+ runId: entry.runId,+ occurrence: nextIndex - entry.startIndex,+ },+ navigationId: nextNavigationId,+ },+ };+ }+ return {+ ...previous,+ start:+ pending || !selected+ ? previous.start+ : { entryId: selected.entryId, occurrence: selected.occurrence },+ offset: pending ? previous.offset + delta : delta,+ navigationId: nextNavigationId,+ requestId: nextNavigationId,+ };+ });+ };++ // Refresh at most once per 300 ms, even while tokens continue arriving.+ // An identity anchor keeps newly inserted matches from shifting the selection.+ const refreshLiveResultsRef = useRef(() => {});+ useLayoutEffect(() => {+ refreshLiveResultsRef.current = () => {+ if (!isOpen || !state.query.trim()) return;+ // Paging can change client content while the server is still counting.+ // Coalesce those updates instead of repeatedly restarting the scan.+ if (progressive && remote.isPending) {+ refreshAfterSearchRef.current = true;+ return;+ }+ if (!match || state.navigationId !== navigationId) {+ remote.refresh();+ return;+ }+ const start = { entryId: match.entryId, occurrence: match.occurrence };+ if (+ state.offset === 0 &&+ state.start?.entryId === start.entryId &&+ state.start.occurrence === start.occurrence &&+ state.requestId === state.navigationId+ ) {+ remote.refresh();+ } else {+ setState((previous) => ({+ ...previous,+ start,+ offset: 0,+ requestId: previous.navigationId,+ }));+ }+ };+ });+ useEffect(() => {+ if (!refreshAfterSearchRef.current || remote.isPending) return;+ refreshAfterSearchRef.current = false;+ if (!remote.error) refreshLiveResultsRef.current();+ }, [remote.isPending, remote.error]);+ useEffect(() => {+ if (lastContentRef.current === content) return;+ lastContentRef.current = content;+ if (!isOpen || !state.query.trim() || refreshTimerRef.current !== null) return;+ refreshTimerRef.current = setTimeout(() => {+ refreshTimerRef.current = null;+ refreshLiveResultsRef.current();+ }, 300);+ }, [content, isOpen, state.query]);+ useEffect(() => {+ if (!isOpen || threadKey === null || !state.query.trim()) return;+ return () => {+ if (refreshTimerRef.current !== null) clearTimeout(refreshTimerRef.current);+ refreshTimerRef.current = null;+ refreshAfterSearchRef.current = false;+ };+ }, [threadKey, isOpen, state.query]);++ const findExpanded = isOpen && state.query.trim().length > 0;+ const findQuery = isOpen && remote.data?.match ? state.query : "";+ const timelineProps = useMemo(+ () => ({+ findOpen: isOpen,+ // Keep folds open between keystrokes while the next result loads.+ findExpanded,+ findPositionReaderRef,+ findQuery,+ activeFindMatch: match,+ findNavigationId: navigationId,+ }),+ [isOpen, findExpanded, findQuery, match, navigationId],+ );++ return {+ isOpen,+ open,+ close,+ barProps: {+ open: isOpen,+ query: state.query,+ matchCount: count,+ counting,+ activeIndex,+ status,+ focusRequestId: state.focusRequestId,+ onRetry: remote.refresh,+ onQueryChange: (query: string) => {+ const start = findPositionReaderRef.current?.(query.trim());+ setState((previous) => ({+ ...previous,+ query,+ offset: 0,+ start,+ localSelection: null,+ navigationId: previous.navigationId + 1,+ requestId: previous.navigationId + 1,+ }));+ },+ onNext: () => step(1),+ onPrevious: () => step(-1),+ onClose: close,+ },+ timelineProps,+ };+}++/** A response for an older anchor can update counts without undoing newer local steps. */+function rebaseLocalSelection(+ selection: typeof CLOSED_FIND.localSelection,+ data: OrchestrationV2SearchThreadResult | null,+ navigationId: number,+) {+ if (!selection || !data) return null;+ if (selection.base === data && selection.baseNavigationId === navigationId) return selection;+ if (navigationId >= selection.navigationId) return null;+ const entry = data.navigation?.find((entry) => entry.entryId === selection.match.entryId);+ if (!entry || selection.match.occurrence >= entry.count) return selection;+ const activeIndex = entry.startIndex + selection.match.occurrence;+ return activeIndex === selection.activeIndex ? selection : { ...selection, activeIndex };+}++/** Query atoms cancel obsolete requests; navigation retains only the current query's result. */+function useServerResults(+ thread: ScopedThreadRef | null,+ query: string,+ offset: number,+ navigationId: number,+ start: ThreadFindStart | undefined,+ skills: readonly InlineSkill[],+ progressive: boolean,+) {+ const skillLabels = useMemo(+ () => skills.map(({ name, displayName }) => ({ name, displayName })),+ [skills],+ );+ const normalizedQuery = query.trim();+ const debouncedQuery = useDebouncedValue(normalizedQuery, 100);+ const environmentId = thread?.environmentId;+ const threadId = thread?.threadId;+ const atom = useMemo(+ () =>+ environmentId && threadId && debouncedQuery && normalizedQuery === debouncedQuery+ ? (progressive+ ? orchestrationEnvironment.threadFindProgressive+ : orchestrationEnvironment.threadFind)({+ environmentId,+ input: {+ threadId,+ query: debouncedQuery,+ ...(start ? { start } : {}),+ ...(offset !== 0 ? { offset } : {}),+ skills: skillLabels,+ },+ })+ : null,+ [+ environmentId,+ threadId,+ debouncedQuery,+ normalizedQuery,+ start,+ offset,+ skillLabels,+ progressive,+ ],+ );+ const result = useEnvironmentQuery(atom);+ const key = thread+ ? JSON.stringify([thread.environmentId, thread.threadId, normalizedQuery, skillLabels])+ : null;+ const [previous, setPrevious] = useState({+ key,+ data: result.data,+ navigationId,+ });+ if (+ previous.key !== key ||+ (result.data !== null &&+ (!result.isPending || (progressive && previous.data !== result.data)) &&+ (previous.data !== result.data || previous.navigationId !== navigationId))+ ) {+ const response = result.data;+ setPrevious({+ key,+ data: response,+ navigationId,+ });+ }+ return {+ ...result,+ data: key === previous.key && !result.error ? previous.data : null,+ navigationId: previous.navigationId,+ isPending:+ thread !== null &&+ normalizedQuery.length > 0 &&+ (normalizedQuery !== debouncedQuery || result.isPending),+ };+}diff --git a/apps/web/src/components/chat/useThreadFindNavigation.test.tsx b/apps/web/src/components/chat/useThreadFindNavigation.test.tsxnew file mode 100644index 00000000000..7f717bdfcb9--- /dev/null+++ b/apps/web/src/components/chat/useThreadFindNavigation.test.tsx@@ -0,0 +1,393 @@+// @vitest-environment jsdom++import type { LegendListRef } from "@legendapp/list/react";+import { act, type ComponentProps } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { useThreadFindNavigation } from "./useThreadFindNavigation";++const renders = vi.fn();+function Probe(props: Parameters<typeof useThreadFindNavigation>[0]) {+ renders();+ useThreadFindNavigation(props);+ return null;+}++let root: Root;+let host: HTMLDivElement;+let container: HTMLDivElement;+let rect: DOMRect;+const scrollToIndex = vi.fn<LegendListRef["scrollToIndex"]>();+const scrollToOffset = vi.fn<LegendListRef["scrollToOffset"]>();+let props: ComponentProps<typeof Probe>;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.stubGlobal("CSS", { highlights: new Map() });+ vi.stubGlobal(+ "Highlight",+ class extends Set<Range> {+ constructor(...ranges: Range[]) {+ super(ranges);+ }+ },+ );+ rect = new DOMRect(0, 200, 40, 20);+ Object.defineProperty(Range.prototype, "getBoundingClientRect", {+ configurable: true,+ value: () => rect,+ });+ host = document.createElement("div");+ container = document.createElement("div");+ container.innerHTML =+ '<div data-timeline-row-id="message"><p data-thread-find-text>COD4 and COD4</p></div>';+ container.getBoundingClientRect = () => new DOMRect(0, 0, 800, 600);+ document.body.append(host, container);+ root = createRoot(host);+ scrollToIndex.mockResolvedValue();+ props = {+ container,+ query: "COD4",+ match: { entryId: "message", runId: null, occurrence: 0 },+ navigationId: 0,+ rowIndex: 0,+ entries: [{ id: "message" }],+ listRef: {+ current: {+ scrollToIndex,+ scrollToOffset,+ getState: () => ({ scroll: 300 }),+ } as unknown as LegendListRef,+ },+ contentInsetEndAdjustment: 100,+ listReady: true,+ };+});++afterEach(async () => {+ await act(async () => root.unmount());+ host.remove();+ container.remove();+ Reflect.deleteProperty(Range.prototype, "getBoundingClientRect");+ vi.clearAllMocks();+ vi.unstubAllGlobals();+});++describe("find result navigation", () => {+ it("retargets a pending first jump when progressive history moves the matching row", async () => {+ container.replaceChildren();+ let first!: () => void;+ let second!: () => void;+ scrollToIndex+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ first = resolve;+ }),+ )+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ second = resolve;+ }),+ );+ await act(async () => root.render(<Probe {...props} rowIndex={2} />));+ await act(async () =>+ root.render(<Probe {...props} rowIndex={6} entries={[{ id: "tool" }, ...props.entries]} />),+ );+ expect(scrollToIndex.mock.calls.map(([request]) => request.index)).toEqual([2, 6]);+ await act(async () => first());+ expect(scrollToOffset).not.toHaveBeenCalled();+ await act(async () => {+ container.innerHTML =+ '<div data-timeline-row-id="message"><p data-thread-find-text>COD4</p></div>';+ rect = new DOMRect(0, 450, 40, 20);+ second();+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 366, animated: false });+ });++ it("keeps the highlighted text at the same position when progressive activity arrives", async () => {+ const historyControls = {+ hasMoreHistory: true,+ loading: true,+ error: null,+ onLoadEarlier: vi.fn(),+ };+ await act(async () => root.render(<Probe {...props} historyControls={historyControls} />));+ rect = new DOMRect(0, 368, 40, 20);+ scrollToOffset.mockImplementationOnce(async () => {+ rect = new DOMRect(0, 200, 40, 20);+ });+ await act(async () =>+ root.render(+ <Probe+ {...props}+ entries={[{ id: "tool" }, { id: "message" }]}+ historyControls={{ ...historyControls, loading: false }}+ />,+ ),+ );+ expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 468, animated: false });+ expect(scrollToIndex).not.toHaveBeenCalled();+ });++ it("respects scrolling away from a partial match before activity arrives", async () => {+ const historyControls = {+ hasMoreHistory: true,+ loading: true,+ error: null,+ onLoadEarlier: vi.fn(),+ };+ await act(async () => root.render(<Probe {...props} historyControls={historyControls} />));+ rect = new DOMRect(0, -600, 40, 20);+ container.dispatchEvent(new Event("scroll"));+ await act(async () =>+ root.render(+ <Probe+ {...props}+ entries={[{ id: "tool" }, { id: "message" }]}+ historyControls={{ ...historyControls, loading: false }}+ />,+ ),+ );+ expect(scrollToOffset).not.toHaveBeenCalled();+ });++ it("reveals settled virtual text without another timeline render", async () => {+ let complete!: () => void;+ scrollToIndex.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ complete = resolve;+ }),+ );+ rect = new DOMRect(0, 1800, 40, 20);+ await act(async () => root.render(<Probe {...props} />));+ expect(renders).toHaveBeenCalledTimes(1);+ expect(scrollToOffset).not.toHaveBeenCalled();+ rect = new DOMRect(0, 450, 40, 20);+ await act(async () => {+ complete();+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 366, animated: false });+ expect(renders).toHaveBeenCalledTimes(1);+ });++ it("ignores an older scroll completion after navigation moves to another occurrence", async () => {+ let first!: () => void;+ let second!: () => void;+ scrollToIndex+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ first = resolve;+ }),+ )+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ second = resolve;+ }),+ );+ rect = new DOMRect(0, 1800, 40, 20);+ await act(async () => root.render(<Probe {...props} />));+ await act(async () =>+ root.render(+ <Probe+ {...props}+ navigationId={1}+ match={{ entryId: "message", runId: null, occurrence: 1 }}+ />,+ ),+ );+ rect = new DOMRect(0, 450, 40, 20);+ await act(async () => first());+ expect(scrollToOffset).not.toHaveBeenCalled();+ await act(async () => {+ second();+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 366, animated: false });+ });++ it("loads history until a distant match can be revealed in the conversation", async () => {+ const onLoadEarlier = vi.fn();+ const historyControls = { hasMoreHistory: true, loading: false, error: null, onLoadEarlier };+ const pending = { ...props, rowIndex: -1, entries: [{ id: "recent" }], historyControls };+ await act(async () => root.render(<Probe {...pending} />));+ expect(onLoadEarlier).toHaveBeenCalledTimes(1);+ expect(scrollToIndex).not.toHaveBeenCalled();+ await act(async () =>+ root.render(<Probe {...pending} historyControls={{ ...historyControls, loading: true }} />),+ );+ expect(onLoadEarlier).toHaveBeenCalledTimes(1);+ await act(async () =>+ root.render(<Probe {...pending} entries={[{ id: "older" }, ...pending.entries]} />),+ );+ expect(onLoadEarlier).toHaveBeenCalledTimes(2);+ rect = new DOMRect(0, 1800, 40, 20);+ scrollToIndex.mockImplementationOnce(async () => {+ rect = new DOMRect(0, 200, 40, 20);+ });+ await act(async () => root.render(<Probe {...props} historyControls={historyControls} />));+ expect(onLoadEarlier).toHaveBeenCalledTimes(2);+ expect(scrollToIndex).toHaveBeenCalledTimes(1);+ });++ it("waits for list bootstrap before positioning the first result", async () => {+ rect = new DOMRect(0, 1800, 40, 20);+ await act(async () => root.render(<Probe {...props} listReady={false} />));+ expect(scrollToIndex).not.toHaveBeenCalled();+ expect(scrollToOffset).not.toHaveBeenCalled();+ scrollToIndex.mockImplementationOnce(async () => {+ rect = new DOMRect(0, 200, 40, 20);+ });+ await act(async () => root.render(<Probe {...props} />));+ expect(scrollToIndex).toHaveBeenCalledTimes(1);+ expect(scrollToOffset).not.toHaveBeenCalled();+ });+ it("leaves the scroll position unchanged between already visible occurrences", async () => {+ await act(async () => root.render(<Probe {...props} />));+ await act(async () =>+ root.render(+ <Probe+ {...props}+ navigationId={1}+ match={{ entryId: "message", runId: null, occurrence: 1 }}+ />,+ ),+ );+ expect(scrollToIndex).not.toHaveBeenCalled();+ expect(scrollToOffset).not.toHaveBeenCalled();+ const highlight = CSS.highlights.get("t3-thread-find-active");+ const ranges = [...(highlight as unknown as Set<Range>)];+ expect(ranges).toHaveLength(1);+ expect(ranges[0]?.startOffset).toBe(9);+ expect(ranges[0]?.toString()).toBe("COD4");+ });++ it("reveals the same match again when search restarts after scrolling away", async () => {+ await act(async () => root.render(<Probe {...props} />));+ rect = new DOMRect(0, -1800, 40, 20);+ props.listRef.current = {+ scrollToIndex,+ scrollToOffset,+ getState: () => ({ scroll: 2400 }),+ } as unknown as LegendListRef;+ await act(async () => root.render(<Probe {...props} navigationId={1} />));+ expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 504, animated: false });+ expect(scrollToIndex).not.toHaveBeenCalled();+ expect(+ Array.from(CSS.highlights.get("t3-thread-find-active") ?? [], (range) => range.toString()),+ ).toEqual(["COD4"]);+ });++ it("moves only far enough to reveal text below the composer", async () => {+ await act(async () => root.render(<Probe {...props} />));+ rect = new DOMRect(0, 450, 40, 20);+ await act(async () =>+ root.render(+ <Probe+ {...props}+ navigationId={1}+ match={{ entryId: "message", runId: null, occurrence: 1 }}+ />,+ ),+ );+ expect(scrollToIndex).not.toHaveBeenCalled();+ expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 366, animated: false });+ });++ it("moves only far enough to reveal text above the viewport margin", async () => {+ await act(async () => root.render(<Probe {...props} />));+ rect = new DOMRect(0, 40, 40, 20);+ await act(async () =>+ root.render(+ <Probe+ {...props}+ navigationId={1}+ match={{ entryId: "message", runId: null, occurrence: 1 }}+ />,+ ),+ );+ expect(scrollToIndex).not.toHaveBeenCalled();+ expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 244, animated: false });+ });++ it("keeps the selected text visible when newly measured rows shift during scrolling", async () => {+ let scroll = 300;+ props.listRef.current = {+ scrollToIndex,+ scrollToOffset,+ getState: () => ({ scroll }),+ } as unknown as LegendListRef;+ scrollToOffset+ .mockImplementationOnce(async ({ offset }) => {+ scroll = offset;+ // Newly mounted row measurements offset the first scroll movement.+ })+ .mockImplementationOnce(async ({ offset }) => {+ scroll = offset;+ rect = new DOMRect(0, 200, 40, 20);+ });+ await act(async () => root.render(<Probe {...props} />));+ rect = new DOMRect(0, 450, 40, 20);+ await act(async () =>+ root.render(+ <Probe+ {...props}+ navigationId={1}+ match={{ entryId: "message", runId: null, occurrence: 1 }}+ />,+ ),+ );+ await act(async () => {+ await new Promise<void>((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );+ });+ expect(rect.top).toBe(200);+ expect(scrollToOffset.mock.calls).toEqual([+ [{ offset: 366, animated: false }],+ [{ offset: 432, animated: false }],+ ]);+ expect(renders).toHaveBeenCalledTimes(2);+ });++ it("waits for a new context window to settle before revealing an offscreen result", async () => {+ rect = new DOMRect(0, 1800, 40, 20);+ scrollToIndex.mockImplementationOnce(async () => {+ rect = new DOMRect(0, 450, 40, 20);+ });+ await act(async () => {+ root.render(<Probe {...props} />);+ });+ await act(async () => {+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ expect(scrollToIndex).toHaveBeenCalledTimes(1);+ expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 366, animated: false });+ });++ it("materializes a virtualized message before revealing its occurrence", async () => {+ container.replaceChildren();+ await act(async () => root.render(<Probe {...props} rowIndex={4} />));+ expect(scrollToIndex).toHaveBeenCalledExactlyOnceWith({+ index: 4,+ animated: false,+ viewOffset: 96,+ });+ expect(scrollToOffset).not.toHaveBeenCalled();+ rect = new DOMRect(0, 450, 40, 20);+ await act(async () => {+ container.innerHTML =+ '<div data-timeline-row-id="message"><p data-thread-find-text>COD4</p></div>';+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ });+ expect(scrollToIndex).toHaveBeenCalledTimes(1);+ expect(scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 366, animated: false });+ });+});diff --git a/apps/web/src/components/chat/useThreadFindNavigation.ts b/apps/web/src/components/chat/useThreadFindNavigation.tsnew file mode 100644index 00000000000..30aa49d2d6d--- /dev/null+++ b/apps/web/src/components/chat/useThreadFindNavigation.ts@@ -0,0 +1,261 @@+import type { LegendListRef } from "@legendapp/list/react";+import { useCallback, useEffect, useLayoutEffect, useRef, type RefObject } from "react";+import type { ThreadFindMatch } from "./threadFind";+import { useThreadFindHighlights } from "./threadFindHighlights";++const FIND_MATCH_VIEW_MARGIN = 96;++/** Materializes missing results and otherwise scrolls only enough to reveal the active text. */+export function useThreadFindNavigation({+ container,+ query,+ match,+ navigationId,+ rowIndex,+ entries,+ listRef,+ contentInsetEndAdjustment,+ listReady,+ historyControls,+}: {+ container: HTMLElement | null;+ query: string;+ match: ThreadFindMatch | null;+ navigationId: number;+ rowIndex: number;+ entries: readonly { readonly id: string }[];+ listRef: RefObject<LegendListRef | null>;+ contentInsetEndAdjustment: number;+ listReady: boolean;+ historyControls?:+ | {+ readonly hasMoreHistory: boolean;+ readonly loading: boolean;+ readonly error: string | null;+ readonly onLoadEarlier: (throughEntryId?: string) => void;+ }+ | undefined;+}) {+ const matchKey = match ? `${navigationId}:${query}:${match.entryId}:${match.occurrence}` : null;+ const positioningRef = useRef<{+ key: string;+ rowIndex: number;+ entries: typeof entries;+ } | null>(null);+ const settledMatchRef = useRef<string | null>(null);+ const currentMatchKeyRef = useRef(matchKey);+ const activeRangeRef = useRef<Range | null>(null);+ const pagingPositionRef = useRef<{ key: string; entries: typeof entries; top: number } | null>(+ null,+ );+ const currentEntriesRef = useRef(entries);+ useLayoutEffect(() => {+ currentEntriesRef.current = entries;+ }, [entries]);+ useEffect(() => {+ if (!container) return;+ const onScroll = () => {+ const position = pagingPositionRef.current;+ const range = activeRangeRef.current;+ if (+ !position ||+ position.entries !== currentEntriesRef.current ||+ !range?.startContainer.isConnected+ )+ return;+ const rect = range.getBoundingClientRect();+ const viewport = container.getBoundingClientRect();+ if (rect.bottom < viewport.top || rect.top > viewport.bottom)+ pagingPositionRef.current = null;+ else position.top = rect.top;+ };+ container.addEventListener("scroll", onScroll, { passive: true });+ return () => container.removeEventListener("scroll", onScroll);+ }, [container]);+ const revealRef = useRef<(range: Range | null) => void>(() => {});+ useLayoutEffect(() => {+ currentMatchKeyRef.current = matchKey;+ return () => {+ currentMatchKeyRef.current = null;+ };+ }, [matchKey]);+ const revealedMatchRef = useRef<string | null>(null);+ const positionedEntriesRef = useRef<typeof entries | null>(null);+ const requestedPagesRef = useRef<{ key: string | null; pages: Set<string> }>({+ key: null,+ pages: new Set(),+ });+ useEffect(() => {+ if (requestedPagesRef.current.key !== matchKey)+ requestedPagesRef.current = { key: matchKey, pages: new Set() };+ if (+ !match ||+ !listReady ||+ rowIndex >= 0 ||+ entries.some((entry) => entry.id === match.entryId)+ )+ return;+ if (!historyControls?.hasMoreHistory || historyControls.loading || historyControls.error)+ return;+ const cursor = entries[0]?.id ?? "first";+ if (requestedPagesRef.current.pages.has(cursor)) return;+ requestedPagesRef.current.pages.add(cursor);++ historyControls.onLoadEarlier(match.entryId);+ }, [entries, historyControls, listReady, match, matchKey, rowIndex]);+ const reveal = useCallback(+ (range: Range | null) => {+ activeRangeRef.current = range;+ if (!matchKey) {+ positioningRef.current = null;+ settledMatchRef.current = null;+ revealedMatchRef.current = null;+ pagingPositionRef.current = null;+ return;+ }+ const pagingPosition = pagingPositionRef.current;+ if (pagingPosition && pagingPosition.key !== matchKey) pagingPositionRef.current = null;+ if (+ range?.startContainer.isConnected &&+ pagingPosition?.key === matchKey &&+ pagingPosition.entries !== entries+ ) {+ const restore = () => {+ const pinned = pagingPositionRef.current;+ const currentRange = activeRangeRef.current;+ if (+ currentMatchKeyRef.current !== matchKey ||+ !pinned ||+ !currentRange?.startContainer.isConnected+ )+ return;+ const delta = currentRange.getBoundingClientRect().top - pinned.top;+ const scroll = listRef.current?.getState?.().scroll;+ if (Math.abs(delta) >= 1 && typeof scroll === "number")+ listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });+ };+ pagingPosition.entries = entries;+ restore();+ // The list measures newly inserted activity after the first layout pass.+ requestAnimationFrame(() =>+ requestAnimationFrame(() => {+ restore();+ if (!historyControls?.loading && pagingPositionRef.current === pagingPosition)+ pagingPositionRef.current = null;+ }),+ );+ }+ if (historyControls?.error) pagingPositionRef.current = null;+ if (revealedMatchRef.current === matchKey) return;+ if (!listReady || rowIndex < 0) return;+ const materialize = () => {+ const list = listRef.current;+ const previous = positioningRef.current;+ if (+ !list ||+ (previous?.key === matchKey &&+ previous.rowIndex === rowIndex &&+ previous.entries === entries)+ )+ return;+ // Activity can insert rows while LegendList waits for layout. Retarget the+ // pending jump instead of treating the first requested index as final.+ const request = { key: matchKey, rowIndex, entries };+ positioningRef.current = request;++ void list+ .scrollToIndex({+ index: rowIndex,+ animated: false,+ viewOffset: FIND_MATCH_VIEW_MARGIN,+ })+ .then(() => {+ if (positioningRef.current !== request || currentMatchKeyRef.current !== matchKey)+ return;++ positionedEntriesRef.current = entries;+ settledMatchRef.current = matchKey;+ revealRef.current(activeRangeRef.current);+ });+ };+ if (!range) {+ if (container) materialize();+ return;+ }++ const codeScroller = range.startContainer.parentElement?.closest("pre");+ if (codeScroller) {+ const rect = range.getBoundingClientRect();+ const viewport = codeScroller.getBoundingClientRect();+ if (rect.left < viewport.left) codeScroller.scrollLeft += rect.left - viewport.left - 16;+ else if (rect.right > viewport.right)+ codeScroller.scrollLeft += rect.right - viewport.right + 16;+ }+ const rect = range.getBoundingClientRect();+ const viewport = container?.getBoundingClientRect();+ if (!viewport || rect.height === 0) return;+ // Shrink the margin when the band above the composer is short, so the match stays inside it.+ const margin = Math.min(+ FIND_MATCH_VIEW_MARGIN,+ Math.max(0, (viewport.height - contentInsetEndAdjustment - rect.height) / 2),+ );+ const top = viewport.top + margin;+ const bottom = viewport.bottom - margin - contentInsetEndAdjustment;+ const delta =+ rect.top < top ? rect.top - top : rect.bottom > bottom ? rect.bottom - bottom : 0;+ // A new list can expose DOM text before its virtual row sizes settle.+ // Await row positioning before measuring an offscreen occurrence.+ if (+ Math.abs(delta) >= 1 &&+ positionedEntriesRef.current !== entries &&+ settledMatchRef.current !== matchKey+ ) {+ materialize();+ return;+ }+ const scroll = listRef.current?.getState?.().scroll;+ positionedEntriesRef.current = entries;++ revealedMatchRef.current = matchKey;+ if (historyControls?.loading)+ pagingPositionRef.current = { key: matchKey, entries, top: rect.top - delta };+ if (Math.abs(delta) >= 1 && typeof scroll === "number") {+ listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });+ // Scrolling can mount rows whose measured heights move the selected text again.+ requestAnimationFrame(() => {+ if (currentMatchKeyRef.current !== matchKey) return;+ if (+ listRef.current?.getState?.().scroll === scroll &&+ range.getBoundingClientRect().top === rect.top+ )+ return;+ revealedMatchRef.current = null;+ revealRef.current(activeRangeRef.current);+ });+ }+ },+ [+ container,+ contentInsetEndAdjustment,+ entries,+ historyControls?.loading,+ historyControls?.error,+ listRef,+ listReady,+ matchKey,+ rowIndex,+ ],+ );++ useLayoutEffect(() => {+ revealRef.current = reveal;+ }, [reveal]);++ useThreadFindHighlights({+ container,+ query,+ activeRowId: match?.entryId ?? null,+ activeOccurrence: match?.occurrence ?? 0,+ onActiveRange: reveal,+ });+}diff --git a/apps/web/src/components/files/FileBreadcrumbs.tsx b/apps/web/src/components/files/FileBreadcrumbs.tsxindex a98b4dca69d..d6ac3f594e9 100644--- a/apps/web/src/components/files/FileBreadcrumbs.tsx+++ b/apps/web/src/components/files/FileBreadcrumbs.tsx@@ -19,7 +19,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";import { useTheme } from "~/hooks/useTheme";import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";import { cn } from "~/lib/utils";-import { isAbsolutePath } from "~/terminal-links";+import { isAbsolutePath } from "@t3tools/shared/path";import {type FileBreadcrumb,diff --git a/apps/web/src/components/files/FileMarkdownPreview.tsx b/apps/web/src/components/files/FileMarkdownPreview.tsxindex e36ada48acb..2d4fd14e4b6 100644--- a/apps/web/src/components/files/FileMarkdownPreview.tsx+++ b/apps/web/src/components/files/FileMarkdownPreview.tsx@@ -1,7 +1,7 @@import type { ScopedThreadRef } from "@t3tools/contracts";import ChatMarkdown from "~/components/ChatMarkdown";-import { resolvePathLinkTarget } from "~/terminal-links";+import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";export function FileMarkdownPreview(props: {readonly cwd: string;diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsxindex 6692417adc6..1dbd9f0ea34 100644--- a/apps/web/src/components/files/FilePreviewPanel.tsx+++ b/apps/web/src/components/files/FilePreviewPanel.tsx@@ -57,7 +57,8 @@ import { resolveDiffThemeName } from "~/lib/diffRendering";import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";import { cn } from "~/lib/utils";import type { ChatFileAttachment } from "~/types";-import { isAbsolutePath, resolvePathLinkTarget } from "~/terminal-links";+import { isAbsolutePath } from "@t3tools/shared/path";+import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";import { ScrollArea } from "~/components/ui/scroll-area";import { stackedThreadToast, toastManager } from "~/components/ui/toast";import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";diff --git a/apps/web/src/components/files/filePath.ts b/apps/web/src/components/files/filePath.tsindex e819315310b..aa6225381be 100644--- a/apps/web/src/components/files/filePath.ts+++ b/apps/web/src/components/files/filePath.ts@@ -1,7 +1,5 @@import type { ProjectEntry } from "@t3tools/contracts";-import { isWindowsAbsolutePath } from "@t3tools/shared/path";--import { isAbsolutePath } from "~/terminal-links";+import { isWindowsAbsolutePath, isAbsolutePath } from "@t3tools/shared/path";export interface FileBreadcrumb {label: string;diff --git a/apps/web/src/components/files/filePreviewMode.ts b/apps/web/src/components/files/filePreviewMode.tsindex 764d44bfd83..151855404dd 100644--- a/apps/web/src/components/files/filePreviewMode.ts+++ b/apps/web/src/components/files/filePreviewMode.ts@@ -1,6 +1,5 @@-import { workspaceRelativeFilePath } from "@t3tools/client-runtime/markdown-links";import type { ProjectReadFileError } from "@t3tools/contracts";-import { isAbsolutePath } from "~/terminal-links";+import { isAbsolutePath, workspaceRelativeFilePath } from "@t3tools/shared/path";/** Resolve workspace links before choosing between the explorer and a file preview. */export function resolveFilePreviewPath(path: string | null, cwd: string): string | null {diff --git a/apps/web/src/components/settings/ThemeEditorPanel.tsx b/apps/web/src/components/settings/ThemeEditorPanel.tsxindex 27176181768..63482a22a10 100644--- a/apps/web/src/components/settings/ThemeEditorPanel.tsx+++ b/apps/web/src/components/settings/ThemeEditorPanel.tsx@@ -162,6 +162,24 @@ const THEME_EDITOR_ROLE_GROUPS: ReadonlyArray<{},],},+ {+ id: "search",+ title: "Search",+ families: [+ {+ id: "search-matches",+ label: "Search matches",+ role: "searchMatchBackground",+ roles: ["searchMatchBackground", "searchMatchForeground"],+ },+ {+ id: "current-match",+ label: "Current match",+ role: "searchMatchActiveBackground",+ roles: ["searchMatchActiveBackground", "searchMatchActiveForeground"],+ },+ ],+ },{id: "context",title: "Context",diff --git a/apps/web/src/components/ui/input-group.tsx b/apps/web/src/components/ui/input-group.tsxindex 9a9228ede61..76eceb0bd01 100644--- a/apps/web/src/components/ui/input-group.tsx+++ b/apps/web/src/components/ui/input-group.tsx@@ -11,11 +11,19 @@ const inputGroupVariants = cva({defaultVariants: {variant: "default",+ size: "default",},variants: {+ size: {+ default: null,+ lg: "h-9",+ },variant: {default:"border-input bg-background not-dark:bg-clip-padding shadow-xs/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--control-radius)-1px)] not-has-[input:disabled,textarea:disabled]:not-has-[input:focus-visible,textarea:focus-visible]:not-has-[input[aria-invalid],textarea[aria-invalid]]:before:shadow-[0_1px_--theme(--color-black/4%)] dark:bg-input/32 dark:not-has-[input:disabled,textarea:disabled]:not-has-[input:focus-visible,textarea:focus-visible]:not-has-[input[aria-invalid],textarea[aria-invalid]]:before:shadow-[0_-1px_--theme(--color-white/6%)]",+ // Matches floating glass cards (no shadow); focus darkens the hairline instead of a ring.+ popover:+ "dropdown-glass rounded-2xl has-[input:focus-visible,textarea:focus-visible]:ring-0 has-[input:focus-visible,textarea:focus-visible]:border-[color-mix(in_srgb,var(--contrast-foreground)_18%,transparent)]",ghost:"border-transparent bg-transparent shadow-none hover:bg-muted/40 has-[input:focus-visible,textarea:focus-visible]:bg-background",},@@ -26,11 +34,12 @@ const inputGroupVariants = cva(function InputGroup({className,variant,+ size,...props}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupVariants>) {return (<div- className={cn(inputGroupVariants({ variant }), className)}+ className={cn(inputGroupVariants({ variant, size }), className)}data-slot="input-group"role="group"{...props}@@ -44,7 +53,24 @@ const inputGroupAddonVariants = cva(defaultVariants: {align: "inline-start",},+ compoundVariants: [+ // Pill groups curve too tightly for buttons pulled to the edge; keep them inset.+ {+ align: "inline-end",+ inset: "pill",+ className: "has-[>button]:me-0 pe-1 [[data-size=sm]+&]:pe-1 gap-0.5",+ },+ {+ align: "inline-start",+ inset: "pill",+ className: "has-[>button]:ms-0 ps-1 [[data-size=sm]+&]:ps-1 gap-0.5",+ },+ ],variants: {+ inset: {+ default: null,+ pill: "[&_button]:rounded-full",+ },align: {"block-end":"order-last w-full justify-start px-[calc(--spacing(3)-1px)] pb-[calc(--spacing(3)-1px)] [.border-t]:pt-[calc(--spacing(3)-1px)] [[data-size=sm]+&]:px-[calc(--spacing(2.5)-1px)]",@@ -62,11 +88,12 @@ const inputGroupAddonVariants = cva(function InputGroupAddon({className,align = "inline-start",+ inset,...props}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {return (<div- className={cn(inputGroupAddonVariants({ align }), className)}+ className={cn(inputGroupAddonVariants({ align, inset }), className)}data-align={align}data-slot="input-group-addon"onMouseDown={(e) => {diff --git a/apps/web/src/diffFileActions.ts b/apps/web/src/diffFileActions.tsindex 3ac22c28cf2..99baf13c941 100644--- a/apps/web/src/diffFileActions.ts+++ b/apps/web/src/diffFileActions.ts@@ -2,7 +2,7 @@ import type { ScopedThreadRef } from "@t3tools/contracts";import { isWindowsAbsolutePath, normalizeProjectPathForComparison } from "@t3tools/shared/path";import { useRightPanelStore } from "./rightPanelStore";-import { resolvePathLinkTarget } from "./terminal-links";+import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";interface OpenDiffFilePrimaryActionInput {readonly threadRef: ScopedThreadRef | null;diff --git a/apps/web/src/fileContextMenu.ts b/apps/web/src/fileContextMenu.tsindex 05425f20595..3035f5825ac 100644--- a/apps/web/src/fileContextMenu.ts+++ b/apps/web/src/fileContextMenu.ts@@ -22,7 +22,7 @@ import { readLocalApi } from "./localApi";import { serverEnvironment } from "./state/server";import { shellEnvironment } from "./state/shell";import { useAtomCommand } from "./state/use-atom-command";-import { resolvePathLinkTarget } from "./terminal-links";+import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";import { toastManager } from "./components/ui/toast";import { useAtomValue } from "@effect/atom-react";diff --git a/apps/web/src/filePathDisplay.ts b/apps/web/src/filePathDisplay.tsindex 36f5873cf8e..7fee707bf4c 100644--- a/apps/web/src/filePathDisplay.ts+++ b/apps/web/src/filePathDisplay.ts@@ -1,10 +1,9 @@import {fileBasename,- formatFilePathPosition,- splitFilePathPosition,stripSlashPrefixedWindowsDrive,-} from "@t3tools/client-runtime/markdown-links";-import { isWindowsAbsolutePath } from "@t3tools/shared/path";+ isWindowsAbsolutePath,+} from "@t3tools/shared/path";+import { formatFilePathPosition, splitFilePathPosition } from "@t3tools/shared/fileLinks";function normalizePathSeparators(path: string): string {return path.replaceAll("\\", "/");diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex 453a9fd599f..f0374b2160a 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -373,6 +373,20 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil}}+/* Paint find results without changing rendered markdown or copied text. */+::highlight(t3-thread-find) {+ color: var(--app-theme-search-match-foreground, var(--color-foreground));+ background-color: var(--app-theme-search-match-background, oklch(0.826487 0.157967 78.604 / 0.3));+}++::highlight(t3-thread-find-active) {+ color: var(--app-theme-search-match-active-foreground, oklch(0.216164 0.028283 77.423));+ background-color: var(+ --app-theme-search-match-active-background,+ oklch(0.774202 0.151946 74.331)+ );+}+@utility dialog-glass {background: color-mix(in srgb, var(--background) var(--glass-opacity), transparent);-webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.tsindex 811d9101cbc..73b1fa8fc00 100644--- a/apps/web/src/keybindings.test.ts+++ b/apps/web/src/keybindings.test.ts@@ -142,6 +142,14 @@ const DEFAULT_BINDINGS = compile([shortcut: modShortcut("t", { altKey: true, shiftKey: true }),command: "themeEditor.toggle",},+ {+ shortcut: modShortcut("f"),+ command: "chat.find",+ whenAst: whenAnd(+ whenNot(whenIdentifier("terminalFocus")),+ whenNot(whenIdentifier("previewFocus")),+ ),+ },{shortcut: modShortcut("m", { shiftKey: true }),command: "modelPicker.toggle",diff --git a/apps/web/src/markdown-incremental.test.tsx b/apps/web/src/markdown-incremental.test.tsxindex cf06355f3b4..3682deb281f 100644--- a/apps/web/src/markdown-incremental.test.tsx+++ b/apps/web/src/markdown-incremental.test.tsx@@ -1,16 +1,15 @@+import { CHAT_MARKDOWN_REHYPE_PLUGINS } from "@t3tools/shared/markdownPipeline";import type { Root } from "mdast";import { renderToStaticMarkup } from "react-dom/server";import ReactMarkdown from "react-markdown";-import rehypeRaw from "rehype-raw";-import rehypeSanitize from "rehype-sanitize";import remarkGfm from "remark-gfm";import type { Plugin } from "unified";import { describe, expect, it } from "vite-plus/test";-import { remarkCodexDirectives } from "@t3tools/client-runtime/codex-markdown-directives";-import { remarkGithubAlerts } from "./markdown-github-alerts";+import { remarkCodexDirectives } from "@t3tools/shared/codexMarkdownDirectives";+import { remarkGithubAlerts } from "@t3tools/shared/markdownGithubAlerts";import { createIncrementalMarkdownPlugin } from "./markdown-incremental";-import { remarkNormalizeListItemIndentation } from "./markdown-list-indentation";+import { remarkNormalizeListItemIndentation } from "@t3tools/shared/markdownListIndentation";function render(source: string, incremental?: Plugin<[], Root>, parsedSources?: string[]) {let tree: Root | undefined;@@ -37,7 +36,7 @@ function render(source: string, incremental?: Plugin<[], Root>, parsedSources?:remarkCodexDirectives,...(incremental ? [incremental] : []),]}- rehypePlugins={[rehypeRaw, rehypeSanitize]}+ rehypePlugins={CHAT_MARKDOWN_REHYPE_PLUGINS}>{source}</ReactMarkdown>,diff --git a/apps/web/src/markdown-links.test.ts b/apps/web/src/markdown-links.test.tsindex fe352ec1a44..a8e01e834c7 100644--- a/apps/web/src/markdown-links.test.ts+++ b/apps/web/src/markdown-links.test.ts@@ -1,66 +1,13 @@import { describe, expect, it } from "vite-plus/test";-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";-import ReactMarkdown from "react-markdown";import {- extractMarkdownLinkHrefs,- isWindowsDrivePathHref,resolveInlineCodeFileLinkMeta,resolveMarkdownFileLinkMeta,- resolveMarkdownFileLinkTarget,rewriteMarkdownFileUriHref,shouldOpenMarkdownFileLinkInBrowserByDefault,shouldOpenMarkdownFileLinkInEditor,} from "./markdown-links";-describe("isWindowsDrivePathHref", () => {- it.each([- ["C:\\repo\\image.png", true],- ["C:%5Crepo%5Cimage.png", true],- ["https://example.com/image.png", false],- ])("classifies %s as %s", (href, expected) => {- expect(isWindowsDrivePathHref(href)).toBe(expected);- });-});--function renderMarkdownLinkHref(markdown: string): string | undefined {- let renderedHref: string | undefined;- renderToStaticMarkup(- createElement(- ReactMarkdown,- {- components: {- a({ href }) {- renderedHref = href;- return createElement("a", { href });- },- },- },- markdown,- ),- );- return renderedHref;-}--describe("extractMarkdownLinkHrefs", () => {- it("extracts angle-bracketed paths containing spaces", () => {- expect(- extractMarkdownLinkHrefs(- "[Open the Bike Receipts folder](</Users/dara/Downloads/Lime Ride Artifacts/Bike Receipts>)",- ),- ).toEqual(["/Users/dara/Downloads/Lime Ride Artifacts/Bike Receipts"]);- });-- it("preserves ordinary destinations and ignores link titles", () => {- expect(- extractMarkdownLinkHrefs(- '[source](apps/web/src/markdown-links.ts "implementation") and [docs](https://example.com)',- ),- ).toEqual(["apps/web/src/markdown-links.ts", "https://example.com"]);- });-});-describe("shouldOpenMarkdownFileLinkInEditor", () => {it("uses command-click on macOS", () => {expect(shouldOpenMarkdownFileLinkInEditor({ metaKey: true, ctrlKey: false }, "MacIntel")).toBe(@@ -130,213 +77,6 @@ describe("rewriteMarkdownFileUriHref", () => {});});-describe("resolveMarkdownFileLinkTarget", () => {- it("resolves absolute posix file paths", () => {- expect(resolveMarkdownFileLinkTarget("/Users/julius/project/AGENTS.md")).toBe(- "/Users/julius/project/AGENTS.md",- );- });-- it("resolves relative file paths against cwd", () => {- expect(resolveMarkdownFileLinkTarget("src/processRunner.ts:71", "/Users/julius/project")).toBe(- "/Users/julius/project/src/processRunner.ts:71",- );- });-- it("does not treat filename line references as external schemes", () => {- expect(resolveMarkdownFileLinkTarget("script.ts:10", "/Users/julius/project")).toBe(- "/Users/julius/project/script.ts:10",- );- });-- it("resolves bare file names against cwd", () => {- expect(resolveMarkdownFileLinkTarget("AGENTS.md", "/Users/julius/project")).toBe(- "/Users/julius/project/AGENTS.md",- );- });-- it("maps #L line anchors to editor line suffixes", () => {- expect(resolveMarkdownFileLinkTarget("/Users/julius/project/src/main.ts#L42C7")).toBe(- "/Users/julius/project/src/main.ts:42:7",- );- });-- it("ignores external urls", () => {- expect(resolveMarkdownFileLinkTarget("https://example.com/docs")).toBeNull();- expect(resolveMarkdownFileLinkTarget("//cdn.example.com/clip.mp4", "/workspace")).toBeNull();- });-- it("does not double-decode file URLs", () => {- expect(resolveMarkdownFileLinkTarget("file:///Users/julius/project/file%2520name.md")).toBe(- "/Users/julius/project/file%20name.md",- );- });-- it("resolves file uri authorities as windows UNC paths", () => {- expect(resolveMarkdownFileLinkTarget("file://server/share/workspace-image.svg")).toBe(- "\\\\server\\share\\workspace-image.svg",- );- });-- it("resolves a localhost file uri as a local path", () => {- expect(resolveMarkdownFileLinkTarget("file://localhost/home/me/notes.md")).toBe(- "/home/me/notes.md",- );- });-- it("formats tooltip display paths relative to the cwd when possible", () => {- expect(- resolveMarkdownFileLinkMeta(- "file:///C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts#L501",- "C:/Users/mike/dev-stuff/t3code",- ),- ).toMatchObject({- displayPath: "t3code/apps/web/src/session-logic.ts:501",- workspaceRelativePath: "apps/web/src/session-logic.ts",- });- });-- it("resolves the encoded spaces emitted by the markdown renderer", () => {- expect(- resolveMarkdownFileLinkMeta(- "/Users/dara/Downloads/Lime%20Ride%20Artifacts/Bike%20Receipts",- "/Users/dara/Downloads/Lime Ride Artifacts",- ),- ).toMatchObject({- targetPath: "/Users/dara/Downloads/Lime Ride Artifacts/Bike Receipts",- workspaceRelativePath: "Bike Receipts",- basename: "Bike Receipts",- });- });-- it("resolves relative spaced folders from the markdown renderer", () => {- const href = renderMarkdownLinkHref("[folder](<docs/My Folder>)");-- expect(href).toBe("docs/My%20Folder");- expect(resolveMarkdownFileLinkMeta(href, "/repo/project")).toMatchObject({- targetPath: "/repo/project/docs/My Folder",- workspaceRelativePath: "docs/My Folder",- basename: "My Folder",- });- });-- it.each(["md", "html", "xml"])(- "resolves a bare spaced .%s filename from the markdown renderer",- (extension) => {- const href = renderMarkdownLinkHref(`[checklist](<Updated cutover checklist.${extension}>)`);-- expect(href).toBe(`Updated%20cutover%20checklist.${extension}`);- expect(resolveMarkdownFileLinkMeta(href, "/repo/project")).toMatchObject({- targetPath: `/repo/project/Updated cutover checklist.${extension}`,- workspaceRelativePath: `Updated cutover checklist.${extension}`,- basename: `Updated cutover checklist.${extension}`,- });- },- );-- it("formats tooltip display paths relative to the cwd for slash-prefixed windows paths", () => {- expect(- resolveMarkdownFileLinkMeta(- "/C:/Users/mike/dev-stuff/t3code/apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx",- "C:/Users/mike/dev-stuff/t3code",- ),- ).toMatchObject({- displayPath:- "t3code/apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx",- workspaceRelativePath:- "apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx",- });- });-- it("does not create a preview path for files outside the workspace", () => {- expect(resolveMarkdownFileLinkMeta("/tmp/report.ts", "/repo/project")).toMatchObject({- workspaceRelativePath: null,- });- });-- it("does not classify a case-distinct POSIX sibling as a workspace file", () => {- expect(- resolveMarkdownFileLinkMeta(- "/tmp/t3code-case-test/project/probe.txt",- "/tmp/t3code-case-test/Project",- ),- ).toMatchObject({- displayPath: "/tmp/t3code-case-test/project/probe.txt",- workspaceRelativePath: null,- });- });-- it("keeps Windows workspace comparisons case-insensitive", () => {- expect(- resolveMarkdownFileLinkMeta("C:/Users/MIKE/Project/src/main.ts", "c:/users/mike/project"),- ).toMatchObject({- displayPath: "project/src/main.ts",- workspaceRelativePath: "src/main.ts",- });- });-- it("keeps drive-root workspace comparisons case-insensitive", () => {- expect(resolveMarkdownFileLinkMeta("C:/Users/MIKE/project.ts", "c:/")).toMatchObject({- displayPath: "c:/Users/MIKE/project.ts",- workspaceRelativePath: "Users/MIKE/project.ts",- });- });-- it("keeps backslash UNC workspace comparisons case-insensitive", () => {- expect(- resolveMarkdownFileLinkMeta(- "\\\\server\\share\\PROJECT\\src\\main.ts",- "\\\\Server\\Share\\Project",- ),- ).toMatchObject({- displayPath: "Project/src/main.ts",- workspaceRelativePath: "src/main.ts",- });- });-- it.each([- ["/tmp/repo/file.ts", "/", "tmp/repo/file.ts"],- ["C:/Users/MIKE/file.ts", "c:/", "Users/MIKE/file.ts"],- ["\\\\server\\SHARE\\file.ts", "\\\\Server\\Share\\", "file.ts"],- ["/tmp/repo/file.ts%20", "/tmp/repo", "file.ts "],- ])("preserves the preview target for %s in workspace %s", (href, cwd, workspaceRelativePath) => {- expect(resolveMarkdownFileLinkMeta(href, cwd)).toMatchObject({ workspaceRelativePath });- });-- it("keeps an encoded final space in the absolute target", () => {- expect(resolveMarkdownFileLinkTarget("/tmp/repo/file.ts%20", "/tmp/repo")).toBe(- "/tmp/repo/file.ts ",- );- });-- it("normalizes slash-prefixed windows drive paths before resolving", () => {- expect(- resolveMarkdownFileLinkTarget(- "/D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx#L69",- ),- ).toBe("D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx:69");- });-- it("resolves angle-bracketed windows drive paths", () => {- expect(- resolveMarkdownFileLinkTarget(- "</D:/Programme/t3code/apps/web/src/components/ChatMarkdown.tsx:1>",- ),- ).toBe("D:/Programme/t3code/apps/web/src/components/ChatMarkdown.tsx:1");- });-- it("does not treat app routes as file links, even with a line anchor", () => {- expect(resolveMarkdownFileLinkTarget("/chat/settings")).toBeNull();- expect(resolveMarkdownFileLinkTarget("/chat/settings#L3", "/repo")).toBeNull();- });-- it("decodes an encoded drive colon in a file uri before dropping its slash", () => {- expect(resolveMarkdownFileLinkTarget("file:///c%3A/Users/x/shot.png")).toBe(- "c:/Users/x/shot.png",- );- });-});-describe("relative links inside a rendered host file", () => {it("anchor to the file's directory while workspace membership follows cwd", () => {const meta = resolveMarkdownFileLinkMeta("appendix.md", "/repo", "/tmp/report");diff --git a/apps/web/src/markdown-links.ts b/apps/web/src/markdown-links.tsindex 8ed59eb8775..d25d089f652 100644--- a/apps/web/src/markdown-links.ts+++ b/apps/web/src/markdown-links.ts@@ -1,23 +1,13 @@+import { fileBasename, workspaceRelativeFilePath } from "@t3tools/shared/path";import {- fileBasename,- formatFilePathPosition,inlineCodeFilePathCandidate,- isRelativeFilePath,normalizeMarkdownLinkDestination,- parseFileUrlHref,- parseMarkdownFileLink,- safeDecodeURIComponent,- splitFilePathPosition,- workspaceRelativeFilePath,-} from "@t3tools/client-runtime/markdown-links";+ resolveMarkdownFileLinkTarget,+} from "@t3tools/shared/markdownLinks";+import { parseFileUrlHref, splitFilePathPosition } from "@t3tools/shared/fileLinks";import { formatWorkspaceRelativePath } from "./filePathDisplay";-import { isTerminalLinkActivation, resolvePathLinkTarget } from "./terminal-links";--export { normalizeMarkdownLinkDestination };--const MARKDOWN_LINK_HREF_PATTERN =- /\[[^\]]*]\(\s*(?:<([^>\n]+)>|([^\s)]+))(?:\s+["'][^"']*["'])?\s*\)/g;+import { isTerminalLinkActivation } from "./terminal-links";export interface MarkdownFileLinkMeta {filePath: string;@@ -29,15 +19,6 @@ export interface MarkdownFileLinkMeta {column?: number;}-export function extractMarkdownLinkHrefs(markdown: string): string[] {- const hrefs: string[] = [];- for (const match of markdown.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {- const href = (match[1] ?? match[2])?.trim();- if (href) hrefs.push(href);- }- return hrefs;-}-export function shouldOpenMarkdownFileLinkInEditor(event: Pick<MouseEvent, "metaKey" | "ctrlKey">,platform?: string,@@ -49,36 +30,12 @@ export function shouldOpenMarkdownFileLinkInBrowserByDefault(path: string): boolreturn /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");}-export function isWindowsDrivePathHref(href: string): boolean {- return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));-}-export function rewriteMarkdownFileUriHref(href: string | undefined): string | null {if (!href) return null;const target = parseFileUrlHref(normalizeMarkdownLinkDestination(href));return target ? `${target.path}${target.hash}` : null;}-/**- * `baseDir` anchors relative links; it defaults to the workspace root and is the- * file's own directory when rendering a markdown file. `cwd` stays the workspace- * root so the result still knows whether the target is inside it.- */-export function resolveMarkdownFileLinkTarget(- href: string | undefined,- cwd?: string,- baseDir: string | undefined = cwd,-): string | null {- if (!href) return null;- const target = parseMarkdownFileLink(href);- if (!target) return null;-- const pathWithPosition = formatFilePathPosition(target);- if (!isRelativeFilePath(pathWithPosition)) return pathWithPosition;- if (!baseDir) return null;- return resolvePathLinkTarget(pathWithPosition, baseDir);-}-/*** Inline code spans mostly hold identifiers, commands, and refs (`node.meta`,* `origin/main`) rather than deliberate link destinations, so auto-linkingdiff --git a/apps/web/src/markdown-github-alerts.test.tsx b/apps/web/src/markdownGithubAlerts.test.tsxsimilarity index 96%rename from apps/web/src/markdown-github-alerts.test.tsxrename to apps/web/src/markdownGithubAlerts.test.tsxindex 22bb711103e..ff577a78e53 100644--- a/apps/web/src/markdown-github-alerts.test.tsx+++ b/apps/web/src/markdownGithubAlerts.test.tsx@@ -3,7 +3,7 @@ import ReactMarkdown from "react-markdown";import remarkGfm from "remark-gfm";import { describe, expect, it } from "vite-plus/test";-import { remarkGithubAlerts } from "./markdown-github-alerts";+import { remarkGithubAlerts } from "@t3tools/shared/markdownGithubAlerts";function renderMarkdown(markdown: string): string {return renderToStaticMarkup(diff --git a/apps/web/src/markdown-list-indentation.test.tsx b/apps/web/src/markdownListIndentation.test.tsxsimilarity index 96%rename from apps/web/src/markdown-list-indentation.test.tsxrename to apps/web/src/markdownListIndentation.test.tsxindex 2c04ed5fa83..3ce4ad6a7eb 100644--- a/apps/web/src/markdown-list-indentation.test.tsx+++ b/apps/web/src/markdownListIndentation.test.tsx@@ -3,7 +3,7 @@ import ReactMarkdown from "react-markdown";import remarkGfm from "remark-gfm";import { describe, expect, it } from "vite-plus/test";-import { remarkNormalizeListItemIndentation } from "./markdown-list-indentation";+import { remarkNormalizeListItemIndentation } from "@t3tools/shared/markdownListIndentation";function renderMarkdown(markdown: string): string {return renderToStaticMarkup(diff --git a/apps/web/src/openVsxThemes.test.ts b/apps/web/src/openVsxThemes.test.tsindex b4794f61986..ba6eb482e8c 100644--- a/apps/web/src/openVsxThemes.test.ts+++ b/apps/web/src/openVsxThemes.test.ts@@ -305,6 +305,10 @@ describe("Open VSX themes", () => {"colors": {"editor.foreground": "#eeeeee","focusBorder": "#8b5cf6",+ "editor.findMatchBackground": "#663399",+ "editor.findMatchForeground": "#ffffff",+ "editor.findMatchHighlightBackground": "#445566",+ "editor.findMatchHighlightForeground": "#ffffff",},}`,);@@ -312,7 +316,10 @@ describe("Open VSX themes", () => {"extension/themes/demo-dark.json",`{"include": "./base.jsonc",- "colors": { "editor.background": "#111111" }+ "colors": {+ "editor.background": "#111111",+ "editor.findMatchHighlightBackground": "#ffffff20"+ }}`,);zip.file(@@ -321,7 +328,11 @@ describe("Open VSX themes", () => {"colors": {"editor.background": "#fafafa","editor.foreground": "#222222",- "focusBorder": "#8b5cf6"+ "focusBorder": "#8b5cf6",+ "editor.findMatchBackground": "#335577",+ "editor.findMatchForeground": "#ffffff",+ "editor.findMatchHighlightBackground": "#bbddff",+ "editor.findMatchHighlightForeground": "#112233"}}`,);@@ -410,6 +421,15 @@ describe("Open VSX themes", () => {expect(themeColorToHex(paired.colors.canvas)).toBe("#fafafa");expect(themeColorToHex(getThemeColorsForMode(paired, "dark")!.canvas)).toBe("#111111");expect(themeColorToHex(getThemeColorsForMode(paired, "dark")!.text)).toBe("#eeeeee");+ const darkColors = getThemeColorsForMode(paired, "dark")!;+ expect(themeColorToHex(darkColors.searchMatchActiveBackground)).toBe("#663399");+ expect(themeColorToHex(darkColors.searchMatchActiveForeground)).toBe("#ffffff");+ expect(themeColorToHex(darkColors.searchMatchBackground)).toBe("#2f2f2f");+ expect(themeColorToHex(darkColors.searchMatchForeground)).toBe("#ffffff");+ expect(themeColorToHex(paired.colors.searchMatchActiveBackground)).toBe("#335577");+ expect(themeColorToHex(paired.colors.searchMatchActiveForeground)).toBe("#ffffff");+ expect(themeColorToHex(paired.colors.searchMatchBackground)).toBe("#bbddff");+ expect(themeColorToHex(paired.colors.searchMatchForeground)).toBe("#112233");packagedManifest.contributes.themes[0]!.label = "Renamed Dark";packagedManifest.contributes.themes[1]!.label = "Renamed Light";diff --git a/apps/web/src/openVsxThemes.ts b/apps/web/src/openVsxThemes.tsindex 8b03d84869b..81617e3cd21 100644--- a/apps/web/src/openVsxThemes.ts+++ b/apps/web/src/openVsxThemes.ts@@ -49,6 +49,10 @@ const USED_WORKBENCH_COLORS = new Set(["dropdown.border","editor.background","editor.foreground",+ "editor.findMatchBackground",+ "editor.findMatchForeground",+ "editor.findMatchHighlightBackground",+ "editor.findMatchHighlightForeground","editor.selectionBackground","editorCursor.foreground","editorError.foreground",diff --git a/apps/web/src/proposedPlan.test.ts b/apps/web/src/proposedPlan.test.tsindex a8700ab924e..30e114a0eb7 100644--- a/apps/web/src/proposedPlan.test.ts+++ b/apps/web/src/proposedPlan.test.ts@@ -5,21 +5,9 @@ import {buildPlanImplementationThreadTitle,buildPlanImplementationPrompt,buildProposedPlanMarkdownFilename,- proposedPlanTitle,resolvePlanFollowUpSubmission,- stripDisplayedPlanMarkdown,} from "./proposedPlan";-describe("proposedPlanTitle", () => {- it("reads the first markdown heading as the plan title", () => {- expect(proposedPlanTitle("# Integrate RPC\n\nBody")).toBe("Integrate RPC");- });-- it("returns null when the plan has no heading", () => {- expect(proposedPlanTitle("- step 1")).toBeNull();- });-});-describe("buildPlanImplementationPrompt", () => {it("formats the plan exactly like the Codex follow-up handoff prompt", () => {expect(buildPlanImplementationPrompt("## Ship it\n\n- step 1\n")).toBe(@@ -49,20 +37,6 @@ describe("buildCollapsedProposedPlanPreviewMarkdown", () => {});});-describe("stripDisplayedPlanMarkdown", () => {- it("drops the leading title heading from displayed plan markdown", () => {- expect(stripDisplayedPlanMarkdown("# Integrate RPC\n\n## Summary\n\n- step 1\n")).toBe(- "- step 1",- );- });-- it("preserves non-summary headings after dropping the title heading", () => {- expect(stripDisplayedPlanMarkdown("# Integrate RPC\n\n## Scope\n\n- step 1\n")).toBe(- "## Scope\n\n- step 1",- );- });-});-describe("resolvePlanFollowUpSubmission", () => {it.each(["", "Consider this "])("keeps context-bearing feedback in plan mode with prose %j",diff --git a/apps/web/src/proposedPlan.ts b/apps/web/src/proposedPlan.tsindex 525be17a72e..15f90c59ae2 100644--- a/apps/web/src/proposedPlan.ts+++ b/apps/web/src/proposedPlan.ts@@ -1,23 +1,4 @@-export function proposedPlanTitle(planMarkdown: string): string | null {- const heading = planMarkdown.match(/^\s{0,3}#{1,6}\s+(.+)$/m)?.[1]?.trim();- return heading && heading.length > 0 ? heading : null;-}--export function stripDisplayedPlanMarkdown(planMarkdown: string): string {- const lines = planMarkdown.trimEnd().split(/\r?\n/);- const sourceLines = lines[0] && /^\s{0,3}#{1,6}\s+/.test(lines[0]) ? lines.slice(1) : [...lines];- while (sourceLines[0]?.trim().length === 0) {- sourceLines.shift();- }- const firstHeadingMatch = sourceLines[0]?.match(/^\s{0,3}#{1,6}\s+(.+)$/);- if (firstHeadingMatch?.[1]?.trim().toLowerCase() === "summary") {- sourceLines.shift();- while (sourceLines[0]?.trim().length === 0) {- sourceLines.shift();- }- }- return sourceLines.join("\n");-}+import { stripDisplayedPlanMarkdown, proposedPlanTitle } from "@t3tools/shared/proposedPlanText";export function buildCollapsedProposedPlanPreviewMarkdown(planMarkdown: string,diff --git a/apps/web/src/providerSkillSearch.ts b/apps/web/src/providerSkillSearch.tsindex a570c92d91f..21e182360f9 100644--- a/apps/web/src/providerSkillSearch.ts+++ b/apps/web/src/providerSkillSearch.ts@@ -1,7 +1,7 @@+import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";import type { ServerProviderSkill } from "@t3tools/contracts";import {dedupeProviderSkillsByName,- formatProviderSkillDisplayName,isProviderSkillUserInvocable,} from "@t3tools/client-runtime/providerSkills";import {diff --git a/apps/web/src/terminal-links.test.ts b/apps/web/src/terminal-links.test.tsindex 5cb2ad91582..6dc750edeec 100644--- a/apps/web/src/terminal-links.test.ts+++ b/apps/web/src/terminal-links.test.ts@@ -1,3 +1,4 @@+import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";import { describe, expect, it } from "vite-plus/test";import {@@ -5,7 +6,6 @@ import {extractTerminalLinks,isTerminalLinkActivation,isTerminalUrl,- resolvePathLinkTarget,type TerminalBufferLineLike,} from "./terminal-links";diff --git a/apps/web/src/terminal-links.ts b/apps/web/src/terminal-links.tsindex 0f253588b70..7ad2d83843d 100644--- a/apps/web/src/terminal-links.ts+++ b/apps/web/src/terminal-links.ts@@ -1,8 +1,3 @@-import {- formatFilePathPosition,- splitFilePathPosition,-} from "@t3tools/client-runtime/markdown-links";-import { isMacPlatform } from "./lib/utils";export type TerminalLinkKind = "url" | "path";@@ -98,45 +93,6 @@ function collectMatches(return matches;}-function isWindowsAbsolutePath(value: string): boolean {- return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");-}--export function isAbsolutePath(value: string): boolean {- return value.startsWith("/") || isWindowsAbsolutePath(value);-}--function isWindowsPathStyle(value: string): boolean {- return isWindowsAbsolutePath(value) || /[A-Za-z]:\\/.test(value);-}--function joinPath(base: string, next: string, separator: "/" | "\\"): string {- const cleanBase = base.replace(/[\\/]+$/, "");- if (separator === "\\") {- return `${cleanBase}\\${next.replaceAll("/", "\\")}`;- }- return `${cleanBase}/${next.replace(/^\/+/, "")}`;-}--function inferHomeFromCwd(cwd: string): string | undefined {- const posixUser = cwd.match(/^\/Users\/([^/]+)/);- if (posixUser?.[1]) {- return `/Users/${posixUser[1]}`;- }-- const posixHome = cwd.match(/^\/home\/([^/]+)/);- if (posixHome?.[1]) {- return `/home/${posixHome[1]}`;- }-- const windowsUser = cwd.match(/^([A-Za-z]:\\Users\\[^\\]+)/);- if (windowsUser?.[1]) {- return windowsUser[1];- }-- return undefined;-}-export function extractTerminalLinks(line: string): TerminalLinkMatch[] {const urlMatches = collectMatches(line, "url", URL_PATTERN, []);const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, urlMatches);@@ -203,22 +159,3 @@ export function isTerminalLinkActivation(? event.metaKey && !event.ctrlKey: event.ctrlKey && !event.metaKey;}--export function resolvePathLinkTarget(rawPath: string, cwd: string): string {- const position = splitFilePathPosition(rawPath);- const { path } = position;-- let resolvedPath = path;- if (path.startsWith("~/")) {- const home = inferHomeFromCwd(cwd);- if (home) {- const separator: "/" | "\\" = isWindowsPathStyle(home) ? "\\" : "/";- resolvedPath = joinPath(home, path.slice(2), separator);- }- } else if (!isAbsolutePath(path)) {- const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";- resolvedPath = joinPath(cwd, path, separator);- }-- return formatFilePathPosition({ ...position, path: resolvedPath });-}diff --git a/apps/web/src/themePalette.test.ts b/apps/web/src/themePalette.test.tsindex de26d531c6f..02f9e0b90ce 100644--- a/apps/web/src/themePalette.test.ts+++ b/apps/web/src/themePalette.test.ts@@ -33,6 +33,7 @@ import {IRIS_THEME,OCEAN_THEME,updateCustomTheme,+ updateThemeColorFamily,CUSTOM_THEMES_STORAGE_KEY,createVividThemeColors,getDefaultThemeColors,@@ -90,6 +91,68 @@ describe("theme files", () => {}});+ it("keeps built-in and standard search pairs readable and distinct", () => {+ const palettes = [+ getStandardThemeColors("light"),+ getStandardThemeColors("dark"),+ ...BUILT_IN_THEMES.flatMap((theme) => [theme.colors, ...Object.values(theme.variants ?? {})]),+ ];+ for (const colors of palettes) {+ expect(+ contrastRatio(colors.searchMatchForeground, colors.searchMatchBackground),+ ).toBeGreaterThanOrEqual(4.5);+ expect(+ contrastRatio(colors.searchMatchActiveForeground, colors.searchMatchActiveBackground),+ ).toBeGreaterThanOrEqual(4.5);+ expect(asHex(colors.searchMatchBackground)).not.toBe(+ asHex(colors.searchMatchActiveBackground),+ );+ }+ });++ it("round-trips custom search colours and fills them in for older theme files", () => {+ const legacy = parseThemeFile({+ version: THEME_FILE_VERSION,+ name: "Legacy",+ appearance: "dark",+ colors: { canvas: "#101010" },+ });+ expect(legacy.colors.searchMatchBackground).toBe(+ getDefaultThemeColors("dark").searchMatchBackground,+ );+ const theme = parseThemeFile({+ version: THEME_FILE_VERSION,+ name: "Search",+ appearance: "dark",+ colors: {+ searchMatchBackground: "#224466",+ searchMatchForeground: "#ffffff",+ searchMatchActiveBackground: "#aaddff",+ searchMatchActiveForeground: "#112233",+ },+ variants: { light: { searchMatchBackground: "#ddeeff", searchMatchForeground: "#112233" } },+ });+ const restored = parseThemeFile(JSON.parse(serializeThemeFile(theme)));+ expect(restored.colors).toEqual(theme.colors);+ expect(restored.variants).toEqual(theme.variants);+ });++ it.each(["searchMatchBackground", "searchMatchActiveBackground"] as const)(+ "editing %s derives readable text without changing the other match or warning colours",+ (role) => {+ const original = getDefaultThemeColors("dark");+ const foreground =+ role === "searchMatchBackground" ? "searchMatchForeground" : "searchMatchActiveForeground";+ for (const value of ["#ffffff", "#000000", "#33669980"]) {+ const updated = updateThemeColorFamily("dark", original, role, value);+ expect(contrastRatio(updated[foreground], updated[role])).toBeGreaterThanOrEqual(4.5);+ for (const key of Object.keys(original) as Array<keyof typeof original>) {+ if (key !== role && key !== foreground) expect(updated[key]).toBe(original[key]);+ }+ }+ },+ );+it("keeps stock dark controls in the neutral-black surface hierarchy", () => {expectThemeColors(getStandardThemeColors("dark"), {canvas: "#0a0a0a",@@ -155,6 +218,12 @@ describe("theme files", () => {);expect(colors.secondaryLabel).toBe(colors.textMuted);expect(contrastRatio(colors.accentForeground, colors.accent)).toBeGreaterThanOrEqual(4.5);+ expect(+ contrastRatio(colors.searchMatchForeground, colors.searchMatchBackground),+ ).toBeGreaterThanOrEqual(4.5);+ expect(+ contrastRatio(colors.searchMatchActiveForeground, colors.searchMatchActiveBackground),+ ).toBeGreaterThanOrEqual(4.5);expect(contrastRatio(colors.messageActionForeground, colors.messageAction),).toBeGreaterThanOrEqual(4.5);diff --git a/apps/web/src/themePalette.ts b/apps/web/src/themePalette.tsindex d4a1c4e8cc0..da9af454c5a 100644--- a/apps/web/src/themePalette.ts+++ b/apps/web/src/themePalette.ts@@ -743,6 +743,10 @@ export function createVividThemeColors(const mutedForeground = themeRgbToThemeColor(readableThemeText(mutedRgb, textRgb, 1, 4.6));const placeholder = themeRgbToThemeColor(readableThemeText(surfaceRaisedRgb, textRgb, 1, 4.6));+ // Keep matches visible even when an imported theme has no accent colour.+ const searchMatch = themeOklchToRgb(surfaceAt(0.22, Math.min(0.12, accent.C)));+ const searchMatchActive = themeOklchToRgb(surfaceAt(0.4, Math.min(0.18, accent.C)));+const actionHover: ThemeOklch = { ...action, L: action.L + (dark ? 0.06 : -0.06) };return {@@ -786,6 +790,10 @@ export function createVividThemeColors(messageActionHover: themeColor(actionHover),codeBackground: themeColor(codeBackground),codeForeground: themeRgbToThemeColor(textRgb),+ searchMatchBackground: themeRgbToThemeColor(searchMatch),+ searchMatchForeground: themeRgbToThemeColor(readableThemeForeground(searchMatch)),+ searchMatchActiveBackground: themeRgbToThemeColor(searchMatchActive),+ searchMatchActiveForeground: themeRgbToThemeColor(readableThemeForeground(searchMatchActive)),sidebar: themeColor(sidebar),sidebarForeground: foregroundOn(sidebarRgb),sidebarMutedForeground: themeRgbToThemeColor(standardMutedThemeText(sidebarRgb, textRgb)),@@ -1005,6 +1013,18 @@ export function updateThemeColorFamily(messageSurface: normalized,messageForeground: foregroundOn(selectedOnCanvas),};+ case "searchMatchBackground":+ return {+ ...colors,+ searchMatchBackground: colorOf(selectedOnCanvas),+ searchMatchForeground: foregroundOn(selectedOnCanvas),+ };+ case "searchMatchActiveBackground":+ return {+ ...colors,+ searchMatchActiveBackground: colorOf(selectedOnCanvas),+ searchMatchActiveForeground: foregroundOn(selectedOnCanvas),+ };case "codeBackground":return {...colors,@@ -1469,6 +1489,10 @@ const APP_THEME_VARIABLES: Readonly<Record<ThemeColorRole, string>> = {messageActionHover: "--app-theme-message-action-hover",codeBackground: "--app-theme-code-background",codeForeground: "--app-theme-code-foreground",+ searchMatchBackground: "--app-theme-search-match-background",+ searchMatchForeground: "--app-theme-search-match-foreground",+ searchMatchActiveBackground: "--app-theme-search-match-active-background",+ searchMatchActiveForeground: "--app-theme-search-match-active-foreground",sidebar: "--app-theme-sidebar",sidebarForeground: "--app-theme-sidebar-foreground",sidebarMutedForeground: "--app-theme-sidebar-muted-foreground",diff --git a/apps/web/src/vscodeThemeImport.test.ts b/apps/web/src/vscodeThemeImport.test.tsindex 03860b63148..624d11585f5 100644--- a/apps/web/src/vscodeThemeImport.test.ts+++ b/apps/web/src/vscodeThemeImport.test.ts@@ -292,6 +292,100 @@ describe("VS Code theme import", () => {contrastRatio(lightPlus.colors.placeholder, lightPlus.colors.surfaceRaised),).toBeLessThan(contrastRatio(lightPlus.colors.text, lightPlus.colors.surfaceRaised));});+ it("imports current and other find matches as independent background/text pairs", () => {+ const { colors } = parseVsCodeThemeFile({+ type: "dark",+ colors: {+ "editor.background": "#202020",+ "editor.findMatchBackground": "#663399",+ "editor.findMatchForeground": "#ffffff",+ "editor.findMatchHighlightBackground": "#bce4ff",+ "editor.findMatchHighlightForeground": "#17314a",+ },+ });++ expect(asHex(colors.searchMatchActiveBackground)).toBe("#663399");+ expect(asHex(colors.searchMatchActiveForeground)).toBe("#ffffff");+ expect(asHex(colors.searchMatchBackground)).toBe("#bce4ff");+ expect(asHex(colors.searchMatchForeground)).toBe("#17314a");+ });++ it("composites find backgrounds onto the canvas and foregrounds onto their match", () => {+ const { colors } = parseVsCodeThemeFile({+ type: "dark",+ colors: {+ "editor.background": "#202020",+ "editor.findMatchBackground": "#33669980",+ "editor.findMatchForeground": "#ffffffcc",+ "editor.findMatchHighlightBackground": "#ffcc0040",+ "editor.findMatchHighlightForeground": "#ffffff",+ },+ });++ expect(asHex(colors.searchMatchActiveBackground)).toBe("#2a435d");+ expect(asHex(colors.searchMatchActiveForeground)).toBe("#d4d9df");+ expect(asHex(colors.searchMatchBackground)).toBe("#584b18");+ expect(asHex(colors.searchMatchForeground)).toBe("#ffffff");+ });++ it("uses editor text when no find foreground is specified", () => {+ const { colors } = parseVsCodeThemeFile({+ type: "dark",+ colors: {+ "editor.background": "#101010",+ "editor.foreground": "#eeeeee",+ "editor.findMatchBackground": "#304050",+ "editor.findMatchHighlightBackground": "#403020",+ },+ });++ expect(asHex(colors.searchMatchActiveForeground)).toBe("#eeeeee");+ expect(asHex(colors.searchMatchForeground)).toBe("#eeeeee");+ });++ it.each(["light", "dark"])(+ "keeps missing or invalid find colours readable in %s themes",+ (type) => {+ const base = {+ "editor.background": type === "dark" ? "#101010" : "#fafafa",+ };+ const missing = parseVsCodeThemeFile({ type, colors: base }).colors;+ const invalid = parseVsCodeThemeFile({+ type,+ colors: {+ ...base,+ "editor.findMatchBackground": "not-a-colour",+ "editor.findMatchForeground": 42,+ "editor.findMatchHighlightBackground": null,+ "editor.findMatchHighlightForeground": "invalid",+ },+ }).colors;+ const unreadable = parseVsCodeThemeFile({+ type,+ colors: {+ ...base,+ "editor.findMatchBackground": "#ffffcc",+ "editor.findMatchForeground": "#ffffff",+ "editor.findMatchHighlightBackground": "#101020",+ "editor.findMatchHighlightForeground": "#111111",+ },+ }).colors;++ for (const colors of [missing, invalid, unreadable]) {+ expect(+ contrastRatio(colors.searchMatchForeground, colors.searchMatchBackground),+ ).toBeGreaterThanOrEqual(4.5);+ expect(+ contrastRatio(colors.searchMatchActiveForeground, colors.searchMatchActiveBackground),+ ).toBeGreaterThanOrEqual(4.5);+ }+ expect(invalid.searchMatchBackground).toBe(missing.searchMatchBackground);+ expect(invalid.searchMatchActiveBackground).toBe(missing.searchMatchActiveBackground);+ expect(missing.searchMatchBackground).not.toBe(missing.searchMatchActiveBackground);+ expect(missing.searchMatchBackground).not.toBe(missing.canvas);+ expect(missing.searchMatchActiveBackground).not.toBe(missing.canvas);+ },+ );it("fills every role the file omits with a readable derived value", () => {const theme = parseVsCodeThemeFile(VSCODE_DARK);diff --git a/apps/web/src/vscodeThemeImport.ts b/apps/web/src/vscodeThemeImport.tsindex 2d6ff7f6aa8..a02357d599f 100644--- a/apps/web/src/vscodeThemeImport.ts+++ b/apps/web/src/vscodeThemeImport.ts@@ -321,6 +321,12 @@ export function parseVsCodeThemeFile(value: unknown): ThemeDefinition {break;}}+ // Find overlays can cover prose, code, or message bubbles. Flatten them onto+ // the editor canvas so each imported foreground has one predictable surface.+ const searchMatchBackground =+ solidOver(canvas, "editor.findMatchHighlightBackground") ?? derived.searchMatchBackground;+ const searchMatchActiveBackground =+ solidOver(canvas, "editor.findMatchBackground") ?? derived.searchMatchActiveBackground;const overrides: Partial<Record<ThemeColorRole, string>> = {canvas: canvasHex,@@ -346,6 +352,22 @@ export function parseVsCodeThemeFile(value: unknown): ThemeDefinition {solidOver(canvas, "list.activeSelectionBackground", "list.hoverBackground") ??derived.accentSurface,codeBackground: solidOver(canvas, "textCodeBlock.background") ?? derived.codeBackground,+ searchMatchBackground,+ searchMatchForeground: readableOn(+ searchMatchBackground,+ derived.searchMatchForeground,+ "editor.findMatchHighlightForeground",+ "editor.foreground",+ "foreground",+ ),+ searchMatchActiveBackground,+ searchMatchActiveForeground: readableOn(+ searchMatchActiveBackground,+ derived.searchMatchActiveForeground,+ "editor.findMatchForeground",+ "editor.foreground",+ "foreground",+ ),sidebar: sidebarHex,sidebarForeground: readableOn(sidebarHex, derived.sidebarForeground, "sideBar.foreground"),sidebarBorder: solidOver(sidebar, "sideBar.border") ?? derived.sidebarBorder,diff --git a/docs/user/keybindings.md b/docs/user/keybindings.mdindex 2d7c786cc3f..5523b5aa3c9 100644--- a/docs/user/keybindings.md+++ b/docs/user/keybindings.md@@ -121,6 +121,14 @@ Combine keys with `!` for not, `&&` for and, `||` for or, and parentheses:{ "key": "mod+j", "command": "terminal.toggle", "when": "terminalOpen && !terminalFocus" }```+## Find in the current thread++`chat.find` searches conversation messages and proposed plans in the active thread. Entering a+query searches the entire thread, including older messages. Thread search requires server support;+update an older server to enable it. Select **Retry** if a search fails. It defaults to+`mod+f` outside terminals and previews. Press **Enter** or **Shift+Enter** to move between matches,+and **Escape** to close find.+## PrecedenceThe last rule whose key and condition both match wins, even if it belongs to adiff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex d9735deb681..e640c5143a2 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -63,10 +63,6 @@"types": "./src/markdownImages.ts","default": "./src/markdownImages.ts"},- "./markdown-links": {- "types": "./src/markdownLinks.ts",- "default": "./src/markdownLinks.ts"- },"./media-reference": {"types": "./src/mediaReference.ts","default": "./src/mediaReference.ts"@@ -79,18 +75,6 @@"types": "./src/mediaActions.ts","default": "./src/mediaActions.ts"},- "./codex-file-citations": {- "types": "./src/codexFileCitations.ts",- "default": "./src/codexFileCitations.ts"- },- "./codex-artifact-templates": {- "types": "./src/codexArtifactTemplates.ts",- "default": "./src/codexArtifactTemplates.ts"- },- "./codex-markdown-directives": {- "types": "./src/codexMarkdownDirectives.ts",- "default": "./src/codexMarkdownDirectives.ts"- },"./errors": {"types": "./src/errors/index.ts","default": "./src/errors/index.ts"@@ -412,17 +396,11 @@"@t3tools/contracts": "workspace:*","@t3tools/shared": "workspace:*","effect": "catalog:",- "mdast-util-directive": "^3.1.0",- "micromark-extension-directive": "^4.0.0",- "micromark-util-character": "^2.1.1",- "remark-parse": "^11.0.0",- "three": "0.180.0",- "unified": "^11.0.5"+ "three": "0.180.0"},"devDependencies": {"@effect/vitest": "catalog:","@types/three": "0.180.0",- "micromark-util-types": "^2.0.2","vite-plus": "catalog:"}}diff --git a/packages/client-runtime/src/markdownImages.ts b/packages/client-runtime/src/markdownImages.tsindex f4092674c5a..59a3228037b 100644--- a/packages/client-runtime/src/markdownImages.ts+++ b/packages/client-runtime/src/markdownImages.ts@@ -1,12 +1,11 @@-import { isWindowsAbsolutePath } from "@t3tools/shared/path";+import { isWindowsAbsolutePath, stripSlashPrefixedWindowsDrive } from "@t3tools/shared/path";import {normalizeMarkdownLinkDestination,- parseFileUrlHref,safeDecodeURIComponent,splitMarkdownLinkSearchAndHash,- stripSlashPrefixedWindowsDrive,-} from "./markdownLinks.ts";+} from "@t3tools/shared/markdownLinks";+import { parseFileUrlHref } from "@t3tools/shared/fileLinks";const DIRECT_IMAGE_SOURCE_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i;const URI_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/;diff --git a/packages/client-runtime/src/mediaReference.ts b/packages/client-runtime/src/mediaReference.tsindex f44ec90cd87..da98d4b7ee5 100644--- a/packages/client-runtime/src/mediaReference.ts+++ b/packages/client-runtime/src/mediaReference.ts@@ -1,6 +1,6 @@import { isWindowsAbsolutePath } from "@t3tools/shared/path";-import { safeDecodeURIComponent } from "./markdownLinks.ts";+import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks";/** The authored media location, never the temporary URL used to load its bytes. */export type MediaReference =diff --git a/packages/client-runtime/src/mediaSource.ts b/packages/client-runtime/src/mediaSource.tsindex 6c285e21ba9..5760536a722 100644--- a/packages/client-runtime/src/mediaSource.ts+++ b/packages/client-runtime/src/mediaSource.ts@@ -6,11 +6,9 @@ import {markdownImageSourceFragment,type MarkdownImageSource,} from "./markdownImages.ts";-import {- fileBasename,- splitFilePathPosition,- splitMarkdownLinkSearchAndHash,-} from "./markdownLinks.ts";+import { fileBasename } from "@t3tools/shared/path";+import { splitFilePathPosition } from "@t3tools/shared/fileLinks";+import { splitMarkdownLinkSearchAndHash } from "@t3tools/shared/markdownLinks";import {mediaFileReference,mediaReferenceFileName,diff --git a/packages/client-runtime/src/providerSkills.test.ts b/packages/client-runtime/src/providerSkills.test.tsindex d5c8933f0bf..1b9ca671d10 100644--- a/packages/client-runtime/src/providerSkills.test.ts+++ b/packages/client-runtime/src/providerSkills.test.ts@@ -4,11 +4,11 @@ import {ProviderInstanceId,type ServerProvider,} from "@t3tools/contracts";+import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";import { describe, expect, it } from "vite-plus/test";import {dedupeProviderSkillsByName,- formatProviderSkillDisplayName,getProviderSlashCommandsForSlashMenu,getProviderSkillsForSlashMenu,hasCompleteProviderWorkspaceSnapshot,diff --git a/packages/client-runtime/src/providerSkills.ts b/packages/client-runtime/src/providerSkills.tsindex 4d649cd19f1..fe69c371fc6 100644--- a/packages/client-runtime/src/providerSkills.ts+++ b/packages/client-runtime/src/providerSkills.ts@@ -7,29 +7,10 @@ import {export type ProviderSkillSourceKind = "app" | "repo" | "project" | "personal" | "system" | "other";-function titleCaseWords(value: string): string {- const words: string[] = [];- for (const segment of value.split(/[\s:_-]+/)) {- if (segment.length === 0) continue;- words.push(segment.charAt(0).toUpperCase() + segment.slice(1));- }- return words.join(" ");-}-function normalizePathSeparators(pathValue: string): string {return pathValue.replaceAll("\\", "/");}-export function formatProviderSkillDisplayName(- skill: Pick<ServerProviderSkill, "name" | "displayName">,-): string {- const displayName = skill.displayName?.trim();- if (displayName) {- return displayName;- }- return titleCaseWords(skill.name);-}-export function dedupeProviderSkillsByName(skills: ReadonlyArray<ServerProviderSkill>,): ServerProviderSkill[] {diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.tsindex 483dff47a4e..35a957e9d0f 100644--- a/packages/client-runtime/src/rpc/client.ts+++ b/packages/client-runtime/src/rpc/client.ts@@ -53,6 +53,7 @@ export type EnvironmentSubscriptionRpcTag =| typeof WS_METHODS.providerInstallSubscribe| typeof ORCHESTRATION_V2_WS_METHODS.subscribeShell| typeof ORCHESTRATION_V2_WS_METHODS.subscribeThread+ | typeof ORCHESTRATION_V2_WS_METHODS.searchThreadStream| typeof WS_METHODS.subscribeAuthAccess| typeof WS_METHODS.subscribeServerConfig| typeof WS_METHODS.subscribeServerLifecyclediff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.tsindex 9392ee2baab..04341a64373 100644--- a/packages/client-runtime/src/state/orchestration.ts+++ b/packages/client-runtime/src/state/orchestration.ts@@ -55,6 +55,18 @@ export function createOrchestrationEnvironmentAtoms<R, E>(label: "environment-data:orchestration:full-thread-diff",tag: ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff,}),+ threadFind: createEnvironmentRpcQueryAtomFamily(runtime, {+ label: "environment-data:orchestration:thread-find",+ tag: ORCHESTRATION_V2_WS_METHODS.searchThread,+ staleTimeMs: 0,+ idleTtlMs: 0,+ }),+ threadFindProgressive: createEnvironmentRpcSubscriptionAtomFamily(runtime, {+ label: "environment-data:orchestration:thread-find-progressive",+ tag: ORCHESTRATION_V2_WS_METHODS.searchThreadStream,+ completeWhen: (result) => result.complete !== false,+ idleTtlMs: 0,+ }),threadSearch: createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:orchestration:thread-search",tag: ORCHESTRATION_V2_WS_METHODS.searchThreads,diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.tsindex a6a502dfd1b..2d123c94568 100644--- a/packages/client-runtime/src/state/runtime.test.ts+++ b/packages/client-runtime/src/state/runtime.test.ts@@ -30,6 +30,7 @@ import {environmentRpcKey,createAtomCommandScheduler,createEnvironmentQueryAtomFamily,+ createEnvironmentSubscriptionAtomFamily,createRuntimeCommand,scheduleAtomCommandEffect,executeAtomCommand,@@ -291,6 +292,75 @@ describe("environmentRpcKey", () => {});});+describe("finite environment subscription lifecycle", () => {+ it.effect(+ "exposes early values and settles on the terminal value without waiting for a reconnect",+ () =>+ Effect.scoped(+ Effect.gen(function* () {+ const releaseFinal = yield* Deferred.make<void>();+ const sawEarly = yield* Deferred.make<void>();+ const sawFinal = yield* Deferred.make<void>();+ const closed = yield* Deferred.make<void>();+ const stream = Stream.concat(+ Stream.succeed({ complete: false, count: 1 }),+ Stream.fromEffect(+ Deferred.await(releaseFinal).pipe(Effect.as({ complete: true, count: 123 })),+ ),+ ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined)));+ // Following a registered environment normally remains open for replacements.+ const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({+ followStream: (_environmentId: EnvironmentId, source: typeof stream) =>+ Stream.concat(source, Stream.never),+ } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);+ const runtime = Atom.runtime(+ Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),+ );+ const family = createEnvironmentSubscriptionAtomFamily(runtime, {+ label: "test.finite-subscription",+ subscribe: () => stream,+ completeWhen: (value) => value.complete,+ idleTtlMs: 0,+ });+ const atom = family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined });+ const registry = AtomRegistry.make();+ const observed: Array<+ AsyncResult.AsyncResult<{ complete: boolean; count: number }, unknown>+ > = [];+ const unsubscribe = registry.subscribe(+ atom,+ (result) => {+ observed.push(result);+ if (AsyncResult.isSuccess(result)) {+ if (!result.value.complete) Deferred.doneUnsafe(sawEarly, Exit.void);+ if (result.value.complete && !result.waiting)+ Deferred.doneUnsafe(sawFinal, Exit.void);+ }+ },+ { immediate: true },+ );+ yield* Effect.addFinalizer(() =>+ Effect.sync(() => {+ unsubscribe();+ registry.dispose();+ }),+ );+ yield* Deferred.await(sawEarly);+ const early = registry.get(atom);+ expect(AsyncResult.isSuccess(early) && early.value.count).toBe(1);+ expect(early.waiting).toBe(true);+ yield* Deferred.succeed(releaseFinal, undefined);+ yield* Deferred.await(sawFinal);+ yield* Deferred.await(closed);+ const final = registry.get(atom);+ expect(AsyncResult.isSuccess(final) && final.value.count).toBe(123);+ expect(final.waiting).toBe(false);+ expect(observed.some((result) => AsyncResult.isFailure(result))).toBe(false);+ }),+ ),+ );+});+describe("environment query lifecycle", () => {it.effect("retries an interrupted query without exposing a failure during session replacement",diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.tsindex 27a2348f4d4..fb38e84d309 100644--- a/packages/client-runtime/src/state/runtime.ts+++ b/packages/client-runtime/src/state/runtime.ts@@ -78,6 +78,7 @@ interface EnvironmentSubscriptionAtomOptions<Input, A, E, R> {readonly sensitiveInput?: boolean;readonly label: string;readonly subscribe: (input: Input) => Stream.Stream<A, E, R>;+ readonly completeWhen?: (value: A) => boolean;readonly idleTtlMs?: number;}@@ -618,7 +619,11 @@ export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(const family = Atom.family((key: string) => {const target = parseEnvironmentRpcKey<Input>(key);return runtime- .atom(followStreamInEnvironment(target.environmentId, options.subscribe(target.input)))+ .atom(+ followStreamInEnvironment(target.environmentId, options.subscribe(target.input)).pipe(+ options.completeWhen ? Stream.takeUntil(options.completeWhen) : (stream) => stream,+ ),+ ).pipe(Atom.setIdleTTL(options.idleTtlMs ?? 5 * 60_000),Atom.withLabel(@@ -705,6 +710,7 @@ export function createEnvironmentRpcSubscriptionAtomFamily<readonly label: string;readonly tag: TTag;readonly idleTtlMs?: number;+ readonly completeWhen?: (value: B) => boolean;readonly transform?: (stream: Stream.Stream<EnvironmentRpcStreamValue<TTag>,@@ -720,6 +726,7 @@ export function createEnvironmentRpcSubscriptionAtomFamily<) {return createEnvironmentSubscriptionAtomFamily(runtime, {label: options.label,+ ...(options.completeWhen === undefined ? {} : { completeWhen: options.completeWhen }),...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),subscribe: (input: EnvironmentRpcInput<TTag>) => {const stream = subscribe(options.tag, input);diff --git a/packages/client-runtime/src/state/subagentDisplay.ts b/packages/client-runtime/src/state/subagentDisplay.tsindex 0a456e7a2dd..480cc8e0c7e 100644--- a/packages/client-runtime/src/state/subagentDisplay.ts+++ b/packages/client-runtime/src/state/subagentDisplay.ts@@ -5,7 +5,7 @@ import type {ServerProvider,} from "@t3tools/contracts";import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model";-import { fileBasename } from "../markdownLinks.ts";+import { fileBasename } from "@t3tools/shared/path";import { isTerminalSubagentStatus } from "./subagentRuntime.ts";/** Summarizes one adjacent group, without changing its member identities or order. */diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.tsindex f237f1ce943..0bb601b643b 100644--- a/packages/client-runtime/src/state/threadCommands.ts+++ b/packages/client-runtime/src/state/threadCommands.ts@@ -97,6 +97,7 @@ import * as ThreadHistoryController from "./threadHistoryController.ts";export type LoadEarlierThreadHistoryInput = {readonly threadId: ThreadId;+ readonly throughEntryId?: string;};export type {@@ -387,6 +388,7 @@ export function createThreadEnvironmentAtoms<R, E>(return yield* controller.value.loadEarlier(supervisor.target.environmentId,input.threadId,+ input.throughEntryId,);}),scheduler,diff --git a/packages/client-runtime/src/state/threadHistoryController.ts b/packages/client-runtime/src/state/threadHistoryController.tsindex 81cd93b1b54..4319d1c4215 100644--- a/packages/client-runtime/src/state/threadHistoryController.ts+++ b/packages/client-runtime/src/state/threadHistoryController.ts@@ -13,7 +13,7 @@ export type ThreadHistoryLoadEarlierResult =| { readonly _tag: "error"; readonly message: string };export type ThreadHistoryHandler = {- readonly loadEarlier: () => Effect.Effect<ThreadHistoryLoadEarlierResult>;+ readonly loadEarlier: (throughEntryId?: string) => Effect.Effect<ThreadHistoryLoadEarlierResult>;};/**@@ -42,6 +42,7 @@ export class ThreadHistoryController extends Context.Service<readonly loadEarlier: (environmentId: EnvironmentId,threadId: ThreadId,+ throughEntryId?: string,) => Effect.Effect<ThreadHistoryLoadEarlierResult>;}>()("@t3tools/client-runtime/state/threadHistoryController") {}@@ -78,14 +79,14 @@ export const layer: Layer.Layer<ThreadHistoryController> = Layer.effect(next.delete(key);return next;}),- loadEarlier: (environmentId, threadId) =>+ loadEarlier: (environmentId, threadId, throughEntryId) =>Ref.get(handlers).pipe(Effect.flatMap((current) => {const handler = current.get(threadKey({ environmentId, threadId }));if (handler === undefined) {return Effect.succeed({ _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult);}- return handler.loadEarlier();+ return handler.loadEarlier(throughEntryId);}),),});diff --git a/packages/client-runtime/src/state/threadHistoryHttp.ts b/packages/client-runtime/src/state/threadHistoryHttp.tsindex a2416bda26f..b83cb6f20c3 100644--- a/packages/client-runtime/src/state/threadHistoryHttp.ts+++ b/packages/client-runtime/src/state/threadHistoryHttp.ts@@ -19,6 +19,8 @@ export const fetchEnvironmentThreadHistoryPage = Effect.fn(readonly prepared: PreparedConnection;readonly threadId: ThreadId;readonly cursor: string;+ readonly throughEntryId?: string | undefined;+ readonly view?: "conversation" | "activity" | undefined;readonly signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>;readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;readonly timeoutMs?: number;@@ -33,7 +35,11 @@ export const fetchEnvironmentThreadHistoryPage = Effect.fn(request: ({ client, headers }) =>client.threadHistoryPage({params: { threadId: input.threadId },- query: { cursor: input.cursor },+ query: {+ cursor: input.cursor,+ ...(input.view === undefined ? {} : { view: input.view }),+ ...(input.throughEntryId === undefined ? {} : { throughEntryId: input.throughEntryId }),+ },headers: withOrchestrationProtocolHeader(headers),}),});diff --git a/packages/client-runtime/src/state/threadHistoryMerge.test.ts b/packages/client-runtime/src/state/threadHistoryMerge.test.tsindex 0952e3eedd5..56ef3d235df 100644--- a/packages/client-runtime/src/state/threadHistoryMerge.test.ts+++ b/packages/client-runtime/src/state/threadHistoryMerge.test.ts@@ -45,6 +45,51 @@ function row(index: number): OrchestrationV2ProjectedTurnItem {}describe("threadHistoryMerge", () => {+ it("fills activity around partial messages in canonical order and preserves live edits", () => {+ const initial = { ...v2Projection, turnItems: [row(4).item], visibleTurnItems: [row(4)] };+ const preview = [row(1), row(3)];+ const partial = mergeOlderHistoryIntoProjection(initial, preview);+ const updated = { ...row(1), item: { ...row(1).item, title: "newer live title" } };+ const live = {+ ...partial,+ visibleTurnItems: partial.visibleTurnItems.map((entry) =>+ entry.sourceItemId === updated.sourceItemId ? updated : entry,+ ),+ turnItems: partial.turnItems.map((item) =>+ item.id === updated.item.id ? updated.item : item,+ ),+ };+ const complete = mergeOlderHistoryIntoProjection(live, [row(0), row(1), row(2), row(3)]);+ expect(complete.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([+ "item-0",+ "item-1",+ "item-2",+ "item-3",+ "item-4",+ ]);+ expect(complete.visibleTurnItems[1]?.item).toBe(updated.item);+ expect(complete.visibleTurnItems.map((entry) => entry.position)).toEqual([0, 1, 2, 3, 4]);+ expect(new Set(complete.turnItems.map((item) => item.id)).size).toBe(5);+ const hidden = {+ ...partial,+ visibleTurnItems: partial.visibleTurnItems.filter(+ (entry) => entry.sourceItemId !== preview[0]!.sourceItemId,+ ),+ };+ const hiddenComplete = mergeOlderHistoryIntoProjection(hidden, [+ row(0),+ row(1),+ row(2),+ row(3),+ ]);+ expect(hiddenComplete.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([+ "item-0",+ "item-2",+ "item-3",+ "item-4",+ ]);+ });+it("prepends older rows and dedupes by source identity", () => {const recent = [row(2), row(3)];const projection = {@@ -69,6 +114,32 @@ describe("threadHistoryMerge", () => {]);});+ it("fills inherited activity without confusing identical item IDs from different source threads", () => {+ const inherited = (index: number) => ({+ ...row(index),+ visibility: "inherited" as const,+ sourceThreadId: "fork-source" as never,+ });+ const local = row(1);+ const preview = { ...inherited(1), item: { ...row(1).item, title: "newer inherited title" } };+ const projection = {+ ...v2Projection,+ turnItems: [local.item],+ visibleTurnItems: [preview, local],+ };+ const merged = mergeOlderHistoryIntoProjection(projection, [inherited(0), inherited(1)]);+ expect(+ merged.visibleTurnItems.map((entry) => [entry.sourceThreadId, entry.sourceItemId]),+ ).toEqual([+ ["fork-source", "item-0"],+ ["fork-source", "item-1"],+ [v2ThreadId, "item-1"],+ ]);+ expect(merged.visibleTurnItems[1]?.item).toBe(preview.item);+ expect(merged.turnItems).toEqual([local.item]);+ expect(mergeOlderHistoryIntoProjection(merged, [inherited(0), inherited(1)])).toBe(merged);+ });+it("retains live rows that arrived after the older page was fetched", () => {const live = [row(5), row(6)];const projection = {diff --git a/packages/client-runtime/src/state/threadHistoryMerge.ts b/packages/client-runtime/src/state/threadHistoryMerge.tsindex 6210686ec07..ef8bd219b9e 100644--- a/packages/client-runtime/src/state/threadHistoryMerge.ts+++ b/packages/client-runtime/src/state/threadHistoryMerge.ts@@ -1,7 +1,6 @@import type {OrchestrationV2ProjectedTurnItem,OrchestrationV2ThreadProjection,- OrchestrationV2TurnItem,} from "@t3tools/contracts";import { isOrchestrationV2TurnItemVisible } from "@t3tools/shared/orchestrationV2Timeline";@@ -73,62 +72,61 @@ export function mergeOlderHistoryIntoProjection(return projection;}- const existingKeys = new Set(projection.visibleTurnItems.map(projectedItemKey));- const turnItemById = new Map<string, OrchestrationV2TurnItem>();- for (const item of projection.turnItems) {- turnItemById.set(String(item.id), item);- }- const prepended: OrchestrationV2ProjectedTurnItem[] = [];+ const currentByKey = new Map(+ projection.visibleTurnItems.map((row) => [projectedItemKey(row), row]),+ );+ const turnItemById = new Map(projection.turnItems.map((item) => [String(item.id), item]));+ const pageKeys = new Set<string>();+ const page: OrchestrationV2ProjectedTurnItem[] = [];for (const pageRow of olderItems) {- let row = pageRow;- const key = projectedItemKey(row);- if (existingKeys.has(key)) {- continue;- }- if (row.visibility === "local" || row.sourceThreadId === projection.thread.id) {+ const key = projectedItemKey(pageRow);+ if (pageKeys.has(key)) continue;+ let row = currentByKey.get(key) ?? pageRow;+ if (+ !currentByKey.has(key) &&+ (row.visibility === "local" || row.sourceThreadId === projection.thread.id)+ ) {const currentItem = turnItemById.get(String(row.sourceItemId));+ // Hidden live items stay hidden. Cold snapshots also retain interrupt+ // requests outside the visible window; paging may reveal those requests.if (currentItem !== undefined) {- // A live event may have hidden this item while the page was in flight.- // Do not resurrect the stale page copy. Retained interrupt requests are- // the exception: they intentionally exist outside the bounded visible- // window and should become visible when their history page arrives.- if (currentItem.type !== "run_interrupt_request") {- continue;- }if (+ currentItem.type !== "run_interrupt_request" ||!isOrchestrationV2TurnItemVisible({item: currentItem,runs: projection.runs,attempts: projection.attempts,items: projection.turnItems,})- ) {+ )continue;- }row = { ...row, item: currentItem };}}- existingKeys.add(key);- prepended.push(row);+ pageKeys.add(key);+ page.push(row);+ if (+ (row.visibility === "local" || row.sourceThreadId === projection.thread.id) &&+ !turnItemById.has(String(row.sourceItemId))+ )+ turnItemById.set(String(row.sourceItemId), row.item);}- if (prepended.length === 0) {+ if (page.length === 0) return projection;+ // Server page order fills gaps between rows from a partial conversation load.+ // Existing rows supply live values; rows outside this range keep their order.+ const visible = [+ ...page,+ ...projection.visibleTurnItems.filter((row) => !pageKeys.has(projectedItemKey(row))),+ ];+ if (+ visible.length === projection.visibleTurnItems.length &&+ visible.every((row, index) => row === projection.visibleTurnItems[index])+ )return projection;- }-- const visibleTurnItems = renumberVisible([...prepended, ...projection.visibleTurnItems]);-- for (const row of prepended) {- if (row.visibility === "local" || row.sourceThreadId === projection.thread.id) {- if (!turnItemById.has(String(row.sourceItemId))) {- turnItemById.set(String(row.sourceItemId), row.item);- }- }- }-return {...projection,turnItems: [...turnItemById.values()],- visibleTurnItems,+ visibleTurnItems: renumberVisible(visible),};}diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.tsindex d6cbbf6a7f4..b78377b2b1e 100644--- a/packages/client-runtime/src/state/threads-sync.test.ts+++ b/packages/client-runtime/src/state/threads-sync.test.ts@@ -254,7 +254,8 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (oreturn {threadState,- loadEarlier: () => historyController.loadEarlier(TARGET.environmentId, THREAD_ID),+ loadEarlier: (throughEntryId?: string) =>+ historyController.loadEarlier(TARGET.environmentId, THREAD_ID, throughEntryId),inputs,observed,latest,@@ -780,6 +781,7 @@ describe("EnvironmentThreads", () => {const harness = yield* makeHarness({historyHttpClient: HttpClient.make((request, url) => {expect(url.searchParams.get("cursor")).toBe("socket-history-cursor");+ expect(url.searchParams.get("throughEntryId")).toBe(olderItem.id);return Effect.succeed(HttpClientResponse.fromWeb(request,@@ -837,7 +839,7 @@ describe("EnvironmentThreads", () => {hasMoreHistory: true,latestLocalTurnOrdinal: 47,});- expect(yield* harness.loadEarlier()).toEqual({ _tag: "loaded" });+ expect(yield* harness.loadEarlier(olderItem.id)).toEqual({ _tag: "loaded" });const expanded = yield* SubscriptionRef.get(harness.threadState);expect(Option.getOrThrow(expanded.data).turnItems.some((item) => item.id === olderItem.id),@@ -846,6 +848,139 @@ describe("EnvironmentThreads", () => {}),);+ it.effect.each(["complete", "replacement snapshot", "retry"] as const)(+ "progressively reveals conversation history before activity, then handles %s",+ (mode) =>+ Effect.gen(function* () {+ const common = {+ threadId: THREAD_ID,+ runId: null,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ status: "completed",+ title: null,+ startedAt: "2026-06-20T00:00:00.000Z",+ completedAt: "2026-06-20T00:00:00.000Z",+ updatedAt: "2026-06-20T00:00:00.000Z",+ };+ const message = {+ ...common,+ id: "item:older-message",+ ordinal: 1,+ type: "assistant_message",+ messageId: "message:older",+ text: "COD4 result",+ streaming: false,+ };+ const activity = {+ ...common,+ id: "item:older-command",+ ordinal: 2,+ type: "command_execution",+ input: "pwd",+ output: "",+ exitCode: 0,+ };+ const projected = (item: typeof message | typeof activity, position: number) => ({+ position,+ visibility: "local",+ sourceThreadId: THREAD_ID,+ sourceItemId: item.id,+ item,+ });+ const activityStarted = yield* Deferred.make<void>();+ const releaseActivity = yield* Deferred.make<void>();+ let activityRequests = 0;+ const harness = yield* makeHarness({+ historyHttpClient: HttpClient.make((request, url) =>+ Effect.gen(function* () {+ expect(url.searchParams.get("cursor")).toBe("progressive-cursor");+ const conversationOnly = url.searchParams.get("view") === "conversation";+ if (!conversationOnly && activityRequests++ === 0) {+ yield* Deferred.succeed(activityStarted, undefined);+ yield* Deferred.await(releaseActivity);+ if (mode === "retry")+ return HttpClientResponse.fromWeb(+ request,+ new Response("Activity unavailable", { status: 503 }),+ );+ }+ return HttpClientResponse.fromWeb(+ request,+ Response.json({+ snapshotSequence: 14,+ items: conversationOnly+ ? [projected(message, 0)]+ : [projected(message, 0), projected(activity, 1)],+ nextCursor: "next-cursor",+ hasMoreHistory: true,+ }),+ );+ }),+ ),+ });+ yield* Queue.offer(harness.inputs, {+ ...snapshot(BASE_PROJECTION, 14),+ historyCursor: "progressive-cursor",+ hasMoreHistory: true,+ latestLocalTurnOrdinal: 47,+ payloadBudgetExceeded: false,+ });+ yield* awaitThreadState(+ harness.observed,+ (state) => state.history.historyCursor === "progressive-cursor",+ );+ const loading = yield* harness.loadEarlier(message.messageId).pipe(Effect.forkScoped);+ yield* Deferred.await(activityStarted);+ const preview = yield* SubscriptionRef.get(harness.threadState);+ expect(preview.history).toMatchObject({+ loading: true,+ historyCursor: "progressive-cursor",+ expanded: true,+ });+ expect(+ Option.getOrThrow(preview.data).visibleTurnItems.map((row) => row.sourceItemId),+ ).toEqual([message.id]);+ if (mode === "replacement snapshot") {+ yield* Queue.offer(harness.inputs, snapshot(BASE_PROJECTION, 15));+ yield* awaitThreadState(+ harness.observed,+ (state) => state.history.historyCursor === null,+ );+ }+ yield* Deferred.succeed(releaseActivity, undefined);+ const result = yield* Fiber.join(loading);+ if (mode === "replacement snapshot") {+ expect(result).toEqual({ _tag: "noop" });+ const state = yield* SubscriptionRef.get(harness.threadState);+ expect(Option.getOrThrow(state.data).visibleTurnItems).toEqual(+ BASE_PROJECTION.visibleTurnItems,+ );+ expect(state.history.historyCursor).toBeNull();+ return;+ }+ if (mode === "retry") {+ expect(result._tag).toBe("error");+ // The ordinary load-earlier button must also finish a failed search load.+ expect(yield* harness.loadEarlier()).toEqual({ _tag: "loaded" });+ } else expect(result).toEqual({ _tag: "loaded" });+ const complete = yield* SubscriptionRef.get(harness.threadState);+ expect(complete.history).toMatchObject({+ loading: false,+ historyCursor: "next-cursor",+ error: null,+ latestLocalTurnOrdinal: 47,+ });+ expect(+ Option.getOrThrow(complete.data).visibleTurnItems.map((row) => row.sourceItemId),+ ).toEqual([message.id, activity.id]);+ expect(Option.getOrThrow(complete.data).turnItems).toHaveLength(2);+ }),+ );+it.effect("restores compact socket snapshot turnItems before reducing and caching", () =>Effect.gen(function* () {const at = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.tsindex 5c64c41b1d0..a6e31cf40c4 100644--- a/packages/client-runtime/src/state/threads.ts+++ b/packages/client-runtime/src/state/threads.ts@@ -634,7 +634,9 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make);});- const loadEarlier = Effect.fn("EnvironmentThreadState.loadEarlier")(function* () {+ const loadEarlier = Effect.fn("EnvironmentThreadState.loadEarlier")(function* (+ throughEntryId?: string,+ ) {const current = yield* SubscriptionRef.get(state);if (current.status === "deleted" ||@@ -657,117 +659,81 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make: history,);+ const failLoad = (message: string) =>+ SubscriptionRef.modify(+ state,+ (+ latest,+ ): readonly [+ ThreadHistoryController.ThreadHistoryLoadEarlierResult,+ EnvironmentThreadState,+ ] =>+ isActiveHistoryRequestCursor(requestCursor, latest.history)+ ? [+ { _tag: "error", message },+ {+ ...latest,+ history: { ...latest.history, loading: false, error: message },+ },+ ]+ : [{ _tag: "noop" }, latest],+ );+const runLoad = Effect.gen(function* () {const preparedOption = yield* SubscriptionRef.get(supervisor.prepared);- if (Option.isNone(preparedOption) || Option.isNone(httpClient)) {- const message = "Environment is not connected.";- const stillCurrent = yield* SubscriptionRef.modify(- state,- (latest): readonly [boolean, EnvironmentThreadState] => {- if (!isActiveHistoryRequestCursor(requestCursor, latest.history)) {- return [false, latest];- }- return [- true,- {- ...latest,- history: { ...latest.history, loading: false, error: message },- },- ];- },- );- if (!stillCurrent) {- return { _tag: "noop" } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;- }- return {- _tag: "error",- message,- } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;- }-- const pageResult = yield* fetchEnvironmentThreadHistoryPage({- prepared: preparedOption.value,- threadId,- cursor: requestCursor,- signer: dpopSigner,- remoteAuthorization,- }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient.value), Effect.result);-- if (Result.isFailure(pageResult)) {- const message = formatHistoryError(pageResult.failure);- // Only mark error when this request's cursor is still active. Leave- // stream/status/error alone so concurrent live updates stay intact.- const stillCurrent = yield* SubscriptionRef.modify(- state,- (latest): readonly [boolean, EnvironmentThreadState] => {- if (!isActiveHistoryRequestCursor(requestCursor, latest.history)) {- return [false, latest];- }- return [- true,- {- ...latest,- history: { ...latest.history, loading: false, error: message },- },- ];- },- );- if (!stillCurrent) {- return { _tag: "noop" } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;- }- return {- _tag: "error",- message,- } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;- }-- const page = pageResult.success;- const waiting = yield* Ref.get(awaitingCompletion);- // Single atomic merge against whatever is current after the await so a- // concurrent applyItem cannot be clobbered by a stale get/set pair.- return yield* applyLock.withPermits(1)(- SubscriptionRef.modify(- state,- (- latest,- ): readonly [- ThreadHistoryController.ThreadHistoryLoadEarlierResult,- EnvironmentThreadState,- ] => {- // Stale page: socket/full snapshot or newer bounded install changed the- // progressive cursor while this request was in flight. Never mutate the- // replacement meta (including deleted/empty installs).- if (!isActiveHistoryRequestCursor(requestCursor, latest.history)) {- return [{ _tag: "noop" }, latest];- }- if (Option.isNone(latest.data) || latest.status === "deleted") {+ if (Option.isNone(preparedOption) || Option.isNone(httpClient))+ return yield* failLoad("Environment is not connected.");++ const views =+ throughEntryId === undefined ? [undefined] : ["conversation" as const, undefined];+ for (const view of views) {+ const pageResult = yield* fetchEnvironmentThreadHistoryPage({+ prepared: preparedOption.value,+ threadId,+ cursor: requestCursor,+ throughEntryId,+ view,+ signer: dpopSigner,+ remoteAuthorization,+ }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient.value), Effect.result);+ if (Result.isFailure(pageResult))+ return yield* failLoad(formatHistoryError(pageResult.failure));+ const page = pageResult.success;+ const complete = view === undefined;+ const waiting = yield* Ref.get(awaitingCompletion);+ // Both stages merge against live state under the same lock. Only the+ // complete page advances the cursor and releases the loading indicator.+ const result = yield* applyLock.withPermits(1)(+ SubscriptionRef.modify(+ state,+ (+ latest,+ ): readonly [+ ThreadHistoryController.ThreadHistoryLoadEarlierResult,+ EnvironmentThreadState,+ ] => {+ if (!isActiveHistoryRequestCursor(requestCursor, latest.history))+ return [{ _tag: "noop" }, latest];+ if (Option.isNone(latest.data) || latest.status === "deleted")+ return [{ _tag: "noop" }, { ...latest, history: EMPTY_THREAD_HISTORY_META }];return [- { _tag: "noop" },+ { _tag: "loaded" },{...latest,- history: EMPTY_THREAD_HISTORY_META,+ data: Option.some(mergeOlderHistoryIntoProjection(latest.data.value, page.items)),+ status: complete && waiting ? "synchronizing" : latest.status,+ history: complete+ ? applyHistoryPageMeta(latest.history, page)+ : { ...latest.history, expanded: true },},];- }-- const merged = mergeOlderHistoryIntoProjection(latest.data.value, page.items);- const history = applyHistoryPageMeta(latest.history, page);- return [- { _tag: "loaded" },- {- ...latest,- data: Option.some(merged),- status: waiting- ? ("synchronizing" as const)- : latest.status === "live"- ? ("live" as const)- : latest.status,- history,- },- ];- },- ).pipe(Effect.tap(() => remember)),- );+ },+ ),+ );+ if (result._tag !== "loaded") return result;+ if (complete) yield* remember;+ }+ return { _tag: "loaded" } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;});// On Effect interruption only: clear loading when this request cursor is@@ -785,7 +751,8 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.makeif (Option.isSome(historyController)) {const scope = yield* Scope.Scope;const registration = yield* historyController.value.register(environmentId, threadId, {- loadEarlier: () => loadEarlier().pipe(Effect.forkIn(scope), Effect.flatMap(Fiber.join)),+ loadEarlier: (throughEntryId) =>+ loadEarlier(throughEntryId).pipe(Effect.forkIn(scope), Effect.flatMap(Fiber.join)),});yield* Effect.addFinalizer(() => historyController.value.unregister(registration));}diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.tsindex b74affb8621..e60db4527a9 100644--- a/packages/contracts/src/environmentHttp.ts+++ b/packages/contracts/src/environmentHttp.ts@@ -594,6 +594,8 @@ const EnvironmentOrchestrationThreadBoundedSnapshotQuery = Schema.Struct({const EnvironmentOrchestrationThreadHistoryQuery = Schema.Struct({cursor: TrimmedNonEmptyString,+ throughEntryId: Schema.optional(TrimmedNonEmptyString),+ view: Schema.optional(Schema.Literals(["conversation", "activity"])),});const EnvironmentOrchestrationThreadHistoryErrors = [diff --git a/packages/contracts/src/keybindings.test.ts b/packages/contracts/src/keybindings.test.tsindex 429d5d5fb49..1491fbe482b 100644--- a/packages/contracts/src/keybindings.test.ts+++ b/packages/contracts/src/keybindings.test.ts@@ -101,6 +101,12 @@ it.effect("parses keybinding rules", () =>});assert.strictEqual(parsedLocal.command, "chat.newLocal");+ const parsedFind = yield* decode(KeybindingRule, {+ key: "mod+f",+ command: "chat.find",+ });+ assert.strictEqual(parsedFind.command, "chat.find");+const parsedModelPickerToggle = yield* decode(KeybindingRule, {key: "mod+shift+m",command: "modelPicker.toggle",diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.tsindex 20bf0b90138..04c3acab803 100644--- a/packages/contracts/src/keybindings.ts+++ b/packages/contracts/src/keybindings.ts@@ -100,6 +100,7 @@ export const STATIC_KEYBINDING_COMMANDS = ["chat.new","chat.newLocal","chat.newWithoutProject",+ "chat.find","editor.openFavorite","usage.cost","usage.tokens",diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex 8d9763844e1..b1c56457ef0 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -3138,6 +3138,8 @@ export const ORCHESTRATION_V2_WS_METHODS = {getTurnDiff: "orchestration.getTurnDiff",getFullThreadDiff: "orchestration.getFullThreadDiff",searchThreads: "orchestration.searchThreads",+ searchThread: "orchestration.searchThread",+ searchThreadStream: "orchestration.searchThreadStream",getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot",getThreadProjection: "orchestration.getThreadProjection",getWorkflowScript: "orchestration.getWorkflowScript",@@ -3498,7 +3500,67 @@ export class OrchestrationGetWorkflowScriptError extends Schema.TaggedError<Orch}}+export const OrchestrationV2SearchThreadInput = Schema.Struct({+ threadId: ThreadId,+ // Match the skill labels displayed by this client, including custom display names.+ skills: Schema.optionalKey(+ Schema.Array(+ Schema.Struct({+ name: Schema.String.check(Schema.isMaxLength(200)),+ displayName: Schema.optional(Schema.String.check(Schema.isMaxLength(200))),+ }),+ ).check(Schema.isMaxLength(1_000)),+ ),+ query: TrimmedNonEmptyString.check(Schema.isMaxLength(200)),+ index: Schema.optionalKey(NonNegativeInt),+ // Select relative to an entry identity so updates before it do not shift navigation.+ offset: Schema.optionalKey(Schema.Int),+ start: Schema.optionalKey(+ Schema.Struct({ entryId: TrimmedNonEmptyString, occurrence: NonNegativeInt }),+ ),+});+export type OrchestrationV2SearchThreadInput = typeof OrchestrationV2SearchThreadInput.Type;++export const OrchestrationV2ThreadFindMatch = Schema.Struct({+ entryId: TrimmedNonEmptyString,+ runId: Schema.NullOr(RunId),+ occurrence: NonNegativeInt,+});+export const OrchestrationV2SearchThreadResult = Schema.Struct({+ // Omitted by older servers. An early match has no final ordinal or total yet.+ complete: Schema.optionalKey(Schema.Boolean),+ snapshotSequence: NonNegativeInt,+ totalMatches: NonNegativeInt,+ activeIndex: NonNegativeInt,+ match: Schema.NullOr(OrchestrationV2ThreadFindMatch),+ // Counts and identities around the selection let clients step without another round trip.+ navigation: Schema.optionalKey(+ Schema.Array(+ Schema.Struct({+ entryId: TrimmedNonEmptyString,+ runId: Schema.NullOr(RunId),+ startIndex: NonNegativeInt,+ count: NonNegativeInt,+ }),+ ).check(Schema.isMaxLength(17)),+ ),+});+export type OrchestrationV2SearchThreadResult = typeof OrchestrationV2SearchThreadResult.Type;++export class OrchestrationV2SearchThreadError extends Schema.TaggedError<OrchestrationV2SearchThreadError>()(+ "OrchestrationV2SearchThreadError",+ { cause: Schema.Defect() },+) {+ override get message(): string {+ return "Could not search this thread. Please retry.";+ }+}+export const OrchestrationV2RpcSchemas = {+ searchThread: {+ input: OrchestrationV2SearchThreadInput,+ output: OrchestrationV2SearchThreadResult,+ },dispatchCommand: {input: OrchestrationV2Command,output: OrchestrationV2DispatchCommandResult,diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 20645ac4755..875223bfd1c 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -1,3 +1,8 @@+import {+ OrchestrationV2SearchThreadError,+ OrchestrationV2SearchThreadInput,+ OrchestrationV2SearchThreadResult,+} from "./orchestrationV2.ts";import { OrchestrationDispatchCommandError } from "./orchestrationDispatch.ts";import {McpAppCallToolInput,@@ -1565,6 +1570,22 @@ const WsOrchestrationV2GetFullThreadDiffRpc = Rpc.make(},);+const WsOrchestrationV2SearchThreadRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.searchThread, {+ payload: OrchestrationV2SearchThreadInput,+ success: OrchestrationV2SearchThreadResult,+ error: Schema.Union([OrchestrationV2SearchThreadError, EnvironmentAuthorizationError]),+});++const WsOrchestrationV2SearchThreadStreamRpc = Rpc.make(+ ORCHESTRATION_V2_WS_METHODS.searchThreadStream,+ {+ payload: OrchestrationV2SearchThreadInput,+ success: OrchestrationV2SearchThreadResult,+ error: Schema.Union([OrchestrationV2SearchThreadError, EnvironmentAuthorizationError]),+ stream: true,+ },+);+const WsOrchestrationV2SearchThreadsRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.searchThreads, {payload: OrchestrationSearchThreadsInput,success: OrchestrationSearchThreadsResult,@@ -1957,6 +1978,8 @@ export const WsRpcGroup = RpcGroup.make(WsOrchestrationV2GetTurnDiffRpc,WsOrchestrationV2GetFullThreadDiffRpc,WsOrchestrationV2SearchThreadsRpc,+ WsOrchestrationV2SearchThreadRpc,+ WsOrchestrationV2SearchThreadStreamRpc,WsOrchestrationV2GetArchivedShellSnapshotRpc,WsOrchestrationV2GetThreadProjectionRpc,WsOrchestrationV2LaunchThreadRpc,diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.tsindex c46c8b732a6..5e33f1aa4c9 100644--- a/packages/contracts/src/server.ts+++ b/packages/contracts/src/server.ts@@ -669,6 +669,8 @@ export const ServerConfig = Schema.Struct({threadSnapshotPagination: Schema.optionalKey(Schema.Boolean),/** Whether thread reads accept the reasoningMessages opt-in. */reasoningMessages: Schema.optionalKey(Schema.Boolean),+ threadFind: Schema.optionalKey(Schema.Boolean),+ threadFindProgressive: Schema.optionalKey(Schema.Boolean),/*** Folder behind this environment's Scratch project, for threads that need* no repository. Present only on servers that answer projects.ensureScratchdiff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 4025994af07..697dbeb81e3 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -407,6 +407,54 @@"types": "./src/codexAuthHandoff.ts","import": "./src/codexAuthHandoff.ts"},+ "./codexArtifactTemplates": {+ "types": "./src/codexArtifactTemplates.ts",+ "import": "./src/codexArtifactTemplates.ts"+ },+ "./codexFileCitations": {+ "types": "./src/codexFileCitations.ts",+ "import": "./src/codexFileCitations.ts"+ },+ "./codexMarkdownDirectives": {+ "types": "./src/codexMarkdownDirectives.ts",+ "import": "./src/codexMarkdownDirectives.ts"+ },+ "./markdownGithubAlerts": {+ "types": "./src/markdownGithubAlerts.ts",+ "import": "./src/markdownGithubAlerts.ts"+ },+ "./markdownListIndentation": {+ "types": "./src/markdownListIndentation.ts",+ "import": "./src/markdownListIndentation.ts"+ },+ "./proposedPlanText": {+ "types": "./src/proposedPlanText.ts",+ "import": "./src/proposedPlanText.ts"+ },+ "./markdownPipeline": {+ "types": "./src/markdownPipeline.ts",+ "import": "./src/markdownPipeline.ts"+ },+ "./threadFindText": {+ "types": "./src/threadFindText.ts",+ "import": "./src/threadFindText.ts"+ },+ "./threadSearch": {+ "types": "./src/threadSearch.ts",+ "import": "./src/threadSearch.ts"+ },+ "./markdownLinks": {+ "types": "./src/markdownLinks.ts",+ "import": "./src/markdownLinks.ts"+ },+ "./fileLinks": {+ "types": "./src/fileLinks.ts",+ "import": "./src/fileLinks.ts"+ },+ "./inlineSkills": {+ "types": "./src/inlineSkills.ts",+ "import": "./src/inlineSkills.ts"+ },"./mcpApp": {"types": "./src/mcpApp.ts","import": "./src/mcpApp.ts"@@ -422,12 +470,23 @@"@t3tools/contracts": "workspace:*","effect": "catalog:","jose": "catalog:",+ "mdast-util-directive": "catalog:",+ "micromark-extension-directive": "catalog:",+ "micromark-util-character": "catalog:",+ "rehype-raw": "catalog:",+ "rehype-sanitize": "catalog:",+ "remark-breaks": "catalog:",+ "remark-gfm": "catalog:",+ "remark-parse": "catalog:",+ "remark-rehype": "catalog:",+ "unified": "catalog:","yaml": "catalog:"},"devDependencies": {"@effect/platform-node": "catalog:","@effect/vitest": "catalog:","@types/node": "catalog:",+ "micromark-util-types": "catalog:","vite-plus": "catalog:"}}diff --git a/packages/shared/src/assistantCitations.ts b/packages/shared/src/assistantCitations.tsindex 86ca0701f20..53edc79e47f 100644--- a/packages/shared/src/assistantCitations.ts+++ b/packages/shared/src/assistantCitations.ts@@ -98,6 +98,7 @@ export function parseAssistantCitationHref(href: string): AssistantCitation | nu}}+/** Visible chip text: the comment, else the quoted text, collapsed and capped. */export function assistantCitationLabel(citation: AssistantCitation): string {const preview = (citation.comment?.trim() || citation.text).replace(/\s+/g, " ");return preview.length > 64 ? `${preview.slice(0, 64)}…` : preview;diff --git a/packages/client-runtime/src/codexArtifactTemplates.test.ts b/packages/shared/src/codexArtifactTemplates.test.tssimilarity index 99%rename from packages/client-runtime/src/codexArtifactTemplates.test.tsrename to packages/shared/src/codexArtifactTemplates.test.tsindex d92236104a5..65c1d489039 100644--- a/packages/client-runtime/src/codexArtifactTemplates.test.ts+++ b/packages/shared/src/codexArtifactTemplates.test.ts@@ -6,7 +6,7 @@ import {codexArtifactTemplateUsePrompt,resolveCodexArtifactTemplate,type CodexArtifactTemplate,-} from "./codexArtifactTemplates.js";+} from "./codexArtifactTemplates.ts";const HELLO_WORLD_TEMPLATE: CodexArtifactTemplate = {artifactKind: "document",diff --git a/packages/client-runtime/src/codexArtifactTemplates.ts b/packages/shared/src/codexArtifactTemplates.tssimilarity index 100%rename from packages/client-runtime/src/codexArtifactTemplates.tsrename to packages/shared/src/codexArtifactTemplates.tsdiff --git a/packages/client-runtime/src/codexFileCitations.test.ts b/packages/shared/src/codexFileCitations.test.tssimilarity index 98%rename from packages/client-runtime/src/codexFileCitations.test.tsrename to packages/shared/src/codexFileCitations.test.tsindex d132a5480ca..e993d777cd2 100644--- a/packages/client-runtime/src/codexFileCitations.test.ts+++ b/packages/shared/src/codexFileCitations.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vite-plus/test";-import { codexFileCitationMarkdown, resolveCodexFileCitationLink } from "./codexFileCitations.js";+import { codexFileCitationMarkdown, resolveCodexFileCitationLink } from "./codexFileCitations.ts";describe("resolveCodexFileCitationLink", () => {it("resolves the attributes emitted by Codex", () => {diff --git a/packages/client-runtime/src/codexFileCitations.ts b/packages/shared/src/codexFileCitations.tssimilarity index 100%rename from packages/client-runtime/src/codexFileCitations.tsrename to packages/shared/src/codexFileCitations.tsdiff --git a/packages/client-runtime/src/codexMarkdownDirectives.test.ts b/packages/shared/src/codexMarkdownDirectives.test.tssimilarity index 98%rename from packages/client-runtime/src/codexMarkdownDirectives.test.tsrename to packages/shared/src/codexMarkdownDirectives.test.tsindex efd5262d073..2cfd1a0e20b 100644--- a/packages/client-runtime/src/codexMarkdownDirectives.test.ts+++ b/packages/shared/src/codexMarkdownDirectives.test.ts@@ -7,8 +7,8 @@ import {renderCodexDirectivesForCopy,renderCodexFileCitationsAsMarkdown,splitCodexArtifactTemplateMarkdown,-} from "./codexMarkdownDirectives.js";-import { parseMarkdownFileLink } from "./markdownLinks.js";+} from "./codexMarkdownDirectives.ts";+import { parseMarkdownFileLink } from "./markdownLinks.ts";interface TestNode {readonly type: string;diff --git a/packages/client-runtime/src/codexMarkdownDirectives.ts b/packages/shared/src/codexMarkdownDirectives.tssimilarity index 100%rename from packages/client-runtime/src/codexMarkdownDirectives.tsrename to packages/shared/src/codexMarkdownDirectives.tsdiff --git a/packages/shared/src/composerContextLegacy.ts b/packages/shared/src/composerContextLegacy.tsindex 4f3fd51f1a7..b13caa51e3e 100644--- a/packages/shared/src/composerContextLegacy.ts+++ b/packages/shared/src/composerContextLegacy.ts@@ -24,8 +24,10 @@ export interface UpgradedLegacyContext {}const PLACEHOLDER = "";-const TRAILING_TERMINAL = /\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/;-const TRAILING_ELEMENT = /\n*<element_context>\n([\s\S]*?)\n<\/element_context>\s*$/;+const TRAILING_TERMINAL =+ /\n*<terminal_context>\n((?:(?!\n<\/terminal_context>)[\s\S])*)\n<\/terminal_context>\s*$/;+const TRAILING_ELEMENT =+ /\n*<element_context>\n((?:(?!\n<\/element_context>)[\s\S])*)\n<\/element_context>\s*$/;const TRAILING_PREVIEW =/\n*<preview_annotation>\n((?:(?!\n<\/preview_annotation>)[\s\S])*)\n<\/preview_annotation>\s*$/;const REVIEW_OR_CONTEXT_BLOCK =diff --git a/packages/shared/src/fileLinks.test.ts b/packages/shared/src/fileLinks.test.tsnew file mode 100644index 00000000000..7d07826089f--- /dev/null+++ b/packages/shared/src/fileLinks.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from "vite-plus/test";+import { parseFileUrlHref, splitFilePathPosition, resolvePathLinkTarget } from "./fileLinks.ts";++describe("parseFileUrlHref", () => {+ it.each([+ ["file:///Users/julius/project/src/main.ts#L42", "/Users/julius/project/src/main.ts", "#L42"],+ [+ "file:///D:/Programme/t3code/OpenInPicker.tsx#L69",+ "D:/Programme/t3code/OpenInPicker.tsx",+ "#L69",+ ],+ ["file://server/share/workspace-image.svg", "\\\\server\\share\\workspace-image.svg", ""],+ ["file://localhost/home/me/notes.md", "/home/me/notes.md", ""],+ ])("parses %s", (href, path, hash) => {+ expect(parseFileUrlHref(href)).toEqual({ path, hash });+ });++ it("keeps percent-encoding so the caller decodes once", () => {+ expect(parseFileUrlHref("file:///Users/julius/project/file%2520name.md")?.path).toBe(+ "/Users/julius/project/file%2520name.md",+ );+ expect(parseFileUrlHref("file:///c%3A/Users/x/shot.png")?.path).toBe("/c%3A/Users/x/shot.png");+ });++ it.each(["https://example.com/a.ts", "file://%", "/Users/julius/a.ts"])("rejects %s", (href) => {+ expect(parseFileUrlHref(href)).toBeNull();+ });+});++describe("splitFilePathPosition", () => {+ it.each([+ ["src/main.ts", "", { path: "src/main.ts" }],+ ["src/main.ts:12", "", { path: "src/main.ts", line: 12 }],+ ["src/main.ts:12:5", "", { path: "src/main.ts", line: 12, column: 5 }],+ ["src/main.ts", "#L18C2", { path: "src/main.ts", line: 18, column: 2 }],+ ["src/main.ts:3", "#L18C2", { path: "src/main.ts", line: 3 }],+ ["src/main.ts:0", "", { path: "src/main.ts" }],+ ["src/main.ts", "#section", { path: "src/main.ts" }],+ ])("splits %s%s", (path, hash, expected) => {+ expect(splitFilePathPosition(path, hash)).toEqual(expected);+ });+});++describe("resolvePathLinkTarget", () => {+ it("resolves relative paths against cwd", () => {+ expect(+ resolvePathLinkTarget(+ "src/components/ThreadTerminalDrawer.tsx:42:7",+ "/Users/julius/project",+ ),+ ).toBe("/Users/julius/project/src/components/ThreadTerminalDrawer.tsx:42:7");+ });++ it("keeps absolute paths unchanged", () => {+ expect(+ resolvePathLinkTarget("/Users/julius/project/src/main.ts:12", "/Users/julius/project"),+ ).toBe("/Users/julius/project/src/main.ts:12");+ });++ it("keeps Windows absolute paths with forward slashes unchanged", () => {+ expect(+ resolvePathLinkTarget("C:/Users/julius/project/src/main.ts:12", "C:\\Users\\julius\\project"),+ ).toBe("C:/Users/julius/project/src/main.ts:12");+ });++ it.each([+ ["C:\\Users\\julius\\project", "C:\\Users\\julius\\notes.md:3"],+ ["C:/Users/julius/project", "C:/Users/julius\\notes.md:3"],+ ])("resolves home paths against the Windows cwd %s", (cwd, expected) => {+ expect(resolvePathLinkTarget("~/notes.md:3", cwd)).toBe(expected);+ });+});diff --git a/packages/shared/src/fileLinks.ts b/packages/shared/src/fileLinks.tsnew file mode 100644index 00000000000..16e1ca567ce--- /dev/null+++ b/packages/shared/src/fileLinks.ts@@ -0,0 +1,183 @@+import {+ fileBasename,+ isAbsolutePath,+ isWindowsAbsolutePath,+ stripSlashPrefixedWindowsDrive,+} from "./path.ts";++const POSITION_SUFFIX_CAPTURE_PATTERN = /:(\d+)(?::(\d+))?$/;++const POSITION_HASH_PATTERN = /^#L(\d+)(?:C(\d+))?$/i;++/**+ * Turns a `file:` URL into a host path, still percent-encoded so callers that+ * decode every destination in one place do not decode file URLs twice. A+ * non-localhost authority becomes a UNC share.+ */+export function parseFileUrlHref(+ href: string,+): { readonly path: string; readonly hash: string } | null {+ try {+ const parsed = new URL(href);+ if (parsed.protocol.toLowerCase() !== "file:") return null;++ const uncHostname = parsed.hostname.toLowerCase() === "localhost" ? "" : parsed.hostname;+ const path = uncHostname+ ? `\\\\${uncHostname}${parsed.pathname.replaceAll("/", "\\")}`+ : parsed.pathname;+ if (path.length === 0) return null;+ return { path: stripSlashPrefixedWindowsDrive(path), hash: parsed.hash };+ } catch {+ return null;+ }+}++export interface FilePathPosition {+ readonly path: string;+ readonly line?: number;+ readonly column?: number;+}++export function splitFilePathPosition(path: string, hash = ""): FilePathPosition {+ const suffixMatch = path.match(POSITION_SUFFIX_CAPTURE_PATTERN);+ const match = suffixMatch ?? hash.match(POSITION_HASH_PATTERN);+ if (!match?.[1]) return { path };++ const line = Number.parseInt(match[1], 10);+ const column = match[2] === undefined ? undefined : Number.parseInt(match[2], 10);+ return {+ path: suffixMatch ? path.slice(0, -suffixMatch[0].length) : path,+ ...(line > 0 ? { line } : {}),+ ...(column !== undefined && column > 0 ? { column } : {}),+ };+}++export function formatFilePathPosition(position: FilePathPosition): string {+ if (!position.line) return position.path;+ return `${position.path}:${position.line}${position.column ? `:${position.column}` : ""}`;+}++function isWindowsPathStyle(value: string): boolean {+ return isWindowsAbsolutePath(value) || /[A-Za-z]:\\/.test(value);+}++function joinPath(base: string, next: string, separator: "/" | "\\"): string {+ const cleanBase = base.replace(/[\\/]+$/, "");+ if (separator === "\\") {+ return `${cleanBase}\\${next.replaceAll("/", "\\")}`;+ }+ return `${cleanBase}/${next.replace(/^\/+/, "")}`;+}++function inferHomeFromCwd(cwd: string): string | undefined {+ const posixUser = cwd.match(/^\/Users\/([^/]+)/);+ if (posixUser?.[1]) {+ return `/Users/${posixUser[1]}`;+ }++ const posixHome = cwd.match(/^\/home\/([^/]+)/);+ if (posixHome?.[1]) {+ return `/home/${posixHome[1]}`;+ }++ const windowsUser = cwd.match(/^([A-Za-z]:[\\/]Users[\\/][^\\/]+)/);+ if (windowsUser?.[1]) {+ return windowsUser[1];+ }++ return undefined;+}++export function resolvePathLinkTarget(rawPath: string, cwd: string): string {+ const position = splitFilePathPosition(rawPath);+ const { path } = position;++ let resolvedPath = path;+ if (path.startsWith("~/")) {+ const home = inferHomeFromCwd(cwd);+ if (home) {+ const separator: "/" | "\\" = isWindowsPathStyle(home) ? "\\" : "/";+ resolvedPath = joinPath(home, path.slice(2), separator);+ }+ } else if (!isAbsolutePath(path)) {+ const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";+ resolvedPath = joinPath(cwd, path, separator);+ }++ return formatFilePathPosition({ ...position, path: resolvedPath });+}++function pathParentSegments(path: string): string[] {+ const normalized = path.replaceAll("\\", "/");+ const segments = normalized.split("/").filter((segment) => segment.length > 0);+ return segments.slice(0, -1);+}++export function buildFileLinkParentSuffixByPath(+ filePaths: ReadonlyArray<string>,+): Map<string, string> {+ const groups = new Map<string, Set<string>>();+ for (const filePath of filePaths) {+ const normalizedPath = filePath.replaceAll("\\", "/");+ const pathSegments = normalizedPath.split("/").filter((segment) => segment.length > 0);+ const basename = pathSegments[pathSegments.length - 1];+ if (!basename) continue;+ const group = groups.get(basename) ?? new Set<string>();+ group.add(normalizedPath);+ groups.set(basename, group);+ }++ const suffixByPath = new Map<string, string>();+ for (const group of groups.values()) {+ const uniquePaths = [...group];+ if (uniquePaths.length < 2) continue;++ const parentSegmentsByPath = new Map(+ uniquePaths.map((filePath) => [filePath, pathParentSegments(filePath)]),+ );+ const minUniqueDepthByPath = new Map<string, number>();++ for (const filePath of uniquePaths) {+ const segments = parentSegmentsByPath.get(filePath) ?? [];+ let resolvedDepth = segments.length;+ for (let depth = 1; depth <= segments.length; depth += 1) {+ const candidate = segments.slice(-depth).join("/");+ const collision = uniquePaths.some((otherPath) => {+ if (otherPath === filePath) return false;+ const otherSegments = parentSegmentsByPath.get(otherPath) ?? [];+ return otherSegments.slice(-depth).join("/") === candidate;+ });+ if (!collision) {+ resolvedDepth = depth;+ break;+ }+ }+ minUniqueDepthByPath.set(filePath, resolvedDepth);+ }++ for (const filePath of uniquePaths) {+ const segments = parentSegmentsByPath.get(filePath) ?? [];+ if (segments.length === 0) continue;+ const minUniqueDepth = minUniqueDepthByPath.get(filePath) ?? 1;+ const suffixDepth = Math.min(segments.length, Math.max(minUniqueDepth, 2));+ suffixByPath.set(filePath, segments.slice(-suffixDepth).join("/"));+ }+ }++ return suffixByPath;+}++/** Visible text of a file chip, shared by Markdown rendering and thread search. */+export function fileLinkLabel(+ file: FilePathPosition,+ parentSuffixByPath: ReadonlyMap<string, string>,+): string {+ const suffix = parentSuffixByPath.get(file.path.replaceAll("\\", "/"));+ return [+ fileBasename(file.path),+ suffix,+ file.line ? `L${file.line}${file.column ? `:C${file.column}` : ""}` : undefined,+ ]+ .filter(Boolean)+ .join(" · ");+}diff --git a/packages/shared/src/inlineSkills.ts b/packages/shared/src/inlineSkills.tsnew file mode 100644index 00000000000..b5f4437b7a3--- /dev/null+++ b/packages/shared/src/inlineSkills.ts@@ -0,0 +1,35 @@+import type { ServerProviderSkill } from "@t3tools/contracts";++export type InlineSkill = Pick<ServerProviderSkill, "name" | "displayName">;++function titleCaseWords(value: string): string {+ const words: string[] = [];+ for (const segment of value.split(/[\s:_-]+/)) {+ if (segment.length === 0) continue;+ words.push(segment.charAt(0).toUpperCase() + segment.slice(1));+ }+ return words.join(" ");+}++export function formatProviderSkillDisplayName(+ skill: Pick<ServerProviderSkill, "name" | "displayName">,+): string {+ const displayName = skill.displayName?.trim();+ if (displayName) {+ return displayName;+ }+ return titleCaseWords(skill.name);+}++const SKILL_TOKEN_REGEX =+ /(^|\s)\p{Sc}(?![0-9][0-9_]*(?:[kKmMbBtT]|[eE][0-9]+)?(?:\s|$))(?=[a-zA-Z0-9:_-]*[a-zA-Z])([a-zA-Z0-9][a-zA-Z0-9:_-]*)(?=\s|$)/gu;++export function* matchInlineSkills(text: string, skills: readonly InlineSkill[]) {+ for (const match of text.matchAll(SKILL_TOKEN_REGEX)) {+ const name = match[2] ?? "";+ const skill = skills.find((candidate) => candidate.name === name);+ if (!skill) continue;+ const start = match.index + (match[1]?.length ?? 0);+ yield { start, end: match.index + match[0].length, skill, rawText: `$${name}` };+ }+}diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.tsindex 84cfeef663e..0e95775fbb3 100644--- a/packages/shared/src/keybindings.ts+++ b/packages/shared/src/keybindings.ts@@ -171,6 +171,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },{ key: "mod+alt+n", command: "chat.newWithoutProject", when: "!terminalFocus" },+ { key: "mod+f", command: "chat.find", when: "!terminalFocus && !previewFocus" },{ key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },{ key: "mod+shift+h", command: "composer.host", when: "!terminalFocus" },{ key: "mod+shift+e", command: "composer.effort", when: "!terminalFocus" },diff --git a/apps/web/src/markdown-github-alerts.ts b/packages/shared/src/markdownGithubAlerts.tssimilarity index 100%rename from apps/web/src/markdown-github-alerts.tsrename to packages/shared/src/markdownGithubAlerts.tsdiff --git a/packages/client-runtime/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.tssimilarity index 66%rename from packages/client-runtime/src/markdownLinks.test.tsrename to packages/shared/src/markdownLinks.test.tsindex b6e52e4534a..b16b01008f9 100644--- a/packages/client-runtime/src/markdownLinks.test.ts+++ b/packages/shared/src/markdownLinks.test.ts@@ -1,13 +1,17 @@+import { splitFilePathPosition } from "./fileLinks.ts";+import { parseFileUrlHref } from "./fileLinks.ts";+import { workspaceRelativeFilePath, fileBasename } from "./path.ts";import { describe, expect, it } from "vite-plus/test";+import {+ extractMarkdownLinkHrefs,+ resolveMarkdownFileLinkTarget,+ isWindowsDrivePathHref,+} from "./markdownLinks.ts";import {- fileBasename,inlineCodeFilePathCandidate,isMarkdownFileLinkLabel,- parseFileUrlHref,parseMarkdownFileLink,- splitFilePathPosition,- workspaceRelativeFilePath,} from "./markdownLinks.ts";describe("isMarkdownFileLinkLabel", () => {@@ -206,3 +210,119 @@ describe("workspaceRelativeFilePath", () => {expect(workspaceRelativeFilePath(path, workspaceRoot)).toBe(relativePath);});});++describe("isWindowsDrivePathHref", () => {+ it.each([+ ["C:\\repo\\image.png", true],+ ["C:%5Crepo%5Cimage.png", true],+ ["https://example.com/image.png", false],+ ])("classifies %s as %s", (href, expected) => {+ expect(isWindowsDrivePathHref(href)).toBe(expected);+ });+});++describe("extractMarkdownLinkHrefs", () => {+ it("extracts angle-bracketed paths containing spaces", () => {+ expect(+ extractMarkdownLinkHrefs(+ "[Open the Bike Receipts folder](</Users/dara/Downloads/Lime Ride Artifacts/Bike Receipts>)",+ ),+ ).toEqual(["/Users/dara/Downloads/Lime Ride Artifacts/Bike Receipts"]);+ });++ it("preserves ordinary destinations and ignores link titles", () => {+ expect(+ extractMarkdownLinkHrefs(+ '[source](apps/web/src/markdown-links.ts "implementation") and [docs](https://example.com)',+ ),+ ).toEqual(["apps/web/src/markdown-links.ts", "https://example.com"]);+ });+});++describe("resolveMarkdownFileLinkTarget", () => {+ it("resolves absolute posix file paths", () => {+ expect(resolveMarkdownFileLinkTarget("/Users/julius/project/AGENTS.md")).toBe(+ "/Users/julius/project/AGENTS.md",+ );+ });++ it("resolves relative file paths against cwd", () => {+ expect(resolveMarkdownFileLinkTarget("src/processRunner.ts:71", "/Users/julius/project")).toBe(+ "/Users/julius/project/src/processRunner.ts:71",+ );+ });++ it("does not treat filename line references as external schemes", () => {+ expect(resolveMarkdownFileLinkTarget("script.ts:10", "/Users/julius/project")).toBe(+ "/Users/julius/project/script.ts:10",+ );+ });++ it("resolves bare file names against cwd", () => {+ expect(resolveMarkdownFileLinkTarget("AGENTS.md", "/Users/julius/project")).toBe(+ "/Users/julius/project/AGENTS.md",+ );+ });++ it("maps #L line anchors to editor line suffixes", () => {+ expect(resolveMarkdownFileLinkTarget("/Users/julius/project/src/main.ts#L42C7")).toBe(+ "/Users/julius/project/src/main.ts:42:7",+ );+ });++ it("ignores external urls", () => {+ expect(resolveMarkdownFileLinkTarget("https://example.com/docs")).toBeNull();+ expect(resolveMarkdownFileLinkTarget("//cdn.example.com/clip.mp4", "/workspace")).toBeNull();+ });++ it("does not double-decode file URLs", () => {+ expect(resolveMarkdownFileLinkTarget("file:///Users/julius/project/file%2520name.md")).toBe(+ "/Users/julius/project/file%20name.md",+ );+ });++ it("resolves file uri authorities as windows UNC paths", () => {+ expect(resolveMarkdownFileLinkTarget("file://server/share/workspace-image.svg")).toBe(+ "\\\\server\\share\\workspace-image.svg",+ );+ });++ it("resolves a localhost file uri as a local path", () => {+ expect(resolveMarkdownFileLinkTarget("file://localhost/home/me/notes.md")).toBe(+ "/home/me/notes.md",+ );+ });++ it("keeps an encoded final space in the absolute target", () => {+ expect(resolveMarkdownFileLinkTarget("/tmp/repo/file.ts%20", "/tmp/repo")).toBe(+ "/tmp/repo/file.ts ",+ );+ });++ it("normalizes slash-prefixed windows drive paths before resolving", () => {+ expect(+ resolveMarkdownFileLinkTarget(+ "/D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx#L69",+ ),+ ).toBe("D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx:69");+ });++ it("resolves angle-bracketed windows drive paths", () => {+ expect(+ resolveMarkdownFileLinkTarget(+ "</D:/Programme/t3code/apps/web/src/components/ChatMarkdown.tsx:1>",+ ),+ ).toBe("D:/Programme/t3code/apps/web/src/components/ChatMarkdown.tsx:1");+ });++ it("does not treat app routes as file links, even with a line anchor", () => {+ expect(resolveMarkdownFileLinkTarget("/chat/settings")).toBeNull();+ expect(resolveMarkdownFileLinkTarget("/chat/settings#L3", "/repo")).toBeNull();+ });++ it("decodes an encoded drive colon in a file uri before dropping its slash", () => {+ expect(resolveMarkdownFileLinkTarget("file:///c%3A/Users/x/shot.png")).toBe(+ "c:/Users/x/shot.png",+ );+ });+});diff --git a/packages/client-runtime/src/markdownLinks.ts b/packages/shared/src/markdownLinks.tssimilarity index 71%rename from packages/client-runtime/src/markdownLinks.tsrename to packages/shared/src/markdownLinks.tsindex 88db0e5a725..875f764d448 100644--- a/packages/client-runtime/src/markdownLinks.ts+++ b/packages/shared/src/markdownLinks.ts@@ -1,23 +1,36 @@-import { isWindowsAbsolutePath } from "@t3tools/shared/path";+import { isWindowsAbsolutePath, stripSlashPrefixedWindowsDrive } from "./path.ts";+import {+ type FilePathPosition,+ formatFilePathPosition,+ parseFileUrlHref,+ resolvePathLinkTarget,+ splitFilePathPosition,+} from "./fileLinks.ts";-const SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN = /^\/[A-Za-z]:[\\/]/;const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;+const RELATIVE_FILE_PATH_PATTERN =/^(?:[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\/)+[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*(?::\d+){0,2}$/;+const RELATIVE_FILE_NAME_PATTERN =/^[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;+const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;+const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;-const POSITION_SUFFIX_CAPTURE_PATTERN = /:(\d+)(?::(\d+))?$/;-const POSITION_HASH_PATTERN = /^#L(\d+)(?:C(\d+))?$/i;+const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;+const INLINE_CODE_DISQUALIFIER_PATTERN = /[\s`]/;+const PATH_SEPARATOR_PATTERN = /[\\/]/;+const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;// A final dot between digits marks a version or model id (`glm-5.3`,// `Qwen2.5-Coder`), not an extension. `ls.1` and `libfoo.so.1` stay files.const VERSION_SUFFIX_PATTERN = /\d\.\d[^.]*$/;const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;+// Standard OS and dev-container roots; deliberately excludes app-route-ish// prefixes like /app/ or /chat/ so SPA routes never read as files.const POSIX_FILE_ROOT_PREFIXES = [@@ -46,6 +59,7 @@ const POSIX_FILE_ROOT_PREFIXES = ["/workspace/","/workspaces/",] as const;+// `Name:digits` also matches `error:1`, `port:3000`, and `TODO:12`.const EXTENSIONLESS_FILE_NAMES = new Set(["Makefile",@@ -76,7 +90,9 @@ const EXTENSIONLESS_FILE_NAMES = new Set(["README","CODEOWNERS",]);+const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);+// These allowlists avoid classifying dotted directories such as `conf.d/`// or filenames such as `Makefile.in:12` as hosts.const GENERIC_HOSTNAME_TLDS = new Set([@@ -106,6 +122,7 @@ const GENERIC_HOSTNAME_TLDS = new Set(["store","link",]);+// Country codes also name file extensions. A :line suffix makes `.pl`// and `.pt` files more likely than hostnames.const COUNTRY_HOSTNAME_TLDS = new Set([@@ -198,11 +215,6 @@ export function normalizeMarkdownLinkDestination(value: string): string {return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;}-/** Browser URL parsers write `C:/foo` as `/C:/foo` for file URLs. */-export function stripSlashPrefixedWindowsDrive(path: string): string {- return SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN.test(path) ? path.slice(1) : path;-}-export function splitMarkdownLinkSearchAndHash(value: string): {readonly path: string;readonly hash: string;@@ -217,54 +229,6 @@ export function splitMarkdownLinkSearchAndHash(value: string): {};}-/**- * Turns a `file:` URL into a host path, still percent-encoded so callers that- * decode every destination in one place do not decode file URLs twice. A- * non-localhost authority becomes a UNC share.- */-export function parseFileUrlHref(- href: string,-): { readonly path: string; readonly hash: string } | null {- try {- const parsed = new URL(href);- if (parsed.protocol.toLowerCase() !== "file:") return null;-- const uncHostname = parsed.hostname.toLowerCase() === "localhost" ? "" : parsed.hostname;- const path = uncHostname- ? `\\\\${uncHostname}${parsed.pathname.replaceAll("/", "\\")}`- : parsed.pathname;- if (path.length === 0) return null;- return { path: stripSlashPrefixedWindowsDrive(path), hash: parsed.hash };- } catch {- return null;- }-}--export interface FilePathPosition {- readonly path: string;- readonly line?: number;- readonly column?: number;-}--export function splitFilePathPosition(path: string, hash = ""): FilePathPosition {- const suffixMatch = path.match(POSITION_SUFFIX_CAPTURE_PATTERN);- const match = suffixMatch ?? hash.match(POSITION_HASH_PATTERN);- if (!match?.[1]) return { path };-- const line = Number.parseInt(match[1], 10);- const column = match[2] === undefined ? undefined : Number.parseInt(match[2], 10);- return {- path: suffixMatch ? path.slice(0, -suffixMatch[0].length) : path,- ...(line > 0 ? { line } : {}),- ...(column !== undefined && column > 0 ? { column } : {}),- };-}--export function formatFilePathPosition(position: FilePathPosition): string {- if (!position.line) return position.path;- return `${position.path}:${position.line}${position.column ? `:${position.column}` : ""}`;-}-/** Keeps filename and destination-path labels compact without discarding prose. */export function isMarkdownFileLinkLabel(label: string, href: string): boolean {const destination = parseMarkdownFileLink(href);@@ -288,7 +252,7 @@ export function isMarkdownFileLinkLabel(label: string, href: string): boolean {return destinationPath === labelPath || destinationPath.endsWith(`/${labelPath}`);}-export function isRelativeFilePath(path: string): boolean {+function isRelativeFilePath(path: string): boolean {return (RELATIVE_PATH_PREFIX_PATTERN.test(path) ||(!path.startsWith("/") && !isWindowsAbsolutePath(path))@@ -342,28 +306,54 @@ export function parseMarkdownFileLink(href: string): FilePathPosition | null {return looksLikeFilePath(position.path, path) ? position : null;}-export function fileBasename(path: string): string {- // A trailing separator is a valid way to write a directory. Trim it before- // taking the final segment so the label is never empty.- const trimmed = path.replace(/[/\\]+$/, "");- if (trimmed.length === 0) return path;- const separatorIndex = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));- return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;+const FENCED_CODE_SEGMENT_PATTERN = /(```[\s\S]*?(?:```|$))/;++const INLINE_CODE_SPAN_PATTERN = /`([^`\n]+)`/g;++export function extractInlineCodeSpans(text: string): string[] {+ const spans: string[] = [];+ const segments = text.split(FENCED_CODE_SEGMENT_PATTERN);+ for (let index = 0; index < segments.length; index += 2) {+ for (const match of (segments[index] ?? "").matchAll(INLINE_CODE_SPAN_PATTERN)) {+ const span = match[1]?.trim();+ if (span) spans.push(span);+ }+ }+ return spans;+}++const MARKDOWN_LINK_HREF_PATTERN =+ /\[[^\]]*]\(\s*(?:<([^>\n]+)>|([^\s)]+))(?:\s+["'][^"']*["'])?\s*\)/g;++export function extractMarkdownLinkHrefs(markdown: string): string[] {+ const hrefs: string[] = [];+ for (const match of markdown.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {+ const href = (match[1] ?? match[2])?.trim();+ if (href) hrefs.push(href);+ }+ return hrefs;}-export function workspaceRelativeFilePath(- path: string,- workspaceRoot: string | null | undefined,+/**+ * `baseDir` anchors relative links; it defaults to the workspace root and is the+ * file's own directory when rendering a markdown file. `cwd` stays the workspace+ * root so the result still knows whether the target is inside it.+ */+export function resolveMarkdownFileLinkTarget(+ href: string | undefined,+ cwd?: string,+ baseDir: string | undefined = cwd,): string | null {- if (!workspaceRoot) return null;- const normalizedPath = stripSlashPrefixedWindowsDrive(path.replaceAll("\\", "/"));- const normalizedRoot = stripSlashPrefixedWindowsDrive(- workspaceRoot.replaceAll("\\", "/"),- ).replace(/\/+$/, "");- const caseInsensitive = isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot));- const pathForCompare = caseInsensitive ? normalizedPath.toLowerCase() : normalizedPath;- const rootForCompare = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;- if (pathForCompare.replace(/\/+$/, "") === rootForCompare) return ".";- if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;- return normalizedPath.slice(normalizedRoot.length + 1);+ if (!href) return null;+ const target = parseMarkdownFileLink(href);+ if (!target) return null;++ const pathWithPosition = formatFilePathPosition(target);+ if (!isRelativeFilePath(pathWithPosition)) return pathWithPosition;+ if (!baseDir) return null;+ return resolvePathLinkTarget(pathWithPosition, baseDir);+}++export function isWindowsDrivePathHref(href: string): boolean {+ return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));}diff --git a/apps/web/src/markdown-list-indentation.ts b/packages/shared/src/markdownListIndentation.tssimilarity index 100%rename from apps/web/src/markdown-list-indentation.tsrename to packages/shared/src/markdownListIndentation.tsdiff --git a/packages/shared/src/markdownPipeline.test.ts b/packages/shared/src/markdownPipeline.test.tsnew file mode 100644index 00000000000..1227e77b942--- /dev/null+++ b/packages/shared/src/markdownPipeline.test.ts@@ -0,0 +1,29 @@+import { expect, it } from "vite-plus/test";+import { unified } from "unified";+import remarkParse from "remark-parse";+import remarkRehype from "remark-rehype";+import { CHAT_MARKDOWN_REHYPE_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS } from "./markdownPipeline.ts";++it("preserves in-app thread links through the shared Markdown sanitizer", () => {+ const processor = unified()+ .use(remarkParse)+ .use(CHAT_MARKDOWN_REMARK_PLUGINS)+ .use(remarkRehype, { allowDangerousHtml: true })+ .use(CHAT_MARKDOWN_REHYPE_PLUGINS);+ const tree = processor.runSync(+ processor.parse(+ '[Open thread](t3-thread://v1/environment/thread)\n\n<a href="javascript:alert(1)">Unsafe</a>',+ ),+ );+ expect(tree.children[0]).toMatchObject({+ tagName: "p",+ children: [+ {+ tagName: "a",+ properties: { href: "t3-thread://v1/environment/thread" },+ children: [{ type: "text", value: "Open thread" }],+ },+ ],+ });+ expect(JSON.stringify(tree)).not.toContain("javascript:");+});diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.tsnew file mode 100644index 00000000000..7317dcc5b9f--- /dev/null+++ b/packages/shared/src/markdownPipeline.ts@@ -0,0 +1,293 @@+import type { Processor } from "unified";+import { isWindowsAbsolutePath } from "./path.ts";+import type { PluggableList } from "unified";+import rehypeRaw from "rehype-raw";+import rehypeSanitize, { defaultSchema } from "rehype-sanitize";+import remarkBreaks from "remark-breaks";+import remarkGfm from "remark-gfm";+import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";+import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";+import {+ CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,+ remarkCodexDirectives,+} from "./codexMarkdownDirectives.ts";+import { isWindowsDrivePathHref } from "./markdownLinks.ts";+import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";++type MarkdownImageHastNode = {+ type?: string;+ value?: string;+ tagName?: string;+ properties?: Record<string, unknown>;+ children?: MarkdownImageHastNode[];+};++function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {+ return (node.children ?? []).filter(+ (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),+ );+}++/**+ * An image that is the only content of its block (optionally wrapped in a+ * link) is almost always a screenshot or figure, so it gets a reserved slot+ * while it loads. Images mixed with text or other images — badge rows, icons+ * in a sentence — stay inline at their natural size, since a placeholder taller+ * than the image would move the page more than the image itself does.+ */+/** Containers whose sole child image reads as a figure rather than part of a sentence. */+const STANDALONE_IMAGE_BLOCKS = new Set([+ "p",+ "div",+ "li",+ "td",+ "th",+ "figure",+ "center",+ "blockquote",+]);++function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {+ const children = meaningfulHastChildren(node);+ if (children.length !== 1) return undefined;+ const only = children[0];+ if (only?.type !== "element") return undefined;+ if (only.tagName === "img") return only;+ // A link, emphasis, or similar inline wrapper around the image still counts+ // as long as nothing else shares the block.+ return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"+ ? soleImageDescendant(only)+ : undefined;+}++function markStandaloneImages(node: MarkdownImageHastNode) {+ // A raw `<img>` on its own line reaches the root without a paragraph.+ if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {+ const image = soleImageDescendant(node);+ if (image) image.properties = { ...image.properties, dataStandalone: true };+ }+ node.children?.forEach((child) => {+ if (child.type === "element") markStandaloneImages(child);+ });+}++/** Keep unmatched inline `<A>` placeholders from opening an HTML link over later blocks. */+function rehypePreserveBareAnchorPlaceholders() {+ return (tree: MarkdownImageHastNode) => {+ const anchors: Array<MarkdownImageHastNode | null> = [];+ let rawTextTag: string | undefined;+ const visit = (node: MarkdownImageHastNode) => {+ if (node.type === "raw" && typeof node.value === "string") {+ // Raw blocks can contain several tags. Consume whole tags, quoted attributes,+ // and comments so text resembling a closing anchor cannot pair a placeholder.+ const tags = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;+ let offset = 0;+ while (rawTextTag !== "plaintext") {+ // Raw text ends at its closing tag even inside comment-looking text.+ const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;+ matcher.lastIndex = offset;+ const match = matcher.exec(node.value);+ if (!match) break;+ const [tag] = match;+ offset = matcher.lastIndex;+ if (rawTextTag) {+ rawTextTag = undefined;+ continue;+ }+ if (tag.startsWith("<!--")) continue;+ const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();+ const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();+ if (+ opening &&+ /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)+ ) {+ rawTextTag = opening;+ } else if (opening === "a") {+ anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);+ } else if (closing === "a") {+ anchors.pop();+ }+ }+ }+ node.children?.forEach(visit);+ };++ visit(tree);+ for (const anchor of anchors) {+ if (anchor) anchor.type = "text";+ }+ };+}++/** Carries authored image source metadata through the sanitizer to the image renderer. */+function rehypePreserveImageSourceMeta() {+ return (tree: MarkdownImageHastNode) => {+ const visit = (node: MarkdownImageHastNode) => {+ const src = node.properties?.src;+ const title = node.properties?.title;+ if (node.type === "element" && node.tagName === "img") {+ node.properties = {+ ...node.properties,+ ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),+ ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),+ };+ }+ node.children?.forEach(visit);+ };++ visit(tree);+ markStandaloneImages(tree);+ };+}++const CHAT_MARKDOWN_SANITIZE_SCHEMA = {+ ...defaultSchema,+ attributes: {+ ...defaultSchema.attributes,+ "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),+ code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],+ blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],+ div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],+ a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],+ img: [+ ...(defaultSchema.attributes?.img ?? []),+ "dataLocalSrc",+ "dataMarkdownTitle",+ "dataStandalone",+ ],+ },+ protocols: {+ ...defaultSchema.protocols,+ href: [+ ...(defaultSchema.protocols?.href ?? []),+ "file",+ "t3-citation",+ "t3-context",+ THREAD_LINK_PROTOCOL,+ ],+ src: [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"],+ },+} satisfies Parameters<typeof rehypeSanitize>[0];++export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [+ remarkGfm,+ remarkKeepWindowsPathDestinations,+ remarkGithubAlerts,+ remarkNormalizeListItemIndentation,+ remarkCodexDirectives,+ remarkPreserveCodeMeta,+ remarkNormalizeLinksAndTagInlineCode,+];++export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [+ remarkGfm,+ remarkKeepWindowsPathDestinations,+ remarkGithubAlerts,+ remarkNormalizeListItemIndentation,+ remarkCodexDirectives,+ remarkBreaks,+ remarkPreserveCodeMeta,+ remarkNormalizeLinksAndTagInlineCode,+];++export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [+ rehypePreserveBareAnchorPlaceholders,+ rehypeRaw,+ rehypePreserveImageSourceMeta,+ [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],+];++type MarkdownAstNode = {+ type?: string;+ meta?: unknown;+ url?: string;+ data?: {+ hProperties?: Record<string, unknown>;+ };+ children?: MarkdownAstNode[];+};++function remarkPreserveCodeMeta() {+ return (tree: MarkdownAstNode) => {+ const visit = (node: MarkdownAstNode) => {+ if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {+ node.data = {+ ...node.data,+ hProperties: {+ ...node.data?.hProperties,+ dataCodeMeta: node.meta.trim(),+ },+ };+ }+ node.children?.forEach(visit);+ };++ visit(tree);+ };+}++/**+ * Preserve Windows drive links as allowed `file:` URLs before sanitization.+ * The same traversal tags inline code while it can still be distinguished+ * from fenced code. Code inside links stays untagged to avoid nested anchors.+ */+function remarkNormalizeLinksAndTagInlineCode() {+ return (tree: MarkdownAstNode) => {+ const visit = (node: MarkdownAstNode, insideLink: boolean) => {+ if (+ (node.type === "link" || node.type === "definition") &&+ typeof node.url === "string" &&+ /^[A-Za-z]:[\\/]/.test(node.url)+ ) {+ node.url = `file:///${node.url.replaceAll("\\", "/")}`;+ }+ if (node.type === "inlineCode" && !insideLink) {+ node.data = {+ ...node.data,+ hProperties: {+ ...node.data?.hProperties,+ dataInlineCode: "",+ },+ };+ }+ const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";+ node.children?.forEach((child) => visit(child, childInsideLink));+ };++ visit(tree, false);+ };+}++interface DestinationCompileContext {+ readonly stack: ReadonlyArray<{ readonly type: string; url?: string }>;+ resume(): string;+ sliceSerialize(token: unknown): string;+}++function keepWindowsPathDestination(this: DestinationCompileContext, token: unknown) {+ const decoded = this.resume();+ const authored = this.sliceSerialize(token);+ const node = this.stack.at(-1);+ // Character references still need decoding, so those destinations keep the parsed URL.+ if (node)+ node.url = isWindowsAbsolutePath(authored) && !authored.includes("&") ? authored : decoded;+}++/**+ * CommonMark reads the `\.` in `C:\me\.t3\shot.png` as an escape, even in a link+ * destination. Every backslash in a Windows path is a separator, so link, image, and+ * definition destinations that are Windows paths keep the text as written.+ */+function remarkKeepWindowsPathDestinations(this: Processor) {+ const data = this.data();+ (data.fromMarkdownExtensions ??= []).push({+ exit: {+ resourceDestinationString: keepWindowsPathDestination,+ definitionDestinationString: keepWindowsPathDestination,+ },+ });+}++export function shouldPreserveAssistantLineBreaks(text: string): boolean {+ return /^★ Insight(?:\s|─)/mu.test(text);+}diff --git a/packages/shared/src/path.test.ts b/packages/shared/src/path.test.tsindex b018a4e81d8..705fdbf97ba 100644--- a/packages/shared/src/path.test.ts+++ b/packages/shared/src/path.test.ts@@ -1,5 +1,7 @@import { describe, expect, it } from "vite-plus/test";import {+ fileBasename,+ workspaceRelativeFilePath,isExplicitRelativePath,isUncPath,isWindowsAbsolutePath,@@ -58,3 +60,40 @@ describe("path helpers", () => {expect(newProjectFolderName("console")).toBe("console");});});++describe("fileBasename", () => {+ it.each([+ ["/tmp/favicons/", "favicons"],+ ["C:\\Users\\kelchm\\.claude\\", ".claude"],+ ["/tmp/", "tmp"],+ ["AGENTS.md", "AGENTS.md"],+ ["/", "/"],+ ])("labels %s as %s", (path, basename) => {+ expect(fileBasename(path)).toBe(basename);+ });+});++describe("workspaceRelativeFilePath", () => {+ it.each([+ ["/repo/project/src/main.ts", "/repo/project", "src/main.ts"],+ ["/repo/project/src/main.ts", "/repo/project/", "src/main.ts"],+ ["C:\\Users\\mike\\t3code\\apps\\web\\a.ts", "C:/Users/mike/t3code", "apps/web/a.ts"],+ ["/C:/Users/mike/t3code/apps/web/a.ts", "C:/Users/mike/t3code", "apps/web/a.ts"],+ ["/Repo/Project/src/main.ts", "/repo/project", null],+ ["/tmp/case/project/probe.txt", "/tmp/case/Project", null],+ ["//tmp/case/project/probe.txt", "//tmp/case/Project", null],+ ["/tmp/case/Project/probe.txt", "/tmp/case/Project", "probe.txt"],+ ["C:/USERS/mike/t3code/main.ts", "c:/users/MIKE/t3code", "main.ts"],+ ["/C:/USERS/mike/t3code/main.ts", "/c:/users/MIKE/t3code", "main.ts"],+ ["\\\\server\\share\\PROJECT\\main.ts", "\\\\Server\\Share\\Project", "main.ts"],+ ["/tmp/repo/file.ts", "/", "tmp/repo/file.ts"],+ ["C:/Users/MIKE/main.ts", "c:/", "Users/MIKE/main.ts"],+ ["\\\\server\\SHARE\\file.ts", "\\\\Server\\Share\\", "file.ts"],+ ["/tmp/repo/file.ts ", "/tmp/repo", "file.ts "],+ ["/tmp/report.ts", "/repo/project", null],+ ["/repo/project-two/a.ts", "/repo/project", null],+ ["/repo/project/a.ts", undefined, null],+ ])("relates %s to %s", (path, workspaceRoot, relativePath) => {+ expect(workspaceRelativeFilePath(path, workspaceRoot)).toBe(relativePath);+ });+});diff --git a/packages/shared/src/path.ts b/packages/shared/src/path.tsindex c8626eb5e14..925e8ac753b 100644--- a/packages/shared/src/path.ts+++ b/packages/shared/src/path.ts@@ -74,3 +74,40 @@ export function newProjectFolderName(name: string): string {if (slug.length === 0) return "project";return WINDOWS_RESERVED_NAME.test(slug) ? `${slug}-project` : slug;}++const SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN = /^\/[A-Za-z]:[\\/]/;++/** Browser URL parsers write `C:/foo` as `/C:/foo` for file URLs. */+export function stripSlashPrefixedWindowsDrive(path: string): string {+ return SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN.test(path) ? path.slice(1) : path;+}++export function fileBasename(path: string): string {+ // A trailing separator is a valid way to write a directory. Trim it before+ // taking the final segment so the label is never empty.+ const trimmed = path.replace(/[/\\]+$/, "");+ if (trimmed.length === 0) return path;+ const separatorIndex = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));+ return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;+}++export function workspaceRelativeFilePath(+ path: string,+ workspaceRoot: string | null | undefined,+): string | null {+ if (!workspaceRoot) return null;+ const normalizedPath = stripSlashPrefixedWindowsDrive(path.replaceAll("\\", "/"));+ const normalizedRoot = stripSlashPrefixedWindowsDrive(+ workspaceRoot.replaceAll("\\", "/"),+ ).replace(/\/+$/, "");+ const caseInsensitive = isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot));+ const pathForCompare = caseInsensitive ? normalizedPath.toLowerCase() : normalizedPath;+ const rootForCompare = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;+ if (pathForCompare.replace(/\/+$/, "") === rootForCompare) return ".";+ if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;+ return normalizedPath.slice(normalizedRoot.length + 1);+}++export function isAbsolutePath(value: string): boolean {+ return value.startsWith("/") || isWindowsAbsolutePath(value);+}diff --git a/packages/shared/src/proposedPlanText.test.ts b/packages/shared/src/proposedPlanText.test.tsnew file mode 100644index 00000000000..f0bcbe35a46--- /dev/null+++ b/packages/shared/src/proposedPlanText.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from "vite-plus/test";+import { proposedPlanTitle, stripDisplayedPlanMarkdown } from "./proposedPlanText.ts";++describe("proposedPlanTitle", () => {+ it("reads the first markdown heading as the plan title", () => {+ expect(proposedPlanTitle("# Integrate RPC\n\nBody")).toBe("Integrate RPC");+ });++ it("returns null when the plan has no heading", () => {+ expect(proposedPlanTitle("- step 1")).toBeNull();+ });+});++describe("stripDisplayedPlanMarkdown", () => {+ it("drops the leading title heading from displayed plan markdown", () => {+ expect(stripDisplayedPlanMarkdown("# Integrate RPC\n\n## Summary\n\n- step 1\n")).toBe(+ "- step 1",+ );+ });++ it("preserves non-summary headings after dropping the title heading", () => {+ expect(stripDisplayedPlanMarkdown("# Integrate RPC\n\n## Scope\n\n- step 1\n")).toBe(+ "## Scope\n\n- step 1",+ );+ });+});diff --git a/packages/shared/src/proposedPlanText.ts b/packages/shared/src/proposedPlanText.tsnew file mode 100644index 00000000000..52d568898ed--- /dev/null+++ b/packages/shared/src/proposedPlanText.ts@@ -0,0 +1,20 @@+export function proposedPlanTitle(planMarkdown: string): string | null {+ const heading = planMarkdown.match(/^\s{0,3}#{1,6}\s+(.+)$/m)?.[1]?.trim();+ return heading && heading.length > 0 ? heading : null;+}++export function stripDisplayedPlanMarkdown(planMarkdown: string): string {+ const lines = planMarkdown.trimEnd().split(/\r?\n/);+ const sourceLines = lines[0] && /^\s{0,3}#{1,6}\s+/.test(lines[0]) ? lines.slice(1) : [...lines];+ while (sourceLines[0]?.trim().length === 0) {+ sourceLines.shift();+ }+ const firstHeadingMatch = sourceLines[0]?.match(/^\s{0,3}#{1,6}\s+(.+)$/);+ if (firstHeadingMatch?.[1]?.trim().toLowerCase() === "summary") {+ sourceLines.shift();+ while (sourceLines[0]?.trim().length === 0) {+ sourceLines.shift();+ }+ }+ return sourceLines.join("\n");+}diff --git a/packages/shared/src/themePalettes.ts b/packages/shared/src/themePalettes.tsindex b26244c0464..b0eccd1b159 100644--- a/packages/shared/src/themePalettes.ts+++ b/packages/shared/src/themePalettes.ts@@ -88,6 +88,10 @@ export const THEME_COLOR_ROLES = ["messageActionHover","codeBackground","codeForeground",+ "searchMatchBackground",+ "searchMatchForeground",+ "searchMatchActiveBackground",+ "searchMatchActiveForeground","sidebar","sidebarForeground","sidebarMutedForeground",@@ -129,6 +133,10 @@ export type ThemeDefinition = Readonly<{* colors are stored as opaque OKLCH tokens.*/export const T3_CODE_LIGHT_THEME_COLORS: ThemeColors = {+ searchMatchBackground: "#fce8c0",+ searchMatchForeground: "#27272a",+ searchMatchActiveBackground: "#eea52b",+ searchMatchActiveForeground: "#21180a",canvas: "#fcfcfc",chrome: "#fcfcfc",toolbar: "#fcfcfc",@@ -189,6 +197,10 @@ export const T3_CODE_LIGHT_THEME_COLORS: ThemeColors = {};export const T3_CODE_DARK_THEME_COLORS: ThemeColors = {+ searchMatchBackground: "#533e16",+ searchMatchForeground: "#f5f5f5",+ searchMatchActiveBackground: "#eea52b",+ searchMatchActiveForeground: "#21180a",canvas: "#0a0a0a",chrome: "#0a0a0a",toolbar: "#0a0a0a",@@ -296,6 +308,10 @@ export const T3_CHAT_THEME: ThemeDefinition = {messageActionHover: "oklch(0.539042 0.197866 0.305)",codeBackground: "oklch(0.953855 0.019695 315.668)",codeForeground: "oklch(0.445128 0.13005 307.026)",+ searchMatchBackground: "oklch(0.869588 0.06751 334.899)",+ searchMatchForeground: "oklch(0.325698 0.116116 325.037)",+ searchMatchActiveBackground: "oklch(0.591646 0.217985 0.584)",+ searchMatchActiveForeground: "oklch(1 0 0)",sidebar: "oklch(0.928886 0.031178 322.592)",sidebarForeground: "oklch(0.396296 0.025134 285.196)",sidebarMutedForeground: "oklch(0.494754 0.190937 354.544)",@@ -356,6 +372,10 @@ export const T3_CHAT_THEME: ThemeDefinition = {messageActionHover: "oklch(0.458754 0.184639 3.857)",codeBackground: "oklch(0.22813 0.020366 307.469)",codeForeground: "oklch(0.848703 0.064239 306.645)",+ searchMatchBackground: "oklch(0.313674 0.030572 310.061)",+ searchMatchForeground: "oklch(0.980735 0.004092 301.426)",+ searchMatchActiveBackground: "oklch(0.460685 0.185347 4.099)",+ searchMatchActiveForeground: "oklch(0.901233 0.057189 343.694)",sidebar: "oklch(0.185778 0.019368 322.159)",sidebarForeground: "oklch(0.967434 0.001326 286.375)",sidebarMutedForeground: "oklch(0.880303 0.03077 342.696)",@@ -423,6 +443,10 @@ export const GROVE_THEME: ThemeDefinition = {messageActionHover: "oklch(0.488753 0.096536 77.829)",codeBackground: "oklch(0.955888 0.004783 158.391)",codeForeground: "oklch(0.222003 0.03479 328.979)",+ searchMatchBackground: "oklch(0.891377 0.026164 164.929)",+ searchMatchForeground: "oklch(0.222003 0.03479 328.979)",+ searchMatchActiveBackground: "oklch(0.523295 0.112292 158.089)",+ searchMatchActiveForeground: "oklch(0.990339 0.008411 325.64)",sidebar: "oklch(0.936464 0.014601 163.554)",sidebarForeground: "oklch(0.222003 0.03479 328.979)",sidebarMutedForeground: "oklch(0.515606 0.011938 318.897)",@@ -483,6 +507,10 @@ export const GROVE_THEME: ThemeDefinition = {messageActionHover: "oklch(0.815227 0.117902 84.21)",codeBackground: "oklch(0.312979 0.018942 164.082)",codeForeground: "oklch(0.990339 0.008411 325.64)",+ searchMatchBackground: "oklch(0.464636 0.066083 158.72)",+ searchMatchForeground: "oklch(0.990339 0.008411 325.64)",+ searchMatchActiveBackground: "oklch(0.796228 0.133058 157.319)",+ searchMatchActiveForeground: "oklch(0.222003 0.03479 328.979)",sidebar: "oklch(0.309925 0.032827 160.944)",sidebarForeground: "oklch(0.990339 0.008411 325.64)",sidebarMutedForeground: "oklch(0.711387 0.007643 175.89)",@@ -550,6 +578,10 @@ export const OCEAN_THEME: ThemeDefinition = {messageActionHover: "oklch(0.45151 0.074407 201.516)",codeBackground: "oklch(0.957684 0.002906 253.68)",codeForeground: "oklch(0.222003 0.03479 328.979)",+ searchMatchBackground: "oklch(0.895373 0.023469 241.913)",+ searchMatchForeground: "oklch(0.222003 0.03479 328.979)",+ searchMatchActiveBackground: "oklch(0.536684 0.120219 247.01)",+ searchMatchActiveForeground: "oklch(0.990339 0.008411 325.64)",sidebar: "oklch(0.939254 0.01193 241.729)",sidebarForeground: "oklch(0.222003 0.03479 328.979)",sidebarMutedForeground: "oklch(0.517366 0.018944 311.433)",@@ -610,6 +642,10 @@ export const OCEAN_THEME: ThemeDefinition = {messageActionHover: "oklch(0.815308 0.096174 199.862)",codeBackground: "oklch(0.29661 0.021883 251.968)",codeForeground: "oklch(0.990339 0.008411 325.64)",+ searchMatchBackground: "oklch(0.439946 0.0561 243.479)",+ searchMatchForeground: "oklch(0.990339 0.008411 325.64)",+ searchMatchActiveBackground: "oklch(0.758933 0.105833 241.548)",+ searchMatchActiveForeground: "oklch(0.222003 0.03479 328.979)",sidebar: "oklch(0.290387 0.032043 247.274)",sidebarForeground: "oklch(0.990339 0.008411 325.64)",sidebarMutedForeground: "oklch(0.69099 0.01395 266.424)",@@ -677,6 +713,10 @@ export const EMBER_THEME: ThemeDefinition = {messageActionHover: "oklch(0.471223 0.145843 24.688)",codeBackground: "oklch(0.959965 0.002668 47.512)",codeForeground: "oklch(0.222003 0.03479 328.979)",+ searchMatchBackground: "oklch(0.899296 0.022939 49.163)",+ searchMatchForeground: "oklch(0.222003 0.03479 328.979)",+ searchMatchActiveBackground: "oklch(0.552831 0.129438 44.656)",+ searchMatchActiveForeground: "oklch(0.990339 0.008411 325.64)",sidebar: "oklch(0.942267 0.01151 50.785)",sidebarForeground: "oklch(0.222003 0.03479 328.979)",sidebarMutedForeground: "oklch(0.519146 0.019214 343.427)",@@ -737,6 +777,10 @@ export const EMBER_THEME: ThemeDefinition = {messageActionHover: "oklch(0.775116 0.117953 29.014)",codeBackground: "oklch(0.299662 0.017229 39.973)",codeForeground: "oklch(0.990339 0.008411 325.64)",+ searchMatchBackground: "oklch(0.442681 0.0608 50.795)",+ searchMatchForeground: "oklch(0.990339 0.008411 325.64)",+ searchMatchActiveBackground: "oklch(0.762174 0.124117 52.082)",+ searchMatchActiveForeground: "oklch(0.222003 0.03479 328.979)",sidebar: "oklch(0.293349 0.029554 46.882)",sidebarForeground: "oklch(0.990339 0.008411 325.64)",sidebarMutedForeground: "oklch(0.691874 0.012538 24.638)",@@ -804,6 +848,10 @@ export const IRIS_THEME: ThemeDefinition = {messageActionHover: "oklch(0.471003 0.16748 340.687)",codeBackground: "oklch(0.95997 0.004338 306.542)",codeForeground: "oklch(0.222003 0.03479 328.979)",+ searchMatchBackground: "oklch(0.897143 0.028558 299.758)",+ searchMatchForeground: "oklch(0.222003 0.03479 328.979)",+ searchMatchActiveBackground: "oklch(0.525348 0.15373 294.176)",+ searchMatchActiveForeground: "oklch(0.990339 0.008411 325.64)",sidebar: "oklch(0.941387 0.014687 300.474)",sidebarForeground: "oklch(0.222003 0.03479 328.979)",sidebarMutedForeground: "oklch(0.518417 0.023683 320.681)",@@ -864,6 +912,10 @@ export const IRIS_THEME: ThemeDefinition = {messageActionHover: "oklch(0.813537 0.114101 337.23)",codeBackground: "oklch(0.281873 0.028308 295.193)",codeForeground: "oklch(0.990339 0.008411 325.64)",+ searchMatchBackground: "oklch(0.395417 0.085554 294.182)",+ searchMatchForeground: "oklch(0.990339 0.008411 325.64)",+ searchMatchActiveBackground: "oklch(0.671712 0.169136 293.929)",+ searchMatchActiveForeground: "oklch(0.222003 0.03479 328.979)",sidebar: "oklch(0.266743 0.044689 294.138)",sidebarForeground: "oklch(0.990339 0.008411 325.64)",sidebarMutedForeground: "oklch(0.668773 0.021522 302.949)",diff --git a/packages/shared/src/threadFindText.test.ts b/packages/shared/src/threadFindText.test.tsnew file mode 100644index 00000000000..b24b0e2c73f--- /dev/null+++ b/packages/shared/src/threadFindText.test.ts@@ -0,0 +1,161 @@+import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";+import { expect, it } from "vite-plus/test";+import { serializeAssistantCitation } from "./assistantCitations.ts";+import { searchableMessageSegments } from "./threadFindText.ts";++it("excludes review attachments rendered as context chips", () => {+ const text = [+ "Before **review**",+ '<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="hidden.ts" startIndex="3" endIndex="14" rangeLabel="L4">',+ "Keep **this literal** comment.",+ "```diff",+ "+ hidden patch content",+ "```",+ "</review_comment>",+ "After review",+ ].join("\n");+ expect(searchableMessageSegments({ role: "user", text, streaming: false })).toEqual([+ "Before review",+ " After review",+ ]);+});++it("keeps malformed review tags visible, matching the message renderer", () => {+ const text = "<review_comment>not a valid attachment</review_comment>";+ expect(searchableMessageSegments({ role: "user", text, streaming: false })).toEqual([text]);+});++it("excludes structured context chips without joining text across them", () => {+ expect(+ searchableMessageSegments({+ role: "user",+ streaming: false,+ text: "before[hidden label](t3-context://v1/terminal/terminal_1)after",+ context: { version: 1, records: [] },+ }),+ ).toEqual(["before", "after"]);+});++it("does not upgrade literal legacy tags in messages with structured context", () => {+ const text =+ "<terminal_context>\n- Terminal 1 line 12:\n 12 | visible output\n</terminal_context>";+ expect(+ searchableMessageSegments({+ role: "user",+ streaming: false,+ text,+ context: { version: 1, records: [] },+ })?.join("\n"),+ ).toContain("visible output");+ expect(searchableMessageSegments({ role: "user", streaming: false, text })).toEqual([]);+});++it("keeps context reference syntax inside code searchable", () => {+ expect(+ searchableMessageSegments({+ role: "user",+ streaming: false,+ text: "`[label](t3-context://v1/terminal/terminal_1)`",+ }),+ ).toEqual(["[label](t3-context://v1/terminal/terminal_1)"]);+});++it("excludes repeated legacy attachments containing literal context tags", () => {+ const context =+ "<terminal_context>\n- Terminal 1 line 12:\n 12 | <terminal_context>literal</terminal_context>\n</terminal_context>";+ expect(+ searchableMessageSegments({+ role: "user",+ streaming: false,+ text: `Fix this\n\n${context}\n\n${context}`,+ }),+ ).toEqual(["Fix this"]);+});++const assistantSegments = (text: string, cwd?: string) =>+ searchableMessageSegments({ role: "assistant", text, streaming: false }, cwd);++it("searches displayed prose and file-chip labels without hidden paths", () => {+ expect(+ assistantSegments("[important description](/tmp/actual.ts). `/tmp/inline-example.ts:42`"),+ ).toEqual(["important description actual.ts. inline-example.ts · L42"]);+ expect(assistantSegments("[label](src/main.ts#L3C2)", "/workspace/repo")).toEqual([+ "label main.ts · L3:C2",+ ]);+ expect(assistantSegments("[label](src/main.ts#L3C2)")).toEqual(["label"]);+});++it("includes the same parent suffixes for duplicate filenames as the renderer", () => {+ expect(+ assistantSegments(+ "[first](src/main.ts) and `/workspace/repo/tests/main.ts:2`",+ "/workspace/repo",+ ),+ ).toEqual(["first main.ts · repo/src and main.ts · repo/tests · L2"]);+ expect(+ assistantSegments(+ "[first](src/main.ts) and `/workspace/repo/src/main.ts:2`",+ "/workspace/repo",+ ),+ ).toEqual(["first main.ts and main.ts · L2"]);+});++it("keeps fence paths literal and indexes file-chip labels in user messages", () => {+ expect(assistantSegments("```text\n/tmp/file.ts:42\n```")).toEqual(["/tmp/file.ts:42\n"]);+ expect(+ searchableMessageSegments({ role: "user", text: "`/tmp/file.ts:42`", streaming: false }),+ ).toEqual(["file.ts · L42"]);+});++it("indexes nested disclosure summaries and bodies in rendered order", () => {+ expect(+ assistantSegments(+ "<details><summary>Outer</summary><p>first</p><details><summary>Inner</summary><p>second</p></details></details>",+ ),+ ).toEqual(["Outer", "first", "Inner", "second"]);+});++it("uses Insight line breaks without splitting ordinary assistant prose", () => {+ expect(assistantSegments("★ Insight ─────\nfirst line\nsecond line")).toEqual([+ "★ Insight ─────",+ " first line",+ " second line",+ ]);+ expect(assistantSegments("first line\nsecond line")).toEqual(["first line second line"]);+});++it("indexes skill labels in prose but leaves links and code literal", () => {+ expect(+ searchableMessageSegments(+ {+ role: "assistant",+ streaming: false,+ text: "Use $test-t3-app now.\n\n`$test-t3-app`\n\n[$test-t3-app](https://example.com)",+ },+ undefined,+ [{ name: "test-t3-app", displayName: "T3 App Testing" }],+ ),+ ).toEqual(["Use T3 App Testing now.", "$test-t3-app", "$test-t3-app"]);+});++it("indexes the citation chip label instead of its link text", () => {+ const citation = {+ version: 1 as const,+ environmentId: EnvironmentId.make("environment"),+ threadId: ThreadId.make("thread"),+ messageId: MessageId.make("message"),+ text: "cited needle",+ start: 0,+ end: 14,+ prefix: "",+ suffix: "",+ };+ const text = `Please fix ${serializeAssistantCitation(citation)} thanks`;+ expect(searchableMessageSegments({ role: "user", text, streaming: false })).toEqual([+ "Please fix cited needle thanks",+ ]);+ const commented = serializeAssistantCitation({ ...citation, comment: "my note" });+ expect(searchableMessageSegments({ role: "user", text: commented, streaming: false })).toEqual([+ "my note",+ ]);+});diff --git a/packages/shared/src/threadFindText.ts b/packages/shared/src/threadFindText.tsnew file mode 100644index 00000000000..ab293fa68ea--- /dev/null+++ b/packages/shared/src/threadFindText.ts@@ -0,0 +1,233 @@+import {+ matchInlineSkills,+ formatProviderSkillDisplayName,+ type InlineSkill,+} from "./inlineSkills.ts";+import {+ artifactTemplateFromHastProperties,+ renderCodexFileCitationsAsMarkdown,+} from "./codexMarkdownDirectives.ts";+import { codexArtifactTemplatePresentationLabel } from "./codexArtifactTemplates.ts";+import {+ buildFileLinkParentSuffixByPath,+ splitFilePathPosition,+ fileLinkLabel,+} from "./fileLinks.ts";+import {+ isMarkdownFileLinkLabel,+ extractMarkdownLinkHrefs,+ extractInlineCodeSpans,+ inlineCodeFilePathCandidate,+ resolveMarkdownFileLinkTarget,+} from "./markdownLinks.ts";+import { upgradeLegacyContextMessage } from "./composerContextLegacy.ts";+import { parseComposerContextHref } from "./composerContextReferences.ts";+import { assistantCitationLabel, parseAssistantCitationHref } from "./assistantCitations.ts";+import type { OrchestrationV2ConversationMessage } from "@t3tools/contracts";+import { proposedPlanTitle, stripDisplayedPlanMarkdown } from "./proposedPlanText.ts";+import { unified } from "unified";+import remarkParse from "remark-parse";+import remarkRehype from "remark-rehype";+import {+ shouldPreserveAssistantLineBreaks,+ CHAT_MARKDOWN_REHYPE_PLUGINS,+ CHAT_MARKDOWN_REMARK_PLUGINS,+ CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,+} from "./markdownPipeline.ts";++// Inline wrappers (including Shiki token spans) must not split a search phrase.+export const THREAD_FIND_BLOCK_TAGS = new Set([+ "address",+ "article",+ "aside",+ "blockquote",+ "br",+ "dd",+ "details",+ "div",+ "dl",+ "dt",+ "figcaption",+ "figure",+ "footer",+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "header",+ "hr",+ "li",+ "main",+ "nav",+ "ol",+ "p",+ "pre",+ "section",+ "summary",+ "table",+ "tbody",+ "td",+ "th",+ "thead",+ "tr",+ "ul",+]);++const assistantProcessor = unified()+ .use(remarkParse)+ .use(CHAT_MARKDOWN_REMARK_PLUGINS)+ .use(remarkRehype, { allowDangerousHtml: true })+ .use(CHAT_MARKDOWN_REHYPE_PLUGINS);+const assistantBreaksProcessor = unified()+ .use(remarkParse)+ .use(CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS)+ .use(remarkRehype, { allowDangerousHtml: true })+ .use(CHAT_MARKDOWN_REHYPE_PLUGINS);+const userProcessor = unified()+ .use(remarkParse)+ .use(CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS)+ .use(remarkRehype, { allowDangerousHtml: true });++interface TextTree {+ readonly type: string;+ readonly tagName?: string;+ readonly value?: string;+ readonly properties?: {+ readonly href?: unknown;+ readonly src?: unknown;+ readonly dataInlineCode?: unknown;+ };+ readonly children?: ReadonlyArray<TextTree>;+}++/** Uses the renderer's Markdown transforms, without mounting folded/virtualized rows. */+function markdownThreadFindText(+ markdown: string,+ userMessage = false,+ cwd?: string,+ skills: readonly InlineSkill[] = [],+ lineBreaks = false,+): string[] {+ const processor = userMessage+ ? userProcessor+ : lineBreaks+ ? assistantBreaksProcessor+ : assistantProcessor;+ const tree = processor.runSync(processor.parse(markdown));+ const paths = [+ ...extractMarkdownLinkHrefs(renderCodexFileCitationsAsMarkdown(markdown)),+ ...extractInlineCodeSpans(markdown).flatMap((span) => inlineCodeFilePathCandidate(span) ?? []),+ ].flatMap((href) => {+ const target = resolveMarkdownFileLinkTarget(href, cwd);+ return target ? [splitFilePathPosition(target).path] : [];+ });+ const parentSuffixes = buildFileLinkParentSuffixByPath(paths);+ const segments: string[] = [];+ let text = "";+ const flush = () => {+ if (text.trim()) segments.push(text);+ text = "";+ };+ const visit = (node: TextTree, inPre = false, inlineSkills = false) => {+ const href = node.properties?.href ?? node.properties?.src;+ if (userMessage && typeof href === "string" && parseComposerContextHref(href)) {+ flush();+ return;+ }+ const citation =+ node.tagName === "a" && typeof href === "string" ? parseAssistantCitationHref(href) : null;+ if (citation) {+ // Matches the citation chip, which shows its label instead of the link text.+ text += assistantCitationLabel(citation);+ return;+ }+ {+ let candidate: string | null = null;+ if (node.tagName === "a" && typeof href === "string") {+ candidate = href;+ } else if (+ node.tagName === "code" &&+ !inPre &&+ node.properties?.dataInlineCode !== undefined+ ) {+ candidate = inlineCodeFilePathCandidate(+ (node.children ?? []).map((child) => child.value ?? "").join(""),+ );+ }+ const target = candidate ? resolveMarkdownFileLinkTarget(candidate, cwd) : null;+ if (target) {+ const labelText = (node: TextTree): string =>+ node.value ?? (node.children ?? []).map(labelText).join("");+ const label = labelText(node);+ if (node.tagName === "a" && candidate && !isMarkdownFileLinkLabel(label, candidate))+ text += `${label} `;+ text += fileLinkLabel(splitFilePathPosition(target), parentSuffixes);+ return;+ }+ }+ const template = artifactTemplateFromHastProperties(node.properties);+ if (template) {+ // Matches the card's visible text; its action button is not indexed.+ flush();+ segments.push(+ template.displayName,+ codexArtifactTemplatePresentationLabel(template.artifactKind),+ );+ return;+ }+ const block = THREAD_FIND_BLOCK_TAGS.has(node.tagName ?? "");+ if (block) flush();+ if (node.type === "text" || (userMessage && node.type === "raw")) {+ let value = node.value ?? "";+ if (inlineSkills) {+ let cursor = 0;+ let rendered = "";+ for (const { start, end, skill } of matchInlineSkills(value, skills)) {+ rendered += value.slice(cursor, start) + formatProviderSkillDisplayName(skill);+ cursor = end;+ }+ value = rendered + value.slice(cursor);+ }+ text += inPre ? value : value.replace(/\r?\n/g, " ");+ }+ const renderSkills =+ node.tagName === "code" || node.tagName === "a"+ ? false+ : inlineSkills || node.tagName === "p" || node.tagName === "li";+ for (const child of node.children ?? [])+ visit(child, inPre || node.tagName === "pre", renderSkills);+ if (block) flush();+ };+ visit(tree);+ flush();+ return segments;+}++/** Plans render `$skill` tokens literally (no skill chips), so they are indexed as written. */+export function searchablePlanSegments(markdown: string, cwd?: string): readonly string[] {+ return [+ proposedPlanTitle(markdown) ?? "Proposed plan",+ ...markdownThreadFindText(stripDisplayedPlanMarkdown(markdown), false, cwd, []),+ ];+}++export function searchableMessageSegments(+ message: Pick<OrchestrationV2ConversationMessage, "role" | "text" | "streaming" | "context">,+ cwd?: string,+ skills: readonly InlineSkill[] = [],+): readonly string[] | null {+ if (message.role === "user") {+ const text = message.context ? message.text : upgradeLegacyContextMessage(message.text).text;+ return markdownThreadFindText(text, true, cwd, skills);+ }+ if (message.role !== "assistant") return null;+ return markdownThreadFindText(+ message.text || (message.streaming ? "" : "(empty response)"),+ false,+ cwd,+ skills,+ shouldPreserveAssistantLineBreaks(message.text),+ );+}diff --git a/packages/shared/src/threadSearch.test.ts b/packages/shared/src/threadSearch.test.tsnew file mode 100644index 00000000000..d25bc91fa04--- /dev/null+++ b/packages/shared/src/threadSearch.test.ts@@ -0,0 +1,23 @@+import { expect, it } from "vite-plus/test";+import { findThreadSearchOccurrences, splitThreadSearchText } from "./threadSearch.ts";++it("finds non-overlapping occurrences without invalidating Unicode offsets", () => {+ expect(findThreadSearchOccurrences("Deploy the Deployment", "deploy")).toEqual([0, 11]);+ expect(findThreadSearchOccurrences("aaaa", "aa")).toEqual([0, 2]);+ expect(findThreadSearchOccurrences("İİİ needle", "needle")).toEqual([4]);+});++it("splits search text into highlighted and unhighlighted parts", () => {+ expect(splitThreadSearchText("one TWO three two", " two ")).toEqual([+ { text: "one ", highlighted: false, start: 0 },+ { text: "TWO", highlighted: true, start: 4 },+ { text: " three ", highlighted: false, start: 7 },+ { text: "two", highlighted: true, start: 14 },+ ]);+});++it("matches both Greek sigma forms without changing source offsets", () => {+ expect(findThreadSearchOccurrences("ΟΣ ος οσ", "Σ")).toEqual([1, 4, 7]);+ expect(findThreadSearchOccurrences("ΟΣ ος οσ", "ς")).toEqual([1, 4, 7]);+ expect(findThreadSearchOccurrences("İ ΟΣ", "Σ")).toEqual([3]);+});diff --git a/packages/shared/src/threadSearch.ts b/packages/shared/src/threadSearch.tsnew file mode 100644index 00000000000..df86c3b94b2--- /dev/null+++ b/packages/shared/src/threadSearch.ts@@ -0,0 +1,70 @@+interface ThreadSearchTextPart {+ readonly text: string;+ readonly highlighted: boolean;+ readonly start: number;+}++function foldThreadSearchCase(text: string): string {+ const lowered = text.toLowerCase().replace(/ς/g, "σ");+ if (lowered.length === text.length) return lowered;++ let folded = "";+ for (const character of text) {+ const loweredCharacter = character.toLowerCase().replace(/ς/g, "σ");+ folded += loweredCharacter.length === character.length ? loweredCharacter : character;+ }+ return folded;+}++function scanThreadSearchOccurrences(text: string, query: string, offsets?: number[]): number {+ if (text.length === 0 || query.length === 0) return 0;++ const foldedText = foldThreadSearchCase(text);+ const foldedQuery = foldThreadSearchCase(query);+ let count = 0;+ let cursor = 0;++ while (cursor <= foldedText.length - foldedQuery.length) {+ const offset = foldedText.indexOf(foldedQuery, cursor);+ if (offset === -1) break;+ offsets?.push(offset);+ count += 1;+ cursor = offset + foldedQuery.length;+ }+ return count;+}++export function countThreadSearchOccurrences(text: string, query: string): number {+ return scanThreadSearchOccurrences(text, query);+}++export function findThreadSearchOccurrences(text: string, query: string): number[] {+ const offsets: number[] = [];+ scanThreadSearchOccurrences(text, query, offsets);+ return offsets;+}++export function splitThreadSearchText(text: string, query: string): ThreadSearchTextPart[] {+ const normalizedQuery = query.trim();+ if (normalizedQuery.length === 0) {+ return [{ text, highlighted: false, start: 0 }];+ }++ const parts: ThreadSearchTextPart[] = [];+ let cursor = 0;+ for (const offset of findThreadSearchOccurrences(text, normalizedQuery)) {+ if (offset > cursor) {+ parts.push({ text: text.slice(cursor, offset), highlighted: false, start: cursor });+ }+ parts.push({+ text: text.slice(offset, offset + normalizedQuery.length),+ highlighted: true,+ start: offset,+ });+ cursor = offset + normalizedQuery.length;+ }+ if (cursor < text.length) {+ parts.push({ text: text.slice(cursor), highlighted: false, start: cursor });+ }+ return parts;+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex dcf710bdd07..e14b1334c32 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -30,9 +30,42 @@ catalogs:jose:specifier: 6.2.2version: 6.2.2+ mdast-util-directive:+ specifier: 3.1.0+ version: 3.1.0+ micromark-extension-directive:+ specifier: 4.0.0+ version: 4.0.0+ micromark-util-character:+ specifier: 2.1.1+ version: 2.1.1+ micromark-util-types:+ specifier: 2.0.2+ version: 2.0.2+ rehype-raw:+ specifier: 7.0.0+ version: 7.0.0+ rehype-sanitize:+ specifier: 6.0.0+ version: 6.0.0+ remark-breaks:+ specifier: 4.0.0+ version: 4.0.0+ remark-gfm:+ specifier: 4.0.1+ version: 4.0.1+ remark-parse:+ specifier: 11.0.0+ version: 11.0.0+ remark-rehype:+ specifier: 11.1.2+ version: 11.1.2typescript:specifier: 7.0.2version: 7.0.2+ unified:+ specifier: 11.0.5+ version: 11.0.5overrides:'@exodus/bytes>@noble/hashes': 1.8.0@@ -777,17 +810,8 @@ importers:react-markdown:specifier: ^10.1.0version: 10.1.0(@types/[email protected])([email protected])- rehype-raw:- specifier: ^7.0.0- version: 7.0.0- rehype-sanitize:- specifier: ^6.0.0- version: 6.0.0- remark-breaks:- specifier: ^4.0.0- version: 4.0.0remark-gfm:- specifier: ^4.0.1+ specifier: 'catalog:'version: 4.0.1tailwind-merge:specifier: ^3.4.0@@ -857,7 +881,7 @@ importers:specifier: 4.3.3version: 4.3.3unified:- specifier: ^11.0.5+ specifier: 'catalog:'version: 11.0.5vite:specifier: npm:@voidzero-dev/[email protected]@@ -957,24 +981,9 @@ importers:effect:specifier: 4.0.1version: 4.0.1(patch_hash=a33cba07c41f32374c2aaa86ea4a84d3ab9a872a78c94b65e929b19f8361856f)- mdast-util-directive:- specifier: ^3.1.0- version: 3.1.0- micromark-extension-directive:- specifier: ^4.0.0- version: 4.0.0- micromark-util-character:- specifier: ^2.1.1- version: 2.1.1- remark-parse:- specifier: ^11.0.0- version: 11.0.0three:specifier: 0.180.0version: 0.180.0- unified:- specifier: ^11.0.5- version: 11.0.5devDependencies:'@effect/vitest':specifier: 4.0.1@@ -982,9 +991,6 @@ importers:'@types/three':specifier: 0.180.0version: 0.180.0- micromark-util-types:- specifier: ^2.0.2- version: 2.0.2vite-plus:specifier: 1.0.0version: 1.0.0(@types/[email protected])(@vitest/[email protected]([email protected]))([email protected])([email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])@@ -1063,6 +1069,36 @@ importers:jose:specifier: 'catalog:'version: 6.2.2+ mdast-util-directive:+ specifier: 'catalog:'+ version: 3.1.0+ micromark-extension-directive:+ specifier: 'catalog:'+ version: 4.0.0+ micromark-util-character:+ specifier: 'catalog:'+ version: 2.1.1+ rehype-raw:+ specifier: 'catalog:'+ version: 7.0.0+ rehype-sanitize:+ specifier: 'catalog:'+ version: 6.0.0+ remark-breaks:+ specifier: 'catalog:'+ version: 4.0.0+ remark-gfm:+ specifier: 'catalog:'+ version: 4.0.1+ remark-parse:+ specifier: 'catalog:'+ version: 11.0.0+ remark-rehype:+ specifier: 'catalog:'+ version: 11.1.2+ unified:+ specifier: 'catalog:'+ version: 11.0.5yaml:specifier: ^2.9.0version: 2.9.0@@ -1076,6 +1112,9 @@ importers:'@types/node':specifier: 24.12.4version: 24.12.4+ micromark-util-types:+ specifier: 'catalog:'+ version: 2.0.2vite-plus:specifier: 1.0.0version: 1.0.0(@types/[email protected])(@vitest/[email protected]([email protected]))([email protected])([email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])@@ -19004,7 +19043,7 @@ snapshots:dependencies:- '@types/hast': 3.0.4+ '@types/hast': 3.0.5'@types/unist': 3.0.3'@ungap/structured-clone': 1.3.1hast-util-from-parse5: 8.0.3@@ -19020,7 +19059,7 @@ snapshots:dependencies:- '@types/hast': 3.0.4+ '@types/hast': 3.0.5'@ungap/structured-clone': 1.3.1unist-util-position: 5.0.0@@ -21445,13 +21484,13 @@ snapshots:dependencies:- '@types/hast': 3.0.4+ '@types/hast': 3.0.5hast-util-raw: 9.1.0vfile: 6.0.3dependencies:- '@types/hast': 3.0.4+ '@types/hast': 3.0.5hast-util-sanitize: 5.0.2@@ -21482,7 +21521,7 @@ snapshots:dependencies:- '@types/hast': 3.0.4+ '@types/hast': 3.0.5'@types/mdast': 4.0.4mdast-util-to-hast: 13.2.1unified: 11.0.5diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 70b61095986..87c007312a7 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -56,6 +56,19 @@ catalog:vite-plus: 1.0.0ws: 8.22.0yaml: ^2.9.0+ # Markdown pipeline: the server counts find matches with the same parser the+ # web renders with, so both must resolve to one version.+ mdast-util-directive: 3.1.0+ micromark-extension-directive: 4.0.0+ micromark-util-character: 2.1.1+ micromark-util-types: 2.0.2+ rehype-raw: 7.0.0+ rehype-sanitize: 6.0.0+ remark-breaks: 4.0.0+ remark-gfm: 4.0.1+ remark-parse: 11.0.0+ remark-rehype: 11.1.2+ unified: 11.0.5minimumReleaseAgeExclude: