Open History to see the last commit
1import {
2 EnvironmentId,
3 ProjectId,
4 ThreadId,
5 type OrchestrationSearchThreadsResult,
6} from "@t3tools/contracts";
7import * as Cause from "effect/Cause";
8import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
9import { expect, it } from "vite-plus/test";
10
11import {
12 claimThreadOpen,
13 nextShownOrder,
14 createThreadSearchResultsAtomFamily,
15 makeThreadSearchKey,
16 threadSearchMatchKey,
17 threadSearchSubject,
18 visibleThreadSearch,
19} from "./threadSearch.ts";
20
21const envA = EnvironmentId.make("env-a");
22const envB = EnvironmentId.make("env-b");
23
24it("creates keys without array methods unavailable in Hermes", () => {
25 const descriptor = Object.getOwnPropertyDescriptor(Array.prototype, "toSorted");
26 Reflect.deleteProperty(Array.prototype, "toSorted");
27
28 try {
29 expect(makeThreadSearchKey([envB, envA], "needle")).toBe('[["env-a","env-b"],"needle"]');
30 } finally {
31 if (descriptor !== undefined) {
32 Reflect.defineProperty(Array.prototype, "toSorted", descriptor);
33 }
34 }
35});
36
37it("encodes scoped thread keys without delimiter collisions", () => {
38 const first = threadSearchMatchKey({
39 environmentId: EnvironmentId.make("env\u0000thread"),
40 threadId: ThreadId.make("id"),
41 });
42 const second = threadSearchMatchKey({
43 environmentId: EnvironmentId.make("env"),
44 threadId: ThreadId.make("thread\u0000id"),
45 });
46
47 expect(first).not.toBe(second);
48});
49
50it("ignores invalid search keys", () => {
51 let searchCount = 0;
52 const searchAtom = createThreadSearchResultsAtomFamily<Error>({
53 getSearchAtom: () => {
54 searchCount += 1;
55 return Atom.make(AsyncResult.success({ matches: [] }));
56 },
57 labelPrefix: "test:thread-search",
58 });
59 const registry = AtomRegistry.make();
60
61 try {
62 const state = registry.get(searchAtom(makeThreadSearchKey([envA], "a".repeat(201))));
63 const malformedState = registry.get(searchAtom("not json{{"));
64
65 expect(state).toEqual({ matches: [], isLoading: false });
66 expect(malformedState).toEqual({ matches: [], isLoading: false });
67 expect(searchCount).toBe(0);
68 } finally {
69 registry.dispose();
70 }
71});
72
73it("merges successful environments and silently ignores failures", () => {
74 const result: OrchestrationSearchThreadsResult = {
75 matches: [
76 {
77 threadId: ThreadId.make("thread-a"),
78 projectId: ProjectId.make("project-a"),
79 source: "user",
80 snippet: "needle",
81 messageCreatedAt: "2026-07-30T00:00:00.000Z",
82 },
83 ],
84 };
85 const searchAtom = createThreadSearchResultsAtomFamily<Error>({
86 getSearchAtom: (environmentId) =>
87 environmentId === envA
88 ? Atom.make(AsyncResult.success(result))
89 : Atom.make(
90 AsyncResult.failure<OrchestrationSearchThreadsResult, Error>(
91 Cause.fail(new Error("unsupported rpc")),
92 ),
93 ),
94 labelPrefix: "test:thread-search",
95 });
96 const registry = AtomRegistry.make();
97
98 const state = registry.get(searchAtom(makeThreadSearchKey([envB, envA], "needle")));
99 expect(state).toEqual({
100 matches: [{ ...result.matches[0], environmentId: envA }],
101 isLoading: false,
102 });
103 expect(threadSearchMatchKey(state.matches[0]!)).toBe('["env-a","thread-a"]');
104
105 registry.dispose();
106});
107
108it("keeps the previous results visible only while a refined or widened query is pending", () => {
109 const previous = {
110 query: "websock",
111 matches: [
112 {
113 environmentId: envA,
114 threadId: ThreadId.make("thread-a"),
115 projectId: ProjectId.make("project-a"),
116 source: "user" as const,
117 snippet: "websocket reconnect",
118 messageCreatedAt: null,
119 },
120 ],
121 };
122 expect(visibleThreadSearch("websocke", null, previous)).toBe(previous);
123 expect(visibleThreadSearch("webso", null, previous)).toBe(previous);
124 expect(visibleThreadSearch("billing", null, previous)).toEqual({ query: "", matches: [] });
125 const ready = { query: "websocke", matches: [] };
126 expect(visibleThreadSearch("websocke", ready, previous)).toBe(ready);
127});
128
129it("ranks recent threads by this client's own latest open", () => {
130 const thread = {
131 environmentId: envA,
132 id: ThreadId.make("thread-local"),
133 title: "Local",
134 branch: null,
135 createdAt: "2026-10-01T00:00:00.000Z",
136 updatedAt: "2026-10-01T00:00:00.000Z",
137 latestUserMessageAt: null,
138 opens: { openedAt: 1_000, score: 1, picks: [] },
139 };
140 claimThreadOpen(envA, "thread-local", 5_000);
141 expect(threadSearchSubject(thread, null).opens?.openedAt).toBe(5_000);
142 // Also when the server has no record of opens, as an older server would not.
143 claimThreadOpen(envA, "thread-unrecorded", 6_000);
144 expect(
145 threadSearchSubject({ ...thread, id: ThreadId.make("thread-unrecorded"), opens: null }, null)
146 .opens,
147 ).toEqual({ openedAt: 6_000, score: 1, picks: [] });
148});
149
150it("counts recency from what the user wrote, else from when the thread began", () => {
151 const thread = {
152 environmentId: envA,
153 id: ThreadId.make("thread-agent"),
154 title: "Launched by an agent",
155 branch: null,
156 createdAt: "2026-10-01T00:00:00.000Z",
157 updatedAt: "2026-10-20T00:00:00.000Z",
158 latestUserMessageAt: "2026-10-20T00:00:00.000Z",
159 opens: null,
160 };
161 expect(
162 threadSearchSubject({ ...thread, latestUserAuthoredMessageAt: null }, null).activityAt,
163 ).toBe(Date.parse("2026-10-01T00:00:00.000Z"));
164 expect(
165 threadSearchSubject(
166 { ...thread, latestUserAuthoredMessageAt: "2026-10-05T00:00:00.000Z" },
167 null,
168 ).activityAt,
169 ).toBe(Date.parse("2026-10-05T00:00:00.000Z"));
170 // An older server omits the field.
171 expect(threadSearchSubject(thread, null).activityAt).toBe(Date.parse("2026-10-20T00:00:00.000Z"));
172});
173
174it("keeps shown message rows in place and leaves room for a slower environment", () => {
175 // The fast environment answers first and fills the limit.
176 const fast = Array.from({ length: 12 }, (_, index) => `a${index}`);
177 const first = nextShownOrder(null, "rust", fast, 10);
178 expect(first.keys.slice(0, first.shown)).toEqual(fast.slice(0, 10));
179 // The slow one's matches rank first: shown rows hold, and its best few come next.
180 const slow = ["b0", "b1", "b2", "b3"];
181 const second = nextShownOrder(first, "rust", [...slow, ...fast], 10);
182 expect(second.keys.slice(0, second.shown)).toEqual([...fast.slice(0, 10), "b0", "b1", "b2"]);
183 // Nothing new: nothing moves and nothing grows.
184 expect(nextShownOrder(second, "rust", [...slow, ...fast], 10)).toBe(second);
185 // A third environment gets no more room past the limit.
186 const third = nextShownOrder(second, "rust", ["c0", ...slow, ...fast], 10);
187 expect(third.shown).toBe(13);
188 expect(third.keys.slice(0, 13)).toEqual(second.keys.slice(0, 13));
189 // A new query starts from its own ranking.
190 expect(nextShownOrder(second, "rusty", ["b0"], 10).keys).toEqual(["b0"]);
191});
192
193it("sends one open per thread every ten minutes by this client's clock", () => {
194 const minute = 60_000;
195 expect(claimThreadOpen(envA, "thread-open", 0)).toBe(true);
196 expect(claimThreadOpen(envA, "thread-open", 9 * minute)).toBe(false);
197 expect(claimThreadOpen(envB, "thread-open", 9 * minute)).toBe(true);
198 expect(claimThreadOpen(envA, "thread-open", 10 * minute)).toBe(true);
199});