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

ThreadSearch.ts

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