Open History to see the last commit
1import {
2 OrchestrationV2TurnItemJson,
3 type OrchestrationV2ProjectedTurnItem,
4 OrchestrationV2SearchThreadInput,
5 type OrchestrationV2SearchThreadResult,
6 type OrchestrationV2TurnItem,
7 ThreadId,
8 TurnItemId,
9} from "@t3tools/contracts";
10import { searchableMessageSegments, searchablePlanSegments } from "@t3tools/shared/threadFindText";
11import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
12import { htmlRenderFromToolItem, mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
13import * as Cache from "effect/Cache";
14import * as Data from "effect/Data";
15import * as Effect from "effect/Effect";
16import * as RcRef from "effect/RcRef";
17import * as Schema from "effect/Schema";
18import * as Stream from "effect/Stream";
19import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
20import * as SqlClient from "effect/sql/SqlClient";
21import { JAVASCRIPT_TRIM_WHITESPACE } from "./deferredCommandMessage.ts";
22import {
23 ProjectionStoreReadError,
24 ProjectionStoreThreadNotFoundError,
25 type ProjectionStoreV2Error,
26} from "./ProjectionStore.ts";
27
28interface FindRow {
29 readonly position: number;
30 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
31 readonly sourceThreadId: ThreadId;
32 readonly sourceItemId: TurnItemId;
33}
34interface FindPayload extends FindRow {
35 readonly payload: string;
36 readonly entryId: string;
37 readonly runId: OrchestrationV2TurnItem["runId"];
38 readonly type: OrchestrationV2TurnItem["type"];
39 readonly emptyText: boolean;
40}
41interface FindDocument extends FindRow {
42 readonly entryId: string;
43 readonly runId: OrchestrationV2TurnItem["runId"];
44 readonly count: number;
45}
46interface RenderedDocument extends Omit<FindDocument, "count"> {
47 readonly segments: readonly string[];
48 readonly sourceLength: number;
49}
50type CompletedScans = Map<
51 string,
52 {
53 sequence: number;
54 documents: readonly FindDocument[];
55 sourceThreadIds: readonly ThreadId[];
56 }
57>;
58// Segments may retain slices of their source text, so the budget includes both.
59interface RenderedSnapshot {
60 current:
61 | {
62 key: string;
63 sequence: number;
64 documents: readonly RenderedDocument[];
65 sourceThreadIds: readonly ThreadId[];
66 }
67 | undefined;
68}
69class TextKey extends Data.Class<{
70 text: string;
71 role: "user" | "assistant" | "plan";
72 streaming: boolean;
73 hasContext: boolean;
74 cwd: string | undefined;
75 skills: NonNullable<OrchestrationV2SearchThreadInput["skills"]>;
76 theme: OrchestrationV2SearchThreadInput["theme"];
77}> {}
78
79function textKey(
80 item: OrchestrationV2TurnItem,
81 cwd: string | undefined,
82 skills: TextKey["skills"],
83 theme: TextKey["theme"],
84) {
85 return new TextKey({
86 text:
87 item.type === "proposed_plan"
88 ? item.markdown
89 : item.type === "user_message" || item.type === "assistant_message"
90 ? item.text
91 : "",
92 role:
93 item.type === "proposed_plan" ? "plan" : item.type === "user_message" ? "user" : "assistant",
94 streaming: item.type === "assistant_message" && item.streaming,
95 hasContext: item.type === "user_message" && item.context !== undefined,
96 cwd,
97 skills,
98 theme,
99 });
100}
101
102function parseText(key: TextKey): readonly string[] {
103 return key.role === "plan"
104 ? searchablePlanSegments(key.text, key.cwd, key.theme)
105 : (searchableMessageSegments(
106 {
107 role: key.role,
108 text: key.text,
109 streaming: key.streaming,
110 context: key.hasContext ? { version: 1, records: [] } : undefined,
111 },
112 key.cwd,
113 key.skills,
114 key.theme,
115 ) ?? []);
116}
117
118function documentFor(row: OrchestrationV2ProjectedTurnItem, count: number): FindDocument {
119 return {
120 position: row.position,
121 visibility: row.visibility,
122 sourceThreadId: row.sourceThreadId,
123 sourceItemId: row.sourceItemId,
124 entryId:
125 row.item.type === "user_message" || row.item.type === "assistant_message"
126 ? row.item.messageId
127 : row.item.id,
128 runId: row.item.runId,
129 count,
130 };
131}
132
133function countSegments(segments: readonly string[], query: string) {
134 return segments.reduce((sum, text) => sum + countThreadSearchOccurrences(text, query), 0);
135}
136
137function selectMatch(
138 documents: readonly FindDocument[],
139 input: Pick<OrchestrationV2SearchThreadInput, "index" | "start" | "offset">,
140) {
141 const totalMatches = documents.reduce((sum, doc) => sum + doc.count, 0);
142 let requestedIndex = input.index ?? 0;
143 if (input.index === undefined && input.start) {
144 const startIndex = documents.findIndex((doc) => doc.entryId === input.start?.entryId);
145 if (startIndex >= 0) {
146 requestedIndex =
147 documents.slice(0, startIndex).reduce((sum, doc) => sum + doc.count, 0) +
148 Math.min(input.start.occurrence, documents[startIndex]!.count);
149 if (requestedIndex >= totalMatches) requestedIndex = 0;
150 }
151 }
152 const activeIndex =
153 input.index === undefined && totalMatches > 0
154 ? (((requestedIndex + (input.offset ?? 0)) % totalMatches) + totalMatches) % totalMatches
155 : Math.min(requestedIndex, Math.max(0, totalMatches - 1));
156 let occurrence = activeIndex;
157 for (const document of documents) {
158 if (occurrence < document.count) return { totalMatches, activeIndex, document, occurrence };
159 occurrence -= document.count;
160 }
161 return { totalMatches, activeIndex, document: null, occurrence: 0 };
162}
163
164function resultForSelection(
165 selected: ReturnType<typeof selectMatch>,
166 documents: readonly FindDocument[],
167 snapshotSequence: number,
168): OrchestrationV2SearchThreadResult {
169 let startIndex = 0;
170 const entries = documents.flatMap(({ entryId, runId, count }) => {
171 const entry = { entryId, runId, count, startIndex };
172 startIndex += count;
173 return count > 0 ? [entry] : [];
174 });
175 const selectedEntry = entries.findIndex((entry) => entry.entryId === selected.document?.entryId);
176 const navigation =
177 entries.length <= 17
178 ? entries
179 : Array.from(
180 { length: 17 },
181 (_, i) => entries[(selectedEntry + i - 8 + entries.length) % entries.length]!,
182 );
183 return {
184 snapshotSequence,
185 totalMatches: selected.totalMatches,
186 activeIndex: selected.activeIndex,
187 navigation,
188 match:
189 selected.document === null
190 ? null
191 : {
192 entryId: selected.document.entryId,
193 runId: selected.document.runId,
194 occurrence: selected.occurrence,
195 },
196 };
197}
198
199export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
200 readIndex: (threadId: ThreadId) => Effect.Effect<
201 readonly (Omit<FindRow, "position"> & {
202 readonly item: Pick<OrchestrationV2TurnItem, "type" | "runId">;
203 })[],
204 ProjectionStoreV2Error
205 >,
206) {
207 const sql = yield* SqlClient.SqlClient;
208 const encodeCacheKey = Schema.encodeEffect(
209 Schema.fromJsonString(
210 Schema.Struct({
211 threadId: ThreadId,
212 cwd: Schema.optional(Schema.String),
213 query: Schema.optional(Schema.String),
214 skills: OrchestrationV2SearchThreadInput.fields.skills,
215 theme: OrchestrationV2SearchThreadInput.fields.theme,
216 }),
217 ),
218 );
219 const encodeThreadIds = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(ThreadId)));
220 const encodeSources = Schema.encodeEffect(
221 Schema.fromJsonString(Schema.Array(Schema.Struct({ threadId: ThreadId, id: TurnItemId }))),
222 );
223 const decodeItem = Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2TurnItemJson));
224 const isSnapshotError = Schema.is(
225 Schema.Union([ProjectionStoreReadError, ProjectionStoreThreadNotFoundError]),
226 );
227 const load = Effect.fn("ThreadFind.load")(function* (
228 threadId: ThreadId,
229 rows: readonly FindRow[],
230 ) {
231 if (rows.length === 0) return [];
232 const sources = yield* encodeSources(
233 rows.map((row) => ({ threadId: row.sourceThreadId, id: row.sourceItemId })),
234 ).pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })));
235 const payloads = yield* sql<{
236 thread_id: string;
237 turn_item_id: string;
238 payload_json: string;
239 entry_id: string;
240 run_id: OrchestrationV2TurnItem["runId"];
241 item_type: OrchestrationV2TurnItem["type"];
242 empty_text: number | null;
243 }>`
244 SELECT item.thread_id, item.turn_item_id, item.payload_json,
245 COALESCE(json_extract(item.payload_json, '$.messageId'), item.turn_item_id) AS entry_id,
246 json_extract(item.payload_json, '$.runId') AS run_id,
247 json_extract(item.payload_json, '$.type') AS item_type,
248 trim(json_extract(item.payload_json, '$.text'), ${JAVASCRIPT_TRIM_WHITESPACE}) = '' AS empty_text
249 FROM orchestration_v2_projection_turn_items AS item
250 JOIN json_each(${sources}) AS wanted
251 ON item.thread_id = json_extract(wanted.value, '$.threadId')
252 AND item.turn_item_id = json_extract(wanted.value, '$.id')
253 `.pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })));
254 const byThread = new Map<string, Map<string, (typeof payloads)[number]>>();
255 for (const row of payloads) {
256 let items = byThread.get(row.thread_id);
257 if (!items) byThread.set(row.thread_id, (items = new Map()));
258 items.set(row.turn_item_id, row);
259 }
260 return yield* Effect.forEach(rows, (row) => {
261 const payload = byThread.get(row.sourceThreadId)?.get(row.sourceItemId);
262 return payload === undefined
263 ? Effect.fail(new ProjectionStoreReadError({ threadId }))
264 : Effect.succeed({
265 ...row,
266 payload: payload.payload_json,
267 entryId: payload.entry_id,
268 runId: payload.run_id,
269 type: payload.item_type,
270 emptyText: payload.empty_text === 1,
271 });
272 });
273 });
274 const makeTextCache = (capacity: number) =>
275 Cache.make({ capacity, lookup: (key: TextKey) => Effect.sync(() => parseText(key)) });
276 // Text keys are message content, so entries never go stale. Cache TTL only expires on access
277 // and would keep the last searched threads forever. Each search borrows this for its whole
278 // stream, and all of it is dropped once Find is idle.
279 const findCaches = yield* RcRef.make({
280 acquire: Effect.all({
281 // Scans visit every message; a cache smaller than the thread churns without hits.
282 text: makeTextCache(8192),
283 // Bounded separately because each entry can hold a large body; typing reuses the parse.
284 largeText: makeTextCache(32),
285 scans: Effect.sync((): CompletedScans => new Map()),
286 rendered: Effect.sync((): RenderedSnapshot => ({ current: undefined })),
287 }),
288 idleTimeToLive: "1 minute",
289 });
290 const readRevision = Effect.fn("ThreadFind.readRevision")(function* (
291 threadIds: readonly ThreadId[],
292 ) {
293 const sources = yield* encodeThreadIds(threadIds);
294 const revision = yield* sql<{ sequence: number }>`
295 WITH RECURSIVE source_threads(thread_id) AS (
296 SELECT value FROM json_each(${sources})
297 UNION
298 SELECT json_extract(t.payload_json, '$.forkedFrom.threadId')
299 FROM orchestration_v2_projection_threads t
300 JOIN source_threads s ON s.thread_id = t.thread_id
301 WHERE json_extract(t.payload_json, '$.forkedFrom.type') = 'run'
302 )
303 SELECT COALESCE(MAX(sequence), 0) AS sequence FROM orchestration_events
304 -- The planner otherwise walks every V2 event backwards from the newest,
305 -- which takes seconds for a thread that has been idle a long time.
306 INDEXED BY idx_orch_events_stream_sequence
307 WHERE application_event_version = 2 AND aggregate_kind = 'thread'
308 AND stream_id IN (SELECT thread_id FROM source_threads)
309 `;
310 return revision[0]?.sequence ?? 0;
311 });
312 const snapshot = Effect.fn("ThreadFind.snapshot")(
313 function* (
314 input: OrchestrationV2SearchThreadInput,
315 scans: CompletedScans,
316 renderedSnapshot: RenderedSnapshot,
317 ) {
318 const { threadId, theme } = input;
319 const active = yield* sql<{ cwd: string | null }>`
320 SELECT COALESCE(json_extract(t.payload_json, '$.worktreePath'), p.workspace_root) AS cwd
321 FROM orchestration_v2_projection_threads t JOIN projection_projects p ON p.project_id = t.project_id
322 WHERE t.thread_id = ${threadId} AND t.deleted_at IS NULL AND p.deleted_at IS NULL
323 `;
324 if (!active[0]) return yield* new ProjectionStoreThreadNotFoundError({ threadId });
325 const cwd = active[0].cwd ?? undefined;
326 const cacheKey = yield* encodeCacheKey({
327 threadId,
328 cwd,
329 query: input.query,
330 skills: input.skills ?? [],
331 ...(theme === undefined ? {} : { theme }),
332 });
333 const cached = scans.get(cacheKey);
334 if (cached && cached.sequence === (yield* readRevision(cached.sourceThreadIds))) {
335 const selected = selectMatch(cached.documents, input);
336 scans.delete(cacheKey);
337 scans.set(cacheKey, cached);
338 return { result: resultForSelection(selected, cached.documents, cached.sequence) };
339 }
340 const documentKey = yield* encodeCacheKey({
341 threadId,
342 cwd,
343 skills: input.skills ?? [],
344 ...(theme === undefined ? {} : { theme }),
345 });
346 const rendered = renderedSnapshot.current;
347 if (
348 rendered?.key === documentKey &&
349 rendered.sequence === (yield* readRevision(rendered.sourceThreadIds))
350 ) {
351 return {
352 rendered: rendered.documents,
353 cwd,
354 sequence: rendered.sequence,
355 cacheKey,
356 documentKey,
357 sourceThreadIds: rendered.sourceThreadIds,
358 };
359 }
360 const index = yield* readIndex(threadId);
361 const sourceThreadIds = [...new Set([threadId, ...index.map((row) => row.sourceThreadId)])];
362 const sequence = yield* readRevision(sourceThreadIds);
363 const candidates = index
364 .map((row, position) => ({ ...row, position }))
365 .filter((row) =>
366 ["user_message", "assistant_message", "proposed_plan", "user_input_request"].includes(
367 row.item.type,
368 ),
369 );
370 const loadAll = Effect.fnUntraced(function* (rows: readonly FindRow[]) {
371 const loaded: FindPayload[] = [];
372 for (let start = 0; start < rows.length; start += 128) {
373 loaded.push(...(yield* load(threadId, rows.slice(start, start + 128))));
374 }
375 return loaded;
376 });
377 const payloads = yield* loadAll(candidates);
378 // Only runs with an empty reply can hide its fallback, so other tool payloads stay unread.
379 const emptyReplyRunIds = new Set(
380 payloads.flatMap((row) =>
381 row.type === "assistant_message" && row.emptyText && row.runId !== null
382 ? [row.runId]
383 : [],
384 ),
385 );
386 const toolPayloads = yield* loadAll(
387 index
388 .map((row, position) => ({ ...row, position }))
389 .filter(
390 (row) =>
391 row.item.type === "dynamic_tool" &&
392 row.item.runId !== null &&
393 emptyReplyRunIds.has(row.item.runId),
394 ),
395 );
396 return { payloads, toolPayloads, cwd, sequence, cacheKey, documentKey, sourceThreadIds };
397 },
398 (effect) => sql.withTransaction(effect).pipe(NodeSqliteClient.readOnly),
399 (effect, input) =>
400 effect.pipe(
401 Effect.mapError((cause) =>
402 isSnapshotError(cause)
403 ? cause
404 : new ProjectionStoreReadError({ threadId: input.threadId, cause }),
405 ),
406 ),
407 );
408 const searchThreadStream = (input: OrchestrationV2SearchThreadInput) =>
409 Stream.unwrap(
410 Effect.gen(function* () {
411 const { scans, rendered: renderedSnapshot, ...textCache } = yield* RcRef.get(findCaches);
412 // Release SQLite before decoding and parsing. Both frames describe one snapshot.
413 const data = yield* snapshot(input, scans, renderedSnapshot);
414 if (data.result) return Stream.succeed(data.result);
415 const { cwd, sequence, cacheKey, documentKey, sourceThreadIds } = data;
416 const payloads = data.payloads ?? [];
417 const toolPayloads = data.toolPayloads ?? [];
418 const decode = (row: FindPayload) =>
419 decodeItem(row.payload).pipe(
420 Effect.map((item) => ({ ...row, item })),
421 Effect.mapError(
422 (cause) => new ProjectionStoreReadError({ threadId: input.threadId, cause }),
423 ),
424 );
425 // Answers rendered inside question cards must not appear as separate matches.
426 const foldedAnswerRunIds = new Map<string, OrchestrationV2TurnItem["runId"]>();
427 for (const payload of payloads) {
428 if (payload.type !== "user_input_request") continue;
429 const { item } = yield* decode(payload);
430 if (item.type === "user_input_request" && item.questionAnswer)
431 foldedAnswerRunIds.set(`async-answer:${item.questionAnswer.requestId}`, item.runId);
432 }
433 // The timeline hides an empty reply's fallback when its run shows an HTML render or MCP app.
434 const embeddedResultRunIds = new Set<OrchestrationV2TurnItem["runId"]>();
435 for (const payload of toolPayloads) {
436 const { item } = yield* decode(payload);
437 if (
438 item.type === "dynamic_tool" &&
439 ((item.status === "completed" && htmlRenderFromToolItem(item)) ||
440 mcpAppFromToolItem(item))
441 )
442 embeddedResultRunIds.add(item.runId);
443 }
444 const rows =
445 data.rendered ??
446 payloads.filter(
447 (row) =>
448 row.type !== "user_input_request" &&
449 !(row.type === "user_message" && foldedAnswerRunIds.get(row.entryId) === row.runId),
450 );
451 const documents = new Map<number, FindDocument & RenderedDocument>();
452 const count = Effect.fnUntraced(function* (row: FindPayload | RenderedDocument) {
453 const cached = documents.get(row.position);
454 if (cached) return cached;
455 let rendered: RenderedDocument;
456 if ("segments" in row) {
457 rendered = row;
458 } else {
459 const decoded = yield* decode(row);
460 const key = textKey(decoded.item, cwd, input.skills ?? [], input.theme);
461 const segments =
462 decoded.item.type === "assistant_message" &&
463 row.emptyText &&
464 embeddedResultRunIds.has(decoded.item.runId)
465 ? []
466 : yield* Cache.get(
467 key.text.length <= 32_768 ? textCache.text : textCache.largeText,
468 key,
469 );
470 rendered = { ...documentFor(decoded, 0), segments, sourceLength: key.text.length };
471 }
472 const document = {
473 ...rendered,
474 count: countSegments(rendered.segments, input.query),
475 };
476 documents.set(row.position, document);
477 yield* Effect.yieldNow;
478 return document;
479 });
480 const finish = Effect.gen(function* () {
481 for (const row of rows) yield* count(row);
482 const ordered = rows.map((row) => documents.get(row.position)!);
483 renderedSnapshot.current =
484 ordered.length <= 8192 &&
485 ordered.reduce(
486 (size, doc) =>
487 size + doc.sourceLength + doc.segments.reduce((sum, text) => sum + text.length, 0),
488 0,
489 ) <= 2_097_152
490 ? { key: documentKey, sequence, documents: ordered, sourceThreadIds }
491 : undefined;
492 scans.delete(cacheKey);
493 scans.set(cacheKey, {
494 sequence,
495 documents: ordered.map(
496 ({ segments: _segments, sourceLength: _sourceLength, ...document }) => document,
497 ),
498 sourceThreadIds,
499 });
500 if (scans.size > 8) {
501 const oldest = scans.keys().next().value;
502 if (oldest !== undefined) scans.delete(oldest);
503 }
504 return resultForSelection(selectMatch(ordered, input), ordered, sequence);
505 });
506 if (input.index !== undefined || (input.offset ?? 0) !== 0)
507 return Stream.fromEffect(finish);
508 const anchor = Math.max(
509 0,
510 rows.findIndex((row) => row.entryId === input.start?.entryId),
511 );
512 for (let step = 0; step <= rows.length; step++) {
513 const index = (anchor + step) % rows.length;
514 const row = rows[index];
515 if (!row) break;
516 const document = yield* count(row);
517 const occurrence =
518 step === 0 && row.entryId === input.start?.entryId
519 ? Math.min(input.start.occurrence, document.count)
520 : 0;
521 if (occurrence >= document.count) continue;
522 const first: OrchestrationV2SearchThreadResult = {
523 complete: false,
524 snapshotSequence: sequence,
525 totalMatches: 1,
526 activeIndex: 0,
527 match: { entryId: document.entryId, runId: document.runId, occurrence },
528 };
529 return Stream.concat(Stream.succeed(first), Stream.fromEffect(finish));
530 }
531 return Stream.fromEffect(finish);
532 }),
533 );
534 return {
535 searchThreadStream,
536 searchThread: (input: OrchestrationV2SearchThreadInput) =>
537 searchThreadStream(input).pipe(
538 Stream.runCollect,
539 Effect.map((results) => results[results.length - 1]!),
540 ),
541 };
542});