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

ThreadFind.ts

534 lines20.5 KB

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