Open History to see the last commit
1import { ProjectId, RunId } from "@t3tools/contracts";
2import { describe, expect, it } from "vite-plus/test";
3
4import {
5 activeThreadAnchorTimestampMs,
6 generateSpreadPinOrderKeys,
7 getLatestThreadForProject,
8 pinOrderKeyBetween,
9 planPinnedMove,
10 planPinnedReorder,
11 resolveSettledThreadTimestamp,
12 sortActiveThreadsByOrderKey,
13 sortPinnedThreadsByOrderKey,
14 sortSettledThreads,
15 sortThreads,
16 type SettledThreadTimestampInput,
17 type ThreadSortInput,
18} from "./threadSort.ts";
19
20describe("activeThreadAnchorTimestampMs", () => {
21 it("uses the later unsettle time when an old thread re-enters the active list", () => {
22 expect(
23 activeThreadAnchorTimestampMs({
24 createdAt: "2026-01-01T00:00:00.000Z",
25 unsettledAt: "2026-08-01T00:00:00.000Z",
26 }),
27 ).toBe(Date.parse("2026-08-01T00:00:00.000Z"));
28 });
29});
30
31type TestThread = { readonly id: string } & ThreadSortInput;
32
33function makeThread(overrides: Partial<TestThread> = {}): TestThread {
34 return {
35 id: "thread-1",
36 createdAt: "2026-03-09T10:00:00.000Z",
37 updatedAt: "2026-03-09T10:00:00.000Z",
38 messages: [],
39 latestUserMessageAt: null,
40 ...overrides,
41 };
42}
43
44describe("resolveSettledThreadTimestamp", () => {
45 it("prefers the persisted settlement stamp over later activity", () => {
46 expect(
47 resolveSettledThreadTimestamp({
48 settledAt: "2026-03-09T10:00:00.000Z",
49 latestUserMessageAt: "2026-03-09T11:00:00.000Z",
50 latestRun: null,
51 updatedAt: "2026-03-09T12:00:00.000Z",
52 }),
53 ).toBe("2026-03-09T10:00:00.000Z");
54 });
55
56 it("falls back to the latest activity when the stamp is missing or malformed", () => {
57 expect(
58 resolveSettledThreadTimestamp({
59 settledAt: "invalid",
60 latestUserMessageAt: "2026-03-09T11:00:00.000Z",
61 latestRun: null,
62 updatedAt: "2026-03-09T12:00:00.000Z",
63 }),
64 ).toBe("2026-03-09T11:00:00.000Z");
65 expect(
66 resolveSettledThreadTimestamp({
67 settledAt: null,
68 latestUserMessageAt: null,
69 latestRun: null,
70 updatedAt: "2026-03-09T12:00:00.000Z",
71 }),
72 ).toBe("2026-03-09T12:00:00.000Z");
73 });
74});
75
76describe("sortSettledThreads", () => {
77 const settled = (input: {
78 id: string;
79 settledAt?: string | null;
80 latestUserMessageAt?: string | null;
81 latestRun?: SettledThreadTimestampInput["latestRun"];
82 updatedAt?: string;
83 }) => ({
84 id: input.id,
85 settledAt: input.settledAt ?? null,
86 latestUserMessageAt: input.latestUserMessageAt ?? null,
87 latestRun: input.latestRun ?? null,
88 updatedAt: input.updatedAt ?? "2026-03-09T09:00:00.000Z",
89 });
90
91 it("orders by settle time, most recently settled first", () => {
92 const sorted = sortSettledThreads([
93 settled({
94 id: "settled-first",
95 settledAt: "2026-03-09T10:00:00.000Z",
96 latestUserMessageAt: "2026-03-09T09:59:00.000Z",
97 }),
98 settled({
99 id: "settled-last",
100 settledAt: "2026-03-09T12:00:00.000Z",
101 latestUserMessageAt: "2026-03-09T08:00:00.000Z",
102 }),
103 ]);
104
105 expect(sorted.map((thread) => thread.id)).toEqual(["settled-last", "settled-first"]);
106 });
107
108 it("falls back to last activity for auto-settled threads without a settledAt stamp", () => {
109 const sorted = sortSettledThreads([
110 settled({ id: "auto-old", latestUserMessageAt: "2026-03-09T08:00:00.000Z" }),
111 settled({ id: "explicit", settledAt: "2026-03-09T10:00:00.000Z" }),
112 settled({ id: "auto-recent", latestUserMessageAt: "2026-03-09T11:00:00.000Z" }),
113 ]);
114
115 expect(sorted.map((thread) => thread.id)).toEqual(["auto-recent", "explicit", "auto-old"]);
116 });
117
118 it("counts a turn completion as activity for auto-settled threads", () => {
119 const sorted = sortSettledThreads([
120 settled({ id: "message-only", latestUserMessageAt: "2026-03-09T10:04:00.000Z" }),
121 settled({
122 id: "completed-later",
123 latestUserMessageAt: "2026-03-09T10:00:00.000Z",
124 latestRun: {
125 runId: RunId.make("run-1"),
126 status: "completed",
127 assistantMessageId: null,
128 requestedAt: "2026-03-09T10:00:00.000Z",
129 startedAt: "2026-03-09T10:00:00.000Z",
130 completedAt: "2026-03-09T10:30:00.000Z",
131 },
132 }),
133 ]);
134
135 expect(sorted.map((thread) => thread.id)).toEqual(["completed-later", "message-only"]);
136 });
137
138 it("breaks timestamp ties by id so the order is stable", () => {
139 const sorted = sortSettledThreads([
140 settled({ id: "b", settledAt: "2026-03-09T10:00:00.000Z" }),
141 settled({ id: "a", settledAt: "2026-03-09T10:00:00.000Z" }),
142 ]);
143
144 expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
145 });
146
147 it("matches the per-comparison order on a shuffled list with ties", () => {
148 const stamps = [
149 { settledAt: "2026-03-09T10:00:00.000Z" },
150 { settledAt: "invalid", latestUserMessageAt: "2026-03-09T10:00:00.000Z" },
151 { latestUserMessageAt: "2026-03-09T11:00:00.000Z" },
152 { updatedAt: "2026-03-09T09:00:00.000Z" },
153 { updatedAt: "invalid" },
154 ];
155 const threads = Array.from({ length: 30 }, (_, index) => {
156 const row = (index * 7) % 30;
157 return { ...settled({ id: `thread-${row % 3}`, ...stamps[row % 5] }), row };
158 });
159 const timestampMs = (thread: SettledThreadTimestampInput) => {
160 const timestamp = resolveSettledThreadTimestamp(thread);
161 return timestamp === null ? 0 : Date.parse(timestamp);
162 };
163 const expected = threads.toSorted(
164 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
165 );
166
167 expect(sortSettledThreads(threads).map((thread) => thread.row)).toEqual(
168 expected.map((thread) => thread.row),
169 );
170 });
171});
172
173describe("sortThreads", () => {
174 it.each(["created_at", "updated_at"] as const)(
175 "preserves references, input order and descending id ties for %s",
176 (sortOrder) => {
177 const threads = Object.freeze([
178 makeThread({ id: "a" }),
179 makeThread({ id: "z" }),
180 makeThread({ id: "invalid-a", createdAt: "invalid", updatedAt: "invalid" }),
181 makeThread({ id: "invalid-z", createdAt: "invalid", updatedAt: "invalid" }),
182 ]);
183 const sorted = sortThreads(threads, sortOrder);
184 expect(sorted).toEqual([threads[1], threads[0], threads[3], threads[2]]);
185 expect(sorted[0]).toBe(threads[1]);
186 expect(threads[0]?.id).toBe("a");
187 },
188 );
189
190 it("falls back to updatedAt and createdAt when latestUserMessageAt is invalid and there are no messages", () => {
191 const sorted = sortThreads(
192 [
193 makeThread({
194 id: "thread-1",
195 latestUserMessageAt: "not-a-date",
196 createdAt: "2026-03-09T10:00:00.000Z",
197 updatedAt: "2026-03-09T10:05:00.000Z",
198 }),
199 makeThread({
200 id: "thread-2",
201 latestUserMessageAt: "still-not-a-date",
202 createdAt: "invalid-created-at",
203 updatedAt: "invalid-updated-at",
204 }),
205 makeThread({
206 id: "thread-3",
207 latestUserMessageAt: "invalid-latest-user-message-at",
208 createdAt: "2026-03-09T10:06:00.000Z",
209 updatedAt: "invalid-updated-at",
210 }),
211 ],
212 "updated_at",
213 );
214
215 expect(sorted.map((thread) => thread.id)).toEqual(["thread-3", "thread-1", "thread-2"]);
216 });
217
218 it("falls back to the latest valid user message when latestUserMessageAt is invalid", () => {
219 const sorted = sortThreads(
220 [
221 makeThread({
222 id: "thread-1",
223 latestUserMessageAt: "invalid-latest-user-message-at",
224 updatedAt: "2026-03-09T10:00:00.000Z",
225 messages: [
226 { role: "user", createdAt: "2026-03-09T10:05:00.000Z" },
227 { role: "assistant", createdAt: "2026-03-09T10:30:00.000Z" },
228 { role: "user", createdAt: "2026-03-09T10:20:00.000Z" },
229 ],
230 }),
231 makeThread({
232 id: "thread-2",
233 createdAt: "2026-03-09T10:15:00.000Z",
234 updatedAt: "2026-03-09T10:15:00.000Z",
235 }),
236 ],
237 "updated_at",
238 );
239
240 expect(sorted.map((thread) => thread.id)).toEqual(["thread-1", "thread-2"]);
241 });
242});
243
244describe("getLatestThreadForProject", () => {
245 it.each(["created_at", "updated_at"] as const)(
246 "matches the first sorted eligible thread for %s",
247 (sortOrder) => {
248 const projectId = ProjectId.make("project");
249 const threads = [
250 { ...makeThread({ id: "a" }), projectId, archivedAt: null },
251 { ...makeThread({ id: "z" }), projectId, archivedAt: null },
252 { ...makeThread({ id: "zz" }), projectId, archivedAt: "2026-03-10T00:00:00Z" },
253 { ...makeThread({ id: "zzz" }), projectId: ProjectId.make("other"), archivedAt: null },
254 ];
255 expect(getLatestThreadForProject(threads, projectId, sortOrder)).toBe(threads[1]);
256 expect(getLatestThreadForProject([], projectId, sortOrder)).toBeNull();
257 expect(getLatestThreadForProject(threads, ProjectId.make("missing"), sortOrder)).toBeNull();
258 const invalid = threads.slice(0, 2).map((thread) => ({
259 ...thread,
260 createdAt: "invalid",
261 updatedAt: "invalid",
262 }));
263 expect(getLatestThreadForProject(invalid, projectId, sortOrder)).toBe(invalid[1]);
264 expect(
265 getLatestThreadForProject([threads[1]!, { ...threads[1]! }], projectId, sortOrder),
266 ).toBe(threads[1]);
267 },
268 );
269});
270
271describe("planPinnedReorder with hidden rows", () => {
272 it("keeps hidden slots available when inserting between visible neighbors", () => {
273 const midpoint = pinOrderKeyBetween("f", "t")!;
274 const keysById = new Map([
275 ["a", "f"],
276 ["b", "t"],
277 ["moved", "z"],
278 ["snoozed", midpoint],
279 ]);
280 const assignments = planPinnedReorder({
281 orderedIds: ["a", "moved", "b"],
282 keysById,
283 movedId: "moved",
284 });
285 expect(assignments).toHaveLength(1);
286 const key = assignments[0]!.orderKey;
287 expect(key > "f" && key < "t").toBe(true);
288 expect(key).not.toBe(midpoint);
289 expect(assignments[0]!.id).toBe("moved");
290 });
291
292 it("materializes keyless rows without overwriting hidden slots", () => {
293 const reserved = generateSpreadPinOrderKeys(6);
294 const keysById = new Map<string, string | null>([
295 ["a", null],
296 ["b", null],
297 ["c", null],
298 ...reserved.map((key, i) => [`hidden-${i}`, key] as const),
299 ]);
300 const assignments = planPinnedReorder({ orderedIds: ["c", "a", "b"], keysById, movedId: "c" });
301 expect(assignments.map(({ id }) => id)).toEqual(["c", "a", "b"]);
302 const keys = assignments.map(({ orderKey }) => orderKey);
303 expect(keys).toEqual([...keys].sort());
304 expect(new Set(keys).size).toBe(3);
305 expect(keys.every((key) => !reserved.includes(key))).toBe(true);
306 });
307});
308
309describe("planPinnedMove", () => {
310 it("moves a thread up with a single key write", () => {
311 const assignments = planPinnedMove({
312 orderedIds: ["a", "b", "c"],
313 keysById: new Map([
314 ["a", "f"],
315 ["b", "m"],
316 ["c", "t"],
317 ]),
318 movedId: "c",
319 direction: "up",
320 });
321 expect(assignments).toHaveLength(1);
322 expect(assignments![0]!.id).toBe("c");
323 expect(assignments![0]!.orderKey > "f" && assignments![0]!.orderKey < "m").toBe(true);
324 });
325
326 it("returns null when the move falls off the end of the list", () => {
327 const input = {
328 orderedIds: ["a", "b"],
329 keysById: new Map([
330 ["a", "f"],
331 ["b", "m"],
332 ]),
333 };
334 expect(planPinnedMove({ ...input, movedId: "a", direction: "up" })).toBeNull();
335 expect(planPinnedMove({ ...input, movedId: "b", direction: "down" })).toBeNull();
336 });
337
338 it("materializes keys for the whole section when a neighbor is keyless", () => {
339 const assignments = planPinnedMove({
340 orderedIds: ["a", "b", "c"],
341 keysById: new Map([
342 ["a", null],
343 ["b", "m"],
344 ["c", null],
345 ]),
346 movedId: "b",
347 direction: "up",
348 });
349 expect(assignments).not.toBeNull();
350 const keys = assignments!.map((entry) => entry.orderKey);
351 expect([...keys].sort()).toEqual(keys);
352 });
353});
354
355describe("sortPinnedThreadsByOrderKey", () => {
356 it("breaks equal keys by id THEN environment so merged lists are stable everywhere", () => {
357 const sorted = sortPinnedThreadsByOrderKey([
358 {
359 id: "thread-1",
360 createdAt: "2026-03-09T10:00:00.000Z",
361 pinOrderKey: "m",
362 environmentId: "env-b",
363 },
364 {
365 id: "thread-1",
366 createdAt: "2026-03-09T11:00:00.000Z",
367 pinOrderKey: "m",
368 environmentId: "env-a",
369 },
370 ]);
371 expect(sorted.map((thread) => thread.environmentId)).toEqual(["env-a", "env-b"]);
372 });
373});
374
375describe("generateSpreadPinOrderKeys", () => {
376 it.each([0, 1, 650, 675, 676, 1_001, 2_000])(
377 "leaves unique, insertable keys for %i threads",
378 (count) => {
379 const keys = generateSpreadPinOrderKeys(count);
380 expect(keys).toHaveLength(count);
381 expect(new Set(keys).size).toBe(count);
382 expect([...keys].sort()).toEqual(keys);
383 for (let index = 0; index < keys.length; index += 1) {
384 const before = keys[index - 1] ?? null;
385 const after = keys[index]!;
386 expect(after).toMatch(/^[a-z]*[b-z]$/);
387 const between = pinOrderKeyBetween(before, after);
388 expect(between).not.toBeNull();
389 expect(between! < after).toBe(true);
390 if (before !== null) expect(between! > before).toBe(true);
391 }
392 },
393 );
394});
395
396describe("sortActiveThreadsByOrderKey", () => {
397 it("keeps new and reopened threads ahead of the saved order", () => {
398 const sorted = sortActiveThreadsByOrderKey([
399 {
400 id: "arranged-first",
401 createdAt: "2026-03-09T09:00:00.000Z",
402 activeOrderKey: "f",
403 },
404 {
405 id: "new",
406 createdAt: "2026-03-09T11:00:00.000Z",
407 activeOrderKey: null,
408 },
409 {
410 id: "arranged-last",
411 createdAt: "2026-03-09T12:00:00.000Z",
412 unsettledAt: "2026-03-09T13:00:00.000Z",
413 activeOrderKey: "t",
414 },
415 {
416 id: "reopened",
417 createdAt: "2026-03-01T09:00:00.000Z",
418 unsettledAt: "2026-03-09T12:00:00.000Z",
419 },
420 ]);
421 expect(sorted.map((thread) => thread.id)).toEqual([
422 "reopened",
423 "new",
424 "arranged-first",
425 "arranged-last",
426 ]);
427 });
428
429 it("breaks equal order keys and timestamps by thread then environment", () => {
430 for (const activeOrderKey of [null, "m"]) {
431 const threads = [
432 { id: "thread-b", environmentId: "env-a" },
433 { id: "thread-a", environmentId: "env-b" },
434 { id: "thread-a", environmentId: "env-a" },
435 ].map((thread) => ({
436 ...thread,
437 createdAt: "2026-03-09T10:00:00.000Z",
438 activeOrderKey,
439 }));
440 expect(
441 sortActiveThreadsByOrderKey(threads).map(
442 (thread) => `${thread.id}:${thread.environmentId}`,
443 ),
444 ).toEqual(["thread-a:env-a", "thread-a:env-b", "thread-b:env-a"]);
445 }
446 });
447
448 it("applies every move across a mixed keyless and keyed section", () => {
449 const threads = Array.from({ length: 6 }, (_, index) => ({
450 id: String(index),
451 createdAt: `2026-03-09T0${6 - index}:00:00.000Z`,
452 activeOrderKey: index < 3 ? null : ["f", "m", "t"][index - 3]!,
453 }));
454 const ids = threads.map((thread) => thread.id);
455 const keysById = new Map(threads.map((thread) => [thread.id, thread.activeOrderKey]));
456 for (const movedId of ids) {
457 for (let targetIndex = 0; targetIndex < ids.length; targetIndex += 1) {
458 const desired = ids.filter((id) => id !== movedId);
459 desired.splice(targetIndex, 0, movedId);
460 const assignments = planPinnedReorder({ orderedIds: desired, keysById, movedId });
461 const nextKeys = new Map(
462 assignments.map((assignment) => [assignment.id, assignment.orderKey]),
463 );
464 const updated = threads.map((thread) => ({
465 ...thread,
466 activeOrderKey: nextKeys.get(thread.id) ?? thread.activeOrderKey,
467 }));
468 expect(sortActiveThreadsByOrderKey(updated).map((thread) => thread.id)).toEqual(desired);
469 }
470 }
471 });
472
473 it("moves a keyless thread into the arranged run with one write", () => {
474 const assignments = planPinnedMove({
475 orderedIds: ["new", "reopened", "first", "last"],
476 keysById: new Map([
477 ["new", null],
478 ["reopened", null],
479 ["first", "f"],
480 ["last", "t"],
481 ]),
482 movedId: "reopened",
483 direction: "down",
484 });
485 expect(assignments).toHaveLength(1);
486 expect(assignments![0]!.id).toBe("reopened");
487 expect(assignments![0]!.orderKey > "f").toBe(true);
488 expect(assignments![0]!.orderKey < "t").toBe(true);
489 });
490
491 it("materializes a large active list without changing the requested order", () => {
492 const threads = Array.from({ length: 1_200 }, (_, index) => ({
493 id: String(index),
494 createdAt: "2026-03-09T10:00:00.000Z",
495 activeOrderKey: null as string | null,
496 }));
497 const orderedIds = threads.map((thread) => thread.id).toReversed();
498 const assignments = planPinnedReorder({
499 orderedIds,
500 movedId: orderedIds[0]!,
501 keysById: new Map(threads.map((thread) => [thread.id, thread.activeOrderKey])),
502 });
503 const keys = new Map(assignments.map((assignment) => [assignment.id, assignment.orderKey]));
504 const updated = threads.map((thread) => ({ ...thread, activeOrderKey: keys.get(thread.id) }));
505 expect(sortActiveThreadsByOrderKey(updated).map((thread) => thread.id)).toEqual(orderedIds);
506 });
507});