Open History to see the last commit
1import {
2 IsoDateTime,
3 MessageId,
4 OrchestrationThreadSearchSource,
5 OrchestrationV2AppThreadJson,
6 OrchestrationV2ThreadOpens,
7 ThreadLinkedPullRequest,
8 ThreadPullRequestLink,
9 type OrchestrationSearchThreadsInput,
10 type OrchestrationSearchThreadsResult,
11 type OrchestrationV2SearchThreadsInput,
12 type OrchestrationV2SearchThreadsResult,
13 type OrchestrationV2ThreadShellSnapshot,
14 ProjectId,
15 ThreadId,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Context from "effect/Context";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Schema from "effect/Schema";
23import * as SqlClient from "effect/sql/SqlClient";
24import * as SqlSchema from "effect/sql/SqlSchema";
25import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
26import {
27 messageSearchTokens,
28 foldSearchQuery,
29 rankMessageMatches,
30 rankSearchItems,
31 messageMatcher,
32 scoreThreadSearch,
33 type ThreadSearchSubject,
34} from "@t3tools/shared/paletteSearch";
35import { threadSearchPullRequests } from "@t3tools/shared/threadPullRequests";
36import {
37 indexedMessageCondition,
38 messageSearchText,
39 nonPlaceholderMessageCondition,
40} from "./messageSearchIndex.ts";
41import { loadOlderSettledThreadsPage } from "./ShellStream.ts";
42
43// When the user last wrote in the thread aliased `threads`, as the clients
44// rank recency; agent notices in the user role do not count.
45const latestUserMessageAt = (sql: SqlClient.SqlClient) => sql`(
46 SELECT messages.updated_at
47 FROM orchestration_v2_projection_messages AS messages
48 WHERE messages.thread_id = threads.thread_id
49 AND messages.role = 'user'
50 AND COALESCE(json_extract(messages.payload_json, '$.createdBy'), 'user') = 'user'
51 ORDER BY messages.updated_at DESC, messages.message_id DESC
52 LIMIT 1
53)`;
54
55export class ThreadSearchError extends Schema.TaggedError<ThreadSearchError>()(
56 "ThreadSearchError",
57 {
58 operation: Schema.Literals(["query", "decode"]),
59 cause: Schema.Defect(),
60 },
61) {
62 override get message(): string {
63 return `Thread search ${this.operation} failed.`;
64 }
65}
66
67// Token lists bind as JSON arrays, so any number of them is one parameter.
68const TokenList = Schema.fromJsonString(Schema.Array(Schema.String));
69const SearchRequest = Schema.Struct({
70 /** The FTS5 query, or null to scan messages instead. */
71 match: Schema.NullOr(Schema.String),
72 /** Tokens every hit must contain, as typed or as their GLOB folding case and Latin accents. */
73 substrings: Schema.fromJsonString(
74 Schema.Array(Schema.Struct({ token: Schema.String, accentInsensitive: Schema.String })),
75 ),
76 /** For each short word outside ASCII, the spellings a hit must contain one of. */
77 shortSpellings: Schema.fromJsonString(Schema.Array(Schema.Array(Schema.String))),
78 projectId: Schema.NullOr(ProjectId),
79 /** Threads the caller already lists, left out before the hit limit. */
80 excludedThreadIds: TokenList,
81});
82const SearchRow = Schema.Struct({
83 messageRowid: Schema.Number,
84 messageId: MessageId,
85 threadId: ThreadId,
86 projectId: ProjectId,
87 source: OrchestrationThreadSearchSource,
88 text: Schema.String,
89 messageCreatedAt: Schema.NullOr(IsoDateTime),
90});
91
92const ThreadOpensRow = Schema.Struct({
93 threadId: ThreadId,
94 opens: Schema.NullOr(Schema.String),
95 latestUserMessageAt: Schema.NullOr(IsoDateTime),
96});
97const decodeThreadOpens = Schema.decodeUnknownOption(
98 Schema.fromJsonString(OrchestrationV2ThreadOpens),
99);
100
101const SNIPPET_LENGTH = 240;
102// The newest hits read per query. A common word stops here instead of reading
103// every message, so time stays flat as history grows.
104const MESSAGE_HIT_LIMIT = 2000;
105// How many of the newest index hits the filters may pass over to fill that
106// limit: a rare short word or hidden threads would otherwise read every hit.
107const MESSAGE_CANDIDATE_LIMIT = 10_000;
108// Without the index, how many of the newest messages a search scans.
109const MESSAGE_SCAN_LIMIT = 20_000;
110const NON_ASCII = /[\u0080-\uffff]/;
111
112/** SQLite's lower() folds ASCII only, so a short word is checked as each spelling it can match. */
113function shortTokenSpellings(token: string): ReadonlyArray<string> {
114 const forms = (char: string) => {
115 const plain = char.normalize("NFD").replace(/\p{M}/gu, "");
116 return [char, char.toUpperCase(), plain, plain.toUpperCase()];
117 };
118 const spellings = Array.from(token).reduce<ReadonlyArray<string>>(
119 (prefixes, char) => prefixes.flatMap((prefix) => forms(char).map((form) => prefix + form)),
120 [""],
121 );
122 return [...new Set(spellings)];
123}
124
125// Latin-1 Supplement and Extended-A/B/Additional letters that fold to ASCII,
126// including Romanian and Vietnamese letters SQLite's lower() leaves alone.
127const accentedForms = Map.groupBy(
128 [
129 ...Array.from({ length: 0x250 - 0xc0 }, (_, offset) => String.fromCharCode(0xc0 + offset)),
130 ...Array.from({ length: 0x1f00 - 0x1e00 }, (_, offset) => String.fromCharCode(0x1e00 + offset)),
131 ].filter((char) => /^[a-z]$/.test(foldSearchQuery(char))),
132 (char) => foldSearchQuery(char),
133);
134// Only text that may hold one of those letters (by UTF-8 lead byte) needs the GLOB:
135// lower() already folds ASCII case.
136const MESSAGE_HOLDS_ACCENTED_LATIN = [
137 ...new Set(
138 [...accentedForms.values()].flat().map((char) => Buffer.from(char).toString("hex", 0, 1)),
139 ),
140]
141 .map((lead) => `instr(CAST(message.text AS BLOB), x'${lead}') > 0`)
142 .join(" OR ");
143
144/** A GLOB pattern for `token` anywhere, in any case and with or without Latin accents. */
145function accentInsensitiveGlob(token: string): string {
146 const pattern = Array.from(token, (char) => {
147 const letter = foldSearchQuery(char);
148 if (/^[a-z]$/.test(letter)) {
149 return `[${letter}${letter.toUpperCase()}${accentedForms.get(letter)?.join("") ?? ""}]`;
150 }
151 return /[*?[]/.test(char) ? `[${char}]` : char;
152 });
153 return `*${pattern.join("")}*`;
154}
155
156/**
157 * The SQL inputs for a message search, or null when the query has no token
158 * long enough to search. Tokens of three or more characters go to the
159 * trigram index as quoted phrases; shorter ones, and every token when the
160 * index cannot serve the query, are checked as substrings of the hits.
161 */
162function buildMessageSearch(
163 query: string,
164 hasIndex: boolean,
165): Omit<typeof SearchRequest.Type, "projectId" | "excludedThreadIds"> | null {
166 const { long, short } = messageSearchTokens(query);
167 if (long.length === 0) return null;
168 // Two-character CJK words are too short for trigrams.
169 const indexed = hasIndex && long.every((token) => Array.from(token).length >= 3);
170 const narrowing = short.filter((token) => !NON_ASCII.test(token));
171 return {
172 match: indexed ? long.map((token) => `"${token.replaceAll('"', '""')}"`).join(" ") : null,
173 substrings: (indexed ? narrowing : [...long, ...narrowing]).map((token) => ({
174 token,
175 accentInsensitive: accentInsensitiveGlob(token),
176 })),
177 shortSpellings: short.filter((token) => NON_ASCII.test(token)).map(shortTokenSpellings),
178 };
179}
180
181// A thread shows a link as its text, so in-thread find cannot reach a match
182// in the address; messages are matched as they read.
183const MARKDOWN_LINK = /!?\[([^\]\n]*)\]\([^)\s]*\)/g;
184
185// Result rows show one line, so the match must sit near the start to be seen.
186const SNIPPET_LEAD = 24;
187
188const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
189
190/**
191 * Up to 240 characters starting a few words before the match at `matchStart`,
192 * whitespace collapsed, with ellipses where the text was cut. The client finds
193 * the highlights again in the result.
194 */
195export function buildSearchSnippet(text: string, matchStart: number): string {
196 let start = Math.max(0, matchStart - SNIPPET_LEAD);
197 const wordStart = text.slice(start, matchStart).search(/\s/);
198 if (start > 0 && wordStart !== -1) start += wordStart + 1;
199 // Cut between characters, not inside an emoji's surrogate pair.
200 if (isLowSurrogate(text.charCodeAt(start))) start++;
201 // Collapsing whitespace shortens the text, so read more of it.
202 const rawEnd = Math.min(text.length, start + SNIPPET_LENGTH * 2);
203 // Emphasis and code marks do not show in a thread either.
204 const shown = text
205 .slice(start, rawEnd)
206 .replace(/\*\*|`+/g, "")
207 .replace(/\s+/g, " ")
208 .trim();
209 let end = Math.min(shown.length, SNIPPET_LENGTH - 2);
210 if (isLowSurrogate(shown.charCodeAt(end))) end--;
211 const cut = end < shown.length || rawEnd < text.length;
212 return `${start > 0 ? "…" : ""}${shown.slice(0, end)}${cut ? "…" : ""}`;
213}
214
215// Filter hidden subagents and side chats before the hit limit; JS checks word starts and ranking.
216// Both paths narrow ASCII tokens with Latin-1 and Extended-A/B/Additional accent variants.
217// Without FTS5 trigrams, or for two-character CJK words, scan the same eligible messages;
218// accented queries and non-Latin case can still miss: "fermée"/"fermee", "ОШИБКА"/"ошибка".
219export const messageHitsQuery = (
220 sql: SqlClient.SqlClient,
221 { match, substrings, shortSpellings, projectId, excludedThreadIds }: typeof SearchRequest.Encoded,
222) => sql`
223 WITH eligible AS MATERIALIZED (
224 SELECT threads.thread_id, threads.project_id
225 FROM orchestration_v2_projection_threads AS threads
226 INNER JOIN projection_projects AS projects
227 ON projects.project_id = threads.project_id
228 WHERE threads.deleted_at IS NULL
229 AND threads.archived_at IS NULL
230 AND projects.deleted_at IS NULL
231 AND (${projectId} IS NULL OR threads.project_id = ${projectId})
232 AND threads.thread_id NOT IN (SELECT value FROM json_each(${excludedThreadIds}))
233 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
234 IS NOT 'subagent'
235 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
236 )
237 ${
238 match === null
239 ? sql`
240 SELECT
241 messages.rowid AS "messageRowid",
242 messages.message_id AS "messageId",
243 messages.thread_id AS "threadId",
244 eligible.project_id AS "projectId",
245 messages.role AS source,
246 ${messageSearchText(sql)} AS text,
247 messages.created_at AS "messageCreatedAt"
248 FROM orchestration_v2_projection_messages AS messages
249 INNER JOIN eligible ON eligible.thread_id = messages.thread_id
250 WHERE ${indexedMessageCondition(sql)}
251 -- A scan reads every message it passes, so it stops at the newest ones.
252 AND messages.rowid > (
253 SELECT coalesce(max(rowid), 0) FROM orchestration_v2_projection_messages
254 ) - ${MESSAGE_SCAN_LIMIT}
255 `
256 : sql`
257 SELECT
258 orchestration_v2_message_search.rowid AS "messageRowid",
259 messages.message_id AS "messageId",
260 messages.thread_id AS "threadId",
261 eligible.project_id AS "projectId",
262 messages.role AS source,
263 ${messageSearchText(sql)} AS text,
264 messages.created_at AS "messageCreatedAt"
265 FROM orchestration_v2_message_search
266 INNER JOIN orchestration_v2_projection_messages AS messages
267 ON messages.rowid = orchestration_v2_message_search.rowid
268 INNER JOIN eligible ON eligible.thread_id = messages.thread_id
269 WHERE orchestration_v2_message_search MATCH ${match}
270 AND orchestration_v2_message_search.rowid >= coalesce((
271 SELECT orchestration_v2_message_search.rowid FROM orchestration_v2_message_search
272 WHERE orchestration_v2_message_search MATCH ${match}
273 ORDER BY orchestration_v2_message_search.rowid DESC
274 LIMIT 1 OFFSET ${MESSAGE_CANDIDATE_LIMIT - 1}
275 ), 0)
276 AND ${nonPlaceholderMessageCondition(sql)}
277 `
278 }
279 -- Answers to an agent's question show inside its question card, where
280 -- neither find nor a jump can reach them.
281 AND messages.message_id NOT LIKE 'async-answer:%'
282 AND NOT EXISTS (
283 -- The text read once, not once per check.
284 SELECT 1 FROM (SELECT ${messageSearchText(sql)} AS text) AS message,
285 json_each(${substrings}) AS substring
286 WHERE instr(lower(message.text), json_extract(substring.value, '$.token')) = 0
287 AND NOT (
288 (${sql.literal(MESSAGE_HOLDS_ACCENTED_LATIN)})
289 AND message.text GLOB json_extract(substring.value, '$.accentInsensitive')
290 )
291 )
292 AND NOT EXISTS (
293 SELECT 1 FROM json_each(${shortSpellings}) AS token
294 WHERE NOT EXISTS (
295 SELECT 1 FROM json_each(token.value) AS spelling
296 WHERE instr(${messageSearchText(sql)}, spelling.value) > 0
297 )
298 )
299 -- The index's own rowid, so FTS5 returns hits newest first and stops at
300 -- the limit; ordering by the messages table's rowid sorts every hit.
301 ORDER BY "messageRowid" DESC
302 LIMIT ${MESSAGE_HIT_LIMIT}
303 `;
304
305const TitleCandidateRow = Schema.Struct({
306 thread: Schema.fromJsonString(OrchestrationV2AppThreadJson),
307 projectTitle: Schema.String,
308 latestUserMessageAt: Schema.NullOr(IsoDateTime),
309});
310
311export interface ThreadSearchHit {
312 readonly threadId: ThreadId;
313 readonly projectId: ProjectId;
314 readonly title: string;
315 readonly source: "title" | OrchestrationThreadSearchSource;
316 readonly snippet?: string;
317 readonly messageCreatedAt?: string | null;
318}
319
320export class ThreadSearch extends Context.Service<
321 ThreadSearch,
322 {
323 /** Message text matches, for clients that rank their own thread list. */
324 readonly search: (
325 input: OrchestrationSearchThreadsInput,
326 ) => Effect.Effect<OrchestrationSearchThreadsResult, ThreadSearchError>;
327 /**
328 * Title, branch, pull request, and project matches ranked as the command
329 * palette ranks them, then message matches for the remaining threads.
330 */
331 readonly searchThreads: (
332 input: OrchestrationSearchThreadsInput & { readonly projectId?: ProjectId | undefined },
333 ) => Effect.Effect<{ readonly matches: ReadonlyArray<ThreadSearchHit> }, ThreadSearchError>;
334 /**
335 * The settled threads before `before` that clients omitting older settled threads should
336 * receive for a query: the best title, branch, pull request and project matches, ranked as
337 * the palette ranks them, then the older ones among `messageThreadIds`, in their order.
338 */
339 readonly searchOlderSettled: (input: {
340 readonly query: string;
341 readonly before: string;
342 readonly projectIds?: ReadonlyArray<ProjectId> | undefined;
343 /** The caller's name for this environment, which its palette also matches. */
344 readonly environmentLabel?: string | undefined;
345 readonly messageThreadIds: ReadonlyArray<ThreadId>;
346 }) => Effect.Effect<ReadonlyArray<ThreadId>, ThreadSearchError>;
347 }
348>()("t3/orchestration-v2/ThreadSearch") {}
349
350// Rows a client gets per search: enough for the shown results without sending every match.
351const OLDER_SETTLED_TITLE_ROWS = 15;
352const OLDER_SETTLED_MESSAGE_ROWS = 5;
353
354// Only the fields the palette scorer reads, so an interactive search does not decode payloads.
355const OlderSettledTitleRow = Schema.Struct({
356 id: ThreadId,
357 title: Schema.String,
358 branch: Schema.NullOr(Schema.String),
359 pullRequests: Schema.NullOr(Schema.fromJsonString(Schema.Array(ThreadPullRequestLink))),
360 linkedPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
361 branchPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
362 opens: Schema.NullOr(Schema.String),
363 createdAt: IsoDateTime,
364 projectTitle: Schema.String,
365 latestUserMessageAt: Schema.NullOr(IsoDateTime),
366});
367
368/** @public */
369export const make = Effect.gen(function* () {
370 const sql = yield* SqlClient.SqlClient;
371
372 const searchRows = SqlSchema.findAll({
373 Request: SearchRequest,
374 Result: SearchRow,
375 execute: (request) => messageHitsQuery(sql, request),
376 });
377
378 const threadOpens = SqlSchema.findAll({
379 Request: Schema.Struct({ threadIds: TokenList }),
380 Result: ThreadOpensRow,
381 execute: ({ threadIds }) => sql`
382 SELECT
383 threads.thread_id AS "threadId",
384 json_extract(threads.payload_json, '$.opens') AS opens,
385 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
386 FROM orchestration_v2_projection_threads AS threads
387 WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds}))
388 `,
389 });
390
391 const titleCandidates = SqlSchema.findAll({
392 Request: Schema.Struct({ projectId: Schema.NullOr(ProjectId) }),
393 Result: TitleCandidateRow,
394 execute: ({ projectId }) => sql`
395 SELECT
396 threads.payload_json AS thread,
397 projects.title AS "projectTitle",
398 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
399 FROM orchestration_v2_projection_threads AS threads
400 INNER JOIN projection_projects AS projects
401 ON projects.project_id = threads.project_id
402 WHERE threads.deleted_at IS NULL
403 AND threads.archived_at IS NULL
404 AND projects.deleted_at IS NULL
405 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
406 IS NOT 'subagent'
407 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
408 AND (${projectId} IS NULL OR threads.project_id = ${projectId})
409 `,
410 });
411
412 const olderSettledTitleCandidates = SqlSchema.findAll({
413 Request: Schema.Struct({
414 before: Schema.String,
415 projectIds: Schema.NullOr(TokenList),
416 }),
417 Result: OlderSettledTitleRow,
418 execute: ({ before, projectIds }) => sql`
419 SELECT
420 threads.thread_id AS id,
421 json_extract(threads.payload_json, '$.title') AS title,
422 json_extract(threads.payload_json, '$.branch') AS branch,
423 json_extract(threads.payload_json, '$.pullRequests') AS "pullRequests",
424 json_extract(threads.payload_json, '$.linkedPullRequest') AS "linkedPullRequest",
425 json_extract(threads.payload_json, '$.branchPullRequest') AS "branchPullRequest",
426 json_extract(threads.payload_json, '$.opens') AS opens,
427 json_extract(threads.payload_json, '$.createdAt') AS "createdAt",
428 projects.title AS "projectTitle",
429 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
430 FROM orchestration_v2_projection_threads AS threads
431 INNER JOIN projection_projects AS projects
432 ON projects.project_id = threads.project_id
433 WHERE threads.deleted_at IS NULL
434 AND json_extract(threads.payload_json, '$.archivedAt') IS NULL
435 AND projects.deleted_at IS NULL
436 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
437 IS NOT 'subagent'
438 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
439 AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'
440 AND json_extract(threads.payload_json, '$.settledAt') < ${before}
441 AND (${projectIds} IS NULL
442 OR threads.project_id IN (SELECT value FROM json_each(${projectIds})))
443 `,
444 });
445
446 const olderSettledIds = SqlSchema.findAll({
447 Request: Schema.Struct({
448 before: Schema.String,
449 threadIds: TokenList,
450 projectIds: Schema.NullOr(TokenList),
451 }),
452 Result: Schema.Struct({ id: ThreadId }),
453 execute: ({ before, threadIds, projectIds }) => sql`
454 SELECT threads.thread_id AS id
455 FROM orchestration_v2_projection_threads AS threads
456 WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds}))
457 AND threads.deleted_at IS NULL
458 AND json_extract(threads.payload_json, '$.archivedAt') IS NULL
459 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
460 IS NOT 'subagent'
461 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
462 AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'
463 AND json_extract(threads.payload_json, '$.settledAt') < ${before}
464 AND (${projectIds} IS NULL
465 OR threads.project_id IN (SELECT value FROM json_each(${projectIds})))
466 `,
467 });
468
469 const read = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
470 sql.withTransaction(effect).pipe(
471 NodeSqliteClient.readOnly,
472 Effect.mapError(
473 (cause) =>
474 new ThreadSearchError({
475 operation: Schema.isSchemaError(cause) ? "decode" : "query",
476 cause,
477 }),
478 ),
479 );
480
481 // A project scope applies before ranking, so other projects' stronger hits
482 // cannot use up the limit.
483 const searchMessages = Effect.fn("ThreadSearch.search")(function* (
484 input: OrchestrationSearchThreadsInput & {
485 readonly projectId: ProjectId | null;
486 /** Threads the caller already lists, which must not use up the limit. */
487 readonly excludedThreadIds?: ReadonlySet<ThreadId>;
488 /** Off for an agent's search, which has no use for the user's picks. */
489 readonly picks?: boolean;
490 },
491 ) {
492 // One message per thread: the best word match, then what the user wrote,
493 // since that is what they remember asking, then the newest by when it was
494 // written. Row order is not age: imported histories arrive in one batch.
495 // Text relevance (bm25) would cost a pass over every hit in history.
496 type Hit = {
497 readonly row: typeof SearchRow.Type;
498 /** The message as it reads, links as their text. */
499 readonly text: string;
500 readonly quality: number;
501 readonly offset: number;
502 };
503 const newer = (left: Hit, right: Hit) =>
504 (right.row.messageCreatedAt ?? "").localeCompare(left.row.messageCreatedAt ?? "");
505 const compareHits = (left: Hit, right: Hit) =>
506 right.quality - left.quality ||
507 Number(left.row.source !== "user") - Number(right.row.source !== "user") ||
508 newer(left, right);
509 const rows = yield* read(
510 Effect.gen(function* () {
511 const index = yield* sql`
512 SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
513 `;
514 const messageSearch = buildMessageSearch(input.query, index.length > 0);
515 return messageSearch === null
516 ? []
517 : yield* searchRows({
518 ...messageSearch,
519 projectId: input.projectId,
520 excludedThreadIds: [...(input.excludedThreadIds ?? [])],
521 });
522 }),
523 );
524 const best = new Map<ThreadId, Hit>();
525 // Matching messages per thread at its best quality: a thread that keeps
526 // using the word ranks above a passing mention, and weaker hits ("Trust"
527 // for "rust") never add to a whole word's count.
528 const hitCounts = new Map<ThreadId, number>();
529 const hitCount = (threadId: ThreadId) => hitCounts.get(threadId) ?? 1;
530 const matchMessage = messageMatcher(input.query);
531 for (const row of rows) {
532 const text = row.text.replace(MARKDOWN_LINK, "$1");
533 const match = matchMessage(text);
534 if (match === null) continue;
535 const hit = { row, text, ...match };
536 const current = best.get(row.threadId);
537 if (current === undefined || hit.quality > current.quality) {
538 hitCounts.set(row.threadId, 1);
539 } else if (hit.quality === current.quality) {
540 hitCounts.set(row.threadId, hitCount(row.threadId) + 1);
541 }
542 if (current === undefined || compareHits(hit, current) < 0) best.set(row.threadId, hit);
543 }
544 // Ranked as clients rank them, with picks and use, before the limit cuts:
545 // a thread picked for this query must come back even when it only
546 // matches in a few old messages.
547 const opens = best.size === 0 ? [] : yield* read(threadOpens({ threadIds: [...best.keys()] }));
548 const subjectById = new Map(
549 opens.map((row) => [
550 row.threadId,
551 {
552 title: "",
553 activityAt: row.latestUserMessageAt === null ? null : Date.parse(row.latestUserMessageAt),
554 opens: Option.getOrNull(decodeThreadOpens(row.opens)),
555 },
556 ]),
557 );
558 const now = DateTime.toEpochMillis(yield* DateTime.now);
559 const ranked = rankMessageMatches(
560 [...best.values()].map((hit) => ({
561 ...hit,
562 hits: hitCount(hit.row.threadId),
563 messageCreatedAt: hit.row.messageCreatedAt,
564 })),
565 (hit) => subjectById.get(hit.row.threadId),
566 foldSearchQuery(input.query),
567 now,
568 { picks: input.picks ?? true },
569 );
570 return {
571 matches: ranked.slice(0, input.limit ?? 50).map(({ row, text, quality, offset }) => ({
572 hits: hitCount(row.threadId),
573 threadId: row.threadId,
574 messageId: row.messageId,
575 projectId: row.projectId,
576 source: row.source,
577 snippet: buildSearchSnippet(text, offset),
578 messageCreatedAt: row.messageCreatedAt,
579 quality,
580 })),
581 };
582 });
583
584 const search: ThreadSearch["Service"]["search"] = (input) =>
585 searchMessages({ ...input, projectId: null });
586
587 const searchThreads: ThreadSearch["Service"]["searchThreads"] = Effect.fn(
588 "ThreadSearch.searchThreads",
589 )(function* (input) {
590 const limit = input.limit ?? 50;
591 const normalizedQuery = foldSearchQuery(input.query);
592 const now = DateTime.toEpochMillis(yield* DateTime.now);
593 // Agents call this rarely, and a project has hundreds of threads, not
594 // millions, so ranking every active thread in memory stays cheap.
595 const candidates = yield* read(titleCandidates({ projectId: input.projectId ?? null }));
596 const subjectById = new Map(
597 candidates.map((row): [ThreadId, ThreadSearchSubject] => [
598 row.thread.id,
599 {
600 id: row.thread.id,
601 title: row.thread.title,
602 branch: row.thread.branch,
603 projectTitle: row.projectTitle,
604 pullRequests: threadSearchPullRequests(row.thread),
605 // Like the clients: what the user last wrote, else when the thread began.
606 activityAt: Date.parse(
607 row.latestUserMessageAt ?? DateTime.formatIso(row.thread.createdAt),
608 ),
609 opens: row.thread.opens ?? null,
610 },
611 ]),
612 );
613 const titleHits: ThreadSearchHit[] = rankSearchItems(candidates, (row, options) =>
614 // An agent's search has no use for the user's palette picks.
615 scoreThreadSearch(normalizedQuery, subjectById.get(row.thread.id)!, now, {
616 ...options,
617 picks: false,
618 }),
619 )
620 .slice(0, limit)
621 .map(({ item }) => ({
622 threadId: item.thread.id,
623 projectId: item.thread.projectId,
624 title: item.thread.title,
625 source: "title",
626 }));
627 const shown = new Set(titleHits.map((hit) => hit.threadId));
628 const { matches } = yield* searchMessages({
629 query: input.query,
630 limit: 50,
631 projectId: input.projectId ?? null,
632 excludedThreadIds: shown,
633 picks: false,
634 });
635 const messageHits = matches
636 .filter((match) => subjectById.has(match.threadId))
637 .map(({ quality: _quality, hits: _hits, messageId: _messageId, ...match }) => ({
638 ...match,
639 title: subjectById.get(match.threadId)!.title,
640 }));
641 // Titles come first, but a fifth of the slots stay for message matches,
642 // as the palette keeps its "In messages" section.
643 const messageSlots = Math.min(messageHits.length, Math.floor(limit / 5));
644 return {
645 matches: [...titleHits.slice(0, limit - messageSlots), ...messageHits].slice(0, limit),
646 };
647 });
648
649 const searchOlderSettled: ThreadSearch["Service"]["searchOlderSettled"] = Effect.fn(
650 "ThreadSearch.searchOlderSettled",
651 )(function* ({ query, before, projectIds, environmentLabel, messageThreadIds }) {
652 const normalizedQuery = foldSearchQuery(query);
653 const now = DateTime.toEpochMillis(yield* DateTime.now);
654 const candidates = yield* read(
655 olderSettledTitleCandidates({ before, projectIds: projectIds ?? null }),
656 );
657 const subjectOf = (row: typeof OlderSettledTitleRow.Type): ThreadSearchSubject => ({
658 id: row.id,
659 title: row.title,
660 branch: row.branch,
661 projectTitle: row.projectTitle,
662 environmentLabel: environmentLabel ?? null,
663 pullRequests: threadSearchPullRequests({
664 pullRequests: row.pullRequests ?? undefined,
665 linkedPullRequest: row.linkedPullRequest,
666 branchPullRequest: row.branchPullRequest,
667 }),
668 // Like the clients: what the user last wrote, else when the thread began.
669 activityAt: Date.parse(row.latestUserMessageAt ?? row.createdAt),
670 opens: Option.getOrNull(decodeThreadOpens(row.opens)),
671 });
672 // Picks on, as in the command palette: a thread picked for this query must make the cut.
673 const titleIds = rankSearchItems(candidates, (row, options) =>
674 scoreThreadSearch(normalizedQuery, subjectOf(row), now, { ...options, picks: true }),
675 )
676 .slice(0, OLDER_SETTLED_TITLE_ROWS)
677 .map(({ item }) => item.id);
678 const shown = new Set(titleIds);
679 const messageCandidates = [...new Set(messageThreadIds)].filter((id) => !shown.has(id));
680 const older =
681 messageCandidates.length === 0
682 ? new Set<ThreadId>()
683 : new Set(
684 (yield* read(
685 olderSettledIds({
686 before,
687 threadIds: messageCandidates,
688 projectIds: projectIds ?? null,
689 }),
690 )).map((row) => row.id),
691 );
692 return [
693 ...titleIds,
694 ...messageCandidates.filter((id) => older.has(id)).slice(0, OLDER_SETTLED_MESSAGE_ROWS),
695 ];
696 });
697
698 return ThreadSearch.of({ search, searchThreads, searchOlderSettled });
699});
700
701export const layer = Layer.effect(ThreadSearch, make);
702
703/**
704 * The client search: message hits, and with `olderSettledBefore`, the rows of the best older
705 * settled matches, which shells that omit them do not hold.
706 */
707export const searchThreadsWithOlderSettledRows = Effect.fn(
708 "ThreadSearch.searchThreadsWithOlderSettledRows",
709)(function* <E1, E2, E3, E4, E5>(input: {
710 readonly request: OrchestrationV2SearchThreadsInput;
711 readonly search: (
712 input: OrchestrationSearchThreadsInput,
713 ) => Effect.Effect<OrchestrationSearchThreadsResult, E1>;
714 readonly searchOlderSettled: (
715 input: Parameters<ThreadSearch["Service"]["searchOlderSettled"]>[0],
716 ) => Effect.Effect<ReadonlyArray<ThreadId>, E2>;
717 readonly sql: SqlClient.SqlClient;
718 readonly readThreads: (
719 threadIds: ReadonlyArray<ThreadId>,
720 ) => Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E4>, E3>;
721 readonly latestSequence: Effect.Effect<number, E5>;
722}) {
723 const { olderSettledBefore, projectIds, environmentLabel, titlesOnly, ...request } =
724 input.request;
725 const messages: OrchestrationV2SearchThreadsResult =
726 titlesOnly === true ? { matches: [] } : yield* input.search(request);
727 if (olderSettledBefore === undefined) return messages;
728 // Ranked before the rows' transaction, so scoring never holds the shared reader.
729 const threadIds = yield* input.searchOlderSettled({
730 query: request.query,
731 before: olderSettledBefore,
732 projectIds,
733 environmentLabel,
734 messageThreadIds: messages.matches.map((match) => match.threadId),
735 });
736 const older = yield* loadOlderSettledThreadsPage({
737 sql: input.sql,
738 listThreads: Effect.succeed({ threadIds, counts: [] }),
739 readThreads: input.readThreads,
740 latestSequence: input.latestSequence,
741 });
742 return { ...messages, snapshotSequence: older.snapshotSequence, threads: older.threads };
743});