Open History to see the last commit
1import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
2import * as Effect from "effect/Effect";
3import type * as SqlClient from "effect/sql/SqlClient";
4
5// SQLite's ltrim needs the characters matched by isAttachmentOnlyBootstrapPrompt's \s explicitly.
6const BOOTSTRAP_PREFIX_WHITESPACE =
7 "\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff";
8
9export const nonPlaceholderMessageCondition = (sql: SqlClient.SqlClient, row = "messages") =>
10 sql.literal(`
11 CASE
12 WHEN substr(json_extract(${row}.payload_json, '$.text'), 1, 11) = 'Ultrathink:' COLLATE NOCASE
13 THEN ltrim(substr(json_extract(${row}.payload_json, '$.text'), 12), '${BOOTSTRAP_PREFIX_WHITESPACE}')
14 ELSE json_extract(${row}.payload_json, '$.text')
15 END COLLATE BINARY <> '${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT.replaceAll("'", "''")}'
16`);
17
18/**
19 * Exclude attachment placeholders, generated notices and subagent threads. ACP subagents
20 * rewrite their finished answer on every streamed chunk.
21 * Migration triggers, backfill, rebuild and scans share this predicate; `row` may be `new`.
22 */
23export const indexedMessageCondition = (sql: SqlClient.SqlClient, row = "messages") =>
24 sql`
25 ${sql.literal(`
26 ${row}.streaming = 0
27 AND (
28 ${row}.role = 'assistant'
29 OR (
30 ${row}.role = 'user'
31 AND COALESCE(json_extract(${row}.payload_json, '$.createdBy'), 'user') = 'user'
32 )
33 )
34 AND NOT EXISTS (
35 SELECT 1 FROM orchestration_v2_projection_threads AS subagent_threads
36 WHERE subagent_threads.thread_id = ${row}.thread_id
37 AND json_extract(subagent_threads.payload_json, '$.lineage.relationshipToParent') = 'subagent'
38 )
39`)}
40 AND ${nonPlaceholderMessageCondition(sql, row)}
41`;
42
43/**
44 * What the index stores for a message: its text with curly apostrophes
45 * straight, as search folds a query, since iOS keyboards type "’" and others
46 * type "'". Migration 69's triggers use it too. `payload` is the message's
47 * JSON column.
48 */
49export const indexedMessageText = (sql: SqlClient.SqlClient, payload: string) =>
50 sql.literal(`replace(replace(json_extract(${payload}, '$.text'), '’', ''''), '‘', '''')`);
51
52export const createMessageSearchTriggers = Effect.fn("MessageSearchIndex.createTriggers")(
53 function* (sql: SqlClient.SqlClient) {
54 yield* sql`
55 CREATE TRIGGER orchestration_v2_message_search_insert
56 AFTER INSERT ON orchestration_v2_projection_messages
57 WHEN ${indexedMessageCondition(sql, "new")}
58 BEGIN
59 INSERT INTO orchestration_v2_message_search (rowid, text)
60 SELECT new.rowid, ${indexedMessageText(sql, "new.payload_json")}
61 WHERE json_extract(new.payload_json, '$.text') IS NOT NULL;
62 END
63 `;
64 // Streaming deltas rewrite the row many times a second; skip them until the
65 // message settles. Upserts rewrite every column, so a finished message
66 // re-indexes only when what the index reads changed. Deleting a rowid the
67 // index never held is a no-op.
68 yield* sql`
69 CREATE TRIGGER orchestration_v2_message_search_update
70 AFTER UPDATE OF payload_json, streaming, role ON orchestration_v2_projection_messages
71 WHEN (old.streaming = 0 OR new.streaming = 0)
72 AND (
73 old.streaming IS NOT new.streaming
74 OR old.role IS NOT new.role
75 OR json_extract(old.payload_json, '$.text') IS NOT json_extract(new.payload_json, '$.text')
76 OR json_extract(old.payload_json, '$.createdBy')
77 IS NOT json_extract(new.payload_json, '$.createdBy')
78 )
79 BEGIN
80 DELETE FROM orchestration_v2_message_search WHERE rowid = old.rowid AND old.streaming = 0;
81 INSERT INTO orchestration_v2_message_search (rowid, text)
82 SELECT new.rowid, ${indexedMessageText(sql, "new.payload_json")}
83 WHERE ${indexedMessageCondition(sql, "new")}
84 AND json_extract(new.payload_json, '$.text') IS NOT NULL;
85 END
86 `;
87 yield* sql`
88 CREATE TRIGGER orchestration_v2_message_search_delete
89 AFTER DELETE ON orchestration_v2_projection_messages
90 WHEN old.streaming = 0
91 BEGIN
92 DELETE FROM orchestration_v2_message_search WHERE rowid = old.rowid;
93 END
94 `;
95 },
96);
97
98/**
99 * Refills the search index from the messages table. The index is keyed by
100 * message rowid, so anything that may renumber or copy rows (VACUUM, a dev
101 * database copy) rebuilds it instead of trusting it. Databases from before
102 * migration 69, or on an SQLite without FTS5 trigrams, have no index.
103 */
104export const rebuildMessageSearch = Effect.fn("MessageSearchIndex.rebuild")(function* (
105 sql: SqlClient.SqlClient,
106) {
107 const index = yield* sql`
108 SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
109 `;
110 if (index.length === 0) return;
111 // One transaction: an interrupt between clear and refill would leave an
112 // empty index that nothing repairs, since search only checks the table exists.
113 yield* sql.withTransaction(
114 Effect.gen(function* () {
115 yield* sql`
116 INSERT INTO orchestration_v2_message_search (orchestration_v2_message_search)
117 VALUES ('delete-all')
118 `;
119 yield* sql`
120 INSERT INTO orchestration_v2_message_search (rowid, text)
121 SELECT messages.rowid, ${indexedMessageText(sql, "messages.payload_json")}
122 FROM orchestration_v2_projection_messages AS messages
123 WHERE ${indexedMessageCondition(sql)}
124 AND json_extract(messages.payload_json, '$.text') IS NOT NULL
125 `;
126 }),
127 );
128});