The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 18:15 UTC
feat(search): Cmd+K finds the right thread first, with indexed message search (#24343)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 24, 2026 at 04:05 UTC
bb7783e295506ad423f527ed28a019836e331e8c
69 files changed
+5797
-718
apps/mobile/src/features/archive/archivedThreadList.ts
+10
-3
@@ -5,7 +5,9 @@ import {
5
type EnvironmentProject,
6
type EnvironmentThreadShell,
7
} from "@t3tools/client-runtime/state/shell";
8
+import { threadSearchSubject } from "@t3tools/client-runtime/state/thread-search";
9
import type { EnvironmentId } from "@t3tools/contracts";
10
+import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
11
import * as Arr from "effect/Array";
12
import * as Order from "effect/Order";
13
@@ -36,6 +38,7 @@ export function buildArchivedThreadGroups(input: {
38
readonly sortOrder: ArchivedThreadSortOrder;
39
}): ReadonlyArray<ArchivedThreadGroup> {
40
const query = input.searchQuery.trim().toLocaleLowerCase();
41
+ const foldedQuery = foldSearchQuery(input.searchQuery);
42
const groups: ArchivedThreadGroup[] = [];
43
44
for (const entry of input.snapshots) {
@@ -62,11 +65,15 @@ export function buildArchivedThreadGroups(input: {
65
matchesQuery(project.title, query) ||
66
matchesQuery(project.workspaceRoot, query) ||
67
matchesQuery(environmentLabel, query);
68
+ // Threads match as in every other thread search; the list keeps its own order.
69
const matchingThreads = groupMatches
70
? projectThreads
67
- : projectThreads.filter(
68
- (thread) => matchesQuery(thread.title, query) || matchesQuery(thread.branch, query),
69
- );
71
+ : rankSearchItems(projectThreads, (thread, options) =>
72
+ scoreThreadSearch(foldedQuery, threadSearchSubject(thread, null), 0, {
73
+ ...options,
74
+ picks: false,
75
+ }),
76
+ ).map(({ item }) => item);
77
78
if (matchingThreads.length === 0) {
79
continue;
apps/mobile/src/features/home/HomeScreen.tsx
+29
-19
@@ -52,6 +52,8 @@ import {
52
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
53
import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
54
import { useThreadSearch } from "../../state/queries";
55
+import { requestThreadMessageJump } from "../threads/threadMessageJump";
56
+import { useThreadListSearchMatches } from "../threads/useThreadListSearchMatches";
57
import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
58
import { usePendingThreadOrder } from "../../state/thread-order";
59
import { threadListEnvironmentsAtom } from "../../state/server";
@@ -297,16 +299,8 @@ export function HomeScreen(props: HomeScreenProps) {
299
? [props.selectedEnvironmentId]
300
: [];
301
const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
300
- const threadSearchMatchByKey = (() => {
301
- const matches = new Map<string, EnvironmentThreadSearchMatch>();
302
- for (const match of threadSearch.matches) {
303
- if (match.source === "user" || match.source === "assistant") {
304
- matches.set(threadSearchMatchKey(match), match);
305
- }
306
- }
307
- return matches;
308
- })();
309
- const matchedThreadKeys = new Set(threadSearch.matches.map(threadSearchMatchKey));
302
+ const threadSearchMatchByKey = useThreadListSearchMatches(props.threads, threadSearch);
303
+ const matchedThreadKeys = new Set(threadSearchMatchByKey.keys());
304
const handleSwipeableWillOpen = (methods: SwipeableMethods) => {
305
if (openSwipeableRef.current !== methods) {
306
openSwipeableRef.current?.close();
@@ -561,7 +555,19 @@ export function HomeScreen(props: HomeScreenProps) {
555
shelfPreferencesLoading: !shelfPreferencesLoaded,
556
});
557
564
- useThreadJumpShortcuts(threadListV2Items, props.onSelectThread);
558
+ // A row listed for a message match opens the thread at that message, by
559
+ // tap or by shortcut.
560
+ const selectThread = (thread: EnvironmentThreadShell) => {
561
+ const key = threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id });
562
+ const messageId = threadListV2Layout.contentOnlyThreadKeys.has(key)
563
+ ? threadSearchMatchByKey.get(key)?.messageId
564
+ : undefined;
565
+ if (messageId) {
566
+ requestThreadMessageJump(scopedThreadKey(thread.environmentId, thread.id), messageId);
567
+ }
568
+ props.onSelectThread(thread);
569
+ };
570
+ useThreadJumpShortcuts(threadListV2Items, selectThread);
571
useEffect(() => {
572
if (swipeEnabled) activateVisibleRows(threadListV2Items);
573
}, [activateVisibleRows, swipeEnabled, threadListV2Items]);
@@ -662,14 +668,18 @@ export function HomeScreen(props: HomeScreenProps) {
668
: null
669
}
670
environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
665
- searchMatch={threadSearchMatchByKey.get(
666
- threadSearchMatchKey({
667
- environmentId: thread.environmentId,
668
- threadId: thread.id,
669
- }),
670
- )}
671
- searchQuery={props.searchQuery}
672
- onSelectThread={props.onSelectThread}
671
+ searchMatch={
672
+ // Only rows listed for their messages show one and open at it.
673
+ threadListV2Layout.contentOnlyThreadKeys.has(
674
+ threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
675
+ )
676
+ ? threadSearchMatchByKey.get(
677
+ threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
678
+ )
679
+ : undefined
680
+ }
681
+ searchQuery={threadSearch.query}
682
+ onSelectThread={selectThread}
683
onOpenThreadPullRequests={handleOpenThreadPullRequests}
684
onDeleteThread={handleDeleteThread}
685
onArchiveThread={props.onArchiveThread}
apps/mobile/src/features/keyboard/CommandPalette.tsx
+175
-40
@@ -1,8 +1,21 @@
1
import { uuidv4 } from "../../lib/uuid";
2
import { useNavigation } from "@react-navigation/native";
3
-import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
3
+import {
4
+ claimThreadOpen,
5
+ nextShownOrder,
6
+ threadSearchSubject,
7
+ type EnvironmentThreadSearchMatch,
8
+ type ShownOrder,
9
+} from "@t3tools/client-runtime/state/thread-search";
10
import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";
5
-import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
11
+import {
12
+ foldSearchQuery,
13
+ PALETTE_MESSAGE_LIMIT,
14
+ rankMessageMatches,
15
+ splitSearchText,
16
+ pickedQuery,
17
+ threadRecentUse,
18
+} from "@t3tools/shared/paletteSearch";
19
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
20
import {
21
FlatList,
@@ -30,6 +43,9 @@ import { useNativeLayoutMetrics } from "../../native/native-layout-metrics";
43
import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
44
import { useProjects, useThreadShell, useThreadShells } from "../../state/entities";
45
import { useThreadSearch } from "../../state/queries";
46
+import { requestThreadMessageJump } from "../threads/threadMessageJump";
47
+import { threadEnvironment } from "../../state/threads";
48
+import { useAtomCommand } from "../../state/use-atom-command";
49
import { useWorkspaceEnvironments } from "../../state/workspace";
50
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
51
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
@@ -39,6 +55,7 @@ import {
55
filterCommandPaletteItems,
56
nextPaletteIndex,
57
type CommandPaletteItem,
58
+ type CommandPaletteResult,
59
} from "./commandPaletteItems";
60
import { parseActiveThreadPath, type HardwareKeyboardCommand } from "./hardwareKeyboardCommands";
61
import { threadJumpIndex } from "./threadKeyboardShortcuts";
@@ -52,6 +69,8 @@ const PALETTE_COMMANDS: ReadonlyArray<HardwareKeyboardCommand> = [
69
...THREAD_JUMP_KEYBINDING_COMMANDS,
70
];
71
const ROW_HEIGHT = 50;
72
+// The "In messages" label above the first message match; server results always come last.
73
+const SECTION_LABEL_HEIGHT = 26;
74
75
const ACTION_ICONS: Record<string, AppSymbolName> = {
76
newTask: "square.and.pencil",
@@ -74,7 +93,7 @@ function itemIcon(item: CommandPaletteItem): AppSymbolName {
93
}
94
95
function PaletteRow(props: {
77
- readonly item: CommandPaletteItem;
96
+ readonly item: CommandPaletteResult;
97
readonly index: number;
98
readonly selected: boolean;
99
readonly searchMatch?: EnvironmentThreadSearchMatch;
@@ -121,9 +140,34 @@ function PaletteRow(props: {
140
)}
141
</View>
142
<View className="flex-1">
124
- <Text numberOfLines={1} className={cn("text-base", foregroundClassName)}>
125
- {props.item.title}
126
- </Text>
143
+ <View className="flex-row items-baseline gap-2">
144
+ <Text numberOfLines={1} className={cn("shrink text-base", foregroundClassName)}>
145
+ {props.item.titleRanges?.length
146
+ ? splitSearchText(props.item.title, props.item.titleRanges).map((part) => (
147
+ <Text
148
+ key={part.start}
149
+ className={cn("text-base", part.highlighted && "font-t3-bold")}
150
+ >
151
+ {part.text}
152
+ </Text>
153
+ ))
154
+ : props.item.title}
155
+ </Text>
156
+ {/* The second line shows the snippet or hint, so keep where the thread
157
+ lives, unless the hint already names it. */}
158
+ {(props.searchMatch ||
159
+ (props.item.matchHint &&
160
+ props.item.matchHint.label !== "Project" &&
161
+ props.item.matchHint.label !== "Environment")) &&
162
+ props.item.detail ? (
163
+ <Text
164
+ numberOfLines={1}
165
+ className={cn("max-w-[45%] shrink-0 text-sm", mutedForegroundClassName)}
166
+ >
167
+ {props.item.detail}
168
+ </Text>
169
+ ) : null}
170
+ </View>
171
{props.searchMatch ? (
172
<ThreadSearchMatchExcerpt
173
match={props.searchMatch}
@@ -131,6 +175,15 @@ function PaletteRow(props: {
175
selected={props.selected}
176
compact
177
/>
178
+ ) : props.item.matchHint ? (
179
+ <Text numberOfLines={1} className={cn("text-sm", mutedForegroundClassName)}>
180
+ {props.item.matchHint.label}:{" "}
181
+ {splitSearchText(props.item.matchHint.text, props.item.matchHint.ranges).map((part) => (
182
+ <Text key={part.start} className={cn("text-sm", part.highlighted && "font-t3-bold")}>
183
+ {part.text}
184
+ </Text>
185
+ ))}
186
+ </Text>
187
) : props.item.detail ? (
188
<Text numberOfLines={1} className={cn("text-sm", mutedForegroundClassName)}>
189
{props.item.detail}
@@ -162,15 +215,18 @@ export function CommandPalette(props: {
215
const threads = useThreadShells();
216
const activeThreadRef = useMemo(() => parseActiveThreadPath(props.pathname), [props.pathname]);
217
const activeThread = useThreadShell(activeThreadRef);
218
+ const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
219
const environments = useWorkspaceEnvironments();
220
const { savedConnectionsById } = useSavedRemoteConnections();
221
const [query, setQuery] = useState("");
222
+ // Ranking is relative to when the palette opened, so rows do not reorder as time passes.
223
+ const [now] = useState(() => Date.now());
224
const [selection, setSelection] = useState<string | null>(null);
225
const [visible, setVisible] = useState(true);
226
const pendingAction = useRef<(() => void) | null>(null);
227
const closing = useRef(false);
228
const inputRef = useRef<TextInputInstance>(null);
173
- const listRef = useRef<FlatList<CommandPaletteItem>>(null);
229
+ const listRef = useRef<FlatList<CommandPaletteResult>>(null);
230
const { width, height } = useWindowDimensions();
231
// The palette floats above every column, so it keeps itself inside the window's side insets
232
// and to one side of a book fold.
@@ -183,11 +239,6 @@ export function CommandPalette(props: {
239
[environments],
240
);
241
const search = useThreadSearch(searchEnvironmentIds, query.startsWith(">") ? "" : query);
186
- const matchedThreadKeys = useMemo(
187
- () =>
188
- new Set(search.matches.map((match) => scopedThreadKey(match.environmentId, match.threadId))),
189
- [search.matches],
190
- );
242
const contentMatchByKey = useMemo(
243
() =>
244
new Map(
@@ -342,11 +393,6 @@ export function CommandPalette(props: {
393
(thread) =>
394
thread.archivedAt === null && thread.lineage.relationshipToParent !== "subagent",
395
)
345
- .sort((left, right) =>
346
- (right.latestUserMessageAt ?? right.updatedAt).localeCompare(
347
- left.latestUserMessageAt ?? left.updatedAt,
348
- ),
349
- )
396
.map((thread) => {
397
const project = projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId));
398
const environment =
@@ -356,19 +402,30 @@ export function CommandPalette(props: {
402
kind: "thread",
403
title: thread.title || "Untitled thread",
404
detail: [project?.title, environment].filter(Boolean).join(" · "),
359
- searchTerms: [
360
- project?.title ?? "",
361
- environment,
362
- thread.branch ?? "",
363
- ...threadPullRequestSearchTerms(thread),
364
- ],
405
+ searchTerms: [],
406
+ threadSearch: threadSearchSubject(
407
+ thread,
408
+ project?.title,
409
+ environments.length > 1 ? environment : null,
410
+ ),
411
+ // Last among threads: picking the thread already open does nothing.
412
+ ...(thread.environmentId === activeThread?.environmentId && thread.id === activeThread.id
413
+ ? { secondary: true }
414
+ : {}),
415
run: () => selectThread(thread),
416
};
417
});
418
+ // Recent means used recently: written in or opened, whichever is later.
419
+ threadItems.sort(
420
+ (left, right) =>
421
+ (right.threadSearch ? threadRecentUse(right.threadSearch) : 0) -
422
+ (left.threadSearch ? threadRecentUse(left.threadSearch) : 0),
423
+ );
424
return [...actions, ...projectItems, ...threadItems];
425
}, [
426
activeThread,
427
activeThreadRef,
428
+ environments.length,
429
navigation,
430
projects,
431
runCommand,
@@ -377,10 +434,68 @@ export function CommandPalette(props: {
434
selectThreadRoute,
435
threads,
436
]);
380
- const results = useMemo(
381
- () => filterCommandPaletteItems(items, query, matchedThreadKeys),
382
- [items, matchedThreadKeys, query],
437
+ const rankedMessageKeys = useMemo(() => {
438
+ const subjectByKey = new Map(
439
+ items.flatMap((item) => (item.threadSearch ? [[item.key, item.threadSearch] as const] : [])),
440
+ );
441
+ const keyOf = (match: EnvironmentThreadSearchMatch) =>
442
+ scopedThreadKey(match.environmentId, match.threadId);
443
+ return rankMessageMatches(
444
+ search.matches,
445
+ (match) => subjectByKey.get(keyOf(match)),
446
+ foldSearchQuery(query),
447
+ now,
448
+ { withoutTitleMatches: true },
449
+ ).map(keyOf);
450
+ }, [items, now, query, search.matches]);
451
+ // Rows already shown keep their places when a slower environment answers.
452
+ const [shownOrder, setShownOrder] = useState<ShownOrder | null>(null);
453
+ const messageOrder = nextShownOrder(
454
+ shownOrder,
455
+ search.query,
456
+ rankedMessageKeys,
457
+ PALETTE_MESSAGE_LIMIT,
458
);
459
+ if (messageOrder !== shownOrder) setShownOrder(messageOrder);
460
+ const messageMatchKeys = useMemo(
461
+ () => messageOrder.keys.slice(0, messageOrder.shown),
462
+ [messageOrder.keys, messageOrder.shown],
463
+ );
464
+ const results = useMemo(() => {
465
+ const ranked = filterCommandPaletteItems(items, query, messageMatchKeys, now);
466
+ // Recent threads leave out the open one, which would always lead them.
467
+ const activeKey = activeThread
468
+ ? scopedThreadKey(activeThread.environmentId, activeThread.id)
469
+ : null;
470
+ return query.trim() ? ranked : ranked.filter((item) => item.key !== activeKey);
471
+ }, [activeThread, items, messageMatchKeys, now, query]);
472
+ const runResult = (item: CommandPaletteResult) => {
473
+ const thread =
474
+ item.kind === "thread" && query.trim() && !query.startsWith(">")
475
+ ? threads.find(
476
+ (candidate) => scopedThreadKey(candidate.environmentId, candidate.id) === item.key,
477
+ )
478
+ : undefined;
479
+ // A message result opens the thread at that message.
480
+ const messageId = item.fromMessages ? contentMatchByKey.get(item.key)?.messageId : undefined;
481
+ if (messageId) requestThreadMessageJump(item.key, messageId);
482
+ // A pick sends its open with the query, always, so the server records it;
483
+ // the thread screen then skips its own open. The open thread is no pick.
484
+ if (thread && !item.secondary) claimThreadOpen(thread.environmentId, thread.id, Date.now());
485
+ if (thread && thread.lastVisitedAt !== undefined && !item.secondary) {
486
+ void visitThread({
487
+ environmentId: thread.environmentId,
488
+ input: {
489
+ threadId: thread.id,
490
+ visitedAt: thread.updatedAt,
491
+ opened: true,
492
+ searchQuery: pickedQuery(query),
493
+ },
494
+ });
495
+ }
496
+ item.run();
497
+ };
498
+ const firstMessageIndex = results.findIndex((item) => item.fromMessages);
499
const selectedIndex = Math.max(
500
0,
501
results.findIndex((item) => item.key === selection),
@@ -430,7 +545,7 @@ export function CommandPalette(props: {
545
);
546
} else {
547
const item = results[threadJumpIndex(command)];
433
- if (item) close(item.run);
548
+ if (item) close(() => runResult(item));
549
}
550
}
551
@@ -493,7 +608,7 @@ export function CommandPalette(props: {
608
submitBehavior="submit"
609
onSubmitEditing={() => {
610
const item = results[selectedIndex];
496
- if (item) close(item.run);
611
+ if (item) close(() => runResult(item));
612
}}
613
/>
614
</View>
@@ -505,8 +620,12 @@ export function CommandPalette(props: {
620
keyboardShouldPersistTaps="handled"
621
keyExtractor={(item) => item.key}
622
getItemLayout={(_, index) => ({
508
- length: ROW_HEIGHT,
509
- offset: ROW_HEIGHT * index,
623
+ length: ROW_HEIGHT + (index === firstMessageIndex ? SECTION_LABEL_HEIGHT : 0),
624
+ offset:
625
+ ROW_HEIGHT * index +
626
+ (firstMessageIndex !== -1 && index > firstMessageIndex
627
+ ? SECTION_LABEL_HEIGHT
628
+ : 0),
629
index,
630
})}
631
contentContainerClassName="pb-2"
@@ -515,17 +634,33 @@ export function CommandPalette(props: {
634
{search.isPending ? "Searching…" : "No results"}
635
</Text>
636
}
637
+ // Message results from slower environments may still arrive below.
638
+ ListFooterComponent={
639
+ results.length > 0 && search.isPending && !query.startsWith(">") ? (
640
+ <Text className="px-5 pt-2 text-xs text-foreground-muted">
641
+ Searching messages…
642
+ </Text>
643
+ ) : undefined
644
+ }
645
renderItem={({ item, index }) => (
519
- <PaletteRow
520
- item={item}
521
- index={index}
522
- selected={item.key === selectedKey}
523
- searchMatch={
524
- item.kind === "thread" ? contentMatchByKey.get(item.key) : undefined
525
- }
526
- searchQuery={query}
527
- onSelect={() => close(item.run)}
528
- />
646
+ <>
647
+ {index === firstMessageIndex ? (
648
+ <Text
649
+ className="px-5 pt-2 text-xs text-foreground-muted"
650
+ style={{ height: SECTION_LABEL_HEIGHT }}
651
+ >
652
+ In messages
653
+ </Text>
654
+ ) : null}
655
+ <PaletteRow
656
+ item={item}
657
+ index={index}
658
+ selected={item.key === selectedKey}
659
+ searchMatch={item.fromMessages ? contentMatchByKey.get(item.key) : undefined}
660
+ searchQuery={search.query}
661
+ onSelect={() => close(() => runResult(item))}
662
+ />
663
+ </>
664
)}
665
/>
666
</GlassSurface>
apps/mobile/src/features/keyboard/commandPaletteItems.test.ts
+33
-17
@@ -2,39 +2,55 @@ import { describe, expect, it } from "vite-plus/test";
2
3
import { filterCommandPaletteItems, type CommandPaletteItem } from "./commandPaletteItems";
4
5
+const NOW = Date.UTC(2026, 9, 23);
6
+
7
function item(
8
key: string,
9
title: string,
10
kind: CommandPaletteItem["kind"],
11
searchTerms: string[] = [],
12
): CommandPaletteItem {
11
- return { key, title, kind, searchTerms, run: () => {} };
13
+ return {
14
+ key,
15
+ title,
16
+ kind,
17
+ searchTerms,
18
+ ...(kind === "thread" ? { threadSearch: { title, activityAt: NOW } } : {}),
19
+ run: () => {},
20
+ };
21
}
22
23
const items = [
24
item("new", "New thread in…", "action", ["project", "create"]),
25
item("settings", "Open settings", "action", ["preferences"]),
26
item("project", "Mobile app", "project", ["/workspaces/mobile", "new thread"]),
18
- item("siva:one", "Keyboard shortcuts", "thread", ["Mobile app", "Siva"]),
19
- item("mac:one", "Mobile app", "thread", ["Mac"]),
27
+ item("siva:one", "Keyboard shortcuts", "thread"),
28
+ item("mac:one", "Mobile app layout", "thread"),
29
];
21
-const emptyMatches = new Set<string>();
30
+const keys = (results: ReadonlyArray<{ readonly key: string }>) =>
31
+ results.map((entry) => entry.key);
32
33
describe("filterCommandPaletteItems", () => {
24
- it("matches query tokens across titles and metadata and ranks exact titles first", () => {
25
- expect(
26
- filterCommandPaletteItems(items, " MOBILE app ", emptyMatches).map((item) => item.key),
27
- ).toEqual(["project", "mac:one", "siva:one"]);
28
- expect(
29
- filterCommandPaletteItems(items, "siva keyboard", emptyMatches).map((item) => item.key),
30
- ).toEqual(["siva:one"]);
34
+ it("ranks like the web palette, whole words first, with every token required", () => {
35
+ // A thread active today outranks a project that matches as well, but not
36
+ // one whose whole name was typed.
37
+ expect(keys(filterCommandPaletteItems(items, "mobile", [], NOW))).toEqual([
38
+ "mac:one",
39
+ "project",
40
+ ]);
41
+ expect(keys(filterCommandPaletteItems(items, " MOBILE app ", [], NOW))).toEqual([
42
+ "project",
43
+ "mac:one",
44
+ ]);
45
+ expect(keys(filterCommandPaletteItems(items, "keyboard short", [], NOW))).toEqual(["siva:one"]);
46
});
47
33
- it("includes server content matches scoped to the correct environment, except in actions-only mode", () => {
34
- const matches = new Set(["siva:one", "project"]);
35
- expect(
36
- filterCommandPaletteItems(items, "message content", matches).map((item) => item.key),
37
- ).toEqual(["siva:one"]);
38
- expect(filterCommandPaletteItems(items, "> message content", matches)).toEqual([]);
48
+ it("lists message matches after the other results, once, except in actions-only mode", () => {
49
+ const results = filterCommandPaletteItems(items, "layout", ["siva:one", "mac:one"], NOW);
50
+ expect(results.map((entry) => [entry.key, entry.fromMessages ?? false])).toEqual([
51
+ ["mac:one", false],
52
+ ["siva:one", true],
53
+ ]);
54
+ expect(filterCommandPaletteItems(items, "> layout", ["siva:one"], NOW)).toEqual([]);
55
});
56
});
apps/mobile/src/features/keyboard/commandPaletteItems.ts
+86
-26
@@ -1,4 +1,16 @@
1
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
2
+import {
3
+ foldSearchQuery,
4
+ PALETTE_SECONDARY_LIMIT,
5
+ PALETTE_THREAD_LIMIT,
6
+ rankSearchGroups,
7
+ scoreSearchTerms,
8
+ scoreThreadSearch,
9
+ type SearchMatchHint,
10
+ type SearchRange,
11
+ type SearchTermsMatch,
12
+ type ThreadSearchSubject,
13
+} from "@t3tools/shared/paletteSearch";
14
15
export interface CommandPaletteItem {
16
readonly key: string;
@@ -7,40 +19,88 @@ export interface CommandPaletteItem {
19
readonly title: string;
20
readonly detail?: string;
21
readonly searchTerms: ReadonlyArray<string>;
22
+ /** Thread rows rank by match quality and use instead of by `searchTerms`. */
23
+ readonly threadSearch?: ThreadSearchSubject;
24
+ /** Listed last in its group, as the thread already open. */
25
+ readonly secondary?: boolean;
26
readonly run: () => void;
27
}
28
29
+export interface CommandPaletteResult extends CommandPaletteItem {
30
+ /** Listed because its messages match; the row shows the message snippet. */
31
+ readonly fromMessages?: boolean;
32
+ /** Title ranges the query matched, for highlighting. */
33
+ readonly titleRanges?: ReadonlyArray<SearchRange>;
34
+ /** Shown in place of the detail when the match is not in the title. */
35
+ readonly matchHint?: SearchMatchHint;
36
+}
37
+
38
+/**
39
+ * Ranks like the web palette: actions, projects, and threads order by their
40
+ * best match, threads by match quality and use. Threads whose messages match
41
+ * come last, in `messageMatchKeys` order, so late server results never move
42
+ * the rows above them.
43
+ */
44
export function filterCommandPaletteItems(
45
items: ReadonlyArray<CommandPaletteItem>,
46
query: string,
16
- matchedThreadKeys: ReadonlySet<string>,
17
-) {
47
+ messageMatchKeys: ReadonlyArray<string>,
48
+ now = Date.now(),
49
+): CommandPaletteResult[] {
50
const actionsOnly = query.startsWith(">");
19
- const normalized = (actionsOnly ? query.slice(1) : query).trim().toLocaleLowerCase();
20
- const tokens = normalized.split(/\s+/);
21
- return items
22
- .flatMap((item, index) => {
23
- if (actionsOnly && item.kind !== "action") return [];
24
- if (!normalized) return item.kind === "project" ? [] : [{ item, rank: 0, index }];
25
- const title = item.title.toLocaleLowerCase();
26
- const haystack = [title, ...item.searchTerms].join(" ").toLocaleLowerCase();
27
- if (
28
- !tokens.every((token) => haystack.includes(token)) &&
29
- !(item.kind === "thread" && matchedThreadKeys.has(item.key))
51
+ const normalizedQuery = foldSearchQuery(actionsOnly ? query.slice(1) : query);
52
+ const candidates = actionsOnly ? items.filter((item) => item.kind === "action") : items;
53
+ if (!normalizedQuery) return candidates.filter((item) => item.kind !== "project");
54
+
55
+ // On equal match classes, groups keep this order, as on web.
56
+ const kinds = ["action", "thread", "project"] as const;
57
+ const groups = rankSearchGroups(
58
+ kinds.map((kind) => ({ group: kind, items: candidates.filter((item) => item.kind === kind) })),
59
+ (
60
+ item,
61
+ options,
62
+ ): (SearchTermsMatch & { explain?: () => SearchMatchHint | undefined }) | null => {
63
+ const match = item.threadSearch
64
+ ? scoreThreadSearch(normalizedQuery, item.threadSearch, now, options)
65
+ : scoreSearchTerms(normalizedQuery, [item.title, ...item.searchTerms], options);
66
+ // The open thread, listed last, does not decide where its group sits.
67
+ return match && item.secondary ? { ...match, groupQuality: 0 } : match;
68
+ },
69
+ );
70
+ const threadsMatch = groups.some(({ group }) => group === "thread");
71
+ const ranked = groups.flatMap(({ group, ranked: entries }) =>
72
+ [...entries]
73
+ // Stable, so rank order holds otherwise.
74
+ .sort(
75
+ (left, right) =>
76
+ Number(left.item.secondary ?? false) - Number(right.item.secondary ?? false),
77
)
31
- return [];
32
- const rank =
33
- title === normalized
34
- ? 3
35
- : title.startsWith(normalized)
36
- ? 2
37
- : title.includes(normalized)
38
- ? 1
39
- : 0;
40
- return [{ item, rank, index }];
41
- })
42
- .sort((left, right) => right.rank - left.rank || left.index - right.index)
43
- .map(({ item }) => item);
78
+ .slice(
79
+ 0,
80
+ group === "thread"
81
+ ? PALETTE_THREAD_LIMIT
82
+ : threadsMatch && !actionsOnly
83
+ ? PALETTE_SECONDARY_LIMIT
84
+ : entries.length,
85
+ )
86
+ .map(({ item, match }): CommandPaletteResult => {
87
+ // Built only for the rows shown.
88
+ const matchHint = match.explain?.();
89
+ return { ...item, titleRanges: match.ranges, ...(matchHint ? { matchHint } : {}) };
90
+ }),
91
+ );
92
+ if (actionsOnly) return ranked;
93
+
94
+ const listed = new Set(ranked.map((item) => item.key));
95
+ const threadByKey = new Map(
96
+ items.filter((item) => item.kind === "thread").map((item) => [item.key, item]),
97
+ );
98
+ // `messageMatchKeys` arrive cut to what the palette shows; see `nextShownOrder`.
99
+ const fromMessages = messageMatchKeys.flatMap((key) => {
100
+ const item = threadByKey.get(key);
101
+ return item && !listed.has(key) ? [{ ...item, fromMessages: true }] : [];
102
+ });
103
+ return [...ranked, ...fromMessages];
104
}
105
106
export function nextPaletteIndex(index: number, direction: -1 | 1, count: number) {
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+81
-1
@@ -75,7 +75,16 @@ import type { QueuedRunEdit } from "../../state/queued-run-edit";
75
import type { FollowUpBehavior } from "../../lib/followUpBehavior";
76
import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch";
77
import * as Haptics from "expo-haptics";
78
-import { useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from "react";
78
+import {
79
+ useCallback,
80
+ useContext,
81
+ useEffect,
82
+ useEffectEvent,
83
+ useLayoutEffect,
84
+ useRef,
85
+ useState,
86
+ useSyncExternalStore,
87
+} from "react";
88
import {
89
AppState,
90
Keyboard,
@@ -131,6 +140,12 @@ import { ThreadBrowserFloat } from "../browser/ThreadBrowserFloat";
140
import { useThreadServerBrowserTabs } from "../../state/preview";
141
import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
142
import { scopedThreadKey } from "../../lib/scopedEntities";
143
+import { claimThreadOpen } from "@t3tools/client-runtime/state/thread-search";
144
+import {
145
+ finishThreadMessageJump,
146
+ pendingThreadMessageJump,
147
+ subscribeThreadMessageJump,
148
+} from "./threadMessageJump";
149
import { parentThreadIsBelow } from "../../lib/android-workspace-navigation";
150
import {
151
clearThreadComposerError,
@@ -404,6 +419,36 @@ function ThreadVisitWatermark(props: {
419
const wakeIsLatestUpdate = selectedThreadUpdatedAt === selectedThreadWokeAt;
420
const selectedThreadLastVisitedAt = thread.lastVisitedAt;
421
const selectedThreadCompletedAt = thread.latestRun?.completedAt;
422
+ // Opening a thread is one visit that also counts toward search ranking; a
423
+ // palette pick already sent it with the query. The watermark effect below
424
+ // skips it.
425
+ const recordedOpenRef = useRef<string | null>(null);
426
+ useEffect(() => {
427
+ if (!showContent) return;
428
+ if (recordedOpenRef.current === selectedThreadKey) return;
429
+ recordedOpenRef.current = selectedThreadKey;
430
+ // Recorded here even when the server cannot take opens, so recents follow it.
431
+ const claimed = claimThreadOpen(props.environmentId, selectedThreadId, Date.now());
432
+ if (!claimed || selectedThreadLastVisitedAt === undefined) return;
433
+ lastDispatchedVisitRef.current = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
434
+ lastVisitDispatchRef.current = { threadKey: selectedThreadKey, at: Date.now() };
435
+ void visitThread({
436
+ environmentId: props.environmentId,
437
+ input: {
438
+ threadId: selectedThreadId,
439
+ visitedAt: selectedThreadUpdatedAt,
440
+ opened: true,
441
+ },
442
+ });
443
+ }, [
444
+ props.environmentId,
445
+ selectedThreadId,
446
+ selectedThreadKey,
447
+ selectedThreadLastVisitedAt,
448
+ selectedThreadUpdatedAt,
449
+ showContent,
450
+ visitThread,
451
+ ]);
452
useEffect(() => {
453
if (!showContent || selectedThreadLastVisitedAt === undefined) return;
454
const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
@@ -817,6 +862,39 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
862
(entry) => "acknowledged" in entry && entry.acknowledged === true,
863
);
864
const selectedThreadFeed = props.selectedThreadFeed;
865
+ // A palette message result opens the thread at that message: earlier
866
+ // history loads until the message is in the feed, which then scrolls to it.
867
+ const jumpMessageId = useSyncExternalStore(subscribeThreadMessageJump, () =>
868
+ pendingThreadMessageJump(selectedThreadKey),
869
+ );
870
+ const jumpMessageLoaded =
871
+ jumpMessageId !== null &&
872
+ selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === jumpMessageId);
873
+ // A jump this screen never reached lets go when the thread closes.
874
+ useEffect(() => () => finishThreadMessageJump(selectedThreadKey), [selectedThreadKey]);
875
+ const historyForJump = props.historyControls;
876
+ // History down to the message in one request; another page if it is not
877
+ // there yet.
878
+ const loadEarlierForJump = useEffectEvent(() => {
879
+ if (jumpMessageId !== null) historyForJump?.onLoadThrough(jumpMessageId);
880
+ });
881
+ useEffect(() => {
882
+ if (jumpMessageId === null || jumpMessageLoaded || contentPresentationKind !== "ready") return;
883
+ if (historyForJump?.loading) return;
884
+ if (!historyForJump?.hasMoreHistory || historyForJump.error !== null) {
885
+ finishThreadMessageJump(selectedThreadKey);
886
+ return;
887
+ }
888
+ loadEarlierForJump();
889
+ }, [
890
+ contentPresentationKind,
891
+ historyForJump?.error,
892
+ historyForJump?.hasMoreHistory,
893
+ historyForJump?.loading,
894
+ jumpMessageId,
895
+ jumpMessageLoaded,
896
+ selectedThreadKey,
897
+ ]);
898
const hasCompactableConversation =
899
selectedThreadFeed.some(
900
(entry) =>
@@ -1418,6 +1496,8 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1496
listRef={listRef}
1497
freeze={freeze}
1498
anchorMessageId={anchorMessageId}
1499
+ jumpToMessageId={jumpMessageLoaded ? jumpMessageId : null}
1500
+ onJumpedToMessage={() => finishThreadMessageJump(selectedThreadKey)}
1501
submittedMessageId={submittedMessageId}
1502
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
1503
keyboardOffset={composerKeyboardOffset}
apps/mobile/src/features/threads/ThreadFeed.tsx
+46
@@ -205,6 +205,7 @@ import {
205
isSecretRequestActivityGroup,
206
type ThreadFeedEntry,
207
type ThreadFeedLatestRun,
208
+ messageFoldRunId,
209
} from "../../lib/threadActivity";
210
import type { ThreadContentPresentation } from "./threadContentPresentation";
211
import {
@@ -327,6 +328,8 @@ export interface ThreadFeedHistoryControls {
328
readonly loading: boolean;
329
readonly error: string | null;
330
readonly onLoadEarlier: () => void;
331
+ /** Loads earlier history down to the entry, in one request. */
332
+ readonly onLoadThrough: (entryId: string) => void;
333
}
334
335
export interface ThreadFeedProps {
@@ -349,6 +352,9 @@ export interface ThreadFeedProps {
352
readonly listRef: RefObject<LegendListRef | null>;
353
readonly freeze: SharedValue<boolean>;
354
readonly anchorMessageId: MessageId | null;
355
+ /** A message to scroll to once it is in the feed; see `onJumpedToMessage`. */
356
+ readonly jumpToMessageId?: MessageId | null;
357
+ readonly onJumpedToMessage?: () => void;
358
readonly submittedMessageId: MessageId | null;
359
readonly contentInsetEndAdjustment: SharedValue<number>;
360
readonly keyboardOffset: number;
@@ -2623,6 +2629,45 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2629
listRef.current?.reportContentInset({ bottom });
2630
}
2631
}, [listMountKey, props.contentInsetEndAdjustment, listRef]);
2632
+ // Opening at a message: its run unfolds, the list stops following the end
2633
+ // (a render later, so the end does not pull it back), then it scrolls there.
2634
+ const [loadedListKey, setLoadedListKey] = useState<string | null>(null);
2635
+ const { jumpToMessageId } = props;
2636
+ const finishJump = useEffectEvent(() => props.onJumpedToMessage?.());
2637
+ const stopFollowingEnd = useEffectEvent(() => setEndFollow(false));
2638
+ useEffect(() => {
2639
+ if (!jumpToMessageId || loadedListKey !== listMountKey) return;
2640
+ const index = presentedFeed.findIndex(
2641
+ (entry) => entry.type === "message" && entry.id === jumpToMessageId,
2642
+ );
2643
+ if (index === -1) {
2644
+ const runId = messageFoldRunId(props.feed, jumpToMessageId);
2645
+ if (runId && !expandedTurnIds.has(runId)) {
2646
+ setInteractionState((current) => ({
2647
+ ...current,
2648
+ expandedTurnIds: new Set(current.expandedTurnIds).add(runId),
2649
+ }));
2650
+ } else {
2651
+ finishJump();
2652
+ }
2653
+ return;
2654
+ }
2655
+ if (endFollowEnabled) {
2656
+ stopFollowingEnd();
2657
+ return;
2658
+ }
2659
+ void listRef.current?.scrollToIndex({ index, viewPosition: 0.2, animated: false });
2660
+ finishJump();
2661
+ }, [
2662
+ endFollowEnabled,
2663
+ expandedTurnIds,
2664
+ jumpToMessageId,
2665
+ listMountKey,
2666
+ listRef,
2667
+ loadedListKey,
2668
+ presentedFeed,
2669
+ props.feed,
2670
+ ]);
2671
2672
const reflowLayout = () => ({
2673
rowsTop: FEED_PADDING_TOP + listHeaderSizeRef.current,
@@ -3110,6 +3155,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3155
initialScrollAtEnd
3156
onLoad={() => {
3157
loadedListKeyRef.current = listMountKey;
3158
+ setLoadedListKey(listMountKey);
3159
}}
3160
// Row positions start below the header; the reflow anchor converts between them.
3161
onMetricsChange={(metrics) => {
apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+29
-19
@@ -42,6 +42,8 @@ import { useWorkspaceState } from "../../state/workspace";
42
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
43
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
44
import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
45
+import { requestThreadMessageJump } from "./threadMessageJump";
46
+import { useThreadListSearchMatches } from "./useThreadListSearchMatches";
47
import { useHomeListOptions } from "../home/home-list-options";
48
import { buildHomeListFilterMenu } from "../home/home-list-filter-menu";
49
import { buildHomeProjectScopes } from "../home/homeThreadList";
@@ -185,18 +187,10 @@ function ThreadNavigationSidebarPane(
187
? [options.selectedEnvironmentId]
188
: [];
189
const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
188
- // These maps reach LegendList's extraData, which re-renders every row whenever it changes
189
- // identity. The compiler leaves them unmemoized because they stay live across later hook calls.
190
- const threadSearchMatchByKey = useMemo(() => {
191
- const matches = new Map<string, EnvironmentThreadSearchMatch>();
192
- for (const match of threadSearch.matches) {
193
- if (match.source === "user" || match.source === "assistant") {
194
- matches.set(threadSearchMatchKey(match), match);
195
- }
196
- }
197
- return matches;
198
- }, [threadSearch.matches]);
199
- const matchedThreadKeys = new Set(threadSearch.matches.map(threadSearchMatchKey));
190
+ // This map reaches LegendList's extraData, which re-renders every row whenever it changes
191
+ // identity; the hook keeps it stable.
192
+ const threadSearchMatchByKey = useThreadListSearchMatches(threads, threadSearch);
193
+ const matchedThreadKeys = new Set(threadSearchMatchByKey.keys());
194
const projectScopeKey = options.selectedProjectKey;
195
const resolvedProjectKey = resolveScratchProjectScopeKey(projectScopeKey, projects, {
196
sidebarProjectGroupingMode: options.projectGroupingMode,
@@ -505,7 +499,16 @@ function ThreadNavigationSidebarPane(
499
// These close the open row too, so they cannot be pass-throughs. The compiler would
500
// recache a closure over `props` whenever any prop changed.
501
const { onSelectThread, onOpenThreadPullRequests } = props;
502
+ // A row listed for a message match opens the thread at that message, by
503
+ // tap or by shortcut.
504
const handleSelectThread = (thread: EnvironmentThreadShell) => {
505
+ const key = threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id });
506
+ const messageId = threadListV2Layout.contentOnlyThreadKeys.has(key)
507
+ ? threadSearchMatchByKey.get(key)?.messageId
508
+ : undefined;
509
+ if (messageId) {
510
+ requestThreadMessageJump(scopedThreadKey(thread.environmentId, thread.id), messageId);
511
+ }
512
onSelectThread(thread);
513
openSwipeableRef.current?.close();
514
};
@@ -629,13 +632,20 @@ function ThreadNavigationSidebarPane(
632
: null
633
}
634
environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
632
- searchMatch={threadSearchMatchByKey.get(
633
- threadSearchMatchKey({
634
- environmentId: thread.environmentId,
635
- threadId: thread.id,
636
- }),
637
- )}
638
- searchQuery={props.searchQuery}
635
+ searchMatch={
636
+ // Only rows listed for their messages show one and open at it.
637
+ threadListV2Layout.contentOnlyThreadKeys.has(
638
+ threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
639
+ )
640
+ ? threadSearchMatchByKey.get(
641
+ threadSearchMatchKey({
642
+ environmentId: thread.environmentId,
643
+ threadId: thread.id,
644
+ }),
645
+ )
646
+ : undefined
647
+ }
648
+ searchQuery={threadSearch.query}
649
pane="sidebar"
650
selected={
651
!activeNewTask &&
apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+6
@@ -326,6 +326,12 @@ function ThreadRouteContent(
326
input: { threadId: selectedThread.id },
327
});
328
},
329
+ onLoadThrough: (throughEntryId: string) => {
330
+ void loadEarlierHistory({
331
+ environmentId: selectedThread.environmentId,
332
+ input: { threadId: selectedThread.id, throughEntryId },
333
+ });
334
+ },
335
};
336
})();
337
const navigation = useNavigation();
apps/mobile/src/features/threads/thread-list-v2-items.tsx
+3
-2
@@ -602,6 +602,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
602
const pinnedRow = props.pinned === true;
603
const dormant = useSwipeRowDormant(props.activationKey);
604
605
+ const selectThread = () => onSelectThread(thread);
606
const { providerDrivers, providerIconUrl } = useMemo(() => {
607
const provider = props.providers?.find(
608
(candidate) =>
@@ -1257,7 +1258,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
1258
}}
1259
onPress={() => {
1260
close();
1260
- onSelectThread(thread);
1261
+ selectThread();
1262
}}
1263
style={rowAppearance.cardStyle}
1264
>
@@ -1286,7 +1287,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
1287
className={rowAppearance.className}
1288
onPress={() => {
1289
close();
1289
- onSelectThread(thread);
1290
+ selectThread();
1291
}}
1292
style={rowAppearance.style}
1293
>
apps/mobile/src/features/threads/thread-search-match.tsx
+5
-2
@@ -1,4 +1,4 @@
1
-import { splitThreadSearchText } from "@t3tools/shared/threadSearch";
1
+import { findSearchTokenRanges, splitSearchText } from "@t3tools/shared/paletteSearch";
2
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
3
4
import { AppText as Text } from "../../components/ui/AppText";
@@ -12,7 +12,10 @@ export function ThreadSearchMatchExcerpt(props: {
12
readonly sidebar?: boolean;
13
}) {
14
const isUser = props.match.source === "user";
15
- const parts = splitThreadSearchText(props.match.snippet, props.query);
15
+ const parts = splitSearchText(
16
+ props.match.snippet,
17
+ findSearchTokenRanges(props.match.snippet, props.query),
18
+ );
19
return (
20
<Text
21
className={cn(
apps/mobile/src/features/threads/threadListV2.test.ts
+42
@@ -1,3 +1,4 @@
1
+import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
2
import { presentThreadShell } from "@t3tools/client-runtime/state/models";
3
import * as DateTime from "effect/DateTime";
4
import * as Schema from "effect/Schema";
@@ -151,6 +152,33 @@ describe("queued messages keep a settled thread active", () => {
152
});
153
});
154
155
+describe("search lists ranked matches", () => {
156
+ const matchKey = (id: string) =>
157
+ threadSearchMatchKey({ environmentId, threadId: ThreadId.make(id) });
158
+
159
+ it("lists matches by rank across shelves, then threads listed for their messages", () => {
160
+ const layout = buildThreadListV2Items({
161
+ threads: [
162
+ makeThread({ id: ThreadId.make("notes"), title: "Deploy notes" }),
163
+ makeThread({ id: ThreadId.make("mentioned"), title: "Weekly notes" }),
164
+ makeThread({ id: ThreadId.make("exact"), title: "Deploy", settledOverride: "settled" }),
165
+ ],
166
+ environmentId: null,
167
+ searchQuery: "deploy",
168
+ matchedThreadKeys: new Set([matchKey("mentioned"), matchKey("notes")]),
169
+ settledShelfExpanded: false,
170
+ now: NOW,
171
+ });
172
+ // The exact title leads even from a collapsed Settled shelf, and keeps its look.
173
+ expect(layout.items.map((item) => [item.thread.id, item.variant])).toEqual([
174
+ ["exact", "slim"],
175
+ ["notes", "card"],
176
+ ["mentioned", "card"],
177
+ ]);
178
+ expect([...layout.contentOnlyThreadKeys]).toEqual([matchKey("mentioned")]);
179
+ });
180
+});
181
+
182
describe("sortThreadsForListV2", () => {
183
it("honors a saved active order and leaves new threads above it", () => {
184
const sorted = sortThreadsForListV2([
@@ -428,6 +456,20 @@ describe("buildThreadListV2Items", () => {
456
]);
457
});
458
459
+ it("forgives a typo even when a hidden thread matches the query exactly", () => {
460
+ const { items } = buildThreadListV2Items({
461
+ threads: [
462
+ makeThread({ id: ThreadId.make("visible"), title: "Restore drag handles" }),
463
+ makeThread({ id: ThreadId.make("archived"), title: "Drga notes", archivedAt: NOW }),
464
+ ],
465
+ environmentId: null,
466
+ searchQuery: "drga",
467
+ now: NOW,
468
+ });
469
+
470
+ expect(items.map((item) => item.thread.id)).toEqual(["visible"]);
471
+ });
472
+
473
it("scopes the flat list to every environment member of a logical project", () => {
474
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
475
const projectId = ProjectId.make("project-1");
apps/mobile/src/features/threads/threadListV2.ts
+79
-23
@@ -1,4 +1,3 @@
1
-import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
1
import {
2
canSnooze,
3
effectiveSnoozed,
@@ -11,7 +10,11 @@ import {
10
import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
11
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
12
import { resolveThreadProviderStack } from "@t3tools/client-runtime/state/models";
14
-import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
13
+import {
14
+ threadSearchMatchKey,
15
+ threadSearchSubject,
16
+} from "@t3tools/client-runtime/state/thread-search";
17
+import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
18
import {
19
createInboxReturnTracker,
20
isThreadWorking,
@@ -279,6 +282,8 @@ export interface ThreadListV2Layout {
282
* a snooze expires instead of on the next minute tick.
283
*/
284
readonly nextSnoozeWakeAt: string | null;
285
+ /** Threads listed only because their messages match the search. */
286
+ readonly contentOnlyThreadKeys: ReadonlySet<string>;
287
}
288
289
export interface ThreadListV2ThreadListItem {
@@ -602,7 +607,8 @@ export function buildThreadListV2Items(input: {
607
pendingOrder: null,
608
}),
609
);
605
- const query = input.searchQuery.trim().toLocaleLowerCase();
610
+ const query = foldSearchQuery(input.searchQuery);
611
+ const nowMs = Date.parse(now);
612
const projectKeys = input.projectRefs
613
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
614
: null;
@@ -615,26 +621,36 @@ export function buildThreadListV2Items(input: {
621
const snoozed: EnvironmentThreadShell[] = [];
622
let nextSnoozeWakeAt: string | null = null;
623
const queuedThreadKeys = input.queuedThreadKeys?.size ? input.queuedThreadKeys : undefined;
618
- for (const thread of input.threads) {
619
- if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent") continue;
620
- if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
621
- if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
622
- continue;
623
- }
624
- if (
625
- query.length > 0 &&
626
- !thread.title.toLocaleLowerCase().includes(query) &&
627
- !threadPullRequestSearchTerms(thread).some((term) =>
628
- term.toLocaleLowerCase().includes(query),
629
- ) &&
630
- input.matchedThreadKeys?.has(
631
- threadSearchMatchKey({
632
- environmentId: thread.environmentId,
633
- threadId: thread.id,
634
- }),
635
- ) !== true
636
- ) {
637
- continue;
624
+ const listedThreads = input.threads.filter(
625
+ (thread) =>
626
+ thread.archivedAt === null &&
627
+ thread.lineage.relationshipToParent !== "subagent" &&
628
+ (input.environmentId === null || thread.environmentId === input.environmentId) &&
629
+ (projectKeys === null || projectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
630
+ );
631
+ // The same matches as the command palette, typo fallback included. Only
632
+ // listed threads are ranked: a hidden exact match must not turn typos off.
633
+ const rankedMatches =
634
+ query.length > 0
635
+ ? rankSearchItems(listedThreads, (thread, options) =>
636
+ scoreThreadSearch(query, threadSearchSubject(thread, null), nowMs, {
637
+ ...options,
638
+ picks: false,
639
+ }),
640
+ ).map(({ item }) => item)
641
+ : null;
642
+ const matchingThreads = rankedMatches === null ? null : new Set(rankedMatches);
643
+ // Threads listed only because their messages match; only their rows show
644
+ // the message and open at it.
645
+ const contentOnlyThreadKeys = new Set<string>();
646
+ for (const thread of listedThreads) {
647
+ if (matchingThreads !== null && !matchingThreads.has(thread)) {
648
+ const key = threadSearchMatchKey({
649
+ environmentId: thread.environmentId,
650
+ threadId: thread.id,
651
+ });
652
+ if (input.matchedThreadKeys?.has(key) !== true) continue;
653
+ contentOnlyThreadKeys.add(key);
654
}
655
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
656
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
@@ -662,6 +678,45 @@ export function buildThreadListV2Items(input: {
678
}
679
}
680
681
+ if (rankedMatches !== null) {
682
+ // Searching lists every match by rank across shelves, as the palette and
683
+ // the web sidebar do, then threads listed for their messages in the
684
+ // server's order. Each row keeps its shelf's look.
685
+ const slim = new Set([...snoozed, ...settled]);
686
+ const snoozedThreads = new Set(snoozed);
687
+ const pinnedThreads = new Set(pinned);
688
+ const threadByKey = new Map(
689
+ listedThreads.map((thread) => [
690
+ threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
691
+ thread,
692
+ ]),
693
+ );
694
+ const contentOnly = [...(input.matchedThreadKeys ?? [])].flatMap((key) => {
695
+ const thread = contentOnlyThreadKeys.has(key) ? threadByKey.get(key) : undefined;
696
+ return thread ? [thread] : [];
697
+ });
698
+ const results = [...rankedMatches, ...contentOnly];
699
+ return {
700
+ items: results.map((thread, index) => ({
701
+ thread,
702
+ variant: slim.has(thread) ? "slim" : "card",
703
+ snoozed: snoozedThreads.has(thread),
704
+ pinned: pinnedThreads.has(thread),
705
+ wokeAt: slim.has(thread) ? null : resolveThreadListV2WokeAt(thread, { now }),
706
+ isLast: index === results.length - 1,
707
+ })),
708
+ hiddenSettledCount: 0,
709
+ workingCount: 0,
710
+ workingShelfHeaderIndex: null,
711
+ snoozedCount: 0,
712
+ snoozedShelfHeaderIndex: null,
713
+ settledCount: 0,
714
+ settledShelfHeaderIndex: null,
715
+ nextSnoozeWakeAt,
716
+ contentOnlyThreadKeys,
717
+ };
718
+ }
719
+
720
const orderedActive = workingShelfEnabled
721
? sortInboxThreadsByReturn(active, input.inboxReturnAt)
722
: applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending);
@@ -774,5 +829,6 @@ export function buildThreadListV2Items(input: {
829
settledCount: orderedSettled.length,
830
settledShelfHeaderIndex,
831
nextSnoozeWakeAt,
832
+ contentOnlyThreadKeys,
833
};
834
}
apps/mobile/src/features/threads/threadMessageJump.test.ts
new
+15
@@ -0,0 +1,15 @@
1
+import { MessageId } from "@t3tools/contracts";
2
+import { describe, expect, it, vi } from "vite-plus/test";
3
+
4
+import { pendingThreadMessageJump, requestThreadMessageJump } from "./threadMessageJump";
5
+
6
+describe("threadMessageJump", () => {
7
+ it("lets a jump lapse when its thread never showed", () => {
8
+ using now = vi.spyOn(Date, "now").mockReturnValue(0);
9
+ requestThreadMessageJump("thread-a", MessageId.make("message-1"));
10
+ expect(pendingThreadMessageJump("thread-a")).toBe("message-1");
11
+ expect(pendingThreadMessageJump("thread-b")).toBeNull();
12
+ now.mockReturnValue(30_000);
13
+ expect(pendingThreadMessageJump("thread-a")).toBeNull();
14
+ });
15
+});
apps/mobile/src/features/threads/threadMessageJump.ts
new
+42
@@ -0,0 +1,42 @@
1
+import type { MessageId } from "@t3tools/contracts";
2
+
3
+// A palette message result opens its thread at that message. The thread
4
+// screen reads the request while it shows that thread, and finishes it once
5
+// the feed is there or the message cannot be found. A request whose thread
6
+// never showed lapses, so a later plain open does not jump, as on web.
7
+const PENDING_JUMP_MS = 30_000;
8
+let pending: {
9
+ readonly threadKey: string;
10
+ readonly messageId: MessageId;
11
+ readonly at: number;
12
+} | null = null;
13
+const listeners = new Set<() => void>();
14
+
15
+function notify() {
16
+ for (const listener of listeners) listener();
17
+}
18
+
19
+export function requestThreadMessageJump(threadKey: string, messageId: MessageId): void {
20
+ pending = { threadKey, messageId, at: Date.now() };
21
+ notify();
22
+}
23
+
24
+/** The message this thread should open at, if a palette pick asked for one. */
25
+export function pendingThreadMessageJump(threadKey: string): MessageId | null {
26
+ return pending?.threadKey === threadKey && Date.now() - pending.at < PENDING_JUMP_MS
27
+ ? pending.messageId
28
+ : null;
29
+}
30
+
31
+export function finishThreadMessageJump(threadKey: string): void {
32
+ if (pending?.threadKey !== threadKey) return;
33
+ pending = null;
34
+ notify();
35
+}
36
+
37
+export function subscribeThreadMessageJump(listener: () => void): () => void {
38
+ listeners.add(listener);
39
+ return () => {
40
+ listeners.delete(listener);
41
+ };
42
+}
apps/mobile/src/features/threads/use-composer-command-menu.ts
+3
@@ -205,6 +205,8 @@ export function useComposerCommandMenu({
205
readonly onUsageLimits?: () => void;
206
}) {
207
const [selection, setSelection] = useState(() => composerSelectionAtEnd(draftMessage));
208
+ // Thread mentions rank by recency as of when the composer mounted.
209
+ const [now] = useState(() => Date.now());
210
const previousOwnerKeyRef = useRef(ownerKey);
211
const onSelectionChange = (nextSelection: ComposerEditorSelection) => {
212
setSelection(nextSelection);
@@ -500,6 +502,7 @@ export function useComposerCommandMenu({
502
environmentId,
503
excludeThreadId: currentThreadId,
504
query: trigger.query,
505
+ now,
506
})
507
: [];
508
return [
apps/mobile/src/features/threads/useThreadListSearchMatches.ts
new
+58
@@ -0,0 +1,58 @@
1
+import {
2
+ nextShownOrder,
3
+ threadSearchMatchKey,
4
+ threadSearchSubject,
5
+ type EnvironmentThreadSearchMatch,
6
+ type ShownOrder,
7
+} from "@t3tools/client-runtime/state/thread-search";
8
+import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
9
+import { foldSearchQuery, rankMessageMatches } from "@t3tools/shared/paletteSearch";
10
+import { useMemo, useState } from "react";
11
+
12
+const NO_MATCHES: ReadonlyMap<string, EnvironmentThreadSearchMatch> = new Map();
13
+
14
+/**
15
+ * A thread list's message matches by thread key, ranked across environments
16
+ * as the palette ranks them. Rows already shown keep their places while
17
+ * slower environments answer. The map keeps its identity while nothing
18
+ * changes, since lists pass it to every row.
19
+ */
20
+export function useThreadListSearchMatches(
21
+ threads: ReadonlyArray<EnvironmentThreadShell>,
22
+ search: {
23
+ readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
24
+ readonly query: string;
25
+ },
26
+): ReadonlyMap<string, EnvironmentThreadSearchMatch> {
27
+ const [now] = useState(() => Date.now());
28
+ const [shownOrder, setShownOrder] = useState<ShownOrder | null>(null);
29
+ const rankedKeys = useMemo(() => {
30
+ if (search.matches.length === 0) return [];
31
+ const subjectByKey = new Map(
32
+ threads.map((thread) => [
33
+ threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
34
+ threadSearchSubject(thread, null),
35
+ ]),
36
+ );
37
+ return rankMessageMatches(
38
+ search.matches,
39
+ (match) => subjectByKey.get(threadSearchMatchKey(match)),
40
+ foldSearchQuery(search.query),
41
+ now,
42
+ { picks: false },
43
+ ).map(threadSearchMatchKey);
44
+ }, [now, search.matches, search.query, threads]);
45
+ // A list shows every match, so nothing is cut; late ones go below.
46
+ const order = nextShownOrder(shownOrder, search.query, rankedKeys, Number.POSITIVE_INFINITY);
47
+ if (order !== shownOrder) setShownOrder(order);
48
+ return useMemo(() => {
49
+ if (order.keys.length === 0) return NO_MATCHES;
50
+ const matchByKey = new Map(search.matches.map((match) => [threadSearchMatchKey(match), match]));
51
+ return new Map(
52
+ order.keys.flatMap((key) => {
53
+ const match = matchByKey.get(key);
54
+ return match ? [[key, match] as const] : [];
55
+ }),
56
+ );
57
+ }, [order, search.matches]);
58
+}
apps/mobile/src/lib/threadActivity.test.ts
+27
@@ -26,6 +26,7 @@ import {
26
buildThreadFeed,
27
createThreadFeedCache,
28
deriveThreadFeedPresentation,
29
+ messageFoldRunId,
30
type ThreadFeedCache,
31
type ThreadFeedEntry,
32
type ThreadFeedLatestRun,
@@ -524,6 +525,32 @@ describe("buildThreadFeed", () => {
525
expect(activities.at(-1)?.prominent).toBe(true);
526
});
527
528
+ it("names the fold that hides a progress message, with or without a run", () => {
529
+ const middle = {
530
+ ...assistantMessage("2026-06-20T00:00:02.500Z"),
531
+ id: TurnItemId.make("item-middle"),
532
+ messageId: MessageId.make("message-middle"),
533
+ text: "Needle found in the build config.",
534
+ };
535
+ const items = [userMessage(), command(), middle, assistantMessage()];
536
+ for (const runless of [false, true]) {
537
+ const feed = buildThreadFeed(
538
+ items.map((item, position) =>
539
+ projected(runless ? { ...item, runId: null } : item, position),
540
+ ),
541
+ );
542
+ const foldRunId = messageFoldRunId(feed, "message-middle");
543
+ expect(foldRunId, String(runless)).toBe(runless ? "runless:message-user" : runId);
544
+ const ids = (expanded: ReadonlySet<RunId>) =>
545
+ deriveThreadFeedPresentation(feed, null, expanded).map((entry) => entry.id);
546
+ expect(ids(new Set())).not.toContain("message-middle");
547
+ expect(ids(new Set([foldRunId!]))).toContain("message-middle");
548
+ }
549
+ expect(messageFoldRunId(buildThreadFeed([projected(userMessage(), 0)]), "message-user")).toBe(
550
+ null,
551
+ );
552
+ });
553
+
554
it("folds progress messages while keeping the final assistant answer visible", () => {
555
const opening = {
556
...assistantMessage("2026-06-20T00:00:01.500Z"),
apps/mobile/src/lib/threadActivity.ts
+22
@@ -1064,6 +1064,28 @@ export function failedFeedRunIds(
1064
return failed;
1065
}
1066
1067
+/**
1068
+ * The key a run fold uses for the message `entryId`: its run, or for an
1069
+ * imported message with no run, the runless key of the user message before
1070
+ * it. Null for user messages, which never fold.
1071
+ */
1072
+export function messageFoldRunId(
1073
+ feed: ReadonlyArray<ThreadFeedEntry>,
1074
+ entryId: string,
1075
+): RunId | null {
1076
+ let runlessKey: RunId | null = null;
1077
+ for (const entry of feed) {
1078
+ if (entry.type !== "message") continue;
1079
+ if (entry.message.role === "user") {
1080
+ if (entry.id === entryId) return null;
1081
+ runlessKey = entry.message.runId == null ? RunId.make(`runless:${entry.id}`) : null;
1082
+ } else if (entry.id === entryId) {
1083
+ return entry.message.runId ?? runlessKey;
1084
+ }
1085
+ }
1086
+ return null;
1087
+}
1088
+
1089
function deriveThreadFeedRunFolds(
1090
feed: ReadonlyArray<ThreadFeedEntry>,
1091
latestRun: ThreadFeedLatestRun | null,
apps/mobile/src/state/queries.ts
+28
-6
@@ -17,8 +17,12 @@ import type {
17
import {
18
createThreadSearchResultsAtomFamily,
19
makeThreadSearchKey,
20
+ visibleThreadSearch,
21
type EnvironmentThreadSearchMatch,
22
+ type SettledThreadSearch,
23
} from "@t3tools/client-runtime/state/thread-search";
24
+import { THREAD_SEARCH_QUERY_MAX_LENGTH } from "@t3tools/contracts";
25
+import { messageSearchTokens } from "@t3tools/shared/paletteSearch";
26
import { useAtomValue } from "@effect/atom-react";
27
import * as Cause from "effect/Cause";
28
import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
@@ -40,7 +44,7 @@ import {
44
45
const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200;
46
const COMPOSER_PATH_SEARCH_LIMIT = 20;
43
-const THREAD_SEARCH_DEBOUNCE_MS = 200;
47
+const THREAD_SEARCH_DEBOUNCE_MS = 120;
48
const VCS_REF_LIST_LIMIT = 100;
49
const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
50
const INITIAL_BRANCH_CURSORS = [undefined] as const;
@@ -164,21 +168,39 @@ export function useThreadSearch(
168
query: string,
169
): {
170
readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
171
+ /** The query `matches` are for, which lags the typed one while a search runs. */
172
+ readonly query: string;
173
readonly isPending: boolean;
174
} {
169
- const normalizedQuery = query.trim();
175
+ // A pasted wall of text searches by its start rather than failing the request.
176
+ const normalizedQuery = query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH).trim();
177
const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
171
- const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2;
178
+ // The server needs a word of three or more letters; shorter queries would always come back empty.
179
+ const canSearch =
180
+ environmentIds.length > 0 && messageSearchTokens(normalizedQuery).long.length > 0;
181
const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
182
const searchKey =
183
settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery);
184
const result = useAtomValue(
185
searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
186
);
178
- const isDebouncing = canSearch && normalizedQuery !== debouncedQuery;
187
+ const isPending = canSearch && (normalizedQuery !== debouncedQuery || result.isLoading);
188
+ // What fast environments returned shows without waiting for a slow one;
189
+ // callers keep shown rows in place with `nextShownOrder`.
190
+ const ready =
191
+ settledQuery !== null && (!result.isLoading || result.matches.length > 0)
192
+ ? { query: settledQuery, matches: result.matches }
193
+ : null;
194
+ // Kept from earlier renders: React's pattern for information from previous renders.
195
+ const [previous, setPrevious] = useState<SettledThreadSearch | null>(null);
196
+ if (ready !== null && previous?.matches !== ready.matches) setPrevious(ready);
197
+ const visible = canSearch
198
+ ? visibleThreadSearch(normalizedQuery, ready, previous)
199
+ : { query: "", matches: EMPTY_THREAD_SEARCH_MATCHES };
200
return {
180
- matches: isDebouncing ? EMPTY_THREAD_SEARCH_MATCHES : result.matches,
181
- isPending: canSearch && (isDebouncing || result.isLoading),
201
+ matches: visible.matches,
202
+ query: visible.query,
203
+ isPending,
204
};
205
}
206
apps/server/scripts/migrate-dev-db.ts
+15
-2
@@ -16,6 +16,7 @@ import * as SqlClient from "effect/sql/SqlClient";
16
import { Command, Flag } from "effect/cli";
17
18
import * as ProjectionStore from "../src/orchestration-v2/ProjectionStore.ts";
19
+import { rebuildMessageSearch } from "../src/orchestration-v2/messageSearchIndex.ts";
20
import { migrationManifest, runMigrations } from "../src/persistence/Migrations.ts";
21
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
22
@@ -216,6 +217,7 @@ const CLEARED_TABLES: ReadonlyArray<string> = [
217
];
218
219
const PROVIDER_SESSIONS_TABLE = "orchestration_v2_projection_provider_sessions";
220
+const FTS5_SHADOW_SUFFIXES = ["_data", "_idx", "_content", "_docsize", "_config"];
221
222
// Settled threads stay: they are most of real history, and the UI shows them.
223
const rootIsVisible = (sql: SqlClient.SqlClient) => sql`
@@ -236,7 +238,17 @@ const copySourceSlice = Effect.fn("copyDevDbSourceSlice")(function* (sourcePath:
238
SELECT m.name, c."notnull" FROM src.sqlite_master m, pragma_table_info(m.name, 'src') c
239
WHERE m.type = 'table' AND c.name = 'thread_id'`;
240
const threadIdNullable = new Map(threadColumns.map((row) => [row.name, row.notnull === 0]));
239
- const tables = schema.filter((entry) => entry.type === "table");
241
+ // FTS5 makes its own shadow tables and contentless rows cannot be copied:
242
+ // create the virtual table, skip its shadow tables and rows, and rebuild the
243
+ // index once the messages and triggers are in.
244
+ const virtualTables = schema
245
+ .filter((entry) => entry.type === "table" && /^CREATE VIRTUAL TABLE/i.test(entry.sql))
246
+ .map((entry) => entry.name);
247
+ const isShadowTable = (name: string) =>
248
+ virtualTables.some((virtual) =>
249
+ FTS5_SHADOW_SUFFIXES.some((suffix) => name === `${virtual}${suffix}`),
250
+ );
251
+ const tables = schema.filter((entry) => entry.type === "table" && !isShadowTable(entry.name));
252
const filtered = tables.some((table) => table.name === "orchestration_v2_projection_threads");
253
254
yield* sql.withTransaction(
@@ -251,7 +263,7 @@ const copySourceSlice = Effect.fn("copyDevDbSourceSlice")(function* (sourcePath:
263
WHERE ${rootIsVisible(sql)}`;
264
}
265
for (const { name } of tables) {
254
- if (CLEARED_TABLES.includes(name)) continue;
266
+ if (CLEARED_TABLES.includes(name) || virtualTables.includes(name)) continue;
267
const nullable = threadIdNullable.get(name);
268
const filter = !filtered
269
? ""
@@ -271,6 +283,7 @@ const copySourceSlice = Effect.fn("copyDevDbSourceSlice")(function* (sourcePath:
283
for (const entry of schema) {
284
if (entry.type !== "table") yield* sql.unsafe(entry.sql).unprepared;
285
}
286
+ yield* rebuildMessageSearch(sql);
287
}),
288
);
289
yield* sql`DETACH DATABASE src`;
apps/server/src/mcp/toolkits/thread/handlers.ts
+3
-9
@@ -104,16 +104,10 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
104
t3_thread_search: McpToolAccess.reads((input) =>
105
Effect.gen(function* () {
106
const { caller } = yield* readCaller();
107
- const { projectId: requested, ...query } = input;
108
- const projectId = requested ?? caller?.projectId;
107
const threadSearch = yield* ThreadSearch.ThreadSearch;
110
- const result = yield* threadSearch.search(query).pipe(Effect.mapError(unavailable));
111
- return {
112
- matches:
113
- projectId === undefined
114
- ? result.matches
115
- : result.matches.filter((match) => match.projectId === projectId),
116
- };
108
+ return yield* threadSearch
109
+ .searchThreads({ ...input, projectId: input.projectId ?? caller?.projectId })
110
+ .pipe(Effect.mapError(unavailable));
111
}),
112
),
113
t3_thread_fork: writesThread((input) =>
apps/server/src/mcp/toolkits/thread/tools.ts
+14
-3
@@ -2,7 +2,7 @@ import {
2
ScheduledTaskId,
3
ScheduledTask,
4
OrchestrationSearchThreadsInput,
5
- OrchestrationSearchThreadsResult,
5
+ OrchestrationThreadSearchMatch,
6
OrchestrationV2ThreadForkSourcePoint,
7
OrchestrationV2ContextTransfer,
8
TrimmedNonEmptyString,
@@ -243,12 +243,23 @@ const ThreadTransfersTool = Tool.make("t3_thread_transfers", {
243
const ThreadSearchTool = Tool.make("t3_thread_search", {
244
...commandTool,
245
description:
246
- "Search active thread titles and content with the app's existing bounded search. Matches are limited to one project (projectId, else the calling thread's project) out of the global top matches, so this may return fewer than limit. A caller outside a T3 thread that omits projectId searches every project. No pagination or exhaustive-result guarantee.",
246
+ 'Search active threads the way the command palette does: title, branch, pull request, and project matches first (source "title", ranked by match quality and recent use, with one-typo tolerance), then threads whose messages contain every query word of three or more characters (source "user" or "assistant", with a snippet; up to a fifth of the limit is kept for these). Subagent threads are skipped. Limited to one project (projectId, else the calling thread\'s project); a caller outside a T3 thread that omits projectId searches every project. No pagination or exhaustive-result guarantee.',
247
parameters: Schema.Struct({
248
...OrchestrationSearchThreadsInput.fields,
249
projectId: Schema.optional(ProjectId),
250
}),
251
- success: OrchestrationSearchThreadsResult,
251
+ success: Schema.Struct({
252
+ matches: Schema.Array(
253
+ Schema.Struct({
254
+ threadId: OrchestrationThreadSearchMatch.fields.threadId,
255
+ projectId: OrchestrationThreadSearchMatch.fields.projectId,
256
+ title: Schema.String,
257
+ source: Schema.Literals(["title", "user", "assistant"]),
258
+ snippet: Schema.optional(OrchestrationThreadSearchMatch.fields.snippet),
259
+ messageCreatedAt: Schema.optional(OrchestrationThreadSearchMatch.fields.messageCreatedAt),
260
+ }),
261
+ ),
262
+ }),
263
dependencies: [...commandTool.dependencies, ThreadSearch.ThreadSearch],
264
})
265
.annotate(Tool.Readonly, true)
apps/server/src/orchestration-v2/Orchestrator.ts
+16
-2
@@ -64,6 +64,7 @@ import {
64
type TurnItemId,
65
} from "@t3tools/contracts";
66
import { modelSelectionsEqual } from "@t3tools/shared/model";
67
+import { recordThreadOpen } from "@t3tools/shared/paletteSearch";
68
import {
69
derivePendingBackgroundWork,
70
pendingBackgroundTurnItems,
@@ -2566,6 +2567,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2567
const movesForward =
2568
thread.lastVisitedAt === null ||
2569
DateTime.toEpochMillis(visitedAt.value) > DateTime.toEpochMillis(thread.lastVisitedAt);
2570
+ const occurredAt = yield* DateTime.now;
2571
+ // Opens are timed by the server clock so devices with skewed clocks agree.
2572
+ const opens = command.opened
2573
+ ? recordThreadOpen(
2574
+ thread.opens ?? null,
2575
+ DateTime.toEpochMillis(occurredAt),
2576
+ command.searchQuery,
2577
+ )
2578
+ : null;
2579
// Viewing a thread changes read state only. Loading its transcript (or
2580
// bumping updatedAt) makes a routine read receipt scale with its history.
2581
yield* emit(
@@ -2575,8 +2585,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2585
type: "thread.visited",
2586
threadId: command.threadId,
2587
providerInstanceId: thread.providerInstanceId,
2578
- occurredAt: yield* DateTime.now,
2579
- payload: movesForward ? { ...thread, lastVisitedAt: visitedAt.value } : thread,
2588
+ occurredAt,
2589
+ payload: {
2590
+ ...thread,
2591
+ ...(movesForward ? { lastVisitedAt: visitedAt.value } : {}),
2592
+ ...(opens ? { opens } : {}),
2593
+ },
2594
});
2595
});
2596
apps/server/src/orchestration-v2/ProjectionStore.ts
+2
@@ -1678,6 +1678,7 @@ export function threadShellFromProjection(
1678
autoSettleDisabledAt: projection.thread.autoSettleDisabledAt ?? null,
1679
pinOrderKey: projection.thread.pinOrderKey ?? null,
1680
lastVisitedAt: projection.thread.lastVisitedAt,
1681
+ opens: projection.thread.opens ?? null,
1682
titleRegeneration: projection.thread.titleRegeneration ?? null,
1683
limitRecovery: projection.thread.limitRecovery ?? null,
1684
deletedAt: projection.thread.deletedAt,
@@ -1921,6 +1922,7 @@ function shellFromState(input: {
1922
autoSettleDisabledAt: input.state.thread.autoSettleDisabledAt ?? null,
1923
pinOrderKey: input.state.thread.pinOrderKey ?? null,
1924
lastVisitedAt: input.state.thread.lastVisitedAt,
1925
+ opens: input.state.thread.opens ?? null,
1926
titleRegeneration: input.state.thread.titleRegeneration ?? null,
1927
limitRecovery: input.state.thread.limitRecovery ?? null,
1928
deletedAt: input.state.thread.deletedAt,
apps/server/src/orchestration-v2/ThreadForkService.ts
+2
@@ -111,6 +111,8 @@ export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(
111
snoozedUntil: null,
112
snoozedAt: null,
113
lastVisitedAt: null,
114
+ // A fork is a new thread; it does not inherit how often the source was opened.
115
+ opens: null,
116
deletedAt: null,
117
};
118
const transfer: OrchestrationV2ContextTransfer = {
apps/server/src/orchestration-v2/ThreadManagementService.ts
+1
-1
@@ -87,7 +87,7 @@ function existingThreadIdsForCommand(
87
case "thread.create":
88
return [];
89
// Read-state commands only rewrite the thread payload's visited/unread
90
- // watermark; they never touch messages, so they do not need the imported
90
+ // watermark and open stats; they never touch messages, so they do not need the imported
91
// v1 transcript hydrated first. Visits fire on every thread-activity bump
92
// while a thread is open, so keeping them off the import path matters.
93
case "thread.visit":
apps/server/src/orchestration-v2/ThreadSearch.test.ts
+647
-8
@@ -11,6 +11,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
11
import * as DateTime from "effect/DateTime";
12
import * as Deferred from "effect/Deferred";
13
import * as Effect from "effect/Effect";
14
+import * as TestClock from "effect/testing/TestClock";
15
import * as FileSystem from "effect/FileSystem";
16
import * as Fiber from "effect/Fiber";
17
import * as Layer from "effect/Layer";
@@ -59,7 +60,12 @@ const createProject = (projectId: ProjectId) =>
60
const thread = (
61
threadId: ThreadId,
62
projectId: ProjectId,
62
- overrides: { readonly archivedAt?: DateTime.Utc; readonly deletedAt?: DateTime.Utc } = {},
63
+ overrides: {
64
+ readonly archivedAt?: DateTime.Utc;
65
+ readonly deletedAt?: DateTime.Utc;
66
+ readonly subagentOf?: ThreadId;
67
+ readonly title?: string;
68
+ } = {},
69
): OrchestrationV2DomainEvent => ({
70
id: EventId.make(`created:${threadId}`),
71
type: "thread.created",
@@ -71,7 +77,7 @@ const thread = (
77
creationSource: "web",
78
id: threadId,
79
projectId,
74
- title: threadId,
80
+ title: overrides.title ?? threadId,
81
providerInstanceId,
82
modelSelection: { instanceId: providerInstanceId, model: "gpt-5" },
83
runtimeMode: "full-access",
@@ -79,7 +85,13 @@ const thread = (
85
branch: null,
86
worktreePath: null,
87
activeProviderThreadId: null,
82
- lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
88
+ lineage: overrides.subagentOf
89
+ ? {
90
+ parentThreadId: overrides.subagentOf,
91
+ relationshipToParent: "subagent",
92
+ rootThreadId: overrides.subagentOf,
93
+ }
94
+ : { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
95
forkedFrom: null,
96
createdAt: at(0),
97
updatedAt: at(0),
@@ -96,7 +108,11 @@ const message = (
108
id: string,
109
role: "user" | "assistant" | "system",
110
text: string,
99
- options: { readonly minute?: number; readonly streaming?: boolean } = {},
111
+ options: {
112
+ readonly minute?: number;
113
+ readonly streaming?: boolean;
114
+ readonly createdBy?: "user" | "agent";
115
+ } = {},
116
): OrchestrationV2DomainEvent => ({
117
id: EventId.make(`message:${id}`),
118
type: "message.updated",
@@ -104,7 +120,7 @@ const message = (
120
providerInstanceId,
121
occurredAt: at(options.minute ?? 1),
122
payload: {
107
- createdBy: role === "user" ? "user" : "agent",
123
+ createdBy: options.createdBy ?? (role === "user" ? "user" : "agent"),
124
creationSource: role === "user" ? "web" : "provider",
125
id: MessageId.make(id),
126
threadId,
@@ -120,6 +136,21 @@ const message = (
136
});
137
138
it.layer(layerTest)("ThreadSearch", (it) => {
139
+ it.effect("reads the newest hits without sorting all of them", () =>
140
+ Effect.gen(function* () {
141
+ const sql = yield* SqlClient.SqlClient;
142
+ for (const match of ['"needle"', null]) {
143
+ const plan = yield* sql<{
144
+ readonly detail: string;
145
+ }>`EXPLAIN QUERY PLAN ${ThreadSearch.messageHitsQuery(sql, { match, substrings: "[]", projectId: null, excludedThreadIds: "[]" })}`;
146
+ assert.isFalse(
147
+ plan.some((row) => row.detail.includes("TEMP B-TREE")),
148
+ plan.map((row) => row.detail).join("\n"),
149
+ );
150
+ }
151
+ }),
152
+ );
153
+
154
it.effect("returns one finished user or assistant match per active thread", () =>
155
Effect.gen(function* () {
156
const projections = yield* ProjectionStore.ProjectionStoreV2;
@@ -168,18 +199,626 @@ it.layer(layerTest)("ThreadSearch", (it) => {
199
200
const result = yield* search.search({ query: "NEEDLE", limit: 20 });
201
assert.deepEqual(
171
- result.matches.map((match) => [match.threadId, match.source, match.snippet]),
202
+ result.matches
203
+ .map((match) => [match.threadId, match.source, match.snippet, match.messageId])
204
+ .toSorted(([left], [right]) => String(left).localeCompare(String(right))),
205
[
173
- [both, "user", "newer needle question"],
174
- [assistantOnly, "assistant", "needle in an answer"],
206
+ [assistantOnly, "assistant", "needle in an answer", "assistant-only"],
207
+ [both, "user", "newer needle question", "both-user-new"],
208
],
209
);
210
assert.lengthOf((yield* search.search({ query: "needle", limit: 1 })).matches, 1);
211
assert.deepEqual((yield* search.search({ query: "ne%le" })).matches, []);
212
}),
213
);
214
+
215
+ it.effect("indexes a message when it finishes streaming and follows later edits", () =>
216
+ Effect.gen(function* () {
217
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
218
+ const search = yield* ThreadSearch.ThreadSearch;
219
+ const project = ProjectId.make("project:search-sync");
220
+ const threadId = ThreadId.make("thread:sync");
221
+ yield* createProject(project);
222
+ yield* projections.apply(thread(threadId, project));
223
+ const threadIds = (query: string) =>
224
+ search.search({ query }).pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
225
+
226
+ yield* projections.apply(
227
+ message(threadId, "sync", "assistant", "streaming draft", { streaming: true }),
228
+ );
229
+ assert.deepEqual(yield* threadIds("draft"), []);
230
+
231
+ yield* projections.apply(message(threadId, "sync", "assistant", "finished answer"));
232
+ assert.deepEqual(yield* threadIds("finished"), [threadId]);
233
+
234
+ yield* projections.apply(message(threadId, "sync", "assistant", "edited reply"));
235
+ assert.deepEqual(yield* threadIds("finished"), []);
236
+ assert.deepEqual(yield* threadIds("edited"), [threadId]);
237
+ }),
238
+ );
239
+
240
+ it.effect("matches inside identifiers and skips subagent threads and short tokens", () =>
241
+ Effect.gen(function* () {
242
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
243
+ const search = yield* ThreadSearch.ThreadSearch;
244
+ const project = ProjectId.make("project:search-tokens");
245
+ const parent = ThreadId.make("thread:tokens-parent");
246
+ const subagent = ThreadId.make("thread:tokens-subagent");
247
+ yield* createProject(project);
248
+ yield* Effect.forEach(
249
+ [
250
+ thread(parent, project),
251
+ message(parent, "parent", "user", "Rename ThreadSearchService before shipping"),
252
+ thread(subagent, project, { subagentOf: parent }),
253
+ message(subagent, "subagent", "assistant", "ThreadSearchService renamed"),
254
+ ],
255
+ projections.apply,
256
+ { discard: true },
257
+ );
258
+
259
+ const result = yield* search.search({ query: "search servi" });
260
+ assert.deepEqual(
261
+ result.matches.map((match) => [match.threadId, match.snippet]),
262
+ [[parent, "Rename ThreadSearchService before shipping"]],
263
+ );
264
+ // "ab" alone cannot use the index; with a longer token it narrows the hits.
265
+ assert.deepEqual((yield* search.search({ query: "ab" })).matches, []);
266
+ assert.lengthOf((yield* search.search({ query: "renam be" })).matches, 1);
267
+ assert.lengthOf((yield* search.search({ query: "renam ab" })).matches, 0);
268
+ }),
269
+ );
270
+
271
+ it.effect("indexes neither subagent messages nor rewrites that keep the text", () =>
272
+ Effect.gen(function* () {
273
+ const sql = yield* SqlClient.SqlClient;
274
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
275
+ const project = ProjectId.make("project:search-index-writes");
276
+ const parent = ThreadId.make("thread:index-parent");
277
+ const subagent = ThreadId.make("thread:index-subagent");
278
+ yield* createProject(project);
279
+ yield* Effect.forEach(
280
+ [
281
+ thread(parent, project),
282
+ message(parent, "index-parent", "assistant", "parent answer"),
283
+ thread(subagent, project, { subagentOf: parent }),
284
+ message(subagent, "index-subagent", "assistant", "subagent answer"),
285
+ ],
286
+ projections.apply,
287
+ { discard: true },
288
+ );
289
+ const indexedThreads = sql<{ readonly threadId: string }>`
290
+ SELECT messages.thread_id AS "threadId"
291
+ FROM orchestration_v2_message_search AS search
292
+ INNER JOIN orchestration_v2_projection_messages AS messages
293
+ ON messages.rowid = search.rowid
294
+ WHERE messages.thread_id IN (${parent}, ${subagent})
295
+ `.pipe(Effect.map((rows) => rows.map((row) => row.threadId)));
296
+ assert.deepEqual(yield* indexedThreads, [parent]);
297
+
298
+ // total_changes counts trigger writes, so 1 means the index was untouched.
299
+ const changes = sql<{ readonly n: number }>`SELECT total_changes() AS n`.pipe(
300
+ Effect.map(([row]) => row?.n ?? 0),
301
+ );
302
+ const before = yield* changes;
303
+ yield* sql`
304
+ UPDATE orchestration_v2_projection_messages
305
+ SET payload_json = json_set(payload_json, '$.updatedAt', '2026-09-27T01:00:00.000Z')
306
+ WHERE message_id = 'index-parent'
307
+ `;
308
+ assert.strictEqual((yield* changes) - before, 1);
309
+ assert.deepEqual(yield* indexedThreads, [parent]);
310
+ }),
311
+ );
312
});
313
314
+it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => {
315
+ it.effect("orders message matches by when they were written, not by row order", () =>
316
+ Effect.gen(function* () {
317
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
318
+ const search = yield* ThreadSearch.ThreadSearch;
319
+ const project = ProjectId.make("project:written");
320
+ yield* createProject(project);
321
+ const recent = ThreadId.make("thread:written-recent");
322
+ const imported = ThreadId.make("thread:written-imported");
323
+ // An imported history lands after newer messages in row order.
324
+ yield* Effect.forEach(
325
+ [
326
+ thread(recent, project),
327
+ message(recent, "written-recent", "user", "kestrel deploy notes", { minute: 30 }),
328
+ thread(imported, project),
329
+ message(imported, "written-imported", "user", "kestrel deploy notes", { minute: 1 }),
330
+ ],
331
+ projections.apply,
332
+ { discard: true },
333
+ );
334
+ const { matches } = yield* search.search({ query: "kestrel" });
335
+ assert.deepEqual(
336
+ matches.map((match) => match.threadId),
337
+ [recent, imported],
338
+ );
339
+ }),
340
+ );
341
+
342
+ it.effect("ranks a thread about the word above a passing mention", () =>
343
+ Effect.gen(function* () {
344
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
345
+ const search = yield* ThreadSearch.ThreadSearch;
346
+ const project = ProjectId.make("project:about");
347
+ yield* createProject(project);
348
+ const about = ThreadId.make("thread:about-osprey");
349
+ const mention = ThreadId.make("thread:mention-osprey");
350
+ yield* Effect.forEach(
351
+ [
352
+ thread(about, project),
353
+ ...Array.from({ length: 12 }, (_, index) =>
354
+ message(about, `about-osprey-${index}`, "assistant", `osprey step ${index}`, {
355
+ minute: 2,
356
+ }),
357
+ ),
358
+ thread(mention, project),
359
+ message(mention, "mention-osprey", "user", "also check osprey", { minute: 5 }),
360
+ ],
361
+ projections.apply,
362
+ { discard: true },
363
+ );
364
+ const { matches } = yield* search.search({ query: "osprey" });
365
+ assert.deepEqual(
366
+ matches.map((match) => [match.threadId, match.hits]),
367
+ [
368
+ [about, 12],
369
+ [mention, 1],
370
+ ],
371
+ );
372
+ }),
373
+ );
374
+
375
+ it.effect("counts a thread's hits at its best match only", () =>
376
+ Effect.gen(function* () {
377
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
378
+ const search = yield* ThreadSearch.ThreadSearch;
379
+ const project = ProjectId.make("project:best-hits");
380
+ yield* createProject(project);
381
+ const clarks = ThreadId.make("thread:clarks");
382
+ const larks = ThreadId.make("thread:lark-many");
383
+ yield* Effect.forEach(
384
+ [
385
+ thread(clarks, project),
386
+ message(clarks, "clarks-lark", "user", "Lark once", { minute: 3 }),
387
+ ...Array.from({ length: 31 }, (_, index) =>
388
+ message(clarks, `clarks-${index}`, "assistant", "Clark the plan", { minute: 3 }),
389
+ ),
390
+ thread(larks, project),
391
+ ...Array.from({ length: 8 }, (_, index) =>
392
+ message(larks, `lark-many-${index}`, "assistant", "Lark again", { minute: 3 }),
393
+ ),
394
+ ],
395
+ projections.apply,
396
+ { discard: true },
397
+ );
398
+ const { matches } = yield* search.search({ query: "lark" });
399
+ assert.deepEqual(
400
+ matches.map((match) => [match.threadId, match.hits]),
401
+ [
402
+ [larks, 8],
403
+ [clarks, 1],
404
+ ],
405
+ );
406
+ }),
407
+ );
408
+
409
+ it.effect("finds a visible match behind hundreds of hidden or narrower hits", () =>
410
+ Effect.gen(function* () {
411
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
412
+ const search = yield* ThreadSearch.ThreadSearch;
413
+ const project = ProjectId.make("project:crowded");
414
+ const parent = ThreadId.make("thread:crowded-parent");
415
+ const subagent = ThreadId.make("thread:crowded-subagent");
416
+ const older = ThreadId.make("thread:crowded-older");
417
+ yield* createProject(project);
418
+ yield* Effect.forEach(
419
+ [
420
+ thread(parent, project),
421
+ thread(subagent, project, { subagentOf: parent }),
422
+ thread(older, project),
423
+ ...Array.from({ length: 450 }, (_, index) =>
424
+ message(subagent, `subagent-${index}`, "assistant", "needle needle"),
425
+ ),
426
+ ...Array.from({ length: 450 }, (_, index) =>
427
+ message(older, `older-${index}`, "assistant", "pnpm 11 pnpm"),
428
+ ),
429
+ message(parent, "parent-needle", "user", "a needle in a long haystack of other words"),
430
+ // Agent-written notices in user messages are not indexed, so they never read as "You".
431
+ message(older, "older-notice", "user", "needle update from a watched pull request", {
432
+ createdBy: "agent",
433
+ }),
434
+ message(parent, "parent-pnpm", "user", "moved the repo to pnpm 12 today"),
435
+ ],
436
+ projections.apply,
437
+ { discard: true },
438
+ );
439
+
440
+ const threadIds = (query: string) =>
441
+ search.search({ query }).pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
442
+ assert.deepEqual(yield* threadIds("needle"), [parent]);
443
+ assert.deepEqual(yield* threadIds("pnpm 12"), [parent]);
444
+ }),
445
+ );
446
+
447
+ it.effect("keeps a thread picked for the query when the limit cuts", () =>
448
+ Effect.gen(function* () {
449
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
450
+ const search = yield* ThreadSearch.ThreadSearch;
451
+ const sql = yield* SqlClient.SqlClient;
452
+ const project = ProjectId.make("project:plover");
453
+ const busy = ThreadId.make("thread:plover-busy");
454
+ const picked = ThreadId.make("thread:plover-picked");
455
+ yield* createProject(project);
456
+ yield* Effect.forEach(
457
+ [
458
+ thread(busy, project),
459
+ message(busy, "plover-1", "user", "plover notes", { minute: 3 }),
460
+ message(busy, "plover-2", "user", "more plover notes", { minute: 4 }),
461
+ thread(picked, project),
462
+ message(picked, "plover-old", "user", "one plover mention", { minute: 1 }),
463
+ ],
464
+ projections.apply,
465
+ { discard: true },
466
+ );
467
+ const threadIds = () =>
468
+ search
469
+ .search({ query: "plover", limit: 1 })
470
+ .pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
471
+ assert.deepEqual(yield* threadIds(), [busy]);
472
+ // A pick at time 0 would read as no pick.
473
+ yield* TestClock.adjust("1 day");
474
+ const at = DateTime.toEpochMillis(yield* DateTime.now);
475
+ yield* sql`
476
+ UPDATE orchestration_v2_projection_threads
477
+ SET payload_json = json_set(payload_json, '$.opens', json(${JSON.stringify({
478
+ openedAt: at,
479
+ score: 1,
480
+ picks: [{ query: "plover", at }],
481
+ })}))
482
+ WHERE thread_id = ${picked}
483
+ `;
484
+ assert.deepEqual(yield* threadIds(), [picked]);
485
+ }),
486
+ );
487
+
488
+ it.effect("finds a curly apostrophe for a straight one and back", () =>
489
+ Effect.gen(function* () {
490
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
491
+ const search = yield* ThreadSearch.ThreadSearch;
492
+ const project = ProjectId.make("project:apostrophes");
493
+ const curly = ThreadId.make("thread:apostrophe-curly");
494
+ const straight = ThreadId.make("thread:apostrophe-straight");
495
+ yield* createProject(project);
496
+ yield* Effect.forEach(
497
+ [
498
+ thread(curly, project),
499
+ message(curly, "apostrophe-curly", "user", "the gannet\u2019s nest"),
500
+ thread(straight, project),
501
+ message(straight, "apostrophe-straight", "user", "a kittiwake's nest"),
502
+ ],
503
+ projections.apply,
504
+ { discard: true },
505
+ );
506
+ const threadIds = (query: string) =>
507
+ search.search({ query }).pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
508
+ assert.deepEqual(yield* threadIds("gannet's"), [curly]);
509
+ assert.deepEqual(yield* threadIds("kittiwake\u2019s"), [straight]);
510
+ }),
511
+ );
512
+
513
+ it.effect("leaves out answers to an agent's question, which show in its card", () =>
514
+ Effect.gen(function* () {
515
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
516
+ const search = yield* ThreadSearch.ThreadSearch;
517
+ const project = ProjectId.make("project:answers");
518
+ const asked = ThreadId.make("thread:answers");
519
+ yield* createProject(project);
520
+ yield* Effect.forEach(
521
+ [
522
+ thread(asked, project),
523
+ message(asked, "async-answer:request-1", "user", "use the albatross drive"),
524
+ ],
525
+ projections.apply,
526
+ { discard: true },
527
+ );
528
+ assert.deepEqual((yield* search.search({ query: "albatross" })).matches, []);
529
+ }),
530
+ );
531
+
532
+ it.effect("matches messages as they read, with links as their text", () =>
533
+ Effect.gen(function* () {
534
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
535
+ const search = yield* ThreadSearch.ThreadSearch;
536
+ const project = ProjectId.make("project:heron");
537
+ const labeled = ThreadId.make("thread:heron-label");
538
+ const addressOnly = ThreadId.make("thread:heron-address");
539
+ yield* createProject(project);
540
+ yield* Effect.forEach(
541
+ [
542
+ thread(labeled, project),
543
+ message(labeled, "heron-label", "assistant", "See [the heron plan](https://x.dev/a) now"),
544
+ thread(addressOnly, project),
545
+ message(addressOnly, "heron-address", "user", "Read [this](https://heron.dev/b)"),
546
+ ],
547
+ projections.apply,
548
+ { discard: true },
549
+ );
550
+ const { matches } = yield* search.search({ query: "heron" });
551
+ assert.deepEqual(
552
+ matches.map((match) => [match.threadId, match.snippet]),
553
+ [[labeled, "See the heron plan now"]],
554
+ );
555
+ }),
556
+ );
557
+
558
+ it.effect("reads at most the newest 10,000 index hits, however many the filters drop", () =>
559
+ Effect.gen(function* () {
560
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
561
+ const search = yield* ThreadSearch.ThreadSearch;
562
+ const sql = yield* SqlClient.SqlClient;
563
+ const project = ProjectId.make("project:kestrel");
564
+ const old = ThreadId.make("thread:kestrel-old");
565
+ const busy = ThreadId.make("thread:kestrel-busy");
566
+ yield* createProject(project);
567
+ yield* Effect.forEach(
568
+ [
569
+ thread(old, project),
570
+ message(old, "kestrel-old", "user", "kestrel ci is red"),
571
+ thread(busy, project),
572
+ ],
573
+ projections.apply,
574
+ { discard: true },
575
+ );
576
+ const insertBusy = (count: number) => sql`
577
+ WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ${count})
578
+ INSERT INTO orchestration_v2_projection_messages
579
+ (message_id, thread_id, role, streaming, created_at, updated_at, payload_json)
580
+ SELECT 'kestrel-busy-' || i, ${busy}, 'assistant', 0, ${DateTime.formatIso(at(5))},
581
+ ${DateTime.formatIso(at(5))}, json_object('text', 'kestrel packages')
582
+ FROM n
583
+ `;
584
+ const threadIds = (query: string) =>
585
+ search.search({ query }).pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
586
+ yield* insertBusy(9_999);
587
+ assert.deepEqual(yield* threadIds("kestrel ci"), [old]);
588
+ yield* sql`DELETE FROM orchestration_v2_projection_messages WHERE thread_id = ${busy}`;
589
+ yield* insertBusy(10_000);
590
+ assert.deepEqual(yield* threadIds("kestrel ci"), []);
591
+ }),
592
+ );
593
+});
594
+
595
+it.layer(layerTest)("ThreadSearch across scripts and without the index", (it) => {
596
+ it.effect(
597
+ "matches Korean, Japanese, and two-character Chinese words, and whole short words",
598
+ () =>
599
+ Effect.gen(function* () {
600
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
601
+ const search = yield* ThreadSearch.ThreadSearch;
602
+ const sql = yield* SqlClient.SqlClient;
603
+ const project = ProjectId.make("project:scripts");
604
+ const threadId = ThreadId.make("thread:scripts");
605
+ const drafts = ThreadId.make("thread:drafts");
606
+ const addresses = ThreadId.make("thread:addresses");
607
+ yield* createProject(project);
608
+ yield* Effect.forEach(
609
+ [
610
+ thread(threadId, project),
611
+ message(threadId, "korean", "user", "검색 기능을 고쳐 주세요"),
612
+ message(threadId, "japanese", "user", "がんばって検索します"),
613
+ message(threadId, "chinese", "user", "明天部署到生产环境"),
614
+ message(threadId, "fts", "assistant", "the FTS index is ready"),
615
+ thread(drafts, project),
616
+ message(drafts, "drafts", "assistant", "saved two drafts and shifts"),
617
+ message(threadId, "camel", "assistant", "Configure enableFTS today"),
618
+ message(threadId, "accented", "user", "Review Résumé indexing"),
619
+ thread(addresses, project),
620
+ message(addresses, "addresses", "user", "This addresses Résumé indexing"),
621
+ ],
622
+ projections.apply,
623
+ { discard: true },
624
+ );
625
+ const threadIds = (query: string) =>
626
+ search
627
+ .search({ query })
628
+ .pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
629
+
630
+ // Short words must start a word, which camelCase and accented words do.
631
+ for (const query of ["검색 기능", "がんばって", "部署", "fts", "enable"]) {
632
+ assert.deepEqual(yield* threadIds(query), [threadId], query);
633
+ }
634
+ // "res" inside "addresses" does not hide the accented word after it.
635
+ assert.sameMembers(yield* threadIds("res"), [threadId, addresses]);
636
+ // A word beats the same letters inside a longer word, even in an older message.
637
+ const trust = ThreadId.make("thread:trust");
638
+ const rust = ThreadId.make("thread:rust");
639
+ yield* Effect.forEach(
640
+ [
641
+ thread(rust, project),
642
+ message(rust, "rust", "assistant", "Rust rewrite notes"),
643
+ thread(trust, project),
644
+ message(trust, "trust", "user", "We trust the build"),
645
+ ],
646
+ projections.apply,
647
+ { discard: true },
648
+ );
649
+ const { matches } = yield* search.search({ query: "rust" });
650
+ assert.deepEqual(
651
+ matches.map((match) => [match.threadId, (match.quality ?? 1) <= 0.3]),
652
+ [
653
+ [rust, false],
654
+ [trust, true],
655
+ ],
656
+ );
657
+ // Without the index (an SQLite build without FTS5 trigrams) search scans instead.
658
+ yield* sql`DROP TABLE orchestration_v2_message_search`;
659
+ assert.deepEqual(yield* threadIds("検索"), [threadId]);
660
+ assert.deepEqual(yield* threadIds("fts"), [threadId]);
661
+ }),
662
+ );
663
+});
664
+
665
+it.layer(layerTest)("ThreadSearch.searchThreads", (it) => {
666
+ it.effect("keeps room for a message-only thread behind many titled ones", () =>
667
+ Effect.gen(function* () {
668
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
669
+ const search = yield* ThreadSearch.ThreadSearch;
670
+ const project = ProjectId.make("project:petrel");
671
+ yield* createProject(project);
672
+ const messageOnly = ThreadId.make("thread:petrel-message");
673
+ yield* Effect.forEach(
674
+ [
675
+ thread(messageOnly, project),
676
+ // The oldest message, so a cut taken before titles drop would lose it.
677
+ message(messageOnly, "petrel-old", "user", "a petrel note", { minute: 1 }),
678
+ ...Array.from({ length: 50 }, (_, index) => {
679
+ const id = ThreadId.make(`thread:petrel-${index}`);
680
+ return [
681
+ thread(id, project, { title: `Petrel ${index}` }),
682
+ message(id, `petrel-${index}`, "user", "petrel again", { minute: 2 }),
683
+ ];
684
+ }).flat(),
685
+ ],
686
+ projections.apply,
687
+ { discard: true },
688
+ );
689
+ const { matches } = yield* search.searchThreads({ query: "petrel", limit: 5 });
690
+ assert.include(
691
+ matches.map((match) => match.threadId),
692
+ messageOnly,
693
+ );
694
+ }),
695
+ );
696
+
697
+ it.effect("leaves titled threads out before the hit limit", () =>
698
+ Effect.gen(function* () {
699
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
700
+ const search = yield* ThreadSearch.ThreadSearch;
701
+ const sql = yield* SqlClient.SqlClient;
702
+ const project = ProjectId.make("project:hit-limit");
703
+ const messageOnly = ThreadId.make("thread:grebe-message");
704
+ const titled = ThreadId.make("thread:grebe-titled");
705
+ yield* createProject(project);
706
+ yield* Effect.forEach(
707
+ [
708
+ thread(messageOnly, project, { title: "Unrelated" }),
709
+ message(messageOnly, "grebe-old", "user", "a grebe note", { minute: 1 }),
710
+ thread(titled, project, { title: "Grebe" }),
711
+ ],
712
+ projections.apply,
713
+ { discard: true },
714
+ );
715
+ // Newer hits than one read holds, all in the titled thread.
716
+ yield* sql`
717
+ WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
718
+ INSERT INTO orchestration_v2_projection_messages
719
+ (message_id, thread_id, role, streaming, created_at, updated_at, payload_json)
720
+ SELECT 'grebe-titled-' || i, ${titled}, 'assistant', 0, ${DateTime.formatIso(at(5))},
721
+ ${DateTime.formatIso(at(5))}, json_object('text', 'grebe again')
722
+ FROM n
723
+ `;
724
+ const { matches } = yield* search.searchThreads({ query: "grebe", limit: 5 });
725
+ assert.include(
726
+ matches.map((match) => match.threadId),
727
+ messageOnly,
728
+ );
729
+ }),
730
+ );
731
+
732
+ it.effect("ranks title matches like the palette, then message matches, within one project", () =>
733
+ Effect.gen(function* () {
734
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
735
+ const search = yield* ThreadSearch.ThreadSearch;
736
+ const project = ProjectId.make("project:titles");
737
+ const otherProject = ProjectId.make("project:titles-other");
738
+ yield* createProject(project);
739
+ yield* createProject(otherProject);
740
+ const wordStart = ThreadId.make("thread:word-start");
741
+ const midWord = ThreadId.make("thread:mid-word");
742
+ const messageOnly = ThreadId.make("thread:message-only");
743
+ const elsewhere = ThreadId.make("thread:elsewhere");
744
+ yield* Effect.forEach(
745
+ [
746
+ thread(midWord, project, { title: "Fix oauth redirect" }),
747
+ thread(wordStart, project, { title: "Clean up auth tokens" }),
748
+ thread(messageOnly, project, { title: "Unrelated" }),
749
+ message(messageOnly, "message-only", "user", "the auth flow broke again"),
750
+ thread(elsewhere, otherProject, { title: "Auth everywhere" }),
751
+ ],
752
+ projections.apply,
753
+ { discard: true },
754
+ );
755
+
756
+ // Stronger message hits in another project must not use up this project's limit.
757
+ yield* Effect.forEach(
758
+ Array.from({ length: 55 }, (_, index) => {
759
+ const busy = ThreadId.make(`thread:elsewhere-${index}`);
760
+ return [
761
+ thread(busy, otherProject),
762
+ message(busy, `elsewhere-${index}`, "user", "auth auth auth"),
763
+ ];
764
+ }).flat(),
765
+ projections.apply,
766
+ { discard: true },
767
+ );
768
+ const result = yield* search.searchThreads({ query: "auth", projectId: project, limit: 3 });
769
+ assert.deepEqual(
770
+ result.matches.map((match) => [match.threadId, match.source]),
771
+ [
772
+ [wordStart, "title"],
773
+ [midWord, "title"],
774
+ [messageOnly, "user"],
775
+ ],
776
+ );
777
+ // With one slot, an exact title keeps it.
778
+ assert.deepEqual(
779
+ (yield* search.searchThreads({ query: "auth", projectId: project, limit: 1 })).matches.map(
780
+ (match) => match.threadId,
781
+ ),
782
+ [wordStart],
783
+ );
784
+ // Exact matching finds nothing, so one typo is forgiven.
785
+ assert.deepEqual(
786
+ (yield* search.searchThreads({ query: "tokesn", projectId: project })).matches.map(
787
+ (match) => match.title,
788
+ ),
789
+ ["Clean up auth tokens"],
790
+ );
791
+ }),
792
+ );
793
+});
794
+
795
+it.effect("starts snippets a few words before the match so one line shows it", () =>
796
+ Effect.sync(() => {
797
+ const snippet = (text: string, word: string) =>
798
+ ThreadSearch.buildSearchSnippet(text, text.indexOf(word));
799
+ const long = `${"lead ".repeat(60)}the NEEDLE sits here ${"tail ".repeat(60)}`;
800
+ const cut = snippet(long, "NEEDLE");
801
+ assert.isAtMost(cut.length, 240);
802
+ assert.match(cut, /^…(lead ){2,4}the NEEDLE sits here/);
803
+ assert.isTrue(cut.endsWith("…"));
804
+ // Whitespace collapses only in the shown part, so the offset still lands.
805
+ assert.match(snippet(`${"word\n\n ".repeat(60)}un café`, "café"), /un café$/);
806
+ // A cut never splits an emoji's surrogate pair.
807
+ assert.notMatch(
808
+ snippet(`x${"🚀".repeat(200)}needle`, "needle"),
809
+ /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,
810
+ );
811
+ // Emphasis and code marks go, as the thread shows the text.
812
+ assert.equal(
813
+ ThreadSearch.buildSearchSnippet("Use **bold** and `code` here", 0),
814
+ "Use bold and code here",
815
+ );
816
+ assert.equal(ThreadSearch.buildSearchSnippet("Call __init__ first", 0), "Call __init__ first");
817
+ // Short text still moves a late match into view.
818
+ assert.equal(snippet(`${"word ".repeat(20)}needle`, "needle"), "…word word word word needle");
819
+ }),
820
+);
821
+
822
it.effect("searches on the reader worker while the writer is busy", () =>
823
Effect.gen(function* () {
824
const fileSystem = yield* FileSystem.FileSystem;
apps/server/src/orchestration-v2/ThreadSearch.ts
+424
-100
@@ -1,18 +1,46 @@
1
import {
2
IsoDateTime,
3
+ MessageId,
4
OrchestrationThreadSearchSource,
5
+ OrchestrationV2AppThreadJson,
6
+ OrchestrationV2ThreadOpens,
7
type OrchestrationSearchThreadsInput,
8
type OrchestrationSearchThreadsResult,
9
ProjectId,
10
ThreadId,
11
} from "@t3tools/contracts";
12
+import * as DateTime from "effect/DateTime";
13
import * as Context from "effect/Context";
14
import * as Effect from "effect/Effect";
15
import * as Layer from "effect/Layer";
16
+import * as Option from "effect/Option";
17
import * as Schema from "effect/Schema";
18
import * as SqlClient from "effect/sql/SqlClient";
19
import * as SqlSchema from "effect/sql/SqlSchema";
20
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
21
+import {
22
+ messageSearchTokens,
23
+ foldSearchQuery,
24
+ rankMessageMatches,
25
+ rankSearchItems,
26
+ messageMatcher,
27
+ scoreThreadSearch,
28
+ type ThreadSearchSubject,
29
+} from "@t3tools/shared/paletteSearch";
30
+import { threadSearchPullRequests } from "@t3tools/shared/threadPullRequests";
31
+import { indexedMessageCondition } from "./messageSearchIndex.ts";
32
+
33
+// When the user last wrote in the thread aliased `threads`, as the clients
34
+// rank recency; agent notices in the user role do not count.
35
+const latestUserMessageAt = (sql: SqlClient.SqlClient) => sql`(
36
+ SELECT messages.updated_at
37
+ FROM orchestration_v2_projection_messages AS messages
38
+ WHERE messages.thread_id = threads.thread_id
39
+ AND messages.role = 'user'
40
+ AND COALESCE(json_extract(messages.payload_json, '$.createdBy'), 'user') = 'user'
41
+ ORDER BY messages.updated_at DESC, messages.message_id DESC
42
+ LIMIT 1
43
+)`;
44
45
export class ThreadSearchError extends Schema.TaggedError<ThreadSearchError>()(
46
"ThreadSearchError",
@@ -26,45 +54,211 @@ export class ThreadSearchError extends Schema.TaggedError<ThreadSearchError>()(
54
}
55
}
56
29
-const SearchRequest = Schema.Struct({ pattern: Schema.String, limit: Schema.Int });
57
+// Token lists bind as JSON arrays, so any number of them is one parameter.
58
+const TokenList = Schema.fromJsonString(Schema.Array(Schema.String));
59
+const SearchRequest = Schema.Struct({
60
+ /** The FTS5 query, or null to scan messages instead. */
61
+ match: Schema.NullOr(Schema.String),
62
+ /** Tokens every hit must contain, checked on the text. */
63
+ substrings: TokenList,
64
+ projectId: Schema.NullOr(ProjectId),
65
+ /** Threads the caller already lists, left out before the hit limit. */
66
+ excludedThreadIds: TokenList,
67
+});
68
const SearchRow = Schema.Struct({
69
+ messageRowid: Schema.Number,
70
+ messageId: MessageId,
71
threadId: ThreadId,
72
projectId: ProjectId,
73
source: OrchestrationThreadSearchSource,
34
- matchText: Schema.String,
74
+ text: Schema.String,
75
messageCreatedAt: Schema.NullOr(IsoDateTime),
76
});
77
38
-function escapeLikePattern(value: string): string {
39
- return value.replaceAll("!", "!!").replaceAll("%", "!%").replaceAll("_", "!_");
78
+const ThreadOpensRow = Schema.Struct({
79
+ threadId: ThreadId,
80
+ opens: Schema.NullOr(Schema.String),
81
+ latestUserMessageAt: Schema.NullOr(IsoDateTime),
82
+});
83
+const decodeThreadOpens = Schema.decodeUnknownOption(
84
+ Schema.fromJsonString(OrchestrationV2ThreadOpens),
85
+);
86
+
87
+const SNIPPET_LENGTH = 240;
88
+// The newest hits read per query. A common word stops here instead of reading
89
+// every message, so time stays flat as history grows.
90
+const MESSAGE_HIT_LIMIT = 2000;
91
+// How many of the newest index hits the filters may pass over to fill that
92
+// limit: a rare short word or hidden threads would otherwise read every hit.
93
+const MESSAGE_CANDIDATE_LIMIT = 10_000;
94
+// Without the index, how many of the newest messages a search scans.
95
+const MESSAGE_SCAN_LIMIT = 20_000;
96
+
97
+/**
98
+ * The SQL inputs for a message search, or null when the query has no token
99
+ * long enough to search. Tokens of three or more characters go to the
100
+ * trigram index as quoted phrases; shorter ones, and every token when the
101
+ * index cannot serve the query, are checked as substrings of the hits.
102
+ */
103
+function buildMessageSearch(
104
+ query: string,
105
+ hasIndex: boolean,
106
+): Omit<typeof SearchRequest.Type, "projectId" | "excludedThreadIds"> | null {
107
+ const { long, short } = messageSearchTokens(query);
108
+ if (long.length === 0) return null;
109
+ // Two-character CJK words are too short for trigrams.
110
+ const indexed = hasIndex && long.every((token) => Array.from(token).length >= 3);
111
+ return {
112
+ match: indexed ? long.map((token) => `"${token.replaceAll('"', '""')}"`).join(" ") : null,
113
+ substrings: indexed ? short : [...long, ...short],
114
+ };
115
}
116
42
-function foldAsciiCase(value: string): string {
43
- return value.replace(/[A-Z]/g, (character) => character.toLowerCase());
117
+// A thread shows a link as its text, so in-thread find cannot reach a match
118
+// in the address; messages are matched as they read.
119
+const MARKDOWN_LINK = /!?\[([^\]\n]*)\]\([^)\s]*\)/g;
120
+
121
+// Result rows show one line, so the match must sit near the start to be seen.
122
+const SNIPPET_LEAD = 24;
123
+
124
+const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
125
+
126
+/**
127
+ * Up to 240 characters starting a few words before the match at `matchStart`,
128
+ * whitespace collapsed, with ellipses where the text was cut. The client finds
129
+ * the highlights again in the result.
130
+ */
131
+export function buildSearchSnippet(text: string, matchStart: number): string {
132
+ let start = Math.max(0, matchStart - SNIPPET_LEAD);
133
+ const wordStart = text.slice(start, matchStart).search(/\s/);
134
+ if (start > 0 && wordStart !== -1) start += wordStart + 1;
135
+ // Cut between characters, not inside an emoji's surrogate pair.
136
+ if (isLowSurrogate(text.charCodeAt(start))) start++;
137
+ // Collapsing whitespace shortens the text, so read more of it.
138
+ const rawEnd = Math.min(text.length, start + SNIPPET_LENGTH * 2);
139
+ // Emphasis and code marks do not show in a thread either.
140
+ const shown = text
141
+ .slice(start, rawEnd)
142
+ .replace(/\*\*|`+/g, "")
143
+ .replace(/\s+/g, " ")
144
+ .trim();
145
+ let end = Math.min(shown.length, SNIPPET_LENGTH - 2);
146
+ if (isLowSurrogate(shown.charCodeAt(end))) end--;
147
+ const cut = end < shown.length || rawEnd < text.length;
148
+ return `${start > 0 ? "…" : ""}${shown.slice(0, end)}${cut ? "…" : ""}`;
149
}
150
46
-function buildSearchSnippet(text: string, query: string): string {
47
- const normalizedText = text.replace(/\s+/g, " ").trim();
48
- if (normalizedText.length <= 240) {
49
- return normalizedText;
50
- }
51
- const normalizedQuery = foldAsciiCase(query.replace(/\s+/g, " ").trim());
52
- const matchIndex = foldAsciiCase(normalizedText).indexOf(normalizedQuery);
53
- const bodyLength = 236;
54
- const idealStart = Math.max(0, matchIndex - 72);
55
- const start = Math.min(idealStart, normalizedText.length - bodyLength);
56
- const end = Math.min(normalizedText.length, start + bodyLength);
57
- return `${start > 0 ? "…" : ""}${normalizedText.slice(start, end)}${
58
- end < normalizedText.length ? "…" : ""
59
- }`;
151
+// The newest messages that hold every token, from active, non-subagent
152
+// threads. Every palette and sidebar hides subagent threads, so their
153
+// messages would only use up the hit limit; filters apply before it, so
154
+// hidden threads never crowd out a visible match. Word starts and ranking
155
+// happen in JS, with the rules titles use.
156
+//
157
+// Without the index (an SQLite build without FTS5 trigrams, see migration
158
+// 69) or for two-character CJK words, the same query scans the newest
159
+// messages migration 69 would index. That scan is weaker than the index: it
160
+// ignores case for ASCII only and does not fold accents ("cafe" misses
161
+// "café"). Exported so a test can check the query plan.
162
+export const messageHitsQuery = (
163
+ sql: SqlClient.SqlClient,
164
+ { match, substrings, projectId, excludedThreadIds }: typeof SearchRequest.Encoded,
165
+) => sql`
166
+ WITH eligible AS MATERIALIZED (
167
+ SELECT threads.thread_id, threads.project_id
168
+ FROM orchestration_v2_projection_threads AS threads
169
+ INNER JOIN projection_projects AS projects
170
+ ON projects.project_id = threads.project_id
171
+ WHERE threads.deleted_at IS NULL
172
+ AND threads.archived_at IS NULL
173
+ AND projects.deleted_at IS NULL
174
+ AND (${projectId} IS NULL OR threads.project_id = ${projectId})
175
+ AND threads.thread_id NOT IN (SELECT value FROM json_each(${excludedThreadIds}))
176
+ AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
177
+ IS NOT 'subagent'
178
+ )
179
+ ${
180
+ match === null
181
+ ? sql`
182
+ SELECT
183
+ messages.rowid AS "messageRowid",
184
+ messages.message_id AS "messageId",
185
+ messages.thread_id AS "threadId",
186
+ eligible.project_id AS "projectId",
187
+ messages.role AS source,
188
+ json_extract(messages.payload_json, '$.text') AS text,
189
+ messages.created_at AS "messageCreatedAt"
190
+ FROM orchestration_v2_projection_messages AS messages
191
+ INNER JOIN eligible ON eligible.thread_id = messages.thread_id
192
+ WHERE ${indexedMessageCondition(sql)}
193
+ -- A scan reads every message it passes, so it stops at the newest ones.
194
+ AND messages.rowid > (
195
+ SELECT coalesce(max(rowid), 0) FROM orchestration_v2_projection_messages
196
+ ) - ${MESSAGE_SCAN_LIMIT}
197
+ `
198
+ : sql`
199
+ SELECT
200
+ orchestration_v2_message_search.rowid AS "messageRowid",
201
+ messages.message_id AS "messageId",
202
+ messages.thread_id AS "threadId",
203
+ eligible.project_id AS "projectId",
204
+ messages.role AS source,
205
+ json_extract(messages.payload_json, '$.text') AS text,
206
+ messages.created_at AS "messageCreatedAt"
207
+ FROM orchestration_v2_message_search
208
+ INNER JOIN orchestration_v2_projection_messages AS messages
209
+ ON messages.rowid = orchestration_v2_message_search.rowid
210
+ INNER JOIN eligible ON eligible.thread_id = messages.thread_id
211
+ WHERE orchestration_v2_message_search MATCH ${match}
212
+ AND orchestration_v2_message_search.rowid >= coalesce((
213
+ SELECT rowid FROM orchestration_v2_message_search
214
+ WHERE orchestration_v2_message_search MATCH ${match}
215
+ ORDER BY rowid DESC
216
+ LIMIT 1 OFFSET ${MESSAGE_CANDIDATE_LIMIT - 1}
217
+ ), 0)
218
+ `
219
+ }
220
+ -- Answers to an agent's question show inside its question card, where
221
+ -- neither find nor a jump can reach them.
222
+ AND messages.message_id NOT LIKE 'async-answer:%'
223
+ AND NOT EXISTS (
224
+ SELECT 1 FROM json_each(${substrings}) AS token
225
+ WHERE instr(lower(json_extract(messages.payload_json, '$.text')), token.value) = 0
226
+ )
227
+ -- The index's own rowid, so FTS5 returns hits newest first and stops at
228
+ -- the limit; ordering by the messages table's rowid sorts every hit.
229
+ ORDER BY "messageRowid" DESC
230
+ LIMIT ${MESSAGE_HIT_LIMIT}
231
+ `;
232
+
233
+const TitleCandidateRow = Schema.Struct({
234
+ thread: Schema.fromJsonString(OrchestrationV2AppThreadJson),
235
+ projectTitle: Schema.String,
236
+ latestUserMessageAt: Schema.NullOr(IsoDateTime),
237
+});
238
+
239
+export interface ThreadSearchHit {
240
+ readonly threadId: ThreadId;
241
+ readonly projectId: ProjectId;
242
+ readonly title: string;
243
+ readonly source: "title" | OrchestrationThreadSearchSource;
244
+ readonly snippet?: string;
245
+ readonly messageCreatedAt?: string | null;
246
}
247
248
export class ThreadSearch extends Context.Service<
249
ThreadSearch,
250
{
251
+ /** Message text matches, for clients that rank their own thread list. */
252
readonly search: (
253
input: OrchestrationSearchThreadsInput,
254
) => Effect.Effect<OrchestrationSearchThreadsResult, ThreadSearchError>;
255
+ /**
256
+ * Title, branch, pull request, and project matches ranked as the command
257
+ * palette ranks them, then message matches for the remaining threads.
258
+ */
259
+ readonly searchThreads: (
260
+ input: OrchestrationSearchThreadsInput & { readonly projectId?: ProjectId | undefined },
261
+ ) => Effect.Effect<{ readonly matches: ReadonlyArray<ThreadSearchHit> }, ThreadSearchError>;
262
}
263
>()("t3/orchestration-v2/ThreadSearch") {}
264
@@ -75,93 +269,223 @@ export const make = Effect.gen(function* () {
269
const searchRows = SqlSchema.findAll({
270
Request: SearchRequest,
271
Result: SearchRow,
78
- execute: ({ pattern, limit }) => sql`
79
- WITH candidate AS (
80
- SELECT
81
- threads.thread_id,
82
- threads.project_id,
83
- messages.role,
84
- json_extract(messages.payload_json, '$.text') AS match_text,
85
- messages.created_at AS message_created_at,
86
- messages.message_id,
87
- threads.updated_at AS thread_updated_at
88
- FROM orchestration_v2_projection_messages AS messages
89
- INNER JOIN orchestration_v2_projection_threads AS threads
90
- ON threads.thread_id = messages.thread_id
91
- INNER JOIN projection_projects AS projects
92
- ON projects.project_id = threads.project_id
93
- WHERE threads.deleted_at IS NULL
94
- AND threads.archived_at IS NULL
95
- AND projects.deleted_at IS NULL
96
- AND messages.streaming = 0
97
- AND messages.role IN ('user', 'assistant')
98
- AND json_extract(messages.payload_json, '$.text') LIKE ${pattern} ESCAPE '!'
99
- ),
100
- ranked AS (
101
- SELECT
102
- thread_id,
103
- project_id,
104
- role AS source,
105
- match_text,
106
- message_created_at,
107
- CASE role WHEN 'user' THEN 0 ELSE 1 END AS match_rank,
108
- thread_updated_at,
109
- ROW_NUMBER() OVER (
110
- PARTITION BY thread_id
111
- ORDER BY
112
- CASE role WHEN 'user' THEN 0 ELSE 1 END ASC,
113
- message_created_at DESC,
114
- message_id ASC
115
- ) AS thread_match_rank
116
- FROM candidate
117
- )
272
+ execute: (request) => messageHitsQuery(sql, request),
273
+ });
274
+
275
+ const threadOpens = SqlSchema.findAll({
276
+ Request: Schema.Struct({ threadIds: TokenList }),
277
+ Result: ThreadOpensRow,
278
+ execute: ({ threadIds }) => sql`
279
+ SELECT
280
+ threads.thread_id AS "threadId",
281
+ json_extract(threads.payload_json, '$.opens') AS opens,
282
+ ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
283
+ FROM orchestration_v2_projection_threads AS threads
284
+ WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds}))
285
+ `,
286
+ });
287
+
288
+ const titleCandidates = SqlSchema.findAll({
289
+ Request: Schema.Struct({ projectId: Schema.NullOr(ProjectId) }),
290
+ Result: TitleCandidateRow,
291
+ execute: ({ projectId }) => sql`
292
SELECT
119
- thread_id AS "threadId",
120
- project_id AS "projectId",
121
- source,
122
- match_text AS "matchText",
123
- message_created_at AS "messageCreatedAt"
124
- FROM ranked
125
- WHERE thread_match_rank = 1
126
- ORDER BY match_rank ASC, thread_updated_at DESC, thread_id ASC
127
- LIMIT ${limit}
293
+ threads.payload_json AS thread,
294
+ projects.title AS "projectTitle",
295
+ ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
296
+ FROM orchestration_v2_projection_threads AS threads
297
+ INNER JOIN projection_projects AS projects
298
+ ON projects.project_id = threads.project_id
299
+ WHERE threads.deleted_at IS NULL
300
+ AND threads.archived_at IS NULL
301
+ AND projects.deleted_at IS NULL
302
+ AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
303
+ IS NOT 'subagent'
304
+ AND (${projectId} IS NULL OR threads.project_id = ${projectId})
305
`,
306
});
307
131
- const search: ThreadSearch["Service"]["search"] = Effect.fn("ThreadSearch.search")(
132
- function* (input) {
133
- // The scan reads every message, so run it on the reader worker rather
134
- // than the event loop.
135
- const rows = yield* sql
136
- .withTransaction(
137
- searchRows({
138
- pattern: `%${escapeLikePattern(input.query)}%`,
139
- limit: input.limit ?? 50,
308
+ const read = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
309
+ sql.withTransaction(effect).pipe(
310
+ NodeSqliteClient.readOnly,
311
+ Effect.mapError(
312
+ (cause) =>
313
+ new ThreadSearchError({
314
+ operation: Schema.isSchemaError(cause) ? "decode" : "query",
315
+ cause,
316
}),
141
- )
142
- .pipe(
143
- NodeSqliteClient.readOnly,
144
- Effect.mapError(
145
- (cause) =>
146
- new ThreadSearchError({
147
- operation: Schema.isSchemaError(cause) ? "decode" : "query",
148
- cause,
149
- }),
150
- ),
151
- );
152
- return {
153
- matches: rows.map((row) => ({
154
- threadId: row.threadId,
155
- projectId: row.projectId,
156
- source: row.source,
157
- snippet: buildSearchSnippet(row.matchText, input.query),
158
- messageCreatedAt: row.messageCreatedAt,
159
- })),
160
- };
317
+ ),
318
+ );
319
+
320
+ // A project scope applies before ranking, so other projects' stronger hits
321
+ // cannot use up the limit.
322
+ const searchMessages = Effect.fn("ThreadSearch.search")(function* (
323
+ input: OrchestrationSearchThreadsInput & {
324
+ readonly projectId: ProjectId | null;
325
+ /** Threads the caller already lists, which must not use up the limit. */
326
+ readonly excludedThreadIds?: ReadonlySet<ThreadId>;
327
+ /** Off for an agent's search, which has no use for the user's picks. */
328
+ readonly picks?: boolean;
329
},
162
- );
330
+ ) {
331
+ // One message per thread: the best word match, then what the user wrote,
332
+ // since that is what they remember asking, then the newest by when it was
333
+ // written. Row order is not age: imported histories arrive in one batch.
334
+ // Text relevance (bm25) would cost a pass over every hit in history.
335
+ type Hit = {
336
+ readonly row: typeof SearchRow.Type;
337
+ /** The message as it reads, links as their text. */
338
+ readonly text: string;
339
+ readonly quality: number;
340
+ readonly offset: number;
341
+ };
342
+ const newer = (left: Hit, right: Hit) =>
343
+ (right.row.messageCreatedAt ?? "").localeCompare(left.row.messageCreatedAt ?? "");
344
+ const compareHits = (left: Hit, right: Hit) =>
345
+ right.quality - left.quality ||
346
+ Number(left.row.source !== "user") - Number(right.row.source !== "user") ||
347
+ newer(left, right);
348
+ const rows = yield* read(
349
+ Effect.gen(function* () {
350
+ const index = yield* sql`
351
+ SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
352
+ `;
353
+ const messageSearch = buildMessageSearch(input.query, index.length > 0);
354
+ return messageSearch === null
355
+ ? []
356
+ : yield* searchRows({
357
+ ...messageSearch,
358
+ projectId: input.projectId,
359
+ excludedThreadIds: [...(input.excludedThreadIds ?? [])],
360
+ });
361
+ }),
362
+ );
363
+ const best = new Map<ThreadId, Hit>();
364
+ // Matching messages per thread at its best quality: a thread that keeps
365
+ // using the word ranks above a passing mention, and weaker hits ("Trust"
366
+ // for "rust") never add to a whole word's count.
367
+ const hitCounts = new Map<ThreadId, number>();
368
+ const hitCount = (threadId: ThreadId) => hitCounts.get(threadId) ?? 1;
369
+ const matchMessage = messageMatcher(input.query);
370
+ for (const row of rows) {
371
+ const text = row.text.replace(MARKDOWN_LINK, "$1");
372
+ const match = matchMessage(text);
373
+ if (match === null) continue;
374
+ const hit = { row, text, ...match };
375
+ const current = best.get(row.threadId);
376
+ if (current === undefined || hit.quality > current.quality) {
377
+ hitCounts.set(row.threadId, 1);
378
+ } else if (hit.quality === current.quality) {
379
+ hitCounts.set(row.threadId, hitCount(row.threadId) + 1);
380
+ }
381
+ if (current === undefined || compareHits(hit, current) < 0) best.set(row.threadId, hit);
382
+ }
383
+ // Ranked as clients rank them, with picks and use, before the limit cuts:
384
+ // a thread picked for this query must come back even when it only
385
+ // matches in a few old messages.
386
+ const opens = best.size === 0 ? [] : yield* read(threadOpens({ threadIds: [...best.keys()] }));
387
+ const subjectById = new Map(
388
+ opens.map((row) => [
389
+ row.threadId,
390
+ {
391
+ title: "",
392
+ activityAt: row.latestUserMessageAt === null ? null : Date.parse(row.latestUserMessageAt),
393
+ opens: Option.getOrNull(decodeThreadOpens(row.opens)),
394
+ },
395
+ ]),
396
+ );
397
+ const now = DateTime.toEpochMillis(yield* DateTime.now);
398
+ const ranked = rankMessageMatches(
399
+ [...best.values()].map((hit) => ({
400
+ ...hit,
401
+ hits: hitCount(hit.row.threadId),
402
+ messageCreatedAt: hit.row.messageCreatedAt,
403
+ })),
404
+ (hit) => subjectById.get(hit.row.threadId),
405
+ foldSearchQuery(input.query),
406
+ now,
407
+ { picks: input.picks ?? true },
408
+ );
409
+ return {
410
+ matches: ranked.slice(0, input.limit ?? 50).map(({ row, text, quality, offset }) => ({
411
+ hits: hitCount(row.threadId),
412
+ threadId: row.threadId,
413
+ messageId: row.messageId,
414
+ projectId: row.projectId,
415
+ source: row.source,
416
+ snippet: buildSearchSnippet(text, offset),
417
+ messageCreatedAt: row.messageCreatedAt,
418
+ quality,
419
+ })),
420
+ };
421
+ });
422
+
423
+ const search: ThreadSearch["Service"]["search"] = (input) =>
424
+ searchMessages({ ...input, projectId: null });
425
+
426
+ const searchThreads: ThreadSearch["Service"]["searchThreads"] = Effect.fn(
427
+ "ThreadSearch.searchThreads",
428
+ )(function* (input) {
429
+ const limit = input.limit ?? 50;
430
+ const normalizedQuery = foldSearchQuery(input.query);
431
+ const now = DateTime.toEpochMillis(yield* DateTime.now);
432
+ // Agents call this rarely, and a project has hundreds of threads, not
433
+ // millions, so ranking every active thread in memory stays cheap.
434
+ const candidates = yield* read(titleCandidates({ projectId: input.projectId ?? null }));
435
+ const subjectById = new Map(
436
+ candidates.map((row): [ThreadId, ThreadSearchSubject] => [
437
+ row.thread.id,
438
+ {
439
+ id: row.thread.id,
440
+ title: row.thread.title,
441
+ branch: row.thread.branch,
442
+ projectTitle: row.projectTitle,
443
+ pullRequests: threadSearchPullRequests(row.thread),
444
+ // Like the clients: what the user last wrote, else when the thread began.
445
+ activityAt: Date.parse(
446
+ row.latestUserMessageAt ?? DateTime.formatIso(row.thread.createdAt),
447
+ ),
448
+ opens: row.thread.opens ?? null,
449
+ },
450
+ ]),
451
+ );
452
+ const titleHits: ThreadSearchHit[] = rankSearchItems(candidates, (row, options) =>
453
+ // An agent's search has no use for the user's palette picks.
454
+ scoreThreadSearch(normalizedQuery, subjectById.get(row.thread.id)!, now, {
455
+ ...options,
456
+ picks: false,
457
+ }),
458
+ )
459
+ .slice(0, limit)
460
+ .map(({ item }) => ({
461
+ threadId: item.thread.id,
462
+ projectId: item.thread.projectId,
463
+ title: item.thread.title,
464
+ source: "title",
465
+ }));
466
+ const shown = new Set(titleHits.map((hit) => hit.threadId));
467
+ const { matches } = yield* searchMessages({
468
+ query: input.query,
469
+ limit: 50,
470
+ projectId: input.projectId ?? null,
471
+ excludedThreadIds: shown,
472
+ picks: false,
473
+ });
474
+ const messageHits = matches
475
+ .filter((match) => subjectById.has(match.threadId))
476
+ .map(({ quality: _quality, hits: _hits, messageId: _messageId, ...match }) => ({
477
+ ...match,
478
+ title: subjectById.get(match.threadId)!.title,
479
+ }));
480
+ // Titles come first, but a fifth of the slots stay for message matches,
481
+ // as the palette keeps its "In messages" section.
482
+ const messageSlots = Math.min(messageHits.length, Math.floor(limit / 5));
483
+ return {
484
+ matches: [...titleHits.slice(0, limit - messageSlots), ...messageHits].slice(0, limit),
485
+ };
486
+ });
487
164
- return ThreadSearch.of({ search });
488
+ return ThreadSearch.of({ search, searchThreads });
489
});
490
491
export const layer = Layer.effect(ThreadSearch, make);
apps/server/src/orchestration-v2/messageSearchIndex.ts
new
+68
@@ -0,0 +1,68 @@
1
+import * as Effect from "effect/Effect";
2
+import type * as SqlClient from "effect/sql/SqlClient";
3
+
4
+/**
5
+ * The messages search indexes: finished, and either written by the user or
6
+ * answered by an agent. User-role notices that agents or the system wrote
7
+ * stay out. Subagent threads stay out too: search never shows them, and ACP
8
+ * subagents rewrite their whole finished answer on every streamed chunk.
9
+ * Migration 69's triggers, its backfill, the rebuild, and the scan all use
10
+ * it; `row` names the message row (a table alias, or `new` in a trigger).
11
+ */
12
+export const indexedMessageCondition = (sql: SqlClient.SqlClient, row = "messages") =>
13
+ sql.literal(`
14
+ ${row}.streaming = 0
15
+ AND (
16
+ ${row}.role = 'assistant'
17
+ OR (
18
+ ${row}.role = 'user'
19
+ AND COALESCE(json_extract(${row}.payload_json, '$.createdBy'), 'user') = 'user'
20
+ )
21
+ )
22
+ AND NOT EXISTS (
23
+ SELECT 1 FROM orchestration_v2_projection_threads AS subagent_threads
24
+ WHERE subagent_threads.thread_id = ${row}.thread_id
25
+ AND json_extract(subagent_threads.payload_json, '$.lineage.relationshipToParent') = 'subagent'
26
+ )
27
+`);
28
+
29
+/**
30
+ * What the index stores for a message: its text with curly apostrophes
31
+ * straight, as search folds a query, since iOS keyboards type "’" and others
32
+ * type "'". Migration 69's triggers use it too. `payload` is the message's
33
+ * JSON column.
34
+ */
35
+export const indexedMessageText = (sql: SqlClient.SqlClient, payload: string) =>
36
+ sql.literal(`replace(replace(json_extract(${payload}, '$.text'), '’', ''''), '‘', '''')`);
37
+
38
+/**
39
+ * Refills the search index from the messages table. The index is keyed by
40
+ * message rowid, so anything that may renumber or copy rows (VACUUM, a dev
41
+ * database copy) rebuilds it instead of trusting it. Databases from before
42
+ * migration 69, or on an SQLite without FTS5 trigrams, have no index.
43
+ */
44
+export const rebuildMessageSearch = Effect.fn("MessageSearchIndex.rebuild")(function* (
45
+ sql: SqlClient.SqlClient,
46
+) {
47
+ const index = yield* sql`
48
+ SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
49
+ `;
50
+ if (index.length === 0) return;
51
+ // One transaction: an interrupt between clear and refill would leave an
52
+ // empty index that nothing repairs, since search only checks the table exists.
53
+ yield* sql.withTransaction(
54
+ Effect.gen(function* () {
55
+ yield* sql`
56
+ INSERT INTO orchestration_v2_message_search (orchestration_v2_message_search)
57
+ VALUES ('delete-all')
58
+ `;
59
+ yield* sql`
60
+ INSERT INTO orchestration_v2_message_search (rowid, text)
61
+ SELECT messages.rowid, ${indexedMessageText(sql, "messages.payload_json")}
62
+ FROM orchestration_v2_projection_messages AS messages
63
+ WHERE ${indexedMessageCondition(sql)}
64
+ AND json_extract(messages.payload_json, '$.text') IS NOT NULL
65
+ `;
66
+ }),
67
+ );
68
+});
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+70
@@ -5543,6 +5543,76 @@ it.layer(layerSharedApplicationDataPlaneTest)("visited projection", (it) => {
5543
);
5544
});
5545
5546
+it.layer(Layer.fresh(layerSharedApplicationDataPlaneTest))("thread opens", (it) => {
5547
+ it.effect(
5548
+ "counts opens on the server clock, merges quick reopens, and keeps picked queries",
5549
+ () =>
5550
+ Effect.gen(function* () {
5551
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
5552
+ const threadId = ThreadId.make("runtime-layer-opened-thread");
5553
+ yield* orchestrator.dispatch({
5554
+ type: "thread.create",
5555
+ createdBy: "user",
5556
+ creationSource: "web",
5557
+ commandId: CommandId.make("runtime-layer-opened-thread-create"),
5558
+ threadId,
5559
+ projectId: ProjectId.make("runtime-layer-opened-project"),
5560
+ title: "Opened thread",
5561
+ modelSelection,
5562
+ runtimeMode: "full-access",
5563
+ interactionMode: "default",
5564
+ branch: null,
5565
+ worktreePath: null,
5566
+ });
5567
+ let visits = 0;
5568
+ const visit = (input: { readonly opened?: boolean; readonly searchQuery?: string }) =>
5569
+ orchestrator.dispatch({
5570
+ type: "thread.visit",
5571
+ commandId: CommandId.make(`runtime-layer-opened-visit-${++visits}`),
5572
+ threadId,
5573
+ // A client clock far in the past must not move the open time.
5574
+ visitedAt: "2000-01-01T00:00:00.000Z",
5575
+ ...input,
5576
+ });
5577
+ const opens = Effect.map(
5578
+ orchestrator.getShellSnapshot(),
5579
+ (shell) => shell.threads.find((thread) => thread.id === threadId)?.opens ?? null,
5580
+ );
5581
+ const start = DateTime.toEpochMillis(yield* DateTime.now);
5582
+
5583
+ yield* visit({ opened: true, searchQuery: " Upl " });
5584
+ assert.deepEqual(yield* opens, {
5585
+ openedAt: start,
5586
+ score: 1,
5587
+ picks: [{ query: "upl", at: start }],
5588
+ });
5589
+
5590
+ yield* TestClock.adjust("1 minute");
5591
+ yield* visit({ opened: true, searchQuery: "Uploadthing docs" });
5592
+ assert.deepEqual(yield* opens, {
5593
+ openedAt: start,
5594
+ score: 1,
5595
+ picks: [
5596
+ { query: "uploadthing docs", at: start + 60_000 },
5597
+ { query: "upl", at: start },
5598
+ ],
5599
+ });
5600
+
5601
+ yield* TestClock.adjust("14 days");
5602
+ yield* visit({});
5603
+ yield* visit({ opened: true });
5604
+ const later = yield* opens;
5605
+ assert.closeTo(later!.score, 1 + 2 ** (-(14 * 24 * 60 + 1) / (14 * 24 * 60)), 1e-9);
5606
+ assert.equal(later!.openedAt, DateTime.toEpochMillis(yield* DateTime.now));
5607
+ // Opening without a query keeps each pick and its time.
5608
+ assert.deepEqual(later!.picks, [
5609
+ { query: "uploadthing docs", at: start + 60_000 },
5610
+ { query: "upl", at: start },
5611
+ ]);
5612
+ }),
5613
+ );
5614
+});
5615
+
5616
it.layer(Layer.fresh(layerSharedApplicationDataPlaneTest))("compact PR events", (it) => {
5617
it.effect("persists only the changed PR link and replays it without losing other links", () =>
5618
Effect.gen(function* () {
apps/server/src/persistence/DatabaseMaintenance.test.ts
+24
@@ -98,6 +98,20 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
98
yield* sql`CREATE TABLE discarded_data (value BLOB)`;
99
yield* sql`INSERT INTO discarded_data VALUES (zeroblob(4194304))`;
100
yield* sql`DROP TABLE discarded_data`;
101
+ yield* sql`
102
+ INSERT INTO orchestration_v2_projection_messages (
103
+ message_id, thread_id, run_id, node_id, role, streaming, created_at, updated_at, payload_json
104
+ )
105
+ VALUES (
106
+ 'message-1', 'thread-1', NULL, NULL, 'user', 0,
107
+ '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z', '{"text":"needle"}'
108
+ )
109
+ `;
110
+ // An index that drifted from its rows, as a renumbering VACUUM would leave it.
111
+ yield* sql`
112
+ INSERT INTO orchestration_v2_message_search (orchestration_v2_message_search)
113
+ VALUES ('delete-all')
114
+ `;
115
yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
116
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
117
@@ -118,6 +132,16 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
132
const sql = yield* SqlClient.SqlClient;
133
assert.deepEqual(yield* sql`PRAGMA auto_vacuum`, [{ auto_vacuum: 2 }]);
134
assert.deepEqual(yield* sql`SELECT value FROM retained_data`, [{ value: "keep" }]);
135
+ assert.deepEqual(
136
+ yield* sql`
137
+ SELECT messages.message_id AS "messageId"
138
+ FROM orchestration_v2_message_search AS search
139
+ INNER JOIN orchestration_v2_projection_messages AS messages
140
+ ON messages.rowid = search.rowid
141
+ WHERE orchestration_v2_message_search MATCH '"needle"'
142
+ `,
143
+ [{ messageId: "message-1" }],
144
+ );
145
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath, readonly: true })));
146
}).pipe(Effect.scoped),
147
);
apps/server/src/persistence/DatabaseMaintenance.ts
+2
@@ -11,6 +11,7 @@ import { isSqlError } from "effect/sql/SqlError";
11
import * as EventStore from "../orchestration-v2/EventStore.ts";
12
import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
13
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
14
+import { rebuildMessageSearch } from "../orchestration-v2/messageSearchIndex.ts";
15
16
export class DatabaseMissingError extends Schema.TaggedError<DatabaseMissingError>()(
17
"DatabaseMissingError",
@@ -194,6 +195,7 @@ const make = Effect.gen(function* () {
195
// database to incremental auto_vacuum; the server reclaims online after.
196
yield* sql`PRAGMA auto_vacuum = INCREMENTAL`;
197
yield* sql`VACUUM`;
198
+ yield* rebuildMessageSearch(sql);
199
yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
200
return summary;
201
}).pipe(
apps/server/src/persistence/Migrations.ts
+2
@@ -71,6 +71,7 @@ import Migration0065 from "./Migrations/065_CodexUsageNativeTurnIndex.ts";
71
import Migration0066 from "./Migrations/066_RepairClientSettlementTimestamps.ts";
72
import Migration0067 from "./Migrations/067_WebhookDedupe.ts";
73
import Migration0068 from "./Migrations/068_ShellStopRequestIndex.ts";
74
+import Migration0069 from "./Migrations/069_ThreadMessageSearch.ts";
75
76
const migrationEntries = [
77
[1, "OrchestrationEvents", Migration0001],
@@ -142,6 +143,7 @@ const migrationEntries = [
143
[66, "RepairClientSettlementTimestamps", Migration0066],
144
[67, "WebhookDedupe", Migration0067],
145
[68, "ShellStopRequestIndex", Migration0068],
146
+ [69, "ThreadMessageSearch", Migration0069],
147
] as const;
148
149
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
apps/server/src/persistence/Migrations/069_ThreadMessageSearch.test.ts
new
+55
@@ -0,0 +1,55 @@
1
+import { assert, it } from "@effect/vitest";
2
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3
+import * as Effect from "effect/Effect";
4
+import * as SqlClient from "effect/sql/SqlClient";
5
+
6
+import { runMigrations } from "../Migrations.ts";
7
+
8
+const layer = it.layer(NodeSqliteClient.layer({ filename: ":memory:" }));
9
+
10
+layer("069_ThreadMessageSearch", (it) => {
11
+ it.effect("backfills what users wrote and agents answered, then follows deletes", () =>
12
+ Effect.gen(function* () {
13
+ const sql = yield* SqlClient.SqlClient;
14
+ yield* runMigrations({ toMigrationInclusive: 68 });
15
+ const insert = (
16
+ id: string,
17
+ role: string,
18
+ streaming: number,
19
+ text: string,
20
+ createdBy: string | undefined = role === "user" ? "user" : "agent",
21
+ ) => sql`
22
+ INSERT INTO orchestration_v2_projection_messages (
23
+ message_id, thread_id, run_id, node_id, role, streaming, created_at, updated_at, payload_json
24
+ )
25
+ VALUES (
26
+ ${id}, 'thread-1', NULL, NULL, ${role}, ${streaming},
27
+ '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z', ${JSON.stringify({ text, createdBy })}
28
+ )
29
+ `;
30
+ yield* insert("user", "user", 0, "needle from the user");
31
+ yield* insert("assistant", "assistant", 0, "needle from the agent");
32
+ yield* insert("streaming", "assistant", 1, "needle still streaming");
33
+ yield* insert("system", "system", 0, "needle in a system prompt");
34
+ yield* insert("notice", "user", 0, "needle in a pull request update", "agent");
35
+ // Older rows carry no author; they were the user's.
36
+ yield* insert("legacy", "user", 0, "needle from before authors", undefined);
37
+
38
+ yield* runMigrations();
39
+
40
+ const indexed = () =>
41
+ sql<{ readonly messageId: string }>`
42
+ SELECT messages.message_id AS "messageId"
43
+ FROM orchestration_v2_message_search AS search
44
+ INNER JOIN orchestration_v2_projection_messages AS messages
45
+ ON messages.rowid = search.rowid
46
+ WHERE orchestration_v2_message_search MATCH '"needle"'
47
+ ORDER BY messages.message_id
48
+ `.pipe(Effect.map((rows) => rows.map((row) => row.messageId)));
49
+ assert.deepEqual(yield* indexed(), ["assistant", "legacy", "user"]);
50
+
51
+ yield* sql`DELETE FROM orchestration_v2_projection_messages WHERE message_id = 'user'`;
52
+ assert.deepEqual(yield* indexed(), ["assistant", "legacy"]);
53
+ }),
54
+ );
55
+});
apps/server/src/persistence/Migrations/069_ThreadMessageSearch.ts
new
+106
@@ -0,0 +1,106 @@
1
+import * as Effect from "effect/Effect";
2
+import * as Predicate from "effect/Predicate";
3
+import * as SqlClient from "effect/sql/SqlClient";
4
+
5
+import {
6
+ indexedMessageCondition,
7
+ indexedMessageText,
8
+} from "../../orchestration-v2/messageSearchIndex.ts";
9
+
10
+/**
11
+ * Full-text index for thread message search. The trigram tokenizer matches any
12
+ * substring of three or more characters, ignoring case and accents, so
13
+ * identifiers inside code still match, without the full-table scan a
14
+ * `LIKE '%q%'` needs.
15
+ *
16
+ * It holds what the user wrote and what agents answered. User-role messages
17
+ * that agents or the system wrote (pull request updates, task notices) would
18
+ * flood results and read as "You".
19
+ *
20
+ * The index is contentless and keyed by the message rowid: search reads the
21
+ * text back from the message row, so the text is not stored twice. `t3 doctor`
22
+ * rebuilds it after its VACUUM, since SQLite does not promise to keep rowids.
23
+ * Thread search scans the same messages when the index is missing.
24
+ *
25
+ * Triggers keep it in sync with every write to the messages table. Streaming
26
+ * messages are indexed once they finish, with apostrophes folded as search
27
+ * folds them.
28
+ */
29
+export default Effect.gen(function* () {
30
+ const sql = yield* SqlClient.SqlClient;
31
+
32
+ // Node and Electron bundle a SQLite with these options; a Node built against
33
+ // an older system SQLite may lack them. Search then scans messages instead
34
+ // of failing to start. Only SQLITE_ERROR ("no such module", "no such
35
+ // tokenizer", "unrecognized option") means that: a full disk or I/O error
36
+ // fails the migration, so the next start retries instead of skipping the
37
+ // index for good.
38
+ const created = yield* sql`
39
+ CREATE VIRTUAL TABLE orchestration_v2_message_search USING fts5(
40
+ text,
41
+ content = '',
42
+ contentless_delete = 1,
43
+ tokenize = 'trigram remove_diacritics 1'
44
+ )
45
+ `.pipe(
46
+ Effect.as(true),
47
+ Effect.catchIf(
48
+ (cause) =>
49
+ Predicate.hasProperty(cause.reason.cause, "errcode") && cause.reason.cause.errcode === 1,
50
+ (cause) =>
51
+ Effect.logWarning(
52
+ "Message search index unavailable; search will scan messages.",
53
+ cause,
54
+ ).pipe(Effect.as(false)),
55
+ ),
56
+ );
57
+ if (!created) return;
58
+ yield* sql`
59
+ CREATE TRIGGER orchestration_v2_message_search_insert
60
+ AFTER INSERT ON orchestration_v2_projection_messages
61
+ WHEN ${indexedMessageCondition(sql, "new")}
62
+ BEGIN
63
+ INSERT INTO orchestration_v2_message_search (rowid, text)
64
+ SELECT new.rowid, ${indexedMessageText(sql, "new.payload_json")}
65
+ WHERE json_extract(new.payload_json, '$.text') IS NOT NULL;
66
+ END
67
+ `;
68
+ // Streaming deltas rewrite the row many times a second; skip them until the
69
+ // message settles. Upserts rewrite every column, so a finished message
70
+ // re-indexes only when what the index reads changed. Deleting a rowid the
71
+ // index never held is a no-op.
72
+ yield* sql`
73
+ CREATE TRIGGER orchestration_v2_message_search_update
74
+ AFTER UPDATE OF payload_json, streaming, role ON orchestration_v2_projection_messages
75
+ WHEN (old.streaming = 0 OR new.streaming = 0)
76
+ AND (
77
+ old.streaming IS NOT new.streaming
78
+ OR old.role IS NOT new.role
79
+ OR json_extract(old.payload_json, '$.text') IS NOT json_extract(new.payload_json, '$.text')
80
+ OR json_extract(old.payload_json, '$.createdBy')
81
+ IS NOT json_extract(new.payload_json, '$.createdBy')
82
+ )
83
+ BEGIN
84
+ DELETE FROM orchestration_v2_message_search WHERE rowid = old.rowid AND old.streaming = 0;
85
+ INSERT INTO orchestration_v2_message_search (rowid, text)
86
+ SELECT new.rowid, ${indexedMessageText(sql, "new.payload_json")}
87
+ WHERE ${indexedMessageCondition(sql, "new")}
88
+ AND json_extract(new.payload_json, '$.text') IS NOT NULL;
89
+ END
90
+ `;
91
+ yield* sql`
92
+ CREATE TRIGGER orchestration_v2_message_search_delete
93
+ AFTER DELETE ON orchestration_v2_projection_messages
94
+ WHEN old.streaming = 0
95
+ BEGIN
96
+ DELETE FROM orchestration_v2_message_search WHERE rowid = old.rowid;
97
+ END
98
+ `;
99
+ yield* sql`
100
+ INSERT INTO orchestration_v2_message_search (rowid, text)
101
+ SELECT messages.rowid, ${indexedMessageText(sql, "messages.payload_json")}
102
+ FROM orchestration_v2_projection_messages AS messages
103
+ WHERE ${indexedMessageCondition(sql)}
104
+ AND json_extract(messages.payload_json, '$.text') IS NOT NULL
105
+ `;
106
+});
apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+2
@@ -48,6 +48,7 @@ describe("V2 preview upgrade", () => {
48
[66, "RepairClientSettlementTimestamps"],
49
[67, "WebhookDedupe"],
50
[68, "ShellStopRequestIndex"],
51
+ [69, "ThreadMessageSearch"],
52
]);
53
assert.deepStrictEqual(yield* runMigrations(), []);
54
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -139,6 +140,7 @@ describe("V2 preview upgrade", () => {
140
[66, "RepairClientSettlementTimestamps"],
141
[67, "WebhookDedupe"],
142
[68, "ShellStopRequestIndex"],
143
+ [69, "ThreadMessageSearch"],
144
]);
145
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
146
);
apps/web/src/components/CommandPalette.logic.test.ts
+320
-56
@@ -112,6 +112,26 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
112
}
113
114
describe("buildThreadActionItems", () => {
115
+ it("keeps threads apart when two environments share a thread ID", async () => {
116
+ const local = makeThread();
117
+ const remote = makeThread({ environmentId: EnvironmentId.make("remote-copy") });
118
+ const runThread = vi.fn(async () => {});
119
+ const items = buildThreadActionItems({
120
+ threads: [local, remote],
121
+ activeThread: remote,
122
+ projectByKey: new Map([
123
+ [`${local.environmentId}:${local.projectId}`, { title: "Local project" }],
124
+ [`${remote.environmentId}:${remote.projectId}`, { title: "Remote project" }],
125
+ ]),
126
+ icon: null,
127
+ runThread,
128
+ });
129
+ expect(new Set(items.map((item) => item.value)).size).toBe(2);
130
+ const remoteItem = items.find((item) => item.description === "Remote project · Current thread");
131
+ await remoteItem?.run();
132
+ expect(runThread).toHaveBeenCalledWith(remote);
133
+ });
134
+
135
it("ranks thread title matches ahead of contextual project-name matches", () => {
136
const threadItems = buildThreadActionItems({
137
threads: [
@@ -127,8 +147,7 @@ describe("buildThreadActionItems", () => {
147
updatedAt: "2026-03-19T00:00:00.000Z",
148
}),
149
],
130
- projectTitleById: new Map([[PROJECT_ID, "Project"]]),
131
- sortOrder: "updated_at",
150
+ projectByKey: new Map([[`${LOCAL_ENVIRONMENT_ID}:${PROJECT_ID}`, { title: "Project" }]]),
151
icon: null,
152
runThread: async (_thread) => undefined,
153
});
@@ -144,57 +163,250 @@ describe("buildThreadActionItems", () => {
163
expect(groups).toHaveLength(1);
164
expect(groups[0]?.value).toBe("threads-search");
165
expect(groups[0]?.items.map((item) => item.value)).toEqual([
147
- "thread:thread-title-match",
148
- "thread:thread-context-match",
166
+ "thread:environment-local:thread-title-match",
167
+ "thread:environment-local:thread-context-match",
168
]);
169
});
170
152
- it("orders title matches by recent activity before older prefix matches", () => {
171
+ it("lists message matches last, once, without moving the title matches above them", () => {
172
const threads = [
154
- makeThread({
155
- id: ThreadId.make("old-prefix"),
156
- title: "Convex InvalidCursor in Convex threads query",
157
- createdAt: "2026-01-01T00:00:00.000Z",
158
- updatedAt: "2026-01-02T00:00:00.000Z",
159
- }),
160
- makeThread({
161
- id: ThreadId.make("recent-title"),
162
- title: "Disable Convex schema validation",
163
- createdAt: "2025-12-01T00:00:00.000Z",
164
- updatedAt: "2026-03-24T00:00:00.000Z",
165
- }),
166
- makeThread({
167
- id: ThreadId.make("recent-content"),
168
- title: "Fix schema validation",
169
- createdAt: "2026-03-25T00:00:00.000Z",
170
- updatedAt: "2026-03-25T00:00:00.000Z",
171
- }),
173
+ makeThread({ id: ThreadId.make("title"), title: "Disable Convex schema validation" }),
174
+ makeThread({ id: ThreadId.make("message"), title: "Fix schema validation" }),
175
];
176
const items = buildThreadActionItems({
177
threads,
175
- projectTitleById: new Map([[PROJECT_ID, "T3 Code"]]),
176
- sortOrder: "created_at",
178
+ projectByKey: new Map(),
179
icon: null,
178
- getContentMatch: (thread) =>
179
- thread.id === ThreadId.make("recent-content")
180
- ? { source: "user", snippet: "Please check Convex", query: "convex" }
181
- : undefined,
180
runThread: async () => undefined,
181
});
182
+ const filter = (threadMessageItems: typeof items) =>
183
+ filterCommandPaletteGroups({
184
+ activeGroups: [],
185
+ query: "convex",
186
+ isInSubmenu: false,
187
+ projectSearchItems: [],
188
+ threadSearchItems: items,
189
+ threadMessageItems,
190
+ }).map((group) => [group.label, group.items.map((item) => item.value)]);
191
+
192
+ const before = filter([]);
193
+ // The server matched both; the title match stays where it was.
194
+ const after = filter([items[0]!, items[1]!].toReversed());
195
+ expect(before).toEqual([["Threads", ["thread:environment-local:title"]]]);
196
+ expect(after).toEqual([
197
+ ["Threads", ["thread:environment-local:title"]],
198
+ ["In messages", ["thread:environment-local:message"]],
199
+ ]);
200
+ });
201
202
+ it("keeps an active thread first while its title is typed, above settings and actions", () => {
203
+ const now = Date.parse("2026-10-23T00:00:00.000Z");
204
+ const action = (value: string, title: string, searchTerms: string[] = [title]) => ({
205
+ kind: "action" as const,
206
+ value,
207
+ searchTerms,
208
+ title,
209
+ icon: null,
210
+ run: async () => undefined,
211
+ });
212
+ const threadSearchItems = buildThreadActionItems({
213
+ threads: [
214
+ makeThread({
215
+ title: "Compaction prompt timing and cache age",
216
+ latestUserMessageAt: "2026-10-11T00:00:00.000Z",
217
+ }),
218
+ ],
219
+ projectByKey: new Map(),
220
+ icon: null,
221
+ runThread: async () => undefined,
222
+ });
223
+ const firstGroup = (query: string) =>
224
+ filterCommandPaletteGroups({
225
+ activeGroups: [
226
+ { value: "actions", label: "Actions", items: [action("action:copy", "Copy thread ID")] },
227
+ ],
228
+ query,
229
+ isInSubmenu: false,
230
+ projectSearchItems: [],
231
+ settingsSearchItems: [
232
+ action("setting:compact", "Compact idle threads"),
233
+ action("setting:providers", "Providers", ["Providers", "compatibility"]),
234
+ ],
235
+ threadSearchItems,
236
+ now,
237
+ })[0]?.label;
238
+
239
+ for (const query of ["comp", "compa", "compac", "compact", "compacti", "compaction"]) {
240
+ expect(firstGroup(query), query).toBe("Threads");
241
+ }
242
+ });
243
+
244
+ it("orders groups by their best match, so a strong thread is not under a weak action", () => {
245
+ const action = (value: string, title: string) => ({
246
+ kind: "action" as const,
247
+ value,
248
+ searchTerms: [title],
249
+ title,
250
+ icon: null,
251
+ run: async () => undefined,
252
+ });
253
+ const threadSearchItems = buildThreadActionItems({
254
+ threads: [makeThread({ title: "Upgrade to pnpm 12" })],
255
+ projectByKey: new Map(),
256
+ icon: null,
257
+ runThread: async () => undefined,
258
+ });
259
+ const labels = (query: string) =>
260
+ filterCommandPaletteGroups({
261
+ activeGroups: [
262
+ { value: "actions", label: "Actions", items: [action("action:upload", "Upload file")] },
263
+ ],
264
+ query,
265
+ isInSubmenu: false,
266
+ projectSearchItems: [],
267
+ threadSearchItems,
268
+ }).map((group) => group.label);
269
+
270
+ expect(labels("upgrade")).toEqual(["Threads"]);
271
+ expect(labels("upl")).toEqual(["Actions"]);
272
+ // A short query still finds a command by a keyword it equals.
273
+ const prGroups = filterCommandPaletteGroups({
274
+ activeGroups: [
275
+ {
276
+ value: "actions",
277
+ label: "Actions",
278
+ items: [
279
+ {
280
+ kind: "action",
281
+ value: "action:open-prs",
282
+ searchTerms: ["Open pull requests", "pr", "prs", "review"],
283
+ title: "Open pull requests",
284
+ icon: null,
285
+ run: async () => undefined,
286
+ },
287
+ action("action:project", "Project settings"),
288
+ ],
289
+ },
290
+ ],
291
+ query: "pr",
292
+ isInSubmenu: false,
293
+ projectSearchItems: [],
294
+ threadSearchItems: [],
295
+ });
296
+ expect(prGroups.flatMap((group) => group.items.map((item) => item.value))).toEqual([
297
+ "action:open-prs",
298
+ "action:project",
299
+ ]);
300
+ expect(labels("up")).toEqual(["Actions", "Threads"]);
301
+ expect(labels("pnpm up")).toEqual(["Threads"]);
302
+ });
303
+
304
+ it("runs the command for its whole name over a thread with that title, and lists the open thread last", () => {
305
+ const threads = [
306
+ makeThread({ id: ThreadId.make("thread-new"), title: "New thread" }),
307
+ makeThread({ id: ThreadId.make("thread-open"), title: "New thread layout" }),
308
+ makeThread({ id: ThreadId.make("thread-other"), title: "New thread button" }),
309
+ ];
310
+ const threadSearchItems = buildThreadActionItems({
311
+ threads,
312
+ activeThread: threads[1]!,
313
+ projectByKey: new Map(),
314
+ icon: null,
315
+ runThread: async () => undefined,
316
+ });
317
const groups = filterCommandPaletteGroups({
186
- activeGroups: [],
187
- query: "convex",
318
+ activeGroups: [
319
+ {
320
+ value: "actions",
321
+ label: "Actions",
322
+ items: [
323
+ {
324
+ kind: "action",
325
+ value: "action:new-thread",
326
+ searchTerms: ["New thread in t3code"],
327
+ title: "New thread in t3code",
328
+ icon: null,
329
+ run: async () => undefined,
330
+ },
331
+ ],
332
+ },
333
+ ],
334
+ query: "new thread",
335
isInSubmenu: false,
336
projectSearchItems: [],
190
- threadSearchItems: items,
337
+ threadSearchItems,
338
});
339
+ expect(groups.map((group) => group.label)).toEqual(["Actions", "Threads"]);
340
+ expect(groups[1]?.items.at(-1)?.title).toBe("New thread layout");
341
+ });
342
193
- expect(groups[0]?.items.map((item) => item.value)).toEqual([
194
- "thread:recent-title",
195
- "thread:old-prefix",
196
- "thread:recent-content",
197
- ]);
343
+ it("lists a project above threads that only hold its name when the name is typed", () => {
344
+ const threadSearchItems = buildThreadActionItems({
345
+ threads: [makeThread({ title: "Lakebed performance gains" })],
346
+ projectByKey: new Map(),
347
+ icon: null,
348
+ runThread: async () => undefined,
349
+ });
350
+ const projectSearchItems = [
351
+ {
352
+ kind: "action" as const,
353
+ value: "project:lakebed",
354
+ searchTerms: ["Lakebed", "/code/lakebed"],
355
+ title: "Lakebed",
356
+ icon: null,
357
+ run: async () => undefined,
358
+ },
359
+ ];
360
+ const labels = (query: string) =>
361
+ filterCommandPaletteGroups({
362
+ activeGroups: [],
363
+ query,
364
+ isInSubmenu: false,
365
+ projectSearchItems,
366
+ threadSearchItems,
367
+ }).map((group) => group.label);
368
+ expect(labels("lakebed")).toEqual(["Projects", "Threads"]);
369
+ expect(labels("lake")).toEqual(["Threads", "Projects"]);
370
+ });
371
+
372
+ it("keeps a command first over a thread in daily use that matches as well", () => {
373
+ const now = Date.parse("2026-10-23T00:00:00.000Z");
374
+ const threadSearchItems = buildThreadActionItems({
375
+ threads: [
376
+ makeThread({
377
+ title: "New onboarding flow",
378
+ latestUserMessageAt: "2026-10-22T00:00:00.000Z",
379
+ opens: { openedAt: Date.parse("2026-10-22T00:00:00.000Z"), score: 7, picks: [] },
380
+ }),
381
+ ],
382
+ projectByKey: new Map(),
383
+ icon: null,
384
+ runThread: async () => undefined,
385
+ });
386
+ const groups = filterCommandPaletteGroups({
387
+ activeGroups: [
388
+ {
389
+ value: "actions",
390
+ label: "Actions",
391
+ items: [
392
+ {
393
+ kind: "action",
394
+ value: "action:new-thread",
395
+ searchTerms: ["new thread", "chat"],
396
+ title: "New thread",
397
+ icon: null,
398
+ run: async () => undefined,
399
+ },
400
+ ],
401
+ },
402
+ ],
403
+ query: "new",
404
+ isInSubmenu: false,
405
+ projectSearchItems: [],
406
+ threadSearchItems,
407
+ now,
408
+ });
409
+ expect(groups.map((group) => group.label)).toEqual(["Actions", "Threads"]);
410
});
411
412
it("ranks an order-independent setting title match above a split context match", () => {
@@ -234,6 +446,59 @@ describe("buildThreadActionItems", () => {
446
]);
447
});
448
449
+ it("searches a styled command title by its plain text", () => {
450
+ const groups = filterCommandPaletteGroups({
451
+ activeGroups: [
452
+ {
453
+ value: "actions",
454
+ label: "Actions",
455
+ items: [
456
+ {
457
+ kind: "action",
458
+ value: "action:new-thread",
459
+ searchTerms: ["new thread", "chat"],
460
+ // Styled: not a string, so only `searchTitle` holds its words.
461
+ title: ["New thread in ", "t3code"],
462
+ searchTitle: "New thread in t3code",
463
+ icon: null,
464
+ run: async () => undefined,
465
+ },
466
+ ],
467
+ },
468
+ ],
469
+ query: "> new t3code",
470
+ isInSubmenu: false,
471
+ projectSearchItems: [],
472
+ threadSearchItems: [],
473
+ });
474
+ expect(groups.flatMap((group) => group.items.map((item) => item.value))).toEqual([
475
+ "action:new-thread",
476
+ ]);
477
+ });
478
+
479
+ it("forgives a typo in a setting name when nothing matches exactly", () => {
480
+ const groups = filterCommandPaletteGroups({
481
+ activeGroups: [],
482
+ query: "keybindngs",
483
+ isInSubmenu: false,
484
+ projectSearchItems: [],
485
+ threadSearchItems: [],
486
+ settingsSearchItems: [
487
+ {
488
+ kind: "action",
489
+ value: "setting:keybindings",
490
+ title: "Keybindings",
491
+ searchTerms: ["Keybindings", "General", "shortcuts"],
492
+ icon: null,
493
+ run: async () => undefined,
494
+ },
495
+ ],
496
+ });
497
+ expect(groups.flatMap((group) => group.items.map((item) => item.value))).toEqual([
498
+ "setting:keybindings",
499
+ ]);
500
+ });
501
+
502
it("normalizes case independently of the host locale", () => {
503
const toLocaleLowerCase = String.prototype.toLocaleLowerCase;
504
const localeLowerCase = vi
@@ -280,8 +545,7 @@ describe("buildThreadActionItems", () => {
545
});
546
const items = buildThreadActionItems({
547
threads: [idThread, titleThread],
283
- projectTitleById: new Map([[PROJECT_ID, "T3 Code"]]),
284
- sortOrder: "updated_at",
548
+ projectByKey: new Map([[`${LOCAL_ENVIRONMENT_ID}:${PROJECT_ID}`, { title: "T3 Code" }]]),
549
icon: null,
550
runThread: async (_thread) => undefined,
551
});
@@ -296,8 +560,8 @@ describe("buildThreadActionItems", () => {
560
});
561
562
expect(groups.flatMap((group) => group.items)).toEqual([
299
- expect.objectContaining({ value: `thread:${titleThread.id}` }),
300
- expect.objectContaining({ value: `thread:${idThread.id}` }),
563
+ expect.objectContaining({ value: `thread:${LOCAL_ENVIRONMENT_ID}:${titleThread.id}` }),
564
+ expect.objectContaining({ value: `thread:${LOCAL_ENVIRONMENT_ID}:${idThread.id}` }),
565
]);
566
});
567
@@ -325,13 +589,15 @@ describe("buildThreadActionItems", () => {
589
},
590
}),
591
],
328
- projectTitleById: new Map(),
329
- sortOrder: "updated_at",
592
+ projectByKey: new Map(),
593
icon: null,
594
runThread: async () => undefined,
595
});
596
334
- expect(items.map((item) => item.value).toSorted()).toEqual(["thread:fork", "thread:parent"]);
597
+ expect(items.map((item) => item.value).toSorted()).toEqual([
598
+ "thread:environment-local:fork",
599
+ "thread:environment-local:parent",
600
+ ]);
601
});
602
603
it("ranks word-start title matches above newer mid-word matches", () => {
@@ -354,8 +620,7 @@ describe("buildThreadActionItems", () => {
620
updatedAt: "2026-03-01T00:00:00.000Z",
621
}),
622
],
357
- projectTitleById: new Map(),
358
- sortOrder: "updated_at",
623
+ projectByKey: new Map(),
624
icon: null,
625
runThread: async () => undefined,
626
});
@@ -369,13 +634,13 @@ describe("buildThreadActionItems", () => {
634
});
635
636
expect(groups[0]?.items.map((item) => item.value)).toEqual([
372
- "thread:word-start",
373
- "thread:branch-word-start",
374
- "thread:mid-word",
637
+ "thread:environment-local:word-start",
638
+ "thread:environment-local:branch-word-start",
639
+ "thread:environment-local:mid-word",
640
]);
641
});
642
378
- it("breaks ties within a match tier by latest user message", () => {
643
+ it("breaks ties between equal matches by latest user message", () => {
644
const items = buildThreadActionItems({
645
threads: [
646
makeThread({
@@ -391,8 +656,7 @@ describe("buildThreadActionItems", () => {
656
latestUserMessageAt: "2026-03-10T00:00:00.000Z",
657
}),
658
],
394
- projectTitleById: new Map(),
395
- sortOrder: "updated_at",
659
+ projectByKey: new Map(),
660
icon: null,
661
runThread: async () => undefined,
662
});
@@ -403,11 +667,12 @@ describe("buildThreadActionItems", () => {
667
isInSubmenu: false,
668
projectSearchItems: [],
669
threadSearchItems: items,
670
+ now: Date.parse("2026-03-20T00:00:00.000Z"),
671
});
672
673
expect(groups[0]?.items.map((item) => item.value)).toEqual([
409
- "thread:word-fresh",
410
- "thread:prefix-stale",
674
+ "thread:environment-local:word-fresh",
675
+ "thread:environment-local:prefix-stale",
676
]);
677
});
678
});
@@ -457,8 +722,7 @@ it.each([
722
}),
723
makeThread({ id: ThreadId.make("unrelated"), title: "Other work" }),
724
],
460
- projectTitleById: new Map(),
461
- sortOrder: "updated_at",
725
+ projectByKey: new Map(),
726
icon: null,
727
runThread: async () => undefined,
728
});
apps/web/src/components/CommandPalette.logic.ts
+150
-124
@@ -1,4 +1,15 @@
1
-import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
1
+import {
2
+ foldSearchQuery,
3
+ PALETTE_SECONDARY_LIMIT,
4
+ PALETTE_THREAD_LIMIT,
5
+ rankSearchGroups,
6
+ scoreSearchTerms,
7
+ scoreThreadSearch,
8
+ type SearchMatchHint,
9
+ type SearchRange,
10
+ type ThreadSearchSubject,
11
+} from "@t3tools/shared/paletteSearch";
12
+import { threadSearchSubject } from "@t3tools/client-runtime/state/thread-search";
13
import type { CommandPaletteLinkedThreads } from "../commandPaletteBus";
14
import {
15
addProjectRemoteSourceLabel,
@@ -17,12 +28,7 @@ import {
28
THREAD_JUMP_KEYBINDING_COMMANDS,
29
} from "@t3tools/contracts";
30
import { filterFilesystemBrowseEntries } from "@t3tools/client-runtime/state/filesystem";
20
-import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
21
-import * as Arr from "effect/Array";
22
-import * as Result from "effect/Result";
31
import { type ReactNode } from "react";
24
-import { getThreadSortTimestamp, sortThreads } from "../lib/threadSort";
25
-import { normalizeSearchText } from "../lib/utils";
32
import { formatRelativeTimeLabel } from "../timestampFormat";
33
import { type Project, type SidebarThreadSummary, type Thread } from "../types";
34
import { isSidebarSubagentThread } from "./Sidebar.logic";
@@ -155,10 +161,17 @@ export interface CommandPaletteItem {
161
readonly value: string;
162
readonly searchTerms: ReadonlyArray<string>;
163
readonly title: ReactNode;
164
+ /** The title as plain text, for searching, when `title` is styled. */
165
+ readonly searchTitle?: string;
166
readonly description?: ReactNode;
167
readonly threadContentMatch?: CommandPaletteThreadContentMatch;
168
readonly timestamp?: string;
161
- readonly searchRecency?: number;
169
+ /** Thread rows rank by this, with use history, instead of by `searchTerms`. */
170
+ readonly threadSearch?: ThreadSearchSubject;
171
+ /** Title ranges the current query matched, for highlighting. */
172
+ readonly titleRanges?: ReadonlyArray<SearchRange>;
173
+ /** Shown in place of the description when the match is not in the title. */
174
+ readonly matchHint?: SearchMatchHint;
175
readonly icon: ReactNode;
176
readonly disabled?: boolean;
177
readonly titleLeadingContent?: ReactNode;
@@ -360,36 +373,37 @@ export type BuildThreadActionItemsThread = Pick<
373
| "runtime"
374
| "title"
375
| "worktreePath"
363
-> & {
364
- pullRequests?: SidebarThreadSummary["pullRequests"];
365
- updatedAt: string;
366
- latestUserMessageAt?: string | null;
367
-};
376
+> &
377
+ Partial<
378
+ Pick<
379
+ SidebarThreadSummary,
380
+ "pullRequests" | "linkedPullRequest" | "branchPullRequest" | "opens" | "latestUserMessageAt"
381
+ >
382
+ > & {
383
+ updatedAt: string;
384
+ };
385
386
export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
387
threads: ReadonlyArray<TThread>;
371
- activeThreadId?: Thread["id"];
372
- projectTitleById: ReadonlyMap<Project["id"], string>;
373
- sortOrder: SidebarThreadSortOrder;
388
+ activeThread?: Pick<Thread, "environmentId" | "id">;
389
+ projectByKey: ReadonlyMap<string, Pick<Project, "title">>;
390
icon: ReactNode;
391
renderLeadingContent?: (thread: TThread) => ReactNode;
392
renderTrailingContent?: (thread: TThread) => ReactNode;
393
renderDescription?: (thread: TThread, meta: { projectTitle: string | undefined }) => ReactNode;
378
- getContentMatch?: (thread: TThread) => CommandPaletteThreadContentMatch | undefined;
379
- runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
380
- limit?: number;
394
+ runThread: (thread: TThread) => Promise<void>;
395
+ /** Makes the environment searchable; pass it only with two or more environments. */
396
+ environmentLabelOf?: (thread: TThread) => string | null;
397
}): CommandPaletteActionItem[] {
382
- const sortedThreads = sortThreads(
383
- input.threads.filter(
384
- (thread) => thread.archivedAt === null && !isSidebarSubagentThread(thread),
385
- ),
386
- input.sortOrder,
398
+ // Callers order these: recents by last use, search results by rank.
399
+ const visibleThreads = input.threads.filter(
400
+ (thread) => thread.archivedAt === null && !isSidebarSubagentThread(thread),
401
);
388
- const visibleThreads =
389
- input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
402
403
return visibleThreads.map((thread) => {
392
- const projectTitle = input.projectTitleById.get(thread.projectId);
404
+ const projectTitle = input.projectByKey.get(
405
+ `${thread.environmentId}:${thread.projectId}`,
406
+ )?.title;
407
const descriptionParts: string[] = [];
408
409
if (projectTitle) {
@@ -398,13 +412,15 @@ export function buildThreadActionItems<TThread extends BuildThreadActionItemsThr
412
if (thread.branch) {
413
descriptionParts.push(`#${thread.branch}`);
414
}
401
- if (thread.id === input.activeThreadId) {
415
+ const isCurrent =
416
+ thread.id === input.activeThread?.id &&
417
+ thread.environmentId === input.activeThread.environmentId;
418
+ if (isCurrent) {
419
descriptionParts.push("Current thread");
420
}
421
422
const leadingContent = input.renderLeadingContent?.(thread);
423
const trailingContent = input.renderTrailingContent?.(thread);
407
- const contentMatch = input.getContentMatch?.(thread);
424
const description = input.renderDescription
425
? input.renderDescription(thread, { projectTitle })
426
: descriptionParts.join(` · `);
@@ -412,26 +428,28 @@ export function buildThreadActionItems<TThread extends BuildThreadActionItemsThr
428
return Object.assign(
429
{
430
kind: "action" as const,
415
- value: `thread:${thread.id}`,
416
- searchTerms: [
417
- thread.title,
418
- ...threadPullRequestSearchTerms(thread),
419
- projectTitle ?? ``,
420
- thread.branch ?? ``,
421
- contentMatch?.snippet ?? ``,
422
- thread.id,
423
- ],
431
+ value: `thread:${thread.environmentId}:${thread.id}`,
432
+ searchTerms: [thread.title],
433
+ threadSearch: threadSearchSubject(
434
+ {
435
+ ...thread,
436
+ latestUserMessageAt: thread.latestUserMessageAt ?? null,
437
+ opens: thread.opens ?? null,
438
+ },
439
+ projectTitle,
440
+ input.environmentLabelOf?.(thread),
441
+ ),
442
title: thread.title,
443
description,
444
timestamp: formatRelativeTimeLabel(
445
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
446
),
429
- searchRecency: getThreadSortTimestamp(thread, "updated_at"),
447
icon: input.icon,
448
},
449
leadingContent ? { titleLeadingContent: leadingContent } : {},
450
trailingContent ? { titleTrailingContent: trailingContent } : {},
434
- contentMatch ? { threadContentMatch: contentMatch } : {},
451
+ // Last in its group: picking the thread already open does nothing.
452
+ isCurrent ? { secondary: true } : {},
453
{
454
run: async () => {
455
await input.runThread(thread);
@@ -441,60 +459,54 @@ export function buildThreadActionItems<TThread extends BuildThreadActionItemsThr
459
});
460
}
461
444
-const ALPHANUMERIC = /[\p{L}\p{N}]/u;
445
-
446
-function startsWord(field: string, token: string): boolean {
447
- for (let index = field.indexOf(token); index !== -1; index = field.indexOf(token, index + 1)) {
448
- if (index === 0 || !ALPHANUMERIC.test(field[index - 1]!)) return true;
449
- }
450
- return false;
451
-}
462
+type PaletteItem = CommandPaletteActionItem | CommandPaletteSubmenuItem;
463
453
-// 3 exact, 2 field prefix, 1 every token starts a word, 0 a token only matches mid-word.
454
-function rankSearchFieldMatch(
455
- field: string,
464
+function rankPaletteItem(
465
+ item: PaletteItem,
466
normalizedQuery: string,
457
- queryTokens: ReadonlyArray<string>,
458
-): number {
459
- const normalizedField = normalizeSearchText(field);
460
- if (
461
- normalizedField.length === 0 ||
462
- !queryTokens.every((token) => normalizedField.includes(token))
463
- ) {
464
- return Number.NEGATIVE_INFINITY;
465
- }
466
- if (normalizedField === normalizedQuery) {
467
- return 3;
468
- }
469
- if (normalizedField.startsWith(normalizedQuery)) {
470
- return 2;
471
- }
472
- if (queryTokens.every((token) => startsWord(normalizedField, token))) {
473
- return 1;
474
- }
475
- return 0;
476
-}
477
-
478
-// A word-start match in any field beats a mid-word match, then earlier fields win.
479
-// Thread titles collapse prefix and word-start into one tier so recency picks between them.
480
-function rankCommandPaletteItemMatch(
481
- item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
467
+ now: number,
468
+ options: { readonly typos: boolean },
469
+): {
470
+ readonly score: number;
471
+ readonly quality: number;
472
+ readonly groupQuality?: number;
473
+ readonly strong: boolean;
474
+ readonly ranges: ReadonlyArray<SearchRange>;
475
+ readonly explain?: () => SearchMatchHint | undefined;
476
+ readonly pickedAt?: number;
477
+ readonly pickedExactly?: boolean;
478
+} | null {
479
+ const match = scorePaletteItem(item, normalizedQuery, now, options);
480
+ // A row listed last in its group (a keybinding setting, the open thread)
481
+ // does not decide where the group sits.
482
+ return match && item.secondary ? { ...match, groupQuality: 0 } : match;
483
+}
484
+
485
+function scorePaletteItem(
486
+ item: PaletteItem,
487
normalizedQuery: string,
483
- queryTokens: ReadonlyArray<string>,
484
-): number {
485
- let best = 0;
486
- for (const [index, field] of item.searchTerms.filter((term) => term.length > 0).entries()) {
487
- const fieldRank = rankSearchFieldMatch(field, normalizedQuery, queryTokens);
488
- if (fieldRank === Number.NEGATIVE_INFINITY) continue;
489
- const fieldScore =
490
- index === 0 && item.searchRecency !== undefined
491
- ? 1_000 + Number(fieldRank === 3)
492
- : 1_000 - index * 100 + fieldRank;
493
- best = Math.max(best, (fieldRank > 0 ? 10_000 : 0) + fieldScore);
494
- }
495
- return best;
496
-}
497
-
488
+ now: number,
489
+ options: { readonly typos: boolean },
490
+) {
491
+ if (item.threadSearch) return scoreThreadSearch(normalizedQuery, item.threadSearch, now, options);
492
+ // The title names the item; search terms are keywords. Ranges index the
493
+ // first term, so they only highlight a title that is that term.
494
+ const name = typeof item.title === "string" ? item.title : item.searchTitle;
495
+ const terms =
496
+ name !== undefined && name !== item.searchTerms[0]
497
+ ? [name, ...item.searchTerms]
498
+ : item.searchTerms;
499
+ const match = scoreSearchTerms(normalizedQuery, terms, options);
500
+ return match && (item.title === terms[0] ? match : { ...match, ranges: [] });
501
+}
502
+
503
+/**
504
+ * Filters and ranks the palette for a query. Groups order by the class of their
505
+ * best match, and on equal classes commands come first, then threads, so "new"
506
+ * runs "New thread" and a thread's title is not stuck under a setting. Server
507
+ * message matches always come last, in their own group, so rows above never
508
+ * move when they arrive.
509
+ */
510
export function filterCommandPaletteGroups(input: {
511
activeGroups: ReadonlyArray<CommandPaletteGroup>;
512
query: string;
@@ -502,10 +514,13 @@ export function filterCommandPaletteGroups(input: {
514
projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
515
settingsSearchItems?: ReadonlyArray<CommandPaletteActionItem>;
516
threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
517
+ /** Threads whose messages match, best first; threads already listed are skipped. */
518
+ threadMessageItems?: ReadonlyArray<CommandPaletteActionItem>;
519
+ now?: number;
520
}): CommandPaletteGroup[] {
521
const isActionsFilter = input.query.startsWith(">");
522
const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
508
- const normalizedQuery = normalizeSearchText(searchQuery);
523
+ const normalizedQuery = foldSearchQuery(searchQuery);
524
525
if (normalizedQuery.length === 0) {
526
if (isActionsFilter) {
@@ -513,7 +528,6 @@ export function filterCommandPaletteGroups(input: {
528
}
529
return [...input.activeGroups];
530
}
516
- const queryTokens = normalizedQuery.split(" ");
531
532
let baseGroups = [...input.activeGroups];
533
if (isActionsFilter) {
@@ -523,7 +537,17 @@ export function filterCommandPaletteGroups(input: {
537
}
538
539
const searchableGroups = [...baseGroups];
526
- if (!input.isInSubmenu && !isActionsFilter) {
540
+ const searchesEverything = !input.isInSubmenu && !isActionsFilter;
541
+ // On equal match classes, groups keep this order: threads, what people search
542
+ // for most, right after commands.
543
+ if (searchesEverything) {
544
+ if (input.threadSearchItems.length > 0) {
545
+ searchableGroups.push({
546
+ value: "threads-search",
547
+ label: "Threads",
548
+ items: input.threadSearchItems,
549
+ });
550
+ }
551
if (input.projectSearchItems.length > 0) {
552
searchableGroups.push({
553
value: "projects-search",
@@ -538,43 +562,45 @@ export function filterCommandPaletteGroups(input: {
562
items: input.settingsSearchItems,
563
});
564
}
541
- if (input.threadSearchItems.length > 0) {
542
- searchableGroups.push({
543
- value: "threads-search",
544
- label: "Threads",
545
- items: input.threadSearchItems,
546
- });
547
- }
565
}
566
550
- return searchableGroups.flatMap((group) => {
551
- const items = Arr.filterMap(group.items, (item, index) => {
552
- const haystack = normalizeSearchText(item.searchTerms.join(" "));
553
- if (!queryTokens.every((token) => haystack.includes(token))) {
554
- return Result.failVoid;
555
- }
556
-
557
- return Result.succeed({
558
- item,
559
- index,
560
- rank: rankCommandPaletteItemMatch(item, normalizedQuery, queryTokens),
561
- });
562
- })
567
+ const now = input.now ?? Date.now();
568
+ const ranked = rankSearchGroups(
569
+ searchableGroups.map((group) => ({ group, items: group.items })),
570
+ (item, options) => rankPaletteItem(item, normalizedQuery, now, options),
571
+ );
572
+ const threadsMatch = ranked.some(({ group }) => group.value === "threads-search");
573
+ const groups = ranked.map(({ group, ranked }): CommandPaletteGroup => {
574
+ // Secondary items stay below the rest; the sort is stable, so score order holds.
575
+ const limit =
576
+ group.value === "threads-search"
577
+ ? PALETTE_THREAD_LIMIT
578
+ : searchesEverything && threadsMatch
579
+ ? PALETTE_SECONDARY_LIMIT
580
+ : ranked.length;
581
+ // Hints are built only for the rows shown.
582
+ const items = ranked
583
.toSorted(
584
(left, right) =>
565
- Number(left.item.secondary ?? false) - Number(right.item.secondary ?? false) ||
566
- right.rank - left.rank ||
567
- (right.item.searchRecency ?? 0) - (left.item.searchRecency ?? 0) ||
568
- left.index - right.index,
585
+ Number(left.item.secondary ?? false) - Number(right.item.secondary ?? false),
586
)
570
- .map((entry) => entry.item);
571
-
572
- if (items.length === 0) {
573
- return [];
574
- }
575
-
576
- return [{ value: group.value, label: group.label, items }];
587
+ .slice(0, limit)
588
+ .map(({ item, match }) => {
589
+ if (match.ranges.length > 0) return { ...item, titleRanges: match.ranges };
590
+ // Built only for the rows shown.
591
+ const matchHint = match.explain?.();
592
+ return matchHint ? { ...item, matchHint } : item;
593
+ });
594
+ return { value: group.value, label: group.label, items };
595
});
596
+
597
+ if (!searchesEverything) return groups;
598
+ const listed = new Set(groups.flatMap((group) => group.items.map((item) => item.value)));
599
+ // The items arrive cut to what the palette shows; see `nextShownOrder`.
600
+ const messageItems = (input.threadMessageItems ?? []).filter((item) => !listed.has(item.value));
601
+ return messageItems.length === 0
602
+ ? groups
603
+ : [...groups, { value: "threads-messages", label: "In messages", items: messageItems }];
604
}
605
606
export function buildBrowseGroups(input: {
apps/web/src/components/CommandPalette.tsx
+38
-8
@@ -219,7 +219,7 @@ import { ProjectFilePicker } from "./files/ProjectFilePicker";
219
import { openLinkPullRequestDialog } from "./pullRequest/LinkPullRequestDialog";
220
import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";
221
import { toggleThemeEditorForTheme } from "./settings/themeEditorStore";
222
-import { searchSettings, SETTINGS_SECTION_LABELS } from "./settings/settingsSearch";
222
+import { settingsForThisPlatform, SETTINGS_SECTION_LABELS } from "./settings/settingsSearch";
223
import { primaryServerKeybindingsAtom } from "../state/server";
224
import { resolveShortcutCommand, threadJumpIndexFromCommand } from "../keybindings";
225
import { CommandDialog, CommandDialogPopup, CommandFooterAction } from "./ui/command";
@@ -232,6 +232,7 @@ import { buildSidebarProjectPickerEntries } from "../sidebarProjectGrouping";
232
import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
233
import { readPullRequestListPreferences } from "~/components/pullRequest/pullRequestListPreferences";
234
import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";
235
+import { threadRecentUse } from "@t3tools/shared/paletteSearch";
236
237
const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = [];
238
@@ -895,9 +896,25 @@ function OpenCommandPaletteDialog(props: {
896
];
897
})();
898
898
- const { threadItems: allThreadItems, isSearchPending: isThreadSearchPending } =
899
- useCommandPaletteThreadItems({ activeThreadId, threadSearchQuery });
900
- const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);
899
+ const {
900
+ threadItems: allThreadItems,
901
+ threadMessageItems,
902
+ now: searchNow,
903
+ isSearchPending: isThreadSearchPending,
904
+ } = useCommandPaletteThreadItems({ activeThread: activeThread ?? null, threadSearchQuery });
905
+ // Recent means used recently: written in or opened, whichever is later. The
906
+ // open thread would always lead that list, so it is left out.
907
+ const activeThreadValue = activeThread
908
+ ? `thread:${activeThread.environmentId}:${activeThread.id}`
909
+ : null;
910
+ const recentThreadItems = allThreadItems
911
+ .filter((item) => item.value !== activeThreadValue)
912
+ .toSorted(
913
+ (left, right) =>
914
+ (right.threadSearch ? threadRecentUse(right.threadSearch) : 0) -
915
+ (left.threadSearch ? threadRecentUse(left.threadSearch) : 0),
916
+ )
917
+ .slice(0, RECENT_THREAD_LIMIT);
918
919
// Stable so the item builders that capture it during render never see the
920
// highlight ref it writes.
@@ -1200,6 +1217,7 @@ function OpenCommandPaletteDialog(props: {
1217
New thread in <span className="font-semibold">{activeProjectTitle}</span>
1218
</>
1219
),
1220
+ searchTitle: `New thread in ${activeProjectTitle}`,
1221
icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
1222
shortcutCommand: "chat.newLocal",
1223
run: async () => {
@@ -1303,7 +1321,10 @@ function OpenCommandPaletteDialog(props: {
1321
actionItems.push({
1322
kind: "action",
1323
value: "action:copy-thread-reference",
1306
- searchTerms: ["copy", "pull request", "pr link", "thread id", "reference"],
1324
+ searchTerms:
1325
+ activeThreadReferenceCopyTarget.kind === "pull-request"
1326
+ ? ["copy", "pull request", "link", "reference"]
1327
+ : ["copy", "thread id", "reference"],
1328
title:
1329
activeThreadReferenceCopyTarget.kind === "pull-request" ? "Copy PR link" : "Copy thread ID",
1330
description: activeThreadReferenceCopyTarget.value,
@@ -1589,8 +1610,9 @@ function OpenCommandPaletteDialog(props: {
1610
}
1611
1612
const rootGroups = buildRootGroups({ actionItems, recentThreadItems });
1592
- const settingsSearchItems: CommandPaletteActionItem[] = searchSettings(
1593
- deferredQuery,
1613
+ // Every setting goes to the palette's own matcher, so settings get the same
1614
+ // word starts and typo tolerance as threads.
1615
+ const settingsSearchItems: CommandPaletteActionItem[] = settingsForThisPlatform(
1616
availableSettingsSearchItems,
1617
).map((item) => ({
1618
kind: "action",
@@ -1625,6 +1647,8 @@ function OpenCommandPaletteDialog(props: {
1647
? changeAppearanceItem.groups
1648
: (currentView?.groups ?? rootGroups);
1649
1650
+ const isLinkedThreadSearch =
1651
+ linkedThreadSearch?.linkedThreads !== undefined && deferredQuery === linkedThreadSearch.query;
1652
const filteredGroups = filterCommandPaletteGroups({
1653
activeGroups,
1654
query: deferredQuery,
@@ -1632,7 +1656,7 @@ function OpenCommandPaletteDialog(props: {
1656
projectSearchItems: projectSearchItems,
1657
settingsSearchItems,
1658
threadSearchItems:
1635
- linkedThreadSearch?.linkedThreads && deferredQuery === linkedThreadSearch.query
1659
+ isLinkedThreadSearch && linkedThreadSearch?.linkedThreads
1660
? buildLinkedThreadActionItems({
1661
...linkedThreadSearch.linkedThreads,
1662
query: linkedThreadSearch.query,
@@ -1645,6 +1669,8 @@ function OpenCommandPaletteDialog(props: {
1669
},
1670
})
1671
: allThreadItems,
1672
+ threadMessageItems: isLinkedThreadSearch ? [] : threadMessageItems,
1673
+ now: searchNow,
1674
});
1675
1676
const handleAddProjectForEnvironment = async (input: {
@@ -2632,6 +2658,10 @@ function OpenCommandPaletteDialog(props: {
2658
>
2659
{`Open in ${fileManagerName}`}
2660
</CommandFooterAction>
2661
+ ) : isThreadSearchPending && !isLinkedThreadSearch && !isBrowsing ? (
2662
+ // In the footer, so the list keeps its height while message results may
2663
+ // still arrive below it.
2664
+ <span className="text-muted-foreground text-xs">Searching messages…</span>
2665
) : null;
2666
2667
return (
apps/web/src/components/CommandPaletteResults.tsx
+49
-11
@@ -22,7 +22,11 @@ import {
22
CommandShortcut,
23
} from "./ui/command";
24
import { getVirtualizedScrollFadeClassName } from "./ui/scroll-area";
25
-import { ThreadSearchMatchExcerpt } from "./ThreadSearchMatch";
25
+import {
26
+ HighlightedSearchText,
27
+ SearchMatchHintLine,
28
+ ThreadSearchMatchExcerpt,
29
+} from "./ThreadSearchMatch";
30
31
interface CommandPaletteResultsProps {
32
emptyStateMessage?: string;
@@ -155,14 +159,44 @@ export function CommandPaletteTitleIcon(props: { children: ReactNode }) {
159
return <span className="flex h-5 shrink-0 items-center self-start pt-0.5">{props.children}</span>;
160
}
161
158
-function CommandPaletteTitle({ title }: { title: ReactNode }) {
162
+function CommandPaletteTitle({
163
+ item,
164
+}: {
165
+ item: Pick<CommandPaletteActionItem | CommandPaletteSubmenuItem, "title" | "titleRanges">;
166
+}) {
167
+ const { title } = item;
168
return (
169
<span className="truncate" dir={typeof title === "string" ? textDirection(title) : undefined}>
161
- {title}
170
+ {typeof title === "string" && item.titleRanges ? (
171
+ <HighlightedSearchText text={title} ranges={item.titleRanges} />
172
+ ) : (
173
+ title
174
+ )}
175
</span>
176
);
177
}
178
179
+/**
180
+ * Project and environment for a thread row whose second line shows a message
181
+ * snippet or match hint instead, so similar rows can still be told apart.
182
+ */
183
+function ThreadRowContext({
184
+ item,
185
+}: {
186
+ item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
187
+}) {
188
+ if (!item.threadSearch || !(item.threadContentMatch || item.matchHint)) return null;
189
+ // A "Project: …" hint already names the project.
190
+ const context = [item.threadSearch.projectTitle, item.threadSearch.environmentLabel]
191
+ .filter((part) => part && part !== item.matchHint?.text)
192
+ .join(" · ");
193
+ return context ? (
194
+ <span className="max-w-[45%] shrink-0 truncate text-muted-foreground/70 text-xs">
195
+ {context}
196
+ </span>
197
+ ) : null;
198
+}
199
+
200
function DisabledCommandPaletteResultRow(props: {
201
item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
202
}) {
@@ -173,12 +207,14 @@ function DisabledCommandPaletteResultRow(props: {
207
<span className="flex min-w-0 flex-1 flex-col">
208
<span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
209
{props.item.titleLeadingContent}
176
- <CommandPaletteTitle title={props.item.title} />
210
+ <CommandPaletteTitle item={props.item} />
211
+ <ThreadRowContext item={props.item} />
212
</span>
213
{props.item.threadContentMatch ? (
214
<ThreadSearchMatchExcerpt match={props.item.threadContentMatch} />
180
- ) : null}
181
- {props.item.description ? (
215
+ ) : props.item.matchHint ? (
216
+ <SearchMatchHintLine hint={props.item.matchHint} />
217
+ ) : props.item.description ? (
218
<span className="min-w-0 text-muted-foreground/70 text-xs">
219
{props.item.description}
220
</span>
@@ -187,7 +223,7 @@ function DisabledCommandPaletteResultRow(props: {
223
) : (
224
<span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
225
{props.item.titleLeadingContent}
190
- <CommandPaletteTitle title={props.item.title} />
226
+ <CommandPaletteTitle item={props.item} />
227
</span>
228
)}
229
{props.item.titleTrailingContent}
@@ -223,12 +259,14 @@ function CommandPaletteResultRow(props: {
259
<span className="flex min-w-0 flex-1 flex-col">
260
<span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
261
{props.item.titleLeadingContent}
226
- <CommandPaletteTitle title={props.item.title} />
262
+ <CommandPaletteTitle item={props.item} />
263
+ <ThreadRowContext item={props.item} />
264
</span>
265
{props.item.threadContentMatch ? (
266
<ThreadSearchMatchExcerpt match={props.item.threadContentMatch} />
230
- ) : null}
231
- {props.item.description ? (
267
+ ) : props.item.matchHint ? (
268
+ <SearchMatchHintLine hint={props.item.matchHint} />
269
+ ) : props.item.description ? (
270
<span className="min-w-0 text-muted-foreground/70 text-xs">
271
{props.item.description}
272
</span>
@@ -237,7 +275,7 @@ function CommandPaletteResultRow(props: {
275
) : (
276
<span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
277
{props.item.titleLeadingContent}
240
- <CommandPaletteTitle title={props.item.title} />
278
+ <CommandPaletteTitle item={props.item} />
279
</span>
280
)}
281
{props.item.titleTrailingContent}
apps/web/src/components/CommandPaletteThreadItems.tsx
+124
-39
@@ -1,11 +1,23 @@
1
-import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2
-import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
1
+import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2
+import { findForMessageMatch, requestThreadFindQuery } from "./chat/threadFindActionBus";
3
+import {
4
+ claimThreadOpen,
5
+ nextShownOrder,
6
+ type EnvironmentThreadSearchMatch,
7
+ type ShownOrder,
8
+} from "@t3tools/client-runtime/state/thread-search";
9
+import {
10
+ foldSearchQuery,
11
+ PALETTE_MESSAGE_LIMIT,
12
+ pickedQuery,
13
+ rankMessageMatches,
14
+} from "@t3tools/shared/paletteSearch";
15
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
16
import { useAtomValue } from "@effect/atom-react";
17
import { useNavigate } from "@tanstack/react-router";
18
import { MessageSquareIcon } from "lucide-react";
19
+import { useState } from "react";
20
8
-import { useClientSettings } from "../hooks/useSettings";
21
import {
22
applyProviderInstanceSettings,
23
deriveProviderInstanceEntries,
@@ -19,7 +31,10 @@ import {
31
} from "../state/environments";
32
import { useThreadSearch } from "../state/queries";
33
import { primaryServerProvidersAtom } from "../state/server";
34
+import { threadEnvironment } from "../state/threads";
35
+import { useAtomCommand } from "../state/use-atom-command";
36
import { buildThreadRouteParams } from "../threadRoutes";
37
+import { formatRelativeTimeLabel } from "../timestampFormat";
38
import { buildThreadActionItems, ITEM_ICON_CLASS } from "./CommandPalette.logic";
39
import { useEnvironmentLookups, useProjectLookups } from "./CommandPaletteLookups";
40
import { ThreadCommandSubtitle } from "./ThreadCommandSubtitle";
@@ -51,41 +66,44 @@ function useProviderEntryByEnvironmentAndInstanceId() {
66
);
67
}
68
54
-function useThreadSearchWithContentMatches(query: string) {
69
+function useConnectedThreadSearch(query: string) {
70
const { environments } = useEnvironments();
71
const environmentIds: ReadonlyArray<EnvironmentId> = environments
72
.filter((environment) => environment.connection.phase === "connected")
73
.map((environment) => environment.environmentId);
59
- const threadSearch = useThreadSearch(environmentIds, query);
60
- const contentMatchByKey = new Map(
61
- threadSearch.matches.flatMap((match) =>
62
- match.source === "user" || match.source === "assistant"
63
- ? [[threadSearchMatchKey(match), match] as const]
64
- : [],
65
- ),
66
- );
67
- return { threadSearch, contentMatchByKey };
74
+ return useThreadSearch(environmentIds, query);
75
}
76
70
-/** Every thread as a palette item, with message matches for a non-empty `threadSearchQuery`. */
77
+/**
78
+ * Every visible thread as a palette item, plus, for a non-empty
79
+ * `threadSearchQuery`, the threads whose messages match, best first.
80
+ */
81
export function useCommandPaletteThreadItems(input: {
72
- readonly activeThreadId: ThreadId | undefined;
82
+ readonly activeThread: { readonly environmentId: EnvironmentId; readonly id: ThreadId } | null;
83
readonly threadSearchQuery: string;
84
}) {
75
- const { activeThreadId, threadSearchQuery } = input;
85
+ const { activeThread, threadSearchQuery } = input;
86
const navigate = useNavigate();
87
const threads = useThreadShells();
78
- const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);
88
const { projectEnvironmentLocationById } = useEnvironmentLookups();
89
const providerEntryByEnvironmentAndInstanceId = useProviderEntryByEnvironmentAndInstanceId();
81
- const { threadSearch, contentMatchByKey } = useThreadSearchWithContentMatches(threadSearchQuery);
82
- const { projectByKey, projectTitleById } = useProjectLookups();
90
+ const messageSearch = useConnectedThreadSearch(threadSearchQuery);
91
+ const { projectByKey } = useProjectLookups();
92
+ const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
93
+ // Ranking is relative to when the palette opened, so rows do not reorder as time passes.
94
+ const [now] = useState(() => Date.now());
95
96
+ const { environments } = useEnvironments();
97
const threadItems = buildThreadActionItems({
98
threads,
86
- ...(activeThreadId ? { activeThreadId } : {}),
87
- projectTitleById,
88
- sortOrder: sidebarThreadSortOrder,
99
+ ...(environments.length > 1
100
+ ? {
101
+ environmentLabelOf: (thread: (typeof threads)[number]) =>
102
+ projectEnvironmentLocationById.get(thread.environmentId)?.label ?? null,
103
+ }
104
+ : {}),
105
+ ...(activeThread ? { activeThread } : {}),
106
+ projectByKey,
107
icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
108
renderLeadingContent: (thread) => <ThreadRowLeadingStatus thread={thread} />,
109
renderTrailingContent: (thread) => (
@@ -113,7 +131,9 @@ export function useCommandPaletteThreadItems(input: {
131
}
132
branch={thread.branch}
133
worktreePath={thread.worktreePath}
116
- isCurrent={thread.id === activeThreadId}
134
+ isCurrent={
135
+ thread.id === activeThread?.id && thread.environmentId === activeThread.environmentId
136
+ }
137
driverKind={providerEntry?.driverKind ?? null}
138
providerDisplayName={
139
thread.runtime?.providerName ?? providerEntry?.displayName ?? modelInstanceId
@@ -123,22 +143,30 @@ export function useCommandPaletteThreadItems(input: {
143
/>
144
);
145
},
126
- getContentMatch: (thread) => {
127
- const match = contentMatchByKey.get(
128
- threadSearchMatchKey({
129
- environmentId: thread.environmentId,
130
- threadId: thread.id,
131
- }),
132
- );
133
- return match && (match.source === "user" || match.source === "assistant")
134
- ? {
135
- source: match.source,
136
- snippet: match.snippet,
137
- query: threadSearch.query,
138
- }
139
- : undefined;
140
- },
146
runThread: async (thread) => {
147
+ // A pick sends its open with the query, always, so the server records
148
+ // it; the thread view then skips its own open. The open thread is no pick.
149
+ const isOpen =
150
+ activeThread?.environmentId === thread.environmentId && activeThread.id === thread.id;
151
+ if (threadSearchQuery.trim().length > 0 && !threadSearchQuery.startsWith(">") && !isOpen) {
152
+ claimThreadOpen(thread.environmentId, thread.id, Date.now());
153
+ }
154
+ if (
155
+ threadSearchQuery.trim().length > 0 &&
156
+ !threadSearchQuery.startsWith(">") &&
157
+ thread.lastVisitedAt !== undefined &&
158
+ !isOpen
159
+ ) {
160
+ void visitThread({
161
+ environmentId: thread.environmentId,
162
+ input: {
163
+ threadId: thread.id,
164
+ visitedAt: thread.updatedAt,
165
+ opened: true,
166
+ searchQuery: pickedQuery(threadSearchQuery),
167
+ },
168
+ });
169
+ }
170
await navigate({
171
to: "/$environmentId/$threadId",
172
params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),
@@ -146,5 +174,62 @@ export function useCommandPaletteThreadItems(input: {
174
},
175
});
176
149
- return { threadItems, isSearchPending: threadSearch.isPending };
177
+ const itemByValue = new Map(threadItems.map((item) => [item.value, item]));
178
+ const itemForMatch = (match: EnvironmentThreadSearchMatch) =>
179
+ itemByValue.get(`thread:${match.environmentId}:${match.threadId}`);
180
+ const rankedMessageItems = rankMessageMatches(
181
+ messageSearch.matches,
182
+ (match) => itemForMatch(match)?.threadSearch,
183
+ foldSearchQuery(threadSearchQuery),
184
+ now,
185
+ { withoutTitleMatches: true },
186
+ ).flatMap((match) => {
187
+ const item = itemForMatch(match);
188
+ if (!item) return [];
189
+ // The snippet replaces the project line, so a message row is as tall as a title row.
190
+ const { description: _description, ...rest } = item;
191
+ return [
192
+ {
193
+ ...rest,
194
+ // When the matching message was written, not when the thread last moved.
195
+ ...(match.messageCreatedAt
196
+ ? { timestamp: formatRelativeTimeLabel(match.messageCreatedAt) }
197
+ : {}),
198
+ threadContentMatch: {
199
+ source: match.source,
200
+ snippet: match.snippet,
201
+ query: messageSearch.query,
202
+ },
203
+ // Opens the thread with find on the word at the matched message, so it is in view.
204
+ run: async () => {
205
+ await item.run();
206
+ requestThreadFindQuery(
207
+ scopedThreadKey(scopeThreadRef(match.environmentId, match.threadId)),
208
+ findForMessageMatch(match, messageSearch.query),
209
+ );
210
+ },
211
+ },
212
+ ];
213
+ });
214
+
215
+ // Rows already shown keep their places when a slower environment answers.
216
+ const [shownOrder, setShownOrder] = useState<ShownOrder | null>(null);
217
+ const order = nextShownOrder(
218
+ shownOrder,
219
+ messageSearch.query,
220
+ rankedMessageItems.map((item) => item.value),
221
+ PALETTE_MESSAGE_LIMIT,
222
+ );
223
+ if (order !== shownOrder) setShownOrder(order);
224
+ const messageItemByValue = new Map(rankedMessageItems.map((item) => [item.value, item]));
225
+ const threadMessageItems = order.keys
226
+ .slice(0, order.shown)
227
+ .flatMap((value) => messageItemByValue.get(value) ?? []);
228
+
229
+ return {
230
+ threadItems,
231
+ threadMessageItems,
232
+ now,
233
+ isSearchPending: messageSearch.isPending,
234
+ };
235
}
apps/web/src/components/Sidebar.logic.test.ts
+18
-10
@@ -323,17 +323,23 @@ describe("resolveSidebarThreadStatus", () => {
323
});
324
325
describe("searchSidebarThreads", () => {
326
- const searchThread = (id: string, title: string, project: string) => ({
326
+ const searchThread = (id: string, title: string, latestUserMessageAt: string) => ({
327
environmentId: localEnvironmentId,
328
id: ThreadId.make(id),
329
title,
330
- project,
330
+ branch: null,
331
+ createdAt: "2026-01-01T00:00:00.000Z",
332
+ updatedAt: latestUserMessageAt,
333
+ latestUserMessageAt,
334
+ opens: null,
335
});
336
const threads = [
333
- searchThread("thread-1", "Fix workspace search", "Alpha"),
334
- searchThread("thread-2", "Review providers", "Workspace"),
335
- searchThread("thread-3", "WORKTREE cleanup", "Beta"),
337
+ searchThread("thread-1", "Fix workspace search", "2026-10-20T00:00:00.000Z"),
338
+ searchThread("thread-2", "Review providers", "2026-10-22T00:00:00.000Z"),
339
+ searchThread("thread-3", "WORKTREE cleanup", "2026-09-01T00:00:00.000Z"),
340
+ searchThread("thread-4", "Homework notes", "2026-10-22T00:00:00.000Z"),
341
];
342
+ const now = Date.parse("2026-10-23T00:00:00.000Z");
343
const contentKeys = (...ids: ReadonlyArray<string>) =>
344
new Set(
345
ids.map((id) =>
@@ -341,11 +347,13 @@ describe("searchSidebarThreads", () => {
347
),
348
);
349
344
- it("lists a thread matching both title and content once", () => {
345
- expect(searchSidebarThreads(threads, "work", contentKeys("thread-1"))).toEqual([
346
- threads[0],
347
- threads[2],
348
- ]);
350
+ it("ranks word matches by recent use, then lists message matches once", () => {
351
+ expect(searchSidebarThreads(threads, "work", contentKeys("thread-1", "thread-2"), now)).toEqual(
352
+ {
353
+ titleMatches: [threads[0], threads[2], threads[3]],
354
+ contentMatches: [threads[1]],
355
+ },
356
+ );
357
});
358
});
359
apps/web/src/components/Sidebar.logic.ts
+36
-25
@@ -7,7 +7,12 @@ import {
7
type AtomCommandResult,
8
} from "@t3tools/client-runtime/state/runtime";
9
import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
10
-import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
10
+import {
11
+ threadSearchMatchKey,
12
+ threadSearchSubject,
13
+ type ThreadSearchShell,
14
+} from "@t3tools/client-runtime/state/thread-search";
15
+import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
16
import type { ContextMenuItem, EnvironmentId, ThreadId } from "@t3tools/contracts";
17
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
18
import type { AsyncResult } from "effect/reactivity";
@@ -975,37 +980,43 @@ export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3t
980
981
const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
982
983
+/**
984
+ * Sidebar search results: title, branch, and pull request matches ranked as
985
+ * the command palette ranks them, then threads listed only because their
986
+ * messages match, in `contentMatchKeys` order.
987
+ */
988
export function searchSidebarThreads<
979
- T extends {
989
+ T extends ThreadSearchShell & {
990
readonly environmentId: EnvironmentId;
991
readonly id: ThreadId;
982
- readonly title: string;
983
- } & Parameters<typeof threadPullRequestSearchTerms>[0],
992
+ },
993
>(
994
threads: readonly T[],
995
query: string,
996
contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
988
-): T[] {
989
- const normalizedQuery = query.trim().toLowerCase();
990
- if (normalizedQuery.length === 0) return [];
991
- const titleMatches: T[] = [];
992
- const contentMatches: T[] = [];
993
- for (const thread of threads) {
994
- const matchesTitle = [thread.title, ...threadPullRequestSearchTerms(thread)].some((term) =>
995
- term.toLowerCase().includes(normalizedQuery),
996
- );
997
- if (matchesTitle) {
998
- titleMatches.push(thread);
999
- } else if (
1000
- contentMatchKeys.size > 0 &&
1001
- contentMatchKeys.has(
1002
- threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1003
- )
1004
- ) {
1005
- contentMatches.push(thread);
1006
- }
1007
- }
1008
- return [...titleMatches, ...contentMatches];
997
+ now = Date.now(),
998
+): { readonly titleMatches: T[]; readonly contentMatches: T[] } {
999
+ const normalizedQuery = foldSearchQuery(query);
1000
+ if (normalizedQuery.length === 0) return { titleMatches: [], contentMatches: [] };
1001
+ const titleMatches = rankSearchItems(threads, (thread, options) =>
1002
+ scoreThreadSearch(normalizedQuery, threadSearchSubject(thread, null), now, {
1003
+ ...options,
1004
+ picks: false,
1005
+ }),
1006
+ ).map(({ item }) => item);
1007
+ const listed = new Set(titleMatches);
1008
+ // In the order the server ranked their messages, as the palette lists them.
1009
+ const threadByKey = new Map(
1010
+ threads.map((thread) => [
1011
+ threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1012
+ thread,
1013
+ ]),
1014
+ );
1015
+ const contentMatches = [...contentMatchKeys].flatMap((key) => {
1016
+ const thread = threadByKey.get(key);
1017
+ return thread && !listed.has(thread) ? [thread] : [];
1018
+ });
1019
+ return { titleMatches, contentMatches };
1020
}
1021
1022
export function pullRequestMatchesSearchQuery(
apps/web/src/components/Sidebar.tsx
+85
-30
@@ -30,7 +30,14 @@ import {
30
} from "@t3tools/client-runtime/state/thread-settled";
31
import { createInboxReturnTracker } from "@t3tools/client-runtime/state/thread-inbox";
32
import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort";
33
-import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
33
+import {
34
+ nextShownOrder,
35
+ threadSearchMatchKey,
36
+ threadSearchSubject,
37
+ type ShownOrder,
38
+} from "@t3tools/client-runtime/state/thread-search";
39
+import { foldSearchQuery, rankMessageMatches } from "@t3tools/shared/paletteSearch";
40
+import { findForMessageMatch, requestThreadFindQuery } from "./chat/threadFindActionBus";
41
import {
42
threadRuntimeCanArchive,
43
type EnvironmentThreadShell,
@@ -871,7 +878,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
878
const [optimisticDrop, setOptimisticDrop] = useState<SidebarOptimisticDrop | null>(null);
879
const threadSearchInputRef = useRef<HTMLInputElement>(null);
880
const [threadSearchQuery, setThreadSearchQuery] = useState("");
874
- const [searchHighlight, setSearchHighlight] = useState({ orderKey: "", index: 0 });
881
+ const [searchHighlightKey, setSearchHighlightKey] = useState<string | null>(null);
882
const searchEnvironmentIds = useConnectedEnvironmentIds();
883
const threadSearch = useThreadSearch(searchEnvironmentIds, threadSearchQuery);
884
const handleNewThreadRef = useRef(newThreadContext.handleNewThread);
@@ -1104,36 +1111,76 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1111
isSearchingThreads,
1112
]);
1113
1114
+ // Ranked across environments as the palette ranks them, so one
1115
+ // environment's list does not sit above another's better matches; rows
1116
+ // already shown keep their places while slower environments answer.
1117
+ const threadByMatchKey =
1118
+ threadSearch.matches.length === 0
1119
+ ? null
1120
+ : new Map(
1121
+ searchableThreads.map((thread) => [
1122
+ threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1123
+ thread,
1124
+ ]),
1125
+ );
1126
+ const rankedServerMatches =
1127
+ threadByMatchKey === null
1128
+ ? []
1129
+ : rankMessageMatches(
1130
+ threadSearch.matches,
1131
+ (match) => {
1132
+ const thread = threadByMatchKey.get(threadSearchMatchKey(match));
1133
+ return thread ? threadSearchSubject(thread, null) : undefined;
1134
+ },
1135
+ foldSearchQuery(threadSearchQuery),
1136
+ Date.now(),
1137
+ // A list filter, as on mobile: a pick would move rows unexplained.
1138
+ { picks: false },
1139
+ );
1140
+ const serverMatchByKey = new Map(
1141
+ rankedServerMatches.map((match) => [threadSearchMatchKey(match), match] as const),
1142
+ );
1143
+ const [shownMessageOrder, setShownMessageOrder] = useState<ShownOrder | null>(null);
1144
+ const messageOrder = nextShownOrder(
1145
+ shownMessageOrder,
1146
+ threadSearch.query,
1147
+ [...serverMatchByKey.keys()],
1148
+ Number.POSITIVE_INFINITY,
1149
+ );
1150
+ if (messageOrder !== shownMessageOrder) setShownMessageOrder(messageOrder);
1151
+ const { titleMatches: threadTitleResults, contentMatches: threadContentResults } =
1152
+ searchSidebarThreads(searchableThreads, threadSearchQuery, new Set(messageOrder.keys));
1153
+ const threadSearchResults = [...threadTitleResults, ...threadContentResults];
1154
+ // Only rows listed for their messages show one, and open find on it.
1155
const threadSearchMatchByKey = new Map(
1108
- threadSearch.matches.map((match) => [threadSearchMatchKey(match), match] as const),
1156
+ threadContentResults.flatMap((thread) => {
1157
+ const key = threadSearchMatchKey({
1158
+ environmentId: thread.environmentId,
1159
+ threadId: thread.id,
1160
+ });
1161
+ const match = serverMatchByKey.get(key);
1162
+ return match ? [[key, match] as const] : [];
1163
+ }),
1164
);
1110
- const threadSearchResults = searchSidebarThreads(
1111
- searchableThreads,
1112
- threadSearchQuery,
1113
- new Set(threadSearchMatchByKey.keys()),
1165
+ const threadSearchResultKeys = threadSearchResults.map((thread) =>
1166
+ scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
1167
);
1115
- const threadSearchResultOrderKey = threadSearchResults
1116
- .map((thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)))
1117
- .join("\0");
1168
1119
- // The highlight belongs to one result list; a new list starts at the top.
1120
- const activeSearchResultIndex =
1121
- searchHighlight.orderKey === threadSearchResultOrderKey ? searchHighlight.index : 0;
1169
+ // The highlight follows its thread, so rows that arrive late do not move
1170
+ // it under Enter; a new query starts at the top.
1171
+ const activeSearchResultIndex = Math.max(
1172
+ 0,
1173
+ searchHighlightKey === null ? 0 : threadSearchResultKeys.indexOf(searchHighlightKey),
1174
+ );
1175
const setActiveSearchResultIndex = (index: number | ((index: number) => number)) =>
1123
- setSearchHighlight((current) => {
1124
- const currentIndex = current.orderKey === threadSearchResultOrderKey ? current.index : 0;
1125
- return {
1126
- orderKey: threadSearchResultOrderKey,
1127
- index: typeof index === "function" ? index(currentIndex) : index,
1128
- };
1129
- });
1130
- const activeSearchResult = isSearchingThreads
1131
- ? threadSearchResults[activeSearchResultIndex]
1132
- : undefined;
1133
- const activeSearchResultKey =
1134
- activeSearchResult === undefined
1135
- ? null
1136
- : scopedThreadKey(scopeThreadRef(activeSearchResult.environmentId, activeSearchResult.id));
1176
+ setSearchHighlightKey(
1177
+ threadSearchResultKeys[
1178
+ typeof index === "function" ? index(activeSearchResultIndex) : index
1179
+ ] ?? null,
1180
+ );
1181
+ const activeSearchResultKey = isSearchingThreads
1182
+ ? (threadSearchResultKeys[activeSearchResultIndex] ?? null)
1183
+ : null;
1184
useEffect(() => {
1185
if (activeSearchResultKey === null) return;
1186
document
@@ -1208,11 +1255,18 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1255
1256
const clearThreadSearch = () => {
1257
setThreadSearchQuery("");
1211
- setActiveSearchResultIndex(0);
1258
+ setSearchHighlightKey(null);
1259
};
1260
const selectThreadSearchResult = (thread: EnvironmentThreadShell) => {
1261
+ const ref = scopeThreadRef(thread.environmentId, thread.id);
1262
+ // A row listed for a message match opens find on it, as the palette does.
1263
+ const match = threadSearchMatchByKey.get(
1264
+ threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1265
+ );
1266
+ const query = threadSearch.query;
1267
clearThreadSearch();
1215
- navigateToThread(scopeThreadRef(thread.environmentId, thread.id));
1268
+ navigateToThread(ref);
1269
+ if (match) requestThreadFindQuery(scopedThreadKey(ref), findForMessageMatch(match, query));
1270
};
1271
const handleThreadSearchKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
1272
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
@@ -2771,7 +2825,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2825
searchQuery={threadSearchQuery}
2826
onSearchQueryChange={(value) => {
2827
setThreadSearchQuery(value);
2774
- setActiveSearchResultIndex(0);
2828
+ setSearchHighlightKey(null);
2829
}}
2830
onSearchKeyDown={handleThreadSearchKeyDown}
2831
isSearching={isSearchingThreads}
@@ -2834,6 +2888,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2888
) ?? null
2889
}
2890
searchQuery={threadSearchQuery}
2891
+ searchMatchQuery={threadSearch.query}
2892
onHighlight={() => setActiveSearchResultIndex(index)}
2893
onSelect={() => selectThreadSearchResult(thread)}
2894
onFileDropThreads={handleThreadFileDrop}
apps/web/src/components/ThreadSearchMatch.tsx
+24
-39
@@ -1,42 +1,14 @@
1
-function foldAsciiCase(value: string): string {
2
- return value.replace(/[A-Z]/g, (character) => character.toLowerCase());
3
-}
4
-
5
-function HighlightedSearchText(props: { text: string; query: string }) {
6
- const query = props.query.trim();
7
- if (query.length === 0) return props.text;
8
-
9
- const normalizedText = foldAsciiCase(props.text);
10
- const normalizedQuery = foldAsciiCase(query);
11
- const parts: Array<{
12
- readonly text: string;
13
- readonly highlighted: boolean;
14
- readonly start: number;
15
- }> = [];
16
- let cursor = 0;
1
+import {
2
+ findSearchTokenRanges,
3
+ splitSearchText,
4
+ type SearchMatchHint,
5
+ type SearchRange,
6
+} from "@t3tools/shared/paletteSearch";
7
18
- while (cursor < props.text.length) {
19
- const matchIndex = normalizedText.indexOf(normalizedQuery, cursor);
20
- if (matchIndex === -1) {
21
- parts.push({ text: props.text.slice(cursor), highlighted: false, start: cursor });
22
- break;
23
- }
24
- if (matchIndex > cursor) {
25
- parts.push({
26
- text: props.text.slice(cursor, matchIndex),
27
- highlighted: false,
28
- start: cursor,
29
- });
30
- }
31
- parts.push({
32
- text: props.text.slice(matchIndex, matchIndex + query.length),
33
- highlighted: true,
34
- start: matchIndex,
35
- });
36
- cursor = matchIndex + query.length;
37
- }
38
-
39
- return parts.map((part) =>
8
+/** `text` with each range in semibold foreground. */
9
+export function HighlightedSearchText(props: { text: string; ranges: ReadonlyArray<SearchRange> }) {
10
+ if (props.ranges.length === 0) return props.text;
11
+ return splitSearchText(props.text, props.ranges).map((part) =>
12
part.highlighted ? (
13
<mark className="bg-transparent font-semibold text-foreground" key={part.start}>
14
{part.text}
@@ -47,6 +19,16 @@ function HighlightedSearchText(props: { text: string; query: string }) {
19
);
20
}
21
22
+/** Why a row matched when its title does not show it: the field and its match. */
23
+export function SearchMatchHintLine(props: { hint: SearchMatchHint }) {
24
+ return (
25
+ <span className="truncate text-xs text-muted-foreground/85">
26
+ <span className="text-muted-foreground/70">{props.hint.label}:</span>{" "}
27
+ <HighlightedSearchText text={props.hint.text} ranges={props.hint.ranges} />
28
+ </span>
29
+ );
30
+}
31
+
32
export function ThreadSearchMatchExcerpt(props: {
33
match: {
34
readonly source: "user" | "assistant";
@@ -60,7 +42,10 @@ export function ThreadSearchMatchExcerpt(props: {
42
<span className={isUser ? "text-info-foreground" : "text-success-foreground"}>
43
{isUser ? "You:" : "Agent:"}
44
</span>{" "}
63
- <HighlightedSearchText text={props.match.snippet} query={props.match.query} />
45
+ <HighlightedSearchText
46
+ text={props.match.snippet}
47
+ ranges={findSearchTokenRanges(props.match.snippet, props.match.query)}
48
+ />
49
</span>
50
);
51
}
apps/web/src/components/chat/ThreadVisitWatermark.tsx
+31
@@ -1,6 +1,7 @@
1
import { type ScopedThreadRef } from "@t3tools/contracts";
2
import { resolveThreadLastVisitedAt } from "../Sidebar.logic";
3
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
4
+import { claimThreadOpen } from "@t3tools/client-runtime/state/thread-search";
5
import { useEffect, useRef } from "react";
6
import { useUiStateStore } from "../../uiStateStore";
7
import { threadEnvironment } from "../../state/threads";
@@ -25,6 +26,36 @@ export function ThreadVisitWatermark(props: { readonly threadRef: ScopedThreadRe
26
const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
27
const lastDispatchedVisitRef = useRef<string | null>(null);
28
const lastVisitDispatchAtRef = useRef(0);
29
+ const recordedOpenRef = useRef<string | null>(null);
30
+
31
+ // Opening a thread is one visit that also counts toward search ranking. A
32
+ // palette pick already sent it with the query. It runs before the watermark
33
+ // effect, which then sees this watermark as sent.
34
+ useEffect(() => {
35
+ if (!serverThread?.id) return;
36
+ if (recordedOpenRef.current === threadKey) return;
37
+ recordedOpenRef.current = threadKey;
38
+ // Recorded here even when the server cannot take opens, so recents follow it.
39
+ const claimed = claimThreadOpen(serverThread.environmentId, serverThread.id, Date.now());
40
+ if (!claimed || serverThread.lastVisitedAt === undefined) return;
41
+ lastDispatchedVisitRef.current = `${threadKey}:${serverThread.updatedAt}`;
42
+ lastVisitDispatchAtRef.current = Date.now();
43
+ void visitThreadMutation({
44
+ environmentId: serverThread.environmentId,
45
+ input: {
46
+ threadId: serverThread.id,
47
+ visitedAt: serverThread.updatedAt,
48
+ opened: true,
49
+ },
50
+ });
51
+ }, [
52
+ threadKey,
53
+ serverThread?.environmentId,
54
+ serverThread?.id,
55
+ serverThread?.lastVisitedAt,
56
+ serverThread?.updatedAt,
57
+ visitThreadMutation,
58
+ ]);
59
60
useEffect(() => {
61
if (!serverThread?.id) return;
apps/web/src/components/chat/threadFindActionBus.test.ts
new
+22
@@ -0,0 +1,22 @@
1
+import { MessageId } from "@t3tools/contracts";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import { findForMessageMatch } from "./threadFindActionBus";
5
+
6
+describe("findForMessageMatch", () => {
7
+ it("opens find on the longest word as the snippet writes it, at the matched message", () => {
8
+ expect(
9
+ findForMessageMatch(
10
+ { snippet: "The cafeteria, then the Café", messageId: MessageId.make("message-1") },
11
+ "cafe",
12
+ ),
13
+ ).toEqual({ query: "Café", start: { entryId: "message-1", occurrence: 0 } });
14
+ expect(findForMessageMatch({ snippet: "fix the sidebar lag" }, "fix sidebar")).toEqual({
15
+ query: "sidebar",
16
+ });
17
+ // The whole query, when the snippet holds it as typed.
18
+ expect(findForMessageMatch({ snippet: "then Vp run dev again" }, "vp run dev")).toEqual({
19
+ query: "Vp run dev",
20
+ });
21
+ });
22
+});
apps/web/src/components/chat/threadFindActionBus.ts
+70
@@ -1,3 +1,11 @@
1
+import type { OrchestrationThreadSearchMatch } from "@t3tools/contracts";
2
+import {
3
+ findSearchTokenRanges,
4
+ messagePhrase,
5
+ messageSearchTokens,
6
+} from "@t3tools/shared/paletteSearch";
7
+import type { ThreadFindStart } from "./threadFind";
8
+
9
const THREAD_FIND_OPEN_EVENT = "t3:thread-find-open";
10
11
export function requestThreadFindOpen(): void {
@@ -8,3 +16,65 @@ export function subscribeThreadFindOpen(listener: () => void): () => void {
16
window.addEventListener(THREAD_FIND_OPEN_EVENT, listener);
17
return () => window.removeEventListener(THREAD_FIND_OPEN_EVENT, listener);
18
}
19
+
20
+const THREAD_FIND_QUERY_EVENT = "t3:thread-find-query";
21
+interface PendingFind {
22
+ readonly query: string;
23
+ /** Where find starts, such as the message a palette result came from. */
24
+ readonly start?: ThreadFindStart;
25
+}
26
+// A find a palette message result asked for, until that thread's view takes
27
+// it. One the view never took (the navigation failed) lets go after a while,
28
+// so a later visit does not open an old find.
29
+const PENDING_FIND_MS = 30_000;
30
+let pendingFind: (PendingFind & { readonly threadKey: string; readonly at: number }) | null = null;
31
+
32
+/** Opens find on `query` in the thread's view, now or once it mounts. */
33
+export function requestThreadFindQuery(threadKey: string, find: PendingFind): void {
34
+ pendingFind = { threadKey, at: Date.now(), ...find };
35
+ window.dispatchEvent(new Event(THREAD_FIND_QUERY_EVENT));
36
+}
37
+
38
+/** The find waiting for this thread's view; answers once. */
39
+export function takeThreadFindQuery(threadKey: string): PendingFind | null {
40
+ if (pendingFind?.threadKey !== threadKey) return null;
41
+ const { at, threadKey: _threadKey, ...find } = pendingFind;
42
+ pendingFind = null;
43
+ return Date.now() - at < PENDING_FIND_MS ? find : null;
44
+}
45
+
46
+/**
47
+ * The find a message search result opens, at the matched message: the whole
48
+ * query when the snippet holds it as typed ("vp run dev"), else its longest
49
+ * word, as the most telling ("sidebar" in "fix sidebar"), written as the
50
+ * snippet writes it ("Café" for "cafe", since find matches accents).
51
+ */
52
+export function findForMessageMatch(
53
+ match: Pick<OrchestrationThreadSearchMatch, "snippet" | "messageId">,
54
+ query: string,
55
+): PendingFind {
56
+ const start = match.messageId ? { start: { entryId: match.messageId, occurrence: 0 } } : {};
57
+ // Apostrophes are straight in the query; straightening keeps offsets.
58
+ const together = messagePhrase(query)?.exec(match.snippet.replace(/[\u2018\u2019]/g, "'"));
59
+ if (together) {
60
+ return {
61
+ query: match.snippet.slice(together.index, together.index + together[0].length),
62
+ ...start,
63
+ };
64
+ }
65
+ const word =
66
+ messageSearchTokens(query).long.reduce(
67
+ (longest, token) => (token.length > longest.length ? token : longest),
68
+ "",
69
+ ) || query;
70
+ const ranges = findSearchTokenRanges(match.snippet, word);
71
+ // A whole word first, as search ranked it: "Café", not "Cafe" in "Cafeteria".
72
+ const shown =
73
+ ranges.find((range) => !/[\p{L}\p{N}]/u.test(match.snippet[range.end] ?? "")) ?? ranges[0];
74
+ return { query: shown ? match.snippet.slice(shown.start, shown.end) : word, ...start };
75
+}
76
+
77
+export function subscribeThreadFindQuery(listener: () => void): () => void {
78
+ window.addEventListener(THREAD_FIND_QUERY_EVENT, listener);
79
+ return () => window.removeEventListener(THREAD_FIND_QUERY_EVENT, listener);
80
+}
apps/web/src/components/chat/useComposerMenuItems.ts
+4
@@ -1,4 +1,5 @@
1
import { matchComposerThreadItems } from "@t3tools/client-runtime/composerThreadItems";
2
+import { useState } from "react";
3
import type {
4
EnvironmentId,
5
ProjectId,
@@ -74,6 +75,8 @@ export function useComposerMenuItems({
75
readonly selectedProviderSlashCommands: ServerProvider["slashCommands"];
76
readonly showSkillsInSlashMenu: boolean;
77
}) {
78
+ // Thread mentions rank by recency as of when the composer mounted.
79
+ const [now] = useState(() => Date.now());
80
const composerTriggerKind = composerTrigger?.kind ?? null;
81
const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : "";
82
const pullRequestTriggerQuery =
@@ -162,6 +165,7 @@ export function useComposerMenuItems({
165
environmentId,
166
excludeThreadId: activeThreadId,
167
query: composerTrigger.query,
168
+ now,
169
}),
170
...workspaceEntries.entries.map((entry) => ({
171
id: `path:${entry.kind}:${entry.path}`,
apps/web/src/components/chat/useThreadFind.ts
+30
-1
@@ -12,7 +12,11 @@ import {
12
type ThreadFindStart,
13
stepThreadFindIndex,
14
} from "./threadFind";
15
-import { subscribeThreadFindOpen } from "./threadFindActionBus";
15
+import {
16
+ subscribeThreadFindOpen,
17
+ subscribeThreadFindQuery,
18
+ takeThreadFindQuery,
19
+} from "./threadFindActionBus";
20
import { toastManager } from "../ui/toast";
21
22
const EMPTY_SKILLS: readonly InlineSkill[] = [];
@@ -94,6 +98,31 @@ export function useThreadFind({
98
});
99
const close = useStableCallback(() => setState(CLOSED_FIND));
100
useEffect(() => subscribeThreadFindOpen(open), [open]);
101
+ const openOnQuery = useStableCallback((query: string, start?: ThreadFindStart) => {
102
+ if (threadKey === null) return;
103
+ setState((previous) => ({
104
+ ...(previous.threadKey === threadKey ? previous : CLOSED_FIND),
105
+ threadKey,
106
+ query,
107
+ offset: 0,
108
+ start,
109
+ localSelection: null,
110
+ focusRequestId: previous.focusRequestId + 1,
111
+ navigationId: previous.navigationId + 1,
112
+ requestId: previous.navigationId + 1,
113
+ }));
114
+ });
115
+ // A palette message result opens find on its query, at its message, once
116
+ // this thread shows.
117
+ useEffect(() => {
118
+ if (threadKey === null || !enabled) return;
119
+ const take = () => {
120
+ const find = takeThreadFindQuery(threadKey);
121
+ if (find !== null) openOnQuery(find.query, find.start);
122
+ };
123
+ take();
124
+ return subscribeThreadFindQuery(take);
125
+ }, [enabled, openOnQuery, threadKey]);
126
127
const remote = useServerResults(
128
isOpen ? thread : null,
apps/web/src/components/settings/settingsSearch.ts
+15
-7
@@ -1143,6 +1143,20 @@ export function filterAvailableSettingsSearchItems(
1143
);
1144
}
1145
1146
+/** The settings that exist on this platform and app channel. */
1147
+export function settingsForThisPlatform(
1148
+ items: ReadonlyArray<SettingsSearchItem>,
1149
+): ReadonlyArray<SettingsSearchItem> {
1150
+ const platform = typeof navigator === "undefined" ? "" : navigator.platform;
1151
+ return items.filter(
1152
+ (item) =>
1153
+ (isElectron || item.desktopOnly !== true) &&
1154
+ (!item.releaseChannelOnly || isElectron || HOSTED_APP_CHANNEL !== null) &&
1155
+ (!item.macOnly || isMacPlatform(platform)) &&
1156
+ (!item.windowsOnly || isWindowsPlatform(platform)),
1157
+ );
1158
+}
1159
+
1160
export function searchSettings(
1161
query: string,
1162
items: ReadonlyArray<SettingsSearchItem> = SETTINGS_SEARCH_ITEMS,
@@ -1150,15 +1164,9 @@ export function searchSettings(
1164
const normalizedQuery = normalizeSearchText(query);
1165
if (normalizedQuery.length === 0) return [];
1166
const queryTokens = normalizedQuery.split(" ");
1153
- const platform = typeof navigator === "undefined" ? "" : navigator.platform;
1167
1155
- return items
1168
+ return settingsForThisPlatform(items)
1169
.flatMap((item, index) => {
1157
- if (!isElectron && item.desktopOnly === true) return [];
1158
- if (item.releaseChannelOnly && !isElectron && HOSTED_APP_CHANNEL === null) return [];
1159
- if (item.macOnly && !isMacPlatform(platform)) return [];
1160
- if (item.windowsOnly && !isWindowsPlatform(platform)) return [];
1161
-
1170
const title = normalizeSearchText(item.title);
1171
const fields = [
1172
title,
apps/web/src/components/sidebar/SidebarThreadRow.tsx
+3
-1
@@ -1517,6 +1517,8 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props
1517
resultId: string;
1518
searchMatch: EnvironmentThreadSearchMatch | null;
1519
searchQuery: string;
1520
+ /** The query `searchMatch` was found for, which lags `searchQuery` while a search runs. */
1521
+ searchMatchQuery?: string;
1522
onHighlight: () => void;
1523
onSelect: () => void;
1524
onFileDropThreads: (threadRef: ScopedThreadRef, files: File[]) => void;
@@ -1655,7 +1657,7 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props
1657
match={{
1658
source: props.searchMatch.source,
1659
snippet: props.searchMatch.snippet,
1658
- query: props.searchQuery,
1660
+ query: props.searchMatchQuery ?? props.searchQuery,
1661
}}
1662
/>
1663
) : null}
apps/web/src/state/queries.ts
+26
-7
@@ -6,8 +6,12 @@ import {
6
import {
7
createThreadSearchResultsAtomFamily,
8
makeThreadSearchKey,
9
+ visibleThreadSearch,
10
type EnvironmentThreadSearchMatch,
11
+ type SettledThreadSearch,
12
} from "@t3tools/client-runtime/state/thread-search";
13
+import { THREAD_SEARCH_QUERY_MAX_LENGTH } from "@t3tools/contracts";
14
+import { messageSearchTokens } from "@t3tools/shared/paletteSearch";
15
import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
16
import type {
17
EnvironmentId,
@@ -36,7 +40,7 @@ const PROJECT_PATH_SEARCH_DEBOUNCE_MS = 120;
40
const COMPOSER_PATH_SEARCH_LIMIT = 80;
41
const PROJECT_CONTENT_SEARCH_DEBOUNCE_MS = 120;
42
const PROJECT_CONTENT_SEARCH_LIMIT = 500;
39
-const THREAD_SEARCH_DEBOUNCE_MS = 200;
43
+const THREAD_SEARCH_DEBOUNCE_MS = 120;
44
const VCS_REF_LIST_LIMIT = 100;
45
const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
46
const EMPTY_PROJECT_ENTRIES: ReadonlyArray<ProjectEntry> = [];
@@ -80,20 +84,35 @@ export function useThreadSearch(
84
readonly query: string;
85
readonly isPending: boolean;
86
} {
83
- const normalizedQuery = query.trim();
87
+ // A pasted wall of text searches by its start rather than failing the request.
88
+ const normalizedQuery = query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH).trim();
89
const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
85
- const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2;
90
+ // The server needs a word of three or more letters; shorter queries would always come back empty.
91
+ const canSearch =
92
+ environmentIds.length > 0 && messageSearchTokens(normalizedQuery).long.length > 0;
93
const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
94
const searchKey =
95
settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery);
96
const result = useAtomValue(
97
searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
98
);
92
- const isDebouncing = canSearch && normalizedQuery !== debouncedQuery;
99
+ const isPending = canSearch && (normalizedQuery !== debouncedQuery || result.isLoading);
100
+ // What fast environments returned shows without waiting for a slow one;
101
+ // callers keep shown rows in place with `nextShownOrder`.
102
+ const ready =
103
+ settledQuery !== null && (!result.isLoading || result.matches.length > 0)
104
+ ? { query: settledQuery, matches: result.matches }
105
+ : null;
106
+ // Kept from earlier renders: React's pattern for information from previous renders.
107
+ const [previous, setPrevious] = useState<SettledThreadSearch | null>(null);
108
+ if (ready !== null && previous?.matches !== ready.matches) setPrevious(ready);
109
+ const visible = canSearch
110
+ ? visibleThreadSearch(normalizedQuery, ready, previous)
111
+ : { query: "", matches: EMPTY_THREAD_SEARCH_MATCHES };
112
return {
94
- matches: isDebouncing ? EMPTY_THREAD_SEARCH_MATCHES : result.matches,
95
- query: settledQuery ?? "",
96
- isPending: canSearch && (isDebouncing || result.isLoading),
113
+ matches: visible.matches,
114
+ query: visible.query,
115
+ isPending,
116
};
117
}
118
docs/user/thread-sidebar.md
+9
-2
@@ -187,8 +187,15 @@ The linked pull request participates in automatic settlement.
187
## Find and reference work
188
189
On web and desktop, open the command palette with `Cmd/Ctrl+K` to search threads
190
-across connected environments. Message search starts after two characters and
191
-includes your messages and final agent responses.
190
+across connected environments by title, branch, pull request, or project.
191
+Threads you open often or recently rank higher, and for three weeks the thread
192
+you last picked for a query ranks higher when you type that query again.
193
+Threads whose messages contain all your words appear below, under **In
194
+messages**, and open at the matching message. Message search needs at least
195
+one word of three or more letters, or two for Chinese, Japanese, and Korean.
196
+On mobile, the thread list search also lists message matches and opens them at
197
+the matching message; on an iPad with a keyboard, `Cmd+K` opens the same
198
+palette.
199
200
Use **Settings → Keybindings** to find or customize shortcuts for searching files
201
and copying a thread reference. A copied reference uses the thread's pull request
packages/client-runtime/src/composerThreadItems.test.ts
new
+50
@@ -0,0 +1,50 @@
1
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2
+import { expect, it } from "vite-plus/test";
3
+
4
+import { matchComposerThreadItems, type ComposerThreadCandidate } from "./composerThreadItems.ts";
5
+
6
+const environmentId = EnvironmentId.make("env-composer");
7
+
8
+function shell(
9
+ id: string,
10
+ title: string,
11
+ overrides: Partial<ComposerThreadCandidate> = {},
12
+): ComposerThreadCandidate {
13
+ return {
14
+ environmentId,
15
+ id: ThreadId.make(id),
16
+ title,
17
+ branch: null,
18
+ createdAt: "2026-10-01T00:00:00.000Z",
19
+ updatedAt: "2026-10-01T00:00:00.000Z",
20
+ latestUserMessageAt: null,
21
+ opens: null,
22
+ archivedAt: null,
23
+ lineage: { rootThreadId: ThreadId.make(id), parentThreadId: null, relationshipToParent: null },
24
+ ...overrides,
25
+ };
26
+}
27
+
28
+it("ranks thread mentions like the palette and leaves out subagent threads", () => {
29
+ const items = matchComposerThreadItems({
30
+ shells: [
31
+ shell("newer-mid-word", "Remodel the settings page", {
32
+ updatedAt: "2026-10-20T00:00:00.000Z",
33
+ }),
34
+ shell("word", "Fix model picker"),
35
+ shell("subagent", "Model review", {
36
+ lineage: {
37
+ rootThreadId: ThreadId.make("word"),
38
+ parentThreadId: ThreadId.make("word"),
39
+ relationshipToParent: "subagent",
40
+ },
41
+ }),
42
+ shell("other-environment", "Model docs", { environmentId: EnvironmentId.make("env-other") }),
43
+ ],
44
+ environmentId,
45
+ excludeThreadId: null,
46
+ query: "model",
47
+ now: Date.parse("2026-10-23T00:00:00.000Z"),
48
+ });
49
+ expect(items.map((item) => item.thread.threadId)).toEqual(["word", "newer-mid-word"]);
50
+});
packages/client-runtime/src/composerThreadItems.ts
+26
-20
@@ -1,14 +1,13 @@
1
import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
2
+import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
3
+
4
+import type { EnvironmentThreadShell } from "./state/models.ts";
5
+import { threadSearchSubject, type ThreadSearchShell } from "./state/threadSearch.ts";
6
7
const COMPOSER_THREAD_RESULT_LIMIT = 5;
8
5
-export interface ComposerThreadCandidate {
6
- readonly environmentId: EnvironmentId;
7
- readonly id: ThreadId;
8
- readonly title: string;
9
- readonly updatedAt: string;
10
- readonly archivedAt: string | null;
11
-}
9
+export type ComposerThreadCandidate = ThreadSearchShell &
10
+ Pick<EnvironmentThreadShell, "archivedAt" | "lineage">;
11
12
export interface ComposerThreadItem {
13
readonly id: string;
@@ -19,28 +18,35 @@ export interface ComposerThreadItem {
18
}
19
20
/**
22
- * The agent can only read threads on its own server, so candidates stay within the
23
- * composer's environment.
21
+ * Threads to reference from the composer, matched and ranked like the command
22
+ * palette, without subagent threads. The agent can only read threads on its
23
+ * own server, so candidates stay within the composer's environment.
24
*/
25
export function matchComposerThreadItems(input: {
26
shells: ReadonlyArray<ComposerThreadCandidate>;
27
environmentId: EnvironmentId;
28
excludeThreadId: ThreadId | null;
29
query: string;
30
+ /** Recency is measured against this time. */
31
+ now: number;
32
}): ComposerThreadItem[] {
31
- const query = input.query.trim().toLowerCase();
33
+ const query = foldSearchQuery(input.query);
34
if (query.length === 0) return [];
33
- return input.shells
34
- .filter(
35
- (shell) =>
36
- shell.environmentId === input.environmentId &&
37
- shell.id !== input.excludeThreadId &&
38
- shell.archivedAt === null &&
39
- shell.title.toLowerCase().includes(query),
40
- )
41
- .sort((left, right) => right.updatedAt.localeCompare(left.updatedAt))
35
+ const candidates = input.shells.filter(
36
+ (shell) =>
37
+ shell.environmentId === input.environmentId &&
38
+ shell.id !== input.excludeThreadId &&
39
+ shell.archivedAt === null &&
40
+ shell.lineage.relationshipToParent !== "subagent",
41
+ );
42
+ return rankSearchItems(candidates, (shell, options) =>
43
+ scoreThreadSearch(query, threadSearchSubject(shell, null), input.now, {
44
+ ...options,
45
+ picks: false,
46
+ }),
47
+ )
48
.slice(0, COMPOSER_THREAD_RESULT_LIMIT)
43
- .map((shell) => ({
49
+ .map(({ item: shell }) => ({
50
id: `thread:${shell.environmentId}:${shell.id}`,
51
type: "thread",
52
thread: { environmentId: shell.environmentId, threadId: shell.id },
packages/client-runtime/src/operations/commands.ts
+5
@@ -114,6 +114,9 @@ export interface UnsnoozeThreadInput extends ThreadCommandInput {
114
115
export interface VisitThreadInput extends ThreadCommandInput {
116
readonly visitedAt: string;
117
+ /** Counts toward search frecency; `searchQuery` is the palette query that picked it. */
118
+ readonly opened?: boolean;
119
+ readonly searchQuery?: string;
120
}
121
122
export type MarkThreadUnreadInput = ThreadCommandInput;
@@ -542,6 +545,8 @@ export const visitThread = Effect.fn("EnvironmentCommands.visitThread")(function
545
commandId: yield* allocateCommandId(input),
546
threadId: input.threadId,
547
visitedAt: input.visitedAt,
548
+ ...(input.opened ? { opened: true } : {}),
549
+ ...(input.searchQuery ? { searchQuery: input.searchQuery } : {}),
550
});
551
});
552
packages/client-runtime/src/state/models.ts
+3
@@ -186,6 +186,8 @@ export interface EnvironmentThreadShell {
186
* local visited state they keep.
187
*/
188
readonly lastVisitedAt?: string | null;
189
+ /** Server-tracked open history for search ranking. */
190
+ readonly opens?: import("@t3tools/contracts").OrchestrationV2ThreadOpens | null;
191
readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
192
readonly deletedAt: string | null;
193
readonly source: OrchestrationV2ThreadShell;
@@ -332,6 +334,7 @@ export function presentThreadShell(
334
...(thread.lastVisitedAt === undefined
335
? {}
336
: { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
337
+ opens: thread.opens ?? null,
338
titleRegeneration:
339
thread.titleRegeneration == null
340
? null
packages/client-runtime/src/state/threadSearch.test.ts
+97
@@ -9,9 +9,13 @@ import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
9
import { expect, it } from "vite-plus/test";
10
11
import {
12
+ claimThreadOpen,
13
+ nextShownOrder,
14
createThreadSearchResultsAtomFamily,
15
makeThreadSearchKey,
16
threadSearchMatchKey,
17
+ threadSearchSubject,
18
+ visibleThreadSearch,
19
} from "./threadSearch.ts";
20
21
const envA = EnvironmentId.make("env-a");
@@ -100,3 +104,96 @@ it("merges successful environments and silently ignores failures", () => {
104
105
registry.dispose();
106
});
107
+
108
+it("keeps the previous results visible only while a refined or widened query is pending", () => {
109
+ const previous = {
110
+ query: "websock",
111
+ matches: [
112
+ {
113
+ environmentId: envA,
114
+ threadId: ThreadId.make("thread-a"),
115
+ projectId: ProjectId.make("project-a"),
116
+ source: "user" as const,
117
+ snippet: "websocket reconnect",
118
+ messageCreatedAt: null,
119
+ },
120
+ ],
121
+ };
122
+ expect(visibleThreadSearch("websocke", null, previous)).toBe(previous);
123
+ expect(visibleThreadSearch("webso", null, previous)).toBe(previous);
124
+ expect(visibleThreadSearch("billing", null, previous)).toEqual({ query: "", matches: [] });
125
+ const ready = { query: "websocke", matches: [] };
126
+ expect(visibleThreadSearch("websocke", ready, previous)).toBe(ready);
127
+});
128
+
129
+it("ranks recent threads by this client's own latest open", () => {
130
+ const thread = {
131
+ environmentId: envA,
132
+ id: ThreadId.make("thread-local"),
133
+ title: "Local",
134
+ branch: null,
135
+ createdAt: "2026-10-01T00:00:00.000Z",
136
+ updatedAt: "2026-10-01T00:00:00.000Z",
137
+ latestUserMessageAt: null,
138
+ opens: { openedAt: 1_000, score: 1, picks: [] },
139
+ };
140
+ claimThreadOpen(envA, "thread-local", 5_000);
141
+ expect(threadSearchSubject(thread, null).opens?.openedAt).toBe(5_000);
142
+ // Also when the server has no record of opens, as an older server would not.
143
+ claimThreadOpen(envA, "thread-unrecorded", 6_000);
144
+ expect(
145
+ threadSearchSubject({ ...thread, id: ThreadId.make("thread-unrecorded"), opens: null }, null)
146
+ .opens,
147
+ ).toEqual({ openedAt: 6_000, score: 1, picks: [] });
148
+});
149
+
150
+it("counts recency from what the user wrote, else from when the thread began", () => {
151
+ const thread = {
152
+ environmentId: envA,
153
+ id: ThreadId.make("thread-agent"),
154
+ title: "Launched by an agent",
155
+ branch: null,
156
+ createdAt: "2026-10-01T00:00:00.000Z",
157
+ updatedAt: "2026-10-20T00:00:00.000Z",
158
+ latestUserMessageAt: "2026-10-20T00:00:00.000Z",
159
+ opens: null,
160
+ };
161
+ expect(
162
+ threadSearchSubject({ ...thread, latestUserAuthoredMessageAt: null }, null).activityAt,
163
+ ).toBe(Date.parse("2026-10-01T00:00:00.000Z"));
164
+ expect(
165
+ threadSearchSubject(
166
+ { ...thread, latestUserAuthoredMessageAt: "2026-10-05T00:00:00.000Z" },
167
+ null,
168
+ ).activityAt,
169
+ ).toBe(Date.parse("2026-10-05T00:00:00.000Z"));
170
+ // An older server omits the field.
171
+ expect(threadSearchSubject(thread, null).activityAt).toBe(Date.parse("2026-10-20T00:00:00.000Z"));
172
+});
173
+
174
+it("keeps shown message rows in place and leaves room for a slower environment", () => {
175
+ // The fast environment answers first and fills the limit.
176
+ const fast = Array.from({ length: 12 }, (_, index) => `a${index}`);
177
+ const first = nextShownOrder(null, "rust", fast, 10);
178
+ expect(first.keys.slice(0, first.shown)).toEqual(fast.slice(0, 10));
179
+ // The slow one's matches rank first: shown rows hold, and its best few come next.
180
+ const slow = ["b0", "b1", "b2", "b3"];
181
+ const second = nextShownOrder(first, "rust", [...slow, ...fast], 10);
182
+ expect(second.keys.slice(0, second.shown)).toEqual([...fast.slice(0, 10), "b0", "b1", "b2"]);
183
+ // Nothing new: nothing moves and nothing grows.
184
+ expect(nextShownOrder(second, "rust", [...slow, ...fast], 10)).toBe(second);
185
+ // A third environment gets no more room past the limit.
186
+ const third = nextShownOrder(second, "rust", ["c0", ...slow, ...fast], 10);
187
+ expect(third.shown).toBe(13);
188
+ expect(third.keys.slice(0, 13)).toEqual(second.keys.slice(0, 13));
189
+ // A new query starts from its own ranking.
190
+ expect(nextShownOrder(second, "rusty", ["b0"], 10).keys).toEqual(["b0"]);
191
+});
192
+
193
+it("sends one open per thread every ten minutes by this client's clock", () => {
194
+ const minute = 60_000;
195
+ expect(claimThreadOpen(envA, "thread-open", 0)).toBe(true);
196
+ expect(claimThreadOpen(envA, "thread-open", 9 * minute)).toBe(false);
197
+ expect(claimThreadOpen(envB, "thread-open", 9 * minute)).toBe(true);
198
+ expect(claimThreadOpen(envA, "thread-open", 10 * minute)).toBe(true);
199
+});
packages/client-runtime/src/state/threadSearch.ts
+155
-6
@@ -7,6 +7,37 @@ import {
7
import * as Option from "effect/Option";
8
import * as Schema from "effect/Schema";
9
import { AsyncResult, Atom } from "effect/reactivity";
10
+import {
11
+ foldSearchQuery,
12
+ THREAD_OPEN_DEDUPE_MS,
13
+ type ThreadSearchSubject,
14
+} from "@t3tools/shared/paletteSearch";
15
+import { threadSearchPullRequests } from "@t3tools/shared/threadPullRequests";
16
+
17
+import type { EnvironmentThreadShell } from "./models.ts";
18
+import { getThreadSortTimestamp } from "./threadSort.ts";
19
+
20
+// When this client last sent an open per thread, by its own clock: a server
21
+// timestamp would be off by any clock skew. The server merges opens closer
22
+// together than THREAD_OPEN_DEDUPE_MS anyway, so skipping them saves a command
23
+// and a broadcast while flipping between threads.
24
+const sentThreadOpens = new Map<string, number>();
25
+// When this client last opened each thread, sent or not, so recent threads
26
+// follow quick switches the server merges.
27
+const localThreadOpens = new Map<string, number>();
28
+/**
29
+ * Records that this client opened a thread, and says whether to send the open
30
+ * to the server now.
31
+ */
32
+export function claimThreadOpen(environmentId: EnvironmentId, threadId: string, now: number) {
33
+ const key = `${environmentId}:${threadId}`;
34
+ localThreadOpens.set(key, now);
35
+ if (now - (sentThreadOpens.get(key) ?? Number.NEGATIVE_INFINITY) < THREAD_OPEN_DEDUPE_MS) {
36
+ return false;
37
+ }
38
+ sentThreadOpens.set(key, now);
39
+ return true;
40
+}
41
42
export interface EnvironmentThreadSearchMatch extends OrchestrationThreadSearchMatch {
43
readonly environmentId: EnvironmentId;
@@ -65,12 +96,7 @@ export function createThreadSearchResultsAtomFamily<E>(options: {
96
isLoading ||= result.waiting;
97
const value = Option.getOrNull(AsyncResult.value(result));
98
if (value !== null) {
68
- matches.push(
69
- ...value.matches.map((match) => ({
70
- ...match,
71
- environmentId,
72
- })),
73
- );
99
+ matches.push(...value.matches.map((match) => ({ ...match, environmentId })));
100
}
101
}
102
@@ -78,3 +104,126 @@ export function createThreadSearchResultsAtomFamily<E>(options: {
104
}).pipe(Atom.withLabel(`${options.labelPrefix}:${key}`)),
105
);
106
}
107
+
108
+export type ThreadSearchShell = Pick<
109
+ EnvironmentThreadShell,
110
+ | "environmentId"
111
+ | "id"
112
+ | "title"
113
+ | "branch"
114
+ | "createdAt"
115
+ | "updatedAt"
116
+ | "latestUserMessageAt"
117
+ | "latestUserAuthoredMessageAt"
118
+ | "opens"
119
+> &
120
+ Partial<Pick<EnvironmentThreadShell, "pullRequests" | "linkedPullRequest" | "branchPullRequest">>;
121
+
122
+/**
123
+ * What the web and mobile palettes rank a thread shell by. Pass the
124
+ * environment label only when there are two or more environments.
125
+ */
126
+export function threadSearchSubject(
127
+ thread: ThreadSearchShell,
128
+ projectTitle: string | null | undefined,
129
+ environmentLabel?: string | null,
130
+): ThreadSearchSubject {
131
+ // What the user wrote, not agent wakes or task notices in the user role. A
132
+ // thread the user never wrote in counts from its creation; an older server
133
+ // omits the field, so the latest user-role message stands in.
134
+ const authored = thread.latestUserAuthoredMessageAt;
135
+ const activityAt =
136
+ authored === undefined
137
+ ? getThreadSortTimestamp(thread, "updated_at")
138
+ : Date.parse(authored ?? thread.createdAt);
139
+ const localOpenedAt = localThreadOpens.get(`${thread.environmentId}:${thread.id}`) ?? 0;
140
+ return {
141
+ id: thread.id,
142
+ title: thread.title,
143
+ branch: thread.branch,
144
+ projectTitle: projectTitle ?? null,
145
+ environmentLabel: environmentLabel ?? null,
146
+ pullRequests: threadSearchPullRequests(thread),
147
+ activityAt: Number.isFinite(activityAt) ? activityAt : null,
148
+ // This client's own latest open counts too: the server merged it, or has
149
+ // no record yet (an older server ignores opens).
150
+ opens:
151
+ localOpenedAt > (thread.opens?.openedAt ?? 0)
152
+ ? { score: 1, picks: [], ...thread.opens, openedAt: localOpenedAt }
153
+ : (thread.opens ?? null),
154
+ };
155
+}
156
+
157
+/** Message result keys in the order a search box last showed them for `query`. */
158
+export interface ShownOrder {
159
+ readonly query: string;
160
+ readonly keys: ReadonlyArray<string>;
161
+ /** How many of `keys` are on screen; only those hold their places. */
162
+ readonly shown: number;
163
+}
164
+
165
+// Rows past the limit a slower environment's best matches may take.
166
+const LATE_ROOM = 3;
167
+
168
+/**
169
+ * The order to show message results in, and how many: rows already shown for
170
+ * this query keep their places, and results that arrive later, from a slower
171
+ * environment, go below them with up to LATE_ROOM rows past `limit`. Nothing
172
+ * moves under the pointer or the keyboard highlight, and a late best match
173
+ * still shows. Returns `previous` when nothing changed, so it can sit in React
174
+ * state.
175
+ */
176
+export function nextShownOrder(
177
+ previous: ShownOrder | null,
178
+ query: string,
179
+ ranked: ReadonlyArray<string>,
180
+ limit: number,
181
+): ShownOrder {
182
+ if (previous?.query !== query) {
183
+ return { query, keys: ranked, shown: Math.min(limit, ranked.length) };
184
+ }
185
+ const listed = new Set(ranked);
186
+ const kept = previous.keys.slice(0, previous.shown).filter((key) => listed.has(key));
187
+ const held = new Set(kept);
188
+ const seen = new Set(previous.keys);
189
+ const rest = ranked.filter((key) => !held.has(key));
190
+ const arrived = rest.filter((key) => !seen.has(key)).length;
191
+ const keys = [...kept, ...rest];
192
+ const shown = Math.min(
193
+ keys.length,
194
+ limit + LATE_ROOM,
195
+ Math.max(limit, kept.length + Math.min(arrived, LATE_ROOM)),
196
+ );
197
+ const unchanged =
198
+ shown === previous.shown &&
199
+ keys.length === previous.keys.length &&
200
+ keys.every((key, index) => key === previous.keys[index]);
201
+ return unchanged ? previous : { query, keys, shown };
202
+}
203
+
204
+export interface SettledThreadSearch {
205
+ readonly query: string;
206
+ readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
207
+}
208
+
209
+/**
210
+ * What a search box shows for `query`: its own results once they arrive
211
+ * (`ready`), else the previous results if `query` refines or widens their
212
+ * query, so result rows do not blink out and back on every keystroke.
213
+ * Results for an unrelated query clear.
214
+ */
215
+export function visibleThreadSearch(
216
+ query: string,
217
+ ready: SettledThreadSearch | null,
218
+ previous: SettledThreadSearch | null,
219
+): SettledThreadSearch {
220
+ if (ready !== null) return ready;
221
+ const current = foldSearchQuery(query);
222
+ const before = foldSearchQuery(previous?.query ?? "");
223
+ return previous !== null &&
224
+ current.length > 0 &&
225
+ before.length > 0 &&
226
+ (current.startsWith(before) || before.startsWith(current))
227
+ ? previous
228
+ : { query: "", matches: [] };
229
+}
packages/contracts/src/orchestrationV2.test.ts
+41
@@ -10,6 +10,7 @@ import {
10
OrchestrationV2ProviderThreadJson,
11
OrchestrationV2RpcSchemas,
12
OrchestrationV2Subagent,
13
+ OrchestrationV2ThreadShellJson,
14
OrchestrationV2SubagentJson,
15
OrchestrationV2ThreadHistoryPage,
16
OrchestrationV2TurnItem,
@@ -419,6 +420,46 @@ describe("orchestration V2 contracts", () => {
420
});
421
});
422
423
+describe("thread open stats", () => {
424
+ it("reads a thread whose open stats this build cannot read, without them", () => {
425
+ const shell = {
426
+ id: "thread-test",
427
+ projectId: "project-test",
428
+ title: "Thread",
429
+ providerInstanceId: "codex",
430
+ modelSelection: { instanceId: "codex", model: "gpt-5.4" },
431
+ runtimeMode: "full-access",
432
+ interactionMode: "default",
433
+ branch: null,
434
+ worktreePath: null,
435
+ activeProviderThreadId: null,
436
+ lineage: { rootThreadId: "thread-test", parentThreadId: null, relationshipToParent: null },
437
+ forkedFrom: null,
438
+ createdBy: "user",
439
+ creationSource: "mobile",
440
+ latestRunId: null,
441
+ activeRunId: null,
442
+ status: "idle",
443
+ pendingRuntimeRequest: null,
444
+ latestVisibleMessage: null,
445
+ latestUserMessageAt: null,
446
+ hasActionableProposedPlan: false,
447
+ itemCount: 0,
448
+ visibleItemCount: 0,
449
+ createdAt: "2026-10-01T00:00:00.000Z",
450
+ updatedAt: "2026-10-01T00:00:00.000Z",
451
+ archivedAt: null,
452
+ settledOverride: null,
453
+ settledAt: null,
454
+ deletedAt: null,
455
+ };
456
+ const decode = Schema.decodeUnknownSync(OrchestrationV2ThreadShellJson);
457
+ const opens = { openedAt: 1, score: 1, picks: [{ query: "upl", at: 1 }] };
458
+ expect(decode({ ...shell, opens }).opens).toEqual(opens);
459
+ expect(decode({ ...shell, opens: { openedAt: "2026-10-01", score: 1 } }).opens).toBeNull();
460
+ });
461
+});
462
+
463
describe("background work kinds from older or newer servers", () => {
464
const storedNotification = (source: unknown) => ({
465
id: "notification",
packages/contracts/src/orchestrationV2.ts
+28
@@ -370,6 +370,28 @@ export const OrchestrationV2LimitRecoveryUpdate = Schema.Struct({
370
);
371
export type OrchestrationV2LimitRecoveryUpdate = typeof OrchestrationV2LimitRecoveryUpdate.Type;
372
373
+/**
374
+ * How often the user opens a thread, for search ranking. `score` is an open
375
+ * count that halves every two weeks, as of `openedAt`. `picks` holds the last
376
+ * few palette queries that picked the thread, folded to lowercase, newest
377
+ * first, each with when it was picked. Times are epoch milliseconds: ranking
378
+ * does arithmetic on them.
379
+ */
380
+export const OrchestrationV2ThreadOpens = Schema.Struct({
381
+ openedAt: Schema.Finite,
382
+ score: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
383
+ picks: Schema.Array(
384
+ Schema.Struct({ query: Schema.String.check(Schema.isMaxLength(32)), at: Schema.Finite }),
385
+ ).check(Schema.isMaxLength(3)),
386
+});
387
+export type OrchestrationV2ThreadOpens = typeof OrchestrationV2ThreadOpens.Type;
388
+
389
+// Open stats only rank search results, so a value this build cannot read (an
390
+// older or newer shape) becomes null instead of failing the whole thread.
391
+const LenientThreadOpens = Schema.NullOr(OrchestrationV2ThreadOpens).pipe(
392
+ Schema.catchDecoding(() => Effect.succeedSome(null)),
393
+);
394
+
395
export const OrchestrationV2AppThread = Schema.Struct({
396
...OrchestrationV2CreationFields,
397
id: ThreadId,
@@ -419,6 +441,7 @@ export const OrchestrationV2AppThread = Schema.Struct({
441
lastVisitedAt: Schema.NullOr(Schema.DateTimeUtc).pipe(
442
Schema.withDecodingDefault(Effect.succeed(null)),
443
),
444
+ opens: Schema.optional(LenientThreadOpens),
445
titleRegeneration: Schema.optional(
446
Schema.NullOr(
447
Schema.Struct({
@@ -1877,6 +1900,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
1900
pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
1901
activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
1902
lastVisitedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
1903
+ opens: Schema.optional(LenientThreadOpens),
1904
titleRegeneration: Schema.optional(
1905
Schema.NullOr(
1906
Schema.Struct({
@@ -2691,6 +2715,10 @@ export const OrchestrationV2Command = Schema.Union([
2715
commandId: CommandId,
2716
threadId: ThreadId,
2717
visitedAt: IsoDateTime,
2718
+ // The user opened the thread, as opposed to new activity on an open one.
2719
+ // Older servers ignore both fields and only move the read watermark.
2720
+ opened: Schema.optional(Schema.Boolean),
2721
+ searchQuery: Schema.optional(Schema.String.check(Schema.isMaxLength(200))),
2722
}),
2723
Schema.Struct({
2724
type: Schema.Literal("thread.mark-unread"),
packages/contracts/src/threadSearch.ts
+19
-1
@@ -2,6 +2,7 @@ import * as Schema from "effect/Schema";
2
3
import {
4
IsoDateTime,
5
+ MessageId,
6
ProjectId,
7
ThreadId,
8
TrimmedNonEmptyString,
@@ -11,10 +12,16 @@ import {
12
export const OrchestrationThreadSearchSource = Schema.Literals(["user", "assistant"]);
13
export type OrchestrationThreadSearchSource = typeof OrchestrationThreadSearchSource.Type;
14
15
+/** Longer queries are cut to this before they are sent. */
16
+export const THREAD_SEARCH_QUERY_MAX_LENGTH = 200;
17
+
18
// The server's SQLite client is synchronous and single-connection. Bound both
19
// scan input and response size so a search cannot monopolize that connection.
20
export const OrchestrationSearchThreadsInput = Schema.Struct({
17
- query: TrimmedString.check(Schema.isMinLength(2), Schema.isMaxLength(200)),
21
+ query: TrimmedString.check(
22
+ Schema.isMinLength(2),
23
+ Schema.isMaxLength(THREAD_SEARCH_QUERY_MAX_LENGTH),
24
+ ),
25
limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 50 }))),
26
});
27
export type OrchestrationSearchThreadsInput = typeof OrchestrationSearchThreadsInput.Type;
@@ -25,6 +32,17 @@ export const OrchestrationThreadSearchMatch = Schema.Struct({
32
source: OrchestrationThreadSearchSource,
33
snippet: Schema.String.check(Schema.isMaxLength(240)),
34
messageCreatedAt: Schema.NullOr(IsoDateTime),
35
+ /**
36
+ * How well the message matches: 1 for whole words, 0.8 when a word only
37
+ * starts one, 0.3 when one only appears inside words, 0.25 more when the
38
+ * words are written together as typed, else 0.1 more when they are near.
39
+ * Older servers omit it.
40
+ */
41
+ quality: Schema.optionalKey(Schema.Finite),
42
+ /** How many of the thread's newest messages match. Older servers omit it. */
43
+ hits: Schema.optionalKey(Schema.Int),
44
+ /** The message the snippet is from. Older servers omit it. */
45
+ messageId: Schema.optionalKey(MessageId),
46
});
47
export type OrchestrationThreadSearchMatch = typeof OrchestrationThreadSearchMatch.Type;
48
packages/shared/package.json
+4
@@ -243,6 +243,10 @@
243
"types": "./src/threadReference.ts",
244
"import": "./src/threadReference.ts"
245
},
246
+ "./paletteSearch": {
247
+ "types": "./src/paletteSearch.ts",
248
+ "import": "./src/paletteSearch.ts"
249
+ },
250
"./threadPullRequests": {
251
"types": "./src/threadPullRequests.ts",
252
"import": "./src/threadPullRequests.ts"
packages/shared/src/paletteSearch.test.ts
new
+740
@@ -0,0 +1,740 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import {
4
+ findSearchTokenRanges,
5
+ foldSearchQuery,
6
+ pickedQuery,
7
+ rankMessageMatches,
8
+ rankSearchGroups,
9
+ rankSearchItems,
10
+ recordThreadOpen,
11
+ messageMatcher,
12
+ scoreSearchTerms,
13
+ scoreThreadSearch,
14
+ SEARCH_RECENCY_HALF_LIFE_MS,
15
+ type SearchTermsMatch,
16
+ type ThreadSearchSubject,
17
+} from "./paletteSearch.ts";
18
+
19
+const NOW = Date.UTC(2026, 9, 23);
20
+const scoreMessageMatch = (text: string, query: string) => messageMatcher(query)(text);
21
+const DAY = 24 * 60 * 60 * 1000;
22
+
23
+function thread(title: string, overrides: Partial<ThreadSearchSubject> = {}): ThreadSearchSubject {
24
+ return { title, activityAt: NOW - 30 * DAY, ...overrides };
25
+}
26
+
27
+function rankTitles(query: string, threads: ReadonlyArray<ThreadSearchSubject>): string[] {
28
+ const normalized = foldSearchQuery(query);
29
+ return rankSearchItems(threads, (subject, options) =>
30
+ scoreThreadSearch(normalized, subject, NOW, options),
31
+ ).map(({ item }) => item.title);
32
+}
33
+
34
+describe("scoreThreadSearch", () => {
35
+ it("ranks whole words over prefixes over newer mid-word matches", () => {
36
+ expect(
37
+ rankTitles("auth", [
38
+ thread("Fix oauth redirect", { activityAt: NOW }),
39
+ thread("Authentication cleanup"),
40
+ thread("Share auth across worktrees"),
41
+ ]),
42
+ ).toEqual(["Share auth across worktrees", "Authentication cleanup", "Fix oauth redirect"]);
43
+ });
44
+
45
+ it("treats camelCase, kebab, path, and digit boundaries as word starts", () => {
46
+ const starts = (title: string, query: string) =>
47
+ scoreThreadSearch(query, thread(title), NOW)?.ranges;
48
+ expect(starts("useThreadSearch hook", "search")).toEqual([{ start: 9, end: 15 }]);
49
+ expect(starts("fix/sidebar-perf", "perf")).toEqual([{ start: 12, end: 16 }]);
50
+ expect(starts("Upgrade to pnpm12", "12")).toEqual([{ start: 15, end: 17 }]);
51
+ expect(starts("Fix JSONSchema parsing", "sch")).toEqual([{ start: 8, end: 11 }]);
52
+ expect(starts("Fix HTTPServer crash", "ser")).toEqual([{ start: 8, end: 11 }]);
53
+ expect(starts("Rename index.ts", ".ts")).toEqual([{ start: 12, end: 15 }]);
54
+ // A match is whole only where a word ends: "githuba" does not fill "GitHubActions".
55
+ expect(scoreThreadSearch("githuba", thread("GitHubActions setup"), NOW)?.quality).toBeLessThan(
56
+ 1,
57
+ );
58
+ expect(rankTitles(".ts", [thread("Fix parser.tsx"), thread("Rename index.ts")])).toEqual([
59
+ "Rename index.ts",
60
+ "Fix parser.tsx",
61
+ ]);
62
+ // Short tokens never match mid-word.
63
+ expect(scoreThreadSearch("ci", thread("Decision log"), NOW)).toBeNull();
64
+ });
65
+
66
+ it("lets recent activity and frequent opens decide between equal matches", () => {
67
+ expect(
68
+ rankTitles("goldbug", [
69
+ thread("Goldbug epilogue", { activityAt: NOW - 20 * DAY }),
70
+ thread("Goldbug processes", { activityAt: NOW - DAY }),
71
+ ]),
72
+ ).toEqual(["Goldbug processes", "Goldbug epilogue"]);
73
+ expect(
74
+ rankTitles("goldbug", [
75
+ thread("Goldbug processes", { activityAt: NOW - DAY }),
76
+ thread("Goldbug notes", {
77
+ activityAt: NOW - 40 * DAY,
78
+ opens: { openedAt: NOW - DAY, score: 12, picks: [] },
79
+ }),
80
+ ]),
81
+ ).toEqual(["Goldbug notes", "Goldbug processes"]);
82
+ });
83
+
84
+ it("puts the thread picked for a query first when that query is typed again", () => {
85
+ const threads = [
86
+ thread("Release checklist", {
87
+ opens: { openedAt: NOW - 5 * DAY, score: 1, picks: [{ query: "rel", at: NOW - 5 * DAY }] },
88
+ }),
89
+ thread("Relay pairing", { activityAt: NOW }),
90
+ ];
91
+ expect(rankTitles("rel", threads)).toEqual(["Release checklist", "Relay pairing"]);
92
+ // A pick never lifts a match inside a word above a word match.
93
+ expect(
94
+ rankTitles("auth", [
95
+ thread("Fix oauth redirect", {
96
+ opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "auth", at: NOW - DAY }] },
97
+ }),
98
+ thread("Share auth across worktrees"),
99
+ ]),
100
+ ).toEqual(["Share auth across worktrees", "Fix oauth redirect"]);
101
+ // Two letters are too little to go on.
102
+ expect(rankTitles("re", threads)).toEqual(["Relay pairing", "Release checklist"]);
103
+ // Once the query leaves the pick behind, the better match wins again.
104
+ expect(rankTitles("rela", threads)).toEqual(["Relay pairing"]);
105
+ // An old pick fades with the thread's last open.
106
+ const stale = [
107
+ thread("Release checklist", {
108
+ opens: {
109
+ openedAt: NOW - 90 * DAY,
110
+ score: 1,
111
+ picks: [{ query: "rel", at: NOW - 90 * DAY }],
112
+ },
113
+ }),
114
+ thread("Relay pairing", { activityAt: NOW }),
115
+ ];
116
+ expect(rankTitles("rel", stale)).toEqual(["Relay pairing", "Release checklist"]);
117
+ // Opening an old pick some other way does not revive it over a newer pick.
118
+ const reopened = [
119
+ thread("Release checklist", {
120
+ opens: { openedAt: NOW - DAY, score: 2, picks: [{ query: "rel", at: NOW - 30 * DAY }] },
121
+ }),
122
+ thread("Relay pairing", {
123
+ opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "rel", at: NOW - DAY }] },
124
+ }),
125
+ ];
126
+ expect(rankTitles("rel", reopened)).toEqual(["Relay pairing", "Release checklist"]);
127
+ // The latest pick for a query wins over an earlier one with a better title match.
128
+ const repicked = [
129
+ thread("Deploy", {
130
+ opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "deploy", at: NOW - DAY }] },
131
+ }),
132
+ thread("Deploy timeout on Railway", {
133
+ opens: { openedAt: NOW, score: 1, picks: [{ query: "deploy", at: NOW }] },
134
+ }),
135
+ ];
136
+ expect(rankTitles("deploy", repicked)).toEqual(["Deploy timeout on Railway", "Deploy"]);
137
+ // A thread's exact pick counts even after a newer pick for a longer query.
138
+ const exact = [
139
+ thread("Fix browser", {
140
+ opens: {
141
+ openedAt: NOW,
142
+ score: 2,
143
+ picks: [
144
+ { query: "fix browser", at: NOW },
145
+ { query: "fix", at: NOW - 2 * DAY },
146
+ ],
147
+ },
148
+ }),
149
+ thread("Fix sidebar", {
150
+ opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "fix", at: NOW - DAY }] },
151
+ }),
152
+ ];
153
+ expect(rankTitles("fix", exact)).toEqual(["Fix sidebar", "Fix browser"]);
154
+ // A pick for a longer query does not pass the thread named by the query.
155
+ const named = [
156
+ thread("Lakebed perf audit", {
157
+ opens: { openedAt: NOW, score: 1, picks: [{ query: "lakebed perf", at: NOW }] },
158
+ }),
159
+ thread("Lakebed"),
160
+ ];
161
+ expect(rankTitles("lakebed", named)).toEqual(["Lakebed", "Lakebed perf audit"]);
162
+ });
163
+
164
+ it("finds a branch pasted with the app's worktree prefix", () => {
165
+ const subject = thread("Cmd+K search", { branch: "t3/cmdk-search-v2" });
166
+ expect(scoreThreadSearch(foldSearchQuery("t3/cmdk-search-v2"), subject, NOW)).not.toBeNull();
167
+ expect(scoreThreadSearch(foldSearchQuery("t3/cmdk"), subject, NOW)).not.toBeNull();
168
+ });
169
+
170
+ it("ranks a title holding the words above the app's own branch prefix and project name", () => {
171
+ const busy = { activityAt: NOW, opens: { openedAt: NOW, score: 6, picks: [] } };
172
+ expect(
173
+ rankTitles("t3 connect", [
174
+ thread("Diagnose Connect provisioning failures", {
175
+ ...busy,
176
+ branch: "t3/diagnose-connect",
177
+ projectTitle: "t3code",
178
+ }),
179
+ thread("T3 Connect Tunnel Lifecycle Review", { projectTitle: "t3code" }),
180
+ ])[0],
181
+ ).toBe("T3 Connect Tunnel Lifecycle Review");
182
+ expect(
183
+ rankTitles("t3code", [
184
+ thread("Fix sidebar lag", { ...busy, projectTitle: "t3code", branch: "t3code/sidebar" }),
185
+ thread("T3 Code vs Gemini Token Volume", { projectTitle: "slophouse" }),
186
+ ])[0],
187
+ ).toBe("T3 Code vs Gemini Token Volume");
188
+ });
189
+
190
+ it("matches pull request numbers, branches, and projects with every token somewhere", () => {
191
+ const subject = thread("Trim model lists", {
192
+ branch: "t3/trim-mcp-models",
193
+ projectTitle: "t3code",
194
+ pullRequests: [{ number: 22889, title: "Smaller MCP payloads" }],
195
+ });
196
+ for (const query of ["#22889", "22889", "trim mcp", "payloads t3code", "models trim"]) {
197
+ expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW), query).not.toBeNull();
198
+ }
199
+ expect(scoreThreadSearch("trim lakebed", subject, NOW)).toBeNull();
200
+ });
201
+
202
+ it("forgives one typo only when nothing matches exactly", () => {
203
+ const threads = [thread("Hosting alternatives to Railway"), thread("Trim MCP model lists")];
204
+ expect(rankTitles("railwya", threads)).toEqual(["Hosting alternatives to Railway"]);
205
+ expect(rankTitles("trim mpc", threads)).toEqual(["Trim MCP model lists"]);
206
+ expect(
207
+ rankTitles("drga", [thread("Restore drag handles"), thread("Organize indicators")]),
208
+ ).toEqual(["Restore drag handles"]);
209
+ expect(rankTitles("22889", [thread("Stats", { pullRequests: [{ number: 22189 }] })])).toEqual(
210
+ [],
211
+ );
212
+ // Words with digits still forgive one.
213
+ expect(rankTitles("t3coed", [thread("t3code perf audit"), thread("Other")])).toEqual([
214
+ "t3code perf audit",
215
+ ]);
216
+ expect(rankTitles("oath2", [thread("Fix oauth2 redirect")])).toEqual(["Fix oauth2 redirect"]);
217
+ // A typo beats a mid-word accident: "ilde" is "idle", not the middle of "Builder".
218
+ expect(
219
+ rankTitles("ilde", [thread("Typesafe App Builder"), thread("De-risk idle tunnel cleanup")]),
220
+ ).toEqual(["De-risk idle tunnel cleanup", "Typesafe App Builder"]);
221
+ // "ing" is not "Nightly": a three-letter typo keeps the first letter.
222
+ expect(rankTitles("ing", [thread("Nightly build fix")])).toEqual([]);
223
+ // A short word may miss one letter while it is typed, but not change one.
224
+ expect(rankTitles("srv", [thread("Server restart"), thread("Other")])).toEqual([
225
+ "Server restart",
226
+ ]);
227
+ expect(rankTitles("sidb", [thread("Fix sidebar lag")])).toEqual(["Fix sidebar lag"]);
228
+ expect(rankTitles("cron", [thread("Config cleanup")])).toEqual([]);
229
+ // Filler words in a phrase-style query are not required, but alone they are.
230
+ expect(rankTitles("fix the sidebar", [thread("Fix Sidebar Lag")])).toEqual(["Fix Sidebar Lag"]);
231
+ expect(rankTitles("the", [thread("Fix sidebar lag")])).toEqual([]);
232
+ // A typed straight apostrophe finds a curly one.
233
+ expect(rankTitles("don't", [thread("Don’t merge yet")])).toEqual(["Don’t merge yet"]);
234
+ // Typos count across camelCase joins.
235
+ expect(rankTitles("githbu", [thread("GitHub API usage"), thread("Other")])).toEqual([
236
+ "GitHub API usage",
237
+ ]);
238
+ expect(rankTitles("macso", [thread("Fix macOS window"), thread("Other")])).toEqual([
239
+ "Fix macOS window",
240
+ ]);
241
+ // "enter" is not "external" when the right thread is already there.
242
+ expect(
243
+ rankTitles("cmd enter", [thread("Fix Cmd+Enter"), thread("Open links external")]),
244
+ ).toEqual(["Fix Cmd+Enter"]);
245
+ });
246
+});
247
+
248
+describe("queries that fold to empty words", () => {
249
+ it("returns for a hash and a space, or marks that fold to nothing", () => {
250
+ expect(rankTitles("# fix", [thread("Fix sidebar lag")])).toEqual(["Fix sidebar lag"]);
251
+ expect(rankTitles("#", [thread("Fix sidebar lag")])).toEqual([]);
252
+ expect(rankTitles("´´´", [thread("Fix sidebar lag")])).toEqual([]);
253
+ expect(scoreSearchTerms("# fix", ["Fix sidebar"])).toBeNull();
254
+ expect(findSearchTokenRanges("Fix sidebar", "´´´")).toEqual([]);
255
+ expect(scoreMessageMatch("Fix sidebar", "´´´")).toBeNull();
256
+ });
257
+});
258
+
259
+describe("scoreThreadSearch beyond Latin text and titles", () => {
260
+ it("leaves out a row whose words only meet across unrelated fields", () => {
261
+ const scattered = thread("eMudhra certificate update request", {
262
+ pullRequests: [
263
+ { number: 22645, title: "fix model picker" },
264
+ { number: 22649, title: "CI speedups" },
265
+ ],
266
+ });
267
+ expect(scoreThreadSearch("fix ci", scattered, NOW)).toBeNull();
268
+ // The project explains its own words; one field explains the rest.
269
+ const lakebed = thread("Weekly notes", {
270
+ projectTitle: "lakebed",
271
+ pullRequests: [{ number: 243, title: "perf: faster cold starts" }],
272
+ });
273
+ expect(scoreThreadSearch("lakebed perf", lakebed, NOW)?.explain?.()).toEqual({
274
+ label: "PR",
275
+ text: "#243 perf: faster cold starts",
276
+ ranges: [{ start: 5, end: 9 }],
277
+ });
278
+ });
279
+
280
+ it("says which field matched when the title does not", () => {
281
+ const subject = thread("Trim model lists", {
282
+ branch: "t3/cleanup-payloads",
283
+ pullRequests: [{ number: 22889, title: "Smaller MCP payloads" }],
284
+ });
285
+ for (const query of ["#22889", "pr 22889", "pr22889", "pull request #22889"]) {
286
+ expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW)?.explain?.(), query).toEqual({
287
+ label: "PR",
288
+ text: "#22889 Smaller MCP payloads",
289
+ ranges: [{ start: 1, end: 6 }],
290
+ });
291
+ }
292
+ // The app's own worktree prefix is not part of what the branch says.
293
+ expect(scoreThreadSearch("cleanup", subject, NOW)?.explain?.()).toEqual({
294
+ label: "Branch",
295
+ text: "cleanup-payloads",
296
+ ranges: [{ start: 0, end: 7 }],
297
+ });
298
+ expect(scoreThreadSearch("trim", subject, NOW)?.explain?.()).toBeUndefined();
299
+ });
300
+
301
+ it("reads letters and numbers typed together, without forgiving typos in numbers", () => {
302
+ const threads = [
303
+ thread("Upgrade to pnpm 12"),
304
+ thread("GPT-5 eval"),
305
+ thread("iOS 26 support"),
306
+ thread("Other"),
307
+ ];
308
+ expect(rankTitles("pnpm12", threads)).toEqual(["Upgrade to pnpm 12"]);
309
+ expect(rankTitles("gpt5", threads)).toEqual(["GPT-5 eval"]);
310
+ expect(rankTitles("ios26", threads)).toEqual(["iOS 26 support"]);
311
+ expect(rankTitles("pnpm13", threads)).toEqual([]);
312
+ });
313
+
314
+ it("reads whole words typed together, but not scattered letters", () => {
315
+ const threads = [
316
+ thread("VS Code extension settings"),
317
+ thread("Fix UI bug in sidebar"),
318
+ thread("I plan to open source all of lakebed in the next few weeks"),
319
+ ];
320
+ expect(rankTitles("vscode", threads)).toEqual(["VS Code extension settings"]);
321
+ expect(rankTitles("fixuibug", threads)).toEqual(["Fix UI bug in sidebar"]);
322
+ expect(rankTitles("lint", threads)).toEqual([]);
323
+ // Short words before a mere prefix are a coincidence.
324
+ expect(rankTitles("inth", [thread("Show skill names in thread overview")])).toEqual([]);
325
+ expect(rankTitles("tos", [thread("Move Client State to Server")])).toEqual([]);
326
+ expect(rankTitles("t3co", [thread("T3 Code vs Gemini")])).toEqual(["T3 Code vs Gemini"]);
327
+ expect(rankTitles('"sidebar lag"', [thread("Fix sidebar lag")])).toEqual(["Fix sidebar lag"]);
328
+ // A pasted query with a separate accent mark matches the composed title.
329
+ expect(rankTitles("cafe\u0301", [thread("Café menu")])).toEqual(["Café menu"]);
330
+ // Three letters of the last word are enough, as it is typed.
331
+ expect(rankTitles("gomod", [thread("Migrate to Go modules")])).toEqual([
332
+ "Migrate to Go modules",
333
+ ]);
334
+ // Joined words beat an earlier match inside a word.
335
+ expect(scoreThreadSearch("vscode", thread("Fixvscode and VS Code"), NOW)?.quality).toBe(0.6);
336
+ // A strong match elsewhere does not hide joined words.
337
+ expect(
338
+ rankTitles("vscode", [
339
+ thread("VS Code remote support"),
340
+ thread("Old work", { branch: "vscode", activityAt: NOW - 400 * DAY }),
341
+ ]),
342
+ ).toContain("VS Code remote support");
343
+ });
344
+
345
+ it("stores picked queries without splitting an emoji", () => {
346
+ expect(pickedQuery(`${"a".repeat(31)}🚀`)).toBe("a".repeat(31));
347
+ expect(pickedQuery(" Upl ")).toBe("upl");
348
+ // Folded before it is cut, as stored and as compared.
349
+ const spaced = "investigate workspace thread reset bug";
350
+ expect(pickedQuery(spaced)).toBe(pickedQuery(foldSearchQuery(spaced)));
351
+ });
352
+
353
+ it("matches emoji in titles", () => {
354
+ expect(rankTitles("🚀", [thread("🚀 Launch checklist"), thread("Launch notes")])).toEqual([
355
+ "🚀 Launch checklist",
356
+ ]);
357
+ });
358
+
359
+ it("treats each Chinese or Japanese character as a word start", () => {
360
+ expect(scoreThreadSearch("搜索", thread("实现全文搜索"), NOW)).not.toBeNull();
361
+ expect(scoreThreadSearch("検索", thread("新しい検索機能"), NOW)).not.toBeNull();
362
+ });
363
+});
364
+
365
+describe("scoreThreadSearch with heavy use and loose input", () => {
366
+ it("keeps a whole word on a quiet thread above a mid-word hit on a thread opened daily", () => {
367
+ let opens = recordThreadOpen(null, NOW - 60 * DAY, undefined);
368
+ for (let day = 59; day >= 1; day--) opens = recordThreadOpen(opens, NOW - day * DAY, undefined);
369
+ expect(
370
+ rankTitles("auth", [
371
+ thread("Fix oauth redirect", { activityAt: NOW, opens }),
372
+ thread("Share auth across worktrees", { activityAt: NOW - 90 * DAY }),
373
+ ]),
374
+ ).toEqual(["Share auth across worktrees", "Fix oauth redirect"]);
375
+ });
376
+
377
+ it("reads a word and the start of the next typed together, highlighting each part", () => {
378
+ const threads = [thread("Fix sidebar lag"), thread("Unrelated work")];
379
+ expect(rankTitles("fixsid", threads)).toEqual(["Fix sidebar lag"]);
380
+ // A later "F" can start the run.
381
+ expect(rankTitles("fixsid", [thread("Feature: Fix sidebar lag")])).toEqual([
382
+ "Feature: Fix sidebar lag",
383
+ ]);
384
+ expect(scoreThreadSearch("fixsid", threads[0]!, NOW)?.ranges).toEqual([
385
+ { start: 0, end: 3 },
386
+ { start: 4, end: 7 },
387
+ ]);
388
+ // Initials are not words typed together.
389
+ expect(rankTitles("fsl", threads)).toEqual([]);
390
+ });
391
+
392
+ it("finds nothing rather than an unrelated thread when no word matches", () => {
393
+ const threads = [
394
+ thread("Projectless threads without Git"),
395
+ thread("Concern about connection setup"),
396
+ thread("Simplify worktree thread creation"),
397
+ thread("Start a new conversation"),
398
+ thread("Setting up the sentinel"),
399
+ thread("I plan to open source all of lakebed in the next few weeks"),
400
+ thread("Design notes"),
401
+ thread("Link pull request to thread"),
402
+ ];
403
+ for (const query of ["posthog", "cron", "stripe", "gpu", "fxsb", "lint", "deno"]) {
404
+ expect(rankTitles(query, threads), query).toEqual([]);
405
+ }
406
+ });
407
+
408
+ it("matches pieces of references that hold a number, and environment names", () => {
409
+ const subject = thread("Trim model lists", {
410
+ id: "thread-5fe6f59c-4976",
411
+ environmentLabel: "BeeBox",
412
+ pullRequests: [
413
+ {
414
+ number: 22889,
415
+ references: ["pingdotgg/t3code#22889", "https://github.com/pingdotgg/t3code/pull/22889"],
416
+ },
417
+ ],
418
+ });
419
+ for (const query of [
420
+ "t3code#22889",
421
+ "github.com/pingdotgg/t3code/pull/22889",
422
+ "https://github.com/pingdotgg/t3code/pull/22889/files",
423
+ "5fe6f59c",
424
+ "beebox",
425
+ ]) {
426
+ expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW), query).not.toBeNull();
427
+ }
428
+ expect(scoreThreadSearch("github.com", subject, NOW)).toBeNull();
429
+ // A number is never cut short.
430
+ for (const query of ["github.com/pingdotgg/t3code/pull/2288", "t3code#2288"]) {
431
+ expect(scoreThreadSearch(foldSearchQuery(query), subject, NOW), query).toBeNull();
432
+ }
433
+ });
434
+});
435
+
436
+describe("rankMessageMatches", () => {
437
+ it("merges environments by word match, then picks, then quality and use", () => {
438
+ const subjects = new Map([
439
+ ["a-word", thread("A word")],
440
+ ["a-word-2", thread("A word too")],
441
+ ["b-prefix", thread("B prefix")],
442
+ ["b-recent", thread("B recent", { activityAt: NOW })],
443
+ [
444
+ "b-picked",
445
+ thread("B picked", {
446
+ opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "needle", at: NOW - DAY }] },
447
+ }),
448
+ ],
449
+ ]);
450
+ // Environment A sent two whole words, environment B a prefix and two more.
451
+ const matches = [
452
+ { key: "a-word", quality: 1 },
453
+ { key: "a-word-2", quality: 1 },
454
+ { key: "b-prefix", quality: 0.8 },
455
+ { key: "b-recent", quality: 1 },
456
+ { key: "b-picked", quality: 0.8 },
457
+ ];
458
+ expect(
459
+ rankMessageMatches(matches, (match) => subjects.get(match.key), "needle", NOW).map(
460
+ (match) => match.key,
461
+ ),
462
+ ).toEqual(["b-picked", "b-recent", "a-word", "a-word-2", "b-prefix"]);
463
+ // A palette lists title matches above, so they use up no message rows.
464
+ const titled = new Map([...subjects, ["c-titled", thread("Needle cleanup")]]);
465
+ expect(
466
+ rankMessageMatches(
467
+ [{ key: "c-titled", quality: 1 }, ...matches],
468
+ (match) => titled.get(match.key),
469
+ "needle",
470
+ NOW,
471
+ { withoutTitleMatches: true },
472
+ ).map((match) => match.key),
473
+ ).not.toContain("c-titled");
474
+ });
475
+
476
+ it("ranks a thread that keeps using the word above a passing mention of equal quality", () => {
477
+ // The real case: 21 hits seven weeks back against one this week, opened today.
478
+ const subjects = new Map([
479
+ [
480
+ "mention",
481
+ thread("Mention", {
482
+ activityAt: NOW - 3 * DAY,
483
+ opens: { openedAt: NOW, score: 1, picks: [] },
484
+ }),
485
+ ],
486
+ ["about", thread("About it", { activityAt: NOW - 48 * DAY })],
487
+ ]);
488
+ const matches = [
489
+ { key: "mention", quality: 1, hits: 1 },
490
+ { key: "about", quality: 1, hits: 21 },
491
+ ];
492
+ expect(
493
+ rankMessageMatches(matches, (match) => subjects.get(match.key), "tailscale", NOW).map(
494
+ (match) => match.key,
495
+ ),
496
+ ).toEqual(["about", "mention"]);
497
+ });
498
+
499
+ it("keeps matches inside words below word matches, however used", () => {
500
+ const busy = thread("Busy", {
501
+ activityAt: NOW,
502
+ opens: { openedAt: NOW, score: 20, picks: [] },
503
+ });
504
+ const matches = [
505
+ { key: "busy", quality: 0.3 },
506
+ { key: "quiet", quality: 1 },
507
+ ];
508
+ const subjects = new Map([
509
+ ["busy", busy],
510
+ ["quiet", thread("Quiet")],
511
+ ]);
512
+ expect(
513
+ rankMessageMatches(matches, (match) => subjects.get(match.key), "rust", NOW).map(
514
+ (match) => match.key,
515
+ ),
516
+ ).toEqual(["quiet", "busy"]);
517
+ });
518
+});
519
+
520
+describe("rankSearchGroups", () => {
521
+ it("orders groups by their best match and keeps the given order on ties", () => {
522
+ const groups = rankSearchGroups(
523
+ [
524
+ { group: "actions", items: ["Open settings", "New thread"] },
525
+ { group: "threads", items: ["Settings sync rewrite", "Thread settings"] },
526
+ { group: "projects", items: ["Settings app"] },
527
+ ],
528
+ (item, options) => scoreSearchTerms("settings", [item], options),
529
+ );
530
+ expect(groups.map(({ group, ranked }) => [group, ranked.map(({ item }) => item)])).toEqual([
531
+ ["actions", ["Open settings"]],
532
+ ["threads", ["Settings sync rewrite", "Thread settings"]],
533
+ ["projects", ["Settings app"]],
534
+ ]);
535
+ });
536
+});
537
+
538
+describe("rankSearchGroups with keywords and picks", () => {
539
+ it("matches inside a word only in thread titles", () => {
540
+ expect(scoreSearchTerms("arch", ["Search project contents"])).toBeNull();
541
+ expect(
542
+ scoreThreadSearch("arch", thread("Notes", { branch: "research-extension-system" }), NOW),
543
+ ).toBeNull();
544
+ expect(scoreThreadSearch("arch", thread("Research notes"), NOW)?.quality).toBe(0.3);
545
+ });
546
+
547
+ it("forgives typos in names but not in hidden keywords", () => {
548
+ const groups = rankSearchGroups(
549
+ [
550
+ { group: "actions", items: [["Open settings", "preferences", "keybindings"]] },
551
+ { group: "settings", items: [["Keybindings", "General"]] },
552
+ ],
553
+ (terms, options) => scoreSearchTerms("keybindngs", terms, options),
554
+ );
555
+ expect(groups.map(({ group }) => group)).toEqual(["settings"]);
556
+ expect(scoreSearchTerms("duckdb", ["Search engine", "duckduckgo"], { typos: true })).toBeNull();
557
+ expect(scoreSearchTerms("rust", ["GitHub sharing", "trusted"])).toBeNull();
558
+ // Filler words do not make a short query long enough for keyword prefixes.
559
+ expect(scoreSearchTerms("the ci", ["Context window indicator", "circle"])).toBeNull();
560
+ });
561
+
562
+ it("lists a thread named for the query above a command with it as a keyword", () => {
563
+ const rank = (command: string[], subject: ThreadSearchSubject) =>
564
+ rankSearchGroups<string, string[] | ThreadSearchSubject, SearchTermsMatch>(
565
+ [
566
+ { group: "actions", items: [command] },
567
+ { group: "threads", items: [subject] },
568
+ ],
569
+ (item, options) => {
570
+ if (Array.isArray(item)) return scoreSearchTerms("mcp", item, options);
571
+ return scoreThreadSearch("mcp", item, NOW, options);
572
+ },
573
+ ).map(({ group }) => group);
574
+ const named = thread("Trim MCP model lists");
575
+ const picked = thread("Trim MCP model lists", {
576
+ opens: { openedAt: NOW, score: 1, picks: [{ query: "mcp", at: NOW }] },
577
+ });
578
+ expect(rank(["Restart agent session", "reload", "mcp"], named)).toEqual(["threads", "actions"]);
579
+ // A command named for the query stays first; a pick reorders threads but
580
+ // never moves their group, so one pick for "mcp" does not pass the command.
581
+ expect(rank(["Reload MCP servers"], named)).toEqual(["actions", "threads"]);
582
+ expect(rank(["Reload MCP servers"], picked)).toEqual(["actions", "threads"]);
583
+ });
584
+});
585
+
586
+describe("recordThreadOpen", () => {
587
+ it("decays the open count, merges quick reopens, and keeps the latest picked queries", () => {
588
+ const first = recordThreadOpen(null, NOW, " Upl ");
589
+ expect(first).toEqual({ openedAt: NOW, score: 1, picks: [{ query: "upl", at: NOW }] });
590
+ const reopened = recordThreadOpen(first, NOW + 60_000, "uploadthing");
591
+ expect(reopened).toEqual({
592
+ openedAt: NOW,
593
+ score: 1,
594
+ picks: [
595
+ { query: "uploadthing", at: NOW + 60_000 },
596
+ { query: "upl", at: NOW },
597
+ ],
598
+ });
599
+ const later = recordThreadOpen(reopened, NOW + SEARCH_RECENCY_HALF_LIFE_MS, "x".repeat(50));
600
+ expect(later.score).toBe(1.5);
601
+ expect(later.picks.map((pick) => pick.query)).toEqual(["x".repeat(32), "uploadthing", "upl"]);
602
+ const repicked = recordThreadOpen(later, later.openedAt + DAY, "upl");
603
+ expect(repicked.picks).toEqual([
604
+ { query: "upl", at: later.openedAt + DAY },
605
+ { query: "x".repeat(32), at: later.openedAt },
606
+ { query: "uploadthing", at: NOW + 60_000 },
607
+ ]);
608
+ });
609
+
610
+ it("drops picks that no longer count when the thread is opened again", () => {
611
+ const opens = {
612
+ openedAt: NOW - 30 * DAY,
613
+ score: 1,
614
+ picks: [{ query: "old", at: NOW - 30 * DAY }],
615
+ };
616
+ expect(recordThreadOpen(opens, NOW, "new").picks).toEqual([{ query: "new", at: NOW }]);
617
+ });
618
+
619
+ it("does not renew a query's pick when the thread is picked for another one", () => {
620
+ const deploy = [
621
+ thread("Deploy notes", {
622
+ opens: {
623
+ openedAt: NOW,
624
+ score: 2,
625
+ picks: [
626
+ { query: "scripts", at: NOW },
627
+ { query: "deploy", at: NOW - 60 * DAY },
628
+ ],
629
+ },
630
+ }),
631
+ thread("Deploy timeout", {
632
+ opens: { openedAt: NOW - DAY, score: 1, picks: [{ query: "deploy", at: NOW - DAY }] },
633
+ }),
634
+ ];
635
+ expect(rankTitles("deploy", deploy)).toEqual(["Deploy timeout", "Deploy notes"]);
636
+ });
637
+});
638
+
639
+describe("findSearchTokenRanges", () => {
640
+ it("maps folded matches back to the source text and skips short tokens", () => {
641
+ const text = "Le Café résumé ci";
642
+ expect(findSearchTokenRanges(text, "CAFE resume ci")).toEqual([
643
+ { start: 3, end: 7 },
644
+ { start: 8, end: 14 },
645
+ ]);
646
+ });
647
+
648
+ it("highlights a three-letter token only where it starts a word", () => {
649
+ expect(findSearchTokenRanges("drafts, enableFTS", "fts")).toEqual([{ start: 14, end: 17 }]);
650
+ expect(findSearchTokenRanges("Open handlers.ts", ".ts")).toEqual([{ start: 13, end: 16 }]);
651
+ });
652
+});
653
+
654
+describe("scoreMessageMatch", () => {
655
+ it("needs short words at a word start and ranks other words found inside words lower", () => {
656
+ const text = `Saved the drafts. ${"More notes. ".repeat(40)}Then enableFTS and Enable FTS.`;
657
+ const fts = scoreMessageMatch(text, "fts");
658
+ expect(fts?.quality).toBe(1);
659
+ expect(text.slice(fts?.offset)).toMatch(/^FTS and/);
660
+ expect(scoreMessageMatch("saved two drafts", "fts")).toBeNull();
661
+ expect(scoreMessageMatch("We trust the build", "rust")).toEqual({ quality: 0.3, offset: 4 });
662
+ expect(scoreMessageMatch("Rust and trust", "rust")).toEqual({ quality: 1, offset: 0 });
663
+ expect(scoreMessageMatch("Use the sidebar", '"sidebar"')).toEqual({ quality: 1, offset: 8 });
664
+ // Words written together as typed rank above the same words apart, and
665
+ // the snippet starts where they are together.
666
+ const together = "Run the tests, then vp run dev to check";
667
+ expect(scoreMessageMatch(together, "vp run dev")).toEqual({
668
+ quality: 1.25,
669
+ offset: together.indexOf("vp run dev"),
670
+ });
671
+ // Near each other ranks above far apart.
672
+ expect(scoreMessageMatch("dev notes: vp is slow, run it", "vp run dev")?.quality).toBe(1.1);
673
+ const far = `run the tests. ${"More notes. ".repeat(10)}Then dev mode, then vp`;
674
+ expect(scoreMessageMatch(far, "vp run dev")?.quality).toBe(1);
675
+ expect(scoreMessageMatch("I don\u2019t know why", "don't know")?.quality).toBe(1.25);
676
+ expect(scoreMessageMatch("Le Café open late", "cafe open")?.quality).toBe(1.25);
677
+ expect(scoreMessageMatch("The cafe open late", "café open")?.quality).toBe(1.25);
678
+ // The snippet starts where the words meet, not at an early one.
679
+ const phrase = `The plan. ${"More notes. ".repeat(10)}Since the last fix, the sidebar works`;
680
+ expect(scoreMessageMatch(phrase, "fix the sidebar")?.offset).toBe(phrase.indexOf("fix,"));
681
+ const apart = `The lakebed app. ${"Notes. ".repeat(30)}Lakebed page perf is slow`;
682
+ expect(apart.slice(scoreMessageMatch(apart, "lakebed perf")?.offset)).toMatch(/^Lakebed page/);
683
+ // Only where a word counts: not "fix" in "prefix".
684
+ const prefix = `fix ${"unrelated words ".repeat(40)}prefix has CI`;
685
+ expect(scoreMessageMatch(prefix, "fix ci")?.offset).toBe(0);
686
+ // A commit SHA is one word: "cafe" inside one does not match, its start does.
687
+ expect(scoreMessageMatch("see commit 7cafe52bb8", "cafe")).toBeNull();
688
+ expect(scoreMessageMatch("see commit 7cafe52bb8", "7cafe52")).toEqual({
689
+ quality: 1,
690
+ offset: 11,
691
+ });
692
+ expect(scoreMessageMatch("7cafe52bb8, then the cafe", "cafe")?.quality).toBe(1);
693
+ // A whole word beats a word prefix: "mode" prefers "mode" over "model".
694
+ expect(scoreMessageMatch("model settings", "mode")?.quality).toBe(0.8);
695
+ expect(scoreMessageMatch("The model and the mode switch", "mode")).toEqual({
696
+ quality: 1,
697
+ offset: 18,
698
+ });
699
+ expect(scoreMessageMatch("v12rc build", "rc")?.quality).toBe(1);
700
+ expect(scoreMessageMatch("Fix the CLIAdapter state", "ada")?.quality).toBe(0.8);
701
+ // Words too short for the index must start a word too.
702
+ expect(scoreMessageMatch("Switch off the connection", "switch on")).toBeNull();
703
+ expect(scoreMessageMatch("Upgrade pnpm 512 today", "pnpm 12")).toBeNull();
704
+ expect(scoreMessageMatch("Upgrade to pnpm12 today", "pnpm 12")?.quality).toBe(1);
705
+ // A word too short to search only narrows, so typing the next word
706
+ // ("nvme s") does not reorder results; written together still counts.
707
+ expect(scoreMessageMatch("Fix circle rendering", "fix ci")?.quality).toBe(1);
708
+ expect(scoreMessageMatch("Fix CI failures", "fix ci")?.quality).toBe(1.25);
709
+ expect(scoreMessageMatch("Upgrade pnpm 123 today", "pnpm 12")?.quality).toBe(1);
710
+ expect(scoreMessageMatch("Rename the file to index.ts", ".ts")?.quality).toBe(1);
711
+ });
712
+
713
+ it("finds words through case and accents, also after the same letters inside a word", () => {
714
+ expect(scoreMessageMatch("This addresses Résumé indexing", "res")).toMatchObject({
715
+ offset: 15,
716
+ });
717
+ expect(scoreMessageMatch("Le CAFÉ ouvert", "cafe")).toMatchObject({ quality: 1, offset: 3 });
718
+ // An accented whole word beats a plain prefix earlier on.
719
+ expect(scoreMessageMatch("The cafeteria, then the Café", "cafe")).toMatchObject({
720
+ quality: 1,
721
+ offset: 24,
722
+ });
723
+ expect(scoreMessageMatch("I presume this. Résumé indexing", "resume")).toMatchObject({
724
+ quality: 1,
725
+ offset: 16,
726
+ });
727
+ expect(scoreMessageMatch("明天部署到生产环境", "部署")).toMatchObject({ offset: 2 });
728
+ // Vietnamese and combining accents fold too.
729
+ expect(scoreMessageMatch("Properties: tiếng Việt support", "tie")).toMatchObject({
730
+ offset: 12,
731
+ });
732
+ expect(scoreMessageMatch("Properties: tie\u0301ng support", "tie")).toMatchObject({
733
+ offset: 12,
734
+ });
735
+ // A letter that grows when lowercased does not shift later offsets.
736
+ expect(scoreMessageMatch("İ Enable fts and model", "fts")).toMatchObject({ offset: 9 });
737
+ expect(scoreMessageMatch("İ Enable fts and model", "model")?.quality).toBe(1);
738
+ expect(scoreMessageMatch("Trip to İstanbul", "İstanbul")).toEqual({ quality: 1, offset: 8 });
739
+ });
740
+});
packages/shared/src/paletteSearch.ts
new
+1260
@@ -0,0 +1,1260 @@
1
+/**
2
+ * Word-aware fuzzy ranking for the command palettes (web, desktop, mobile) and
3
+ * the MCP thread search, so every surface puts the same thread first.
4
+ *
5
+ * A match scores by quality: a whole word beats a word prefix, which beats
6
+ * words typed together, a one-typo prefix, and then a mid-word substring.
7
+ * Word starts include camelCase, kebab, path, and letter/digit boundaries.
8
+ * Thread scores then multiply quality by how recently and often the thread
9
+ * was used, within limits.
10
+ */
11
+
12
+import type { OrchestrationV2ThreadOpens } from "@t3tools/contracts";
13
+
14
+import { WORKTREE_BRANCH_PREFIX } from "./git.ts";
15
+
16
+const ALPHANUMERIC = /[\p{L}\p{N}]/u;
17
+const LOWERCASE = /\p{Ll}/u;
18
+const UPPERCASE = /\p{Lu}/u;
19
+const DIGIT = /\p{N}/u;
20
+const LETTER = /\p{L}/u;
21
+const COMBINING_MARKS = /\p{M}/gu;
22
+// Emoji and other symbols can be searched for, so they start words too.
23
+const SYMBOL = /\p{So}/u;
24
+const APOSTROPHE = /['’]/;
25
+const CURLY_APOSTROPHES = /[\u2018\u2019]/g;
26
+
27
+interface SearchField {
28
+ /** Case- and accent-folded text, one UTF-16 unit per source unit. */
29
+ readonly text: string;
30
+ /** 1 where a word starts in `text`. */
31
+ readonly wordStarts: Uint8Array;
32
+}
33
+
34
+export interface SearchRange {
35
+ readonly start: number;
36
+ readonly end: number;
37
+}
38
+
39
+// Thread titles, branches, and project names repeat across keystrokes; folding
40
+// them once keeps a keystroke to plain string scans. Each keystroke reads every
41
+// field, so the limit must hold all of them or the cache clears every time; a
42
+// field is a few bytes per character.
43
+const fieldCache = new Map<string, SearchField>();
44
+const FIELD_CACHE_LIMIT = 100_000;
45
+
46
+function foldCharacter(character: string): string {
47
+ // A typed straight apostrophe finds a curly one: iOS keyboards type "’".
48
+ return character
49
+ .normalize("NFKD")
50
+ .replace(COMBINING_MARKS, "")
51
+ .toLowerCase()
52
+ .replace("ς", "σ")
53
+ .replace(/[‘’]/, "'");
54
+}
55
+
56
+/**
57
+ * `text` with case and accents folded one UTF-16 unit at a time, so offsets
58
+ * and word starts still read from `text` and highlights need no mapping. A
59
+ * letter that folds to more or less than one unit ("ß", "fi") stays as it is.
60
+ */
61
+function foldInPlace(text: string): string {
62
+ return text
63
+ .replace(/[\u0080-\uffff]/g, (character) => {
64
+ const folded = foldCharacter(character);
65
+ return folded.length === 1 ? folded : character;
66
+ })
67
+ .toLowerCase();
68
+}
69
+
70
+// Chinese and Japanese text has no spaces, so each ideograph or kana starts a word.
71
+function isCjk(character: string): boolean {
72
+ const code = character.codePointAt(0)!;
73
+ return (
74
+ (code >= 0x3040 && code <= 0x30ff) ||
75
+ (code >= 0x3400 && code <= 0x4dbf) ||
76
+ (code >= 0x4e00 && code <= 0x9fff) ||
77
+ (code >= 0xf900 && code <= 0xfaff)
78
+ );
79
+}
80
+
81
+// Two Chinese, Japanese, or Korean characters already make a common word.
82
+function hasCjkWord(token: string): boolean {
83
+ return Array.from(token).some((character) => {
84
+ const code = character.codePointAt(0)!;
85
+ return isCjk(character) || (code >= 0xac00 && code <= 0xd7af);
86
+ });
87
+}
88
+
89
+/**
90
+ * Whether `character` starts a word after `previous` and `beforePrevious`
91
+ * ("" at the start): after a non-letter, at a camelCase or digit boundary, or
92
+ * at any Chinese or Japanese character. The one rule for titles and messages.
93
+ */
94
+function isWordStart(
95
+ beforePrevious: string,
96
+ previous: string,
97
+ character: string,
98
+ next: string,
99
+): boolean {
100
+ // "Julius’s": a possessive or contraction does not start a word.
101
+ const afterApostrophe = APOSTROPHE.test(previous) && ALPHANUMERIC.test(beforePrevious);
102
+ return (
103
+ (ALPHANUMERIC.test(character) || SYMBOL.test(character)) &&
104
+ !afterApostrophe &&
105
+ (previous === "" ||
106
+ !ALPHANUMERIC.test(previous) ||
107
+ (LOWERCASE.test(previous) && UPPERCASE.test(character)) ||
108
+ // The last capital of an acronym starts the next word: "JSONSchema".
109
+ (UPPERCASE.test(previous) && UPPERCASE.test(character) && LOWERCASE.test(next)) ||
110
+ DIGIT.test(previous) !== DIGIT.test(character) ||
111
+ isCjk(character))
112
+ );
113
+}
114
+
115
+function foldSearchField(source: string): SearchField {
116
+ const wordStarts = new Uint8Array(source.length);
117
+ const characters = Array.from(source);
118
+ let index = 0;
119
+ for (const [position, character] of characters.entries()) {
120
+ const previous = characters[position - 1] ?? "";
121
+ const next = characters[position + 1] ?? "";
122
+ if (isWordStart(characters[position - 2] ?? "", previous, character, next)) {
123
+ wordStarts[index] = 1;
124
+ }
125
+ index += character.length;
126
+ }
127
+ return { text: foldInPlace(source), wordStarts };
128
+}
129
+
130
+function prepareSearchField(source: string): SearchField {
131
+ const cached = fieldCache.get(source);
132
+ if (cached) return cached;
133
+ // Oldest first out. A read does not re-insert: that would cost more than the
134
+ // fold it saves, and the limit holds far more fields than a keystroke reads.
135
+ if (fieldCache.size >= FIELD_CACHE_LIMIT) {
136
+ fieldCache.delete(fieldCache.keys().next().value!);
137
+ }
138
+ const field = foldSearchField(source);
139
+ fieldCache.set(source, field);
140
+ return field;
141
+}
142
+
143
+// Quotes around a pasted query: "fix sidebar".
144
+const WRAPPING_QUOTES = /^\s*["'`“”‘’]+|["'`“”‘’]+\s*$/g;
145
+
146
+/** Folded, whitespace-collapsed query; empty when there is nothing to match. */
147
+export function foldSearchQuery(query: string): string {
148
+ return foldInPlace(query.replace(WRAPPING_QUOTES, "").normalize("NFC"))
149
+ .split(/\s+/)
150
+ .filter((token) => token.length > 0)
151
+ .join(" ");
152
+}
153
+
154
+function wordEnd(field: SearchField, index: number): number {
155
+ let end = index + 1;
156
+ while (end < field.text.length && !field.wordStarts[end] && ALPHANUMERIC.test(field.text[end]!)) {
157
+ end++;
158
+ }
159
+ return end;
160
+}
161
+
162
+// One substitution, insertion, deletion, or swap of neighbours; with
163
+// `swapOnly`, only a swap.
164
+function withinOneEdit(left: string, right: string, swapOnly: boolean): boolean {
165
+ if (Math.abs(left.length - right.length) > (swapOnly ? 0 : 1)) return false;
166
+ let index = 0;
167
+ while (index < left.length && index < right.length && left[index] === right[index]) index++;
168
+ const restLeft = left.slice(index);
169
+ const restRight = right.slice(index);
170
+ const swapped =
171
+ restLeft.length > 1 &&
172
+ restLeft[0] === restRight[1] &&
173
+ restLeft[1] === restRight[0] &&
174
+ restLeft.slice(2) === restRight.slice(2);
175
+ if (swapOnly) return swapped;
176
+ return (
177
+ swapped ||
178
+ restLeft === restRight ||
179
+ restLeft.slice(1) === restRight.slice(1) ||
180
+ restLeft.slice(1) === restRight ||
181
+ restLeft === restRight.slice(1)
182
+ );
183
+}
184
+
185
+const WHOLE_WORD = 1;
186
+// The bonus for a field equal to the whole query lifts a whole word to this.
187
+const WHOLE_NAME = 1.5;
188
+const MID_WORD = 0.3;
189
+const TYPO = 0.45;
190
+// Whole words typed together are exact, so they rank with typos and above
191
+// mid-word hits, though below a match at a word start.
192
+const JOINED_WORDS = 0.6;
193
+
194
+interface TokenMatch extends SearchRange {
195
+ readonly score: number;
196
+ /** Separate ranges, for words typed together. */
197
+ readonly letters?: ReadonlyArray<SearchRange>;
198
+}
199
+
200
+/**
201
+ * Best match of one folded query token in a field. Tokens shorter than four
202
+ * characters only match at a word start ("del" should not find "model"), and
203
+ * longer ones only inside a word where `midWord` allows it. With
204
+ * `typos`, a three-character token may swap a pair and a longer one may carry
205
+ * one typo in a word prefix that keeps its first letter. Numbers never match
206
+ * with a typo: 22889 is not pull request 22189. In the primary field (the
207
+ * name), the token may also be whole words typed together (see
208
+ * `matchJoinedWords`).
209
+ */
210
+function matchToken(
211
+ field: SearchField,
212
+ token: string,
213
+ typos: boolean,
214
+ isPrimary: boolean,
215
+ midWord: boolean,
216
+): TokenMatch | null {
217
+ if (token.length === 0) return null;
218
+ let best: TokenMatch | null = null;
219
+ const ownBoundary = !ALPHANUMERIC.test(token[0]!) && !SYMBOL.test(token[0]!);
220
+ for (
221
+ let index = field.text.indexOf(token);
222
+ index !== -1;
223
+ index = field.text.indexOf(token, index + 1)
224
+ ) {
225
+ // A token that opens with punctuation (".ts") brings its own boundary, as in messages.
226
+ if (field.wordStarts[index] || ownBoundary) {
227
+ // Whole when the match ends where a word ends: "t3c" is a prefix of
228
+ // "t3code", ".ts" whole in "index.ts" but a prefix in "parser.tsx".
229
+ const end = index + token.length;
230
+ const whole =
231
+ end >= field.text.length ||
232
+ field.wordStarts[end] === 1 ||
233
+ !ALPHANUMERIC.test(field.text[end]!);
234
+ let runEnd = end;
235
+ while (runEnd < field.text.length && ALPHANUMERIC.test(field.text[runEnd]!)) runEnd++;
236
+ const score = whole ? WHOLE_WORD : 0.7 + (0.2 * token.length) / (runEnd - index);
237
+ if (best === null || score > best.score) {
238
+ best = { score, start: index, end: index + token.length };
239
+ }
240
+ if (score === WHOLE_WORD) return best;
241
+ } else if (midWord && token.length >= 4 && best === null) {
242
+ best = { score: MID_WORD, start: index, end: index + token.length };
243
+ }
244
+ }
245
+ // Joined words are exact, so they count without the typo pass: a strong
246
+ // match elsewhere must not hide "VS Code" for "vscode".
247
+ if ((best === null || best.score <= MID_WORD) && isPrimary) {
248
+ const joined = matchJoinedWords(field, token);
249
+ if (joined) return joined;
250
+ }
251
+ if ((best !== null && best.score > MID_WORD) || !typos || token.length < 3) return best;
252
+ // Numbers skip typos: #22889 is not #22189. Words with digits ("t3code") do not.
253
+ if (LETTER.test(token)) {
254
+ for (let index = 0; index < field.text.length; index++) {
255
+ if (!field.wordStarts[index]) continue;
256
+ // People rarely mistype the first letter, so a typo keeps it, unless it
257
+ // swaps the first two of a longer word ("ing" is not "nig…").
258
+ const first = field.text[index];
259
+ const firstLetterKept =
260
+ first === token[0] ||
261
+ (token.length > 3 && first === token[1] && field.text[index + 1] === token[0]);
262
+ if (!firstLetterKept) continue;
263
+ // The whole run, across camelCase joins: "githbu" is "GitHub".
264
+ let runEnd = index + 1;
265
+ while (runEnd < field.text.length && ALPHANUMERIC.test(field.text[runEnd]!)) runEnd++;
266
+ const word = field.text.slice(index, runEnd);
267
+ // Short tokens forgive a swapped pair or one missing letter ("srv" for
268
+ // "serv…"); any other edit of a three- or four-letter word matches too
269
+ // much ("cron" would find every "con…").
270
+ const short = token.length <= 4;
271
+ // The same length first, so "githbu" highlights all of "GitHub".
272
+ const lengths = short
273
+ ? [token.length, token.length + 1]
274
+ : [token.length, token.length - 1, token.length + 1];
275
+ for (const length of lengths) {
276
+ if (length > word.length) continue;
277
+ const prefix = word.slice(0, length);
278
+ if (withinOneEdit(token, prefix, short && length === token.length)) {
279
+ return { score: TYPO, start: index, end: index + length };
280
+ }
281
+ }
282
+ }
283
+ }
284
+ return best;
285
+}
286
+
287
+/**
288
+ * Whole words typed together: "vscode" is "VS Code", "fixsid" is "Fix
289
+ * sid(ebar)". Every part is a whole word but the last. Short words before a
290
+ * short prefix are a coincidence inside a title ("inth" is not "in th(read)"),
291
+ * but not at its start ("t3co" is "T3 Co(de)"), before three letters
292
+ * ("gomod"), or a whole word ("vscode").
293
+ */
294
+function matchJoinedWords(field: SearchField, token: string): TokenMatch | null {
295
+ const firstWord = field.wordStarts.indexOf(1);
296
+ for (let start = 0; start < field.text.length; start++) {
297
+ if (!field.wordStarts[start] || field.text[start] !== token[0]) continue;
298
+ const runs: SearchRange[] = [];
299
+ let at = start;
300
+ let rest = token;
301
+ while (rest.length > 0 && at < field.text.length) {
302
+ const end = wordEnd(field, at);
303
+ if (rest.length <= end - at && field.text.startsWith(rest, at)) {
304
+ runs.push({ start: at, end: at + rest.length });
305
+ rest = "";
306
+ } else if (rest.startsWith(field.text.slice(at, end))) {
307
+ runs.push({ start: at, end });
308
+ rest = rest.slice(end - at);
309
+ at = end;
310
+ while (at < field.text.length && !field.wordStarts[at]) at++;
311
+ } else {
312
+ break;
313
+ }
314
+ }
315
+ const last = runs.at(-1);
316
+ if (rest.length > 0 || last === undefined || runs.length < 2) continue;
317
+ if (
318
+ last.end === wordEnd(field, last.start) ||
319
+ last.end - last.start >= 3 ||
320
+ start === firstWord ||
321
+ runs.slice(0, -1).every((run) => run.end - run.start >= 3)
322
+ ) {
323
+ return { score: JOINED_WORDS, start, end: last.end, letters: runs };
324
+ }
325
+ }
326
+ return null;
327
+}
328
+
329
+interface WeightedSearchField {
330
+ readonly value: string;
331
+ readonly weight: number;
332
+ /** Only a whole-word match counts, as for a short query against keywords. */
333
+ readonly wholeWords?: boolean;
334
+ /**
335
+ * Only a match at a word start counts, without typos: hidden keywords that
336
+ * matched loosely would list results the user cannot see why for.
337
+ */
338
+ readonly keyword?: boolean;
339
+ /**
340
+ * Where the thread lives (project, environment): it helps a match, but a
341
+ * word start there does not make the match strong, so it never turns off
342
+ * joined words or typos for the titles.
343
+ */
344
+ readonly context?: boolean;
345
+ /**
346
+ * A token of four or more letters may match inside a word here. Only thread
347
+ * titles allow it: inside a command name or a branch it reads as junk
348
+ * ("arch" in "Search").
349
+ */
350
+ readonly midWord?: boolean;
351
+}
352
+
353
+interface SearchFieldsMatch {
354
+ /** Roughly 0.3 (inside a word) to 1.5 (exact title). */
355
+ readonly quality: number;
356
+ /** Every token matched at a word start, without a typo. */
357
+ readonly strong: boolean;
358
+ /** Source ranges matched in the first field, for highlighting. */
359
+ readonly primaryRanges: ReadonlyArray<SearchRange>;
360
+}
361
+
362
+const FILLER_WORDS = new Set(["a", "an", "and", "for", "in", "of", "on", "the", "to", "with"]);
363
+
364
+// Sorted, with overlapping ranges joined.
365
+function mergeRanges(ranges: ReadonlyArray<SearchRange>): SearchRange[] {
366
+ const merged: SearchRange[] = [];
367
+ for (const range of [...ranges].sort((left, right) => left.start - right.start)) {
368
+ const last = merged.at(-1);
369
+ if (last && range.start <= last.end) {
370
+ merged[merged.length - 1] = { start: last.start, end: Math.max(last.end, range.end) };
371
+ } else {
372
+ merged.push({ start: range.start, end: range.end });
373
+ }
374
+ }
375
+ return merged;
376
+}
377
+
378
+/**
379
+ * Every query token must match some field. Quality is the mean of each token's
380
+ * best weighted match, plus a bonus when the first field holds the whole query
381
+ * as a phrase or equals it.
382
+ */
383
+function matchSearchFields(
384
+ normalizedQuery: string,
385
+ fields: ReadonlyArray<WeightedSearchField>,
386
+ options?: { readonly typos?: boolean },
387
+): SearchFieldsMatch | null {
388
+ if (normalizedQuery.length === 0) return null;
389
+ const prepared = fields
390
+ .filter((field) => field.value.length > 0)
391
+ .map((field) => ({
392
+ field: prepareSearchField(field.value),
393
+ weight: field.weight,
394
+ wholeWords: field.wholeWords ?? false,
395
+ keyword: field.keyword ?? false,
396
+ context: field.context ?? false,
397
+ allowMidWord: field.midWord ?? false,
398
+ }));
399
+ const primary = fields[0]?.value ? prepared[0]?.field : undefined;
400
+ // An empty token would match everywhere, and loop forever in `matchToken`.
401
+ const tokens = normalizedQuery.split(" ").filter((token) => token.length > 0);
402
+ if (tokens.length === 0) return null;
403
+ // A phrase-style query ("fix the sidebar") carries filler words a name may
404
+ // leave out; they count where they match but are not required.
405
+ const fillerOptional = tokens.some((token) => !FILLER_WORDS.has(token));
406
+ const primaryRanges: SearchRange[] = [];
407
+ let total = 0;
408
+ let counted = 0;
409
+ let strong = true;
410
+ for (const token of tokens) {
411
+ let best = 0;
412
+ let bestPrimary: TokenMatch | null = null;
413
+ let atWordStart = false;
414
+ for (const { field, weight, wholeWords, keyword, context, allowMidWord } of prepared) {
415
+ if (best >= weight && field !== primary && atWordStart) continue;
416
+ const typos = (options?.typos ?? false) && !keyword;
417
+ // Joined words only count in the name.
418
+ const match = matchToken(field, token, typos, field === primary, allowMidWord);
419
+ if (match === null || match.score < (wholeWords ? WHOLE_WORD : keyword ? 0.7 : 0)) continue;
420
+ if (field === primary) bestPrimary = match;
421
+ if (match.score >= 0.7 && !context) atWordStart = true;
422
+ if (match.score * weight > best) best = match.score * weight;
423
+ }
424
+ if (best === 0) {
425
+ if (fillerOptional && FILLER_WORDS.has(token)) continue;
426
+ return null;
427
+ }
428
+ strong &&= atWordStart;
429
+ if (bestPrimary) primaryRanges.push(...(bestPrimary.letters ?? [bestPrimary]));
430
+ total += best;
431
+ counted += 1;
432
+ }
433
+ let quality = total / counted;
434
+ if (primary) {
435
+ if (primary.text === normalizedQuery) quality += WHOLE_NAME - WHOLE_WORD;
436
+ else if (tokens.length > 1 && primary.text.includes(normalizedQuery)) quality += 0.25;
437
+ }
438
+ return {
439
+ quality,
440
+ strong,
441
+ primaryRanges: mergeRanges(primaryRanges),
442
+ };
443
+}
444
+
445
+// A two-letter Latin substring of a message is noise rather than a match.
446
+const MESSAGE_TOKEN_MIN_LENGTH = 3;
447
+
448
+/**
449
+ * Message search tokens, lowercased and NFC-composed but not stripped of
450
+ * accents: the server's index folds Latin accents itself, and stripping marks
451
+ * would break Korean and Japanese text. Every `long` token must appear in a
452
+ * message; `short` ones only narrow those hits ("pnpm 12"). A query with no
453
+ * long token searches no messages. Two CJK characters count as long.
454
+ */
455
+export function messageSearchTokens(query: string): {
456
+ readonly long: ReadonlyArray<string>;
457
+ readonly short: ReadonlyArray<string>;
458
+ /** Every token, in the order typed. */
459
+ readonly words: ReadonlyArray<string>;
460
+} {
461
+ const tokens = query
462
+ .replace(WRAPPING_QUOTES, "")
463
+ // The index stores apostrophes straight, as `indexedMessageText` writes them.
464
+ .replace(CURLY_APOSTROPHES, "'")
465
+ .normalize("NFC")
466
+ .toLowerCase()
467
+ .split(/\s+/)
468
+ .filter((token) => token.length > 0);
469
+ const searchable = (token: string) => {
470
+ const length = Array.from(token).length;
471
+ return length >= MESSAGE_TOKEN_MIN_LENGTH || (length === 2 && hasCjkWord(token));
472
+ };
473
+ return {
474
+ long: tokens.filter(searchable),
475
+ short: tokens.filter((token) => !searchable(token)),
476
+ words: tokens,
477
+ };
478
+}
479
+
480
+/**
481
+ * Matches the query's words side by side as whole words, as typed, whatever
482
+ * whitespace is between them and ignoring case; null for a single word.
483
+ */
484
+export function messagePhrase(query: string): RegExp | null {
485
+ const { words } = messageSearchTokens(query);
486
+ return words.length > 1
487
+ ? new RegExp(
488
+ `(?<![\\p{L}\\p{N}])${words
489
+ .map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
490
+ .join("\\s+")}(?![\\p{L}\\p{N}])`,
491
+ "iu",
492
+ )
493
+ : null;
494
+}
495
+
496
+// Words written together, as typed, rank above the same words apart, as in
497
+// titles; words near each other rank above words far apart.
498
+const MESSAGE_PHRASE_BONUS = 0.25;
499
+const MESSAGE_NEAR_BONUS = 0.1;
500
+// About what a result row shows.
501
+const MESSAGE_NEAR_SPAN = 60;
502
+
503
+const NON_ASCII = /[\u0080-\uffff]/;
504
+// A message token shorter than this must start a word: "fts" is not in "drafts".
505
+const MESSAGE_WORD_START_LENGTH = 4;
506
+const MESSAGE_PREFIX = 0.8;
507
+
508
+function startsWordAt(text: string, index: number): boolean {
509
+ const character = text[index]!;
510
+ // A token that opens with punctuation (".ts", "#22889") brings its own boundary.
511
+ if (!ALPHANUMERIC.test(character) && !SYMBOL.test(character)) return true;
512
+ return isWordStart(
513
+ text[index - 2] ?? "",
514
+ text[index - 1] ?? "",
515
+ character,
516
+ text[index + 1] ?? "",
517
+ );
518
+}
519
+
520
+// Whether a word ends right before `end` in `text`.
521
+function endsWordAt(text: string, end: number): boolean {
522
+ return end >= text.length || !ALPHANUMERIC.test(text[end]!) || startsWordAt(text, end);
523
+}
524
+
525
+// A commit SHA or UUID part: seven or more hex characters with a digit.
526
+const HEX_ID = /^(?=[a-f]*\d)[0-9a-f]{7,}$/i;
527
+
528
+// Where `token` best sits in `folded`, a fold of `text`: every place it is a
529
+// whole word, else a word start, else inside a word. Hits past the start of a
530
+// hex ID do not count ("cafe" in "7cafe52bb8"), though a pasted SHA prefix
531
+// does.
532
+function findMessageToken(
533
+ text: string,
534
+ folded: string,
535
+ token: string,
536
+): { readonly at: ReadonlyArray<number>; readonly quality: number } | null {
537
+ let quality = 0;
538
+ let at: number[] = [];
539
+ // The letters-and-digits run around the hit, kept for later hits in the
540
+ // same run: rescanning it per hit is quadratic in a long run ("0000" in a
541
+ // hex dump).
542
+ let run = { start: 0, end: -1, hex: false };
543
+ for (let index = folded.indexOf(token); index !== -1; index = folded.indexOf(token, index + 1)) {
544
+ if (index + token.length > run.end) {
545
+ let start = index;
546
+ while (start > 0 && ALPHANUMERIC.test(text[start - 1]!)) start--;
547
+ let end = index + token.length;
548
+ while (end < text.length && ALPHANUMERIC.test(text[end]!)) end++;
549
+ run = { start, end, hex: HEX_ID.test(text.slice(start, end)) };
550
+ }
551
+ if (run.hex && run.start < index) continue;
552
+ const found = !startsWordAt(text, index)
553
+ ? MID_WORD
554
+ : endsWordAt(text, index + token.length)
555
+ ? 1
556
+ : MESSAGE_PREFIX;
557
+ if (found > quality) {
558
+ quality = found;
559
+ at = [index];
560
+ } else if (found === quality) {
561
+ at.push(index);
562
+ }
563
+ }
564
+ return at.length === 0 ? null : { at, quality };
565
+}
566
+
567
+export interface MessageMatch {
568
+ /**
569
+ * 1 when every searched word is a whole word, MESSAGE_PREFIX when one only
570
+ * starts a word ("mode" in "model"), MID_WORD when one only appears inside
571
+ * words, plus MESSAGE_PHRASE_BONUS when the words are written together as
572
+ * typed, else MESSAGE_NEAR_BONUS when they sit within a row's width.
573
+ */
574
+ readonly quality: number;
575
+ /** Where a snippet should start to show the match. */
576
+ readonly offset: number;
577
+}
578
+
579
+/**
580
+ * Grades messages against a query, so message hits rank like titles: null
581
+ * when a token is missing or a short one never starts a word ("fts" in
582
+ * "drafts"). Case and accents are ignored, as in the server's index. The
583
+ * query is prepared once, since the server grades thousands of hits for it.
584
+ */
585
+export function messageMatcher(query: string): (text: string) => MessageMatch | null {
586
+ const { long, short, words } = messageSearchTokens(query);
587
+ const tokens = [...long, ...short].map((token) => ({
588
+ token,
589
+ // Marks go from the folded token: lowercasing "İ" adds one.
590
+ folded: foldInPlace(token).replace(COMBINING_MARKS, ""),
591
+ nonAscii: NON_ASCII.test(token),
592
+ mustStartWord: Array.from(token).length < MESSAGE_WORD_START_LENGTH,
593
+ // Too short to search, so it only narrows: grading by it would reorder
594
+ // results on each keystroke while the next word is typed ("nvme s").
595
+ grades: long.includes(token),
596
+ }));
597
+ const phrase = messagePhrase(query);
598
+ // Accents typed or left out still read as written together: "cafe open"
599
+ // in "Café open".
600
+ const foldedPhrase = messagePhrase(
601
+ words.map((word) => foldInPlace(word).replace(COMBINING_MARKS, "")).join(" "),
602
+ );
603
+ const queryNonAscii = NON_ASCII.test(query);
604
+ return (text) => {
605
+ const lower = text.toLowerCase();
606
+ // "İ" lowercases to two units, which would shift every offset after it.
607
+ const plain = lower.length === text.length ? lower : foldInPlace(text);
608
+ let folded: string | null = null;
609
+ let quality = 1;
610
+ const positions: Array<ReadonlyArray<number>> = [];
611
+ for (const { token, folded: foldedToken, nonAscii, mustStartWord, grades } of tokens) {
612
+ let found = findMessageToken(text, plain, token);
613
+ // Accents typed or left out: "cafe" finds "Café", also after "cafeteria".
614
+ if (found?.quality !== 1 && foldedToken.length > 0 && (nonAscii || NON_ASCII.test(text))) {
615
+ found = findMessageToken(text, (folded ??= foldInPlace(text)), foldedToken);
616
+ }
617
+ if (found === null) return null;
618
+ if (found.quality === MID_WORD && mustStartWord) return null;
619
+ if (grades) quality = Math.min(quality, found.quality);
620
+ positions.push(found.at);
621
+ }
622
+ // Written together as typed: the snippet starts there. Apostrophes are
623
+ // straight in the query, and straightening keeps offsets.
624
+ const straight = (value: string) => value.replace(CURLY_APOSTROPHES, "'");
625
+ const together =
626
+ phrase?.exec(straight(plain)) ??
627
+ (queryNonAscii || NON_ASCII.test(text)
628
+ ? foldedPhrase?.exec(straight((folded ??= foldInPlace(text))))
629
+ : null);
630
+ if (together) return { quality: quality + MESSAGE_PHRASE_BONUS, offset: together.index };
631
+ // Else the shortest stretch that holds every word: the snippet starts
632
+ // there, so it shows them all, and words close together rank above words
633
+ // far apart ("lakebed perf").
634
+ const near = shortestSpan(positions);
635
+ return {
636
+ quality:
637
+ long.length > 1 && near.length <= MESSAGE_NEAR_SPAN
638
+ ? quality + MESSAGE_NEAR_BONUS
639
+ : quality,
640
+ offset: near.start,
641
+ };
642
+ };
643
+}
644
+
645
+// The shortest stretch of text holding one place of each word, from each
646
+// word's places in order.
647
+function shortestSpan(places: ReadonlyArray<ReadonlyArray<number>>): {
648
+ readonly start: number;
649
+ readonly length: number;
650
+} {
651
+ const hits = places
652
+ .flatMap((at, word) => at.map((index) => ({ index, word })))
653
+ .sort((left, right) => left.index - right.index);
654
+ const counts = places.map(() => 0);
655
+ let covered = 0;
656
+ let best = { start: hits[0]?.index ?? 0, length: Number.POSITIVE_INFINITY };
657
+ let left = 0;
658
+ for (const hit of hits) {
659
+ counts[hit.word] = (counts[hit.word] ?? 0) + 1;
660
+ if (counts[hit.word] === 1) covered++;
661
+ while (covered === places.length) {
662
+ const first = hits[left]!;
663
+ if (hit.index - first.index < best.length) {
664
+ best = { start: first.index, length: hit.index - first.index };
665
+ }
666
+ counts[first.word] = (counts[first.word] ?? 1) - 1;
667
+ if (counts[first.word] === 0) covered--;
668
+ left++;
669
+ }
670
+ }
671
+ return best;
672
+}
673
+
674
+/**
675
+ * Ranges of `text` that contain a long message search token, for message
676
+ * snippets, ignoring case and accents. Shorter tokens would light up half the
677
+ * snippet, and a short long token only counts where it starts a word.
678
+ * Snippets vary per query, so they skip the field cache.
679
+ */
680
+export function findSearchTokenRanges(text: string, query: string): SearchRange[] {
681
+ const tokens = new Map(
682
+ messageSearchTokens(query)
683
+ .long.map(
684
+ (token) =>
685
+ [foldSearchQuery(token), Array.from(token).length < MESSAGE_WORD_START_LENGTH] as const,
686
+ )
687
+ // Some tokens fold to nothing ("´´´"), which would match everywhere.
688
+ .filter(([token]) => token.length > 0),
689
+ );
690
+ if (tokens.size === 0) return [];
691
+ const field = foldSearchField(text);
692
+ const ranges: SearchRange[] = [];
693
+ for (const [token, needsWordStart] of tokens) {
694
+ // A token that opens with punctuation brings its own boundary, as in scoring.
695
+ const ownBoundary = !ALPHANUMERIC.test(token[0]!) && !SYMBOL.test(token[0]!);
696
+ for (let index = field.text.indexOf(token); index !== -1;) {
697
+ if (needsWordStart && !ownBoundary && !field.wordStarts[index]) {
698
+ index = field.text.indexOf(token, index + 1);
699
+ continue;
700
+ }
701
+ ranges.push({ start: index, end: index + token.length });
702
+ index = field.text.indexOf(token, index + token.length);
703
+ }
704
+ }
705
+ return mergeRanges(ranges);
706
+}
707
+
708
+export interface SearchTextPart {
709
+ readonly text: string;
710
+ readonly highlighted: boolean;
711
+ readonly start: number;
712
+}
713
+
714
+/** `text` cut into plain and highlighted parts at sorted, non-overlapping `ranges`. */
715
+export function splitSearchText(
716
+ text: string,
717
+ ranges: ReadonlyArray<SearchRange>,
718
+): SearchTextPart[] {
719
+ const parts: SearchTextPart[] = [];
720
+ let cursor = 0;
721
+ for (const range of ranges) {
722
+ if (range.start > cursor) {
723
+ parts.push({ text: text.slice(cursor, range.start), highlighted: false, start: cursor });
724
+ }
725
+ parts.push({ text: text.slice(range.start, range.end), highlighted: true, start: range.start });
726
+ cursor = range.end;
727
+ }
728
+ if (cursor < text.length || parts.length === 0) {
729
+ parts.push({ text: text.slice(cursor), highlighted: false, start: cursor });
730
+ }
731
+ return parts;
732
+}
733
+
734
+const DAY_MS = 24 * 60 * 60 * 1000;
735
+/** Both activity recency and open counts halve every two weeks. */
736
+export const SEARCH_RECENCY_HALF_LIFE_MS = 14 * DAY_MS;
737
+/**
738
+ * Opens closer together than this count once, so flipping between threads is
739
+ * not frequency. Clients skip sending them.
740
+ */
741
+export const THREAD_OPEN_DEDUPE_MS = 10 * 60 * 1000;
742
+const THREAD_SEARCH_PICK_LIMIT = 3;
743
+/** Picked queries are stored this long; clients send no more. */
744
+const THREAD_SEARCH_PICK_MAX_LENGTH = 32;
745
+
746
+/**
747
+ * `query` as a pick is stored and compared: folded, then cut to the stored
748
+ * length without splitting an emoji in two. Clients and the server both use
749
+ * it, so a long pick matches its query again.
750
+ */
751
+export function pickedQuery(query: string): string {
752
+ const cut = foldSearchQuery(query).slice(0, THREAD_SEARCH_PICK_MAX_LENGTH);
753
+ return (/[\ud800-\udbff]$/.test(cut) ? cut.slice(0, -1) : cut).trim();
754
+}
755
+
756
+function decay(ageMs: number): number {
757
+ return 2 ** (-Math.max(0, ageMs) / SEARCH_RECENCY_HALF_LIFE_MS);
758
+}
759
+
760
+/** Server-stored open history; see `OrchestrationV2ThreadOpens`. */
761
+export type ThreadOpenStats = OrchestrationV2ThreadOpens;
762
+
763
+/**
764
+ * Next open stats after an open at `at`. `query` is the palette query that
765
+ * picked the thread, when it was opened from search.
766
+ */
767
+export function recordThreadOpen(
768
+ previous: ThreadOpenStats | null,
769
+ at: number,
770
+ query: string | undefined,
771
+): ThreadOpenStats {
772
+ const pick = pickedQuery(query ?? "");
773
+ // Picks that no longer count are not kept or synced.
774
+ const earlier = (previous?.picks ?? []).filter((entry) => at - entry.at <= PICK_WINDOW_MS);
775
+ const picks = pick
776
+ ? [{ query: pick, at }, ...earlier.filter((entry) => entry.query !== pick)].slice(
777
+ 0,
778
+ THREAD_SEARCH_PICK_LIMIT,
779
+ )
780
+ : earlier;
781
+ if (previous !== null && at - previous.openedAt < THREAD_OPEN_DEDUPE_MS) {
782
+ return { ...previous, picks };
783
+ }
784
+ const score = previous === null ? 1 : previous.score * decay(at - previous.openedAt) + 1;
785
+ return { openedAt: at, score, picks };
786
+}
787
+
788
+export interface ThreadSearchSubject {
789
+ /** Matched only by the whole query, like references. */
790
+ readonly id?: string;
791
+ readonly title: string;
792
+ readonly branch?: string | null;
793
+ readonly projectTitle?: string | null;
794
+ /** Only set with two or more environments; it tells same-named threads apart. */
795
+ readonly environmentLabel?: string | null;
796
+ readonly pullRequests?: ReadonlyArray<{
797
+ readonly number: number;
798
+ readonly title?: string | null;
799
+ /** Values such as URLs, matched only by the whole query. */
800
+ readonly references?: ReadonlyArray<string>;
801
+ }>;
802
+ /** Latest user activity, in epoch ms. */
803
+ readonly activityAt: number | null;
804
+ readonly opens?: ThreadOpenStats | null;
805
+}
806
+
807
+// Use reorders matches of about the same quality but never turns a mid-word
808
+// hit on a busy thread into a better result than a whole word on a quiet one.
809
+const USE_BOOST_LIMIT = 2.5;
810
+
811
+/**
812
+ * How much use lifts a thread: 1 for a stale, never-opened thread, about 2 for
813
+ * one active today, and up to 2.5 for threads opened often.
814
+ */
815
+function threadUsageBoost(thread: ThreadSearchSubject, now: number): number {
816
+ const recency = thread.activityAt === null ? 0 : decay(now - thread.activityAt);
817
+ const opens = thread.opens ? thread.opens.score * decay(now - thread.opens.openedAt) : 0;
818
+ return Math.min(USE_BOOST_LIMIT, 1 + recency + 0.5 * Math.log2(1 + opens));
819
+}
820
+
821
+const REFERENCE_PREFIX_MIN = 8;
822
+
823
+// IDs and URLs split into many word starts, so matching them as fields would
824
+// let a two-letter query hit every thread. Only a long piece of one matches: a
825
+// prefix, or, when it holds a digit like an ID or pull request number, any
826
+// part ("t3code#22889", a URL without its scheme). Both are ASCII, so
827
+// lowercasing is enough.
828
+function matchReference(
829
+ normalizedQuery: string,
830
+ thread: ThreadSearchSubject,
831
+): SearchFieldsMatch | null {
832
+ if (normalizedQuery.length < REFERENCE_PREFIX_MIN) return null;
833
+ const references = [
834
+ ...(thread.id ? [thread.id] : []),
835
+ ...(thread.pullRequests ?? []).flatMap((pullRequest) => pullRequest.references ?? []),
836
+ ];
837
+ const anywhere = DIGIT.test(normalizedQuery);
838
+ // A number is never cut short: ".../pull/2288" is not pull request 22889.
839
+ const notCut = (text: string, end: number) => !DIGIT.test(text[end] ?? "");
840
+ return references.some((reference) => {
841
+ const folded = reference.toLowerCase();
842
+ const at = folded.indexOf(normalizedQuery);
843
+ // A pasted link may go on past the reference: ".../pull/22889/files".
844
+ return anywhere
845
+ ? (at !== -1 && notCut(folded, at + normalizedQuery.length)) ||
846
+ (normalizedQuery.startsWith(folded) && notCut(normalizedQuery, folded.length))
847
+ : at === 0;
848
+ })
849
+ ? { quality: 0.6, strong: true, primaryRanges: [] }
850
+ : null;
851
+}
852
+
853
+// How long a pick lasts. While it does, typing the query again (or the start of
854
+// it) puts the thread first among its group's word matches, the exact query's
855
+// pick and then the latest first. A pick never moves the group itself, so a
856
+// thread picked once for "new" does not pass the command of that name. It runs
857
+// from the pick, so an old pick lets go even if the thread is opened in other
858
+// ways.
859
+const PICK_WINDOW_MS = 21 * DAY_MS;
860
+// The start of a picked query counts from three letters: "n" is too little to
861
+// go on.
862
+const PICK_PREFIX_MIN_LENGTH = 3;
863
+
864
+/** The latest pick of the thread for this query, while it lasts. */
865
+function activePick(
866
+ thread: ThreadSearchSubject,
867
+ normalizedQuery: string,
868
+ now: number,
869
+): ThreadOpenStats["picks"][number] | undefined {
870
+ // Stored picks are cut to a length, so compare the query cut the same way.
871
+ const query = pickedQuery(normalizedQuery);
872
+ const prefix = query.length >= PICK_PREFIX_MIN_LENGTH;
873
+ // The latest exact pick, else the latest pick the query starts.
874
+ let exact: ThreadOpenStats["picks"][number] | undefined;
875
+ let latest: ThreadOpenStats["picks"][number] | undefined;
876
+ for (const pick of thread.opens?.picks ?? []) {
877
+ if (now - pick.at > PICK_WINDOW_MS) continue;
878
+ if (pick.query === query && (exact === undefined || pick.at > exact.at)) exact = pick;
879
+ const matches = pick.query === query || (prefix && pick.query.startsWith(query));
880
+ if (matches && (latest === undefined || pick.at > latest.at)) latest = pick;
881
+ }
882
+ return exact ?? latest;
883
+}
884
+
885
+export interface ThreadSearchMatch {
886
+ /** Match quality times use; what results sort by. */
887
+ readonly score: number;
888
+ /** Match quality alone; see `rankSearchGroups`. */
889
+ readonly quality: number;
890
+ /** Every token matched at a word start; see `rankSearchGroups`. */
891
+ readonly strong: boolean;
892
+ /** Matched ranges in the title. */
893
+ readonly ranges: ReadonlyArray<SearchRange>;
894
+ /**
895
+ * Why the thread matched when its title shows no match, for the result row.
896
+ * Built on demand, so only the rows shown pay for it.
897
+ */
898
+ readonly explain?: () => SearchMatchHint | undefined;
899
+ /** When the thread was picked for this query, while that pick lasts; see `rankSearchGroups`. */
900
+ readonly pickedAt?: number;
901
+ /** Picked for exactly this query, before newer picks for longer ones; see `rankSearchGroups`. */
902
+ readonly pickedExactly?: boolean;
903
+ /** Below the whole-name class; see `scoreThreadSearch`. */
904
+ readonly groupQuality: number;
905
+}
906
+
907
+export interface SearchMatchHint {
908
+ readonly label: string;
909
+ readonly text: string;
910
+ readonly ranges: ReadonlyArray<SearchRange>;
911
+}
912
+
913
+// Most threads' branches start with the app's own worktree prefix ("t3/", and
914
+// "t3code/" before it), so "t3 connect" would match nearly every thread.
915
+// Only before more text, so typing "t3/" does not empty the list for a keystroke.
916
+const WORKTREE_BRANCH_PREFIX_PATTERN = new RegExp(`^(?:${WORKTREE_BRANCH_PREFIX}|t3code)/(?=\\S)`);
917
+
918
+function searchableBranch(branch: string | null | undefined): string | null {
919
+ return branch ? branch.replace(WORKTREE_BRANCH_PREFIX_PATTERN, "") : null;
920
+}
921
+
922
+/**
923
+ * The field that explains a match whose title shows none: the first that holds
924
+ * the whole query, else, past the words the project or environment holds, the
925
+ * first that holds the rest ("lakebed perf" in project "lakebed" with the PR
926
+ * title "perf: …").
927
+ */
928
+function matchHint(
929
+ normalizedQuery: string,
930
+ thread: ThreadSearchSubject,
931
+ typos: boolean,
932
+): SearchMatchHint | undefined {
933
+ const candidates: Array<{ readonly label: string; readonly text: string | null | undefined }> = [
934
+ ...(thread.pullRequests ?? []).map((pullRequest) => ({
935
+ label: "PR",
936
+ text: `#${pullRequest.number}${pullRequest.title ? ` ${pullRequest.title}` : ""}`,
937
+ })),
938
+ { label: "Branch", text: searchableBranch(thread.branch) },
939
+ { label: "Project", text: thread.projectTitle },
940
+ { label: "Environment", text: thread.environmentLabel },
941
+ ];
942
+ const holds = (text: string, query: string) =>
943
+ matchSearchFields(query, [{ value: text, weight: 1 }], { typos })?.primaryRanges;
944
+ const hintFor = (query: string) => {
945
+ for (const { label, text } of candidates) {
946
+ const ranges = text ? holds(text, query) : undefined;
947
+ if (text && ranges) return { label, text, ranges };
948
+ }
949
+ return undefined;
950
+ };
951
+ const whole = hintFor(normalizedQuery);
952
+ if (whole) return whole;
953
+ const contexts = [thread.projectTitle, thread.environmentLabel].filter(
954
+ (text): text is string => !!text,
955
+ );
956
+ const rest = normalizedQuery
957
+ .split(" ")
958
+ .filter((token) => !contexts.some((text) => holds(text, token)))
959
+ .join(" ");
960
+ return rest && rest !== normalizedQuery ? hintFor(rest) : undefined;
961
+}
962
+
963
+/**
964
+ * Scores a thread for a normalized query, or null when it does not match.
965
+ * Titles and pull request numbers count fully, pull request titles and
966
+ * branches less, project and environment names least.
967
+ */
968
+export function scoreThreadSearch(
969
+ normalizedQuery: string,
970
+ thread: ThreadSearchSubject,
971
+ now: number,
972
+ options?: {
973
+ readonly typos?: boolean;
974
+ /**
975
+ * Palette picks; off where a pick would show up unexplained, such as a
976
+ * sidebar filter or an agent's search.
977
+ */
978
+ readonly picks?: boolean;
979
+ },
980
+): ThreadSearchMatch | null {
981
+ const fields: WeightedSearchField[] = [{ value: thread.title, weight: 1, midWord: true }];
982
+ for (const pullRequest of thread.pullRequests ?? []) {
983
+ fields.push({ value: `#${pullRequest.number}`, weight: 1 });
984
+ if (pullRequest.title) fields.push({ value: pullRequest.title, weight: 0.5 });
985
+ }
986
+ const branch = searchableBranch(thread.branch);
987
+ if (branch) fields.push({ value: branch, weight: 0.6 });
988
+ if (thread.projectTitle) {
989
+ fields.push({ value: thread.projectTitle, weight: 0.25, context: true });
990
+ }
991
+ if (thread.environmentLabel) {
992
+ fields.push({ value: thread.environmentLabel, weight: 0.25, context: true });
993
+ }
994
+ // "#22889", "pr 22889", and a pasted "t3/branch" search without their
995
+ // prefixes, as the branch field is stored without the app's worktree prefix.
996
+ const fieldQuery = normalizedQuery
997
+ .replace(/^(?:pr|pull request|pull)\s*(?=#?\d)/, "")
998
+ .replace(/^#\s*/, "")
999
+ .replace(WORKTREE_BRANCH_PREFIX_PATTERN, "");
1000
+ const fieldMatch = matchSearchFields(fieldQuery, fields, options);
1001
+ const referenceMatch = fieldMatch ? null : matchReference(normalizedQuery, thread);
1002
+ const match = fieldMatch ?? referenceMatch;
1003
+ if (match === null) return null;
1004
+ // A row whose title shows no match must say why. With several words, one
1005
+ // that cannot (its words spread over unrelated fields) is a coincidence and
1006
+ // is left out; a single word always sits in the field that matched it, so
1007
+ // its hint waits until the row is shown.
1008
+ const typos = options?.typos ?? false;
1009
+ const titleShowsMatch = match.primaryRanges.length > 0;
1010
+ const checkHint = !titleShowsMatch && referenceMatch === null && fieldQuery.includes(" ");
1011
+ const checkedHint = checkHint ? matchHint(fieldQuery, thread, typos) : undefined;
1012
+ if (checkHint && checkedHint === undefined) return null;
1013
+ const explain = titleShowsMatch
1014
+ ? undefined
1015
+ : (): SearchMatchHint | undefined =>
1016
+ referenceMatch
1017
+ ? { label: "ID or link", text: normalizedQuery, ranges: [] }
1018
+ : (checkedHint ?? matchHint(fieldQuery, thread, typos));
1019
+ const pick = options?.picks === false ? undefined : activePick(thread, normalizedQuery, now);
1020
+ return {
1021
+ score: match.quality * threadUsageBoost(thread, now),
1022
+ quality: match.quality,
1023
+ // A thread's whole title never lifts its group over a command or project
1024
+ // of that name: every new thread is titled "New thread" for a while.
1025
+ groupQuality: Math.min(match.quality, WHOLE_NAME - 0.01),
1026
+ strong: match.strong,
1027
+ ranges: match.primaryRanges,
1028
+ ...(explain ? { explain } : {}),
1029
+ ...(pick ? { pickedAt: pick.at } : {}),
1030
+ ...(pick?.query === pickedQuery(normalizedQuery) ? { pickedExactly: true } : {}),
1031
+ };
1032
+}
1033
+
1034
+/** When the user last used a thread: their last message or their last open. */
1035
+export function threadRecentUse(thread: ThreadSearchSubject): number {
1036
+ return Math.max(thread.activityAt ?? 0, thread.opens?.openedAt ?? 0);
1037
+}
1038
+
1039
+/**
1040
+ * How strongly a thread's messages match among matches of one quality: a
1041
+ * thread that keeps using the word outweighs a recent passing mention, as
1042
+ * hits count for more than recency or use (21 hits about 5.5, one hit 2).
1043
+ */
1044
+function messageMatchWeight(hits: number): number {
1045
+ return 1 + Math.log2(1 + hits);
1046
+}
1047
+
1048
+/**
1049
+ * Orders message matches from the server, from any number of environments:
1050
+ * word matches before matches inside words, then threads picked for the
1051
+ * query, then match quality, then hit count times use, then the newest
1052
+ * message. With `withoutTitleMatches`, threads that match by title are left
1053
+ * out: a palette lists them above, so they must not use up message rows.
1054
+ */
1055
+export function rankMessageMatches<
1056
+ T extends {
1057
+ readonly quality?: number;
1058
+ readonly hits?: number;
1059
+ readonly messageCreatedAt?: string | null;
1060
+ },
1061
+>(
1062
+ matches: ReadonlyArray<T>,
1063
+ subjectOf: (match: T) => ThreadSearchSubject | undefined,
1064
+ normalizedQuery: string,
1065
+ now: number,
1066
+ options?: { readonly picks?: boolean; readonly withoutTitleMatches?: boolean },
1067
+): T[] {
1068
+ return matches
1069
+ .flatMap((match) => {
1070
+ const subject = subjectOf(match);
1071
+ if (!subject) return [];
1072
+ if (
1073
+ options?.withoutTitleMatches &&
1074
+ scoreThreadSearch(normalizedQuery, subject, now, { picks: false }) !== null
1075
+ ) {
1076
+ return [];
1077
+ }
1078
+ // Older servers send no quality; their matches count as words.
1079
+ const quality = match.quality ?? 1;
1080
+ return [
1081
+ {
1082
+ match,
1083
+ quality,
1084
+ pickedAt:
1085
+ options?.picks === false ? 0 : (activePick(subject, normalizedQuery, now)?.at ?? 0),
1086
+ score: messageMatchWeight(match.hits ?? 1) * threadUsageBoost(subject, now),
1087
+ },
1088
+ ];
1089
+ })
1090
+ .sort(
1091
+ (left, right) =>
1092
+ // Word matches first; among them a pick, then the closer match.
1093
+ Number(right.quality >= MESSAGE_PREFIX) - Number(left.quality >= MESSAGE_PREFIX) ||
1094
+ right.pickedAt - left.pickedAt ||
1095
+ right.quality - left.quality ||
1096
+ right.score - left.score ||
1097
+ (right.match.messageCreatedAt ?? "").localeCompare(left.match.messageCreatedAt ?? ""),
1098
+ )
1099
+ .map(({ match }) => match);
1100
+}
1101
+
1102
+/** Palette limits shared by web and mobile. */
1103
+export const PALETTE_THREAD_LIMIT = 20;
1104
+export const PALETTE_MESSAGE_LIMIT = 10;
1105
+/** Next to matching threads, other groups show only their best few rows. */
1106
+export const PALETTE_SECONDARY_LIMIT = 3;
1107
+
1108
+// The whole name typed (1.5 and up), every token at a word start of a main
1109
+// field (0.7 and up), a typo in a main field (0.4 and up), or weaker. Whole
1110
+// word against prefix is too fine a line for group order: "compact" must not
1111
+// lift a setting named "Compact…" over the thread "Compaction…". But the
1112
+// project named "lakebed" leads for "lakebed", and "keybindngs" is the setting
1113
+// of that name, not a command that lists it as a keyword.
1114
+function matchClass(quality: number): number {
1115
+ return quality >= WHOLE_NAME ? 3 : quality >= 0.7 ? 2 : quality >= 0.4 ? 1 : 0;
1116
+}
1117
+
1118
+export interface RankedSearchItem<T, M> {
1119
+ readonly item: T;
1120
+ readonly match: M;
1121
+}
1122
+
1123
+/**
1124
+ * Ranks grouped items: within a group, word matches before weaker ones,
1125
+ * results picked for exactly the query first among them (the latest pick
1126
+ * first), then by match class, then results picked for a query that starts
1127
+ * with this one, then best score. Groups with no match are dropped. The rest order by the class of
1128
+ * their best match (the whole name, word starts in a name, typos in a name or
1129
+ * keyword matches, or weaker), and ties keep the given order. Classes
1130
+ * rather than scores keep the group order steady while a word is typed, and
1131
+ * keep use, which only counts for threads, from outweighing a command that
1132
+ * matches as well.
1133
+ *
1134
+ * Typos are only tried when no result matches every token at a word start:
1135
+ * next to a real match, typo matches are noise ("enter" finding "external"),
1136
+ * but they should beat a mid-word accident ("ilde" in "Builder" for "idle").
1137
+ * Skipping them also keeps a keystroke cheap.
1138
+ */
1139
+export function rankSearchGroups<
1140
+ G,
1141
+ T,
1142
+ M extends {
1143
+ readonly score: number;
1144
+ readonly quality: number;
1145
+ readonly strong: boolean;
1146
+ readonly pickedAt?: number;
1147
+ readonly pickedExactly?: boolean;
1148
+ readonly groupQuality?: number;
1149
+ },
1150
+>(
1151
+ groups: ReadonlyArray<{ readonly group: G; readonly items: ReadonlyArray<T> }>,
1152
+ score: (item: T, options: { readonly typos: boolean }, group: G) => M | null,
1153
+): Array<{ readonly group: G; readonly ranked: ReadonlyArray<RankedSearchItem<T, M>> }> {
1154
+ const rank = (typos: boolean) =>
1155
+ groups.map(({ group, items }) => ({
1156
+ group,
1157
+ ranked: items.flatMap((item) => {
1158
+ const match = score(item, { typos }, group);
1159
+ return match === null ? [] : [{ item, match }];
1160
+ }),
1161
+ }));
1162
+ let ranked = rank(false);
1163
+ if (!ranked.some((entry) => entry.ranked.some(({ match }) => match.strong))) {
1164
+ ranked = rank(true);
1165
+ }
1166
+ return ranked
1167
+ .flatMap(({ group, ranked: items }, order) => {
1168
+ if (items.length === 0) return [];
1169
+ // Use decides within a match class, never across one: a busy thread
1170
+ // matched through its project does not pass a title that holds the words.
1171
+ // Picks reorder word matches but never lift a match inside a word or a
1172
+ // typo above one, and a pick for a longer query ("lakebed perf") does not
1173
+ // pass the result whose whole name is the query ("Lakebed").
1174
+ const wordMatch = (match: M) => Math.min(matchClass(match.quality), 2);
1175
+ const exactPickAt = (match: M) => (match.pickedExactly ? (match.pickedAt ?? 0) : 0);
1176
+ const sorted = [...items].sort(
1177
+ (left, right) =>
1178
+ wordMatch(right.match) - wordMatch(left.match) ||
1179
+ exactPickAt(right.match) - exactPickAt(left.match) ||
1180
+ matchClass(right.match.quality) - matchClass(left.match.quality) ||
1181
+ (right.match.pickedAt ?? 0) - (left.match.pickedAt ?? 0) ||
1182
+ right.match.score - left.match.score,
1183
+ );
1184
+ const best = Math.max(
1185
+ ...items.map(({ match }) => matchClass(match.groupQuality ?? match.quality)),
1186
+ );
1187
+ return [{ group, ranked: sorted, best, order }];
1188
+ })
1189
+ .sort((left, right) => right.best - left.best || left.order - right.order)
1190
+ .map(({ group, ranked: items }) => ({ group, ranked: items }));
1191
+}
1192
+
1193
+/** `rankSearchGroups` for a single list. */
1194
+export function rankSearchItems<
1195
+ T,
1196
+ M extends { readonly score: number; readonly quality: number; readonly strong: boolean },
1197
+>(
1198
+ items: ReadonlyArray<T>,
1199
+ score: (item: T, options: { readonly typos: boolean }) => M | null,
1200
+): ReadonlyArray<RankedSearchItem<T, M>> {
1201
+ return rankSearchGroups([{ group: null, items }], score)[0]?.ranked ?? [];
1202
+}
1203
+
1204
+export interface SearchTermsMatch {
1205
+ readonly score: number;
1206
+ readonly quality: number;
1207
+ /** The quality its group ranks by, when lower; see `scoreSearchTerms`. */
1208
+ readonly groupQuality?: number;
1209
+ readonly strong: boolean;
1210
+ readonly ranges: ReadonlyArray<SearchRange>;
1211
+}
1212
+
1213
+const KEYWORD_QUALITY = 0.65;
1214
+// Below this, keyword prefixes match too much: "co" or "pro" would list most
1215
+// settings. A short query still matches a keyword it equals ("pr").
1216
+const KEYWORD_QUERY_MIN_LENGTH = 4;
1217
+
1218
+/**
1219
+ * Scores a non-thread result such as a command or project. The first term
1220
+ * names it; the others are keywords that help it match but count less, so a
1221
+ * keyword match ranks a group below a name match ("mcp" finds the thread
1222
+ * named for it before a command with that keyword). Keywords match only at
1223
+ * word starts, and for queries under four characters only as whole words.
1224
+ */
1225
+export function scoreSearchTerms(
1226
+ normalizedQuery: string,
1227
+ terms: ReadonlyArray<string>,
1228
+ options?: { readonly typos?: boolean },
1229
+): SearchTermsMatch | null {
1230
+ // Filler words ("the ci") do not make a short query long.
1231
+ const meaningful = normalizedQuery
1232
+ .split(" ")
1233
+ .filter((token) => !FILLER_WORDS.has(token))
1234
+ .join(" ");
1235
+ const short = (meaningful || normalizedQuery).length < KEYWORD_QUERY_MIN_LENGTH;
1236
+ const match = matchSearchFields(
1237
+ normalizedQuery,
1238
+ terms.map((value, index) =>
1239
+ index === 0
1240
+ ? { value, weight: 1 }
1241
+ : // An alias typed in full ("pr") is deliberate, above a mere name prefix.
1242
+ { value, weight: short ? 0.8 : 0.6, wholeWords: short, keyword: true },
1243
+ ),
1244
+ options,
1245
+ );
1246
+ return (
1247
+ match && {
1248
+ score: match.quality,
1249
+ quality: match.quality,
1250
+ // Below the word-start class: a match only in hidden keywords must not put
1251
+ // its group above a result whose name matches. Inside the group an exact
1252
+ // alias still beats a name prefix ("pr" lists "Open pull requests" first).
1253
+ ...(match.primaryRanges.length > 0
1254
+ ? {}
1255
+ : { groupQuality: Math.min(match.quality, KEYWORD_QUALITY) }),
1256
+ strong: match.strong,
1257
+ ranges: match.primaryRanges,
1258
+ }
1259
+ );
1260
+}
packages/shared/src/threadPullRequests.ts
+43
-17
@@ -288,29 +288,55 @@ export function resolveThreadPullRequestBadge(
288
return { kind: "pull-request", others: visible.length - 1, state };
289
}
290
291
-export function threadPullRequestSearchTerms(thread: {
291
+export interface ThreadSearchPullRequest {
292
+ readonly number: number;
293
+ readonly title: string | null;
294
+ /** `owner/repo#123` and the pull request URL, matched only by a whole query. */
295
+ readonly references: ReadonlyArray<string>;
296
+}
297
+
298
+const SEARCHED_PULL_REQUEST_TITLES = 3;
299
+
300
+/** Pull requests thread search matches by number, title, and reference. */
301
+export function threadSearchPullRequests(thread: {
302
readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
303
readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
304
readonly branchPullRequest?: ThreadLinkedPullRequest | null | undefined;
295
-}): string[] {
296
- const branch = thread.branchPullRequest;
297
- const terms = branch
298
- ? [`#${branch.number}`, `${branch.repository}#${branch.number}`, branch.url]
299
- : [];
305
+}): ThreadSearchPullRequest[] {
306
+ const entry = (
307
+ link: Pick<ThreadLinkedPullRequest, "number" | "repository" | "url">,
308
+ title: string | null,
309
+ ): ThreadSearchPullRequest => ({
310
+ number: link.number,
311
+ title,
312
+ references: [`${link.repository}#${link.number}`, link.url],
313
+ });
314
+ const branch = thread.branchPullRequest ? [entry(thread.branchPullRequest, null)] : [];
315
if (thread.pullRequests !== undefined && thread.pullRequests.length > 0) {
301
- return terms.concat(
302
- visibleThreadPullRequests(thread.pullRequests).flatMap((link) => [
303
- `#${link.number}`,
304
- `${link.repository}#${link.number}`,
305
- link.url,
306
- link.snapshot?.title ?? "",
307
- ]),
316
+ // Every pull request matches by number and link, but only the newest few
317
+ // by title: a triage thread linked to dozens would match almost any word.
318
+ const newestFirst = [...visibleThreadPullRequests(thread.pullRequests)].sort(
319
+ (left, right) => latestUpdatedAt(right) - latestUpdatedAt(left),
320
+ );
321
+ return branch.concat(
322
+ newestFirst.map((link, index) =>
323
+ entry(link, index < SEARCHED_PULL_REQUEST_TITLES ? (link.snapshot?.title ?? null) : null),
324
+ ),
325
);
326
}
310
- const legacy = thread.linkedPullRequest;
311
- return legacy
312
- ? terms.concat([`#${legacy.number}`, `${legacy.repository}#${legacy.number}`, legacy.url])
313
- : terms;
327
+ return thread.linkedPullRequest ? branch.concat(entry(thread.linkedPullRequest, null)) : branch;
328
+}
329
+
330
+export function threadPullRequestSearchTerms(thread: {
331
+ readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
332
+ readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
333
+ readonly branchPullRequest?: ThreadLinkedPullRequest | null | undefined;
334
+}): string[] {
335
+ return threadSearchPullRequests(thread).flatMap((pullRequest) => [
336
+ `#${pullRequest.number}`,
337
+ ...pullRequest.references,
338
+ ...(pullRequest.title ? [pullRequest.title] : []),
339
+ ]);
340
}
341
342
/** Older V2 event payloads stored one link; an explicit empty array means it was unlinked. */
packages/shared/src/threadSearch.ts
-31
@@ -1,9 +1,3 @@
1
-interface ThreadSearchTextPart {
2
- readonly text: string;
3
- readonly highlighted: boolean;
4
- readonly start: number;
5
-}
6
-
1
function foldThreadSearchCase(text: string): string {
2
const lowered = text.toLowerCase().replace(/ς/g, "σ");
3
if (lowered.length === text.length) return lowered;
@@ -43,28 +37,3 @@ export function findThreadSearchOccurrences(text: string, query: string): number
37
scanThreadSearchOccurrences(text, query, offsets);
38
return offsets;
39
}
46
-
47
-export function splitThreadSearchText(text: string, query: string): ThreadSearchTextPart[] {
48
- const normalizedQuery = query.trim();
49
- if (normalizedQuery.length === 0) {
50
- return [{ text, highlighted: false, start: 0 }];
51
- }
52
-
53
- const parts: ThreadSearchTextPart[] = [];
54
- let cursor = 0;
55
- for (const offset of findThreadSearchOccurrences(text, normalizedQuery)) {
56
- if (offset > cursor) {
57
- parts.push({ text: text.slice(cursor, offset), highlighted: false, start: cursor });
58
- }
59
- parts.push({
60
- text: text.slice(offset, offset + normalizedQuery.length),
61
- highlighted: true,
62
- start: offset,
63
- });
64
- cursor = offset + normalizedQuery.length;
65
- }
66
- if (cursor < text.length) {
67
- parts.push({ text: text.slice(cursor), highlighted: false, start: cursor });
68
- }
69
- return parts;
70
-}