Open History to see the last commit
1import { ProjectId } from "@t3tools/contracts";
2import { describe, expect, it } from "vite-plus/test";
3
4import {
5 generateSpreadPinOrderKeys,
6 getLatestThreadForProject,
7 pinOrderKeyBetween,
8 planPinnedMove,
9 planPinnedReorder,
10 resolveSettledThreadTimestamp,
11 sortActiveThreadsByOrderKey,
12 sortPinnedThreadsByOrderKey,
13 sortThreads,
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 };
28}
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 latestTurn: 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 latestTurn: 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 latestTurn: null,
56 updatedAt: "2026-03-09T12:00:00.000Z",
57 }),
58 ).toBe("2026-03-09T12:00:00.000Z");
59 });
60});
61
62describe("sortThreads", () => {
63 it.each(["created_at", "updated_at"] as const)(
64 "preserves references, input order and descending id ties for %s",
65 (sortOrder) => {
66 const threads = Object.freeze([
67 makeThread({ id: "a" }),
68 makeThread({ id: "z" }),
69 makeThread({ id: "invalid-a", createdAt: "invalid", updatedAt: "invalid" }),
70 makeThread({ id: "invalid-z", createdAt: "invalid", updatedAt: "invalid" }),
71 ]);
72 const sorted = sortThreads(threads, sortOrder);
73 expect(sorted).toEqual([threads[1], threads[0], threads[3], threads[2]]);
74 expect(sorted[0]).toBe(threads[1]);
75 expect(threads[0]?.id).toBe("a");
76 },
77 );
78
79 it("falls back to updatedAt and createdAt when latestUserMessageAt is invalid and there are no messages", () => {
80 const sorted = sortThreads(
81 [
82 makeThread({
83 id: "thread-1",
84 latestUserMessageAt: "not-a-date",
85 createdAt: "2026-03-09T10:00:00.000Z",
86 updatedAt: "2026-03-09T10:05:00.000Z",
87 }),
88 makeThread({
89 id: "thread-2",
90 latestUserMessageAt: "still-not-a-date",
91 createdAt: "invalid-created-at",
92 updatedAt: "invalid-updated-at",
93 }),
94 makeThread({
95 id: "thread-3",
96 latestUserMessageAt: "invalid-latest-user-message-at",
97 createdAt: "2026-03-09T10:06:00.000Z",
98 updatedAt: "invalid-updated-at",
99 }),
100 ],
101 "updated_at",
102 );
103
104 expect(sorted.map((thread) => thread.id)).toEqual(["thread-3", "thread-1", "thread-2"]);
105 });
106
107 it("falls back to the latest valid user message when latestUserMessageAt is invalid", () => {
108 const sorted = sortThreads(
109 [
110 makeThread({
111 id: "thread-1",
112 latestUserMessageAt: "invalid-latest-user-message-at",
113 updatedAt: "2026-03-09T10:00:00.000Z",
114 messages: [
115 { role: "user", createdAt: "2026-03-09T10:05:00.000Z" },
116 { role: "assistant", createdAt: "2026-03-09T10:30:00.000Z" },
117 { role: "user", createdAt: "2026-03-09T10:20:00.000Z" },
118 ],
119 }),
120 makeThread({
121 id: "thread-2",
122 createdAt: "2026-03-09T10:15:00.000Z",
123 updatedAt: "2026-03-09T10:15:00.000Z",
124 }),
125 ],
126 "updated_at",
127 );
128
129 expect(sorted.map((thread) => thread.id)).toEqual(["thread-1", "thread-2"]);
130 });
131});
132
133describe("getLatestThreadForProject", () => {
134 it.each(["created_at", "updated_at"] as const)(
135 "matches the first sorted eligible thread for %s",
136 (sortOrder) => {
137 const projectId = ProjectId.make("project");
138 const threads = [
139 { ...makeThread({ id: "a" }), projectId, archivedAt: null },
140 { ...makeThread({ id: "z" }), projectId, archivedAt: null },
141 { ...makeThread({ id: "zz" }), projectId, archivedAt: "2026-03-10T00:00:00Z" },
142 { ...makeThread({ id: "zzz" }), projectId: ProjectId.make("other"), archivedAt: null },
143 ];
144 expect(getLatestThreadForProject(threads, projectId, sortOrder)).toBe(threads[1]);
145 expect(getLatestThreadForProject([], projectId, sortOrder)).toBeNull();
146 expect(getLatestThreadForProject(threads, ProjectId.make("missing"), sortOrder)).toBeNull();
147 const invalid = threads.slice(0, 2).map((thread) => ({
148 ...thread,
149 createdAt: "invalid",
150 updatedAt: "invalid",
151 }));
152 expect(getLatestThreadForProject(invalid, projectId, sortOrder)).toBe(invalid[1]);
153 expect(
154 getLatestThreadForProject([threads[1]!, { ...threads[1]! }], projectId, sortOrder),
155 ).toBe(threads[1]);
156 },
157 );
158});
159
160describe("planPinnedReorder with hidden rows", () => {
161 it("keeps hidden slots available when inserting between visible neighbors", () => {
162 const midpoint = pinOrderKeyBetween("f", "t")!;
163 const keysById = new Map([
164 ["a", "f"],
165 ["b", "t"],
166 ["moved", "z"],
167 ["snoozed", midpoint],
168 ]);
169 const assignments = planPinnedReorder({
170 orderedIds: ["a", "moved", "b"],
171 keysById,
172 movedId: "moved",
173 });
174 expect(assignments).toHaveLength(1);
175 const key = assignments[0]!.orderKey;
176 expect(key > "f" && key < "t").toBe(true);
177 expect(key).not.toBe(midpoint);
178 expect(assignments[0]!.id).toBe("moved");
179 });
180
181 it("materializes keyless rows without overwriting hidden slots", () => {
182 const reserved = generateSpreadPinOrderKeys(6);
183 const keysById = new Map<string, string | null>([
184 ["a", null],
185 ["b", null],
186 ["c", null],
187 ...reserved.map((key, i) => [`hidden-${i}`, key] as const),
188 ]);
189 const assignments = planPinnedReorder({ orderedIds: ["c", "a", "b"], keysById, movedId: "c" });
190 expect(assignments.map(({ id }) => id)).toEqual(["c", "a", "b"]);
191 const keys = assignments.map(({ orderKey }) => orderKey);
192 expect(keys).toEqual([...keys].sort());
193 expect(new Set(keys).size).toBe(3);
194 expect(keys.every((key) => !reserved.includes(key))).toBe(true);
195 });
196});
197
198describe("planPinnedMove", () => {
199 it("moves a thread up with a single key write", () => {
200 const assignments = planPinnedMove({
201 orderedIds: ["a", "b", "c"],
202 keysById: new Map([
203 ["a", "f"],
204 ["b", "m"],
205 ["c", "t"],
206 ]),
207 movedId: "c",
208 direction: "up",
209 });
210 expect(assignments).toHaveLength(1);
211 expect(assignments![0]!.id).toBe("c");
212 expect(assignments![0]!.orderKey > "f" && assignments![0]!.orderKey < "m").toBe(true);
213 });
214
215 it("returns null when the move falls off the end of the list", () => {
216 const input = {
217 orderedIds: ["a", "b"],
218 keysById: new Map([
219 ["a", "f"],
220 ["b", "m"],
221 ]),
222 };
223 expect(planPinnedMove({ ...input, movedId: "a", direction: "up" })).toBeNull();
224 expect(planPinnedMove({ ...input, movedId: "b", direction: "down" })).toBeNull();
225 });
226
227 it("materializes keys for the whole section when a neighbor is keyless", () => {
228 const assignments = planPinnedMove({
229 orderedIds: ["a", "b", "c"],
230 keysById: new Map([
231 ["a", null],
232 ["b", "m"],
233 ["c", null],
234 ]),
235 movedId: "b",
236 direction: "up",
237 });
238 expect(assignments).not.toBeNull();
239 const keys = assignments!.map((entry) => entry.orderKey);
240 expect([...keys].sort()).toEqual(keys);
241 });
242});
243
244describe("sortPinnedThreadsByOrderKey", () => {
245 it("breaks equal keys by id THEN environment so merged lists are stable everywhere", () => {
246 const sorted = sortPinnedThreadsByOrderKey([
247 {
248 id: "thread-1",
249 createdAt: "2026-03-09T10:00:00.000Z",
250 pinOrderKey: "m",
251 environmentId: "env-b",
252 },
253 {
254 id: "thread-1",
255 createdAt: "2026-03-09T11:00:00.000Z",
256 pinOrderKey: "m",
257 environmentId: "env-a",
258 },
259 ]);
260 expect(sorted.map((thread) => thread.environmentId)).toEqual(["env-a", "env-b"]);
261 });
262});
263
264describe("generateSpreadPinOrderKeys", () => {
265 it.each([0, 1, 650, 675, 676, 1_001, 2_000])(
266 "leaves unique, insertable keys for %i threads",
267 (count) => {
268 const keys = generateSpreadPinOrderKeys(count);
269 expect(keys).toHaveLength(count);
270 expect(new Set(keys).size).toBe(count);
271 expect([...keys].sort()).toEqual(keys);
272 for (let index = 0; index < keys.length; index += 1) {
273 const before = keys[index - 1] ?? null;
274 const after = keys[index]!;
275 expect(after).toMatch(/^[a-z]*[b-z]$/);
276 const between = pinOrderKeyBetween(before, after);
277 expect(between).not.toBeNull();
278 expect(between! < after).toBe(true);
279 if (before !== null) expect(between! > before).toBe(true);
280 }
281 },
282 );
283});
284
285describe("sortActiveThreadsByOrderKey", () => {
286 it("keeps new and reopened threads ahead of the saved order", () => {
287 const sorted = sortActiveThreadsByOrderKey([
288 {
289 id: "arranged-first",
290 createdAt: "2026-03-09T09:00:00.000Z",
291 activeOrderKey: "f",
292 },
293 {
294 id: "new",
295 createdAt: "2026-03-09T11:00:00.000Z",
296 activeOrderKey: null,
297 },
298 {
299 id: "arranged-last",
300 createdAt: "2026-03-09T12:00:00.000Z",
301 unsettledAt: "2026-03-09T13:00:00.000Z",
302 activeOrderKey: "t",
303 },
304 {
305 id: "reopened",
306 createdAt: "2026-03-01T09:00:00.000Z",
307 unsettledAt: "2026-03-09T12:00:00.000Z",
308 },
309 ]);
310 expect(sorted.map((thread) => thread.id)).toEqual([
311 "reopened",
312 "new",
313 "arranged-first",
314 "arranged-last",
315 ]);
316 });
317
318 it("breaks equal order keys and timestamps by thread then environment", () => {
319 for (const activeOrderKey of [null, "m"]) {
320 const threads = [
321 { id: "thread-b", environmentId: "env-a" },
322 { id: "thread-a", environmentId: "env-b" },
323 { id: "thread-a", environmentId: "env-a" },
324 ].map((thread) => ({
325 ...thread,
326 createdAt: "2026-03-09T10:00:00.000Z",
327 activeOrderKey,
328 }));
329 expect(
330 sortActiveThreadsByOrderKey(threads).map(
331 (thread) => `${thread.id}:${thread.environmentId}`,
332 ),
333 ).toEqual(["thread-a:env-a", "thread-a:env-b", "thread-b:env-a"]);
334 }
335 });
336
337 it("applies every move across a mixed keyless and keyed section", () => {
338 const threads = Array.from({ length: 6 }, (_, index) => ({
339 id: String(index),
340 createdAt: `2026-03-09T0${6 - index}:00:00.000Z`,
341 activeOrderKey: index < 3 ? null : ["f", "m", "t"][index - 3]!,
342 }));
343 const ids = threads.map((thread) => thread.id);
344 const keysById = new Map(threads.map((thread) => [thread.id, thread.activeOrderKey]));
345 for (const movedId of ids) {
346 for (let targetIndex = 0; targetIndex < ids.length; targetIndex += 1) {
347 const desired = ids.filter((id) => id !== movedId);
348 desired.splice(targetIndex, 0, movedId);
349 const assignments = planPinnedReorder({ orderedIds: desired, keysById, movedId });
350 const nextKeys = new Map(
351 assignments.map((assignment) => [assignment.id, assignment.orderKey]),
352 );
353 const updated = threads.map((thread) => ({
354 ...thread,
355 activeOrderKey: nextKeys.get(thread.id) ?? thread.activeOrderKey,
356 }));
357 expect(sortActiveThreadsByOrderKey(updated).map((thread) => thread.id)).toEqual(desired);
358 }
359 }
360 });
361
362 it("moves a keyless thread into the arranged run with one write", () => {
363 const assignments = planPinnedMove({
364 orderedIds: ["new", "reopened", "first", "last"],
365 keysById: new Map([
366 ["new", null],
367 ["reopened", null],
368 ["first", "f"],
369 ["last", "t"],
370 ]),
371 movedId: "reopened",
372 direction: "down",
373 });
374 expect(assignments).toHaveLength(1);
375 expect(assignments![0]!.id).toBe("reopened");
376 expect(assignments![0]!.orderKey > "f").toBe(true);
377 expect(assignments![0]!.orderKey < "t").toBe(true);
378 });
379
380 it("materializes a large active list without changing the requested order", () => {
381 const threads = Array.from({ length: 1_200 }, (_, index) => ({
382 id: String(index),
383 createdAt: "2026-03-09T10:00:00.000Z",
384 activeOrderKey: null as string | null,
385 }));
386 const orderedIds = threads.map((thread) => thread.id).toReversed();
387 const assignments = planPinnedReorder({
388 orderedIds,
389 movedId: orderedIds[0]!,
390 keysById: new Map(threads.map((thread) => [thread.id, thread.activeOrderKey])),
391 });
392 const keys = new Map(assignments.map((assignment) => [assignment.id, assignment.orderKey]));
393 const updated = threads.map((thread) => ({ ...thread, activeOrderKey: keys.get(thread.id) }));
394 expect(sortActiveThreadsByOrderKey(updated).map((thread) => thread.id)).toEqual(orderedIds);
395 });
396});