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