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

ThreadFind.test.ts

1,006 lines37.9 KB

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