Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 EventId,
4 MessageId,
5 ProjectId,
6 ProviderInstanceId,
7 ThreadId,
8 type OrchestrationV2DomainEvent,
9} from "@t3tools/contracts";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as SqlClient from "effect/sql/SqlClient";
14
15import * as SqlitePersistence from "../persistence/Sqlite.ts";
16import * as ProjectionStore from "./ProjectionStore.ts";
17import * as ProjectStore from "./ProjectStore.ts";
18import * as ThreadSearch from "./ThreadSearch.ts";
19
20const layerTest = Layer.mergeAll(
21 ThreadSearch.layer,
22 ProjectionStore.layer,
23 ProjectStore.layer,
24).pipe(Layer.provideMerge(SqlitePersistence.layerMemory));
25
26const providerInstanceId = ProviderInstanceId.make("codex");
27const at = (minute: number) => DateTime.makeUnsafe(Date.UTC(2026, 8, 27, 0, minute));
28
29const createProject = (projectId: ProjectId) =>
30 Effect.flatMap(ProjectStore.ProjectStoreV2, (projects) =>
31 projects.apply({
32 sequence: 0,
33 eventId: EventId.make(`created:${projectId}`),
34 aggregateKind: "project",
35 aggregateId: projectId,
36 occurredAt: DateTime.formatIso(at(0)),
37 commandId: null,
38 causationEventId: null,
39 correlationId: null,
40 metadata: {},
41 type: "project.created",
42 payload: {
43 projectId,
44 title: projectId,
45 workspaceRoot: `/work/${projectId}`,
46 defaultModelSelection: null,
47 scripts: [],
48 createdAt: DateTime.formatIso(at(0)),
49 updatedAt: DateTime.formatIso(at(0)),
50 },
51 }),
52 );
53
54const thread = (
55 threadId: ThreadId,
56 projectId: ProjectId,
57 overrides: { readonly archivedAt?: DateTime.Utc; readonly deletedAt?: DateTime.Utc } = {},
58): OrchestrationV2DomainEvent => ({
59 id: EventId.make(`created:${threadId}`),
60 type: "thread.created",
61 threadId,
62 providerInstanceId,
63 occurredAt: at(0),
64 payload: {
65 createdBy: "user",
66 creationSource: "web",
67 id: threadId,
68 projectId,
69 title: threadId,
70 providerInstanceId,
71 modelSelection: { instanceId: providerInstanceId, model: "gpt-5" },
72 runtimeMode: "full-access",
73 interactionMode: "default",
74 branch: null,
75 worktreePath: null,
76 activeProviderThreadId: null,
77 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
78 forkedFrom: null,
79 createdAt: at(0),
80 updatedAt: at(0),
81 archivedAt: overrides.archivedAt ?? null,
82 settledOverride: null,
83 settledAt: null,
84 lastVisitedAt: null,
85 deletedAt: overrides.deletedAt ?? null,
86 },
87});
88
89const message = (
90 threadId: ThreadId,
91 id: string,
92 role: "user" | "assistant" | "system",
93 text: string,
94 options: { readonly minute?: number; readonly streaming?: boolean } = {},
95): OrchestrationV2DomainEvent => ({
96 id: EventId.make(`message:${id}`),
97 type: "message.updated",
98 threadId,
99 providerInstanceId,
100 occurredAt: at(options.minute ?? 1),
101 payload: {
102 createdBy: role === "user" ? "user" : "agent",
103 creationSource: role === "user" ? "web" : "provider",
104 id: MessageId.make(id),
105 threadId,
106 runId: null,
107 nodeId: null,
108 role,
109 text,
110 attachments: [],
111 streaming: options.streaming ?? false,
112 createdAt: at(options.minute ?? 1),
113 updatedAt: at(options.minute ?? 1),
114 },
115});
116
117it.layer(layerTest)("ThreadSearch", (it) => {
118 it.effect("returns one finished user or assistant match per active thread", () =>
119 Effect.gen(function* () {
120 const projections = yield* ProjectionStore.ProjectionStoreV2;
121 const search = yield* ThreadSearch.ThreadSearch;
122 const project = ProjectId.make("project:search");
123 const deletedProject = ProjectId.make("project:search-deleted");
124 yield* createProject(project);
125 yield* createProject(deletedProject);
126 yield* Effect.flatMap(ProjectStore.ProjectStoreV2, (projects) =>
127 projects.apply({
128 sequence: 0,
129 eventId: EventId.make("deleted:project"),
130 aggregateKind: "project",
131 aggregateId: deletedProject,
132 occurredAt: DateTime.formatIso(at(2)),
133 commandId: null,
134 causationEventId: null,
135 correlationId: null,
136 metadata: {},
137 type: "project.deleted",
138 payload: { projectId: deletedProject, deletedAt: DateTime.formatIso(at(2)) },
139 }),
140 );
141
142 const both = ThreadId.make("thread:both");
143 const assistantOnly = ThreadId.make("thread:assistant");
144 const events: ReadonlyArray<OrchestrationV2DomainEvent> = [
145 thread(both, project),
146 message(both, "both-assistant", "assistant", "needle from the answer", { minute: 3 }),
147 message(both, "both-user-old", "user", "older needle question", { minute: 1 }),
148 message(both, "both-user-new", "user", "newer needle question", { minute: 2 }),
149 thread(assistantOnly, project),
150 message(assistantOnly, "assistant-only", "assistant", "needle in an answer"),
151 message(assistantOnly, "assistant-streaming", "user", "needle still typing", {
152 streaming: true,
153 }),
154 message(assistantOnly, "assistant-system", "system", "needle system prompt"),
155 thread(ThreadId.make("thread:archived"), project, { archivedAt: at(1) }),
156 message(ThreadId.make("thread:archived"), "archived", "user", "needle archived"),
157 thread(ThreadId.make("thread:deleted"), project, { deletedAt: at(1) }),
158 message(ThreadId.make("thread:deleted"), "deleted", "user", "needle deleted"),
159 thread(ThreadId.make("thread:orphaned"), deletedProject),
160 message(ThreadId.make("thread:orphaned"), "orphaned", "user", "needle orphaned"),
161 ];
162 yield* Effect.forEach(events, projections.apply, { discard: true });
163
164 const result = yield* search.search({ query: "NEEDLE", limit: 20 });
165 assert.deepEqual(
166 result.matches.map((match) => [match.threadId, match.source, match.snippet]),
167 [
168 [both, "user", "newer needle question"],
169 [assistantOnly, "assistant", "needle in an answer"],
170 ],
171 );
172 assert.lengthOf((yield* search.search({ query: "needle", limit: 1 })).matches, 1);
173 // LIKE wildcards in the query match literally.
174 assert.deepEqual((yield* search.search({ query: "ne%le" })).matches, []);
175 }),
176 );
177
178 it.effect("reports an unreadable match as a decode failure", () =>
179 Effect.gen(function* () {
180 const projections = yield* ProjectionStore.ProjectionStoreV2;
181 const search = yield* ThreadSearch.ThreadSearch;
182 const sql = yield* SqlClient.SqlClient;
183 const project = ProjectId.make("project:search-corrupt");
184 const threadId = ThreadId.make("thread:corrupt");
185 yield* createProject(project);
186 yield* Effect.forEach(
187 [thread(threadId, project), message(threadId, "corrupt", "user", "20260927")],
188 projections.apply,
189 { discard: true },
190 );
191 yield* sql`
192 UPDATE orchestration_v2_projection_messages
193 SET payload_json = json_set(payload_json, '$.text', 20260927)
194 WHERE message_id = 'corrupt'
195 `;
196
197 const error = yield* Effect.flip(search.search({ query: "0260927" }));
198 assert.equal(error.operation, "decode");
199 }),
200 );
201});