Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadSearch.ts

667 lines27.2 KB

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