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