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

threadSort.test.ts

323 lines10.5 KB

1import { RunId } from "@t3tools/contracts";
2import { describe, expect, it } from "vite-plus/test";
3​
4import {
5 generateSpreadPinOrderKeys,
6 pinOrderKeyBetween,
7 planPinnedMove,
8 planPinnedReorder,
9 resolveSettledThreadTimestamp,
10 sortActiveThreadsByOrderKey,
11 sortSettledThreads,
12 sortThreads,
13 type SettledThreadTimestampInput,
14 type ThreadSortInput,
15} from "./threadSort.ts";
16​
17type TestThread = { readonly id: string } & ThreadSortInput;
18​
19function makeThread(overrides: Partial<TestThread> = {}): TestThread {
20 return {
21 id: "thread-1",
22 createdAt: "2026-03-09T10:00:00.000Z",
23 updatedAt: "2026-03-09T10:00:00.000Z",
24 messages: [],
25 latestUserMessageAt: null,
26 ...overrides,
27 };
29​
30describe("resolveSettledThreadTimestamp", () => {
31 it("prefers the persisted settlement stamp over later activity", () => {
32 expect(
33 resolveSettledThreadTimestamp({
34 settledAt: "2026-03-09T10:00:00.000Z",
35 latestUserMessageAt: "2026-03-09T11:00:00.000Z",
36 latestRun: null,
37 updatedAt: "2026-03-09T12:00:00.000Z",
38 }),
39 ).toBe("2026-03-09T10:00:00.000Z");
40 });
41​
42 it("falls back to the latest activity when the stamp is missing or malformed", () => {
43 expect(
44 resolveSettledThreadTimestamp({
45 settledAt: "invalid",
46 latestUserMessageAt: "2026-03-09T11:00:00.000Z",
47 latestRun: null,
48 updatedAt: "2026-03-09T12:00:00.000Z",
49 }),
50 ).toBe("2026-03-09T11:00:00.000Z");
51 expect(
52 resolveSettledThreadTimestamp({
53 settledAt: null,
54 latestUserMessageAt: null,
55 latestRun: null,
56 updatedAt: "2026-03-09T12:00:00.000Z",
57 }),
58 ).toBe("2026-03-09T12:00:00.000Z");
59 });
60});
61​
62describe("sortSettledThreads", () => {
63 const settled = (input: {
64 id: string;
65 settledAt?: string | null;
66 latestUserMessageAt?: string | null;
67 latestRun?: SettledThreadTimestampInput["latestRun"];
68 updatedAt?: string;
69 }) => ({
70 id: input.id,
71 settledAt: input.settledAt ?? null,
72 latestUserMessageAt: input.latestUserMessageAt ?? null,
73 latestRun: input.latestRun ?? null,
74 updatedAt: input.updatedAt ?? "2026-03-09T09:00:00.000Z",
75 });
76​
77 it("counts a turn completion as activity for auto-settled threads", () => {
78 const sorted = sortSettledThreads([
79 settled({ id: "message-only", latestUserMessageAt: "2026-03-09T10:04:00.000Z" }),
80 settled({
81 id: "completed-later",
82 latestUserMessageAt: "2026-03-09T10:00:00.000Z",
83 latestRun: {
84 runId: RunId.make("run-1"),
85 status: "completed",
86 assistantMessageId: null,
87 requestedAt: "2026-03-09T10:00:00.000Z",
88 startedAt: "2026-03-09T10:00:00.000Z",
89 completedAt: "2026-03-09T10:30:00.000Z",
90 },
91 }),
92 ]);
93​
94 expect(sorted.map((thread) => thread.id)).toEqual(["completed-later", "message-only"]);
95 });
96​
97 it("breaks timestamp ties by id so the order is stable", () => {
98 const sorted = sortSettledThreads([
99 settled({ id: "b", settledAt: "2026-03-09T10:00:00.000Z" }),
100 settled({ id: "a", settledAt: "2026-03-09T10:00:00.000Z" }),
101 ]);
102​
103 expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
104 });
105});
106​
107describe("sortThreads", () => {
108 it.each(["created_at", "updated_at"] as const)(
109 "preserves references, input order and descending id ties for %s",
110 (sortOrder) => {
111 const threads = Object.freeze([
112 makeThread({ id: "a" }),
113 makeThread({ id: "z" }),
114 makeThread({ id: "invalid-a", createdAt: "invalid", updatedAt: "invalid" }),
115 makeThread({ id: "invalid-z", createdAt: "invalid", updatedAt: "invalid" }),
116 ]);
117 const sorted = sortThreads(threads, sortOrder);
118 expect(sorted).toEqual([threads[1], threads[0], threads[3], threads[2]]);
119 expect(sorted[0]).toBe(threads[1]);
120 expect(threads[0]?.id).toBe("a");
121 },
122 );
123​
124 it("falls back to updatedAt and createdAt when latestUserMessageAt is invalid and there are no messages", () => {
125 const sorted = sortThreads(
126 [
127 makeThread({
128 id: "thread-1",
129 latestUserMessageAt: "not-a-date",
130 createdAt: "2026-03-09T10:00:00.000Z",
131 updatedAt: "2026-03-09T10:05:00.000Z",
132 }),
133 makeThread({
134 id: "thread-2",
135 latestUserMessageAt: "still-not-a-date",
136 createdAt: "invalid-created-at",
137 updatedAt: "invalid-updated-at",
138 }),
139 makeThread({
140 id: "thread-3",
141 latestUserMessageAt: "invalid-latest-user-message-at",
142 createdAt: "2026-03-09T10:06:00.000Z",
143 updatedAt: "invalid-updated-at",
144 }),
145 ],
146 "updated_at",
147 );
148​
149 expect(sorted.map((thread) => thread.id)).toEqual(["thread-3", "thread-1", "thread-2"]);
150 });
151​
152 it("falls back to the latest valid user message when latestUserMessageAt is invalid", () => {
153 const sorted = sortThreads(
154 [
155 makeThread({
156 id: "thread-1",
157 latestUserMessageAt: "invalid-latest-user-message-at",
158 updatedAt: "2026-03-09T10:00:00.000Z",
159 messages: [
160 { role: "user", createdAt: "2026-03-09T10:05:00.000Z" },
161 { role: "assistant", createdAt: "2026-03-09T10:30:00.000Z" },
162 { role: "user", createdAt: "2026-03-09T10:20:00.000Z" },
163 ],
164 }),
165 makeThread({
166 id: "thread-2",
167 createdAt: "2026-03-09T10:15:00.000Z",
168 updatedAt: "2026-03-09T10:15:00.000Z",
169 }),
170 ],
171 "updated_at",
172 );
173​
174 expect(sorted.map((thread) => thread.id)).toEqual(["thread-1", "thread-2"]);
175 });
176});
177​
178describe("planPinnedReorder with hidden rows", () => {
179 it("keeps hidden slots available when inserting between visible neighbors", () => {
180 const midpoint = pinOrderKeyBetween("f", "t")!;
181 const keysById = new Map([
182 ["a", "f"],
183 ["b", "t"],
184 ["moved", "z"],
185 ["snoozed", midpoint],
186 ]);
187 const assignments = planPinnedReorder({
188 orderedIds: ["a", "moved", "b"],
189 keysById,
190 movedId: "moved",
191 });
192 expect(assignments).toHaveLength(1);
193 const key = assignments[0]!.orderKey;
194 expect(key > "f" && key < "t").toBe(true);
195 expect(key).not.toBe(midpoint);
196 expect(assignments[0]!.id).toBe("moved");
197 });
198​
199 it("materializes keyless rows without overwriting hidden slots", () => {
200 const reserved = generateSpreadPinOrderKeys(6);
201 const keysById = new Map<string, string | null>([
202 ["a", null],
203 ["b", null],
204 ["c", null],
205 ...reserved.map((key, i) => [`hidden-${i}`, key] as const),
206 ]);
207 const assignments = planPinnedReorder({ orderedIds: ["c", "a", "b"], keysById, movedId: "c" });
208 expect(assignments.map(({ id }) => id)).toEqual(["c", "a", "b"]);
209 const keys = assignments.map(({ orderKey }) => orderKey);
210 expect(keys).toEqual([...keys].sort());
211 expect(new Set(keys).size).toBe(3);
212 expect(keys.every((key) => !reserved.includes(key))).toBe(true);
213 });
214});
215​
216describe("generateSpreadPinOrderKeys", () => {
217 it.each([0, 1, 650, 675, 676, 1_001, 2_000])(
218 "leaves unique, insertable keys for %i threads",
219 (count) => {
220 const keys = generateSpreadPinOrderKeys(count);
221 expect(keys).toHaveLength(count);
222 expect(new Set(keys).size).toBe(count);
223 expect([...keys].sort()).toEqual(keys);
224 for (let index = 0; index < keys.length; index += 1) {
225 const before = keys[index - 1] ?? null;
226 const after = keys[index]!;
227 expect(after).toMatch(/^[a-z]*[b-z]$/);
228 const between = pinOrderKeyBetween(before, after);
229 expect(between).not.toBeNull();
230 expect(between! < after).toBe(true);
231 if (before !== null) expect(between! > before).toBe(true);
232 }
233 },
234 );
235});
236​
237describe("sortActiveThreadsByOrderKey", () => {
238 it("keeps new and reopened threads ahead of the saved order", () => {
239 const sorted = sortActiveThreadsByOrderKey([
240 {
241 id: "arranged-first",
242 createdAt: "2026-03-09T09:00:00.000Z",
243 activeOrderKey: "f",
244 },
245 {
246 id: "new",
247 createdAt: "2026-03-09T11:00:00.000Z",
248 activeOrderKey: null,
249 },
250 {
251 id: "arranged-last",
252 createdAt: "2026-03-09T12:00:00.000Z",
253 unsettledAt: "2026-03-09T13:00:00.000Z",
254 activeOrderKey: "t",
255 },
256 {
257 id: "reopened",
258 createdAt: "2026-03-01T09:00:00.000Z",
259 unsettledAt: "2026-03-09T12:00:00.000Z",
260 },
261 ]);
262 expect(sorted.map((thread) => thread.id)).toEqual([
263 "reopened",
264 "new",
265 "arranged-first",
266 "arranged-last",
267 ]);
268 });
269​
270 it("breaks equal order keys and timestamps by thread then environment", () => {
271 for (const activeOrderKey of [null, "m"]) {
272 const threads = [
273 { id: "thread-b", environmentId: "env-a" },
274 { id: "thread-a", environmentId: "env-b" },
275 { id: "thread-a", environmentId: "env-a" },
276 ].map((thread) => ({
277 ...thread,
278 createdAt: "2026-03-09T10:00:00.000Z",
279 activeOrderKey,
280 }));
281 expect(
282 sortActiveThreadsByOrderKey(threads).map(
283 (thread) => `${thread.id}:${thread.environmentId}`,
284 ),
285 ).toEqual(["thread-a:env-a", "thread-a:env-b", "thread-b:env-a"]);
286 }
287 });
288​
289 it("moves a keyless thread into the arranged run with one write", () => {
290 const assignments = planPinnedMove({
291 orderedIds: ["new", "reopened", "first", "last"],
292 keysById: new Map([
293 ["new", null],
294 ["reopened", null],
295 ["first", "f"],
296 ["last", "t"],
297 ]),
298 movedId: "reopened",
299 direction: "down",
300 });
301 expect(assignments).toHaveLength(1);
302 expect(assignments![0]!.id).toBe("reopened");
303 expect(assignments![0]!.orderKey > "f").toBe(true);
304 expect(assignments![0]!.orderKey < "t").toBe(true);
305 });
306​
307 it("materializes a large active list without changing the requested order", () => {
308 const threads = Array.from({ length: 1_200 }, (_, index) => ({
309 id: String(index),
310 createdAt: "2026-03-09T10:00:00.000Z",
311 activeOrderKey: null as string | null,
312 }));
313 const orderedIds = threads.map((thread) => thread.id).toReversed();
314 const assignments = planPinnedReorder({
315 orderedIds,
316 movedId: orderedIds[0]!,
317 keysById: new Map(threads.map((thread) => [thread.id, thread.activeOrderKey])),
318 });
319 const keys = new Map(assignments.map((assignment) => [assignment.id, assignment.orderKey]));
320 const updated = threads.map((thread) => ({ ...thread, activeOrderKey: keys.get(thread.id) }));
321 expect(sortActiveThreadsByOrderKey(updated).map((thread) => thread.id)).toEqual(orderedIds);
322 });
323});