Open History to see the last commit
1import { assert, it, describe } from "@effect/vitest";
2import {
3 EventId,
4 MessageId,
5 PlanId,
6 RunId,
7 RuntimeRequestId,
8 TurnItemId,
9 type OrchestrationV2TurnItem,
10 type OrchestrationV2Run,
11 type OrchestrationV2ThreadHistoryPage,
12 ProjectId,
13 ProviderInstanceId,
14 ThreadId,
15 type OrchestrationV2DomainEvent,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as SqlClient from "effect/sql/SqlClient";
21import * as Stream from "effect/Stream";
22
23import * as SqlitePersistence from "../persistence/Sqlite.ts";
24import * as ProjectionStore from "./ProjectionStore.ts";
25import * as ProjectStore from "./ProjectStore.ts";
26import * as EventStore from "./EventStore.ts";
27import { encodeThreadHistoryCursor, selectHistoryPageFromCursor } from "./threadHistoryPaging.ts";
28import { projectTurnItemForWire } from "./WireProjection.ts";
29
30const layerTest = Layer.mergeAll(EventStore.layer, ProjectionStore.layer, ProjectStore.layer).pipe(
31 Layer.provideMerge(SqlitePersistence.layerMemory),
32);
33
34const providerInstanceId = ProviderInstanceId.make("codex");
35const at = (minute: number) => DateTime.makeUnsafe(Date.UTC(2026, 8, 27, 0, minute));
36
37const createProject = (projectId: ProjectId) =>
38 Effect.flatMap(ProjectStore.ProjectStoreV2, (projects) =>
39 projects.apply({
40 sequence: 0,
41 eventId: EventId.make(`created:${projectId}`),
42 aggregateKind: "project",
43 aggregateId: projectId,
44 occurredAt: DateTime.formatIso(at(0)),
45 commandId: null,
46 causationEventId: null,
47 correlationId: null,
48 metadata: {},
49 type: "project.created",
50 payload: {
51 projectId,
52 title: projectId,
53 workspaceRoot: `/work/${projectId}`,
54 defaultModelSelection: null,
55 scripts: [],
56 createdAt: DateTime.formatIso(at(0)),
57 updatedAt: DateTime.formatIso(at(0)),
58 },
59 }),
60 );
61
62const thread = (
63 threadId: ThreadId,
64 projectId: ProjectId,
65 overrides: { readonly archivedAt?: DateTime.Utc; readonly deletedAt?: DateTime.Utc } = {},
66): OrchestrationV2DomainEvent => ({
67 id: EventId.make(`created:${threadId}`),
68 type: "thread.created",
69 threadId,
70 providerInstanceId,
71 occurredAt: at(0),
72 payload: {
73 createdBy: "user",
74 creationSource: "web",
75 id: threadId,
76 projectId,
77 title: threadId,
78 providerInstanceId,
79 modelSelection: { instanceId: providerInstanceId, model: "gpt-5" },
80 runtimeMode: "full-access",
81 interactionMode: "default",
82 branch: null,
83 worktreePath: null,
84 activeProviderThreadId: null,
85 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
86 forkedFrom: null,
87 createdAt: at(0),
88 updatedAt: at(0),
89 archivedAt: overrides.archivedAt ?? null,
90 settledOverride: null,
91 settledAt: null,
92 lastVisitedAt: null,
93 deletedAt: overrides.deletedAt ?? null,
94 },
95});
96
97const threadId = ThreadId.make("thread:find");
98const projectId = ProjectId.make("project:find");
99const runId = RunId.make("run:find");
100
101function item(
102 id: string,
103 ordinal: number,
104 text: string,
105 kind: "user_message" | "assistant_message" | "proposed_plan" = "assistant_message",
106 owner = threadId,
107): Extract<
108 OrchestrationV2TurnItem,
109 { type: "user_message" | "assistant_message" | "proposed_plan" }
110> {
111 const base = {
112 id: TurnItemId.make(id),
113 threadId: owner,
114 runId,
115 nodeId: null,
116 providerThreadId: null,
117 providerTurnId: null,
118 nativeItemRef: null,
119 parentItemId: null,
120 ordinal,
121 status: "completed" as const,
122 title: null,
123 startedAt: at(100 - ordinal),
124 completedAt: at(100 - ordinal),
125 updatedAt: at(1),
126 };
127 if (kind === "proposed_plan")
128 return { ...base, type: kind, planId: PlanId.make(id), markdown: text, streaming: false };
129 if (kind === "user_message")
130 return {
131 ...base,
132 type: kind,
133 messageId: MessageId.make(id),
134 text,
135 inputIntent: "turn_start",
136 attachments: [],
137 createdBy: "user",
138 creationSource: "web",
139 };
140 return { ...base, type: kind, messageId: MessageId.make(id), text, streaming: false };
141}
142
143function run(
144 owner = threadId,
145 id = runId,
146 ordinal = 1,
147 status: OrchestrationV2Run["status"] = "completed",
148): Extract<OrchestrationV2DomainEvent, { type: "run.created" }> {
149 return {
150 id: EventId.make(`run:${owner}:${id}:${status}`),
151 threadId: owner,
152 occurredAt: at(1),
153 type: "run.created",
154 payload: {
155 id,
156 threadId: owner,
157 ordinal,
158 providerInstanceId,
159 modelSelection: { instanceId: providerInstanceId, model: "gpt-6" },
160 providerThreadId: null,
161 userMessageId: MessageId.make("prompt"),
162 rootNodeId: null,
163 activeAttemptId: null,
164 status,
165 requestedAt: at(1),
166 startedAt: at(1),
167 completedAt: at(2),
168 checkpointId: null,
169 contextHandoffId: null,
170 },
171 };
172}
173
174const commit = Effect.fn("ThreadFindTest.commit")(function* (
175 events: readonly OrchestrationV2DomainEvent[],
176) {
177 const store = yield* EventStore.EventStoreV2;
178 const projection = yield* ProjectionStore.ProjectionStoreV2;
179 yield* store.append({ events });
180 yield* Effect.forEach(events, projection.apply, { discard: true });
181});
182const putItems = (items: readonly OrchestrationV2TurnItem[], version = "initial") =>
183 commit(
184 items.map((payload) => ({
185 id: EventId.make(`${payload.threadId}:${payload.id}:${version}`),
186 threadId: payload.threadId,
187 occurredAt: at(1),
188 type: "turn-item.updated" as const,
189 payload,
190 })),
191 );
192const setup = Effect.gen(function* () {
193 yield* createProject(projectId);
194 yield* commit([thread(threadId, projectId), run()]);
195 return yield* ProjectionStore.ProjectionStoreV2;
196});
197
198describe("V2 thread find", () => {
199 it.effect("finishes one snapshot while later searches include newly inserted matches", () =>
200 Effect.gen(function* () {
201 const projection = yield* setup;
202 yield* putItems([
203 item("selected", 1, "snapshot needle"),
204 item("last", 2, "snapshot last needle"),
205 ]);
206 const frames = yield* projection.searchThreadStream({ threadId, query: "needle" }).pipe(
207 Stream.tap((frame) =>
208 frame.complete === false
209 ? putItems([item("inserted", 0, "snapshot inserted needle")], "during-search")
210 : Effect.void,
211 ),
212 Stream.runCollect,
213 );
214 assert.equal(frames.length, 2);
215 assert.equal(frames[1]!.totalMatches, 2);
216 assert.deepEqual(frames[1]!.match, frames[0]!.match);
217 const updated = yield* projection.searchThread({
218 threadId,
219 query: "needle",
220 start: { entryId: "selected", occurrence: 0 },
221 });
222 assert.equal(updated.totalMatches, 3);
223 assert.equal(updated.activeIndex, 1);
224 assert.equal(updated.match?.entryId, "selected");
225 }).pipe(Effect.provide(layerTest)),
226 );
227
228 it.effect("returns bounded navigation counts around the selection, including wraparound", () =>
229 Effect.gen(function* () {
230 const projection = yield* setup;
231 yield* putItems(
232 Array.from({ length: 30 }, (_, i) =>
233 item(`message:${i}`, i, "needle ".repeat((i % 3) + 1)),
234 ),
235 );
236 const current = yield* projection.searchThread({
237 threadId,
238 query: "needle",
239 start: { entryId: "message:14", occurrence: 1 },
240 });
241 assert.equal(current.totalMatches, 60);
242 assert.equal(current.activeIndex, 28);
243 assert.equal(current.navigation?.length, 17);
244 assert.deepEqual(
245 current.navigation?.map((entry) => entry.entryId),
246 Array.from({ length: 17 }, (_, i) => `message:${i + 6}`),
247 );
248 assert.deepEqual(
249 current.navigation?.find((entry) => entry.entryId === "message:14"),
250 {
251 entryId: "message:14",
252 runId,
253 startIndex: 27,
254 count: 3,
255 },
256 );
257 const first = yield* projection.searchThread({ threadId, query: "needle" });
258 assert.equal(first.navigation?.length, 17);
259 assert.include(first.navigation?.map((entry) => entry.entryId) ?? [], "message:29");
260 const empty = yield* projection.searchThread({ threadId, query: "absent" });
261 assert.deepEqual(empty.navigation, []);
262 }).pipe(Effect.provide(layerTest)),
263 );
264
265 it.effect("keeps navigation compact for a message with thousands of occurrences", () =>
266 Effect.gen(function* () {
267 const projection = yield* setup;
268 yield* putItems([item("many", 1, "needle ".repeat(5000))]);
269 const result = yield* projection.searchThread({ threadId, query: "needle", index: 2000 });
270 assert.equal(result.totalMatches, 5000);
271 assert.equal(result.match?.occurrence, 2000);
272 assert.deepEqual(result.navigation, [{ entryId: "many", runId, startIndex: 0, count: 5000 }]);
273 assert.isBelow(JSON.stringify(result).length, 500);
274 }).pipe(Effect.provide(layerTest)),
275 );
276
277 it.effect("cycles relative to the current match when new matches are inserted", () =>
278 Effect.gen(function* () {
279 const projection = yield* setup;
280 yield* putItems([
281 item("first", 10, "needle"),
282 item("current", 20, "needle"),
283 item("last", 30, "needle"),
284 ]);
285 const initial = yield* projection.searchThread({ threadId, query: "needle", index: 1 });
286 assert.equal(initial.match?.entryId, "current");
287 yield* putItems([
288 item("new-before", 15, "needle"),
289 item("new-after", 25, "needle"),
290 item("new-last", 40, "needle"),
291 ]);
292 const start = { entryId: "current", occurrence: 0 };
293 const refreshed = yield* projection.searchThread({ threadId, query: "needle", start });
294 assert.equal(refreshed.totalMatches, 6);
295 assert.equal(refreshed.activeIndex, 2);
296 assert.equal(refreshed.match?.entryId, "current");
297 const next = yield* projection.searchThread({ threadId, query: "needle", start, offset: 1 });
298 assert.equal(next.match?.entryId, "new-after");
299 const previous = yield* projection.searchThread({
300 threadId,
301 query: "needle",
302 start,
303 offset: -1,
304 });
305 assert.equal(previous.match?.entryId, "new-before");
306 const end = yield* projection.searchThread({
307 threadId,
308 query: "needle",
309 start: { entryId: "last", occurrence: 0 },
310 offset: 1,
311 });
312 assert.equal(end.match?.entryId, "new-last");
313 const wrapped = yield* projection.searchThread({
314 threadId,
315 query: "needle",
316 start: { entryId: "new-last", occurrence: 0 },
317 offset: 1,
318 });
319 assert.equal(wrapped.match?.entryId, "first");
320 const backwards = yield* projection.searchThread({
321 threadId,
322 query: "needle",
323 start: { entryId: "first", occurrence: 0 },
324 offset: -1,
325 });
326 assert.equal(backwards.match?.entryId, "new-last");
327 }).pipe(Effect.provide(layerTest)),
328 );
329
330 it.effect("searches visible rendered messages and plans in canonical item order", () =>
331 Effect.gen(function* () {
332 const projection = yield* setup;
333 yield* putItems([
334 item("user", 1, "Check **the build**", "user_message"),
335 item("assistant", 2, "check the build twice: check the build"),
336 item("plan-item", 3, "# Check the build\nShip it", "proposed_plan"),
337 item("url", 4, "[documentation](https://hidden.example/needle)"),
338 ]);
339 const matches = [];
340 for (let index = 0; index < 4; index++) {
341 const result = yield* projection.searchThread({
342 threadId,
343 query: "CHECK THE BUILD",
344 index,
345 });
346 assert.equal(result.totalMatches, 4);
347 matches.push(result.match);
348 }
349 assert.deepEqual(matches, [
350 { entryId: "user", runId, occurrence: 0 },
351 { entryId: "assistant", runId, occurrence: 0 },
352 { entryId: "assistant", runId, occurrence: 1 },
353 { entryId: "plan-item", runId, occurrence: 0 },
354 ]);
355 assert.equal(
356 (yield* projection.searchThread({ threadId, query: "hidden.example" })).totalMatches,
357 0,
358 );
359 assert.equal(
360 (yield* projection.searchThread({ threadId, query: "check", index: 99 })).activeIndex,
361 3,
362 );
363 }).pipe(Effect.provide(layerTest)),
364 );
365
366 it.effect("searches displayed skill labels and invalidates parsed text when labels change", () =>
367 Effect.gen(function* () {
368 const projection = yield* setup;
369 yield* putItems([item("skill", 1, "Use $test-t3-app now")]);
370 const input = {
371 threadId,
372 query: "T3 App Testing",
373 skills: [{ name: "test-t3-app", displayName: "T3 App Testing" }],
374 };
375 assert.equal((yield* projection.searchThread(input)).totalMatches, 1);
376 assert.equal((yield* projection.searchThread({ ...input, skills: [] })).totalMatches, 0);
377 yield* putItems(
378 [item("skill-plan", 2, "# Verify\nUse $test-t3-app now", "proposed_plan")],
379 "plan",
380 );
381 assert.equal((yield* projection.searchThread(input)).totalMatches, 1);
382 assert.equal(
383 (yield* projection.searchThread({ ...input, query: "$test-t3-app" })).totalMatches,
384 1,
385 );
386 assert.equal((yield* projection.searchThread({ ...input, query: "App" })).totalMatches, 2);
387 }).pipe(Effect.provide(layerTest)),
388 );
389
390 it.effect("never mixes message versions when the searched thread changes during a scan", () =>
391 Effect.gen(function* () {
392 const projection = yield* setup;
393 const sql = yield* SqlClient.SqlClient;
394 const items = Array.from({ length: 260 }, (_, i) => item(`message:${i}`, i, "needle"));
395 yield* putItems(items);
396 const updated = items.map((item) =>
397 item.type === "assistant_message" ? { ...item, text: "needle needle" } : item,
398 );
399 const [during] = yield* Effect.all(
400 [
401 projection.searchThread({ threadId, query: "needle" }),
402 sql.withTransaction(putItems(updated, "concurrent")),
403 ],
404 { concurrency: "unbounded" },
405 );
406 assert.include([260, 520], during.totalMatches);
407 assert.equal(
408 (yield* projection.searchThread({ threadId, query: "needle" })).totalMatches,
409 520,
410 );
411 }).pipe(Effect.provide(layerTest)),
412 );
413
414 it.effect("starts at the reading position and wraps when no later match exists", () =>
415 Effect.gen(function* () {
416 const projection = yield* setup;
417 yield* putItems([
418 item("first", 1, "needle"),
419 item("reading", 2, "needle above, needle below"),
420 item("between", 3, "nothing"),
421 item("last", 4, "needle"),
422 item("end", 5, "nothing"),
423 ]);
424 const from = (entryId: string, occurrence = 0) =>
425 projection.searchThread({ threadId, query: "needle", start: { entryId, occurrence } });
426 assert.equal((yield* from("reading")).activeIndex, 1);
427 const below = yield* from("reading", 1);
428 assert.equal(below.activeIndex, 2);
429 assert.equal(below.match?.occurrence, 1);
430 assert.equal((yield* from("between")).match?.entryId, "last");
431 assert.equal((yield* from("reading", 2)).activeIndex, 3);
432 assert.equal((yield* from("end")).match?.entryId, "first");
433 assert.equal((yield* from("missing")).activeIndex, 0);
434 const explicit = yield* projection.searchThread({
435 threadId,
436 query: "needle",
437 start: { entryId: "last", occurrence: 0 },
438 index: 1,
439 });
440 assert.equal(explicit.match?.entryId, "reading");
441 }).pipe(Effect.provide(layerTest)),
442 );
443
444 it.effect("finds matches beyond the recent history window", () =>
445 Effect.gen(function* () {
446 const projection = yield* setup;
447 const items = Array.from({ length: 520 }, (_, i) =>
448 item(`message:${i}`, i + 1, i === 8 || i === 510 ? "sentinel" : "other message"),
449 );
450 yield* putItems(items);
451 const first = yield* projection.searchThread({ threadId, query: "sentinel" });
452 const last = yield* projection.searchThread({ threadId, query: "sentinel", index: 1 });
453 assert.equal(first.totalMatches, 2);
454 assert.equal(first.match?.entryId, "message:8");
455 assert.equal(last.match?.entryId, "message:510");
456 }).pipe(Effect.provide(layerTest)),
457 );
458
459 it.effect("invalidates cached counts when streamed text changes or a run rolls back", () =>
460 Effect.gen(function* () {
461 const projection = yield* setup;
462 const original = item("streaming", 1, "needle");
463 yield* putItems([original]);
464 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 1);
465 if (original.type !== "assistant_message") return;
466 yield* putItems([{ ...original, text: "needle needle", streaming: true }], "streaming");
467 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 2);
468 const updated = run(threadId, runId, 1, "rolled_back");
469 yield* commit([{ ...updated, type: "run.updated" }]);
470 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 0);
471 }).pipe(Effect.provide(layerTest)),
472 );
473
474 it.effect(
475 "does not search undispatched inputs, cancelled queue rows, or folded question answers",
476 () =>
477 Effect.gen(function* () {
478 const projection = yield* setup;
479 const queuedRunId = RunId.make("queued:cancelled");
480 yield* commit([run(threadId, queuedRunId, 2, "cancelled")]);
481 const queued = item("cancelled", 1, "needle", "user_message");
482 if (queued.type !== "user_message") return;
483 const answer = item("async-answer:question", 2, "needle", "user_message");
484 const question: OrchestrationV2TurnItem = {
485 ...item("question", 3, ""),
486 type: "user_input_request",
487 requestId: RuntimeRequestId.make("question"),
488 questions: [],
489 questionAnswer: { requestId: "question", answers: {}, attachmentsByQuestionId: {} },
490 };
491 yield* putItems([
492 { ...queued, runId: queuedRunId, inputIntent: "queued_turn" },
493 answer,
494 question,
495 ]);
496 const event: OrchestrationV2DomainEvent = {
497 id: EventId.make("undispatched"),
498 threadId,
499 occurredAt: at(2),
500 type: "message.updated",
501 payload: {
502 id: MessageId.make("undispatched"),
503 threadId,
504 runId: null,
505 nodeId: null,
506 role: "user",
507 text: "needle",
508 attachments: [],
509 streaming: false,
510 createdBy: "user",
511 creationSource: "web",
512 createdAt: at(2),
513 updatedAt: at(2),
514 },
515 };
516 yield* commit([event]);
517 const result = yield* projection.searchThread({ threadId, query: "needle" });
518 assert.equal(result.totalMatches, 0);
519 assert.isNull(result.match);
520 }).pipe(Effect.provide(layerTest)),
521 );
522
523 it.effect(
524 "searches inherited fork history through the fork boundary, using source item identities",
525 () =>
526 Effect.gen(function* () {
527 const projection = yield* setup;
528 const parent = ThreadId.make("thread:parent");
529 const laterRun = RunId.make("run:later");
530 const parentRun = RunId.make("run:parent");
531 yield* commit([
532 thread(parent, projectId),
533 run(parent, parentRun),
534 run(parent, laterRun, 2),
535 ]);
536 yield* putItems([
537 { ...item("inherited", 1, "needle", "assistant_message", parent), runId: parentRun },
538 { ...item("after-fork", 2, "needle", "assistant_message", parent), runId: laterRun },
539 ]);
540 const child = thread(threadId, projectId);
541 if (child.type !== "thread.created") return;
542 yield* commit([
543 {
544 ...child,
545 id: EventId.make("child:fork"),
546 type: "thread.metadata-updated",
547 payload: {
548 ...child.payload,
549 forkedFrom: { type: "run", threadId: parent, runId: parentRun },
550 },
551 },
552 ]);
553 yield* putItems([item("local", 1, "needle")]);
554 const inherited = yield* projection.searchThread({ threadId, query: "needle" });
555 assert.equal(inherited.totalMatches, 2);
556 assert.equal(inherited.match?.entryId, "inherited");
557 assert.equal(
558 (yield* projection.searchThread({ threadId, query: "needle", index: 1 })).match?.entryId,
559 "local",
560 );
561 const snapshot = yield* projection.getThreadSnapshot(threadId);
562 const history = yield* projection.getThreadHistoryPage(
563 threadId,
564 encodeThreadHistoryCursor({
565 snapshotSequence: snapshot.snapshotSequence,
566 sourceThreadId: threadId,
567 sourceItemId: "local",
568 position: 2,
569 }),
570 );
571 assert.deepEqual(
572 history.items,
573 snapshot.projection.visibleTurnItems
574 .slice(0, -1)
575 .map((row) => ({ ...row, item: projectTurnItemForWire(row.item) })),
576 );
577 assert.equal(history.items[0]?.sourceThreadId, parent);
578 assert.equal(history.items.at(-1)?.item.type, "fork");
579 yield* putItems(
580 [{ ...item("inherited", 1, "gone", "assistant_message", parent), runId: parentRun }],
581 "parent-update",
582 );
583 assert.equal(
584 (yield* projection.searchThread({ threadId, query: "needle" })).totalMatches,
585 1,
586 );
587 }).pipe(Effect.provide(layerTest)),
588 );
589
590 it.effect("rejects deleted threads and keeps results scoped to their thread", () =>
591 Effect.gen(function* () {
592 const projection = yield* setup;
593 const other = ThreadId.make("thread:other");
594 yield* commit([thread(other, projectId), run(other, RunId.make("run:other"))]);
595 yield* putItems([
596 item("shared-id", 1, "needle"),
597 item("other-id", 1, "other text", "assistant_message", other),
598 ]);
599 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 1);
600 assert.equal(
601 (yield* projection.searchThread({ threadId: other, query: "needle" })).totalMatches,
602 0,
603 );
604 const deleted = thread(threadId, projectId, { deletedAt: at(3) });
605 if (deleted.type !== "thread.created") return;
606 yield* commit([{ ...deleted, id: EventId.make("deleted"), type: "thread.deleted" }]);
607 const error = yield* Effect.flip(projection.searchThread({ threadId, query: "needle" }));
608 assert.equal(error._tag, "ProjectionStoreThreadNotFoundError");
609 const historyError = yield* Effect.flip(
610 projection.getThreadHistoryPage(
611 threadId,
612 encodeThreadHistoryCursor({
613 snapshotSequence: 0,
614 sourceThreadId: threadId,
615 sourceItemId: "shared-id",
616 position: 0,
617 }),
618 ),
619 );
620 assert.equal(historyError._tag, "ProjectionStoreThreadNotFoundError");
621 }).pipe(Effect.provide(layerTest)),
622 );
623
624 it.effect("invalidates a cached fork search when its empty source gains its first message", () =>
625 Effect.gen(function* () {
626 const projection = yield* setup;
627 const parent = ThreadId.make("thread:empty-parent");
628 const parentRun = RunId.make("run:empty-parent");
629 yield* commit([thread(parent, projectId), run(parent, parentRun)]);
630 const child = thread(threadId, projectId);
631 if (child.type !== "thread.created") return;
632 yield* commit([
633 {
634 ...child,
635 id: EventId.make("child:empty-fork"),
636 type: "thread.metadata-updated",
637 payload: {
638 ...child.payload,
639 forkedFrom: { type: "run", threadId: parent, runId: parentRun },
640 },
641 },
642 ]);
643 yield* putItems([item("local", 1, "needle")]);
644 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 1);
645 yield* putItems([
646 { ...item("inherited", 1, "needle", "assistant_message", parent), runId: parentRun },
647 ]);
648 const updated = yield* projection.searchThread({ threadId, query: "needle" });
649 assert.equal(updated.totalMatches, 2);
650 assert.equal(updated.match?.entryId, "inherited");
651 }).pipe(Effect.provide(layerTest)),
652 );
653});
654
655describe("V2 history materialization", () => {
656 it.effect(
657 "combines history pages through a match's message identity without skipping intervening turns",
658 () =>
659 Effect.gen(function* () {
660 const projection = yield* setup;
661 const items = Array.from({ length: 45 }, (_, turn) => [
662 item(`user:${turn}`, turn * 3, `turn ${turn}`, "user_message"),
663 {
664 ...item(`answer:${turn}`, turn * 3 + 1, `answer ${turn}`),
665 messageId: MessageId.make(`message:${turn}`),
666 },
667 {
668 ...item(`tool:${turn}`, turn * 3 + 2, ""),
669 type: "command_execution" as const,
670 input: "pwd",
671 output: "huge output".repeat(1000),
672 exitCode: 0,
673 },
674 ]).flat();
675 yield* putItems(items);
676 const snapshot = yield* projection.getThreadSnapshot(threadId);
677 const cursor = encodeThreadHistoryCursor({
678 snapshotSequence: snapshot.snapshotSequence,
679 sourceThreadId: threadId,
680 sourceItemId: "absent",
681 position: items.length,
682 });
683 const ordinary = yield* projection.getThreadHistoryPage(threadId, cursor);
684 assert.equal(ordinary.items[0]?.sourceItemId, "user:25");
685 const targeted = yield* projection.getThreadHistoryPage(threadId, cursor, "message:10");
686 assert.equal(targeted.items[0]?.sourceItemId, "user:10");
687 assert.deepEqual(
688 targeted.items.map((row) => row.sourceItemId),
689 items.slice(30).map((entry) => entry.id),
690 );
691 const conversation = yield* projection.getThreadHistoryPage(
692 threadId,
693 cursor,
694 "message:10",
695 true,
696 );
697 assert.equal(conversation.nextCursor, targeted.nextCursor);
698 assert.equal(conversation.hasMoreHistory, targeted.hasMoreHistory);
699 assert.deepEqual(
700 conversation.items.map((row) => row.sourceItemId),
701 targeted.items
702 .filter((row) => row.item.type !== "command_execution")
703 .map((row) => row.sourceItemId),
704 );
705 assert.equal(conversation.items.length, 70);
706 assert.equal(targeted.items.length, 105);
707 assert.isTrue(targeted.hasMoreHistory);
708 const earlier = yield* projection.getThreadHistoryPage(threadId, targeted.nextCursor!);
709 assert.deepEqual(
710 earlier.items.map((row) => row.sourceItemId),
711 items.slice(0, 30).map((entry) => entry.id),
712 );
713 assert.isFalse(earlier.hasMoreHistory);
714 const capped = yield* projection.getThreadHistoryPage(threadId, cursor, "message:0");
715 assert.equal(capped.items[0]?.sourceItemId, "user:5");
716 const absent = yield* projection.getThreadHistoryPage(
717 threadId,
718 cursor,
719 "another-thread-message",
720 );
721 assert.deepEqual(absent, ordinary);
722 }).pipe(Effect.provide(layerTest)),
723 );
724
725 it.effect("pages complete turns without duplicating or skipping messages", () =>
726 Effect.gen(function* () {
727 const projection = yield* setup;
728 const items = Array.from({ length: 45 }, (_, turn) => [
729 item(`user:${turn}`, turn * 3, `turn ${turn}`, "user_message"),
730 {
731 ...item(`steer:${turn}`, turn * 3 + 1, "steer", "user_message"),
732 inputIntent: "steer" as const,
733 },
734 item(
735 `answer:${turn}`,
736 turn * 3 + 2,
737 turn === 40 ? "large ".repeat(200_000) : `answer ${turn}`,
738 ),
739 ]).flat();
740 yield* putItems(items);
741 const snapshot = yield* projection.getThreadSnapshot(threadId);
742 const rows = snapshot.projection.visibleTurnItems.map((row) => ({
743 ...row,
744 item: projectTurnItemForWire(row.item),
745 }));
746 let cursor: string | null = encodeThreadHistoryCursor({
747 snapshotSequence: snapshot.snapshotSequence,
748 sourceThreadId: threadId,
749 sourceItemId: "absent",
750 position: rows.length,
751 });
752 const collected: string[] = [];
753 while (cursor !== null) {
754 const page: OrchestrationV2ThreadHistoryPage = yield* projection.getThreadHistoryPage(
755 threadId,
756 cursor,
757 );
758 assert.deepEqual(page, {
759 snapshotSequence: snapshot.snapshotSequence,
760 ...selectHistoryPageFromCursor({
761 items: rows,
762 cursor,
763 snapshotSequence: snapshot.snapshotSequence,
764 }),
765 });
766 assert.equal(page.items[0]?.item.type, "user_message");
767 collected.unshift(...page.items.map((row) => String(row.sourceItemId)));
768 cursor = page.nextCursor;
769 }
770 assert.deepEqual(
771 collected,
772 items.map((entry) => String(entry.id)),
773 );
774 }).pipe(Effect.provide(layerTest)),
775 );
776
777 it.effect("enforces fallback item and byte limits and always admits an oversized row", () =>
778 Effect.gen(function* () {
779 const projection = yield* setup;
780 yield* putItems(
781 Array.from({ length: 80 }, (_, ordinal) =>
782 item(`row:${ordinal}`, ordinal, ordinal < 78 ? "small" : "large ".repeat(200_000)),
783 ),
784 );
785 const snapshot = yield* projection.getThreadSnapshot(threadId);
786 const rows = snapshot.projection.visibleTurnItems.map((row) => ({
787 ...row,
788 item: projectTurnItemForWire(row.item),
789 }));
790 let cursor: string | null = encodeThreadHistoryCursor({
791 snapshotSequence: snapshot.snapshotSequence,
792 sourceThreadId: threadId,
793 sourceItemId: "absent",
794 position: rows.length,
795 });
796 const sizes: number[] = [];
797 while (cursor !== null) {
798 const page: OrchestrationV2ThreadHistoryPage = yield* projection.getThreadHistoryPage(
799 threadId,
800 cursor,
801 );
802 assert.deepEqual(page, {
803 snapshotSequence: snapshot.snapshotSequence,
804 ...selectHistoryPageFromCursor({
805 items: rows,
806 cursor,
807 snapshotSequence: snapshot.snapshotSequence,
808 }),
809 });
810 sizes.push(page.items.length);
811 cursor = page.nextCursor;
812 }
813 assert.deepEqual(sizes, [1, 1, 75, 3]);
814 }).pipe(Effect.provide(layerTest)),
815 );
816});