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

ThreadFind.test.ts

908 lines33.5 KB

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