feat(web): find messages and plans in the current thread (#10439)

Co-authored-by: Yash Singh <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-10-08 08:24:50 -05:00
1 parent a4c9494b0e
commit 12069eefd7
139 files changed
+8009 -1471

No files matched your search

@@ -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";
@@ -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";
@@ -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,
@@ -36,9 +36,9 @@ import { writeComposerContextClipboard } from "../../lib/composerContextClipboar
import {
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/presen
import {
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";
@@ -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";
@@ -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 (
<Text
className={cn(
+2
View File
@@ -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,
@@ -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",
@@ -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")(functio
recoverDelegatedTask,
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 })),
@@ -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_id
FROM 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) => {
@@ -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"),
File diff suppressed because it is too large. Load diff
@@ -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]!),
),
};
});
@@ -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)),
+21 -48
View File
@@ -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,
};
}),
);
}),
@@ -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): ThreadHistoryCursorPa
return 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,
});
}
@@ -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"),
+11
View File
@@ -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(
+2 -5
View File
@@ -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:"
}
@@ -1,6 +1,12 @@
// @vitest-environment jsdom
import { 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();
}
},
);
+68 -379
View File
@@ -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-ignore
type="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"}
>
<CollapsibleTrigger
className="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}>
<div
className="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>
@@ -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";
+1 -1
View File
@@ -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,
+71 -13
View File
@@ -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 ? (
<div
className="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 && (
<div
className="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 */}
@@ -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();
@@ -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";
@@ -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,
@@ -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,
+12 -1
View File
@@ -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}>
@@ -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);
@@ -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,
@@ -1,5 +1,5 @@
import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";
import {
formatProviderSkillDisplayName,
resolveProviderSkillSourceKind,
type ProviderSkillSourceKind,
} from "@t3tools/client-runtime/providerSkills";
@@ -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>
@@ -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", () => {
@@ -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): boo
return 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"],
+315 -123
View File
@@ -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>
<AssistantChangedFilesSection
turnSummary={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(prop
footer?: 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 ? (
<div
className={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 ? (
<Button
type="button"
size="xs"
@@ -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 ? (
<ChatMarkdown
text={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>
@@ -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) {
@@ -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";
@@ -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>
);
}
@@ -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);
});
@@ -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();
}}
/>
);
}
@@ -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],
);
}
@@ -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();
@@ -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;
}
@@ -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");
});
});
@@ -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}`;
}
@@ -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);
}
@@ -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);
});
});
@@ -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);
}
};
}
@@ -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();
});
});
@@ -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;
}
@@ -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);
});
});
@@ -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),
};
}
@@ -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 });
});
});
@@ -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,
});
}
@@ -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,
@@ -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;
@@ -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";
+1 -3
View File
@@ -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;
@@ -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 {
@@ -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",
+29 -2
View File
@@ -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) => {
+1 -1
View File
@@ -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;
+1 -1
View File
@@ -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";
+3 -4
View File
@@ -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("\\", "/");
+14
View File
@@ -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));
+8
View File
@@ -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",
+5 -6
View File
@@ -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>,
-260
View File
@@ -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");
+5 -48
View File
@@ -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): bool
return /\.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-linking
@@ -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(
@@ -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(
+22 -2
View File
@@ -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";
+4
View File
@@ -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",
-26
View File
@@ -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",
+1 -20
View File
@@ -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,
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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";
-63
View File
@@ -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 });
}
+69
View File
@@ -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);
+24
View File
@@ -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",
+94
View File
@@ -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);
+22
View File
@@ -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,
+8
View File
@@ -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.
## Precedence
The last rule whose key and condition both match wins, even if it belongs to a
+1 -23
View File
@@ -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:"
}
}
@@ -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+.-]*:/;
@@ -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 =
+3 -5
View File
@@ -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,
@@ -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,
@@ -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[] {
@@ -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.subscribeServerLifecycle
@@ -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,
@@ -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",
+8 -1
View File
@@ -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);
@@ -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. */
@@ -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,
@@ -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);
}),
),
});
@@ -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),
}),
});
@@ -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 = {
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more