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

threadSearch.test.ts

270 lines9.9 KB

1import {
2 EnvironmentId,
3 ProjectId,
4 ThreadId,
5 type OrchestrationSearchThreadsResult,
6 type OrchestrationV2SearchThreadsInput,
7 type OrchestrationV2ThreadShell,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
11import { expect, it } from "vite-plus/test";
12​
13import {
14 claimThreadOpen,
15 createThreadSearchResultsAtomFamily,
16 makeThreadSearchKey,
17 nextShownOrder,
18 releaseThreadOpen,
19 threadSearchMatchKey,
20 threadSearchSubject,
21 visibleThreadSearch,
22} from "./threadSearch.ts";
23​
24const envA = EnvironmentId.make("env-a");
25const envB = EnvironmentId.make("env-b");
26​
27it("creates keys without array methods unavailable in Hermes", () => {
28 const descriptor = Object.getOwnPropertyDescriptor(Array.prototype, "toSorted");
29 Reflect.deleteProperty(Array.prototype, "toSorted");
30​
31 try {
32 expect(makeThreadSearchKey([envB, envA], "needle")).toBe('[["env-a","env-b"],"needle"]');
33 } finally {
34 if (descriptor !== undefined) {
35 Reflect.defineProperty(Array.prototype, "toSorted", descriptor);
36 }
37 }
38});
39​
40it("encodes scoped thread keys without delimiter collisions", () => {
41 const first = threadSearchMatchKey({
42 environmentId: EnvironmentId.make("env\u0000thread"),
43 threadId: ThreadId.make("id"),
44 });
45 const second = threadSearchMatchKey({
46 environmentId: EnvironmentId.make("env"),
47 threadId: ThreadId.make("thread\u0000id"),
48 });
49​
50 expect(first).not.toBe(second);
51});
52​
53it("ignores invalid search keys", () => {
54 let searchCount = 0;
55 const searchAtom = createThreadSearchResultsAtomFamily<Error>({
56 getSearchAtom: () => {
57 searchCount += 1;
58 return Atom.make(AsyncResult.success({ matches: [] }));
59 },
60 labelPrefix: "test:thread-search",
61 }).results;
62 const registry = AtomRegistry.make();
63​
64 try {
65 const state = registry.get(searchAtom(makeThreadSearchKey([envA], "a".repeat(201))));
66 const malformedState = registry.get(searchAtom("not json{{"));
67​
68 expect(state).toEqual({ matches: [], isLoading: false, failed: false, rows: [] });
69 expect(malformedState).toEqual({ matches: [], isLoading: false, failed: false, rows: [] });
70 expect(searchCount).toBe(0);
71 } finally {
72 registry.dispose();
73 }
74});
75​
76it("merges successful environments, and reports a failure only when none answered", () => {
77 const result: OrchestrationSearchThreadsResult = {
78 matches: [
79 {
80 threadId: ThreadId.make("thread-a"),
81 projectId: ProjectId.make("project-a"),
82 source: "user",
83 snippet: "needle",
84 messageCreatedAt: "2026-07-30T00:00:00.000Z",
85 },
86 ],
87 };
88 const searchAtom = createThreadSearchResultsAtomFamily<Error>({
89 getSearchAtom: (environmentId) =>
90 environmentId === envA
91 ? Atom.make(AsyncResult.success(result))
92 : Atom.make(
93 AsyncResult.failure<OrchestrationSearchThreadsResult, Error>(
94 Cause.fail(new Error("unsupported rpc")),
95 ),
96 ),
97 labelPrefix: "test:thread-search",
98 }).results;
99 const registry = AtomRegistry.make();
100​
101 const state = registry.get(searchAtom(makeThreadSearchKey([envB, envA], "needle")));
102 expect(state).toEqual({
103 matches: [{ ...result.matches[0], environmentId: envA }],
104 isLoading: false,
105 failed: false,
106 rows: [],
107 });
108 expect(threadSearchMatchKey(state.matches[0]!)).toBe('["env-a","thread-a"]');
109 // With no environment answering, an empty result must not read as "no matches".
110 expect(registry.get(searchAtom(makeThreadSearchKey([envB], "needle")))).toEqual({
111 matches: [],
112 isLoading: false,
113 failed: true,
114 rows: [],
115 });
116​
117 registry.dispose();
118});
119​
120it("asks environments that omit older settled threads for their rows, with the caller's scope", () => {
121 const inputs: Array<readonly [EnvironmentId, OrchestrationV2SearchThreadsInput]> = [];
122 const row = { id: ThreadId.make("thread-old") } as OrchestrationV2ThreadShell;
123 const search = createThreadSearchResultsAtomFamily<Error>({
124 getSearchAtom: (environmentId, input) => {
125 inputs.push([environmentId, input]);
126 return Atom.make(AsyncResult.success({ matches: [], snapshotSequence: 9, threads: [row] }));
127 },
128 olderSettledBefore: (environmentId) =>
129 Atom.make(environmentId === envA ? "2026-10-01T00:00:00.000Z" : null),
130 labelPrefix: "test:thread-search",
131 });
132 const registry = AtomRegistry.make();
133 const scope = {
134 projectIds: [ProjectId.make("project-a")],
135 environmentLabels: { [envA]: "Laptop" },
136 };
137​
138 // Too short to match messages: only the environment with older rows is asked, for titles.
139 const key = makeThreadSearchKey([envA, envB], "ui", scope);
140 expect(registry.get(search.results(key)).rows).toEqual([
141 { environmentId: envA, read: { snapshotSequence: 9, threads: [row] } },
142 ]);
143 expect(registry.get(search.rows(key, envA))).toEqual([{ snapshotSequence: 9, threads: [row] }]);
144 expect(inputs).toEqual([
145 [
146 envA,
147 {
148 query: "ui",
149 olderSettledBefore: "2026-10-01T00:00:00.000Z",
150 projectIds: scope.projectIds,
151 environmentLabel: "Laptop",
152 titlesOnly: true,
153 },
154 ],
155 ]);
156 inputs.length = 0;
157 registry.get(search.results(makeThreadSearchKey([envB], "needle")));
158 expect(inputs).toEqual([[envB, { query: "needle" }]]);
159 inputs.length = 0;
160 // Message hits stay in the caller's projects without an older settled cut too.
161 registry.get(search.results(makeThreadSearchKey([envB], "needle", scope)));
162 expect(inputs).toEqual([[envB, { query: "needle", projectIds: scope.projectIds }]]);
163​
164 registry.dispose();
165});
166​
167it("keeps the previous results visible only while a refined or widened query is pending", () => {
168 const previous = {
169 query: "websock",
170 matches: [
171 {
172 environmentId: envA,
173 threadId: ThreadId.make("thread-a"),
174 projectId: ProjectId.make("project-a"),
175 source: "user" as const,
176 snippet: "websocket reconnect",
177 messageCreatedAt: null,
178 },
179 ],
180 };
181 expect(visibleThreadSearch("websocke", null, previous)).toBe(previous);
182 expect(visibleThreadSearch("webso", null, previous)).toBe(previous);
183 expect(visibleThreadSearch("billing", null, previous)).toEqual({ query: "", matches: [] });
184 const ready = { query: "websocke", matches: [] };
185 expect(visibleThreadSearch("websocke", ready, previous)).toBe(ready);
186});
187​
188it("ranks recent threads by this client's own latest open", () => {
189 const thread = {
190 environmentId: envA,
191 id: ThreadId.make("thread-local"),
192 title: "Local",
193 branch: null,
194 createdAt: "2026-10-01T00:00:00.000Z",
195 updatedAt: "2026-10-01T00:00:00.000Z",
196 latestUserMessageAt: null,
197 opens: { openedAt: 1_000, score: 1, picks: [] },
198 };
199 claimThreadOpen(envA, "thread-local", 5_000);
200 expect(threadSearchSubject(thread, null).opens).toEqual({
201 openedAt: 5_000,
202 scoredAt: 1_000,
203 score: 1,
204 picks: [],
205 });
206 // Also when the server has no record of opens, as an older server would not.
207 claimThreadOpen(envA, "thread-unrecorded", 6_000);
208 expect(
209 threadSearchSubject({ ...thread, id: ThreadId.make("thread-unrecorded"), opens: null }, null)
210 .opens,
211 ).toEqual({ openedAt: 6_000, score: 1, picks: [] });
212 // A subject built before the open does not hide it.
213 claimThreadOpen(envA, "thread-local", 7_000);
214 expect(threadSearchSubject(thread, null).opens?.openedAt).toBe(7_000);
215 expect(threadSearchSubject(thread, "Project").projectTitle).toBe("Project");
216});
217​
218it("counts recency from what the user wrote, else from when the thread began", () => {
219 const thread = {
220 environmentId: envA,
221 id: ThreadId.make("thread-agent"),
222 title: "Launched by an agent",
223 branch: null,
224 createdAt: "2026-10-01T00:00:00.000Z",
225 updatedAt: "2026-10-20T00:00:00.000Z",
226 latestUserMessageAt: "2026-10-20T00:00:00.000Z",
227 opens: null,
228 };
229 expect(
230 threadSearchSubject({ ...thread, latestUserAuthoredMessageAt: null }, null).activityAt,
231 ).toBe(Date.parse("2026-10-01T00:00:00.000Z"));
232 expect(
233 threadSearchSubject(
234 { ...thread, latestUserAuthoredMessageAt: "2026-10-05T00:00:00.000Z" },
235 null,
236 ).activityAt,
237 ).toBe(Date.parse("2026-10-05T00:00:00.000Z"));
238 // An older server omits the field.
239 expect(threadSearchSubject(thread, null).activityAt).toBe(Date.parse("2026-10-20T00:00:00.000Z"));
240});
241​
242it("keeps shown message rows in place and leaves room for a slower environment", () => {
243 // The fast environment answers first and fills the limit.
244 const fast = Array.from({ length: 12 }, (_, index) => `a${index}`);
245 const first = nextShownOrder(null, "rust", fast, 10);
246 expect(first.keys.slice(0, first.shown)).toEqual(fast.slice(0, 10));
247 // The slow one's matches rank first: shown rows hold, and its best few come next.
248 const slow = ["b0", "b1", "b2", "b3"];
249 const second = nextShownOrder(first, "rust", [...slow, ...fast], 10);
250 expect(second.keys.slice(0, second.shown)).toEqual([...fast.slice(0, 10), "b0", "b1", "b2"]);
251 // Nothing new: nothing moves and nothing grows.
252 expect(nextShownOrder(second, "rust", [...slow, ...fast], 10)).toBe(second);
253 // A third environment gets no more room past the limit.
254 const third = nextShownOrder(second, "rust", ["c0", ...slow, ...fast], 10);
255 expect(third.shown).toBe(13);
256 expect(third.keys.slice(0, 13)).toEqual(second.keys.slice(0, 13));
257 // A new query starts from its own ranking.
258 expect(nextShownOrder(second, "rusty", ["b0"], 10).keys).toEqual(["b0"]);
259});
260​
261it("dedupes repeated opens of the open thread but sends a switch back within ten minutes", () => {
262 const minute = 60_000;
263 expect(claimThreadOpen(envA, "thread-open", 0)).toBe(true);
264 expect(claimThreadOpen(envA, "thread-open", 9 * minute)).toBe(false);
265 expect(claimThreadOpen(envB, "thread-open", 9 * minute)).toBe(true);
266 expect(claimThreadOpen(envA, "thread-open", 9 * minute + 1_000)).toBe(true);
267 releaseThreadOpen(envA, "thread-open");
268 expect(claimThreadOpen(envA, "thread-open", 9 * minute + 2_000)).toBe(true);
269 expect(claimThreadOpen(envA, "thread-open", 20 * minute)).toBe(true);
270});