Skip to content
TypeScript

perf(clients): thread search reuses per-thread fields across keystrokes (#26936)

Hieu Le9504a09f089a
diff --git a/packages/client-runtime/src/state/threadSearch.test.ts b/packages/client-runtime/src/state/threadSearch.test.ts
index b8d180e3a0f..d9f2cca584f 100644
--- a/packages/client-runtime/src/state/threadSearch.test.ts
+++ b/packages/client-runtime/src/state/threadSearch.test.ts
@@ -191,6 +191,10 @@ it("ranks recent threads by this client's own latest open", () => {
threadSearchSubject({ ...thread, id: ThreadId.make("thread-unrecorded"), opens: null }, null)
.opens,
).toEqual({ openedAt: 6_000, score: 1, picks: [] });
+ // A subject built before the open does not hide it.
+ claimThreadOpen(envA, "thread-local", 7_000);
+ expect(threadSearchSubject(thread, null).opens?.openedAt).toBe(7_000);
+ expect(threadSearchSubject(thread, "Project").projectTitle).toBe("Project");
});
it("counts recency from what the user wrote, else from when the thread began", () => {
diff --git a/packages/client-runtime/src/state/threadSearch.ts b/packages/client-runtime/src/state/threadSearch.ts
index caaebb016ec..23794cec2c3 100644
--- a/packages/client-runtime/src/state/threadSearch.ts
+++ b/packages/client-runtime/src/state/threadSearch.ts
@@ -29,6 +29,7 @@ const sentThreadOpens = new Map<string, number>();
// When this client last opened each thread, sent or not, so recent threads
// follow quick switches the server merges.
const localThreadOpens = new Map<string, number>();
+let localThreadOpensVersion = 0;
/**
* Records that this client opened a thread, and says whether to send the open
* to the server now.
@@ -36,6 +37,7 @@ const localThreadOpens = new Map<string, number>();
export function claimThreadOpen(environmentId: EnvironmentId, threadId: string, now: number) {
const key = `${environmentId}:${threadId}`;
localThreadOpens.set(key, now);
+ localThreadOpensVersion += 1;
if (now - (sentThreadOpens.get(key) ?? Number.NEGATIVE_INFINITY) < THREAD_OPEN_DEDUPE_MS) {
return false;
}
@@ -208,6 +210,41 @@ export function threadSearchSubject(
thread: ThreadSearchShell,
projectTitle: string | null | undefined,
environmentLabel?: string | null,
+): ThreadSearchSubject {
+ // A keystroke ranks the same shells again, so a subject is built once per shell.
+ const cached = subjectCache.get(thread);
+ if (
+ cached !== undefined &&
+ cached.projectTitle === projectTitle &&
+ cached.environmentLabel === environmentLabel &&
+ cached.opensVersion === localThreadOpensVersion
+ ) {
+ return cached.subject;
+ }
+ const subject = buildThreadSearchSubject(thread, projectTitle, environmentLabel);
+ subjectCache.set(thread, {
+ projectTitle,
+ environmentLabel,
+ opensVersion: localThreadOpensVersion,
+ subject,
+ });
+ return subject;
+}
+
+const subjectCache = new WeakMap<
+ ThreadSearchShell,
+ {
+ readonly projectTitle: string | null | undefined;
+ readonly environmentLabel: string | null | undefined;
+ readonly opensVersion: number;
+ readonly subject: ThreadSearchSubject;
+ }
+>();
+
+function buildThreadSearchSubject(
+ thread: ThreadSearchShell,
+ projectTitle: string | null | undefined,
+ environmentLabel: string | null | undefined,
): ThreadSearchSubject {
// What the user wrote, not agent wakes or task notices in the user role. A
// thread the user never wrote in counts from its creation; an older server
diff --git a/packages/shared/src/paletteSearch.ts b/packages/shared/src/paletteSearch.ts
index efcccd8aa4e..8594100a27e 100644
--- a/packages/shared/src/paletteSearch.ts
+++ b/packages/shared/src/paletteSearch.ts
@@ -202,14 +202,17 @@ function matchToken(
): TokenMatch | null {
if (token.length === 0) return null;
let best: TokenMatch | null = null;
- const ownBoundary = !ALPHANUMERIC.test(token[0]!) && !SYMBOL.test(token[0]!);
+ let ownBoundary: boolean | undefined;
for (
let index = field.text.indexOf(token);
index !== -1;
index = field.text.indexOf(token, index + 1)
) {
// A token that opens with punctuation (".ts") brings its own boundary, as in messages.
- if (field.wordStarts[index] || ownBoundary) {
+ if (
+ field.wordStarts[index] ||
+ (ownBoundary ??= !ALPHANUMERIC.test(token[0]!) && !SYMBOL.test(token[0]!))
+ ) {
// Whole when the match ends where a word ends: "t3c" is a prefix of
// "t3code", ".ts" whole in "index.ts" but a prefix in "parser.tsx".
const end = index + token.length;
@@ -275,9 +278,12 @@ function matchToken(
* Allow them at its start ("t3co"), before three letters ("gomod"), or a whole word ("vscode").
*/
function matchJoinedWords(field: SearchField, token: string): TokenMatch | null {
- const firstWord = field.wordStarts.indexOf(1);
- for (let start = 0; start < field.text.length; start++) {
- if (!field.wordStarts[start] || field.text[start] !== token[0]) continue;
+ for (
+ let start = field.text.indexOf(token[0]!);
+ start !== -1;
+ start = field.text.indexOf(token[0]!, start + 1)
+ ) {
+ if (!field.wordStarts[start]) continue;
const runs: SearchRange[] = [];
let at = start;
let rest = token;
@@ -300,7 +306,7 @@ function matchJoinedWords(field: SearchField, token: string): TokenMatch | null
if (
last.end === wordEnd(field, last.start) ||
last.end - last.start >= 3 ||
- start === firstWord ||
+ start === field.wordStarts.indexOf(1) ||
runs.slice(0, -1).every((run) => run.end - run.start >= 3)
) {
return { score: JOINED_WORDS, start, end: last.end, letters: runs };
@@ -311,6 +317,8 @@ function matchJoinedWords(field: SearchField, token: string): TokenMatch | null
interface WeightedSearchField {
readonly value: string;
+ /** `value` folded; set on first use, so fields kept across keystrokes fold once. */
+ prepared?: SearchField;
readonly weight: number;
/** Only a whole-word match counts, as for a short query against keywords. */
readonly wholeWords?: boolean;
@@ -342,6 +350,10 @@ interface SearchFieldsMatch {
readonly primaryRanges: ReadonlyArray<SearchRange>;
}
+function preparedField(weighted: WeightedSearchField): SearchField {
+ return (weighted.prepared ??= prepareSearchField(weighted.value));
+}
+
const FILLER_WORDS = new Set(["a", "an", "and", "for", "in", "of", "on", "the", "to", "with"]);
// Sorted, with overlapping ranges joined.
@@ -358,6 +370,25 @@ function mergeRanges(ranges: ReadonlyArray<SearchRange>): SearchRange[] {
return merged;
}
+// A keystroke scores every thread for one query, so its tokens are split once.
+let lastQuery:
+ | { readonly query: string; readonly tokens: string[]; readonly fillerOptional: boolean }
+ | undefined;
+
+function queryTokens(normalizedQuery: string) {
+ if (lastQuery?.query !== normalizedQuery) {
+ const tokens = normalizedQuery.split(" ").filter((token) => token.length > 0);
+ // A phrase-style query ("fix the sidebar") carries filler words a name may
+ // leave out; they count where they match but are not required.
+ lastQuery = {
+ query: normalizedQuery,
+ tokens,
+ fillerOptional: tokens.some((token) => !FILLER_WORDS.has(token)),
+ };
+ }
+ return lastQuery;
+}
+
/**
* Every query token must match some field. Quality is the mean of each token's
* best weighted match, plus a bonus when the first field holds the whole query
@@ -369,23 +400,10 @@ function matchSearchFields(
options?: { readonly typos?: boolean },
): SearchFieldsMatch | null {
if (normalizedQuery.length === 0) return null;
- const prepared = fields
- .filter((field) => field.value.length > 0)
- .map((field) => ({
- field: prepareSearchField(field.value),
- weight: field.weight,
- wholeWords: field.wholeWords ?? false,
- keyword: field.keyword ?? false,
- context: field.context ?? false,
- allowMidWord: field.midWord ?? false,
- }));
- const primary = fields[0]?.value ? prepared[0]?.field : undefined;
+ const primary = fields[0]?.value ? preparedField(fields[0]) : undefined;
// An empty token would match everywhere, and loop forever in `matchToken`.
- const tokens = normalizedQuery.split(" ").filter((token) => token.length > 0);
+ const { tokens, fillerOptional } = queryTokens(normalizedQuery);
if (tokens.length === 0) return null;
- // A phrase-style query ("fix the sidebar") carries filler words a name may
- // leave out; they count where they match but are not required.
- const fillerOptional = tokens.some((token) => !FILLER_WORDS.has(token));
const primaryRanges: SearchRange[] = [];
let total = 0;
let counted = 0;
@@ -394,11 +412,14 @@ function matchSearchFields(
let best = 0;
let bestPrimary: TokenMatch | null = null;
let atWordStart = false;
- for (const { field, weight, wholeWords, keyword, context, allowMidWord } of prepared) {
+ for (const weighted of fields) {
+ if (weighted.value.length === 0) continue;
+ const { weight, wholeWords, keyword, context, midWord } = weighted;
+ const field = preparedField(weighted);
if (best >= weight && field !== primary && atWordStart) continue;
const typos = (options?.typos ?? false) && !keyword;
// Joined words only count in the name.
- const match = matchToken(field, token, typos, field === primary, allowMidWord);
+ const match = matchToken(field, token, typos, field === primary, midWord ?? false);
if (match === null || match.score < (wholeWords ? WHOLE_WORD : keyword ? 0.7 : 0)) continue;
if (field === primary) bestPrimary = match;
if (match.score >= 0.7 && !context) atWordStart = true;
@@ -801,6 +822,9 @@ function threadUsageBoost(thread: ThreadSearchSubject, now: number): number {
const REFERENCE_PREFIX_MIN = 8;
+// A number is never cut short: ".../pull/2288" is not pull request 22889.
+const notCut = (text: string, end: number) => !DIGIT.test(text[end] ?? "");
+
// IDs and URLs have many word starts, so field matching would let short queries hit every thread.
// Require a long prefix, or any long part containing a digit. Both are ASCII; lowercasing suffices.
function matchReference(
@@ -808,14 +832,8 @@ function matchReference(
thread: ThreadSearchSubject,
): SearchFieldsMatch | null {
if (normalizedQuery.length < REFERENCE_PREFIX_MIN) return null;
- const references = [
- ...(thread.id ? [thread.id] : []),
- ...(thread.pullRequests ?? []).flatMap((pullRequest) => pullRequest.references ?? []),
- ];
const anywhere = DIGIT.test(normalizedQuery);
- // A number is never cut short: ".../pull/2288" is not pull request 22889.
- const notCut = (text: string, end: number) => !DIGIT.test(text[end] ?? "");
- return references.some((reference) => {
+ const matches = (reference: string) => {
const folded = reference.toLowerCase();
const at = folded.indexOf(normalizedQuery);
// A pasted link may go on past the reference: ".../pull/22889/files".
@@ -823,7 +841,9 @@ function matchReference(
? (at !== -1 && notCut(folded, at + normalizedQuery.length)) ||
(normalizedQuery.startsWith(folded) && notCut(normalizedQuery, folded.length))
: at === 0;
- })
+ };
+ return (thread.id && matches(thread.id)) ||
+ thread.pullRequests?.some((pullRequest) => pullRequest.references?.some(matches))
? { quality: 0.6, strong: true, primaryRanges: [] }
: null;
}
@@ -934,6 +954,45 @@ function matchHint(
return rest && rest !== normalizedQuery ? hintFor(rest) : undefined;
}
+// A keystroke scores each thread's fields again, so they are listed once per subject.
+const threadFieldsCache = new WeakMap<ThreadSearchSubject, ReadonlyArray<WeightedSearchField>>();
+
+function threadSearchFields(thread: ThreadSearchSubject): ReadonlyArray<WeightedSearchField> {
+ const cached = threadFieldsCache.get(thread);
+ if (cached) return cached;
+ const fields: WeightedSearchField[] = [{ value: thread.title, weight: 1, midWord: true }];
+ for (const pullRequest of thread.pullRequests ?? []) {
+ fields.push({ value: `#${pullRequest.number}`, weight: 1 });
+ if (pullRequest.title) fields.push({ value: pullRequest.title, weight: 0.5 });
+ }
+ const branch = searchableBranch(thread.branch);
+ if (branch) fields.push({ value: branch, weight: 0.6 });
+ if (thread.projectTitle) {
+ fields.push({ value: thread.projectTitle, weight: 0.25, context: true });
+ }
+ if (thread.environmentLabel) {
+ fields.push({ value: thread.environmentLabel, weight: 0.25, context: true });
+ }
+ threadFieldsCache.set(thread, fields);
+ return fields;
+}
+
+let lastFieldQuery: { readonly query: string; readonly fieldQuery: string } | undefined;
+
+// Strip pull request prefixes and the worktree prefix so queries match the stored fields.
+function threadFieldQuery(normalizedQuery: string): string {
+ if (lastFieldQuery?.query !== normalizedQuery) {
+ lastFieldQuery = {
+ query: normalizedQuery,
+ fieldQuery: normalizedQuery
+ .replace(/^(?:pr|pull request|pull)\s*(?=#?\d)/, "")
+ .replace(/^#\s*/, "")
+ .replace(WORKTREE_BRANCH_PREFIX_PATTERN, ""),
+ };
+ }
+ return lastFieldQuery.fieldQuery;
+}
+
/**
* Scores a thread for a normalized query, or null when it does not match.
* Titles and pull request numbers count fully, pull request titles and
@@ -952,24 +1011,8 @@ export function scoreThreadSearch(
readonly picks?: boolean;
},
): ThreadSearchMatch | null {
- const fields: WeightedSearchField[] = [{ value: thread.title, weight: 1, midWord: true }];
- for (const pullRequest of thread.pullRequests ?? []) {
- fields.push({ value: `#${pullRequest.number}`, weight: 1 });
- if (pullRequest.title) fields.push({ value: pullRequest.title, weight: 0.5 });
- }
- const branch = searchableBranch(thread.branch);
- if (branch) fields.push({ value: branch, weight: 0.6 });
- if (thread.projectTitle) {
- fields.push({ value: thread.projectTitle, weight: 0.25, context: true });
- }
- if (thread.environmentLabel) {
- fields.push({ value: thread.environmentLabel, weight: 0.25, context: true });
- }
- // Strip pull request prefixes and the worktree prefix so queries match the stored fields.
- const fieldQuery = normalizedQuery
- .replace(/^(?:pr|pull request|pull)\s*(?=#?\d)/, "")
- .replace(/^#\s*/, "")
- .replace(WORKTREE_BRANCH_PREFIX_PATTERN, "");
+ const fields = threadSearchFields(thread);
+ const fieldQuery = threadFieldQuery(normalizedQuery);
const fieldMatch = matchSearchFields(fieldQuery, fields, options);
const referenceMatch = fieldMatch ? null : matchReference(normalizedQuery, thread);
const match = fieldMatch ?? referenceMatch;
@@ -1102,13 +1145,15 @@ export function rankSearchGroups<
score: (item: T, options: { readonly typos: boolean }, group: G) => M | null,
): Array<{ readonly group: G; readonly ranked: ReadonlyArray<RankedSearchItem<T, M>> }> {
const rank = (typos: boolean) =>
- groups.map(({ group, items }) => ({
- group,
- ranked: items.flatMap((item) => {
- const match = score(item, { typos }, group);
- return match === null ? [] : [{ item, match }];
- }),
- }));
+ groups.map(({ group, items }) => {
+ const options = { typos };
+ const ranked: Array<RankedSearchItem<T, M>> = [];
+ for (const item of items) {
+ const match = score(item, options, group);
+ if (match !== null) ranked.push({ item, match });
+ }
+ return { group, ranked };
+ });
let ranked = rank(false);
if (!ranked.some((entry) => entry.ranked.some(({ match }) => match.strong))) {
ranked = rank(true);