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