Open History to see the last commit
1import {
2 IsoDateTime,
3 OrchestrationThreadSearchSource,
4 type OrchestrationSearchThreadsInput,
5 type OrchestrationSearchThreadsResult,
6 ProjectId,
7 ThreadId,
8} from "@t3tools/contracts";
9import * as Context from "effect/Context";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Schema from "effect/Schema";
13import * as SqlClient from "effect/sql/SqlClient";
14import * as SqlSchema from "effect/sql/SqlSchema";
15import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
16
17export class ThreadSearchError extends Schema.TaggedError<ThreadSearchError>()(
18 "ThreadSearchError",
19 {
20 operation: Schema.Literals(["query", "decode"]),
21 cause: Schema.Defect(),
22 },
23) {
24 override get message(): string {
25 return `Thread search ${this.operation} failed.`;
26 }
27}
28
29const SearchRequest = Schema.Struct({ pattern: Schema.String, limit: Schema.Int });
30const SearchRow = Schema.Struct({
31 threadId: ThreadId,
32 projectId: ProjectId,
33 source: OrchestrationThreadSearchSource,
34 matchText: Schema.String,
35 messageCreatedAt: Schema.NullOr(IsoDateTime),
36});
37
38function escapeLikePattern(value: string): string {
39 return value.replaceAll("!", "!!").replaceAll("%", "!%").replaceAll("_", "!_");
40}
41
42function foldAsciiCase(value: string): string {
43 return value.replace(/[A-Z]/g, (character) => character.toLowerCase());
44}
45
46function buildSearchSnippet(text: string, query: string): string {
47 const normalizedText = text.replace(/\s+/g, " ").trim();
48 if (normalizedText.length <= 240) {
49 return normalizedText;
50 }
51 const normalizedQuery = foldAsciiCase(query.replace(/\s+/g, " ").trim());
52 const matchIndex = foldAsciiCase(normalizedText).indexOf(normalizedQuery);
53 const bodyLength = 236;
54 const idealStart = Math.max(0, matchIndex - 72);
55 const start = Math.min(idealStart, normalizedText.length - bodyLength);
56 const end = Math.min(normalizedText.length, start + bodyLength);
57 return `${start > 0 ? "…" : ""}${normalizedText.slice(start, end)}${
58 end < normalizedText.length ? "…" : ""
59 }`;
60}
61
62export class ThreadSearch extends Context.Service<
63 ThreadSearch,
64 {
65 readonly search: (
66 input: OrchestrationSearchThreadsInput,
67 ) => Effect.Effect<OrchestrationSearchThreadsResult, ThreadSearchError>;
68 }
69>()("t3/orchestration-v2/ThreadSearch") {}
70
71/** @public Service construction is part of the canonical Effect module API. */
72export const make = Effect.gen(function* () {
73 const sql = yield* SqlClient.SqlClient;
74
75 const searchRows = SqlSchema.findAll({
76 Request: SearchRequest,
77 Result: SearchRow,
78 execute: ({ pattern, limit }) => sql`
79 WITH candidate AS (
80 SELECT
81 threads.thread_id,
82 threads.project_id,
83 messages.role,
84 json_extract(messages.payload_json, '$.text') AS match_text,
85 messages.created_at AS message_created_at,
86 messages.message_id,
87 threads.updated_at AS thread_updated_at
88 FROM orchestration_v2_projection_messages AS messages
89 INNER JOIN orchestration_v2_projection_threads AS threads
90 ON threads.thread_id = messages.thread_id
91 INNER JOIN projection_projects AS projects
92 ON projects.project_id = threads.project_id
93 WHERE threads.deleted_at IS NULL
94 AND threads.archived_at IS NULL
95 AND projects.deleted_at IS NULL
96 AND messages.streaming = 0
97 AND messages.role IN ('user', 'assistant')
98 AND json_extract(messages.payload_json, '$.text') LIKE ${pattern} ESCAPE '!'
99 ),
100 ranked AS (
101 SELECT
102 thread_id,
103 project_id,
104 role AS source,
105 match_text,
106 message_created_at,
107 CASE role WHEN 'user' THEN 0 ELSE 1 END AS match_rank,
108 thread_updated_at,
109 ROW_NUMBER() OVER (
110 PARTITION BY thread_id
111 ORDER BY
112 CASE role WHEN 'user' THEN 0 ELSE 1 END ASC,
113 message_created_at DESC,
114 message_id ASC
115 ) AS thread_match_rank
116 FROM candidate
117 )
118 SELECT
119 thread_id AS "threadId",
120 project_id AS "projectId",
121 source,
122 match_text AS "matchText",
123 message_created_at AS "messageCreatedAt"
124 FROM ranked
125 WHERE thread_match_rank = 1
126 ORDER BY match_rank ASC, thread_updated_at DESC, thread_id ASC
127 LIMIT ${limit}
128 `,
129 });
130
131 const search: ThreadSearch["Service"]["search"] = Effect.fn("ThreadSearch.search")(
132 function* (input) {
133 // The scan reads every message, so run it on the reader worker rather
134 // than the event loop.
135 const rows = yield* sql
136 .withTransaction(
137 searchRows({
138 pattern: `%${escapeLikePattern(input.query)}%`,
139 limit: input.limit ?? 50,
140 }),
141 )
142 .pipe(
143 NodeSqliteClient.readOnly,
144 Effect.mapError(
145 (cause) =>
146 new ThreadSearchError({
147 operation: Schema.isSchemaError(cause) ? "decode" : "query",
148 cause,
149 }),
150 ),
151 );
152 return {
153 matches: rows.map((row) => ({
154 threadId: row.threadId,
155 projectId: row.projectId,
156 source: row.source,
157 snippet: buildSearchSnippet(row.matchText, input.query),
158 messageCreatedAt: row.messageCreatedAt,
159 })),
160 };
161 },
162 );
163
164 return ThreadSearch.of({ search });
165});
166
167export const layer = Layer.effect(ThreadSearch, make);