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 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 };
121}
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 ? "…" : ""}`;
155}
156
157// Filter hidden subagents and side chats 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 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
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 orchestration_v2_message_search.rowid FROM orchestration_v2_message_search
214 WHERE orchestration_v2_message_search MATCH ${match}
215 ORDER BY orchestration_v2_message_search.rowid DESC
216 LIMIT 1 OFFSET ${MESSAGE_CANDIDATE_LIMIT - 1}
217 ), 0)
218 AND ${nonPlaceholderMessageCondition(sql)}
219 `
220 }
221 -- Answers to an agent's question show inside its question card, where
222 -- neither find nor a jump can reach them.
223 AND messages.message_id NOT LIKE 'async-answer:%'
224 AND NOT EXISTS (
225 SELECT 1 FROM json_each(${substrings}) AS token
226 WHERE instr(lower(json_extract(messages.payload_json, '$.text')), token.value) = 0
227 )
228 -- The index's own rowid, so FTS5 returns hits newest first and stops at
229 -- the limit; ordering by the messages table's rowid sorts every hit.
230 ORDER BY "messageRowid" DESC
231 LIMIT ${MESSAGE_HIT_LIMIT}
232 `;
233
234const TitleCandidateRow = Schema.Struct({
235 thread: Schema.fromJsonString(OrchestrationV2AppThreadJson),
236 projectTitle: Schema.String,
237 latestUserMessageAt: Schema.NullOr(IsoDateTime),
238});
239
240export interface ThreadSearchHit {
241 readonly threadId: ThreadId;
242 readonly projectId: ProjectId;
243 readonly title: string;
244 readonly source: "title" | OrchestrationThreadSearchSource;
245 readonly snippet?: string;
246 readonly messageCreatedAt?: string | null;
247}
248
249export class ThreadSearch extends Context.Service<
250 ThreadSearch,
251 {
252 /** Message text matches, for clients that rank their own thread list. */
253 readonly search: (
254 input: OrchestrationSearchThreadsInput,
255 ) => Effect.Effect<OrchestrationSearchThreadsResult, ThreadSearchError>;
256 /**
257 * Title, branch, pull request, and project matches ranked as the command
258 * palette ranks them, then message matches for the remaining threads.
259 */
260 readonly searchThreads: (
261 input: OrchestrationSearchThreadsInput & { readonly projectId?: ProjectId | undefined },
262 ) => Effect.Effect<{ readonly matches: ReadonlyArray<ThreadSearchHit> }, ThreadSearchError>;
263 /**
264 * The settled threads before `before` that clients omitting older settled threads should
265 * receive for a query: the best title, branch, pull request and project matches, ranked as
266 * the palette ranks them, then the older ones among `messageThreadIds`, in their order.
267 */
268 readonly searchOlderSettled: (input: {
269 readonly query: string;
270 readonly before: string;
271 readonly projectIds?: ReadonlyArray<ProjectId> | undefined;
272 /** The caller's name for this environment, which its palette also matches. */
273 readonly environmentLabel?: string | undefined;
274 readonly messageThreadIds: ReadonlyArray<ThreadId>;
275 }) => Effect.Effect<ReadonlyArray<ThreadId>, ThreadSearchError>;
276 }
277>()("t3/orchestration-v2/ThreadSearch") {}
278
279// Rows a client gets per search: enough for the shown results without sending every match.
280const OLDER_SETTLED_TITLE_ROWS = 15;
281const OLDER_SETTLED_MESSAGE_ROWS = 5;
282
283// Only the fields the palette scorer reads, so an interactive search does not decode payloads.
284const OlderSettledTitleRow = Schema.Struct({
285 id: ThreadId,
286 title: Schema.String,
287 branch: Schema.NullOr(Schema.String),
288 pullRequests: Schema.NullOr(Schema.fromJsonString(Schema.Array(ThreadPullRequestLink))),
289 linkedPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
290 branchPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
291 opens: Schema.NullOr(Schema.String),
292 createdAt: IsoDateTime,
293 projectTitle: Schema.String,
294 latestUserMessageAt: Schema.NullOr(IsoDateTime),
295});
296
297/** @public */
298export const make = Effect.gen(function* () {
299 const sql = yield* SqlClient.SqlClient;
300
301 const searchRows = SqlSchema.findAll({
302 Request: SearchRequest,
303 Result: SearchRow,
304 execute: (request) => messageHitsQuery(sql, request),
305 });
306
307 const threadOpens = SqlSchema.findAll({
308 Request: Schema.Struct({ threadIds: TokenList }),
309 Result: ThreadOpensRow,
310 execute: ({ threadIds }) => sql`
311 SELECT
312 threads.thread_id AS "threadId",
313 json_extract(threads.payload_json, '$.opens') AS opens,
314 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
315 FROM orchestration_v2_projection_threads AS threads
316 WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds}))
317 `,
318 });
319
320 const titleCandidates = SqlSchema.findAll({
321 Request: Schema.Struct({ projectId: Schema.NullOr(ProjectId) }),
322 Result: TitleCandidateRow,
323 execute: ({ projectId }) => sql`
324 SELECT
325 threads.payload_json AS thread,
326 projects.title AS "projectTitle",
327 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
328 FROM orchestration_v2_projection_threads AS threads
329 INNER JOIN projection_projects AS projects
330 ON projects.project_id = threads.project_id
331 WHERE threads.deleted_at IS NULL
332 AND threads.archived_at IS NULL
333 AND projects.deleted_at IS NULL
334 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
335 IS NOT 'subagent'
336 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
337 AND (${projectId} IS NULL OR threads.project_id = ${projectId})
338 `,
339 });
340
341 const olderSettledTitleCandidates = SqlSchema.findAll({
342 Request: Schema.Struct({
343 before: Schema.String,
344 projectIds: Schema.NullOr(TokenList),
345 }),
346 Result: OlderSettledTitleRow,
347 execute: ({ before, projectIds }) => sql`
348 SELECT
349 threads.thread_id AS id,
350 json_extract(threads.payload_json, '$.title') AS title,
351 json_extract(threads.payload_json, '$.branch') AS branch,
352 json_extract(threads.payload_json, '$.pullRequests') AS "pullRequests",
353 json_extract(threads.payload_json, '$.linkedPullRequest') AS "linkedPullRequest",
354 json_extract(threads.payload_json, '$.branchPullRequest') AS "branchPullRequest",
355 json_extract(threads.payload_json, '$.opens') AS opens,
356 json_extract(threads.payload_json, '$.createdAt') AS "createdAt",
357 projects.title AS "projectTitle",
358 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
359 FROM orchestration_v2_projection_threads AS threads
360 INNER JOIN projection_projects AS projects
361 ON projects.project_id = threads.project_id
362 WHERE threads.deleted_at IS NULL
363 AND json_extract(threads.payload_json, '$.archivedAt') IS NULL
364 AND projects.deleted_at IS NULL
365 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
366 IS NOT 'subagent'
367 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
368 AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'
369 AND json_extract(threads.payload_json, '$.settledAt') < ${before}
370 AND (${projectIds} IS NULL
371 OR threads.project_id IN (SELECT value FROM json_each(${projectIds})))
372 `,
373 });
374
375 const olderSettledIds = SqlSchema.findAll({
376 Request: Schema.Struct({
377 before: Schema.String,
378 threadIds: TokenList,
379 projectIds: Schema.NullOr(TokenList),
380 }),
381 Result: Schema.Struct({ id: ThreadId }),
382 execute: ({ before, threadIds, projectIds }) => sql`
383 SELECT threads.thread_id AS id
384 FROM orchestration_v2_projection_threads AS threads
385 WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds}))
386 AND threads.deleted_at IS NULL
387 AND json_extract(threads.payload_json, '$.archivedAt') IS NULL
388 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
389 IS NOT 'subagent'
390 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
391 AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'
392 AND json_extract(threads.payload_json, '$.settledAt') < ${before}
393 AND (${projectIds} IS NULL
394 OR threads.project_id IN (SELECT value FROM json_each(${projectIds})))
395 `,
396 });
397
398 const read = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
399 sql.withTransaction(effect).pipe(
400 NodeSqliteClient.readOnly,
401 Effect.mapError(
402 (cause) =>
403 new ThreadSearchError({
404 operation: Schema.isSchemaError(cause) ? "decode" : "query",
405 cause,
406 }),
407 ),
408 );
409
410 // A project scope applies before ranking, so other projects' stronger hits
411 // cannot use up the limit.
412 const searchMessages = Effect.fn("ThreadSearch.search")(function* (
413 input: OrchestrationSearchThreadsInput & {
414 readonly projectId: ProjectId | null;
415 /** Threads the caller already lists, which must not use up the limit. */
416 readonly excludedThreadIds?: ReadonlySet<ThreadId>;
417 /** Off for an agent's search, which has no use for the user's picks. */
418 readonly picks?: boolean;
419 },
420 ) {
421 // One message per thread: the best word match, then what the user wrote,
422 // since that is what they remember asking, then the newest by when it was
423 // written. Row order is not age: imported histories arrive in one batch.
424 // Text relevance (bm25) would cost a pass over every hit in history.
425 type Hit = {
426 readonly row: typeof SearchRow.Type;
427 /** The message as it reads, links as their text. */
428 readonly text: string;
429 readonly quality: number;
430 readonly offset: number;
431 };
432 const newer = (left: Hit, right: Hit) =>
433 (right.row.messageCreatedAt ?? "").localeCompare(left.row.messageCreatedAt ?? "");
434 const compareHits = (left: Hit, right: Hit) =>
435 right.quality - left.quality ||
436 Number(left.row.source !== "user") - Number(right.row.source !== "user") ||
437 newer(left, right);
438 const rows = yield* read(
439 Effect.gen(function* () {
440 const index = yield* sql`
441 SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
442 `;
443 const messageSearch = buildMessageSearch(input.query, index.length > 0);
444 return messageSearch === null
445 ? []
446 : yield* searchRows({
447 ...messageSearch,
448 projectId: input.projectId,
449 excludedThreadIds: [...(input.excludedThreadIds ?? [])],
450 });
451 }),
452 );
453 const best = new Map<ThreadId, Hit>();
454 // Matching messages per thread at its best quality: a thread that keeps
455 // using the word ranks above a passing mention, and weaker hits ("Trust"
456 // for "rust") never add to a whole word's count.
457 const hitCounts = new Map<ThreadId, number>();
458 const hitCount = (threadId: ThreadId) => hitCounts.get(threadId) ?? 1;
459 const matchMessage = messageMatcher(input.query);
460 for (const row of rows) {
461 const text = row.text.replace(MARKDOWN_LINK, "$1");
462 const match = matchMessage(text);
463 if (match === null) continue;
464 const hit = { row, text, ...match };
465 const current = best.get(row.threadId);
466 if (current === undefined || hit.quality > current.quality) {
467 hitCounts.set(row.threadId, 1);
468 } else if (hit.quality === current.quality) {
469 hitCounts.set(row.threadId, hitCount(row.threadId) + 1);
470 }
471 if (current === undefined || compareHits(hit, current) < 0) best.set(row.threadId, hit);
472 }
473 // Ranked as clients rank them, with picks and use, before the limit cuts:
474 // a thread picked for this query must come back even when it only
475 // matches in a few old messages.
476 const opens = best.size === 0 ? [] : yield* read(threadOpens({ threadIds: [...best.keys()] }));
477 const subjectById = new Map(
478 opens.map((row) => [
479 row.threadId,
480 {
481 title: "",
482 activityAt: row.latestUserMessageAt === null ? null : Date.parse(row.latestUserMessageAt),
483 opens: Option.getOrNull(decodeThreadOpens(row.opens)),
484 },
485 ]),
486 );
487 const now = DateTime.toEpochMillis(yield* DateTime.now);
488 const ranked = rankMessageMatches(
489 [...best.values()].map((hit) => ({
490 ...hit,
491 hits: hitCount(hit.row.threadId),
492 messageCreatedAt: hit.row.messageCreatedAt,
493 })),
494 (hit) => subjectById.get(hit.row.threadId),
495 foldSearchQuery(input.query),
496 now,
497 { picks: input.picks ?? true },
498 );
499 return {
500 matches: ranked.slice(0, input.limit ?? 50).map(({ row, text, quality, offset }) => ({
501 hits: hitCount(row.threadId),
502 threadId: row.threadId,
503 messageId: row.messageId,
504 projectId: row.projectId,
505 source: row.source,
506 snippet: buildSearchSnippet(text, offset),
507 messageCreatedAt: row.messageCreatedAt,
508 quality,
509 })),
510 };
511 });
512
513 const search: ThreadSearch["Service"]["search"] = (input) =>
514 searchMessages({ ...input, projectId: null });
515
516 const searchThreads: ThreadSearch["Service"]["searchThreads"] = Effect.fn(
517 "ThreadSearch.searchThreads",
518 )(function* (input) {
519 const limit = input.limit ?? 50;
520 const normalizedQuery = foldSearchQuery(input.query);
521 const now = DateTime.toEpochMillis(yield* DateTime.now);
522 // Agents call this rarely, and a project has hundreds of threads, not
523 // millions, so ranking every active thread in memory stays cheap.
524 const candidates = yield* read(titleCandidates({ projectId: input.projectId ?? null }));
525 const subjectById = new Map(
526 candidates.map((row): [ThreadId, ThreadSearchSubject] => [
527 row.thread.id,
528 {
529 id: row.thread.id,
530 title: row.thread.title,
531 branch: row.thread.branch,
532 projectTitle: row.projectTitle,
533 pullRequests: threadSearchPullRequests(row.thread),
534 // Like the clients: what the user last wrote, else when the thread began.
535 activityAt: Date.parse(
536 row.latestUserMessageAt ?? DateTime.formatIso(row.thread.createdAt),
537 ),
538 opens: row.thread.opens ?? null,
539 },
540 ]),
541 );
542 const titleHits: ThreadSearchHit[] = rankSearchItems(candidates, (row, options) =>
543 // An agent's search has no use for the user's palette picks.
544 scoreThreadSearch(normalizedQuery, subjectById.get(row.thread.id)!, now, {
545 ...options,
546 picks: false,
547 }),
548 )
549 .slice(0, limit)
550 .map(({ item }) => ({
551 threadId: item.thread.id,
552 projectId: item.thread.projectId,
553 title: item.thread.title,
554 source: "title",
555 }));
556 const shown = new Set(titleHits.map((hit) => hit.threadId));
557 const { matches } = yield* searchMessages({
558 query: input.query,
559 limit: 50,
560 projectId: input.projectId ?? null,
561 excludedThreadIds: shown,
562 picks: false,
563 });
564 const messageHits = matches
565 .filter((match) => subjectById.has(match.threadId))
566 .map(({ quality: _quality, hits: _hits, messageId: _messageId, ...match }) => ({
567 ...match,
568 title: subjectById.get(match.threadId)!.title,
569 }));
570 // Titles come first, but a fifth of the slots stay for message matches,
571 // as the palette keeps its "In messages" section.
572 const messageSlots = Math.min(messageHits.length, Math.floor(limit / 5));
573 return {
574 matches: [...titleHits.slice(0, limit - messageSlots), ...messageHits].slice(0, limit),
575 };
576 });
577
578 const searchOlderSettled: ThreadSearch["Service"]["searchOlderSettled"] = Effect.fn(
579 "ThreadSearch.searchOlderSettled",
580 )(function* ({ query, before, projectIds, environmentLabel, messageThreadIds }) {
581 const normalizedQuery = foldSearchQuery(query);
582 const now = DateTime.toEpochMillis(yield* DateTime.now);
583 const candidates = yield* read(
584 olderSettledTitleCandidates({ before, projectIds: projectIds ?? null }),
585 );
586 const subjectOf = (row: typeof OlderSettledTitleRow.Type): ThreadSearchSubject => ({
587 id: row.id,
588 title: row.title,
589 branch: row.branch,
590 projectTitle: row.projectTitle,
591 environmentLabel: environmentLabel ?? null,
592 pullRequests: threadSearchPullRequests({
593 pullRequests: row.pullRequests ?? undefined,
594 linkedPullRequest: row.linkedPullRequest,
595 branchPullRequest: row.branchPullRequest,
596 }),
597 // Like the clients: what the user last wrote, else when the thread began.
598 activityAt: Date.parse(row.latestUserMessageAt ?? row.createdAt),
599 opens: Option.getOrNull(decodeThreadOpens(row.opens)),
600 });
601 // Picks on, as in the command palette: a thread picked for this query must make the cut.
602 const titleIds = rankSearchItems(candidates, (row, options) =>
603 scoreThreadSearch(normalizedQuery, subjectOf(row), now, { ...options, picks: true }),
604 )
605 .slice(0, OLDER_SETTLED_TITLE_ROWS)
606 .map(({ item }) => item.id);
607 const shown = new Set(titleIds);
608 const messageCandidates = [...new Set(messageThreadIds)].filter((id) => !shown.has(id));
609 const older =
610 messageCandidates.length === 0
611 ? new Set<ThreadId>()
612 : new Set(
613 (yield* read(
614 olderSettledIds({
615 before,
616 threadIds: messageCandidates,
617 projectIds: projectIds ?? null,
618 }),
619 )).map((row) => row.id),
620 );
621 return [
622 ...titleIds,
623 ...messageCandidates.filter((id) => older.has(id)).slice(0, OLDER_SETTLED_MESSAGE_ROWS),
624 ];
625 });
626
627 return ThreadSearch.of({ search, searchThreads, searchOlderSettled });
628});
629
630export const layer = Layer.effect(ThreadSearch, make);
631
632/**
633 * The client search: message hits, and with `olderSettledBefore`, the rows of the best older
634 * settled matches, which shells that omit them do not hold.
635 */
636export const searchThreadsWithOlderSettledRows = Effect.fn(
637 "ThreadSearch.searchThreadsWithOlderSettledRows",
638)(function* <E1, E2, E3, E4, E5>(input: {
639 readonly request: OrchestrationV2SearchThreadsInput;
640 readonly search: (
641 input: OrchestrationSearchThreadsInput,
642 ) => Effect.Effect<OrchestrationSearchThreadsResult, E1>;
643 readonly searchOlderSettled: (
644 input: Parameters<ThreadSearch["Service"]["searchOlderSettled"]>[0],
645 ) => Effect.Effect<ReadonlyArray<ThreadId>, E2>;
646 readonly sql: SqlClient.SqlClient;
647 readonly readThreads: (
648 threadIds: ReadonlyArray<ThreadId>,
649 ) => Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E4>, E3>;
650 readonly latestSequence: Effect.Effect<number, E5>;
651}) {
652 const { olderSettledBefore, projectIds, environmentLabel, titlesOnly, ...request } =
653 input.request;
654 const messages: OrchestrationV2SearchThreadsResult =
655 titlesOnly === true ? { matches: [] } : yield* input.search(request);
656 if (olderSettledBefore === undefined) return messages;
657 // Ranked before the rows' transaction, so scoring never holds the shared reader.
658 const threadIds = yield* input.searchOlderSettled({
659 query: request.query,
660 before: olderSettledBefore,
661 projectIds,
662 environmentLabel,
663 messageThreadIds: messages.matches.map((match) => match.threadId),
664 });
665 const older = yield* loadOlderSettledThreadsPage({
666 sql: input.sql,
667 listThreads: Effect.succeed({ threadIds, counts: [] }),
668 readThreads: input.readThreads,
669 latestSequence: input.latestSequence,
670 });
671 return { ...messages, snapshotSequence: older.snapshotSequence, threads: older.threads };
672});