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