Open History to see the last commit
1import { assert, it, describe } from "@effect/vitest";
2import { searchableMessageSegments } from "@t3tools/shared/threadFindText";
3import {
4 EventId,
5 MessageId,
6 PlanId,
7 RunId,
8 RuntimeRequestId,
9 TurnItemId,
10 type OrchestrationV2TurnItem,
11 type OrchestrationV2Run,
12 type OrchestrationV2ThreadHistoryPage,
13 ProjectId,
14 ProviderInstanceId,
15 ThreadId,
16 type OrchestrationV2DomainEvent,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
21import * as Layer from "effect/Layer";
22import * as SqlClient from "effect/sql/SqlClient";
23import * as Statement from "effect/sql/Statement";
24import * as Stream from "effect/Stream";
25import * as TestClock from "effect/testing/TestClock";
26import * as Tracer from "effect/Tracer";
27import { vi } from "vite-plus/test";
28
29import * as SqlitePersistence from "../persistence/Sqlite.ts";
30import * as ProjectionStore from "./ProjectionStore.ts";
31import * as ProjectStore from "./ProjectStore.ts";
32import * as EventStore from "./EventStore.ts";
33import {
34 encodeThreadHistoryCursor,
35 selectHistoryPageFromCursor,
36 THREAD_HISTORY_PAGE_POLICY,
37} from "./threadHistoryPaging.ts";
38import { projectTurnItemForWire } from "./WireProjection.ts";
39
40vi.mock("@t3tools/shared/threadFindText", { spy: true });
41
42const layerTest = Layer.mergeAll(
43 EventStore.layer,
44 ProjectionStore.layer.pipe(Layer.provide(NodeCrypto.layerDigest)),
45 ProjectStore.layer,
46).pipe(Layer.provideMerge(SqlitePersistence.layerMemory));
47
48const providerInstanceId = ProviderInstanceId.make("codex");
49const at = (minute: number) => DateTime.makeUnsafe(Date.UTC(2026, 8, 27, 0, minute));
50
51const createProject = (projectId: ProjectId) =>
52 Effect.flatMap(ProjectStore.ProjectStoreV2, (projects) =>
53 projects.apply({
54 sequence: 0,
55 eventId: EventId.make(`created:${projectId}`),
56 aggregateKind: "project",
57 aggregateId: projectId,
58 occurredAt: DateTime.formatIso(at(0)),
59 commandId: null,
60 causationEventId: null,
61 correlationId: null,
62 metadata: {},
63 type: "project.created",
64 payload: {
65 projectId,
66 title: projectId,
67 workspaceRoot: `/work/${projectId}`,
68 defaultModelSelection: null,
69 scripts: [],
70 createdAt: DateTime.formatIso(at(0)),
71 updatedAt: DateTime.formatIso(at(0)),
72 },
73 }),
74 );
75
76const thread = (
77 threadId: ThreadId,
78 projectId: ProjectId,
79 overrides: { readonly archivedAt?: DateTime.Utc; readonly deletedAt?: DateTime.Utc } = {},
80): OrchestrationV2DomainEvent => ({
81 id: EventId.make(`created:${threadId}`),
82 type: "thread.created",
83 threadId,
84 providerInstanceId,
85 occurredAt: at(0),
86 payload: {
87 createdBy: "user",
88 creationSource: "web",
89 id: threadId,
90 projectId,
91 title: threadId,
92 providerInstanceId,
93 modelSelection: { instanceId: providerInstanceId, model: "gpt-5" },
94 runtimeMode: "full-access",
95 interactionMode: "default",
96 branch: null,
97 worktreePath: null,
98 activeProviderThreadId: null,
99 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
100 forkedFrom: null,
101 createdAt: at(0),
102 updatedAt: at(0),
103 archivedAt: overrides.archivedAt ?? null,
104 settledOverride: null,
105 settledAt: null,
106 lastVisitedAt: null,
107 deletedAt: overrides.deletedAt ?? null,
108 },
109});
110
111const threadId = ThreadId.make("thread:find");
112const projectId = ProjectId.make("project:find");
113const runId = RunId.make("run:find");
114
115function item(
116 id: string,
117 ordinal: number,
118 text: string,
119 kind: "user_message" | "assistant_message" | "proposed_plan" = "assistant_message",
120 owner = threadId,
121): Extract<
122 OrchestrationV2TurnItem,
123 { type: "user_message" | "assistant_message" | "proposed_plan" }
124> {
125 const base = {
126 id: TurnItemId.make(id),
127 threadId: owner,
128 runId,
129 nodeId: null,
130 providerThreadId: null,
131 providerTurnId: null,
132 nativeItemRef: null,
133 parentItemId: null,
134 ordinal,
135 status: "completed" as const,
136 title: null,
137 startedAt: at(100 - ordinal),
138 completedAt: at(100 - ordinal),
139 updatedAt: at(1),
140 };
141 if (kind === "proposed_plan")
142 return { ...base, type: kind, planId: PlanId.make(id), markdown: text, streaming: false };
143 if (kind === "user_message")
144 return {
145 ...base,
146 type: kind,
147 messageId: MessageId.make(id),
148 text,
149 inputIntent: "turn_start",
150 attachments: [],
151 createdBy: "user",
152 creationSource: "web",
153 };
154 return { ...base, type: kind, messageId: MessageId.make(id), text, streaming: false };
155}
156
157function run(
158 owner = threadId,
159 id = runId,
160 ordinal = 1,
161 status: OrchestrationV2Run["status"] = "completed",
162): Extract<OrchestrationV2DomainEvent, { type: "run.created" }> {
163 return {
164 id: EventId.make(`run:${owner}:${id}:${status}`),
165 threadId: owner,
166 occurredAt: at(1),
167 type: "run.created",
168 payload: {
169 id,
170 threadId: owner,
171 ordinal,
172 providerInstanceId,
173 modelSelection: { instanceId: providerInstanceId, model: "gpt-6" },
174 providerThreadId: null,
175 userMessageId: MessageId.make("prompt"),
176 rootNodeId: null,
177 activeAttemptId: null,
178 status,
179 requestedAt: at(1),
180 startedAt: at(1),
181 completedAt: at(2),
182 checkpointId: null,
183 contextHandoffId: null,
184 },
185 };
186}
187
188const commit = Effect.fn("ThreadFindTest.commit")(function* (
189 events: readonly OrchestrationV2DomainEvent[],
190) {
191 const store = yield* EventStore.EventStoreV2;
192 const projection = yield* ProjectionStore.ProjectionStoreV2;
193 yield* store.append({ events });
194 yield* Effect.forEach(events, projection.apply, { discard: true });
195});
196const putItems = (items: readonly OrchestrationV2TurnItem[], version = "initial") =>
197 commit(
198 items.map((payload) => ({
199 id: EventId.make(`${payload.threadId}:${payload.id}:${version}`),
200 threadId: payload.threadId,
201 occurredAt: at(1),
202 type: "turn-item.updated" as const,
203 payload,
204 })),
205 );
206const setup = Effect.gen(function* () {
207 yield* createProject(projectId);
208 yield* commit([thread(threadId, projectId), run()]);
209 return yield* ProjectionStore.ProjectionStoreV2;
210});
211
212const tracePayloadLoads = () => {
213 let batches = 0;
214 const tracer = Tracer.make({
215 span(options) {
216 if (options.name === "ThreadFind.load") batches++;
217 return new Tracer.NativeSpan(options);
218 },
219 });
220 return { tracer, batches: () => batches };
221};
222
223describe("V2 thread find", () => {
224 it.effect.each(["rendered text", "source text"] as const)(
225 "does not retain rendered snapshots over the %s budget",
226 (limit) =>
227 Effect.gen(function* () {
228 const projection = yield* setup;
229 yield* putItems(
230 Array.from({ length: 65 }, (_, i) =>
231 item(
232 `message:${i}`,
233 i,
234 limit === "rendered text"
235 ? "needle ".repeat(2500)
236 : `needle })`,
237 ),
238 ),
239 );
240 const loads = tracePayloadLoads();
241 const first = yield* projection
242 .searchThread({ threadId, query: "needle" })
243 .pipe(Effect.withTracer(loads.tracer));
244 const initialBatches = loads.batches();
245 const second = yield* projection
246 .searchThread({ threadId, query: "need" })
247 .pipe(Effect.withTracer(loads.tracer));
248 assert.equal(second.totalMatches, first.totalMatches);
249 assert.equal(loads.batches(), initialBatches * 2);
250 }).pipe(Effect.provide(layerTest)),
251 );
252
253 it.effect("finishes one snapshot while later searches include newly inserted matches", () =>
254 Effect.gen(function* () {
255 const projection = yield* setup;
256 yield* putItems([
257 item("selected", 1, "snapshot needle"),
258 item("last", 2, "snapshot last needle"),
259 ]);
260 yield* projection.searchThread({ threadId, query: "snapshot" });
261 const frames = yield* projection.searchThreadStream({ threadId, query: "needle" }).pipe(
262 Stream.tap((frame) =>
263 frame.complete === false
264 ? putItems([item("inserted", 0, "snapshot inserted needle")], "during-search")
265 : Effect.void,
266 ),
267 Stream.runCollect,
268 );
269 assert.equal(frames.length, 2);
270 assert.equal(frames[1]!.totalMatches, 2);
271 assert.deepEqual(frames[1]!.match, frames[0]!.match);
272 const updated = yield* projection.searchThread({
273 threadId,
274 query: "needle",
275 start: { entryId: "selected", occurrence: 0 },
276 });
277 assert.equal(updated.totalMatches, 3);
278 assert.equal(updated.activeIndex, 1);
279 assert.equal(updated.match?.entryId, "selected");
280 }).pipe(Effect.provide(layerTest)),
281 );
282
283 it.effect("returns bounded navigation counts around the selection, including wraparound", () =>
284 Effect.gen(function* () {
285 const projection = yield* setup;
286 yield* putItems(
287 Array.from({ length: 30 }, (_, i) =>
288 item(`message:${i}`, i, "needle ".repeat((i % 3) + 1)),
289 ),
290 );
291 const current = yield* projection.searchThread({
292 threadId,
293 query: "needle",
294 start: { entryId: "message:14", occurrence: 1 },
295 });
296 assert.equal(current.totalMatches, 60);
297 assert.equal(current.activeIndex, 28);
298 assert.equal(current.navigation?.length, 17);
299 assert.deepEqual(
300 current.navigation?.map((entry) => entry.entryId),
301 Array.from({ length: 17 }, (_, i) => `message:${i + 6}`),
302 );
303 assert.deepEqual(
304 current.navigation?.find((entry) => entry.entryId === "message:14"),
305 {
306 entryId: "message:14",
307 runId,
308 startIndex: 27,
309 count: 3,
310 },
311 );
312 const first = yield* projection.searchThread({ threadId, query: "needle" });
313 assert.equal(first.navigation?.length, 17);
314 assert.include(first.navigation?.map((entry) => entry.entryId) ?? [], "message:29");
315 const empty = yield* projection.searchThread({ threadId, query: "absent" });
316 assert.deepEqual(empty.navigation, []);
317 }).pipe(Effect.provide(layerTest)),
318 );
319
320 it.effect("keeps navigation compact for a message with thousands of occurrences", () =>
321 Effect.gen(function* () {
322 const projection = yield* setup;
323 yield* putItems([item("many", 1, "needle ".repeat(5000))]);
324 const result = yield* projection.searchThread({ threadId, query: "needle", index: 2000 });
325 assert.equal(result.totalMatches, 5000);
326 assert.equal(result.match?.occurrence, 2000);
327 assert.deepEqual(result.navigation, [{ entryId: "many", runId, startIndex: 0, count: 5000 }]);
328 assert.isBelow(JSON.stringify(result).length, 500);
329 }).pipe(Effect.provide(layerTest)),
330 );
331
332 it.effect("cycles relative to the current match when new matches are inserted", () =>
333 Effect.gen(function* () {
334 const projection = yield* setup;
335 yield* putItems([
336 item("first", 10, "needle"),
337 item("current", 20, "needle"),
338 item("last", 30, "needle"),
339 ]);
340 const initial = yield* projection.searchThread({ threadId, query: "needle", index: 1 });
341 assert.equal(initial.match?.entryId, "current");
342 yield* putItems([
343 item("new-before", 15, "needle"),
344 item("new-after", 25, "needle"),
345 item("new-last", 40, "needle"),
346 ]);
347 const start = { entryId: "current", occurrence: 0 };
348 const refreshed = yield* projection.searchThread({ threadId, query: "needle", start });
349 assert.equal(refreshed.totalMatches, 6);
350 assert.equal(refreshed.activeIndex, 2);
351 assert.equal(refreshed.match?.entryId, "current");
352 const next = yield* projection.searchThread({ threadId, query: "needle", start, offset: 1 });
353 assert.equal(next.match?.entryId, "new-after");
354 const previous = yield* projection.searchThread({
355 threadId,
356 query: "needle",
357 start,
358 offset: -1,
359 });
360 assert.equal(previous.match?.entryId, "new-before");
361 const end = yield* projection.searchThread({
362 threadId,
363 query: "needle",
364 start: { entryId: "last", occurrence: 0 },
365 offset: 1,
366 });
367 assert.equal(end.match?.entryId, "new-last");
368 const wrapped = yield* projection.searchThread({
369 threadId,
370 query: "needle",
371 start: { entryId: "new-last", occurrence: 0 },
372 offset: 1,
373 });
374 assert.equal(wrapped.match?.entryId, "first");
375 const backwards = yield* projection.searchThread({
376 threadId,
377 query: "needle",
378 start: { entryId: "first", occurrence: 0 },
379 offset: -1,
380 });
381 assert.equal(backwards.match?.entryId, "new-last");
382 }).pipe(Effect.provide(layerTest)),
383 );
384
385 it.effect("searches visible rendered messages and plans in canonical item order", () =>
386 Effect.gen(function* () {
387 const projection = yield* setup;
388 yield* putItems([
389 item("user", 1, "Check **the build**", "user_message"),
390 item("assistant", 2, "check the build twice: check the build"),
391 item("plan-item", 3, "# Check the build\nShip it", "proposed_plan"),
392 item("url", 4, "[documentation](https://hidden.example/needle)"),
393 ]);
394 const matches = [];
395 for (let index = 0; index < 4; index++) {
396 const result = yield* projection.searchThread({
397 threadId,
398 query: "CHECK THE BUILD",
399 index,
400 });
401 assert.equal(result.totalMatches, 4);
402 matches.push(result.match);
403 }
404 assert.deepEqual(matches, [
405 { entryId: "user", runId, occurrence: 0 },
406 { entryId: "assistant", runId, occurrence: 0 },
407 { entryId: "assistant", runId, occurrence: 1 },
408 { entryId: "plan-item", runId, occurrence: 0 },
409 ]);
410 assert.equal(
411 (yield* projection.searchThread({ threadId, query: "hidden.example" })).totalMatches,
412 0,
413 );
414 assert.equal(
415 (yield* projection.searchThread({ threadId, query: "check", index: 99 })).activeIndex,
416 3,
417 );
418 }).pipe(Effect.provide(layerTest)),
419 );
420
421 it.effect.each(["", "\n", "\t\u00a0"])("skips a blank reply with a render (%j)", (text) =>
422 Effect.gen(function* () {
423 const projection = yield* setup;
424 const shownRunId = RunId.make("run:shown");
425 yield* commit([run(threadId, shownRunId, 2)]);
426 yield* putItems([
427 {
428 ...item("render", 0, ""),
429 type: "dynamic_tool",
430 toolName: "html_render",
431 input: {},
432 output: { htmlRender: { attachmentId: "visual", title: "Result", height: 120 } },
433 },
434 item("hidden", 1, text),
435 { ...item("shown", 2, text), runId: shownRunId },
436 ]);
437 const result = yield* projection.searchThread({ threadId, query: "empty" });
438 assert.equal(result.totalMatches, 1);
439 assert.equal(result.match?.entryId, "shown");
440 const changed = yield* projection.searchThread({ threadId, query: "response" });
441 assert.equal(changed.totalMatches, 1);
442 assert.equal(changed.match?.entryId, "shown");
443 }).pipe(Effect.provide(layerTest)),
444 );
445
446 it.effect("searches displayed skill labels and invalidates parsed text when labels change", () =>
447 Effect.gen(function* () {
448 const projection = yield* setup;
449 yield* putItems([item("skill", 1, "Use $test-t3-app now")]);
450 const input = {
451 threadId,
452 query: "T3 App Testing",
453 skills: [{ name: "test-t3-app", displayName: "T3 App Testing" }],
454 };
455 assert.equal((yield* projection.searchThread(input)).totalMatches, 1);
456 assert.equal((yield* projection.searchThread({ ...input, skills: [] })).totalMatches, 0);
457 yield* putItems(
458 [item("skill-plan", 2, "# Verify\nUse $test-t3-app now", "proposed_plan")],
459 "plan",
460 );
461 assert.equal((yield* projection.searchThread(input)).totalMatches, 1);
462 assert.equal(
463 (yield* projection.searchThread({ ...input, query: "$test-t3-app" })).totalMatches,
464 1,
465 );
466 assert.equal((yield* projection.searchThread({ ...input, query: "App" })).totalMatches, 2);
467 }).pipe(Effect.provide(layerTest)),
468 );
469
470 it.effect("searches only the picture file chips visible in the viewer's theme", () =>
471 Effect.gen(function* () {
472 const projection = yield* setup;
473 yield* putItems([
474 item(
475 "picture",
476 1,
477 '<picture><source media="(prefers-color-scheme: dark)" srcset="/workspace/repo/notes.ts#L42-L64"><img src="/workspace/repo/screenshot.png" alt="notes"></picture>',
478 ),
479 item(
480 "fallback",
481 2,
482 '<picture><source media="(prefers-color-scheme: dark)" srcset="/workspace/repo/dark.png"><img src="/workspace/repo/fallback.ts#L42-L64" alt="notes"></picture>',
483 ),
484 ]);
485 const dark = { threadId, query: "L42–64", theme: "dark" } as const;
486 const light = { ...dark, theme: "light" } as const;
487 const darkResult = yield* projection.searchThread(dark);
488 assert.equal(darkResult.totalMatches, 1);
489 assert.equal(darkResult.match?.entryId, "picture");
490 assert.equal(
491 (yield* projection.searchThread({ ...light, query: "notes.ts" })).totalMatches,
492 0,
493 );
494 const lightResult = yield* projection.searchThread(light);
495 assert.equal(lightResult.totalMatches, 1);
496 assert.equal(lightResult.match?.entryId, "fallback");
497 assert.equal((yield* projection.searchThread(dark)).match?.entryId, "picture");
498 }).pipe(Effect.provide(layerTest)),
499 );
500
501 it.effect("refreshes file labels when the project cwd changes without a thread event", () =>
502 Effect.gen(function* () {
503 const projection = yield* setup;
504 const sql = yield* SqlClient.SqlClient;
505 yield* putItems([item("paths", 1, "[local](src/main.ts) [other](/elsewhere/src/main.ts)")]);
506 assert.equal(
507 (yield* projection.searchThread({ threadId, query: "project:find/src" })).totalMatches,
508 1,
509 );
510 yield* sql`UPDATE projection_projects SET workspace_root = '/elsewhere'
511 WHERE project_id = ${projectId}`;
512 assert.equal(
513 (yield* projection.searchThread({ threadId, query: "project:find" })).totalMatches,
514 0,
515 );
516 assert.equal(
517 (yield* projection.searchThread({ threadId, query: "main.ts" })).totalMatches,
518 2,
519 );
520 }).pipe(Effect.provide(layerTest)),
521 );
522
523 it.effect("never mixes message versions when the searched thread changes during a scan", () =>
524 Effect.gen(function* () {
525 const projection = yield* setup;
526 const sql = yield* SqlClient.SqlClient;
527 const items = Array.from({ length: 260 }, (_, i) => item(`message:${i}`, i, "needle"));
528 yield* putItems(items);
529 const updated = items.map((item) =>
530 item.type === "assistant_message" ? { ...item, text: "needle needle" } : item,
531 );
532 const [during] = yield* Effect.all(
533 [
534 projection.searchThread({ threadId, query: "needle" }),
535 sql.withTransaction(putItems(updated, "concurrent")),
536 ],
537 { concurrency: "unbounded" },
538 );
539 assert.include([260, 520], during.totalMatches);
540 assert.equal(
541 (yield* projection.searchThread({ threadId, query: "needle" })).totalMatches,
542 520,
543 );
544 }).pipe(Effect.provide(layerTest)),
545 );
546
547 it.effect("starts at the reading position and wraps when no later match exists", () =>
548 Effect.gen(function* () {
549 const projection = yield* setup;
550 yield* putItems([
551 item("first", 1, "needle"),
552 item("reading", 2, "needle above, needle below"),
553 item("between", 3, "nothing"),
554 item("last", 4, "needle"),
555 item("end", 5, "nothing"),
556 ]);
557 const from = (entryId: string, occurrence = 0) =>
558 projection.searchThread({ threadId, query: "needle", start: { entryId, occurrence } });
559 assert.equal((yield* from("reading")).activeIndex, 1);
560 const below = yield* from("reading", 1);
561 assert.equal(below.activeIndex, 2);
562 assert.equal(below.match?.occurrence, 1);
563 assert.equal((yield* from("between")).match?.entryId, "last");
564 assert.equal((yield* from("reading", 2)).activeIndex, 3);
565 assert.equal((yield* from("end")).match?.entryId, "first");
566 assert.equal((yield* from("missing")).activeIndex, 0);
567 const explicit = yield* projection.searchThread({
568 threadId,
569 query: "needle",
570 start: { entryId: "last", occurrence: 0 },
571 index: 1,
572 });
573 assert.equal(explicit.match?.entryId, "reading");
574 }).pipe(Effect.provide(layerTest)),
575 );
576
577 it.effect("finds matches beyond the recent history window", () =>
578 Effect.gen(function* () {
579 const projection = yield* setup;
580 const items = Array.from({ length: 520 }, (_, i) =>
581 item(`message:${i}`, i + 1, i === 8 || i === 510 ? "sentinel" : "other message"),
582 );
583 yield* putItems(items);
584 const loads = tracePayloadLoads();
585 const first = yield* projection
586 .searchThread({ threadId, query: "sentinel" })
587 .pipe(Effect.withTracer(loads.tracer));
588 assert.equal(loads.batches(), 5);
589 const changed = yield* projection
590 .searchThread({ threadId, query: "other message" })
591 .pipe(Effect.withTracer(loads.tracer));
592 assert.equal(changed.totalMatches, 518);
593 assert.equal(changed.match?.entryId, "message:0");
594 assert.equal(loads.batches(), 5);
595 const last = yield* projection.searchThread({ threadId, query: "sentinel", index: 1 });
596 assert.equal(first.totalMatches, 2);
597 assert.equal(first.match?.entryId, "message:8");
598 assert.equal(last.match?.entryId, "message:510");
599 }).pipe(Effect.provide(layerTest)),
600 );
601
602 it.effect("keeps its caches while Find is in use and drops them after one idle minute", () =>
603 Effect.gen(function* () {
604 const projection = yield* setup;
605 yield* putItems([item("one", 1, "idle needle one"), item("two", 2, "idle needle two")]);
606 const parses = () =>
607 vi
608 .mocked(searchableMessageSegments)
609 .mock.calls.filter(([message]) => message.text.startsWith("idle needle")).length;
610 const search = (query: string) => projection.searchThread({ threadId, query });
611 // One idle minute passes inside this search. The later counts fail if it let the caches go.
612 yield* projection.searchThreadStream({ threadId, query: "needle" }).pipe(
613 Stream.tap((frame) =>
614 frame.complete === false ? TestClock.adjust("1 minute") : Effect.void,
615 ),
616 Stream.runDrain,
617 );
618 assert.equal(parses(), 2);
619 yield* TestClock.adjust("40 seconds");
620 yield* search("idle");
621 yield* TestClock.adjust("40 seconds");
622 // A repeated query is answered from the completed scan and still counts as use.
623 const repeated = yield* projection
624 .searchThreadStream({ threadId, query: "needle" })
625 .pipe(Stream.runCollect);
626 assert.equal(repeated.length, 1);
627 yield* TestClock.adjust("40 seconds");
628 yield* search("one");
629 assert.equal(parses(), 2);
630 yield* TestClock.adjust("1 minute");
631 yield* search("needle");
632 assert.equal(parses(), 4);
633 }).pipe(Effect.provide(layerTest)),
634 );
635
636 it.effect("invalidates cached counts when streamed text changes or a run rolls back", () =>
637 Effect.gen(function* () {
638 const projection = yield* setup;
639 const original = item("streaming", 1, "needle");
640 yield* putItems([original]);
641 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 1);
642 if (original.type !== "assistant_message") return;
643 yield* putItems([{ ...original, text: "needle needle", streaming: true }], "streaming");
644 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 2);
645 assert.equal((yield* projection.searchThread({ threadId, query: "need" })).totalMatches, 2);
646 const updated = run(threadId, runId, 1, "rolled_back");
647 yield* commit([{ ...updated, type: "run.updated" }]);
648 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 0);
649 }).pipe(Effect.provide(layerTest)),
650 );
651
652 it.effect(
653 "does not search undispatched inputs, cancelled queue rows, or folded question answers",
654 () =>
655 Effect.gen(function* () {
656 const projection = yield* setup;
657 const queuedRunId = RunId.make("queued:cancelled");
658 const cancelled = run(threadId, queuedRunId, 2, "cancelled");
659 yield* commit([{ ...cancelled, payload: { ...cancelled.payload, startedAt: null } }]);
660 const queued = item("cancelled", 1, "needle", "user_message");
661 if (queued.type !== "user_message") return;
662 const answer = item("async-answer:question", 2, "needle", "user_message");
663 const question: OrchestrationV2TurnItem = {
664 ...item("question", 3, ""),
665 type: "user_input_request",
666 requestId: RuntimeRequestId.make("question"),
667 questions: [],
668 questionAnswer: { requestId: "question", answers: {}, attachmentsByQuestionId: {} },
669 };
670 yield* putItems([
671 { ...queued, runId: queuedRunId, inputIntent: "queued_turn" },
672 answer,
673 question,
674 ]);
675 const event: OrchestrationV2DomainEvent = {
676 id: EventId.make("undispatched"),
677 threadId,
678 occurredAt: at(2),
679 type: "message.updated",
680 payload: {
681 id: MessageId.make("undispatched"),
682 threadId,
683 runId: null,
684 nodeId: null,
685 role: "user",
686 text: "needle",
687 attachments: [],
688 streaming: false,
689 createdBy: "user",
690 creationSource: "web",
691 createdAt: at(2),
692 updatedAt: at(2),
693 },
694 };
695 yield* commit([event]);
696 const result = yield* projection.searchThread({ threadId, query: "needle" });
697 assert.equal(result.totalMatches, 0);
698 assert.isNull(result.match);
699 assert.equal((yield* projection.searchThread({ threadId, query: "need" })).totalMatches, 0);
700 yield* putItems([{ ...question, questionAnswer: undefined }], "unfolded");
701 assert.equal((yield* projection.searchThread({ threadId, query: "need" })).totalMatches, 1);
702 }).pipe(Effect.provide(layerTest)),
703 );
704
705 it.effect("finds an async answer that started a later run", () =>
706 Effect.gen(function* () {
707 yield* createProject(projectId);
708 const projection = yield* ProjectionStore.ProjectionStoreV2;
709 const queuedRun = RunId.make("run:queued");
710 const answerRun = RunId.make("run:answer");
711 yield* commit([
712 thread(threadId, projectId),
713 run(),
714 run(threadId, queuedRun, 2),
715 run(threadId, answerRun, 3),
716 ]);
717 const requestId = RuntimeRequestId.make("late");
718 const question: OrchestrationV2TurnItem = {
719 ...item("question", 1, ""),
720 type: "user_input_request",
721 requestId,
722 questions: [],
723 questionAnswer: { requestId, answers: {}, attachmentsByQuestionId: {} },
724 };
725 const items = [
726 question,
727 { ...item("queued", 2, "queued follow-up", "user_message"), runId: queuedRun },
728 { ...item(`async-answer:${requestId}`, 3, "needle", "user_message"), runId: answerRun },
729 ];
730 yield* commit(
731 items.map((payload) => ({
732 id: EventId.make(`${payload.id}:initial`),
733 threadId,
734 occurredAt: at(1),
735 type: "turn-item.updated" as const,
736 payload,
737 })),
738 );
739 const result = yield* projection.searchThread({ threadId, query: "needle" });
740 assert.equal(result.totalMatches, 1);
741 assert.deepEqual(result.match, {
742 entryId: `async-answer:${requestId}`,
743 runId: answerRun,
744 occurrence: 0,
745 });
746 }).pipe(Effect.provide(layerTest)),
747 );
748
749 it.effect(
750 "searches inherited fork history through the fork boundary, using source item identities",
751 () =>
752 Effect.gen(function* () {
753 const projection = yield* setup;
754 const parent = ThreadId.make("thread:parent");
755 const laterRun = RunId.make("run:later");
756 const parentRun = RunId.make("run:parent");
757 yield* commit([
758 thread(parent, projectId),
759 run(parent, parentRun),
760 run(parent, laterRun, 2),
761 ]);
762 yield* putItems([
763 { ...item("inherited", 1, "needle", "assistant_message", parent), runId: parentRun },
764 { ...item("after-fork", 2, "needle", "assistant_message", parent), runId: laterRun },
765 ]);
766 const child = thread(threadId, projectId);
767 if (child.type !== "thread.created") return;
768 yield* commit([
769 {
770 ...child,
771 id: EventId.make("child:fork"),
772 type: "thread.metadata-updated",
773 payload: {
774 ...child.payload,
775 forkedFrom: { type: "run", threadId: parent, runId: parentRun },
776 },
777 },
778 ]);
779 yield* putItems([item("local", 1, "needle")]);
780 const inherited = yield* projection.searchThread({ threadId, query: "needle" });
781 assert.equal(inherited.totalMatches, 2);
782 assert.equal(inherited.match?.entryId, "inherited");
783 assert.equal(
784 (yield* projection.searchThread({ threadId, query: "needle", index: 1 })).match?.entryId,
785 "local",
786 );
787 assert.equal((yield* projection.searchThread({ threadId, query: "need" })).totalMatches, 2);
788 const snapshot = yield* projection.getThreadSnapshot(threadId);
789 const history = yield* projection.getThreadHistoryPage(
790 threadId,
791 encodeThreadHistoryCursor({
792 snapshotSequence: snapshot.snapshotSequence,
793 sourceThreadId: threadId,
794 sourceItemId: "local",
795 position: 2,
796 }),
797 );
798 assert.deepEqual(
799 history.items,
800 snapshot.projection.visibleTurnItems
801 .slice(0, -1)
802 .map((row) => ({ ...row, item: projectTurnItemForWire(row.item) })),
803 );
804 assert.equal(history.items[0]?.sourceThreadId, parent);
805 assert.equal(history.items.at(-1)?.item.type, "fork");
806 yield* putItems(
807 [{ ...item("inherited", 1, "gone", "assistant_message", parent), runId: parentRun }],
808 "parent-update",
809 );
810 assert.equal(
811 (yield* projection.searchThread({ threadId, query: "needle" })).totalMatches,
812 1,
813 );
814 }).pipe(Effect.provide(layerTest)),
815 );
816
817 it.effect("rejects deleted threads and keeps results scoped to their thread", () =>
818 Effect.gen(function* () {
819 const projection = yield* setup;
820 const other = ThreadId.make("thread:other");
821 yield* commit([thread(other, projectId), run(other, RunId.make("run:other"))]);
822 yield* putItems([
823 item("shared-id", 1, "needle"),
824 item("other-id", 1, "other text", "assistant_message", other),
825 ]);
826 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 1);
827 assert.equal(
828 (yield* projection.searchThread({ threadId: other, query: "needle" })).totalMatches,
829 0,
830 );
831 const deleted = thread(threadId, projectId, { deletedAt: at(3) });
832 if (deleted.type !== "thread.created") return;
833 yield* commit([{ ...deleted, id: EventId.make("deleted"), type: "thread.deleted" }]);
834 const error = yield* Effect.flip(projection.searchThread({ threadId, query: "needle" }));
835 assert.equal(error._tag, "ProjectionStoreThreadNotFoundError");
836 const historyError = yield* Effect.flip(
837 projection.getThreadHistoryPage(
838 threadId,
839 encodeThreadHistoryCursor({
840 snapshotSequence: 0,
841 sourceThreadId: threadId,
842 sourceItemId: "shared-id",
843 position: 0,
844 }),
845 ),
846 );
847 assert.equal(historyError._tag, "ProjectionStoreThreadNotFoundError");
848 }).pipe(Effect.provide(layerTest)),
849 );
850
851 it.effect("invalidates a cached fork search when its empty source gains its first message", () =>
852 Effect.gen(function* () {
853 const projection = yield* setup;
854 const parent = ThreadId.make("thread:empty-parent");
855 const parentRun = RunId.make("run:empty-parent");
856 yield* commit([thread(parent, projectId), run(parent, parentRun)]);
857 const child = thread(threadId, projectId);
858 if (child.type !== "thread.created") return;
859 yield* commit([
860 {
861 ...child,
862 id: EventId.make("child:empty-fork"),
863 type: "thread.metadata-updated",
864 payload: {
865 ...child.payload,
866 forkedFrom: { type: "run", threadId: parent, runId: parentRun },
867 },
868 },
869 ]);
870 yield* putItems([item("local", 1, "needle")]);
871 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 1);
872 yield* putItems([
873 { ...item("inherited", 1, "needle", "assistant_message", parent), runId: parentRun },
874 ]);
875 const updated = yield* projection.searchThread({ threadId, query: "needle" });
876 assert.equal(updated.totalMatches, 2);
877 assert.equal(updated.match?.entryId, "inherited");
878 }).pipe(Effect.provide(layerTest)),
879 );
880});
881
882describe("V2 history materialization", () => {
883 it.effect(
884 "combines history pages through a match's message identity without skipping intervening turns",
885 () =>
886 Effect.gen(function* () {
887 const projection = yield* setup;
888 const items = Array.from({ length: 45 }, (_, turn) => [
889 item(`user:${turn}`, turn * 3, `turn ${turn}`, "user_message"),
890 {
891 ...item(`answer:${turn}`, turn * 3 + 1, `answer ${turn}`),
892 messageId: MessageId.make(`message:${turn}`),
893 },
894 {
895 ...item(`tool:${turn}`, turn * 3 + 2, ""),
896 type: "command_execution" as const,
897 input: "pwd",
898 output: "huge output".repeat(1000),
899 exitCode: 0,
900 },
901 ]).flat();
902 yield* putItems(items);
903 const snapshot = yield* projection.getThreadSnapshot(threadId);
904 const cursor = encodeThreadHistoryCursor({
905 snapshotSequence: snapshot.snapshotSequence,
906 sourceThreadId: threadId,
907 sourceItemId: "absent",
908 position: items.length,
909 });
910 const ordinary = yield* projection.getThreadHistoryPage(threadId, cursor);
911 assert.equal(ordinary.items[0]?.sourceItemId, "user:25");
912 const targeted = yield* projection.getThreadHistoryPage(threadId, cursor, "message:10");
913 assert.equal(targeted.items[0]?.sourceItemId, "user:10");
914 assert.deepEqual(
915 targeted.items.map((row) => row.sourceItemId),
916 items.slice(30).map((entry) => entry.id),
917 );
918 const conversation = yield* projection.getThreadHistoryPage(
919 threadId,
920 cursor,
921 "message:10",
922 true,
923 );
924 assert.equal(conversation.nextCursor, targeted.nextCursor);
925 assert.equal(conversation.hasMoreHistory, targeted.hasMoreHistory);
926 assert.deepEqual(
927 conversation.items.map((row) => row.sourceItemId),
928 targeted.items
929 .filter((row) => row.item.type !== "command_execution")
930 .map((row) => row.sourceItemId),
931 );
932 assert.equal(conversation.items.length, 70);
933 assert.equal(targeted.items.length, 105);
934 assert.isTrue(targeted.hasMoreHistory);
935 const earlier = yield* projection.getThreadHistoryPage(threadId, targeted.nextCursor!);
936 assert.deepEqual(
937 earlier.items.map((row) => row.sourceItemId),
938 items.slice(0, 30).map((entry) => entry.id),
939 );
940 assert.isFalse(earlier.hasMoreHistory);
941 // A client that can hold a gap gets the same rows for a target this near.
942 const near = yield* projection.getThreadHistoryPage(
943 threadId,
944 cursor,
945 "message:10",
946 false,
947 "detached",
948 );
949 assert.isUndefined(near.detached);
950 assert.equal(near.items[0]?.sourceItemId, "user:10");
951 // However far back the target is, one page reaches it.
952 const farthest = yield* projection.getThreadHistoryPage(threadId, cursor, "message:0");
953 assert.equal(farthest.items[0]?.sourceItemId, "user:0");
954 assert.isFalse(farthest.hasMoreHistory);
955 const absent = yield* projection.getThreadHistoryPage(
956 threadId,
957 cursor,
958 "another-thread-message",
959 );
960 assert.deepEqual(absent, ordinary);
961 }).pipe(Effect.provide(layerTest)),
962 );
963
964 it.effect("takes the page around a match far back without reading the whole thread", () =>
965 Effect.gen(function* () {
966 const projection = yield* setup;
967 const items = Array.from({ length: 600 }, (_, turn) => [
968 item(`user:${turn}`, turn * 3, `turn ${turn}`, "user_message"),
969 {
970 ...item(`answer:${turn}`, turn * 3 + 1, `answer ${turn}`),
971 messageId: MessageId.make(`message:${turn}`),
972 },
973 {
974 ...item(`note:${turn}`, turn * 3 + 2, `note ${turn}`),
975 type: "command_execution" as const,
976 input: "echo note",
977 output: "note",
978 exitCode: 0,
979 },
980 ]).flat();
981 yield* putItems(items);
982 const cursor = encodeThreadHistoryCursor({
983 snapshotSequence: 0,
984 sourceThreadId: threadId,
985 sourceItemId: TurnItemId.make("note:599"),
986 position: 0,
987 });
988 const spans: Array<string> = [];
989 const around = yield* projection
990 .getThreadHistoryPage(threadId, cursor, "message:100", false, "detached")
991 .pipe(
992 Effect.withTracer(
993 Tracer.make({
994 span: (options) => {
995 spans.push(options.name);
996 return new Tracer.NativeSpan(options);
997 },
998 }),
999 ),
1000 );
1001 assert.isTrue(around.detached);
1002 // It runs seventeen turns past the match and keeps three before it.
1003 assert.deepEqual(
1004 [around.items[0]?.sourceItemId, around.items.at(-1)?.sourceItemId],
1005 ["user:97", "note:116"],
1006 );
1007 assert.isTrue(around.hasMoreHistory);
1008 assert.notInclude(spans, "ProjectionStore.readTimelineIndex");
1009 const conversation = yield* projection.getThreadHistoryPage(
1010 threadId,
1011 cursor,
1012 "message:100",
1013 true,
1014 "detached",
1015 );
1016 assert.isTrue(conversation.detached);
1017 assert.deepEqual(
1018 conversation.items.map((row) => row.sourceItemId),
1019 around.items
1020 .filter((row) => row.item.type !== "command_execution")
1021 .map((row) => row.sourceItemId),
1022 );
1023 // The rows above it page on from its cursor.
1024 const above = yield* projection.getThreadHistoryPage(threadId, around.nextCursor!);
1025 assert.equal(above.items.at(-1)?.sourceItemId, "note:96");
1026
1027 // A match near the cursor, or an entry the thread lacks, loads as a jump always has.
1028 const near = yield* projection.getThreadHistoryPage(
1029 threadId,
1030 cursor,
1031 "message:590",
1032 false,
1033 "detached",
1034 );
1035 assert.isUndefined(near.detached);
1036 assert.deepEqual(
1037 [near.items[0]?.sourceItemId, near.items.at(-1)?.sourceItemId],
1038 ["user:590", "answer:599"],
1039 );
1040 const absent = yield* projection.getThreadHistoryPage(
1041 threadId,
1042 cursor,
1043 "nothing",
1044 false,
1045 "detached",
1046 );
1047 assert.isUndefined(absent.detached);
1048 }).pipe(Effect.provide(layerTest)),
1049 );
1050
1051 it.effect("bounds a targeted history page by projected UTF-8 bytes", () =>
1052 Effect.gen(function* () {
1053 const projection = yield* setup;
1054 const text = "漢".repeat(1_000_000);
1055 const items = Array.from({ length: 4 }, (_, ordinal) =>
1056 item(`wide:${ordinal}`, ordinal, text),
1057 );
1058 yield* putItems(items);
1059 const snapshot = yield* projection.getThreadSnapshot(threadId);
1060 const cursor = encodeThreadHistoryCursor({
1061 snapshotSequence: snapshot.snapshotSequence,
1062 sourceThreadId: threadId,
1063 sourceItemId: "absent",
1064 position: items.length,
1065 });
1066 const fullPayloadReads: number[] = [];
1067 const page = yield* projection.getThreadHistoryPage(threadId, cursor, "wide:0").pipe(
1068 Effect.provideService(Statement.CurrentTransformer, (statement) => {
1069 const [query, params] = statement.compile();
1070 if (query.includes("SELECT item.thread_id, item.turn_item_id, item.payload_json")) {
1071 fullPayloadReads.push((JSON.parse(String(params[0])) as unknown[]).length);
1072 }
1073 return Effect.succeed(statement);
1074 }),
1075 );
1076 assert.deepEqual(
1077 page.items.map((row) => row.sourceItemId),
1078 ["wide:2", "wide:3"],
1079 );
1080 assert.deepEqual(fullPayloadReads, [2, 1]);
1081 assert.isAtMost(Buffer.byteLength(JSON.stringify(page.items)), 8 * 1_048_576);
1082 assert.isTrue(page.hasMoreHistory);
1083 }).pipe(Effect.provide(layerTest)),
1084 );
1085
1086 it.effect.each([false, true])(
1087 "bounds detached payload reads even if the page anchor rolled back (%s)",
1088 (rollback) =>
1089 Effect.gen(function* () {
1090 const projection = yield* setup;
1091 const cutoffRun = RunId.make("run:detached-cutoffs");
1092 const text = "漢".repeat(200_000);
1093 const items = Array.from({ length: 1_500 }, (_, ordinal) => {
1094 const entry = item(`jump:${ordinal}`, ordinal, ordinal < 4 ? text : `Answer ${ordinal}`);
1095 return ordinal === 35 || ordinal === 355 ? { ...entry, runId: cutoffRun } : entry;
1096 });
1097 yield* commit([run(threadId, cutoffRun, 2)]);
1098 yield* putItems(items);
1099 if (rollback)
1100 yield* commit([{ ...run(threadId, cutoffRun, 2, "rolled_back"), type: "run.updated" }]);
1101
1102 const cursor = encodeThreadHistoryCursor({
1103 snapshotSequence: 0,
1104 sourceThreadId: threadId,
1105 sourceItemId: "jump:1499",
1106 position: 1499,
1107 });
1108 const payloadIds = new Set<string>();
1109 const page = yield* projection
1110 .getThreadHistoryPage(threadId, cursor, "jump:4", false, "detached")
1111 .pipe(
1112 Effect.provideService(Statement.CurrentTransformer, (statement) => {
1113 const [query, params] = statement.compile();
1114 if (query.includes("SELECT item.thread_id, item.turn_item_id, item.payload_json")) {
1115 for (const source of JSON.parse(String(params[0])) as Array<{ id: string }>)
1116 payloadIds.add(source.id);
1117 }
1118 return Effect.succeed(statement);
1119 }),
1120 );
1121 assert.isTrue(page.detached);
1122 assert.isTrue(page.items.some((row) => row.sourceItemId === "jump:4"));
1123 assert.isTrue(payloadIds.has("jump:3"));
1124 assert.isFalse(payloadIds.has("jump:0"));
1125 assert.isAtMost(
1126 Buffer.byteLength(JSON.stringify(page.items)),
1127 THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes,
1128 );
1129 }).pipe(Effect.provide(layerTest)),
1130 );
1131
1132 it.effect("pages long turns without duplicating or skipping messages", () =>
1133 Effect.gen(function* () {
1134 const projection = yield* setup;
1135 const items = Array.from({ length: 45 }, (_, turn) => [
1136 item(`user:${turn}`, turn * 3, `turn ${turn}`, "user_message"),
1137 {
1138 ...item(`steer:${turn}`, turn * 3 + 1, "steer", "user_message"),
1139 inputIntent: "steer" as const,
1140 },
1141 item(
1142 `answer:${turn}`,
1143 turn * 3 + 2,
1144 turn === 40 ? "large ".repeat(200_000) : `answer ${turn}`,
1145 ),
1146 ]).flat();
1147 yield* putItems(items);
1148 const snapshot = yield* projection.getThreadSnapshot(threadId);
1149 const rows = snapshot.projection.visibleTurnItems.map((row) => ({
1150 ...row,
1151 item: projectTurnItemForWire(row.item),
1152 }));
1153 let cursor: string | null = encodeThreadHistoryCursor({
1154 snapshotSequence: snapshot.snapshotSequence,
1155 sourceThreadId: threadId,
1156 sourceItemId: "absent",
1157 position: rows.length,
1158 });
1159 const collected: string[] = [];
1160 while (cursor !== null) {
1161 const page: OrchestrationV2ThreadHistoryPage = yield* projection.getThreadHistoryPage(
1162 threadId,
1163 cursor,
1164 );
1165 assert.deepEqual(page, {
1166 snapshotSequence: snapshot.snapshotSequence,
1167 ...selectHistoryPageFromCursor({
1168 items: rows,
1169 cursor,
1170 snapshotSequence: snapshot.snapshotSequence,
1171 }),
1172 });
1173 // A turn larger than the byte budget is split, but only a lone oversized item may exceed it.
1174 assert.isTrue(
1175 page.items.length === 1 ||
1176 Buffer.byteLength(JSON.stringify(page.items), "utf8") <=
1177 THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes,
1178 );
1179 collected.unshift(...page.items.map((row) => String(row.sourceItemId)));
1180 cursor = page.nextCursor;
1181 }
1182 assert.deepEqual(
1183 collected,
1184 items.map((entry) => String(entry.id)),
1185 );
1186 }).pipe(Effect.provide(layerTest)),
1187 );
1188
1189 it.effect("enforces fallback item and byte limits and always admits an oversized row", () =>
1190 Effect.gen(function* () {
1191 const projection = yield* setup;
1192 yield* putItems(
1193 Array.from({ length: 80 }, (_, ordinal) =>
1194 item(`row:${ordinal}`, ordinal, ordinal < 78 ? "small" : "large ".repeat(200_000)),
1195 ),
1196 );
1197 const snapshot = yield* projection.getThreadSnapshot(threadId);
1198 const rows = snapshot.projection.visibleTurnItems.map((row) => ({
1199 ...row,
1200 item: projectTurnItemForWire(row.item),
1201 }));
1202 let cursor: string | null = encodeThreadHistoryCursor({
1203 snapshotSequence: snapshot.snapshotSequence,
1204 sourceThreadId: threadId,
1205 sourceItemId: "absent",
1206 position: rows.length,
1207 });
1208 const sizes: number[] = [];
1209 while (cursor !== null) {
1210 const page: OrchestrationV2ThreadHistoryPage = yield* projection.getThreadHistoryPage(
1211 threadId,
1212 cursor,
1213 );
1214 assert.deepEqual(page, {
1215 snapshotSequence: snapshot.snapshotSequence,
1216 ...selectHistoryPageFromCursor({
1217 items: rows,
1218 cursor,
1219 snapshotSequence: snapshot.snapshotSequence,
1220 }),
1221 });
1222 sizes.push(page.items.length);
1223 cursor = page.nextCursor;
1224 }
1225 assert.deepEqual(sizes, [1, 1, 75, 3]);
1226 }).pipe(Effect.provide(layerTest)),
1227 );
1228});